diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 000000000..7bc07ec21 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Environment-dependent path to Maven home directory +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..8fd57590c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "3219", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/question-service/.gitignore b/question-service/.gitignore index 415f9b5ec..5819ccfee 100644 --- a/question-service/.gitignore +++ b/question-service/.gitignore @@ -42,3 +42,5 @@ yarn-error.log* *.tsbuildinfo next-env.d.ts /generated/prisma + +/generated/prisma diff --git a/question-service/app/index.js b/question-service/app/index.js index 00d2015f9..7932311c1 100644 --- a/question-service/app/index.js +++ b/question-service/app/index.js @@ -1,5 +1,6 @@ import express from "express"; import cors from "cors"; +import questionRoutes from "./routes/question-routes.js"; const app = express(); @@ -11,6 +12,9 @@ app.get("/healthz", (req, res) => { res.status(200).json({ status: "ok" }); }); +// Use question routes +app.use("/questions", questionRoutes); + app.use("/api", (req, res) => { res.json({ message: "Question service is running!" }); }); diff --git a/question-service/app/routes/question-routes.js b/question-service/app/routes/question-routes.js new file mode 100644 index 000000000..d5aee30e9 --- /dev/null +++ b/question-service/app/routes/question-routes.js @@ -0,0 +1,41 @@ +import express from "express"; +import {PrismaClient} from '../../generated/prisma/index.js'; + +const router = express.Router(); +const prisma = new PrismaClient(); + +// GET /questions - Retrieve all questions +router.get("/", async (req, res) => { + const {difficulty, topic} = req.query; + let questions; + + try { + // If a difficulty or topic is provided, filter questions accordingly + if (difficulty || topic) { + questions = await prisma.question.findMany({ + where: { + ...(difficulty && {difficulty: difficulty.toUpperCase()}), + ...(topic && {topic: topic}), + }, + }); + + if (questions.length === 0) { + return res.status(404).json({error: "No questions found matching the criteria"}); + } + + //pick one random question from the filtered list + const randomIndex = Math.floor(Math.random() * questions.length); + res.json(questions[randomIndex]); + + } else { + // If no filters, return the first 100 questions + questions = await prisma.question.findMany({take: 100}); + res.json(questions); + } + } catch (error) { + console.error("Error fetching questions:", error); + res.status(500).json({error: "Internal Server Error"}); + } +}); + +export default router; \ No newline at end of file diff --git a/question-service/prisma/schema.prisma b/question-service/prisma/schema.prisma new file mode 100644 index 000000000..fbb2961b3 --- /dev/null +++ b/question-service/prisma/schema.prisma @@ -0,0 +1,40 @@ +generator client { + provider = "prisma-client-js" + binaryTargets = ["native", "linux-musl-openssl-3.0.x"] + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model Question { + id Int @id @default(autoincrement()) + title String + description String + descriptionImages String[] @default([]) + constraints String[] @default([]) + examples Json? + solution String + difficulty Difficulty + language String? + topic String + followUp String? + createdAt DateTime @default(now()) +} + +model User { + id String @id + username String @unique + email String @unique + password String + createdAt DateTime @default(now()) + isAdmin Boolean @default(false) +} + +enum Difficulty { + EASY + MEDIUM + HARD +} diff --git a/question-service/prisma/seed/check.js b/question-service/prisma/seed/check.js new file mode 100644 index 000000000..edf182b89 --- /dev/null +++ b/question-service/prisma/seed/check.js @@ -0,0 +1,25 @@ +import { PrismaClient } from "../../generated/prisma/index.js"; + +const prisma = new PrismaClient(); + +async function main() { + const question = await prisma.question.findUnique({ + where: { id: 2000 }, + }); + + console.log("Title:", question.title); + console.log("Description:\n", question.description); + + if (question.examples) { + question.examples.forEach((ex, i) => { + console.log(ex.text); // this will render \n as real line breaks + if (ex.image) console.log("Image:", ex.image); + }); + } +} + +main() + .catch(console.error) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/question-service/prisma/seed/clear-questions.js b/question-service/prisma/seed/clear-questions.js new file mode 100644 index 000000000..326899f4c --- /dev/null +++ b/question-service/prisma/seed/clear-questions.js @@ -0,0 +1,15 @@ +import { PrismaClient } from "../../generated/prisma/index.js"; +const prisma = new PrismaClient(); + +async function main() { + await prisma.question.deleteMany(); // deletes all rows in Question table + console.log("All questions deleted!"); +} + +main() + .catch((e) => { + console.error(e); + }) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/question-service/prisma/seed/questions-list-cleaned.json b/question-service/prisma/seed/questions-list-cleaned.json new file mode 100644 index 000000000..875f9a411 --- /dev/null +++ b/question-service/prisma/seed/questions-list-cleaned.json @@ -0,0 +1,101923 @@ +[ + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two adjacent cells is 1 .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n// BFS\n// We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it.\n boolean visited[][];\n \n // Could also convert the indexes to a single number by mat[0].length * i + j.\n class Pair{\n int x;\n int y;\n Pair(int x, int y){\n this.x = x;\n this.y = y;\n }\n }\n public int[][] updateMatrix(int[][] mat) {\n int level = 0;\n visited = new boolean[mat.length][mat[0].length];\n Queue q = new ArrayDeque<>();\n // Addition of all pairs in mat that have 0.\n for(int i = 0; i < mat.length; i++){\n for(int j = 0; j < mat[0].length; j++){\n if(mat[i][j] == 0){\n visited[i][j] = true;\n q.add(new Pair(i, j));\n }\n }\n }\n while(q.size()>0){\n int size = q.size();\n while(size-- > 0){\n Pair p = q.remove();\n mat[p.x][p.y] = level;\n if(p.x > 0 && visited[p.x - 1][p.y] == false){\n visited[p.x-1][p.y] = true;\n q.add(new Pair(p.x-1, p.y));\n }\n if(p.x < mat.length - 1 && visited[p.x + 1][p.y] == false){\n visited[p.x+1][p.y] = true;\n q.add(new Pair(p.x+1, p.y));\n \n }\n if(p.y > 0 && visited[p.x][p.y-1] == false){\n visited[p.x][p.y-1] = true;\n q.add(new Pair(p.x, p.y-1));\n \n }\n if(p.y < mat[0].length-1 && visited[p.x][p.y + 1] == false){\n visited[p.x][p.y+1] = true;\n q.add(new Pair(p.x, p.y + 1));\n }\n }\n level++;\n }\n return mat;\n }\n}\n", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two adjacent cells is 1 .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 534 ms (Top 69.67%) | Memory: 19.20 MB (Top 71.26%)\n\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n if not mat or not mat[0]:\n return []\n\n m, n = len(mat), len(mat[0])\n queue = deque()\n MAX_VALUE = m * n\n \n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n queue.append((i, j))\n else:\n mat[i][j] = MAX_VALUE\n \n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n \n while queue:\n row, col = queue.popleft()\n for dr, dc in directions:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n queue.append((r, c))\n mat[r][c] = mat[row][col] + 1\n \n return mat\n", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We have two special characters: Given a binary array bits that ends with 0 , return true if the last character must be a one-bit character.", + "description_images": [], + "constraints": [ + "The first character can be represented by one bit 0 .", + "The second character can be represented by two bits ( 10 or 11 )." + ], + "examples": [ + { + "text": "Example 1: Input:bits = [1,0,0]\nOutput:true\nExplanation:The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.", + "image": null + }, + { + "text": "Example 2: Input:bits = [1,1,1,0]\nOutput:false\nExplanation:The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isOneBitCharacter(int[] bits) {\n int ones = 0;\n //Starting from one but last, as last one is always 0.\n for (int i = bits.length - 2; i >= 0 && bits[i] != 0 ; i--) { \n ones++;\n }\n if (ones % 2 > 0) return false; \n return true;\n }\n}\n", + "title": "717. 1-bit and 2-bit Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have two special characters: Given a binary array bits that ends with 0 , return true if the last character must be a one-bit character.", + "description_images": [], + "constraints": [ + "The first character can be represented by one bit 0 .", + "The second character can be represented by two bits ( 10 or 11 )." + ], + "examples": [ + { + "text": "Example 1: Input:bits = [1,0,0]\nOutput:true\nExplanation:The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.", + "image": null + }, + { + "text": "Example 2: Input:bits = [1,1,1,0]\nOutput:false\nExplanation:The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.", + "image": null + } + ], + "follow_up": null, + "solution": "# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282638543/\n# (Time, Space) Complexity : O(n), O(1)\n\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n # Important Rules:\n # 1. If bit n is 0, bit n+1 must be a new char\n # 2. If bits end with 1, last bit must be a two bit char\n # However, this case had been rejected by question\n # 3. If 1s in row and end with 0, \n # we can use count or 1s to check last char\n # If count is even, last char is \"0\"\n # If count is odd, last char is \"10\"\n # Strategy:\n # 1. We don't care last element, since it must be 0.\n # 2. We check from reversed, and count 1s in a row\n # 3. Once 0 occur or list end, We stop counting\n # 4. We use count to determin result\n # 5. Since we will mod count by 2, we simplify it to bool\n ret = True\n for bit in bits[-2::-1]:\n if bit: ret = not ret\n else: break\n return ret\n", + "title": "717. 1-bit and 2-bit Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of n integers nums , a 132 pattern is a subsequence of three integers nums[i] , nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j] . Return true if there is a 132 pattern in nums , otherwise, return false .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 2 * 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:false\nExplanation:There is no 132 pattern in the sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,4,2]\nOutput:true\nExplanation:There is a 132 pattern in the sequence: [1, 4, 2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,3,2,0]\nOutput:true\nExplanation:There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 96.40%) | Memory: 67 MB (Top 55.57%)\nclass Solution {\n public boolean find132pattern(int[] nums) {\n int min = Integer.MIN_VALUE;\n int peak = nums.length;\n for (int i = nums.length - 1; i >= 0; i--) {\n // We find a \"132\" pattern if nums[i] < min, so return true...\n if (nums[i] < min)\n return true;\n // If peak < nums.length & nums[i] is greater than the peak element...\n while (peak < nums.length && nums[i] > nums[peak])\n min = nums[peak++];\n // Now we have nums[i] <= nums[peak]\n // We push nums[i] to the \"stack\"\n peak--;\n nums[peak] = nums[i];\n }\n return false;\n }\n}", + "title": "456. 132 Pattern", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of n integers nums , a 132 pattern is a subsequence of three integers nums[i] , nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j] . Return true if there is a 132 pattern in nums , otherwise, return false .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 2 * 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:false\nExplanation:There is no 132 pattern in the sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,4,2]\nOutput:true\nExplanation:There is a 132 pattern in the sequence: [1, 4, 2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,3,2,0]\nOutput:true\nExplanation:There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 476 ms (Top 99.36%) | Memory: 36.40 MB (Top 85.77%)\n\nclass Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n stack, third = [], float('-inf')\n \n for num in reversed(nums):\n if num < third:\n return True\n while stack and stack[-1] < num:\n third = stack.pop()\n stack.append(num)\n return False\n", + "title": "456. 132 Pattern", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Given an integer n , return the minimum number of operations to get the character 'A' exactly n times on the screen .", + "description_images": [], + "constraints": [ + "Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).", + "Paste: You can paste the characters which are copied last time." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3\nExplanation:Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSteps(int n) {\n int rem = n-1, copied = 0, ans = 0, onScreen = 1;\n \n while(rem>0){\n if(rem % onScreen == 0){\n ans++; // copy operation\n copied = onScreen; \n }\n rem-=copied;\n ans++; // paste operation\n onScreen = n-rem; // no. of characters on screen currently that can be copied in next copy operation\n }\n \n return ans;\n }\n}\n", + "title": "650. 2 Keys Keyboard", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Given an integer n , return the minimum number of operations to get the character 'A' exactly n times on the screen .", + "description_images": [], + "constraints": [ + "Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).", + "Paste: You can paste the characters which are copied last time." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3\nExplanation:Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, n: int) -> int: \n # at every step we can copy or paste\n # paste -> we need to know the current clipboard content (count)\n # copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste)\n \n memo = {}\n \n def dfs(clipboard_count, screen_count):\n if (clipboard_count, screen_count) in memo: \n return memo[(clipboard_count, screen_count)]\n \n # we reached n, this is a valid option\n if screen_count == n: return 0\n \n # we passed n, not a valid option\n if screen_count > n: return float('inf') \n \n # paste or copy\n copy_opt = paste_opt = float('inf')\n \n # we should only paste if clipboard is not empty\n if clipboard_count > 0:\n paste_opt = dfs(clipboard_count, screen_count + clipboard_count) \n \n # we should consider copy only if the last operation was paste\n if screen_count > clipboard_count:\n copy_opt = dfs(screen_count, screen_count) \n \n # save to memo\n memo[(clipboard_count, screen_count)] = 1 + min(paste_opt, copy_opt) \n return memo[(clipboard_count, screen_count)]\n \n return dfs(0, 1)\n \n", + "title": "650. 2 Keys Keyboard", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array cards of length 4 . You have four cards, each containing a number in the range [1, 9] . You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: Return true if you can get such expression that evaluates to 24 , and false otherwise.", + "description_images": [], + "constraints": [ + "The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid.", + "For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid." + ], + "examples": [ + { + "text": "Example 1: Input:cards = [4,1,8,7]\nOutput:true\nExplanation:(8-4) * (7-1) = 24", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,2,1,2]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 96.55%) | Memory: 40.80 MB (Top 91.57%)\n\n// 0 ms. 100%\nclass Solution {\n private static final double EPS = 1e-6;\n private boolean backtrack(double[] A, int n) {\n if(n == 1) return Math.abs(A[0] - 24) < EPS;\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n double a = A[i], b = A[j];\n A[j] = A[n-1];\n A[i] = a + b;\n if(backtrack(A, n - 1)) return true;\n A[i] = a - b;\n if(backtrack(A, n - 1)) return true;\n A[i] = b - a;\n if(backtrack(A, n - 1)) return true;\n A[i] = a * b;\n if(backtrack(A, n - 1)) return true;\n if(Math.abs(b) > EPS) {\n A[i] = a / b;\n if(backtrack(A, n - 1)) return true;\n }\n if(Math.abs(a) > EPS) {\n A[i] = b / a;\n if(backtrack(A, n - 1)) return true;\n }\n A[i] = a; A[j] = b;\n }\n }\n return false;\n }\n public boolean judgePoint24(int[] nums) {\n double[] A = new double[nums.length];\n for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n return backtrack(A, A.length);\n }\n}\n", + "title": "679. 24 Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array cards of length 4 . You have four cards, each containing a number in the range [1, 9] . You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: Return true if you can get such expression that evaluates to 24 , and false otherwise.", + "description_images": [], + "constraints": [ + "The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid.", + "For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid." + ], + "examples": [ + { + "text": "Example 1: Input:cards = [4,1,8,7]\nOutput:true\nExplanation:(8-4) * (7-1) = 24", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,2,1,2]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n return self.allComputeWays(cards, 4, 24)\n \n def allComputeWays(self, nums, l, target):\n if l == 1:\n if abs(nums[0] - target) <= 1e-6:\n return True\n return False\n for first in range(l):\n for second in range(first + 1, l):\n tmp1, tmp2 = nums[first], nums[second]\n nums[second] = nums[l - 1]\n \n nums[first] = tmp1 + tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 - tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp2 - tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 * tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp2:\n nums[first] = tmp1 / tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp1:\n nums[first] = tmp2 / tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first], nums[second] = tmp1, tmp2\n return False", + "title": "679. 24 Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 3000", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,1,2,-1,-4]\nOutput:[[-1,-1,2],[-1,0,1]]\nExplanation:nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1]\nOutput:[]\nExplanation:The only possible triplet does not sum up to 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0]\nOutput:[[0,0,0]]\nExplanation:The only possible triplet sums up to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def threeSum(self, nums):\n ans = []\n nums.sort()\n \n for i in range(len(nums)):\n if nums[i] > 0: break # after sorting, if the min > 0, we couldn't find such three values\n if i > 0 and nums[i] == nums[i - 1]: # ensure that nums[i] is not duplicated\n continue \n l, r = i + 1, len(nums) - 1\n while l < r:\n if nums[l] + nums[r] > -nums[i]:\n r -= 1\n elif nums[l] + nums[r] < -nums[i]:\n l += 1\n else:\n ans.append([nums[i], nums[l], nums[r]])\n\t\t\t\t\t# update l to get a different sum\n l += 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n return ans\n", + "title": "15. 3Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums of length n and an integer target , find three integers in nums such that the sum is closest to target . Return the sum of the three integers . You may assume that each input would have exactly one solution.", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 1000", + "-1000 <= nums[i] <= 1000", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,2,1,-4], target = 1\nOutput:2\nExplanation:The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], target = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1535 ms (Top 7.9%) | Memory: 16.58 MB (Top 11.9%)\n\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n closet = float('inf')\n nums.sort()\n for i in range(len(nums) - 2):\n l, r = i + 1, len(nums) - 1\n while l < r:\n sum3 = nums[i] + nums[l] + nums[r]\n print(sum3)\n if sum3 < target:\n l += 1\n else:\n r -=1\n if abs(sum3 - target) < abs(closet - target):\n closet = sum3\n return closet\n ", + "title": "16. 3Sum Closest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr , and an integer target , return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target . As the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 3000", + "0 <= arr[i] <= 100", + "0 <= target <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput:20\nExplanation:Enumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,2,2], target = 5\nOutput:12\nExplanation:arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,1,3], target = 6\nOutput:1\nExplanation:(1, 2, 3) occured one time in the array so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int threeSumMulti(int[] arr, int target) {\n long[] cnt = new long[101];\n long res = 0;\n for (int i : arr) {\n cnt[i]++;\n }\n for (int i = 0; i < 101 && i <= target; i++) {\n if (cnt[i] == 0) {\n continue;\n }\n for (int j = i; j < 101 && i + j <= target; j++) {\n int k = target - i - j;\n if (k < j) {\n break;\n }\n if (cnt[j] == 0 || k >= 101 || cnt[k] == 0) {\n continue;\n }\n if (i == j && j == k) {\n res += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 3 / 2;\n } else if (i == j) {\n res += cnt[k] * cnt[j] * (cnt[j] - 1) / 2;\n } else if (j == k) {\n res += cnt[i] * cnt[j] * (cnt[j] - 1) / 2;\n } else {\n res += cnt[i] * cnt[j] * cnt[target - i - j];\n }\n }\n }\n return (int) (res % (Math.pow(10, 9) + 7));\n }\n}\n", + "title": "923. 3Sum With Multiplicity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr , and an integer target , return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target . As the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 3000", + "0 <= arr[i] <= 100", + "0 <= target <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput:20\nExplanation:Enumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,2,2], target = 5\nOutput:12\nExplanation:arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,1,3], target = 6\nOutput:1\nExplanation:(1, 2, 3) occured one time in the array so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n arr.sort()\n count = 0\n for i in range(0, len(arr)-2):\n rem_sum = target - arr[i]\n hash_map = {}\n for j in range(i+1, len(arr)):\n if arr[j] > rem_sum:\n break\n if rem_sum - arr[j] in hash_map:\n count = count + hash_map[rem_sum-arr[j]]\n # update the hash_map\n hash_map[arr[j]] = hash_map.get(arr[j], 0) + 1\n return count % 1000000007\n", + "title": "923. 3Sum With Multiplicity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order .", + "description_images": [], + "constraints": [ + "0 <= a, b, c, d < n", + "a , b , c , and d are distinct .", + "nums[a] + nums[b] + nums[c] + nums[d] == target" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,-1,0,-2,2], target = 0\nOutput:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], target = 8\nOutput:[[2,2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 82.83%) | Memory: 42.5 MB (Top 98.57%)\nclass Solution {\n public List> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n List> llans = new LinkedList<>();\n if(nums == null || nums.length <= 2){\n return llans;\n }\n for(int i=0;i ll = new LinkedList<>();\n ll.add(nums[i]);\n ll.add(nums[j]);\n ll.add(nums[l]);\n ll.add(nums[r]);\n llans.add(ll);\n\n while( l List[List[int]]:\n \n if len(nums) < 4: return []\n \n nums.sort()\n res = []\n \n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n l = j+1\n r = len(nums)-1\n while l < r:\n\n sum_ = nums[i]+nums[j]+nums[l]+nums[r]\n a = [nums[i], nums[j], nums[l], nums[r]]\n \n if sum_ == target and a not in res:\n res.append(a)\n \n if sum_ > target:\n r -= 1\n \n else:\n l += 1\n while l < r and nums[l-1] == nums[l]:\n l += 1\n \n return res\n \n # An Upvote will be encouraging\n \n \n", + "title": "18. 4Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given four integer arrays nums1 , nums2 , nums3 , and nums4 all of length n , return the number of tuples (i, j, k, l) such that:", + "description_images": [], + "constraints": [ + "0 <= i, j, k, l < n", + "nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\nOutput:2\nExplanation:The two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 81.61%) | Memory: 44.50 MB (Top 61.42%)\n\nclass Solution {\n public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {\n Map map = new HashMap<>();\n for(int k : nums3)\n for(int l : nums4)\n map.put(k + l, map.getOrDefault(k + l, 0) + 1);\n int count = 0;\n for(int i : nums1)\n for(int j : nums2)\n count += map.getOrDefault(-(i + j), 0);\n return count;\n }\n}\n", + "title": "454. 4Sum II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given four integer arrays nums1 , nums2 , nums3 , and nums4 all of length n , return the number of tuples (i, j, k, l) such that:", + "description_images": [], + "constraints": [ + "0 <= i, j, k, l < n", + "nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\nOutput:2\nExplanation:The two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1360 ms (Top 29.95%) | Memory: 14.2 MB (Top 70.39%)\nclass Solution:\n def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:\n n1n2 = defaultdict(int)\n for n1 in nums1:\n for n2 in nums2:\n n1n2[n1+n2] += 1\n n3n4 = defaultdict(int)\n for n3 in nums3:\n for n4 in nums4:\n n3n4[n3+n4] += 1\n ans = 0\n for s in n1n2:\n ans += n1n2[s] * n3n4[-s]\n return ans", + "title": "454. 4Sum II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Reversing an integer means to reverse all its digits. Given an integer num , reverse num to get reversed1 , then reverse reversed1 to get reversed2 . Return true if reversed2 equals num . Otherwise return false .", + "description_images": [], + "constraints": [ + "For example, reversing 2021 gives 1202 . Reversing 12300 gives 321 as the leading zeros are not retained ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 526\nOutput:true\nExplanation:Reverse num to get 625, then reverse 625 to get 526, which equals num.", + "image": null + }, + { + "text": "Example 2: Input:num = 1800\nOutput:false\nExplanation:Reverse num to get 81, then reverse 81 to get 18, which does not equal num.", + "image": null + }, + { + "text": "Example 3: Input:num = 0\nOutput:true\nExplanation:Reverse num to get 0, then reverse 0 to get 0, which equals num.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.24 MB (Top 48.0%)\n\nclass Solution {\n public boolean isSameAfterReversals(int num) {\n return (num%10!=0||num<10);\n }\n}", + "title": "2119. A Number After a Double Reversal", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Reversing an integer means to reverse all its digits. Given an integer num , reverse num to get reversed1 , then reverse reversed1 to get reversed2 . Return true if reversed2 equals num . Otherwise return false .", + "description_images": [], + "constraints": [ + "For example, reversing 2021 gives 1202 . Reversing 12300 gives 321 as the leading zeros are not retained ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 526\nOutput:true\nExplanation:Reverse num to get 625, then reverse 625 to get 526, which equals num.", + "image": null + }, + { + "text": "Example 2: Input:num = 1800\nOutput:false\nExplanation:Reverse num to get 81, then reverse 81 to get 18, which does not equal num.", + "image": null + }, + { + "text": "Example 3: Input:num = 0\nOutput:true\nExplanation:Reverse num to get 0, then reverse 0 to get 0, which equals num.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isSameAfterReversals(self, num):\n\t\t# All you have to do is check the Trailing zeros\n return num == 0 or num % 10 # num % 10 means num % 10 != 0\n", + "title": "2119. A Number After a Double Reversal", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two positive integers left and right with left <= right . Calculate the product of all integers in the inclusive range [left, right] . Since the product may be very large, you will abbreviate it following these steps: Return a string denoting the abbreviated product of all integers in the inclusive range [left, right] .", + "description_images": [], + "constraints": [ + "For example, there are 3 trailing zeros in 1000 , and there are 0 trailing zeros in 546 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 4\nOutput:\"24e0\"\nExplanation:The product is 1 × 2 × 3 × 4 = 24.\nThere are no trailing zeros, so 24 remains the same. The abbreviation will end with \"e0\".\nSince the number of digits is 2, which is less than 10, we do not have to abbreviate it further.\nThus, the final representation is \"24e0\".", + "image": null + }, + { + "text": "Example 2: Input:left = 2, right = 11\nOutput:\"399168e2\"\nExplanation:The product is 39916800.\nThere are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with \"e2\".\nThe number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.\nHence, the abbreviated product is \"399168e2\".", + "image": null + }, + { + "text": "Example 3: Input:left = 371, right = 375\nOutput:\"7219856259e3\"\nExplanation:The product is 7219856259000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n c2 = c5 = 0\n top12 = tail5 = 1\n\n for i in range(left, right+1):\n # count and remove all 2 and 5\n while i % 2 == 0:\n i //= 2\n c2 += 1\n while i % 5 == 0:\n i //= 5\n c5 += 1\n\n # track top 12 and last 5\n top12 = int(str(top12 * i)[:12])\n tail5 = tail5 * i % 100000\n \n # multiply the remained 2 or 5\n if c2 > c5:\n for _ in range(c2 - c5):\n top12 = int(str(top12 * 2)[:12])\n tail5 = tail5 * 2 % 100000\n elif c2 < c5:\n for _ in range(c5 - c2):\n top12 = int(str(top12 * 5)[:12])\n tail5 = tail5 * 5 % 100000\n\n zero = min(c2, c5)\n\n # as is included in top 12, it's easy to tell when d<=10\n if len(str(top12))<=10:\n return str(top12)+'e'+str(zero)\n \n return str(top12)[:5] + '.'*3 + '0'*(5-len(str(tail5)))+str(tail5)+'e'+str(zero)\n", + "title": "2117. Abbreviating the Product of a Range", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order .", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 92.2%) | Memory: 47.60 MB (Top 65.47%)\n\nclass Solution {\n class UnionFind {\n int[] parent;\n int[] weight;\n \n public UnionFind(int num) {\n parent = new int[num];\n weight = new int[num];\n \n for(int i = 0; i < num; i++) {\n parent[i] = i;\n weight[i] = 1;\n }\n }\n \n public void union(int a, int b) {\n int rootA = root(a);\n int rootB = root(b);\n \n if (rootA == rootB) {\n return;\n }\n \n if (weight[rootA] > weight[rootB]) {\n parent[rootB] = rootA;\n weight[rootA] += weight[rootB];\n } else {\n parent[rootA] = rootB;\n weight[rootB] += weight[rootA];\n }\n }\n \n public int root(int a) {\n if (parent[a] == a) {\n return a;\n }\n \n parent[a] = root(parent[a]);\n return parent[a];\n }\n }\n\n public List> accountsMerge(List> accounts) {\n int size = accounts.size();\n\n UnionFind uf = new UnionFind(size);\n\n // prepare a hash with unique email address as key and index in accouts as value\n HashMap emailToId = new HashMap<>();\n for(int i = 0; i < size; i++) {\n List details = accounts.get(i);\n for(int j = 1; j < details.size(); j++) {\n String email = details.get(j);\n \n\t\t\t\t// if we have already seen this email before, merge the account \"i\" with previous account\n\t\t\t\t// else add it to hash\n if (emailToId.containsKey(email)) {\n uf.union(i, emailToId.get(email));\n } else {\n emailToId.put(email, i);\n }\n }\n }\n \n // prepare a hash with index in accounts as key and list of unique email address for that account as value\n HashMap> idToEmails = new HashMap<>();\n for(String key : emailToId.keySet()) {\n int root = uf.root(emailToId.get(key));\n \n if (!idToEmails.containsKey(root)) {\n idToEmails.put(root, new ArrayList());\n }\n \n idToEmails.get(root).add(key);\n }\n \n // collect the emails from idToEmails, sort it and add account name at index 0 to get the final list to add to final return List\n List> mergedDetails = new ArrayList<>();\n for(Integer id : idToEmails.keySet()) {\n List emails = idToEmails.get(id);\n Collections.sort(emails);\n emails.add(0, accounts.get(id).get(0));\n \n mergedDetails.add(emails);\n }\n \n return mergedDetails;\n }\n}\n", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order .", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n def merge(accounts):\n res = []\n ls = []\n for i in range(len(accounts)):\n temp = list(set(accounts[i][1:]))\n temp.sort()\n temp = [accounts[i][0]] + temp\n if i in ls:\n continue\n for j in range(len(accounts[i:])):\n s = i+j\n if i == s:\n continue\n if accounts[i][0] != accounts[s][0]:\n continue\n temp3 = list(set(accounts[s][1:]))\n uni = list(set(temp[1:]) | set(temp3))\n if len(uni) < len(temp[1:]) + len(temp3):\n temp1 = list(set(temp[1:]) | set(temp3))\n temp = [temp[0]] + temp1 \n ls.append(s)\n temp0 = temp[1:]\n temp0.sort()\n temp = [temp[0]]+temp0\n res.append(temp)\n return res\n merged = merge(accounts)\n while merge(merged) != merged:\n merged = merge(merged)\n\n return merged\n", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two binary strings a and b , return their sum as a binary string .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"\nOutput:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"\nOutput:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 42.20 MB (Top 42.63%)\n\nclass Solution {\n public String addBinary(String a, String b) {\n StringBuilder res = new StringBuilder();\n int i = a.length() - 1;\n int j = b.length() - 1;\n int carry = 0;\n while(i >= 0 || j >= 0){\n int sum = carry;\n if(i >= 0) sum += a.charAt(i--) - '0';\n if(j >= 0) sum += b.charAt(j--) - '0';\n carry = sum > 1 ? 1 : 0;\n res.append(sum % 2);\n }\n if(carry != 0) res.append(carry);\n return res.reverse().toString();\n }\n}\n", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two binary strings a and b , return their sum as a binary string .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"\nOutput:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"\nOutput:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n\n return str(bin(int(a, base = 2)+int(b, base = 2)))[2:]\n", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer num , repeatedly add all its digits until the result has only one digit, and return it.", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 38\nOutput:2\nExplanation:The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.", + "image": null + }, + { + "text": "Example 2: Input:num = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 73.88%) | Memory: 41.9 MB (Top 17.90%)\nclass Solution {\n public int addDigits(int num) {\n if(num == 0) return 0;\n else if(num % 9 == 0) return 9;\n else return num % 9;\n }\n}", + "title": "258. Add Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , repeatedly add all its digits until the result has only one digit, and return it.", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 38\nOutput:2\nExplanation:The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.", + "image": null + }, + { + "text": "Example 2: Input:num = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 20.34%) | Memory: 16.40 MB (Top 13.14%)\n\nclass Solution:\n def addDigits(self, num: int) -> int:\n while num > 9:\n num = num % 10 + num // 10\n return num\n", + "title": "258. Add Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0 , and you want to reach the last rung. You are also given an integer dist . You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist . You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.", + "description_images": [], + "constraints": [ + "1 <= rungs.length <= 10^5", + "1 <= rungs[i] <= 10^9", + "1 <= dist <= 10^9", + "rungs is strictly increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:rungs = [1,3,5,10], dist = 2\nOutput:2\nExplanation:You currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "image": null + }, + { + "text": "Example 2: Input:rungs = [3,6,8,10], dist = 3\nOutput:0\nExplanation:This ladder can be climbed without adding additional rungs.", + "image": null + }, + { + "text": "Example 3: Input:rungs = [3,4,6,7], dist = 2\nOutput:1\nExplanation:You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 46.95%) | Memory: 72.5 MB (Top 49.39%)\nclass Solution {\n public int addRungs(int[] rungs, int dist) {\n int ans = 0;\n for (int i=0 ; i dist ) {\n ans += d/dist;\n ans += ( d%dist == 0 ) ? -1 : 0;\n }\n }\n return ans;\n }\n}", + "title": "1936. Add Minimum Number of Rungs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0 , and you want to reach the last rung. You are also given an integer dist . You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist . You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.", + "description_images": [], + "constraints": [ + "1 <= rungs.length <= 10^5", + "1 <= rungs[i] <= 10^9", + "1 <= dist <= 10^9", + "rungs is strictly increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:rungs = [1,3,5,10], dist = 2\nOutput:2\nExplanation:You currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "image": null + }, + { + "text": "Example 2: Input:rungs = [3,6,8,10], dist = 3\nOutput:0\nExplanation:This ladder can be climbed without adding additional rungs.", + "image": null + }, + { + "text": "Example 3: Input:rungs = [3,4,6,7], dist = 2\nOutput:1\nExplanation:You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n rungs=[0]+rungs\n i,ans=1,0\n while i dist:\n ans+=ceil((rungs[i]-rungs[i-1])/dist)-1\n i+=1\n return ans\n\n\n\n ", + "title": "1936. Add Minimum Number of Rungs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and two integers val and depth , add a row of nodes with value val at the given depth depth . Note that the root node is at depth 1 . The adding rule is:", + "description_images": [], + "constraints": [ + "Given the integer depth , for each not null tree node cur at the depth depth - 1 , create two tree nodes with value val as cur 's left subtree root and right subtree root.", + "cur 's original left subtree should be the left subtree of the new left subtree root.", + "cur 's original right subtree should be the right subtree of the new right subtree root.", + "If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput:[4,1,1,2,null,null,6,3,1,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,null,3,1], val = 1, depth = 3\nOutput:[4,2,null,1,1,3,null,null,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.40 MB (Top 37.52%)\n\nclass Solution {\n public TreeNode addOneRow(TreeNode root, int v, int d) {\n if (d == 1) return new TreeNode(v, root, null);\n else if (d == 2) {\n root.left = new TreeNode(v, root.left, null);\n root.right = new TreeNode(v, null, root.right);\n } else {\n if (root.left != null) addOneRow(root.left, v, d-1);\n if (root.right != null) addOneRow(root.right, v, d-1);\n }\n return root;\n }\n}\n", + "title": "623. Add One Row to Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and two integers val and depth , add a row of nodes with value val at the given depth depth . Note that the root node is at depth 1 . The adding rule is:", + "description_images": [], + "constraints": [ + "Given the integer depth , for each not null tree node cur at the depth depth - 1 , create two tree nodes with value val as cur 's left subtree root and right subtree root.", + "cur 's original left subtree should be the left subtree of the new left subtree root.", + "cur 's original right subtree should be the right subtree of the new right subtree root.", + "If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput:[4,1,1,2,null,null,6,3,1,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,null,3,1], val = 1, depth = 3\nOutput:[4,2,null,1,1,3,null,null,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 6.3%) | Memory: 18.50 MB (Top 98.9%)\n\nclass Solution:\n def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:\n if d == 1: return TreeNode(v, root, None)\n elif d == 2:\n root.left = TreeNode(v, root.left, None)\n root.right = TreeNode(v, None, root.right)\n else:\n if root.left: self.addOneRow(root.left, v, d-1)\n if root.right: self.addOneRow(root.right, v, d-1)\n return root\n", + "title": "623. Add One Row to Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string . You must solve the problem without using any built-in library for handling large integers (such as BigInteger ). You must also not convert the inputs to integers directly.", + "description_images": [], + "constraints": [ + "1 <= num1.length, num2.length <= 10^4", + "num1 and num2 consist of only digits.", + "num1 and num2 don't have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"11\", num2 = \"123\"\nOutput:\"134\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"456\", num2 = \"77\"\nOutput:\"533\"", + "image": null + }, + { + "text": "Example 3: Input:num1 = \"0\", num2 = \"0\"\nOutput:\"0\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 29.95%) | Memory: 42.8 MB (Top 82.92%)\nimport java.math.BigInteger;\nclass Solution {\n public String addStrings(String num1, String num2) {\n return new BigInteger(num1).add(new BigInteger(num2)).toString();\n }\n}", + "title": "415. Add Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string . You must solve the problem without using any built-in library for handling large integers (such as BigInteger ). You must also not convert the inputs to integers directly.", + "description_images": [], + "constraints": [ + "1 <= num1.length, num2.length <= 10^4", + "num1 and num2 consist of only digits.", + "num1 and num2 don't have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"11\", num2 = \"123\"\nOutput:\"134\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"456\", num2 = \"77\"\nOutput:\"533\"", + "image": null + }, + { + "text": "Example 3: Input:num1 = \"0\", num2 = \"0\"\nOutput:\"0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n def func(n):\n value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}\n result = 0\n for digit in n:\n result = 10 * result + value[digit]\n\n return result\n\n ans = func(num1) + func(num2)\n return str(ans)", + "title": "415. Add Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num , the array-form of an integer, and an integer k , return the array-form of the integer num + k .", + "description_images": [], + "constraints": [ + "For example, for num = 1321 , the array form is [1,3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = [1,2,0,0], k = 34\nOutput:[1,2,3,4]\nExplanation:1200 + 34 = 1234", + "image": null + }, + { + "text": "Example 2: Input:num = [2,7,4], k = 181\nOutput:[4,5,5]\nExplanation:274 + 181 = 455", + "image": null + }, + { + "text": "Example 3: Input:num = [2,1,5], k = 806\nOutput:[1,0,2,1]\nExplanation:215 + 806 = 1021", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List addToArrayForm(int[] num, int k) {\n List res = new ArrayList<>();\n \n int i = num.length;\n while(--i >= 0 || k > 0) {\n if(i >= 0)\n k += num[i];\n \n res.add(k % 10);\n k /= 10;\n }\n Collections.reverse(res);\n \n return res;\n }\n}\n", + "title": "989. Add to Array-Form of Integer", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num , the array-form of an integer, and an integer k , return the array-form of the integer num + k .", + "description_images": [], + "constraints": [ + "For example, for num = 1321 , the array form is [1,3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = [1,2,0,0], k = 34\nOutput:[1,2,3,4]\nExplanation:1200 + 34 = 1234", + "image": null + }, + { + "text": "Example 2: Input:num = [2,7,4], k = 181\nOutput:[4,5,5]\nExplanation:274 + 181 = 455", + "image": null + }, + { + "text": "Example 3: Input:num = [2,1,5], k = 806\nOutput:[1,0,2,1]\nExplanation:215 + 806 = 1021", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 384 ms (Top 73.70%) | Memory: 15 MB (Top 73.95%)\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(str(int(\"\".join(map(str,num)))+k))", + "title": "989. Add to Array-Form of Integer", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "-100 <= num1, num2 <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 12, num2 = 5\nOutput:17\nExplanation:num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.", + "image": null + }, + { + "text": "Example 2: Input:num1 = -10, num2 = 4\nOutput:-6\nExplanation:num1 + num2 = -6, so -6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sum(int num1, int num2) {\n int l = -200, r = 200;\n while (l < r) {\n int mid = (l + r) >> 1;\n if (mid == num1 + num2) { return mid; }\n if (mid < num1 + num2) l = mid + 1;\n if (mid > num1 + num2) r = mid - 1;\n }\n return l;\n }\n}\n \n", + "title": "2235. Add Two Integers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "-100 <= num1, num2 <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 12, num2 = 5\nOutput:17\nExplanation:num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.", + "image": null + }, + { + "text": "Example 2: Input:num1 = -10, num2 = 4\nOutput:-6\nExplanation:num1 + num2 = -6, so -6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 99.37%) | Memory: 16.60 MB (Top 53.73%)\n\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n", + "title": "2235. Add Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]\nOutput:[7,0,8]\nExplanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n \n ListNode dummy = new ListNode(-1);\n ListNode temp = dummy;\n int carry = 0;\n while(l1 != null || l2 != null || carry != 0){\n int sum = 0;\n if(l1 != null){\n sum += l1.val;\n l1 = l1.next;\n }\n if(l2 != null){\n sum += l2.val;\n l2 = l2.next;\n } \n sum += carry;\n carry = sum / 10;\n ListNode node = new ListNode(sum % 10);\n temp.next = node;\n temp = temp.next;\n }\n return dummy.next;\n }\n}\n", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]\nOutput:[7,0,8]\nExplanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 13.64%) | Memory: 16.40 MB (Top 51.59%)\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummyHead = ListNode(0)\n tail = dummyHead\n carry = 0\n\n while l1 is not None or l2 is not None or carry != 0:\n digit1 = l1.val if l1 is not None else 0\n digit2 = l2.val if l2 is not None else 0\n\n sum = digit1 + digit2 + carry\n digit = sum % 10\n carry = sum // 10\n\n newNode = ListNode(digit)\n tail.next = newNode\n tail = tail.next\n\n l1 = l1.next if l1 is not None else None\n l2 = l2.next if l2 is not None else None\n\n result = dummyHead.next\n dummyHead.next = None\n return result\n", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [7,2,4,3], l2 = [5,6,4]\nOutput:[7,8,0,7]", + "image": "https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg" + }, + { + "text": "Example 2: Input:l1 = [2,4,3], l2 = [5,6,4]\nOutput:[8,0,7]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [0], l2 = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode res=new ListNode(0);\n ListNode curr=res;\n l1=reverseLinkedList(l1);\n l2=reverseLinkedList(l2);\n int carry=0;\n while(l1!=null||l2!=null||carry==1)\n {\n int sum=0;\n if(l1!=null)\n {\n sum+=l1.val;\n l1=l1.next;\n }\n if(l2!=null)\n {\n sum+=l2.val;\n l2=l2.next;\n }\n sum+=carry;\n carry = sum/10; \n curr.next= new ListNode(sum % 10); \n \n curr = curr.next; \n }\n return reverseLinkedList(res.next);\n }\n public ListNode reverseLinkedList(ListNode head)\n {\n ListNode curr=head;\n ListNode prev=null;\n ListNode next;\n while(curr!=null)\n {\n next=curr.next;\n curr.next=prev;\n prev=curr;\n curr=next;\n }\n return prev;\n }\n}\n", + "title": "445. Add Two Numbers II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [7,2,4,3], l2 = [5,6,4]\nOutput:[7,8,0,7]", + "image": "https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg" + }, + { + "text": "Example 2: Input:l1 = [2,4,3], l2 = [5,6,4]\nOutput:[8,0,7]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [0], l2 = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n def number(head):\n ans = ''\n while head:\n ans+=str(head.val)\n head = head.next\n return int(ans) \n temp = dummy = ListNode(0)\n for i in str(number(l1) + number(l2)):\n temp.next = ListNode(i)\n temp = temp.next\n return dummy.next\n \n\n", + "title": "445. Add Two Numbers II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.", + "description_images": [], + "constraints": [ + "For example, given s = \"EnjoyYourCoffee\" and spaces = [5, 9] , we place spaces before 'Y' and 'C' , which are at indices 5 and 9 respectively. Thus, we obtain \"Enjoy Y our C offee\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetcodeHelpsMeLearn\", spaces = [8,13,15]\nOutput:\"Leetcode Helps Me Learn\"\nExplanation:The indices 8, 13, and 15 correspond to the underlined characters in \"LeetcodeHelpsMeLearn\".\nWe then place spaces before those characters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"icodeinpython\", spaces = [1,5,7,9]\nOutput:\"i code in py thon\"\nExplanation:The indices 1, 5, 7, and 9 correspond to the underlined characters in \"icodeinpython\".\nWe then place spaces before those characters.", + "image": null + }, + { + "text": "Example 3: Input:s = \"spacing\", spaces = [0,1,2,3,4,5,6]\nOutput:\" s p a c i n g\"\nExplanation:We are also able to place spaces before the first character of the string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 68.74%) | Memory: 81.70 MB (Top 14.26%)\n\nclass Solution {\n public String addSpaces(String s, int[] spaces) {\n StringBuilder sb=new StringBuilder();\n int k=0;\n for(int i=0;i str:\n \n arr = []\n prev = 0\n for space in spaces:\n arr.append(s[prev:space])\n prev = space\n arr.append(s[space:])\n \n return \" \".join(arr)\n", + "title": "2109. Adding Spaces to a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two numbers arr1 and arr2 in base -2 , return the result of adding them together. Each number is given in array format :  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3 .  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1 . Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 1000", + "arr1[i] and arr2[i] are 0 or 1", + "arr1 and arr2 have no leading zeros" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,1,1,1,1], arr2 = [1,0,1]\nOutput:[1,0,0,0,0]\nExplanation:arr1 represents 11, arr2 represents 5, the output represents 16.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [0], arr2 = [0]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [0], arr2 = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.4 MB (Top 98.61%)\nclass Solution {\n public int[] addNegabinary(int[] arr1, int[] arr2) {\n\n List result = new ArrayList();\n int pointer_1 = arr1.length-1;\n int pointer_2 = arr2.length-1;\n\n int carry = 0;\n int current = 0;\n int sum = 0;\n\n while(pointer_1 >= 0 || pointer_2 >= 0){\n\n int a = (pointer_1 >=0)? arr1[pointer_1]: 0;\n int b = (pointer_2 >=0)? arr2[pointer_2]: 0;\n\n sum = a+b+carry;\n if(sum == 3){\n current = 1; carry = -1;\n }\n else if(sum == 2){\n current = 0; carry = -1;\n }\n else if(sum == 1){\n current = 1; carry = 0;\n }\n else if(sum == 0){\n current = 0; carry = 0;\n }\n else if(sum == -1)\n {\n current = 1; carry = 1;\n }\n\n result.add(current);\n pointer_1--;\n pointer_2--;\n }\n\n if(carry != 0)\n result.add(1);\n if(carry == -1)\n result.add(1);\n\n // Removing leading zeros\n int idx = result.size()-1;\n while(idx > 0 && result.get(idx) == 0)\n idx--;\n\n // reversing the list and adding the result to an array\n int len = idx+1;\n int[] negaBinary = new int[len];\n for(int i=0; i List[int]:\n \n //final answer\n new = []\n carry = 0\n \n\t\t//make arrays length equal \n if len(arr1) < len(arr2):\n diff = len(arr2) - len(arr1)\n arr1 = ([0] * diff) + arr1\n \n if len(arr1) > len(arr2):\n diff = len(arr1) - len(arr2)\n arr2 = ([0] * diff) + arr2\n \n \n \n //add values at every index and set carry and new value appropriately\n while arr1 and arr2:\n \n top = arr1.pop()\n down = arr2.pop()\n \n add = top + down + carry\n \n if add == -1:\n new = [1] + new\n carry = 1\n \n elif add == 1 or add == 0:\n new = [add] + new\n carry = 0\n \n elif add == 2:\n new = [0] + new\n carry = -1\n \n else:\n new = [1] + new\n carry = -1\n \n // if carry -1 add 1 1 since -1 is 11 in negabinary\n if carry == -1:\n new = [1,1] + new\n \n\t\t//remove any leading zeros\n while new[0] == 0 and len(new) >1:\n new = new[1:]\n \n return new\n", + "title": "1073. Adding Two Negabinary Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An additive number is a string whose digits can form an additive sequence . A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 35", + "num consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:\"112358\"\nOutput:true\nExplanation:The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8", + "image": null + }, + { + "text": "Example 2: Input:\"199100199\"\nOutput:true\nExplanation:The additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public boolean isAdditiveNumber(String num) {\n return backtrack(num, 0, 0, 0, 0);\n }\n \n public boolean backtrack(String num, int idx, long sum, long prev, int length){\n if(idx == num.length()){\n return length >= 3;\n }\n \n long currLong = 0;\n \n for(int i = idx; i < num.length(); i++){\n //make sure it won't start with 0\n if(i > idx && num.charAt(idx) == '0') break;\n currLong = currLong * 10 + num.charAt(i) - '0';\n \n if(length >= 2){\n if(sum < currLong){\n //currLong is greater than sum of previous 2 numbers\n break;\n }else if(sum > currLong){\n //currLong is smaller than sum of previous 2 numbers\n continue;\n }\n }\n //currLong == sum of previous 2 numbers\n if(backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true){\n return true;\n }\n }\n return false;\n }\n}\n", + "title": "306. Additive Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An additive number is a string whose digits can form an additive sequence . A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 35", + "num consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:\"112358\"\nOutput:true\nExplanation:The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8", + "image": null + }, + { + "text": "Example 2: Input:\"199100199\"\nOutput:true\nExplanation:The additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef isAdditiveNumber(self, num: str) -> bool:\n \n def isadditive(num1,num2,st):\n if len(st) == 0:\n return True\n num3 = str(num1+num2)\n l = len(num3)\n return num3 == st[:l] and isadditive(num2,int(num3),st[l:])\n \n for i in range(1,len(num)-1):\n for j in range(i+1,len(num)):\n if num [0] == \"0\" and i != 1:\n break\n if num[i] == \"0\" and i+1 != j:\n break\n \n if isadditive(int(num[:i]),int(num[i:j]),num[j:]):\n \n return True\n return False\n", + "title": "306. Additive Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i] . Return any permutation of nums1 that maximizes its advantage with respect to nums2 .", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= 10^5", + "nums2.length == nums1.length", + "0 <= nums1[i], nums2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,7,11,15], nums2 = [1,10,4,11]\nOutput:[2,11,7,15]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [12,24,8,32], nums2 = [13,25,32,11]\nOutput:[24,32,8,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] advantageCount(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n PriorityQueue pq = new PriorityQueue<>((a,b)->(b[0]-a[0]));\n for(int i=0;imax){\n nums2[pos]=nums1[right];\n right--;\n }else{\n nums2[pos]=nums1[left];\n left++;\n }\n }\n return nums2;\n }\n}\n", + "title": "870. Advantage Shuffle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i] . Return any permutation of nums1 that maximizes its advantage with respect to nums2 .", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= 10^5", + "nums2.length == nums1.length", + "0 <= nums1[i], nums2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,7,11,15], nums2 = [1,10,4,11]\nOutput:[2,11,7,15]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [12,24,8,32], nums2 = [13,25,32,11]\nOutput:[24,32,8,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n # sort by ascend order\n nums1.sort()\n\n # heapq in python is a minimal heap, so if we need to use a maximal heap, the element in the queue should be like: (-num, index)\n q = []\n for i, n in enumerate(nums2):\n heapq.heappush(q, (-n, i))\n\n n = len(nums1)\n l = 0\n r = n - 1\n ans = [0] * n\n\n while q:\n # pop out the maximum number from nums2\n num, i = heapq.heappop(q)\n num = -num\n\n # no number in nums1 > max number in nums2, so grap the minimum numer from nums1\n if nums1[r] <= num:\n ans[i] = nums1[l]\n l += 1\n else:\n ans[i] = nums1[r]\n r -= 1\n\n return ans", + "title": "870. Advantage Shuffle", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Return the probability that the n th person gets his own seat .", + "description_images": [], + "constraints": [ + "Take their own seat if it is still available, and", + "Pick other seats randomly when they find their seat occupied" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:1.00000\nExplanation:The first person can only get the first seat.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:0.50000\nExplanation:The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39 MB (Top 96.77%)\nlass Solution {\n public double nthPersonGetsNthSeat(int n) {\n if(n==1)\n return (double)1;\n return (double)1/2;\n }\n}", + "title": "1227. Airplane Seat Assignment Probability", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Return the probability that the n th person gets his own seat .", + "description_images": [], + "constraints": [ + "Take their own seat if it is still available, and", + "Pick other seats randomly when they find their seat occupied" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:1.00000\nExplanation:The first person can only get the first seat.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:0.50000\nExplanation:The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n\n return 0.5 if n > 1 else 1\n", + "title": "1227. Airplane Seat Assignment Probability", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day . Access times are given in the 24-hour time format \"HH:MM\" , such as \"23:51\" and \"09:49\" . Return a list of unique worker names who received an alert for frequent keycard use . Sort the names in ascending order alphabetically . Notice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period.", + "description_images": [], + "constraints": [ + "1 <= keyName.length, keyTime.length <= 10^5", + "keyName.length == keyTime.length", + "keyTime[i] is in the format \"HH:MM\" .", + "[keyName[i], keyTime[i]] is unique .", + "1 <= keyName[i].length <= 10", + "keyName[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\nOutput:[\"daniel\"]\nExplanation:\"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").", + "image": null + }, + { + "text": "Example 2: Input:keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\nOutput:[\"bob\"]\nExplanation:\"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List alertNames(String[] keyName, String[] keyTime) {\n Map> map = new HashMap<>();\n\t\t// for every entry in keyName and keyTime, add that time to a priorityqueue for that name\n for(int i=0;i pq = map.getOrDefault(keyName[i], new PriorityQueue());\n\t\t\t//convert the time to an integer (0- 2359 inclusive) for easy comparisons\n pq.add(Integer.parseInt(keyTime[i].substring(0,2))*100+Integer.parseInt(keyTime[i].substring(3)));\n map.put(keyName[i],pq);\n }\n \n\t\t// Generate the \"answer\" list\n List ans = new ArrayList<>();\n for(String s: map.keySet()){\n\t\t\t// For each name in the map, determine if that name used the keycard within 1 hour\n PriorityQueue pq = map.get(s);\n if(active(pq)){\n ans.add(s);\n }\n }\n \n\t\t// Sort the names alphabetically\n Collections.sort(ans);\n return ans;\n }\n \n\t// Greedy function to determine if there were 3 uses within an hour\n private boolean active(PriorityQueue pq){\n\t\t// If there are two or less entries, the user could not have entered 3 times, return false\n if(pq.size()<3) return false;\n\t\t\n\t\t// Create rolling data\n\t\t// Using PriorityQueues, the lowest number is removed first by default\n int a = pq.poll();\n int b = pq.poll();\n int c = pq.poll();\n \n\t\t// Test if two entrances are within 1 hour (100 in integer)\n if(c-a <=100) return true;\n while(pq.size()>0){\n a = b;\n b = c;\n c = pq.poll();\n if(c-a <=100) return true;\n }\n\t\t\n\t\t// If the full Queue has been checked, return false\n return false;\n }\n}\n", + "title": "1604. Alert Using Same Key-Card Three or More Times in a One Hour Period", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day . Access times are given in the 24-hour time format \"HH:MM\" , such as \"23:51\" and \"09:49\" . Return a list of unique worker names who received an alert for frequent keycard use . Sort the names in ascending order alphabetically . Notice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period.", + "description_images": [], + "constraints": [ + "1 <= keyName.length, keyTime.length <= 10^5", + "keyName.length == keyTime.length", + "keyTime[i] is in the format \"HH:MM\" .", + "[keyName[i], keyTime[i]] is unique .", + "1 <= keyName[i].length <= 10", + "keyName[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\nOutput:[\"daniel\"]\nExplanation:\"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").", + "image": null + }, + { + "text": "Example 2: Input:keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\nOutput:[\"bob\"]\nExplanation:\"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n # 668 ms, 99.52%. Time: O(NlogN). Space: O(N)\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n \n def is_within_1hr(t1, t2):\n h1, m1 = t1.split(\":\")\n h2, m2 = t2.split(\":\")\n if int(h1) + 1 < int(h2): return False\n if h1 == h2: return True\n return m1 >= m2\n \n records = collections.defaultdict(list)\n for name, time in zip(keyName, keyTime):\n records[name].append(time)\n \n rv = []\n for person, record in records.items():\n record.sort()\n\t\t\t# Loop through 2 values at a time and check if they are within 1 hour.\n if any(is_within_1hr(t1, t2) for t1, t2 in zip(record, record[2:])):\n rv.append(person)\n return sorted(rv)\n \n", + "title": "1604. Alert Using Same Key-Card Three or More Times in a One Hour Period", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 ( inclusive ). You are also given a 2D integer array edges , where edges[i] = [from i , to i ] denotes that there is a unidirectional edge from from i to to i in the graph. Return a list answer , where answer[i] is the list of ancestors of the i th node, sorted in ascending order . A node u is an ancestor of another node v if u can reach v via a set of edges.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= edges.length <= min(2000, n * (n - 1) / 2)", + "edges[i].length == 2", + "0 <= from i , to i <= n - 1", + "from i != to i", + "There are no duplicate edges.", + "The graph is directed and acyclic ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]\nOutput:[[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]\nExplanation:The above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3.", + "image": "https://assets.leetcode.com/uploads/2019/12/12/e1.png" + }, + { + "text": "Example 2: Input:n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nOutput:[[],[0],[0,1],[0,1,2],[0,1,2,3]]\nExplanation:The above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3.", + "image": "https://assets.leetcode.com/uploads/2019/12/12/e2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2132 ms (Top 14.62%) | Memory: 30.4 MB (Top 89.89%)\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n graph = {}\n for a, b in edges:\n graph[b] = graph.get(b, []) + [a]\n op = [[] for i in range(n)]\n for a in graph:\n visited = set()\n paths = [a]\n while len(paths) > 0:\n curr = paths.pop()\n for b in graph.get(curr, []):\n if b not in visited:\n visited.add(b)\n paths.append(b)\n op[a] = sorted(visited)\n return op", + "title": "2192. All Ancestors of a Node in a Directed Acyclic Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed binary array nums of length n . nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) nums left and nums right : The division score of an index i is the sum of the number of 0 's in nums left and the number of 1 's in nums right . Return all distinct indices that have the highest possible division score . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "nums left has all the elements of nums between index 0 and i - 1 (inclusive) , while nums right has all the elements of nums between index i and n - 1 (inclusive) .", + "If i == 0 , nums left is empty , while nums right has all the elements of nums .", + "If i == n , nums left has all the elements of nums, while nums right is empty ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,0,1,0]\nOutput:[2,4]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleftis [0]. numsrightis [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleftis [0,0]. numsrightis [1,0]. The score is 2 + 1 = 3.\n- 3: numsleftis [0,0,1]. numsrightis [0]. The score is 2 + 0 = 2.\n- 4: numsleftis [0,0,1,0]. numsrightis []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]\nOutput:[3]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleftis [0]. numsrightis [0,0]. The score is 1 + 0 = 1.\n- 2: numsleftis [0,0]. numsrightis [0]. The score is 2 + 0 = 2.\n- 3: numsleftis [0,0,0]. numsrightis []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1]\nOutput:[0]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [1,1]. The score is 0 + 2 = 2.\n- 1: numsleftis [1]. numsrightis [1]. The score is 0 + 1 = 1.\n- 2: numsleftis [1,1]. numsrightis []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 98.47%) | Memory: 61.2 MB (Top 91.95%)\nclass Solution {\n public List maxScoreIndices(int[] nums) {\n int N = nums.length;\n List res = new ArrayList<>();\n\n int[] pref = new int[N + 1];\n pref[0] = 0; // at zeroth division we have no elements\n for(int i = 0; i < N; ++i) pref[i+1] = nums[i] + pref[i];\n\n int maxScore = -1;\n int onesToRight, zeroesToLeft, currScore;\n\n for(int i = 0; i < N + 1; ++i) {\n onesToRight = pref[N] - pref[i];\n zeroesToLeft = i - pref[i];\n currScore = zeroesToLeft + onesToRight;\n\n if(currScore > maxScore) {\n res.clear();\n maxScore = currScore;\n }\n if(currScore == maxScore) res.add(i);\n }\n return res;\n }\n}", + "title": "2155. All Divisions With the Highest Score of a Binary Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed binary array nums of length n . nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) nums left and nums right : The division score of an index i is the sum of the number of 0 's in nums left and the number of 1 's in nums right . Return all distinct indices that have the highest possible division score . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "nums left has all the elements of nums between index 0 and i - 1 (inclusive) , while nums right has all the elements of nums between index i and n - 1 (inclusive) .", + "If i == 0 , nums left is empty , while nums right has all the elements of nums .", + "If i == n , nums left has all the elements of nums, while nums right is empty ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,0,1,0]\nOutput:[2,4]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleftis [0]. numsrightis [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleftis [0,0]. numsrightis [1,0]. The score is 2 + 1 = 3.\n- 3: numsleftis [0,0,1]. numsrightis [0]. The score is 2 + 0 = 2.\n- 4: numsleftis [0,0,1,0]. numsrightis []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]\nOutput:[3]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleftis [0]. numsrightis [0,0]. The score is 1 + 0 = 1.\n- 2: numsleftis [0,0]. numsrightis [0]. The score is 2 + 0 = 2.\n- 3: numsleftis [0,0,0]. numsrightis []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1]\nOutput:[0]\nExplanation:Division at index\n- 0: numsleftis []. numsrightis [1,1]. The score is 0 + 2 = 2.\n- 1: numsleftis [1]. numsrightis [1]. The score is 0 + 1 = 1.\n- 2: numsleftis [1,1]. numsrightis []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5049 ms (Top 67.40%) | Memory: 29.4 MB (Top 23.35%)\nclass Solution:\n def maxScoreIndices(self, nums: List[int]) -> List[int]:\n zeroFromLeft = [0] * (len(nums) + 1)\n oneFromRight = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n if nums[i] == 0:\n zeroFromLeft[i + 1] = zeroFromLeft[i] + 1\n else:\n zeroFromLeft[i + 1] = zeroFromLeft[i]\n\n for i in range(len(nums))[::-1]:\n if nums[i] == 1:\n oneFromRight[i] = oneFromRight[i + 1] + 1\n else:\n oneFromRight[i] = oneFromRight[i + 1]\n\n allSum = [0] * (len(nums) + 1)\n currentMax = 0\n res = []\n for i in range(len(nums) + 1):\n allSum[i] = oneFromRight[i] + zeroFromLeft[i]\n if allSum[i] > currentMax:\n res = []\n currentMax = allSum[i]\n if allSum[i] == currentMax:\n res.append(i)\n return res\n", + "title": "2155. All Divisions With the Highest Score of a Binary Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary search trees root1 and root2 , return a list containing all the integers from both trees sorted in ascending order .", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 5000] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [2,1,4], root2 = [1,0,3]\nOutput:[0,1,1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png" + }, + { + "text": "Example 2: Input:root1 = [1,null,8], root2 = [8,1]\nOutput:[1,1,8,8]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 53.0%) | Memory: 44.86 MB (Top 93.0%)\n\nclass Solution {\n public List getAllElements(TreeNode root1, TreeNode root2) {\n Stack st1 = new Stack<>();\n Stack st2 = new Stack<>();\n \n List res = new ArrayList<>();\n \n while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){\n while(root1 != null){\n st1.push(root1);\n root1 = root1.left;\n }\n while(root2 != null){\n st2.push(root2);\n root2 = root2.left;\n }\n if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){\n root1 = st1.pop();\n res.add(root1.val);\n root1 = root1.right;\n }\n else{\n root2 = st2.pop();\n res.add(root2.val);\n root2 = root2.right;\n }\n }\n return res;\n }\n}", + "title": "1305. All Elements in Two Binary Search Trees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two binary search trees root1 and root2 , return a list containing all the integers from both trees sorted in ascending order .", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 5000] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [2,1,4], root2 = [1,0,3]\nOutput:[0,1,1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png" + }, + { + "text": "Example 2: Input:root1 = [1,null,8], root2 = [8,1]\nOutput:[1,1,8,8]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png" + } + ], + "follow_up": null, + "solution": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n \n \n l1,l2=[],[]\n def preorder(root,l):\n if root is None:\n return \n preorder(root.left,l)\n l.append(root.val)\n preorder(root.right,l)\n preorder(root1,l1)\n preorder(root2,l2)\n return sorted(l1+l2)\n", + "title": "1305. All Elements in Two Binary Search Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, the value of a target node target , and an integer k , return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 500] .", + "0 <= Node.val <= 500", + "All the values Node.val are unique .", + "target is the value of one of the nodes in the tree.", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput:[7,4,1]\n\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png" + }, + { + "text": "Example 2: Input:root = [1], target = 1, k = 3\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List distanceK(TreeNode root, TreeNode target, int k) {\n HashMap map=new HashMap<>();\n get_parent(root,map);\n Queue q=new LinkedList<>();\n q.add(target);\n int distance=0;\n HashSet visited=new HashSet<>();\n visited.add(target);\n while(!q.isEmpty())\n {\n if(distance==k)\n break;\n distance++;\n int size=q.size();\n for(int i=0;i ans=new ArrayList<>();\n while(!q.isEmpty())\n ans.add(q.poll().val);\n return ans;\n \n }\n public void get_parent(TreeNode root,HashMap map)\n {\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i K:\n break\n \n for neighbor in graph[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n queue.append((neighbor, distance + 1))\n \n return result\n \n def buildGraph(self, node, parent, graph):\n if not node:\n return\n \n if node not in graph:\n graph[node] = []\n \n if parent:\n graph[node].append(parent)\n graph[parent].append(node)\n \n self.buildGraph(node.left, node, graph)\n self.buildGraph(node.right, node, graph)\n\n", + "title": "863. All Nodes Distance K in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "//Intuitions get from the top answer by @AaronLin1992\nclass AllOne {\n //Thoughts\n //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)?\n //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min\n //to maintain some kind of ordering, the first thing we think about is arrays/lists, however, arrays/lists when insert and delete in the middle, it is O(N) operation\n //so instead, a linked list might work\n //as a result, we considering using Map(s) and LinkedList for our supporting data structures, details below\n \n private Map stringToBucket; //maps a string to bucket\n private Map countToBucket; //maps string count to bucket, note that because when we design this we can have multiple strings in a bucket, that makes it convenient so that for each count, we only need 1 bucket, thus the map data structure\n private BucketList bucketList;\n \n //first, we need to create a class for the LinkedList elements\n class Bucket {\n private Bucket prev;\n private Bucket next;\n \n private int count; //recording the count of instances\n private Set keys; //note that we are using Set of Strings. The reason is because multiple Strings can have the same count and we want to put them in one bucket. This makes the problem easier to solve instead of putting them into different buckets.\n \n Bucket() {\n this.keys = new HashSet<>();\n }\n \n Bucket(String key) {\n this();\n this.count = 1;\n this.keys.add(key);\n }\n \n }\n \n //second, we need to create a linked list data structure of buckets\n class BucketList {\n private Bucket dummyHead; //the fake head before the real head //useful for getMinKey()\n private Bucket dummyTail; //the fake tail before the real tail //useful for getMaxKey()\n \n public BucketList() {\n dummyHead = new Bucket();\n dummyTail = new Bucket();\n dummyHead.next = dummyTail;\n dummyTail.prev = dummyHead;\n }\n \n public Bucket createNewBucket(String key) {\n Bucket bucket = new Bucket(key);\n \n Bucket nextBucket = dummyHead.next;\n dummyHead.next = bucket;\n bucket.prev = dummyHead;\n nextBucket.prev = bucket;\n bucket.next = nextBucket;\n \n return bucket;\n }\n \n public Bucket createBucketToTheRight(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket nextBucket = fromBucket.next;\n fromBucket.next = toBucket;\n toBucket.prev = fromBucket;\n nextBucket.prev = toBucket;\n toBucket.next = nextBucket;\n \n return toBucket;\n }\n \n public Bucket createBucketToTheLeft(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket prevBucket = fromBucket.prev;\n prevBucket.next = toBucket;\n toBucket.prev = prevBucket;\n fromBucket.prev = toBucket;\n toBucket.next = fromBucket;\n \n return toBucket;\n }\n \n public boolean clean(Bucket oldBucket) {//clean bucket if bucket does not have any keys\n if (!oldBucket.keys.isEmpty()) {\n return false;\n }\n \n removeBucket(oldBucket);\n \n return true;\n }\n \n public void removeBucket(Bucket bucket) {\n Bucket prevBucket = bucket.prev;\n Bucket nextBucket = bucket.next;\n \n prevBucket.next = nextBucket;\n nextBucket.prev = prevBucket;\n }\n }\n \n\n public AllOne() {\n this.stringToBucket = new HashMap<>();\n this.countToBucket = new HashMap<>();\n this.bucketList = new BucketList();\n }\n \n public void inc(String key) {\n //first check if the string already present\n if (!stringToBucket.containsKey(key)) { //if not present \n Bucket bucket = null;\n \n //check if there is count of 1 bucket already\n if (!countToBucket.containsKey(1)) { //if does not contain count of 1\n //we need to create a new bucket for count of 1 and add to the head (the minimum). Because count 1 should be the minimum exists in the bucket list\n bucket = bucketList.createNewBucket(key);\n } else { //if contains count of 1\n //then we just need to add the key to the bucket\n bucket = countToBucket.get(1);\n bucket.keys.add(key);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, bucket);\n countToBucket.put(1, bucket);\n } else { //if the key alreay present\n //first of all we need to get the current count for the key\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count++; //increment 1\n //don't forget that we need to remove the key from existing bucket\n oldBucket.keys.remove(key);\n \n //now let's add the key with new count\n if (countToBucket.containsKey(count)) { //if there is already a bucket for this count\n //then just add to the set of keys\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else { //if there is no bucket for this count, create a new bucket, but where to place it? Ans: to the right of the old bucket\n newBucket = bucketList.createBucketToTheRight(oldBucket, key, count); \n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n }\n \n public void dec(String key) {\n //since it is given that \"It is guaranteed that key exists in the data structure before the decrement.\" we don't do additional validation for key exists here\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count--; //decrement\n oldBucket.keys.remove(key);\n \n //special scenario - when count == 0\n if (count == 0) {\n stringToBucket.remove(key);\n } else {\n //now let's find a new bucket for the decremented count\n if (countToBucket.containsKey(count)) {//if there is already a bucket for the count\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else {//if there is no bucket for the count, then following similar logic as before, we need to add a bucket to the left of the existing bucket\n newBucket = bucketList.createBucketToTheLeft(oldBucket, key, count);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n }\n \n public String getMaxKey() {\n Set maxSet = bucketList.dummyTail.prev.keys;\n \n return maxSet.isEmpty() ? \"\" : maxSet.iterator().next(); //if maxSet is empty, that means the bucketList don't have actual buckets\n \n }\n \n public String getMinKey() {\n Set minSet = bucketList.dummyHead.next.keys;\n \n return minSet.isEmpty() ? \"\" : minSet.iterator().next(); //if minSet is empty, that means the bucketList don't have actual buckets\n }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */\n", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\n\nclass Set(object):\n\n def __init__(self):\n self._dict = {}\n self._list = []\n self._len = 0\n\n def add(self, v):\n if v in self._dict:\n pass\n else:\n self._list.append(v)\n self._dict[v] = self._len\n self._len += 1\n\n def __contains__(self, item):\n return item in self._dict\n\n def remove(self, v):\n if v not in self._dict:\n pass\n else:\n idx = self._dict[v]\n\n if idx < self._len - 1:\n self._list[idx] = self._list[-1]\n self._dict[self._list[idx]] = idx\n\n del self._dict[v]\n self._list.pop()\n self._len -= 1\n\n def __iter__(self):\n return iter(self._list)\n\n def check(self):\n assert len(self._dict) == len(self._list)\n for idx, key in enumerate(self._list):\n assert self._dict[key] == idx\n\n def __len__(self):\n return self._len\n\n def __repr__(self):\n return f\"{self._dict}\\n{self._list}\"\n\n\nclass Node(object):\n\n def __init__(self, value):\n self.value = value\n self.prev = None\n self.next = None\n\n def set_prev(self, other_node):\n self.prev = other_node\n if other_node is not None:\n other_node.next = self\n\n def set_next(self, other_node):\n self.next = other_node\n if other_node is not None:\n other_node.prev = self\n\n def __repr__(self):\n return str(self.value)\n\n\nclass SortedKeyList(object):\n\n def __init__(self):\n self.head = Node(value=0)\n self.tail = Node(value=float(\"inf\"))\n self.head.set_next(self.tail)\n\n def is_empty(self):\n return self.head.next is self.tail\n\n def min_key(self):\n if self.is_empty():\n return None\n else:\n return self.head.next.value\n\n def max_key(self):\n if self.is_empty():\n return None\n else:\n return self.tail.prev.value\n\n def incr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value + 1\n next_node = orig_node.next\n if next_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_prev(orig_node)\n new_node.set_next(next_node)\n return self\n\n def decr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value - 1\n prev_node = orig_node.prev\n if prev_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_next(orig_node)\n new_node.set_prev(prev_node)\n return self\n\n def delete_node(self, node):\n prev_node = node.prev\n next_node = node.next\n prev_node.set_next(next_node)\n return self\n\n def __repr__(self):\n a = []\n node = self.head.next\n while True:\n if node is self.tail:\n break\n\n assert node.next.prev is node\n assert node.prev.next is node\n\n a.append(node.value)\n node = node.next\n return str(a)\n\n\nclass AllOne:\n\n def __init__(self):\n self.count_list = SortedKeyList()\n self.counter = defaultdict(lambda: self.count_list.head)\n self.keyed_by_count = defaultdict(set)\n\n def __repr__(self):\n return f\"count_list={self.count_list}\\ncounter={dict(self.counter)}\\nkeyed_by_count={dict(self.keyed_by_count)}\"\n\n def inc(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.incr_key(orig_count_node)\n new_count_node = orig_count_node.next\n new_count = new_count_node.value\n assert new_count == orig_count + 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n if orig_count_node.value > 0:\n self.count_list.delete_node(orig_count_node)\n\n def dec(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.decr_key(orig_count_node)\n new_count_node = orig_count_node.prev\n new_count = new_count_node.value\n assert new_count == orig_count - 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if new_count == 0:\n del self.counter[key]\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n self.count_list.delete_node(orig_count_node)\n\n def getMaxKey(self) -> str:\n max_count = self.count_list.max_key()\n if max_count is not None:\n return next(iter(self.keyed_by_count[max_count]))\n else:\n return \"\"\n\n def getMinKey(self) -> str:\n min_count = self.count_list.min_key()\n if min_count is not None:\n return next(iter(self.keyed_by_count[min_count]))\n else:\n return \"\"\n\n\ndef drive(m, p):\n s = AllOne()\n\n naive_counter = defaultdict(int)\n\n for method, param in zip(m, p):\n if method in (\"inc\", \"dec\"):\n word = param[0]\n\n if method == \"inc\":\n s.inc(word)\n naive_counter[word] += 1\n\n elif method == 'dec':\n s.dec(word)\n naive_counter[word] -= 1\n\n if naive_counter[word] == 0:\n del naive_counter[word]\n\n tmp_counter = defaultdict(set)\n for k, v in naive_counter.items():\n tmp_counter[v].add(k)\n\n sorted_keys = sorted(tmp_counter.keys())\n min_key = sorted_keys[0]\n max_key = sorted_keys[-1]\n\n if s.getMaxKey() not in tmp_counter[max_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n if s.getMinKey() not in tmp_counter[min_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n return None, None, None\n\n\nif __name__ == '__main__':\n m = [\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n p = [[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\n s, naive_counter, tmp_counter = drive(m, p)\n", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a directed acyclic graph ( DAG ) of n nodes labeled from 0 to n - 1 , find all possible paths from node 0 to node n - 1 and return them in any order . The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j] ).", + "description_images": [], + "constraints": [ + "n == graph.length", + "2 <= n <= 15", + "0 <= graph[i][j] < n", + "graph[i][j] != i (i.e., there will be no self-loops).", + "All the elements of graph[i] are unique .", + "The input graph is guaranteed to be a DAG ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[3],[3],[]]\nOutput:[[0,1,3],[0,2,3]]\nExplanation:There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg" + }, + { + "text": "Example 2: Input:graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg" + } + ], + "follow_up": null, + "solution": "Approach : Using dfs+ backtracking we can solve it\t\n\t\n\tclass Solution {\n\t\tpublic List> allPathsSourceTarget(int[][] graph) {\n\t\t\tList> ans=new ArrayList<>();\n\t\t\tList temp=new ArrayList<>();\n\t\t\t boolean []visit=new boolean [graph.length];\n\t\t\thelper(graph,0,graph.length-1,ans,temp,visit);\n\n\t\t\treturn ans;\n\t\t}\n\t\tpublic void helper(int[][] graph, int src,int dest,List> ans,List temp,boolean[]vis)\n\t\t{\n\n\t\t\tvis[src]=true;\n\t\t\ttemp.add(src);\n\t\t\tif(src==dest)\n\t\t\t{\n\t\t\t\tList b =new ArrayList<>();\n\t\t\t\tfor(int h:temp){\n\t\t\t\t\tb.add(h);\n\t\t\t\t}\n\t\t\t\tans.add(b);\n\t\t\t}\n\n\t\t\tfor(int i:graph[src])\n\t\t\t{\n\t\t\t\tif(vis[i]!=true)\n\t\t\t\t{\n\t\t\t\t\thelper(graph,i,dest,ans,temp,vis);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tvis[src]=false;\n\t\t\ttemp.remove(temp.size()-1);\n\t\t}\n\t}\n", + "title": "797. All Paths From Source to Target", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a directed acyclic graph ( DAG ) of n nodes labeled from 0 to n - 1 , find all possible paths from node 0 to node n - 1 and return them in any order . The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j] ).", + "description_images": [], + "constraints": [ + "n == graph.length", + "2 <= n <= 15", + "0 <= graph[i][j] < n", + "graph[i][j] != i (i.e., there will be no self-loops).", + "All the elements of graph[i] are unique .", + "The input graph is guaranteed to be a DAG ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[3],[3],[]]\nOutput:[[0,1,3],[0,2,3]]\nExplanation:There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg" + }, + { + "text": "Example 2: Input:graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n res = []\n self.explore(graph, graph[0], [0], res)\n return res\n \n def explore(self, graph, candidates, step, res):\n if step[-1] == len(graph)-1:\n res.append(list(step))\n else:\n for i in range(len(candidates)):\n step.append(candidates[i])\n self.explore(graph, graph[candidates[i]], step, res)\n step.pop()\n", + "title": "797. All Paths From Source to Target", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return a list of all possible full binary trees with n nodes . Each node of each tree in the answer must have Node.val == 0 . Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order . A full binary tree is a binary tree where each node has exactly 0 or 2 children.", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" + }, + { + "text": "Example 2: Input:n = 3\nOutput:[[0,0,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 43.9 MB (Top 94.53%)\nclass Solution {\n List[] memo;\n public List allPossibleFBT(int n) {\n memo = new ArrayList[n+1];\n return dp(n);\n }\n\n public List dp(int n){\n if(n==0 || n==2){\n return new ArrayList();\n }\n if(n==1){\n List temp = new ArrayList<>();\n temp.add(new TreeNode(0));\n return temp;\n }\n List res = new ArrayList<>();\n for(int i=1;i right;\n List left;\n if(memo[i]!=null) right = memo[i];\n else right = dp(i);\n if(memo[n-1-i]!=null) left = memo[n-1-i];\n else left = dp(n-1-i);\n\n for(TreeNode l : left){\n for(TreeNode r : right){\n TreeNode temp = new TreeNode(0);\n temp.left=l;\n temp.right=r;\n res.add(temp);\n }\n }\n }\n memo[n] = res;\n return res;\n\n }\n}", + "title": "894. All Possible Full Binary Trees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a list of all possible full binary trees with n nodes . Each node of each tree in the answer must have Node.val == 0 . Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order . A full binary tree is a binary tree where each node has exactly 0 or 2 children.", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" + }, + { + "text": "Example 2: Input:n = 3\nOutput:[[0,0,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "We can't create Full Binary tree with even number of nodes. e.g n = 2/4/6/8...\nstart with cache having n = 1\n\tcache = {1:TreeNode()}\n\t\n\tn = 3\n\t\t\t\t\t\t\t0 (root)\n\t\t\t\t\t\t 1 1\n\tn = 5 \n\t 0 (root1) 0 (root2) \n\t\t\t\t\t\t 1 3 3 1\n\tn = 7 \n\t 0 0 0\n\t\t\t\t\t\t 1 5 3 3 5 1\n\n\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n def helper(n):\n if n in cache:\n return cache[n]\n # We use result array to store all possible binary tree of size n\n result = [] \n leftNodes, rightNodes = 1,n-2\n # if n = 7 then, (leftNodes,rightNodes) should be : (1,5),(3,3),(5,1) \n while rightNodes >0:\n root = TreeNode()\n if leftNodes not in cache:\n helper(leftNodes)\n if rightNodes not in cache:\n helper(rightNodes)\n leftTree = cache[leftNodes]\n rightTree = cache[rightNodes]\n # Using two for loops we generate all possible binary tree.\n # Always remember root of each binary tree is diffrent, So create new root every time\n for i in range(len(leftTree)):\n for j in range(len(rightTree)):\n root.left = leftTree[i]\n root.right = rightTree[j]\n result.append(root)\n root = TreeNode()\n leftNodes += 2\n rightNodes -= 2\n cache[n] = result\n return result\n \n if n % 2 == 0:\n return \n else:\n cache = {1:[TreeNode()]}\n return helper(n)\n\t\t\t\nThank You 😊\n\n", + "title": "894. All Possible Full Binary Trees", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array houses where houses[i] is the location of the i th house along a street and an integer k , allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= k <= houses.length <= 100", + "1 <= houses[i] <= 10^4", + "All the integers of houses are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,4,8,10,20], k = 3\nOutput:5\nExplanation:Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" + }, + { + "text": "Example 2: Input:houses = [2,3,5,12,18], k = 2\nOutput:9\nExplanation:Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 85.53%) | Memory: 42.5 MB (Top 53.95%)\nclass Solution {\n public int minDistance(int[] houses, int k) {\n Arrays.sort(houses);\n int n = houses.length;\n int[] dp = new int[n];\n for (int i = 1; i < n; i++){ // know optimal dist for i-1, then for i, we add houses[i] - houses[i/2]\n dp[i]=dp[i-1]+houses[i]-houses[i/2];\n }\n for (int i = 0; i < k-1; i++){\n int[] next = new int[n];\n Arrays.fill(next, Integer.MAX_VALUE);\n for (int j = 0; j < n; j++){\n int sum = 0;\n for (int m = j; m >= 0; m--){\n sum += houses[(m+j+1)>>1]-houses[m]; // likewise, adding to the front needs the +1 to account for the truncation.\n next[j] = Math.min(next[j], (m==0?0:dp[m-1])+sum);\n }\n }\n dp=next;\n }\n return dp[n-1];\n }\n}", + "title": "1478. Allocate Mailboxes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the array houses where houses[i] is the location of the i th house along a street and an integer k , allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= k <= houses.length <= 100", + "1 <= houses[i] <= 10^4", + "All the integers of houses are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,4,8,10,20], k = 3\nOutput:5\nExplanation:Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" + }, + { + "text": "Example 2: Input:houses = [2,3,5,12,18], k = 2\nOutput:9\nExplanation:Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n houses.sort()\n\n @lru_cache(None)\n def dp(left, right, k):\n if k == 1: # <-- 1.\n mid = houses[(left+right) // 2]\n return sum(abs(houses[i] - mid) for i in range(left, right + 1))\n\n return min(dp(left, i, 1) + dp(i+1, right, k - 1) \n for i in range(left, right - k + 2)) # <-- 2.\n\n return dp(0, len(houses)-1, k)", + "title": "1478. Allocate Mailboxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an alphabet board, we start at position (0, 0) , corresponding to character board[0][0] . Here, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"] , as shown in the diagram below. We may make the following moves: (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/07/28/azboard.png" + ], + "constraints": [ + "'U' moves our position up one row, if the position exists on the board;", + "'D' moves our position down one row, if the position exists on the board;", + "'L' moves our position left one column, if the position exists on the board;", + "'R' moves our position right one column, if the position exists on the board;", + "'!' adds the character board[r][c] at our current position (r, c) to the answer." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"leet\"\nOutput:\"DDR!UURRR!!DDD!\"", + "image": null + }, + { + "text": "Example 2: Input:target = \"code\"\nOutput:\"RR!DDRR!UUL!R!\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.07 MB (Top 98.6%)\n\nclass Solution {\n public String alphabetBoardPath(String target) {\n int x = 0, y = 0;\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < target.length(); i++){\n char ch = target.charAt(i);\n int x1 = (ch - 'a') / 5;\n int y1 = (ch - 'a') % 5;\n while(x1 < x) {x--; sb.append('U');}\n while(y1 > y) {y++; sb.append('R');}\n while(y1 < y) {y--; sb.append('L');}\n while(x1 > x) {x++; sb.append('D');}\n sb.append('!');\n }\n return sb.toString();\n }\n}", + "title": "1138. Alphabet Board Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an alphabet board, we start at position (0, 0) , corresponding to character board[0][0] . Here, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"] , as shown in the diagram below. We may make the following moves: (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/07/28/azboard.png" + ], + "constraints": [ + "'U' moves our position up one row, if the position exists on the board;", + "'D' moves our position down one row, if the position exists on the board;", + "'L' moves our position left one column, if the position exists on the board;", + "'R' moves our position right one column, if the position exists on the board;", + "'!' adds the character board[r][c] at our current position (r, c) to the answer." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"leet\"\nOutput:\"DDR!UURRR!!DDD!\"", + "image": null + }, + { + "text": "Example 2: Input:target = \"code\"\nOutput:\"RR!DDRR!UUL!R!\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 16.25%) | Memory: 14 MB (Top 13.50%)\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n def shortestPath(r,c,tr,tc):\n path = \"\"\n pr = r\n while r > tr:\n path += 'U'\n r -= 1\n while r < tr:\n path += 'D'\n r += 1\n if tr == 5 and pr != tr: path = path[:len(path) - 1]\n while c > tc:\n path += 'L'\n c -= 1\n while c < tc:\n path += 'R'\n c += 1\n if tr == 5 and pr != tr: path = path + 'D'\n return path\n\n table = ['abcde','fghij','klmno','pqrst','uvwxy','z']\n r,c = 0,0\n ans = \"\"\n for character in target:\n t_row = None\n for i,word in enumerate(table):\n if character in word:\n t_row = i\n break\n t_col = table[i].index(character)\n ans += shortestPath(r,c,t_row,t_col) + '!'\n r,c = t_row,t_col\n return ans", + "title": "1138. Alphabet Board Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\" . Then, we removed all commas, decimal points, and spaces and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been . Our original representation never had extraneous zeroes, so we never started with numbers like \"00\" , \"0.0\" , \"0.00\" , \"1.0\" , \"001\" , \"00.01\" , or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\" . The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)", + "description_images": [], + "constraints": [ + "For example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(123)\"\nOutput:[\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"(0123)\"\nOutput:[\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\nExplanation:0.0, 00, 0001 or 00.01 are not allowed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(00011)\"\nOutput:[\"(0, 0.011)\",\"(0.001, 1)\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List ret;\n public List ans;\n public List ambiguousCoordinates(String s) {\n ret=new ArrayList<>();\n ans=new ArrayList<>();\n String start=s.substring(0,2);\n util(s,1);\n fun();\n return ans;\n }\n \n //putting comma\n void util(String s,int idx) {\n if(idx==s.length()-2) {\n return;\n }\n \n String ns=s.substring(0,idx+1)+\", \"+s.substring(idx+1);\n ret.add(ns);\n util(s,idx+1);\n }\n \n //helper function for puting decimals after comma\n void fun() {\n for(String s:ret) {\n int cIndex=0;\n for(int i=0;i n1=dot(a);\n List n2=dot(b);\n if(n1==null || n2==null) { //invalid strings\n continue;\n }else { //valid strings\n for(String fir:n1) {\n for(String sec:n2) {\n ans.add(\"(\"+fir+\", \"+sec+\")\");\n }\n }\n }\n }\n }\n \n //putting decimal point\n List dot(String n) {\n List li=new ArrayList<>();\n if(n.length()==1) {\n li.add(n);\n }else {\n \n //just checking for first and last zeroes and making conditions accordingly\n\n if(n.charAt(n.length()-1)=='0') {\n if(n.charAt(0)=='0') {\n return null;\n }else {\n li.add(n);\n }\n }else if(n.charAt(0)=='0') {\n li.add(\"0.\"+n.substring(1));\n }else {\n for(int i=0;i1 and re.match('/^[0]+$/',s) else True\n\n def _isValidNum(ipart,fpart):\n return False if (len(ipart)>1 and ipart[0]=='0') or (fpart and fpart[-1]=='0') else True\n\n def _splitToNums(s):\n rets=[]\n if len(s)==1:return [s]\n for i in range(1,len(s)+1):\n a,b=s[:i],s[i:]\n if _isValidNum(a,b):rets.append(\"%s.%s\"%(a,b) if b else \"%s\"%(a))\n return rets\n\n ans,s=[],s[1:-1]\n for i in range(1,len(s)):\n a,b=s[:i],s[i:]\n if not _isValidSplit(a) or not _isValidSplit(b):continue\n for c1,c2 in itertools.product(_splitToNums(a),_splitToNums(b)):ans.append(\"(%s, %s)\"%(c1,c2))\n return ans", + "title": "816. Ambiguous Coordinates", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two numbers, hour and minutes , return the smaller angle (in degrees) formed between the hour and the minute hand . Answers within 10 -5 of the actual value will be accepted as correct.", + "description_images": [], + "constraints": [ + "1 <= hour <= 12", + "0 <= minutes <= 59" + ], + "examples": [ + { + "text": "Example 1: Input:hour = 12, minutes = 30\nOutput:165", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png" + }, + { + "text": "Example 2: Input:hour = 3, minutes = 30\nOutput:75", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png" + }, + { + "text": "Example 3: Input:hour = 3, minutes = 15\nOutput:7.5", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 38.02%)\nclass Solution {\n public double angleClock(int hour, int minutes) {\n // Position of hour hand in a circle of 0 - 59\n double hrPos = 5 * (hour % 12);\n\n // Adjust hour hand position according to minute hand\n hrPos += (5 * minutes/60.0);\n\n double units = Math.abs(minutes - hrPos);\n\n // Take the min of distance between minute & hour hand and hour & minute hand\n return Math.min(units, 60-units) * 6;\n }\n}", + "title": "1344. Angle Between Hands of a Clock", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two numbers, hour and minutes , return the smaller angle (in degrees) formed between the hour and the minute hand . Answers within 10 -5 of the actual value will be accepted as correct.", + "description_images": [], + "constraints": [ + "1 <= hour <= 12", + "0 <= minutes <= 59" + ], + "examples": [ + { + "text": "Example 1: Input:hour = 12, minutes = 30\nOutput:165", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png" + }, + { + "text": "Example 2: Input:hour = 3, minutes = 30\nOutput:75", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png" + }, + { + "text": "Example 3: Input:hour = 3, minutes = 15\nOutput:7.5", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n \n x = abs(minutes * 6 -(hour * 30 + minutes/2))\n return min(360-x , x)\n", + "title": "1344. Angle Between Hands of a Clock", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum . Return the sum of the k integers appended to nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,25,10,25], k = 2\nOutput:5\nExplanation:The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6], k = 6\nOutput:25\nExplanation:The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 563 ms (Top 89.1%) | Memory: 31.37 MB (Top 44.5%)\n\nclass Solution:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n ans = k*(k+1)//2\n prev = -inf \n for x in sorted(nums): \n if prev < x: \n if x <= k: \n k += 1\n ans += k - x\n else: break\n prev = x\n return ans ", + "title": "2195. Append K Integers With Minimal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices , where the i th product has an ID of products[i] and a price of prices[i] . When a customer is paying, their bill is represented as two parallel integer arrays product and amount , where the j th product they purchased has an ID of product[j] , and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the j th product) . The supermarket decided to have a sale. Every n th customer paying for their groceries will be given a percentage discount . The discount amount is given by discount , where they will be given discount percent off their subtotal. More formally, if their subtotal is bill , then they would actually pay bill * ((100 - discount) / 100) . Implement the Cashier class:", + "description_images": [], + "constraints": [ + "Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n , the discount , and the products and their prices .", + "double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10 -5 of the actual value will be accepted." + ], + "examples": [ + { + "text": "Example 1: Input[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]Output[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]ExplanationCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1stcustomer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2ndcustomer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rdcustomer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4thcustomer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5thcustomer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6thcustomer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6thcustomer, no discount.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 93.75%) | Memory: 76.80 MB (Top 6.6%)\n\nclass Cashier {\n private final int[] prices;\n private final int n;\n private final int discount;\n private int customerNumber;\n\n public Cashier(int n, int discount, int[] products, int[] prices) {\n this.prices = new int[200];\n\n for(int i = 0; i < products.length; ++i)\n this.prices[products[i] - 1] = prices[i];\n\n this.n = n;\n this.discount = discount;\n this.customerNumber = 1;\n }\n \n public double getBill(int[] product, int[] amount) {\n double sum = 0;\n\n for(int i = 0; i < product.length; ++i)\n sum += this.prices[product[i] - 1] * amount[i];\n\n if(this.customerNumber != 0 && this.customerNumber % n == 0)\n sum *= (double) (100 - this.discount) / 100;\n\n this.customerNumber++;\n\n return sum;\n }\n}\n\n/**\n * Your Cashier object will be instantiated and called as such:\n * Cashier obj = new Cashier(n, discount, products, prices);\n * double param_1 = obj.getBill(product,amount);\n */\n", + "title": "1357. Apply Discount Every n Orders", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices , where the i th product has an ID of products[i] and a price of prices[i] . When a customer is paying, their bill is represented as two parallel integer arrays product and amount , where the j th product they purchased has an ID of product[j] , and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the j th product) . The supermarket decided to have a sale. Every n th customer paying for their groceries will be given a percentage discount . The discount amount is given by discount , where they will be given discount percent off their subtotal. More formally, if their subtotal is bill , then they would actually pay bill * ((100 - discount) / 100) . Implement the Cashier class:", + "description_images": [], + "constraints": [ + "Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n , the discount , and the products and their prices .", + "double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10 -5 of the actual value will be accepted." + ], + "examples": [ + { + "text": "Example 1: Input[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]Output[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]ExplanationCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1stcustomer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2ndcustomer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rdcustomer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4thcustomer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5thcustomer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6thcustomer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6thcustomer, no discount.", + "image": null + } + ], + "follow_up": null, + "solution": "class Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n \n self.n = n \n self.discount = discount \n self.price = { }\n self.customer = 0 \n \n for i in range(len(products)) : \n self.price[products[i]] = prices[i]\n\n def getBill(self, product: List[int], amount: List[int]) -> float:\n \n self.customer += 1\n \n bill = 0 \n \n for i in range(len(product)) : \n bill += amount[i] * self.price[product[i]]\n \n \n if self.customer == self.n : \n bill = bill * (1 - self.discount / 100)\n self.customer = 0 \n \n \n return bill\n \n \n\n\n# Your Cashier object will be instantiated and called as such:\n# obj = Cashier(n, discount, products, prices)\n# param_1 = obj.getBill(product,amount)\n", + "title": "1357. Apply Discount Every n Orders", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$' . A word represents a price if it is a sequence of digits preceded by a dollar sign. You are given a string sentence representing a sentence and an integer discount . For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence . Note that all prices will contain at most 10 digits.", + "description_images": [], + "constraints": [ + "For example, \"$100\" , \"$23\" , and \"$6\" represent prices while \"100\" , \"$\" , and \"$1e5\" do not." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\nOutput:\"there are $0.50 $1.00 and 5$ candies in the shop\"\nExplanation:The words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\nOutput:\"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\nExplanation:Applying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public String discountPrices(String sentence, int discount) {\n String x[] = sentence.split(\" \");\n StringBuilder sb = new StringBuilder();\n for (String s : x) {\n if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + \" \"); \n else sb.append(s + \" \");\n }\n sb.deleteCharAt(sb.length() - 1);\n return sb.toString();\n }\n\n boolean isPrice(String s) {\n return s.startsWith(\"$\") && s.substring(1).matches(\"\\\\d+\");\n }\n\n String calc(double num, double discount) {\n double ans = num - (double) ((double) num * discount / 100.00);\n return \"$\" + String.format(\"%.2f\", ans);\n }\n}\n", + "title": "2288. Apply Discount to Prices", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$' . A word represents a price if it is a sequence of digits preceded by a dollar sign. You are given a string sentence representing a sentence and an integer discount . For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence . Note that all prices will contain at most 10 digits.", + "description_images": [], + "constraints": [ + "For example, \"$100\" , \"$23\" , and \"$6\" represent prices while \"100\" , \"$\" , and \"$1e5\" do not." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\nOutput:\"there are $0.50 $1.00 and 5$ candies in the shop\"\nExplanation:The words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\nOutput:\"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\nExplanation:Applying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n s = sentence.split() # convert to List to easily update\n m = discount / 100 \n for i,word in enumerate(s):\n if word[0] == \"$\" and word[1:].isdigit(): # Check whether it is in correct format\n num = int(word[1:]) * (1-m) # discounted price\n w = \"$\" + \"{:.2f}\".format(num) #correctly format\n s[i] = w #Change inside the list\n \n return \" \".join(s) #Combine the updated list\n\t\t```", + "title": "2288. Apply Discount to Prices", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums , return the number of arithmetic subarrays of nums . A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "For example, [1,3,5,7,9] , [7,7,7,7] , and [3,-1,-5,-9] are arithmetic sequences." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:3\nExplanation:We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n = nums.length;\n if (n < 3) {\n return 0;\n }\n int[] dp = new int[n - 1];\n dp[0] = nums[1] - nums[0];\n for (int i = 2; i < n; i++) {\n dp[i - 1] = nums[i] - nums[i - 1];\n }\n int si = 0;\n int count = 0;\n for (int i = 1; i < n - 1; i++) {\n if (dp[i] == dp[i - 1]) {\n count += (i - si);\n } else {\n si = i;\n }\n }\n return count;\n }\n}\n", + "title": "413. Arithmetic Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums , return the number of arithmetic subarrays of nums . A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "For example, [1,3,5,7,9] , [7,7,7,7] , and [3,-1,-5,-9] are arithmetic sequences." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:3\nExplanation:We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 86.27%) | Memory: 16.90 MB (Top 84.26%)\n\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n ans = 0\n table = [0] * len(nums)\n\n for r in range(2, len(nums)):\n diff1 = nums[r] - nums[r-1]\n diff2 = nums[r-1] - nums[r-2]\n\n if diff1 == diff2:\n table[r] = table[r-1] + 1\n ans += table[r-1] + 1\n\n return ans\n", + "title": "413. Arithmetic Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the number of all the arithmetic subsequences of nums . A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer.", + "description_images": [], + "constraints": [ + "For example, [1, 3, 5, 7, 9] , [7, 7, 7, 7] , and [3, -1, -5, -9] are arithmetic sequences.", + "For example, [1, 1, 2, 5, 7] is not an arithmetic sequence." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,6,8,10]\nOutput:7\nExplanation:All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7]\nOutput:16\nExplanation:Any subsequence of this array is arithmetic.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n=nums.length;\n \n HashMap []dp=new HashMap[n];\n \n for(int i=0;i();\n }\n \n int ans=0;\n \n for(int i=1;i=Integer.MAX_VALUE){\n continue;\n }\n \n int endingAtj=dp[j].getOrDefault((int)cd,0);\n int endingAti=dp[i].getOrDefault((int)cd,0);\n \n ans+=endingAtj;\n \n dp[i].put((int)cd,endingAtj+endingAti+1);\n }\n }\n \n return ans;\n }\n}\n", + "title": "446. Arithmetic Slices II - Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of all the arithmetic subsequences of nums . A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer.", + "description_images": [], + "constraints": [ + "For example, [1, 3, 5, 7, 9] , [7, 7, 7, 7] , and [3, -1, -5, -9] are arithmetic sequences.", + "For example, [1, 1, 2, 5, 7] is not an arithmetic sequence." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,6,8,10]\nOutput:7\nExplanation:All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7]\nOutput:16\nExplanation:Any subsequence of this array is arithmetic.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0\n for i in range(1, sz):\n for j in range(i):\n difference = nums[i] - nums[j]\n dp[i][difference] += 1\n if difference in dp[j]:\n dp[i][difference] += dp[j][difference]\n ans += dp[j][difference]\n return ans\n", + "title": "446. Arithmetic Slices II - Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i . For example, these are arithmetic sequences: The following sequence is not arithmetic : You are given an array of n integers, nums , and two arrays of m integers each, l and r , representing the m range queries, where the i th query is the range [l[i], r[i]] . All the arrays are 0-indexed . Return a list of boolean elements answer , where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.", + "description_images": [], + "constraints": [ + "n == nums.length", + "m == l.length", + "m == r.length", + "2 <= n <= 500", + "1 <= m <= 500", + "0 <= l[i] < r[i] < n", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums =[4,6,5,9,3,7], l =[0,0,2], r =[2,3,5]\nOutput:[true,false,true]\nExplanation:In the 0thquery, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1stquery, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2ndquery, the subarray is[5,9,3,7]. Thiscan be rearranged as[3,5,7,9], which is an arithmetic sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput:[false,true,false,false,true,true]", + "image": null + }, + { + "text": "1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9", + "image": null + }, + { + "text": "1, 1, 2, 5, 7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 83.14%) | Memory: 45.90 MB (Top 9.57%)\n\nclass Solution {\n public Boolean check(int[] arr) {\n Arrays.sort(arr);\n int diff = arr[1] - arr[0];\n \n for (int i = 2; i < arr.length; i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false;\n }\n }\n \n return true;\n }\n \n public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List ans = new ArrayList();\n for (int i = 0; i < l.length; i++) {\n int[] arr = new int[r[i] - l[i] + 1];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = nums[l[i] + j];\n }\n \n ans.add(check(arr));\n }\n\n return ans;\n }\n}\n\n", + "title": "1630. Arithmetic Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i . For example, these are arithmetic sequences: The following sequence is not arithmetic : You are given an array of n integers, nums , and two arrays of m integers each, l and r , representing the m range queries, where the i th query is the range [l[i], r[i]] . All the arrays are 0-indexed . Return a list of boolean elements answer , where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.", + "description_images": [], + "constraints": [ + "n == nums.length", + "m == l.length", + "m == r.length", + "2 <= n <= 500", + "1 <= m <= 500", + "0 <= l[i] < r[i] < n", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums =[4,6,5,9,3,7], l =[0,0,2], r =[2,3,5]\nOutput:[true,false,true]\nExplanation:In the 0thquery, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1stquery, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2ndquery, the subarray is[5,9,3,7]. Thiscan be rearranged as[3,5,7,9], which is an arithmetic sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput:[false,true,false,false,true,true]", + "image": null + }, + { + "text": "1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9", + "image": null + }, + { + "text": "1, 1, 2, 5, 7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 22.81%) | Memory: 17.70 MB (Top 6.09%)\n\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n ans = []\n \n def find_diffs(arr):\n \n arr.sort()\n\n dif = []\n \n for i in range(len(arr) - 1):\n dif.append(arr[i] - arr[i + 1])\n \n return len(set(dif)) == 1\n \n for i , j in zip(l , r):\n ans.append(find_diffs(nums[i:j + 1]))\n \n return ans\n", + "title": "1630. Arithmetic Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i th row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n , return the number of complete rows of the staircase you will build .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:Because the 3rdrow is incomplete, we return 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 8\nOutput:3\nExplanation:Because the 4throw is incomplete, we return 3.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 44.14%) | Memory: 40.7 MB (Top 83.77%)\nclass Solution {\n public int arrangeCoins(int n) {\n long s =0; long e = n;\n while (s <= e) {\n long mid = s +(e-s)/2;\n long coin = mid *( mid +1)/2;\n if(coin > n){\n e = mid -1;\n } else if (coin < n){\n s = mid +1;\n } else return (int) mid;\n }\n return (int)e;\n }\n}", + "title": "441. Arranging Coins", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i th row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n , return the number of complete rows of the staircase you will build .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:Because the 3rdrow is incomplete, we return 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 8\nOutput:3\nExplanation:Because the 4throw is incomplete, we return 3.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 6683 ms (Top 5.01%) | Memory: 13.8 MB (Top 57.45%)\nclass Solution:\n def arrangeCoins(self, n: int) -> int:\n for i in range(1,2**31):\n val=i*(i+1)//2\n if val>n:\n a=i\n break\n elif val==n:\n return i\n return a-1", + "title": "441. Arranging Coins", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1] . You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: Return the longest length of a set s[k] .", + "description_images": [], + "constraints": [ + "The first element in s[k] starts with the selection of the element nums[k] of index = k .", + "The next element in s[k] should be nums[nums[k]] , and then nums[nums[nums[k]]] , and so on.", + "We stop adding right before a duplicate element occurs in s[k] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,4,0,3,1,6,2]\nOutput:4\nExplanation:nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int arrayNesting(int[] nums) {\n int res=0;\n boolean[] visited = new boolean[nums.length];\n for(int i=0;i int:\n max_len = 0\n visited = set()\n def dfs(nums, index, dfs_visited):\n if index in dfs_visited:\n return len(dfs_visited)\n \n # add the index to dfs_visited and visited\n visited.add(index)\n dfs_visited.add(index)\n return dfs(nums, nums[index], dfs_visited)\n \n for i in range(len(nums)):\n if i not in visited:\n max_len = max(max_len, dfs(nums, i, set()))\n return max_len\n", + "title": "565. Array Nesting", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array of even length arr , return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2 , or false otherwise .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 3 * 10^4", + "arr.length is even.", + "-10^5 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,3,6]\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,1,2,6]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,-2,2,-4]\nOutput:true\nExplanation:We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReorderDoubled(int[] arr) {\n Map map=new HashMap<>();\n int zeroCount=0,out=0,len=arr.length;\n Arrays.sort(arr);\n for(int ar:arr){\n if(ar%2==1)\n map.put(ar,map.getOrDefault(ar,0)+1);\n else\n {\n if(ar>0)\n {\n int val=map.getOrDefault(ar/2,0);\n if(val>0){\n out++;\n map.put(ar/2,val-1);\n }\n else map.put(ar,map.getOrDefault(ar,0)+1);\n }\n else if(ar<0)\n {\n int val=map.getOrDefault(ar2,0);\n if(val>0){\n out++;\n map.put(ar2,val-1);\n } \n else map.put(ar,map.getOrDefault(ar,0)+1);\n }\n else zeroCount++; \n }\n }\n zeroCount=zeroCount/2;\n return out+zeroCount==len/2;\n }\n}\n", + "title": "954. Array of Doubled Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array of even length arr , return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2 , or false otherwise .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 3 * 10^4", + "arr.length is even.", + "-10^5 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,3,6]\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,1,2,6]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,-2,2,-4]\nOutput:true\nExplanation:We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1769 ms (Top 5.17%) | Memory: 16.6 MB (Top 56.95%)\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n n = len(arr)\n arr.sort()\n times = n//2\n count = {}\n for i in arr :\n if i in count:count[i] += 1\n else: count[i] = 1\n for i in count:\n if i == 0:\n tmp = count[0]//2\n times -= tmp\n if times <=0 : return True\n else:\n if i*2 in count:\n ct1 = count[i]\n ct2 = count[i*2]\n while ct1 > 0 and ct2 > 0 and times > 0:\n ct1 -= 1\n ct2 -= 1\n times -= 1\n count[i] = ct1\n count[i*2] = ct2\n if times == 0:return True\n return False", + "title": "954. Array of Doubled Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums of 2n integers, group these integers into n pairs (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) such that the sum of min(a i , b i ) for all i is maximized . Return the maximized sum .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "nums.length == 2 * n", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,2]\nOutput:4\nExplanation:All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,6,5,1,2]\nOutput:9\nExplanation:The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 17.21%) | Memory: 54.6 MB (Top 23.48%)\nclass Solution {\n public int arrayPairSum(int[] nums) {\n Arrays.sort(nums);\n int sum = 0;\n for(int i = 0; i < nums.length; i+=2){\n sum += nums[i];\n }\n return sum;\n }\n}", + "title": "561. Array Partition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums of 2n integers, group these integers into n pairs (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) such that the sum of min(a i , b i ) for all i is maximized . Return the maximized sum .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "nums.length == 2 * n", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,2]\nOutput:4\nExplanation:All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,6,5,1,2]\nOutput:9\nExplanation:The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n \n nums = sorted(nums)\n \n summ = 0\n for i in range(0,len(nums),2):\n summ += min(nums[i],nums[i+1])\n return summ", + "title": "561. Array Partition", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1 , (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i] . Return any rearrangement of nums that meets the requirements .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]\nOutput:[1,2,4,5,3]\nExplanation:When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,0,9,7]\nOutput:[9,7,6,2,0]\nExplanation:When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 67 ms (Top 33.85%) | Memory: 147.3 MB (Top 73.33%)\nclass Solution {\n public int[] rearrangeArray(int[] nums) {\n Arrays.sort(nums);\n // sort in wave format\n for(int i = 0;i List[int]:\n for i in range(1, len(nums) -1):\n pre = nums[i-1]\n current = nums[i]\n next = nums[i+1]\n \n # If block will run when we meet 1 2 3 or 6 4 2\n if (pre < current < next) or (pre > current > next):\n # Swap next and current\n # For example: \n # 1 2 3 -> 1 3 2\n # 6 4 2 -> 6 2 4\n nums[i+1], nums[i] = nums[i], nums[i+1]\n \n return nums\n", + "title": "1968. Array With Elements Not Equal to Average of Neighbors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n grid containing only values 0 and 1 , where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1 . The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1| .", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,1],[0,0,0],[1,0,1]]\nOutput:2\nExplanation:The cell (1, 1) is as far as possible from all the land with distance 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/1336_ex1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,0,0],[0,0,0],[0,0,0]]\nOutput:4\nExplanation:The cell (2, 2) is as far as possible from all the land with distance 4.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/1336_ex2.JPG" + } + ], + "follow_up": null, + "solution": "class Solution {\n class Point {\n int x, y;\n public Point(int x, int y){\n this.x=x;\n this.y=y;\n }\n }\n int[][] dist;\n int n,ans;\n int[] dx={0, 0, +1, -1};\n int[] dy={+1, -1, 0, 0};\n public int maxDistance(int[][] grid) {\n n=grid.length;\n dist = new int[n][n];\n Queue q = new LinkedList<>();\n for (int i=0;idist[x][y]+1){\n dist[r][c]=dist[x][y]+1;\n Point newP = new Point(r,c);\n q.add(newP);\n }\n }\n }\n for (int i=0;i=0&&c>=0&&r int:\n m,n=len(grid),len(grid[0])\n queue=deque([])\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1:\n queue.append((i,j))\n c=-1\n while queue:\n # print(queue)\n temp=len(queue)\n for _ in range(temp):\n (i,j)=queue.popleft()\n for (x,y) in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):\n if x < 0 or x >= m or y < 0 or y >= n or grid[x][y]==1:\n continue\n grid[x][y]=1\n queue.append((x,y))\n c+=1\n return c if c!=0 else -1\n", + "title": "1162. As Far from Land as Possible", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i] , which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j] . If s[j] >= g[i] , we can assign the cookie j to the child i , and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.", + "description_images": [], + "constraints": [ + "1 <= g.length <= 3 * 10^4", + "0 <= s.length <= 3 * 10^4", + "1 <= g[i], s[j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:g = [1,2,3], s = [1,1]\nOutput:1\nExplanation:You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.", + "image": null + }, + { + "text": "Example 2: Input:g = [1,2], s = [1,2,3]\nOutput:2\nExplanation:You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 98.76%) | Memory: 45.20 MB (Top 5.55%)\n\nclass Solution {\n public int findContentChildren(int[] g, int[] s) {\n int i =0,j=0,c=0;\n \n Arrays.sort(g);\n Arrays.sort(s);\n \n \n for(;i< g.length;i++)\n {\n // System.out.println(s[j]+\" \"+g[i]);\n \n while(j=g[i] )\n {\n // System.out.println(s[j]+\" \"+g[i]);\n j++;c++;\n break;\n }\n j++;\n }\n }\n \n return c;\n \n }\n}\n", + "title": "455. Assign Cookies", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i] , which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j] . If s[j] >= g[i] , we can assign the cookie j to the child i , and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.", + "description_images": [], + "constraints": [ + "1 <= g.length <= 3 * 10^4", + "0 <= s.length <= 3 * 10^4", + "1 <= g[i], s[j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:g = [1,2,3], s = [1,1]\nOutput:1\nExplanation:You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.", + "image": null + }, + { + "text": "Example 2: Input:g = [1,2], s = [1,2,3]\nOutput:2\nExplanation:You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 437 ms (Top 8.80%) | Memory: 15.9 MB (Top 13.77%)\nclass Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort()\n s.sort()\n cont = 0\n c = 0\n k = 0\n while k< len(s) and c < len(g):\n if s[k] >= g[c]:\n c+=1\n k+=1\n cont+=1\n else:\n k+=1\n return cont", + "title": "455. Assign Cookies", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]\nOutput:[5,10]\nExplanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]\nOutput:[]\nExplanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]\nOutput:[10]\nExplanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 6.85%) | Memory: 49 MB (Top 11.86%)\n/*\n0. Start iterating over the asteroid one by one.\n1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n6. Convert the stack to an array in return it.\n\n*/\nclass Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Stack stack = new Stack<>();\n //0. Start iterating over the asteroid one by one.\n for(int a : asteroids) {\n\n //1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n //2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n while(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() < Math.abs(a)) {\n stack.pop();\n }\n\n //3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() == Math.abs(a)) {\n stack.pop();\n continue;\n }\n\n //4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() > Math.abs(a)) {\n continue;\n }\n\n //5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n stack.push(a);\n\n }\n\n //6. Convert the stack to an array in return it.\n int[] ans = new int[stack.size()];\n int i = stack.size() - 1;\n while(!stack.isEmpty()) {\n ans[i] = stack.pop();\n i--;\n }\n return ans;\n }\n}", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]\nOutput:[5,10]\nExplanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]\nOutput:[]\nExplanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]\nOutput:[10]\nExplanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 103 ms (Top 70.1%) | Memory: 17.56 MB (Top 44.2%)\n\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for a in asteroids:\n while stack and stack[-1] > 0 > a:\n if stack[-1] < abs(a):\n stack.pop()\n continue\n elif stack[-1] == abs(a):\n stack.pop()\n break # this means asteroid must be destroyed (not add to stack in else statement below)\n else:\n stack.append(a)\n \n return stack", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B' , black pawns 'p' , and empty squares '.' . When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking . Return the number of available captures for the white rook .", + "description_images": [], + "constraints": [ + "board.length == 8", + "board[i].length == 8", + "board[i][j] is either 'R' , '.' , 'B' , or 'p'", + "There is exactly one cell with board[i][j] == 'R'" + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:3\nExplanation:In this example, the rook is attacking all the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:0\nExplanation:The bishops are blocking the rook from attacking any of the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG" + }, + { + "text": "Example 3: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:3\nExplanation:The rook is attacking the pawns at positions b5, d6, and f5.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.3 MB (Top 62.26%)\nclass Solution {\n public int numRookCaptures(char[][] board) {\n int ans = 0;\n\n int row = 0;\n int col = 0;\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 'R') {\n row = i;\n col = j;\n break;\n }\n }\n }\n\n int j = col;\n while (j >= 0) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j--;\n }\n\n j = col;\n while (j <= board[0].length - 1) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j++;\n }\n\n int i = row;\n while (i <= board.length - 1) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i++;\n }\n\n i = row;\n while (i >= 0) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i--;\n }\n\n return ans;\n }\n}", + "title": "999. Available Captures for Rook", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B' , black pawns 'p' , and empty squares '.' . When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking . Return the number of available captures for the white rook .", + "description_images": [], + "constraints": [ + "board.length == 8", + "board[i].length == 8", + "board[i][j] is either 'R' , '.' , 'B' , or 'p'", + "There is exactly one cell with board[i][j] == 'R'" + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:3\nExplanation:In this example, the rook is attacking all the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:0\nExplanation:The bishops are blocking the rook from attacking any of the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG" + }, + { + "text": "Example 3: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput:3\nExplanation:The rook is attacking the pawns at positions b5, d6, and f5.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n\t\t# Checking for possible case to the right of Rook\n def right_position(n,i):\n List = i[0:n][::-1] # taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List: # Checking if 'p' in list \n pIndex = List.index('p')\n if 'B' in List: # Checking if 'B' in list\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1: # if list does not have 'B' and have 'p'\n return True\n if pIndex == -1: # if list does not have 'p'\n return False\n return bIndex>pIndex \n def left_position(n,i):\n List = i[n+1:]# taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List:\n pIndex = List.index('p')\n if 'B' in List:\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1:\n return True\n if pIndex == -1:\n return False\n return bIndex>pIndex\n Count = 0\n\t\t# Checking for possibilites in row\n for i in board:\n if 'R' in i:\n print(i)\n n = i.index('R')\n if left_position(n,i):\n Count += 1\n if right_position(n,i):\n Count += 1\n Col = []\n\t\t# checking for possibilites in col\n for i in range(0,len(board)):\n Col.append(board[i][n]) # taking the elements from the same col of Rook\n n = Col.index('R')\n if left_position(n,Col):\n Count += 1\n if right_position(n,Col):\n Count += 1\n return Count\n", + "title": "999. Available Captures for Rook", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[3.00000,14.50000,11.00000]\n\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]\nOutput:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.1%) | Memory: 45.45 MB (Top 6.9%)\n\nclass Solution {\n public List averageOfLevels(TreeNode root) {\n Queue q = new LinkedList<>(List.of(root));\n List ans = new ArrayList<>();\n while (q.size() > 0) {\n double qlen = q.size(), row = 0;\n for (int i = 0; i < qlen; i++) {\n TreeNode curr = q.poll();\n row += curr.val;\n if (curr.left != null) q.offer(curr.left);\n if (curr.right != null) q.offer(curr.right);\n }\n ans.add(row/qlen);\n }\n return ans;\n }\n}", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[3.00000,14.50000,11.00000]\n\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]\nOutput:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 94.14%) | Memory: 19.30 MB (Top 21.03%)\n\nclass Solution:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n \n if not root:\n \n # Quick response for empty tree\n return []\n \n traversal_q = [root]\n \n average = []\n \n while traversal_q:\n \n # compute current level average\n cur_avg = sum( (node.val for node in traversal_q if node) ) / len(traversal_q)\n \n # add to result\n average.append( cur_avg )\n \n # update next level queue\n next_level_q = [ child for node in traversal_q for child in (node.left, node.right) if child ]\n \n # update traversal queue as next level's\n traversal_q = next_level_q\n \n return average\n", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of unique integers salary where salary[i] is the salary of the i th employee. Return the average salary of employees excluding the minimum and maximum salary . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "3 <= salary.length <= 100", + "1000 <= salary[i] <= 10^6", + "All the integers of salary are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:salary = [4000,3000,1000,2000]\nOutput:2500.00000\nExplanation:Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500", + "image": null + }, + { + "text": "Example 2: Input:salary = [1000,2000,3000]\nOutput:2000.00000\nExplanation:Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double average(int[] salary) {\n int n = salary.length-2;\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n int sum = 0;\n for(int i=0;i float: \n\n return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)\n", + "title": "1491. Average Salary Excluding the Minimum and Maximum Salary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a restaurant with a single chef. You are given an array customers , where customers[i] = [arrival i , time i ]: When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input . Return the average waiting time of all customers . Solutions within 10 -5 from the actual answer are considered accepted.", + "description_images": [], + "constraints": [ + "arrival i is the arrival time of the i th customer. The arrival times are sorted in non-decreasing order.", + "time i is the time needed to prepare the order of the i th customer." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [[1,2],[2,5],[4,3]]\nOutput:5.00000\nExplanation:1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.", + "image": null + }, + { + "text": "Example 2: Input:customers = [[5,2],[5,4],[10,3],[20,1]]\nOutput:3.25000\nExplanation:1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 7.49%) | Memory: 101.1 MB (Top 30.84%)\nclass Solution {\n public double averageWaitingTime(int[][] customers) {\n double time = 0;\n double waitingTime = 0;\n\n for(int[] cust : customers){\n time = Math.max(cust[0],time);\n time = time + cust[1];\n waitingTime += (time - cust[0]);\n }\n\n return waitingTime/customers.length;\n }\n}", + "title": "1701. Average Waiting Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a restaurant with a single chef. You are given an array customers , where customers[i] = [arrival i , time i ]: When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input . Return the average waiting time of all customers . Solutions within 10 -5 from the actual answer are considered accepted.", + "description_images": [], + "constraints": [ + "arrival i is the arrival time of the i th customer. The arrival times are sorted in non-decreasing order.", + "time i is the time needed to prepare the order of the i th customer." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [[1,2],[2,5],[4,3]]\nOutput:5.00000\nExplanation:1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.", + "image": null + }, + { + "text": "Example 2: Input:customers = [[5,2],[5,4],[10,3],[20,1]]\nOutput:3.25000\nExplanation:1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n start = customers[0][0]\n end = start + customers[0][1]\n total_wait = end - start\n for c in customers[1:]:\n start = c[0]\n if start <= end:\n end += c[1]\n total_wait = total_wait + end - start\n else:\n end = c[0]+c[1]\n total_wait += c[1]\n return total_wait/len(customers)\n \n \n \n \n", + "title": "1701. Average Waiting Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water , there will be a flood . Your goal is to avoid floods in any lake. Given an integer array rains where: Return an array ans where: If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array . Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.", + "description_images": [], + "constraints": [ + "rains[i] > 0 means there will be rains over the rains[i] lake.", + "rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it ." + ], + "examples": [ + { + "text": "Example 1: Input:rains = [1,2,3,4]\nOutput:[-1,-1,-1,-1]\nExplanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.", + "image": null + }, + { + "text": "Example 2: Input:rains = [1,2,0,0,2,1]\nOutput:[-1,-1,2,1,-1,-1]\nExplanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.", + "image": null + }, + { + "text": "Example 3: Input:rains = [1,2,0,1,2]\nOutput:[]\nExplanation:After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 47.1%) | Memory: 59.86 MB (Top 71.2%)\n\nclass Solution {\n public int[] avoidFlood(int[] rains) {\n // the previous appeared idx of rains[i]\n Map map = new HashMap<>();\n TreeSet zeros = new TreeSet<>();\n int[] res = new int[rains.length];\n for (int i = 0; i < rains.length; i++) {\n if (rains[i] == 0) {\n zeros.add(i);\n } else {\n if (map.containsKey(rains[i])) {\n // find the location of zero that can be used to empty rains[i]\n Integer next = zeros.ceiling(map.get(rains[i]));\n if (next == null) return new int[0];\n res[next] = rains[i];\n zeros.remove(next);\n }\n res[i] = -1;\n\t\t\t\tmap.put(rains[i], i);\n }\n }\n for (int i : zeros) res[i] = 1;\n return res;\n }\n}", + "title": "1488. Avoid Flood in The City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water , there will be a flood . Your goal is to avoid floods in any lake. Given an integer array rains where: Return an array ans where: If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array . Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.", + "description_images": [], + "constraints": [ + "rains[i] > 0 means there will be rains over the rains[i] lake.", + "rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it ." + ], + "examples": [ + { + "text": "Example 1: Input:rains = [1,2,3,4]\nOutput:[-1,-1,-1,-1]\nExplanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.", + "image": null + }, + { + "text": "Example 2: Input:rains = [1,2,0,0,2,1]\nOutput:[-1,-1,2,1,-1,-1]\nExplanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.", + "image": null + }, + { + "text": "Example 3: Input:rains = [1,2,0,1,2]\nOutput:[]\nExplanation:After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_left\n\nclass Solution:\n def avoidFlood(self, rains):\n full_lakes, dry_dates = {}, []\n ans = [-1] * len(rains)\n\n for date, rain_lake in enumerate(rains):\n if rain_lake == 0: # no rain, we can dry one lake\n dry_dates.append(date) # keep dry date, we'll decide later\n continue\n\n if rain_lake in full_lakes: # the lake is already full\n # BS find out earliest day we can use to dry that lake | greedy\n dry_day = bisect_left(dry_dates, full_lakes[rain_lake])\n\n if dry_day >= len(dry_dates): return [] # can not find a date to dry this lake\n\n ans[dry_dates.pop(dry_day)] = rain_lake # dry this lake at the date we choose\n\n # remember latest rain on this lake\n full_lakes[rain_lake] = date\n\n # we may have dry dates remain, on these days, rain > 0, we can not use -1, just choose day 1 to dry (maybe nothing happend)\n for dry_day in dry_dates:\n ans[dry_day] = 1\n\n return ans\n", + "title": "1488. Avoid Flood in The City", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two strings s and t , return true if they are equal when both are typed into empty text editors . '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 200", + "s and t only contain lowercase letters and '#' characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab#c\", t = \"ad#c\"\nOutput:true\nExplanation:Both s and t become \"ac\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab##\", t = \"c#d#\"\nOutput:true\nExplanation:Both s and t become \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a#c\", t = \"b\"\nOutput:false\nExplanation:s becomes \"c\" while t becomes \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 94.73%) | Memory: 42.2 MB (Top 59.43%)\n\nclass Solution {\n public boolean backspaceCompare(String s, String t) {\n int i = s.length() - 1, j = t.length() - 1;\n while(i >= 0 || j >= 0) {\n i = getCurPos(i, s);\n j = getCurPos(j, t);\n if (i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j)) return false;\n if ((i >= 0) != (j >= 0)) return false;\n i--;\n j--;\n }\n return true;\n }\n private int getCurPos(int i, String s) {\n int dels = 0;\n while( i >= 0) {\n if (s.charAt(i) == '#') {\n dels++;\n i--;\n } else if (dels > 0) {\n dels--;\n i--;\n } else break;\n }\n return i;\n }\n}", + "title": "844. Backspace String Compare", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , return true if they are equal when both are typed into empty text editors . '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 200", + "s and t only contain lowercase letters and '#' characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab#c\", t = \"ad#c\"\nOutput:true\nExplanation:Both s and t become \"ac\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab##\", t = \"c#d#\"\nOutput:true\nExplanation:Both s and t become \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a#c\", t = \"b\"\nOutput:false\nExplanation:s becomes \"c\" while t becomes \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def backwardResult(string):\n debt = 0\n \n for c in reversed(string):\n if c == '#':\n debt += 1\n \n elif debt > 0:\n debt -= 1\n \n else:\n yield c\n \n return all(a == b for (a, b) in zip_longest(backwardResult(s), backwardResult(t)))", + "title": "844. Backspace String Compare", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an initial power of power , an initial score of 0 , and a bag of tokens where tokens[i] is the value of the i th token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: Each token may be played at most once and in any order . You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens .", + "description_images": [], + "constraints": [ + "If your current power is at least tokens[i] , you may play the i th token face up, losing tokens[i] power and gaining 1 score .", + "If your current score is at least 1 , you may play the i th token face down, gaining tokens[i] power and losing 1 score ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [100], power = 50\nOutput:0\nExplanation:Playing the only token in the bag is impossible because you either have too little power or too little score.", + "image": null + }, + { + "text": "Example 2: Input:tokens = [100,200], power = 150\nOutput:1\nExplanation:Play the 0thtoken (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1sttoken since you cannot play it face up to add to your score.", + "image": null + }, + { + "text": "Example 3: Input:tokens = [100,200,300,400], power = 200\nOutput:2\nExplanation:Play the tokens in this order to get a score of 2:\n1. Play the 0thtoken (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3rdtoken (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1sttoken (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2ndtoken (300) face up, your power becomes 0 and score becomes 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int bagOfTokensScore(int[] tokens, int power) { \n //initially score is 0, that's why in these conditions, return 0. \n if(tokens.length == 0 || power < tokens[0])\n\t\t\treturn 0; \n Arrays.sort(tokens); //sort the array\n \n int i = 0;\n int r = tokens.length - 1;\n int score = 0;\n int answer = 0;\n \n while(i<=r){ \n if(power >= tokens[i]){\n power -= tokens[i++]; \n answer = Math.max(answer, ++score); //play all tokens, but store the max score in answer. \n }\n else if (score > 0){\n power += tokens[r--]; //take power from greatest element\n score--; //decrease by 1.\n } \n //when you can't do any of the steps (face up, face down)\n else\n return answer;\n } \n return answer;\n }\n}\n", + "title": "948. Bag of Tokens", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an initial power of power , an initial score of 0 , and a bag of tokens where tokens[i] is the value of the i th token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: Each token may be played at most once and in any order . You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens .", + "description_images": [], + "constraints": [ + "If your current power is at least tokens[i] , you may play the i th token face up, losing tokens[i] power and gaining 1 score .", + "If your current score is at least 1 , you may play the i th token face down, gaining tokens[i] power and losing 1 score ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [100], power = 50\nOutput:0\nExplanation:Playing the only token in the bag is impossible because you either have too little power or too little score.", + "image": null + }, + { + "text": "Example 2: Input:tokens = [100,200], power = 150\nOutput:1\nExplanation:Play the 0thtoken (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1sttoken since you cannot play it face up to add to your score.", + "image": null + }, + { + "text": "Example 3: Input:tokens = [100,200,300,400], power = 200\nOutput:2\nExplanation:Play the tokens in this order to get a score of 2:\n1. Play the 0thtoken (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3rdtoken (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1sttoken (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2ndtoken (300) face up, your power becomes 0 and score becomes 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 88.07%) | Memory: 17.40 MB (Top 31.65%)\n\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j=0,len(tokens)-1\n m=score=0\n while ipower and score==0:\n break \n if tokens[i]<=power:\n score+=1\n power-=tokens[i]\n m=max(m,score)\n i+=1\n else:\n if score>0:\n score-=1\n power+=tokens[j]\n j-=1\n if i arr = new ArrayList();\n InOrder( root, arr);\n return sortedArrayToBST( arr, 0, arr.size()-1);\n }\n \n public void InOrder(TreeNode node, List arr){\n if(node != null){\n InOrder( node.left, arr);\n arr.add(node.val);\n InOrder( node.right, arr);\n }\n }\n \n public TreeNode sortedArrayToBST(List arr, int start, int end) {\n\n if (start > end) {\n return null;\n }\n \n int mid = (start + end) / 2;\n \n TreeNode node = new TreeNode(arr.get(mid));\n node.left = sortedArrayToBST(arr, start, mid - 1);\n node.right = sortedArrayToBST(arr, mid + 1, end);\n \n return node;\n }\n}\n", + "title": "1382. Balance a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary search tree, return a balanced binary search tree with the same node values . If there is more than one answer, return any of them . A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,null,3,null,4,null,null]\nOutput:[2,1,3,null,null,null,4]\nExplanation:This is not the only correct answer, [3,1,4,null,2] is also correct.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]\nOutput:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def balanceBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n arr = []\n self.flatTree(root, arr)\n return self.createTree(arr, 0, len(arr))\n \n def flatTree(self, root, arr):\n if not root:\n return\n self.flatTree(root.left, arr)\n arr.append(root)\n self.flatTree(root.right, arr)\n \n def createTree(self, arr, start, length):\n if length == 0:\n return None\n root = arr[start + length / 2]\n root.left = self.createTree(arr, start, length / 2)\n root.right = self.createTree(arr, start + length / 2 + 1, length - length / 2 - 1)\n return root\n", + "title": "1382. Balance a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 86 ms (Top 5.00%) | Memory: 44 MB (Top 76.22%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n public int treeHeight(TreeNode root){\n if (root == null)\n return 0;\n\n int left = treeHeight(root.left);\n int right = treeHeight(root.right);\n\n return ( Math.max(left,right) + 1);\n\n }\n\n public boolean isBalanced(TreeNode root) {\n\n if (root == null)\n return true;\n\n boolean leftBalanced = isBalanced( root.left);\n boolean rightBalanced = isBalanced( root.right);\n int leftHeight = treeHeight(root.left);\n int rightHeight = treeHeight(root.right);\n\n //Return true only when all conditions are true\n return (leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1);\n\n }\n}", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n\n # Initialize the result to True\n res = True\n\n # DFS through the tree\n def dfs(node, i):\n nonlocal res\n\n # If there isn't a node, return previous depth\n if not node:\n return i - 1\n\n # Check depths of the left and right subtrees\n left, right = dfs(node.left, i + 1), dfs(node.right, i + 1)\n\n # If they are more than 1 difference, save False to the result\n if abs(right - left) > 1:\n res = False\n\n # Return the max depth of both subtrees\n return max(left, right)\n\n dfs(root, 0)\n\n return res\n", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops , where ops[i] is the i th operation you must apply to the record and is one of the following: Return the sum of all the scores on the record . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= ops.length <= 1000", + "ops[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." + ], + "examples": [ + { + "text": "Example 1: Input:ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput:30\nExplanation:\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.", + "image": null + }, + { + "text": "Example 2: Input:ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput:27\nExplanation:\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.", + "image": null + }, + { + "text": "Example 3: Input:ops = [\"1\",\"C\"]\nOutput:0\nExplanation:\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int calPoints(String[] ops) {\n List list = new ArrayList();\n \n for(int i = 0; i < ops.length; i++){\n switch(ops[i]){\n case \"C\":\n list.remove(list.size() - 1);\n break;\n case \"D\":\n list.add(list.get(list.size() - 1) * 2);\n break;\n case \"+\":\n list.add(list.get(list.size() - 1) + list.get(list.size() - 2));\n break;\n default:\n list.add(Integer.valueOf(ops[i]));\n break;\n }\n }\n \n int finalScore = 0;\n for(Integer score: list)\n finalScore += score;\n \n return finalScore;\n }\n}\n", + "title": "682. Baseball Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops , where ops[i] is the i th operation you must apply to the record and is one of the following: Return the sum of all the scores on the record . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= ops.length <= 1000", + "ops[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." + ], + "examples": [ + { + "text": "Example 1: Input:ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput:30\nExplanation:\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.", + "image": null + }, + { + "text": "Example 2: Input:ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput:27\nExplanation:\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.", + "image": null + }, + { + "text": "Example 3: Input:ops = [\"1\",\"C\"]\nOutput:0\nExplanation:\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def calPoints(self, ops: List[str]) -> int:\n temp = []\n for i in ops:\n if i!=\"C\" and i!=\"D\" and i!=\"+\":\n temp.append(int(i))\n elif i==\"C\":\n temp.remove(temp[len(temp)-1])\n elif i==\"D\":\n temp.append(2*temp[len(temp)-1])\n elif i==\"+\":\n temp.append(temp[len(temp)-1]+temp[len(temp)-2])\n \n \n return sum(temp)\n", + "title": "682. Baseball Game", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int idx; // this index traverse the string in one pass, between different level of recursion\n public int calculate(String s) {\n idx = 0; // Initialization should be here\n return helper(s);\n }\n \n private int helper(String s) {\n int res = 0, num = 0, preSign = 1, n = s.length();\n while (idx < n) {\n char c = s.charAt(idx++);\n if (c == '(') num = helper(s); // Let recursion solve the sub-problem\n else if (c >= '0' && c <= '9') num = num * 10 + c - '0';\n if (c == '+' || c == '-' || c == ')' || idx == n) { // we need one more calculation when idx == n\n res += preSign * num;\n if (c == ')') return res; // end of a sub-problem\n num = 0;\n preSign = c == '+' ? 1 : -1;\n }\n }\n return res;\n }\n}\n", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 57.95%) | Memory: 15.5 MB (Top 50.78%)\n\n```class Solution:\n def calculate(self, s: str) -> int:\n curr,output,sign,stack = 0,0,1,[]\n\n for ch in s:\n if ch.isdigit():\n curr = curr * 10 + int(ch)\n\n elif ch == '+':\n output += sign * curr\n sign = 1\n curr = 0\n\n elif ch == '-':\n output += sign * curr\n sign = -1\n curr = 0\n\n elif ch == '(':\n #push the result and then the sign\n stack.append(output)\n stack.append(sign)\n sign = 1\n output = 0\n\n elif ch == ')':\n output += sign * curr\n output *= stack.pop()\n output += stack.pop()\n curr = 0\n return output + sign*curr``", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s which represents an expression, evaluate this expression and return its value . The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.", + "s represents a valid expression .", + "All the integers in the expression are non-negative integers in the range [0, 2 31 - 1] .", + "The answer is guaranteed to fit in a 32-bit integer ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3+2*2\"\nOutput:7", + "image": null + }, + { + "text": "Example 2: Input:s = \" 3/2 \"\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:s = \" 3+5 / 2 \"\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 27.28%) | Memory: 45.6 MB (Top 25.17%)\nclass Solution {\n public int calculate(String s) {\n if(s==null ||s.length()==0)return 0;\n Stack st = new Stack<>();\n int curr=0;\n char op = '+';\n char [] ch = s.toCharArray();\n for(int i=0;i int:\n stack = []\n currentNumber = 0\n operator = '+'\n operations = '+-/*'\n for i in range(len(s)):\n ch = s[i]\n if ch.isdigit():\n currentNumber = currentNumber * 10 + int(ch)\n\n if ch in operations or i == len(s) - 1:\n if operator == '+':\n stack.append(currentNumber)\n\n elif operator == '-':\n stack.append(-currentNumber)\n\n elif operator == '*':\n stack.append(stack.pop() * currentNumber)\n\n elif operator == '/':\n stack.append(int(stack.pop()/currentNumber))\n\n currentNumber =0\n operator = ch\n\n return sum(stack)\n", + "title": "227. Basic Calculator II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1] ), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"] Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. The format of the output is as follows: Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] .", + "description_images": [], + "constraints": [ + "An expression alternates chunks and symbols, with a space separating each chunk and symbol.", + "A chunk is either an expression in parentheses, a variable, or a non-negative integer.", + "A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like \"2x\" or \"-x\" ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\nOutput:[\"-1*a\",\"14\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\nOutput:[\"-1*pressure\",\"5\"]", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\nOutput:[\"1*e*e\",\"-64\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Node {\n Map, Integer> mem = new HashMap<>();\n \n void update(List cur, int cnt) {\n Collections.sort(cur);\n mem.put(cur, mem.getOrDefault(cur, 0) + cnt);\n }\n \n Node add(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n ans.update(key1, mem.get(key1));\n }\n for (List key2 : cur.mem.keySet()) {\n ans.update(key2, cur.mem.get(key2));\n }\n return ans;\n }\n Node sub(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n ans.update(key1, mem.get(key1));\n }\n for (List key2 : cur.mem.keySet()) {\n ans.update(key2, -cur.mem.get(key2));\n }\n return ans;\n }\n \n Node mul(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n for (List key2 : cur.mem.keySet()) {\n List next = new ArrayList<>();\n next.addAll(key1);\n next.addAll(key2);\n ans.update(next, mem.get(key1) * cur.mem.get(key2));\n }\n }\n return ans;\n }\n \n Node evaluate(Map vars) {\n Node ans = new Node();\n for (List cur : mem.keySet()) {\n int cnt = mem.get(cur);\n List free = new ArrayList<>();\n for (String tmp : cur) {\n if (vars.containsKey(tmp)) {\n cnt = cnt * vars.get(tmp);\n } else {\n free.add(tmp);\n }\n }\n ans.update(free, cnt);\n }\n \n return ans;\n }\n \n List toList() {\n List ans = new ArrayList<>();\n List> keys = new ArrayList<>(mem.keySet());\n Collections.sort(keys, (List a, List b) -> {\n if (a.size() != b.size()) {\n return b.size() - a.size();\n }\n for (int i = 0; i < a.size(); i ++) {\n if (a.get(i).compareTo(b.get(i)) != 0) {\n return a.get(i).compareTo(b.get(i));\n }\n }\n return 0;\n });\n \n for (List key : keys) {\n if (mem.get(key) == 0) {\n continue;\n }\n String cur = \"\" + String.valueOf(mem.get(key));\n for (String data : key) {\n cur += \"*\";\n cur += data;\n }\n ans.add(cur);\n }\n return ans;\n }\n }\n \n Node make(String cur) {\n Node ans = new Node();\n List tmp = new ArrayList<>();\n if (Character.isDigit(cur.charAt(0))) {\n ans.update(tmp, Integer.valueOf(cur));\n } else {\n tmp.add(cur);\n ans.update(tmp, 1);\n }\n return ans;\n }\n int getNext(String expression, int start) {\n int end = start;\n while (end < expression.length() && Character.isLetterOrDigit(expression.charAt(end))) {\n end ++;\n }\n return end - 1;\n }\n \n int getPriority(char a) {\n if (a == '+' || a == '-') {\n return 1;\n } else if (a == '*') {\n return 2;\n }\n return 0;\n }\n \n Node helper(Stack nums, Stack ops) {\n Node b = nums.pop();\n Node a = nums.pop();\n char op = ops.pop();\n if (op == '*') {\n return a.mul(b);\n } else if (op == '+') {\n return a.add(b);\n } \n return a.sub(b);\n }\n \n public List basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {\n List ans = new ArrayList<>();\n if (expression == null || expression.length() == 0 || evalvars == null || evalints == null) {\n return ans;\n }\n \n Map vars = new HashMap<>();\n for (int i = 0; i < evalvars.length; i ++) {\n vars.put(evalvars[i], evalints[i]);\n }\n \n int n = expression.length();\n Stack nums = new Stack<>();\n Stack ops = new Stack<>();\n for (int i = 0; i < n; i ++) {\n char a = expression.charAt(i);\n if (Character.isLetterOrDigit(a)) {\n int end = getNext(expression, i);\n String cur = expression.substring(i, end + 1);\n i = end;\n Node now = make(cur);\n nums.add(now);\n } else if (a == '(') {\n ops.add(a);\n } else if (a == ')') {\n while (ops.peek() != '(') {\n nums.add(helper(nums, ops));\n }\n ops.pop();\n } else if (a == '+' || a == '-' || a == '*') {\n while (ops.size() > 0 && getPriority(ops.peek()) >= getPriority(a)) {\n nums.add(helper(nums, ops));\n }\n ops.add(a);\n }\n }\n \n while (ops.size() > 0) {\n nums.add(helper(nums, ops));\n }\n \n return nums.peek().evaluate(vars).toList();\n \n }\n}\n", + "title": "770. Basic Calculator IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1] ), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"] Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. The format of the output is as follows: Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] .", + "description_images": [], + "constraints": [ + "An expression alternates chunks and symbols, with a space separating each chunk and symbol.", + "A chunk is either an expression in parentheses, a variable, or a non-negative integer.", + "A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like \"2x\" or \"-x\" ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\nOutput:[\"-1*a\",\"14\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\nOutput:[\"-1*pressure\",\"5\"]", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\nOutput:[\"1*e*e\",\"-64\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 83.61%) | Memory: 14.1 MB (Top 62.30%)\nclass Term:\n def __init__(self, exp: Optional[str]='', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r'^\\-?\\d+$', exp):\n self.d[''] += int(exp)\n elif exp:\n self.d[exp] += 1\n\n def __add__(self, other: 'Term') -> 'Term':\n return self._pm(other, add=True)\n\n def __mul__(self, other: 'Term') -> 'Term':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res['*'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n\n def __sub__(self, other: 'Term') -> 'Term':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+'*'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n\n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split('*')))\n\n def _pm(self, other: 'Term', *, add: bool) -> 'Term':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r'[a-z0-9]+', lambda m: \"Term('\"+str(vals.get(m.group(), m.group()))+\"')\", expression)).get()", + "title": "770. Basic Calculator IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.' , return the number of the battleships on board . Battleships can only be placed horizontally or vertically on board . In other words, they can only be made of the shape 1 x k ( 1 row, k columns) or k x 1 ( k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is either '.' or 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/04/10/battelship-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[\".\"]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 10.56%) | Memory: 44.7 MB (Top 26.11%)\nclass Solution {\n public int countBattleships(char[][] board) {\n int result = 0;\n for(int i = 0;i= board.length || j<0 || j>=board[0].length || board[i][j] == '.')\n {\n return;\n }\n board[i][j] = '.';\n remover(i+1, j, board);\n remover(i, j+1, board);\n }\n}", + "title": "419. Battleships in a Board", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.' , return the number of the battleships on board . Battleships can only be placed horizontally or vertically on board . In other words, they can only be made of the shape 1 x k ( 1 row, k columns) or k x 1 ( k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is either '.' or 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/04/10/battelship-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[\".\"]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBattleships(self, board: List[List[str]]) -> int:\n \n m = len(board)\n n = len(board[0])\n res = 0\n \n pole = [ [True for i in range(n)] for j in range(m) ]\n \n for i in range(m):\n for j in range(n):\n if board[i][j] == 'X' and pole[i][j]:\n for z in range(i+1, m):\n if board[z][j] == 'X':\n pole[z][j] = False\n else:\n break\n \n for z in range(j+1, n):\n if board[i][z] == 'X':\n pole[i][z] = False\n else:\n break\n \n \n res += 1\n \n\n \n return res\n", + "title": "419. Battleships in a Board", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Suppose you have n integers labeled 1 through n . A permutation of those n integers perm ( 1-indexed ) is considered a beautiful arrangement if for every i ( 1 <= i <= n ), either of the following is true: Given an integer n , return the number of the beautiful arrangements that you can construct .", + "description_images": [], + "constraints": [ + "perm[i] is divisible by i .", + "i is divisible by perm[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:The first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 93.01%) | Memory: 44.8 MB (Top 13.42%)\nclass Solution {\n int N;\n Integer[][] memo;\n public int countArrangement(int n) {\n this.N = n;\n memo = new Integer[n+1][1< int:\n self.count = 0\n self.backtrack(n, 1, [])\n return self.count\n \n def backtrack(self, N, idx, temp):\n if len(temp) == N:\n self.count += 1\n return\n \n for i in range(1, N+1):\n if i not in temp and (i % idx == 0 or idx % i == 0):\n temp.append(i)\n self.backtrack(N, idx+1, temp)\n temp.pop()", + "title": "526. Beautiful Arrangement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers n and k , construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Return the list answer . If there multiple valid answers, return any of them .", + "description_images": [], + "constraints": [ + "Suppose this list is answer = [a 1 , a 2 , a 3 , ... , a n ] , then the list [|a 1 - a 2 |, |a 2 - a 3 |, |a 3 - a 4 |, ... , |a n-1 - a n |] has exactly k distinct integers." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1\nOutput:[1,2,3]\n\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 2\nOutput:[1,3,2]\n\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] constructArray(int n, int k) {\n int [] result = new int[n];\n result[0] = 1;\n int sign = 1;\n for(int i = 1 ; i < n; i++, k--){\n if(k > 0){\n result[i] = result[i-1] + k * sign;\n sign *= -1;\n }\n else{\n result[i] = i+1;\n }\n }\n return result;\n }\n}\n", + "title": "667. Beautiful Arrangement II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two integers n and k , construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Return the list answer . If there multiple valid answers, return any of them .", + "description_images": [], + "constraints": [ + "Suppose this list is answer = [a 1 , a 2 , a 3 , ... , a n ] , then the list [|a 1 - a 2 |, |a 2 - a 3 |, |a 3 - a 4 |, ... , |a n-1 - a n |] has exactly k distinct integers." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1\nOutput:[1,2,3]\n\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 2\nOutput:[1,3,2]\n\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n # n = 8, k = 5\n # 1 2 3 8 4 7 5 6\n # 1 1 5 4 3 2 1\n res = list(range(1,n-k+1))\n sign, val = 1, k\n for i in range(k):\n res.append(res[-1]+sign*val)\n sign *= -1\n val -= 1\n return res\n", + "title": "667. Beautiful Arrangement II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array nums of length n is beautiful if: Given the integer n , return any beautiful array nums of length n . There will be at least one valid answer for the given n .", + "description_images": [], + "constraints": [ + "nums is a permutation of the integers in the range [1, n] .", + "For every 0 <= i < j < n , there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:[2,1,4,3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[3,1,2,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import permutations\nclass Solution:\n def invalid(self, x):\n n = len(x)\n flag = False\n for i in range(n):\n if flag: break\n for j in range(i+2, n):\n if flag: break\n for k in range(i+1, j):\n if 2*x[k] == x[i]+x[j]: flag = True; break\n return flag\n \n def beautifulArray(self, n: int) -> List[int]:\n for perm in permutations(range(1, n+1)):\n if not self.invalid(perm):\n return perm\n", + "title": "932. Beautiful Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array ranks and a character array suits . You have 5 cards where the i th card has a rank of ranks[i] and a suit of suits[i] . The following are the types of poker hands you can make from best to worst: Return a string representing the best type of poker hand you can make with the given cards. Note that the return values are case-sensitive .", + "description_images": [], + "constraints": [ + "ranks.length == suits.length == 5", + "1 <= ranks[i] <= 13", + "'a' <= suits[i] <= 'd'", + "No two cards have the same rank and suit." + ], + "examples": [ + { + "text": "Example 1: Input:ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\nOutput:\"Flush\"\nExplanation:The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".", + "image": null + }, + { + "text": "Example 2: Input:ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\nOutput:\"Three of a Kind\"\nExplanation:The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.", + "image": null + }, + { + "text": "Example 3: Input:ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\nOutput:\"Pair\"\nExplanation:The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 33.75%)\nclass Solution {\n public String bestHand(int[] ranks, char[] suits) {\n int max = 0;\n int card = 0;\n char ch = suits[0];\n int[] arr = new int[14];\n for(int i = 0; i < 5; i++){\n arr[ranks[i]]++;\n max = Math.max(max,arr[ranks[i]]);\n if(suits[i] == ch) card++;\n }\n if(card == 5) return \"Flush\";\n return max >= 3 ? \"Three of a Kind\":(max == 2 ? \"Pair\" : \"High Card\");\n }\n}", + "title": "2347. Best Poker Hand", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array ranks and a character array suits . You have 5 cards where the i th card has a rank of ranks[i] and a suit of suits[i] . The following are the types of poker hands you can make from best to worst: Return a string representing the best type of poker hand you can make with the given cards. Note that the return values are case-sensitive .", + "description_images": [], + "constraints": [ + "ranks.length == suits.length == 5", + "1 <= ranks[i] <= 13", + "'a' <= suits[i] <= 'd'", + "No two cards have the same rank and suit." + ], + "examples": [ + { + "text": "Example 1: Input:ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\nOutput:\"Flush\"\nExplanation:The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".", + "image": null + }, + { + "text": "Example 2: Input:ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\nOutput:\"Three of a Kind\"\nExplanation:The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.", + "image": null + }, + { + "text": "Example 3: Input:ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\nOutput:\"Pair\"\nExplanation:The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 59.18%) | Memory: 13.9 MB (Top 14.06%)\nclass Solution:\n def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n s={}\n for i in suits:\n if i in s:\n s[i]+=1\n if s[i]==5:\n return 'Flush'\n else:\n s[i]=1\n r={}\n max_ = 0\n for i in ranks:\n if i in r:\n r[i]+=1\n max_=max(max_,r[i])\n else:\n r[i]=1\n if max_>=3:\n return \"Three of a Kind\"\n elif max_==2:\n return \"Pair\"\n else:\n return \"High Card\"", + "title": "2347. Best Poker Hand", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum . Given an array positions where positions[i] = [x i , y i ] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [x centre , y centre ] such that the following formula is minimized: Answers within 10 -5 of the actual value will be accepted.", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 50", + "positions[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput:4.00000\nExplanation:As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg" + }, + { + "text": "Example 2: Input:positions = [[1,1],[3,3]]\nOutput:2.82843\nExplanation:The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final double MIN_STEP = 0.0000001;\n private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n public double getMinDistSum(int[][] positions) {\n double cx = 0, cy = 0;\n int n = positions.length;\n for (int[] pos: positions) {\n cx += pos[0];\n cy += pos[1];\n }\n cx /= n; cy /= n;\n Node center = new Node(cx, cy, totalDistance(positions, cx, cy));\n\n double step = 50.0;\n while (step > MIN_STEP) {\n Node min = center;\n for (int[] direction: DIRECTIONS) {\n double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step;\n double totalDist = totalDistance(positions, dx, dy);\n if (totalDist < center.dist) min = new Node(dx, dy, totalDist);\n }\n if (center == min) step /= 2;\n center = min;\n }\n\n return center.dist;\n }\n\n private double sq(double p) {\n return p * p;\n }\n\n private double dist(int[] pos, double x, double y) {\n return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1]));\n }\n\n private double totalDistance(int[][] positions, double x, double y) {\n double dist = 0;\n for (int[] pos: positions) dist += dist(pos, x, y);\n return dist;\n }\n\n private static class Node {\n double x, y, dist;\n Node (double x, double y, double dist) {\n this.x = x;\n this.y = y;\n this.dist = dist;\n }\n }\n}\n", + "title": "1515. Best Position for a Service Centre", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum . Given an array positions where positions[i] = [x i , y i ] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [x centre , y centre ] such that the following formula is minimized: Answers within 10 -5 of the actual value will be accepted.", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 50", + "positions[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput:4.00000\nExplanation:As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg" + }, + { + "text": "Example 2: Input:positions = [[1,1],[3,3]]\nOutput:2.82843\nExplanation:The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n n = len(positions)\n if n == 1: return 0\n def gradient(x,y):\n ans = [0,0]\n for i in range(n):\n denom = math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n ans[0] += (x-positions[i][0])/denom if denom else 0\n ans[1] += (y-positions[i][1])/denom if denom else 0\n return ans\n def fn(x, y):\n res = 0\n for i in range(n):\n res += math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n return res\n x = sum(x for x,_ in positions)/n\n y = sum(y for _,y in positions)/n\n lr = 1\n while lr > 1e-7:\n dx, dy = gradient(x,y)\n x -= lr*dx\n y -= lr*dy\n lr *= 0.997\n if not dx and not dy:\n lr /= 2\n return fn(x,y)", + "title": "1515. Best Position for a Service Centre", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array values where values[i] represents the value of the i th sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair ( i < j ) of sightseeing spots is values[i] + values[j] + i - j : the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots .", + "description_images": [], + "constraints": [ + "2 <= values.length <= 5 * 10^4", + "1 <= values[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [8,1,5,2,6]\nOutput:11\nExplanation:i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 77.63%) | Memory: 50.10 MB (Top 66.67%)\n\nclass Solution {\n public int maxScoreSightseeingPair(int[] A) {\n // A[i] + A[j] + i - j = (A[i]+i) + (A[j]-j)\n // think about dividing them into two parts\n // get the max of left part and right part, then add them \n // to get the maximum score\n //\n // max(left) + max(right)\n // maximum score = max(A[i]+i) + max((A[j]-j))\n\n /* example:\n i 0 1 2 3 4\n A [8, 1, 5, 2, 6], max = 0\n \n i=1,\n left = A[0]+0 = 8\n right = A[1]-1 = 0\n => max = max(max=0, left + right=8) = 8\n Before moving to i=2, we need to update left part by \n comparing current left and right\n so ----> left = max(left=8, A[1]+1=2) = 8\n i=2,\n left = 8\n right = A[2]-2 = 3\n => max = max(max=8, left + right=11) = 11\n so ----> left = max(left=8, A[2]+2=7) = 8 \n i=3,\n left = 8\n right = A[3]-3 = 1\n => max = max(max=11, left + right=9) = 11\n so ----> left = max(left=8, A[3]+3=5) = 8 \n i=4,\n left = 8\n right = A[4]-4 = 2\n => max = max(max=11, left + right=10) = 11\n so ----> left = max(left=8, A[4]+4=10) = 8 \n end loop\n max = 11\n */\n int N = A.length;\n int left = A[0]+0;\n int right = 0; \n int max = 0;\n\n for (int i=1; i int:\n left_max_vals = [float('-inf') for _ in range(len(values))]\n right_max_vals = [float('-inf') for _ in range(len(values))]\n \n for i in range(1, len(values)):\n left_max_vals[i] = max(left_max_vals[i-1]-1, values[i-1]-1)\n \n for i in range(len(values)-2, -1, -1):\n right_max_vals[i] = max(right_max_vals[i+1]-1, values[i+1]-1)\n \n max_pair = float('-inf')\n for i in range(len(values)):\n max_pair = max(max_pair, values[i] + max(left_max_vals[i], right_max_vals[i]))\n return max_pair\n", + "title": "1014. Best Sightseeing Pair", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts . A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages , where each scores[i] and ages[i] represents the score and age of the i th player, respectively, return the highest overall score of all possible basketball teams .", + "description_images": [], + "constraints": [ + "1 <= scores.length, ages.length <= 1000", + "scores.length == ages.length", + "1 <= scores[i] <= 10^6", + "1 <= ages[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput:34\nExplanation:You can choose all the players.", + "image": null + }, + { + "text": "Example 2: Input:scores = [4,5,6,5], ages = [2,1,2,1]\nOutput:16\nExplanation:It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.", + "image": null + }, + { + "text": "Example 3: Input:scores = [1,2,3,5], ages = [8,9,10,1]\nOutput:6\nExplanation:It is best to choose the first 3 players.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 92.02%) | Memory: 45.10 MB (Top 27.31%)\n\nclass Solution {\n int res = 0;\n public int bestTeamScore(int[] scores, int[] ages) {\n int len = scores.length;\n int[][] team = new int[len][2];\n for (int i = 0; i < len; i++) {\n team[i][0] = ages[i];\n team[i][1] = scores[i]; // team is [age, score]\n }\n\t\t// double sort first by age then by score, then we can traverse from young to old\n Arrays.sort(team, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);\n \n int[] dp = new int[len];\n // dp is the max sum for all sequences (not necessarily consecutive) ending in current idx\n dp[0] = team[0][1];\n for (int i = 1; i < len; i++) {\n int max = team[i][1]; // At least it could start a new sequence by itself without extend\n\t\t\t// for each current idx, go visit all previous index to grow the sequences\n for (int j = 0; j < i; j++) {\n if (team[i][1] >= team[j][1]) {\n max = Math.max(max, dp[j] + team[i][1]);\n }\n }\n dp[i] = max;\n }\n \n int res = 0;\n for (int num : dp) {\n res = Math.max(res, num);\n }\n \n return res;\n }\n}\n", + "title": "1626. Best Team With No Conflicts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts . A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages , where each scores[i] and ages[i] represents the score and age of the i th player, respectively, return the highest overall score of all possible basketball teams .", + "description_images": [], + "constraints": [ + "1 <= scores.length, ages.length <= 1000", + "scores.length == ages.length", + "1 <= scores[i] <= 10^6", + "1 <= ages[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput:34\nExplanation:You can choose all the players.", + "image": null + }, + { + "text": "Example 2: Input:scores = [4,5,6,5], ages = [2,1,2,1]\nOutput:16\nExplanation:It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.", + "image": null + }, + { + "text": "Example 3: Input:scores = [1,2,3,5], ages = [8,9,10,1]\nOutput:6\nExplanation:It is best to choose the first 3 players.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5727 ms (Top 5.11%) | Memory: 14.3 MB (Top 62.50%)\nclass Solution(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n l = len(scores)\n mapped = [[ages[i], scores[i]] for i in range(l)]\n mapped = sorted(mapped, key = lambda x : (x[0], x[1]))\n dp = [i[1] for i in mapped]\n\n for i in range(l):\n for j in range(0, i):\n if mapped[j][1] <= mapped[i][1]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n elif mapped[i][0] == mapped[j][0]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n\n return max(dp)", + "title": "1626. Best Team With No Conflicts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:5\nExplanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 93.59%) | Memory: 83.9 MB (Top 46.18%)\nclass Solution {\n public int maxProfit(int[] prices) {\n int lsf = Integer.MAX_VALUE;\n int op = 0;\n int pist = 0;\n\n for(int i = 0; i < prices.length; i++){\n if(prices[i] < lsf){\n lsf = prices[i];\n }\n pist = prices[i] - lsf;\n if(op < pist){\n op = pist;\n }\n }\n return op;\n }\n}", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:5\nExplanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2509 ms (Top 5.01%) | Memory: 25 MB (Top 86.17%)\n\nclass Solution:\n def maxProfit(self,prices):\n left = 0 #Buy\n right = 1 #Sell\n max_profit = 0\n while right < len(prices):\n currentProfit = prices[right] - prices[left] #our current Profit\n if prices[left] < prices[right]:\n max_profit =max(currentProfit,max_profit)\n else:\n left = right\n right += 1\n return max_profit", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:7\nExplanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n int n = prices.length,profit = 0;\n for(int i=0;iprices[i]){\n profit += prices[i+1]-prices[i];\n }\n }\n return profit;\n }\n}", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:7\nExplanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n=len(prices)\n ans=0\n want=\"valley\"\n for i in range(n-1):\n if want==\"valley\" and prices[i]prices[i+1]:\n ans+=prices[i]\n want=\"valley\"\n if want==\"hill\":\n ans+=prices[-1]\n return ans\n", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]\nOutput:6\nExplanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n \n int n = prices.length;\n int maxSellProfit = 0;\n int min = prices[0];\n int[] maxSellArr = new int[n];\n int i = 1;\n \n while(i < n){\n if(prices[i] < min){\n min = prices[i];\n }\n maxSellArr[i] = Math.max(maxSellArr[i-1],prices[i] - min); \n \n i++;\n }\n int[] maxBuyArr = new int[n];\n int j = n-2;\n int max = prices[n-1];\n while(j >= 0){\n if(prices[j] > max){\n max = prices[j];\n }\n maxBuyArr[j] = Math.max(maxBuyArr[j+1],max - prices[j]);\n \n j--;\n }\n int maxProfitTwoTrans = 0;\n for(int k = 0; k < n; k++){\n maxProfitTwoTrans = Math.max(maxProfitTwoTrans,maxBuyArr[k] + maxSellArr[k]);\n }\n return maxProfitTwoTrans;\n }\n}\n", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]\nOutput:6\nExplanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy1, sell1, buy2, sell2 = -inf,0,-inf,0\n for price in prices:\n buy1 = max(buy1,-price)\n sell1 = max(sell1,price+buy1)\n \n buy2 = max(buy2,sell1-price)\n sell2 = max(sell2,price+buy2)\n return sell2\n", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "0 <= k <= 100", + "0 <= prices.length <= 1000", + "0 <= prices[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, prices = [2,4,1]\nOutput:2\nExplanation:Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, prices = [3,2,6,5,0,3]\nOutput:7\nExplanation:Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int k, int[] prices) {\n int transaction = k;\n int N = prices.length;\n int[][][]dp =new int[N][2][k+1];\n for(int i=0;i int:\n buy = [-inf] * (k+1)\n sell = [0] * (k+1)\n for price in prices:\n for i in range(1,k+1):\n buy[i] = max(buy[i],sell[i-1]-price)\n sell[i] = max(sell[i],buy[i]+price)\n return sell[-1]\n", + "title": "188. Best Time to Buy and Sell Stock IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day)." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,2,3,0,2]\nOutput:3\nExplanation:transactions = [buy, sell, cooldown, buy, sell]", + "image": null + }, + { + "text": "Example 2: Input:prices = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 55.13%) | Memory: 42.3 MB (Top 47.48%)\nclass Solution {\n public int maxProfit(int[] prices) {\n\n int n = prices.length;\n\n int[][] dp = new int[n+2][2];\n\n for(int index = n-1; index>=0; index--){\n for(int buy = 0; buy<=1; buy++){\n\n int profit = 0;\n\n if(buy == 0){ // buy stocks\n profit = Math.max(-prices[index] + dp[index+1][1], 0 + dp[index+1][0]);\n }\n if(buy == 1){ // we can sell stocks\n profit = Math.max(prices[index] + dp[index+2][0], 0 + dp[index+1][1]);\n }\n dp[index][buy] = profit;\n }\n }\n return dp[0][0];\n }\n}", + "title": "309. Best Time to Buy and Sell Stock with Cooldown", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day)." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,2,3,0,2]\nOutput:3\nExplanation:transactions = [buy, sell, cooldown, buy, sell]", + "image": null + }, + { + "text": "Example 2: Input:prices = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n \n cache = {}\n def dfs(i, buying):\n \n if i >= len(prices):\n return 0\n \n if (i, buying) in cache:\n return cache[(i, buying)]\n \n if buying:\n # if have sell the share in previous step\n # then currently we have two options\n # either buy or not buy(cooldown)\n \n # we have bought so, increment the index and set buying flag to not buying\n # and don't forget that we bought so, we have to reduce that share amount from profit\n buy = dfs(i+1, not buying) - prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( buy, cooldown )\n cache[(i, buying)] = profit\n \n else:\n # we have sell the share so, \n # we cannot buy next share we have to skip the next price(cooldown for one day)\n # set (not buying) flag to buying\n # we also have to add that share price to profit\n sell = dfs(i+2, not buying) + prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( sell, cooldown )\n cache[(i, buying)] = profit\n \n return cache[(i, buying)]\n \n return dfs(0, True)\n\n", + "title": "309. Best Time to Buy and Sell Stock with Cooldown", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 5 * 10^4", + "1 <= prices[i] < 5 * 10^4", + "0 <= fee < 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2\nOutput:8\nExplanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 22.74%) | Memory: 58.7 MB (Top 87.06%)\nclass Solution {\n public int maxProfit(int[] prices, int fee) {\n int[][] dp = new int[prices.length][2];\n for (int[] a : dp) {\n a[0] = -1;\n a[1] = -1;\n }\n return profit(prices, fee, 0, 1, dp);\n }\n public int profit(int[] prices, int fee, int i, int buy, int[][] dp) {\n if (i == prices.length) {\n return 0;\n }\n if (dp[i][buy] != -1) {\n return dp[i][buy];\n }\n int maxProfit = 0;\n if (buy == 1) {\n int yesBuy = profit(prices, fee, i + 1, 0, dp) - prices[i];\n int noBuy = profit(prices, fee, i + 1, 1, dp);\n maxProfit = Math.max(yesBuy, noBuy);\n } else {\n int yesSell = prices[i] - fee + profit(prices, fee, i + 1, 1, dp);\n int noSell = profit(prices, fee, i + 1, 0, dp);\n maxProfit = Math.max(yesSell, noSell);\n }\n return dp[i][buy] = maxProfit;\n }\n}", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 5 * 10^4", + "1 <= prices[i] < 5 * 10^4", + "0 <= fee < 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2\nOutput:8\nExplanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n n = len(prices)\n lookup = {}\n def f(ind, buy, lookup):\n \n if ind == n: return 0\n \n if (ind, buy) in lookup: return lookup[(ind, buy)]\n profit = 0\n if buy:\n profit = max(-prices[ind] + f(ind+1,0,lookup), f(ind+1, 1,lookup))\n else:\n profit = max(prices[ind] + f(ind+1,1,lookup) - fee, f(ind+1, 0,lookup))\n \n lookup[(ind,buy)] = profit\n return lookup[(ind,buy)]\n \n return f(0, 1,lookup)\n\n", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , find and return the longest distance between any two adjacent 1 's in the binary representation of n . If there are no two adjacent 1 's, return 0 . Two 1 's are adjacent if there are only 0 's separating them (possibly no 0 's). The distance between two 1 's is the absolute difference between their bit positions. For example, the two 1 's in \"1001\" have a distance of 3.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 22\nOutput:2\nExplanation:22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 8\nOutput:0\nExplanation:8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.", + "image": null + }, + { + "text": "Example 3: Input:n = 5\nOutput:2\nExplanation:5 in binary is \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 30.57%) | Memory: 41 MB (Top 56.77%)\nclass Solution {\n public int binaryGap(int n) {\n char[] arr = Integer.toBinaryString(n).toCharArray();\n List ans = new ArrayList();\n for(int i = 0; i < arr.length ; i++){\n if(arr[i] == '1')\n ans.add(i);\n }\n int res = 0;\n for ( int i = 0 ; i < ans.size() -1 ; i++){\n res =Math.max(res,ans.get(i+1) - ans.get(i));\n }\n return res;\n }\n}", + "title": "868. Binary Gap", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer n , find and return the longest distance between any two adjacent 1 's in the binary representation of n . If there are no two adjacent 1 's, return 0 . Two 1 's are adjacent if there are only 0 's separating them (possibly no 0 's). The distance between two 1 's is the absolute difference between their bit positions. For example, the two 1 's in \"1001\" have a distance of 3.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 22\nOutput:2\nExplanation:22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 8\nOutput:0\nExplanation:8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.", + "image": null + }, + { + "text": "Example 3: Input:n = 5\nOutput:2\nExplanation:5 in binary is \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def binaryGap(self, n: int) -> int:\n prev = 0\n res = 0\n for i, d in enumerate(bin(n)[3:]):\n if d == \"1\":\n res = max(res, i-prev+1)\n prev = i + 1\n return res\n", + "title": "868. Binary Gap", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:true\nExplanation:The binary representation of 5 is: 101", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:false\nExplanation:The binary representation of 7 is: 111.", + "image": null + }, + { + "text": "Example 3: Input:n = 11\nOutput:false\nExplanation:The binary representation of 11 is: 1011.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.76 MB (Top 13.5%)\n\nclass Solution {\n public boolean hasAlternatingBits(int n) {\n int flag = 1;\n if(n % 2 == 0) flag = 0;\n return bin(n / 2, flag);\n }\n public boolean bin(int n, int flag) {\n if(flag == n % 2) return false;\n if(n == 0) return true;\n else return bin(n / 2, n % 2);\n }\n}", + "title": "693. Binary Number with Alternating Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:true\nExplanation:The binary representation of 5 is: 101", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:false\nExplanation:The binary representation of 7 is: 111.", + "image": null + }, + { + "text": "Example 3: Input:n = 11\nOutput:false\nExplanation:The binary representation of 11 is: 1011.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n bin_n = bin(n)[2:]\n for i in range(len(bin_n)-1):\n if bin_n[i] == '0' and bin_n[i+1] == '0':\n return False\n \n if bin_n[i] == '1' and bin_n[i+1] == '1':\n return False\n \n return True\n\n", + "title": "693. Binary Number with Alternating Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9\nOutput:4\nExplanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2\nOutput:-1\nExplanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int l = 0;\n int r = nums.length - 1;\n return binarySearch(nums, l, r, target);\n }\n \n private int binarySearch(int[] nums, int l, int r, int target) {\n if (l <= r) {\n int mid = (r + l) / 2;\n \n if (nums[mid] == target) {\n return mid;\n } \n \n if (nums[mid] < target) {\n return binarySearch(nums, mid + 1, r, target);\n } else {\n return binarySearch(nums, l, mid - 1, target);\n }\n } \n return -1;\n }\n}\n", + "title": "704. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9\nOutput:4\nExplanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2\nOutput:-1\nExplanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 214 ms (Top 71.5%) | Memory: 17.81 MB (Top 65.3%)\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums)-1\n \n while left<=right:\n mid = (left+right)//2\n if nums[mid]==target:\n return mid\n elif nums[mid]>target:\n right = mid-1\n else:\n left = mid+1\n \n return -1", + "title": "704. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "class BSTIterator {\n\n TreeNode root;\n TreeNode current;\n Stack st = new Stack<>();\n public BSTIterator(TreeNode root) {\n this.root = root;\n //init(root);\n current = findLeft(root);\n //System.out.println(\"Init: stack is: \"+st);\n }\n\n public int next() {\n \n int val = -1;\n if(current != null)\n val = current.val;\n else\n return -1;\n \n if(current.right != null)\n current = findLeft(current.right);\n else if(!st.isEmpty())\n current = st.pop();\n else \n current = null;\n // System.out.println(\"next: stack is: \"+st);\n return val;\n }\n \n public TreeNode findLeft(TreeNode node) {\n \n if(node == null)\n return null;\n \n if(node.left != null){\n TreeNode next = node.left;\n st.push(node);\n return findLeft(next);\n }\n else\n return node;\n \n }\n \n public boolean hasNext() {\n return current != null;\n }\n}\n", + "title": "173. Binary Search Tree Iterator", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass BSTIterator:\n\n def __init__(self, root: Optional[TreeNode]):\n self.root=root\n self.tree=[]#list to store the inorder traversal\n def inorder(node):\n if not node:\n return\n inorder(node.left)\n self.tree.append(node.val)\n inorder(node.right)\n return\n inorder(self.root)\n self.i=0\n \n\n def next(self) -> int:\n self.i+=1\n return self.tree[self.i-1]\n\n def hasNext(self) -> bool:\n return self.i-1 bool:\n ans = set()\n for i in range(len(S)):\n for ii in range(i, i + N.bit_length()): \n x = int(S[i:ii+1], 2)\n if 1 <= x <= N: ans.add(x)\n return len(ans) == N\n", + "title": "1016. Binary String With Substrings Representing 1 To N", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer goal , return the number of non-empty subarrays with a sum goal . A subarray is a contiguous part of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "nums[i] is either 0 or 1 .", + "0 <= goal <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,1,0,1], goal = 2\nOutput:4\nExplanation:The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,0,0], goal = 0\nOutput:15", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int numSubarraysWithSum(int[] nums, int goal) {\n \n int pre=0,cnt=0;\n HashMap m=new HashMap();\n for(int i:nums){\n \n pre+=i;\n // if(pre-goal<0)continue;\n if(pre-goal==0)cnt++;\n \n if(m.containsKey(pre-goal)){\n cnt+=m.get(pre-goal);\n \n \n }\n m.put(pre,m.getOrDefault(pre,0)+1);\n\n \n \n }\n \n return cnt;\n}\n", + "title": "930. Binary Subarrays With Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary array nums and an integer goal , return the number of non-empty subarrays with a sum goal . A subarray is a contiguous part of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "nums[i] is either 0 or 1 .", + "0 <= goal <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,1,0,1], goal = 2\nOutput:4\nExplanation:The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,0,0], goal = 0\nOutput:15", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 680 ms (Top 7.52%) | Memory: 17.5 MB (Top 60.81%)\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n my_dict = {0:1}\n accum, res = 0, 0\n for n in nums:\n accum += n\n diff = accum-goal\n if diff in my_dict:\n res += my_dict[diff]\n if accum in my_dict:\n my_dict[accum] +=1\n else:\n my_dict[accum] =1\n return res", + "title": "930. Binary Subarrays With Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "Node.val == 0" + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,0,null,0,0]\nOutput:1\nExplanation:One camera is enough to monitor all nodes if placed as shown.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" + }, + { + "text": "Example 2: Input:root = [0,0,null,0,null,0,null,null,0]\nOutput:2\nExplanation:At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n private int count = 0;\n public int minCameraCover(TreeNode root) {\n if(helper(root) == -1)\n count++;\n return count;\n }\n \n //post order\n //0 - have camera\n //1 - covered\n //-1 - not covered\n public int helper(TreeNode root) {\n if(root == null)\n return 1;\n int left = helper(root.left);\n int right = helper(root.right);\n if(left == -1 || right == -1) {\n count++;\n return 0;\n }\n if(left == 0 || right == 0)\n return 1;\n \n return -1;\n }\n}\n", + "title": "968. Binary Tree Cameras", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "Node.val == 0" + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,0,null,0,0]\nOutput:1\nExplanation:One camera is enough to monitor all nodes if placed as shown.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" + }, + { + "text": "Example 2: Input:root = [0,0,null,0,null,0,null,null,0]\nOutput:2\nExplanation:At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" + } + ], + "follow_up": null, + "solution": "\nimport itertools\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minCameraHelper(self, root: Optional[TreeNode]) -> (int, int):\n # Return 3 things:\n # cam, uncam, uncov\n # cam(era) is best score for valid tree with camera at root\n # uncam(era) is best score for valid tree without camera at root\n # uncov(ered) is best score for invalid tree, where the only invalidity (i.e. the only uncovered node) is the root node\n \n # Note: maxint (float(\"inf\")) is used to signify situations that don't make sense or can't happen.\n # Anywhere there is a float(\"inf\"), you can safely replace that with a 1 as 1 is as bad or worse than worst practical,\n # but I stick with maxint to highlight the nonsensical cases for the reader!\n \n if not root.left and not root.right:\n # base case: leaf\n # Note: \"Uncam\" setting doesn't make much sense (a leaf with no parents can either have a camera or be uncovered,\n # but not covered with no camera)\n return 1, float(\"inf\"), 0\n \n if root.left:\n left_cam, left_uncam, left_uncov = self.minCameraHelper(root.left)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n left_cam, left_uncam, left_uncov = float(\"inf\"), 0, 0\n \n if root.right:\n right_cam, right_uncam, right_uncov = self.minCameraHelper(root.right)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n right_cam, right_uncam, right_uncov = float(\"inf\"), 0, 0\n \n # Get the possible combinations for each setting \n cam_poss = itertools.product([left_cam, left_uncam, left_uncov], [right_cam, right_uncam, right_uncov])\n uncam_poss = [(left_cam, right_cam), (left_uncam, right_cam), (left_cam, right_uncam)]\n uncov_poss = [(left_uncam, right_uncam)]\n \n # Compute costs for each setting\n cam = min([x + y for x, y in cam_poss]) + 1\n uncam = min([x + y for x, y in uncam_poss])\n uncov = min([x + y for x, y in uncov_poss])\n \n return cam, uncam, uncov\n \n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n cam, uncam, _ = self.minCameraHelper(root)\n return min(cam, uncam)\n\n", + "title": "968. Binary Tree Cameras", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n . Initially, the first player names a value x with 1 <= x <= n , and the second player names a value y with 1 <= y <= n and y != x . The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true . If it is not possible, return false .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= x <= n <= 100", + "n is odd.", + "1 <= Node.val <= n", + "All the values of the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput:true\nExplanation:The second player can choose the node with value 2.", + "image": "https://assets.leetcode.com/uploads/2019/08/01/1480-binary-tree-coloring-game.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], n = 3, x = 1\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass Solution {\n\tint xkaLeft=0,xkaRight=0;\n\tpublic int size(TreeNode node, int x)\n\t{\n\t\tif(node==null)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tint ls=size(node.left,x);\n\t\tint rs=size(node.right,x);\n\n\t\tif(node.val==x)\n\t\t{\n\t\t\txkaLeft=ls;\n\t\t\txkaRight=rs;\n\t\t}\n\n\t\treturn ls+rs+1;\n\t}\n\tpublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n\n\t\tsize(root,x);\n\t\tint parent=n-(xkaLeft+xkaRight+1);\n\t\tint max=Math.max(parent,Math.max(xkaRight,xkaLeft));\n\t\tif(max>n/2)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}", + "title": "1145. Binary Tree Coloring Game", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n . Initially, the first player names a value x with 1 <= x <= n , and the second player names a value y with 1 <= y <= n and y != x . The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true . If it is not possible, return false .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= x <= n <= 100", + "n is odd.", + "1 <= Node.val <= n", + "All the values of the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput:true\nExplanation:The second player can choose the node with value 2.", + "image": "https://assets.leetcode.com/uploads/2019/08/01/1480-binary-tree-coloring-game.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], n = 3, x = 1\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findParent(self,node,par = None):\n if node:\n self.parent[node.val] = par\n self.findParent(node.left,node)\n self.findParent(node.right,node)\n \n def traverse(self,node,done):\n if node:\n if node in done: return 0\n done[node] = True\n a = self.traverse(self.parent[node.val],done)\n b = self.traverse(node.left,done)\n c = self.traverse(node.right,done)\n return a + b + c + 1\n return 0\n \n def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n self.parent = {}\n self.findParent(root)\n parent = self.parent[x]\n node = root if root.val == x else parent.left if parent and parent.left and parent.left.val == x else parent.right\n up = self.traverse(parent,{node:True})\n left = self.traverse(node.left,{node:True})\n right = self.traverse(node.right,{node:True})\n return (up > left + right) or (left > up + right) or (right > up + left)\n", + "title": "1145. Binary Tree Coloring Game", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[1,3,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.83 MB (Top 42.1%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List li = new LinkedList();\n public List inorderTraversal(TreeNode root) {\n if(root == null){\n List li = new LinkedList();\n return li ;\n }\n inorderTraversal(root.left); \n li.add(root.val); \n inorderTraversal(root.right);\n return li;\n\n }\n \n}", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[1,3,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tinorder = []\n\t\tstack = []\n\n\t\twhile stack or root is not None:\n\t\t\tif root:\n\t\t\t\tstack.append(root)\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\tnode = stack.pop()\n\t\t\t\tinorder.append(node.val)\n\t\t\t\troot = node.right\n\n\t\treturn inorder\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.inorder_generator(root))\n\n\t@classmethod\n\tdef inorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.inorder_generator(tree.left)\n\t\t\tyield tree.val\n\t\t\tyield from cls.inorder_generator(tree.right)\n", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 39.54%) | Memory: 43.4 MB (Top 69.45%)\nclass Solution {\n public List> levelOrder(TreeNode root) {\n List> result = new ArrayList<>();\n if(root == null)\n return result;\n List rootList = new ArrayList<>();\n rootList.add(root.val);\n result.add(rootList);\n levelOrder(root,1,result);\n return result;\n\n }\n\n private void levelOrder(TreeNode root, int level, List> result) {\n if(root == null)\n return;\n List children = exploreChildren(root);\n if(!children.isEmpty()){\n if(level < result.size())\n result.get(level).addAll(children);\n else\n result.add(children);\n }\n levelOrder(root.left, level + 1, result);\n levelOrder(root.right, level + 1,result);\n }\n\n private List exploreChildren(TreeNode root) {\n List children = new ArrayList<>();\n if(root.left != null)\n children.add(root.left.val);\n if(root.right != null)\n children.add(root.right.val);\n return children;\n }\n}\n", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n \n \n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n \n ret = []\n next_levels = [[root]]\n \n for level in next_levels:\n curr_lv = []\n next_lv = []\n for node in level:\n if not node: \n continue\n curr_lv.append(node.val)\n next_lv.append(node.left)\n next_lv.append(node.right)\n \n if curr_lv: \n ret.append(curr_lv)\n if next_lv: \n next_levels.append(next_lv)\n \n return ret\n", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values . (i.e., from left to right, level by level from leaf to root).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[15,7],[9,20],[3]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> levelOrderBottom(TreeNode root) {\n Queue al=new LinkedList<>();\n List> fal=new LinkedList<>();\n if(root==null) return fal;\n al.offer(root);\n while(!al.isEmpty()){\n List aal=new LinkedList<>();\n int num=al.size();\n for(int i=0;i List[List[int]]:\n def dfs(node, level, result):\n if not node:\n return\n if level >= len(result):\n result.append([])\n result[level].append(node.val)\n dfs(node.left, level+1, result)\n dfs(node.right, level+1, result)\n result = []\n dfs(root, 0, result)\n return result[::-1]", + "title": "107. Binary Tree Level Order Traversal II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:6\nExplanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]\nOutput:42\nExplanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.74%) | Memory: 48.6 MB (Top 11.74%)\nclass Solution {\n\n int[] ans = new int[1];\n public int maxPathSum(TreeNode root) {\n ans[0]=root.val; //Handle edge case\n dfs(root);\n return ans[0];\n }\n\n public int dfs(TreeNode root){\n\n if(root==null)\n return 0;\n\n int left=Math.max(0,dfs(root.left)); //Check on the left subtree and if returned negative take 0\n int right=Math.max(0,dfs(root.right)); //Check on the right subtree and if returned negative take 0\n\n int maxInTheNode=root.val+left+right; //Calculating the max while including the root its left and right child.\n ans[0]=Math.max(ans[0],maxInTheNode); //Keeping max globally\n\n return root.val+Math.max(left,right); //Since only one split is allowed returning the one split that returns max value\n }\n}", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:6\nExplanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]\nOutput:42\nExplanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n self.res=root.val\n def solving(root):\n if not root:\n return 0\n current=root.val\n sleft,sright=float('-inf'),float('-inf')\n if root.left:\n sleft=solving(root.left)\n if(sleft>=0):\n current+=sleft\n if root.right:\n sright=solving(root.right)\n if(sright>=0):\n current+=sright\n if(current>self.res):\n self.res=current\n return max(root.val, root.val+sleft, root.val+sright)\n solving(root)\n return self.res\n", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5]\nOutput:[\"1->2->5\",\"1->3\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[\"1\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.96%) | Memory: 42.40 MB (Top 35.43%)\n\nclass Solution {\n public List binaryTreePaths(TreeNode root) {\n List result = new ArrayList<>();\n dfs(root, new StringBuilder(), result);\n return result;\n }\n\n private void dfs(TreeNode node, StringBuilder path, List result) {\n if (node == null) return;\n int len = path.length();\n if (len > 0) {\n path.append(\"->\");\n }\n path.append(node.val);\n if (node.left == null && node.right == null) {\n result.add(path.toString());\n } else {\n dfs(node.left, path, result);\n dfs(node.right, path, result);\n }\n path.setLength(len); // Backtrack by resetting the StringBuilder\n }\n}\n", + "title": "257. Binary Tree Paths", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5]\nOutput:[\"1->2->5\",\"1->3\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[\"1\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n \n # DFS solution\n output = []\n stack = [(root, '')]\n \n while stack:\n node, path = stack.pop()\n path += str(node.val)\n \n if not node.left and not node.right:\n output.append(path)\n \n path += '->'\n if node.left:\n stack.append((node.left, path))\n if node.right:\n stack.append((node.right, path))\n \n return output\n", + "title": "257. Binary Tree Paths", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[3,2,1]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.3 MB (Top 40.74%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List res = new ArrayList<>();\n public List postorderTraversal(TreeNode root) {\n traversal(root);\n return res;\n }\n\n public void traversal(TreeNode root){\n if(root == null)\n return;\n traversal(root.left);\n traversal(root.right);\n res.add(root.val);\n }\n}", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[3,2,1]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tif root is None:\n\t\t\treturn []\n\n\t\tpostorder = []\n\t\tstack = [root]\n\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tpostorder.append(node.val)\n\t\t\tif node.left is not None:\n\t\t\t\tstack.append(node.left)\n\t\t\tif node.right is not None:\n\t\t\t\tstack.append(node.right)\n\n\t\treturn postorder[::-1]\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.postorder_generator(root))\n\n\t@classmethod\n\tdef postorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.postorder_generator(tree.left)\n\t\t\tyield from cls.postorder_generator(tree.right)\n\t\t\tyield tree.val", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List preorderTraversal(TreeNode root) {\n List result = new ArrayList<>();\n preorderTraversal2(root, result);\n return result;\n }\n\n\n public List preorderTraversal2(TreeNode root,List result) {\n if(root!=null){\n result.add(root.val);\n if(root.left!=null){\n preorderTraversal2(root.left,result);\n }\n if(root.right!=null){\n preorderTraversal2(root.right,result);\n }\n }\n return result;\n }\n}\n", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]\nOutput:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 23.56%) | Memory: 13.9 MB (Top 60.28%)\nfrom collections import deque\nfrom typing import List, Optional\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n\n queue = deque([root])\n preorder = []\n\n while queue:\n node = queue.pop()\n preorder.append(node.val)\n\n if node.right is not None:\n queue.append(node.right)\n if node.left is not None:\n queue.append(node.left)\n\n return preorder\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n return list(self.preorder_generator(root))\n\n @classmethod\n def preorder_generator(cls, tree: Optional[TreeNode]):\n if tree is not None:\n yield tree.val\n yield from cls.preorder_generator(tree.left)\n yield from cls.preorder_generator(tree.right)", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed . A subtree of a node node is node plus every node that is a descendant of node .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 200] .", + "Node.val is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,0,0,1]\nOutput:[1,null,0,null,1]\nExplanation:Only the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" + }, + { + "text": "Example 2: Input:root = [1,0,1,0,0,0,1]\nOutput:[1,null,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" + }, + { + "text": "Example 3: Input:root = [1,1,0,1,1,0,1,0]\nOutput:[1,1,0,1,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.81 MB (Top 82.6%)\n\nclass Solution {\n public TreeNode pruneTree(TreeNode root) {\n \n if(root == null) return root;\n \n root.left = pruneTree(root.left);\n root.right = pruneTree(root.right);\n \n if(root.left == null && root.right == null && root.val == 0) return null;\n else return root;\n }\n}", + "title": "814. Binary Tree Pruning", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed . A subtree of a node node is node plus every node that is a descendant of node .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 200] .", + "Node.val is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,0,0,1]\nOutput:[1,null,0,null,1]\nExplanation:Only the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" + }, + { + "text": "Example 2: Input:root = [1,0,1,0,0,0,1]\nOutput:[1,null,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" + }, + { + "text": "Example 3: Input:root = [1,1,0,1,1,0,1,0]\nOutput:[1,1,0,1,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 80.71%) | Memory: 17.30 MB (Top 5.56%)\n\nclass Solution:\n def pruneTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if not root: return root\n root.left, root.right = self.pruneTree(root.left), self.pruneTree(root.right)\n return None if not root.val and not root.left and not root.right else root\n", + "title": "814. Binary Tree Pruning", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5,null,4]\nOutput:[1,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,3]\nOutput:[1,3]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Utility Function of RightSideView\n public void rightView(TreeNode curr, List list, int level) {\n // if, current is null, return\n if(curr == null) {\n return;\n }\n \n // if, level = list size\n // add current val to list\n if(level == list.size()) {\n list.add(curr.val);\n }\n \n // recursive call for right side view\n rightView(curr.right, list, level + 1);\n // recursive call for left side view\n rightView(curr.left, list, level + 1);\n }\n \n // Binary Tree Right Side View Function\n public List rightSideView(TreeNode root) {\n // create a list\n List result = new ArrayList<>();\n // call right view function\n rightView(root, result, 0);\n return result;\n }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(h) h = height of binary tree\n*/\n", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5,null,4]\nOutput:[1,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,3]\nOutput:[1,3]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 45.43%) | Memory: 13.9 MB (Top 70.59%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n\n def dfs(root, d):\n\n if not root: return\n\n if self.maxi < d:\n self.res.append(root.val)\n self.maxi = d\n\n dfs(root.right, d+1)\n dfs(root.left, d+1)\n\n self.res, self.maxi = [], 0\n dfs(root, 1)\n return self.res\n\n # An Upvote will be encouraging\n", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt . The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values . If a node does not have a left child, then the sum of the left subtree node values is treated as 0 . The rule is similar if the node does not have a right child.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:1\nExplanation:Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,9,3,5,null,7]\nOutput:15\nExplanation:Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg" + }, + { + "text": "Example 3: Input:root = [21,7,14,1,1,2,2,3,3]\nOutput:9", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 45.7 MB (Top 24.54%)\nclass Solution {\n int max = 0;\n public int findTilt(TreeNode root) {\n loop(root);\n return max;\n }\n public int loop(TreeNode root){\n if(root==null) return 0;\n int left = loop(root.left);\n int right = loop(root.right);\n max+= Math.abs(left-right);\n return root.val+left+right;\n }\n}", + "title": "563. Binary Tree Tilt", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt . The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values . If a node does not have a left child, then the sum of the left subtree node values is treated as 0 . The rule is similar if the node does not have a right child.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:1\nExplanation:Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,9,3,5,null,7]\nOutput:15\nExplanation:Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg" + }, + { + "text": "Example 3: Input:root = [21,7,14,1,1,2,2,3,3]\nOutput:9", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 66 ms (Top 84.95%) | Memory: 16.4 MB (Top 43.30%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findTilt(self, root: Optional[TreeNode]) -> int:\n res = [0]\n def tilt_helper(root,res):\n if not root:\n return 0\n\n left = tilt_helper(root.left,res)\n right = tilt_helper(root.right,res)\n\n res[0] += abs(left-right)\n\n return left + right + root.val\n\n tilt_helper(root,res)\n return res[0]", + "title": "563. Binary Tree Tilt", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values . (i.e., from left to right, then right to left for the next level and alternate between).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[3],[20,9],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> zigzagLevelOrder(TreeNode root) {\n Queue q=new LinkedList();\n List> res=new ArrayList<>();\n if(root==null){\n return res;\n }\n q.offer(root);\n boolean flag=true;\n while(!q.isEmpty()){\n int size=q.size();\n List curr=new ArrayList<>();\n for(int i=0;i dp;\n HashSet set;\n \n public int numFactoredBinaryTrees(int[] arr) {\n long ans = 0;\n dp = new HashMap<>();\n set = new HashSet<>();\n \n for(int val : arr) set.add(val);\n \n for(int val : arr) {\n\t\t\t//giving each unique value a chance to be root node of the tree\n ans += solve(val, arr);\n ans %= mod;\n }\n \n return (int)ans;\n }\n \n public long solve(int val, int[] nums) {\n \n if(dp.containsKey(val)) {\n return dp.get(val);\n }\n \n long ans = 1;\n \n for(int i = 0; i < nums.length; i++) {\n if(val % nums[i] == 0 && set.contains(val / nums[i])) {\n long left = solve(nums[i], nums);\n long right = solve(val / nums[i], nums);\n \n ans += ((left * right) % mod);\n ans %= mod;\n }\n }\n \n dp.put(val, ans);\n \n return ans;\n }\n}\n", + "title": "823. Binary Trees With Factors", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of unique integers, arr , where each integer arr[i] is strictly greater than 1 . We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make . The answer may be too large so return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "2 <= arr[i] <= 10^9", + "All the values of arr are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,4]\nOutput:3\nExplanation:We can make these trees:[2], [4], [4, 2, 2]", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,4,5,10]\nOutput:7\nExplanation:We can make these trees:[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numFactoredBinaryTrees(self, nums: List[int]) -> int:\n nums = set(nums)\n n = len(nums)\n \n @lru_cache(None)\n def helper(num):\n trees = 1\n for factor in nums:\n if not num % factor and num // factor in nums:\n trees += helper(factor) * helper(num // factor)\n\n return trees\n \n return sum(helper(num) for num in nums) % (10 ** 9 + 7)", + "title": "823. Binary Trees With Factors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent . You may return the answer in any order . The hour must not contain a leading zero. The minute must be consist of two digits and may contain a leading zero.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg" + ], + "constraints": [ + "For example, the below binary watch reads \"4:51\" ." + ], + "examples": [ + { + "text": "Example 1: Input:turnedOn = 1\nOutput:[\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]", + "image": null + }, + { + "text": "Example 2: Input:turnedOn = 9\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 44 ms (Top 50.1%) | Memory: 16.36 MB (Top 42.0%)\n\nclass Solution:\n def readBinaryWatch(self, turnedOn: int) -> List[str]:\n output = []\n # Loop through all possible combinations of hours and minutes and count the number of set bits\n for h in range(12):\n for m in range(60):\n if bin(h).count('1') + bin(m).count('1') == turnedOn: # Check if the number of set bits in hours and minutes equals the target number\n output.append(f\"{h}:{m:02d}\") # Add the valid combination of hours and minutes to the output list\n return output\n", + "title": "401. Binary Watch", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive .", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int rangeBitwiseAnd(int left, int right) {\n int count=0;\n while(left!=right){\n left>>=1;\n right>>=1;\n count++;\n }\n return right<<=count;\n}\n", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive .", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 17.27%) | Memory: 13.9 MB (Top 25.09%)\nclass Solution:\n def rangeBitwiseAnd(self, left: int, right: int) -> int:\n if not left: return 0\n i = 0\n cur = left\n while cur + (cur & -cur) <= right:\n cur += cur & -cur\n left &= cur\n return left", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j ), we take the bitwise OR of all the elements in sub , obtaining a result arr[i] | arr[i + 1] | ... | arr[j] . Return the number of possible results. Results that occur more than once are only counted once in the final answer", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0]\nOutput:1\nExplanation:There is only one possible result: 0.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2]\nOutput:3\nExplanation:The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4]\nOutput:6\nExplanation:The possible results are 1, 2, 3, 4, 6, and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 454 ms (Top 75.74%) | Memory: 71.3 MB (Top 97.04%)\nclass Solution {\n public int subarrayBitwiseORs(int[] arr) {\n int n = arr.length;\n Set s = new HashSet();\n LinkedList queue = new LinkedList();\n for(int i = 0; i< n; i++){\n int size = queue.size();\n if(!queue.contains(arr[i])){\n queue.offer(arr[i]);\n s.add(arr[i]);\n }\n int j = 0;\n while(j int:\n \n \n ans=set(arr)\n \n # each element is a subarry\n \n \n one = set()\n \n # to get the ans for the subarray of size >1\n # starting from 0th element to the ending element\n \n \n one.add(arr[0])\n \n for i in range(1,len(arr)):\n \n two=set()\n \n for j in one:\n \n two.add(j | arr[i])\n \n # subarray from the element in one set to the current ele(i th one)\n \n ans.add(j| arr[i])\n \n \n two.add(arr[i])\n \n # adding curr element to set two so that from next iteration we can take sub array starting from curr element \n \n one = two\n \n return len(ans)\n \n", + "title": "898. Bitwise ORs of Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array people where people[i] is the weight of the i th person, and an infinite number of boats where each boat can carry a maximum weight of limit . Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit . Return the minimum number of boats to carry every given person .", + "description_images": [], + "constraints": [ + "1 <= people.length <= 5 * 10^4", + "1 <= people[i] <= limit <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:people = [1,2], limit = 3\nOutput:1\nExplanation:1 boat (1, 2)", + "image": null + }, + { + "text": "Example 2: Input:people = [3,2,2,1], limit = 3\nOutput:3\nExplanation:3 boats (1, 2), (2) and (3)", + "image": null + }, + { + "text": "Example 3: Input:people = [3,5,3,4], limit = 5\nOutput:4\nExplanation:4 boats (3), (3), (4), (5)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 38.47%) | Memory: 65.6 MB (Top 33.01%)\nclass Solution {\n public int numRescueBoats(int[] people, int limit) {\n int boatCount = 0;\n Arrays.sort(people);\n\n int left = 0;\n int right = people.length - 1;\n\n while(left <= right){\n int sum = people[left] + people[right];\n if(sum <= limit){\n boatCount++;\n left++;\n right--;\n }\n else{\n boatCount++;\n right--;\n }\n }\n return boatCount;\n }\n}", + "title": "881. Boats to Save People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array people where people[i] is the weight of the i th person, and an infinite number of boats where each boat can carry a maximum weight of limit . Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit . Return the minimum number of boats to carry every given person .", + "description_images": [], + "constraints": [ + "1 <= people.length <= 5 * 10^4", + "1 <= people[i] <= limit <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:people = [1,2], limit = 3\nOutput:1\nExplanation:1 boat (1, 2)", + "image": null + }, + { + "text": "Example 2: Input:people = [3,2,2,1], limit = 3\nOutput:3\nExplanation:3 boats (1, 2), (2) and (3)", + "image": null + }, + { + "text": "Example 3: Input:people = [3,5,3,4], limit = 5\nOutput:4\nExplanation:4 boats (3), (3), (4), (5)", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people)-1\n boats = 0\n while lo <= hi:\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n else:\n hi -= 1\n boats += 1\n return boats\n", + "title": "881. Boats to Save People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A concert hall has n rows numbered from 0 to n - 1 , each with m seats, numbered from 0 to m - 1 . You need to design a ticketing system that can allocate seats in the following cases: Note that the spectators are very picky. Hence: Implement the BookMyShow class:", + "description_images": [], + "constraints": [ + "If a group of k spectators can sit together in a row.", + "If every member of a group of k spectators can get a seat. They may or may not sit together." + ], + "examples": [ + { + "text": "Example 1: Input[\"BookMyShow\", \"gather\", \"gather\", \"scatter\", \"scatter\"]\n[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]Output[null, [0, 0], [], true, false]ExplanationBookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \nbms.gather(4, 0); // return [0, 0]\n // The group books seats [0, 3] of row 0. \nbms.gather(2, 0); // return []\n // There is only 1 seat left in row 0,\n // so it is not possible to book 2 consecutive seats. \nbms.scatter(5, 1); // return True\n // The group books seat 4 of row 0 and seats [0, 3] of row 1. \nbms.scatter(5, 1); // return False\n // There is only one seat left in the hall.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 221 ms (Top 91.46%) | Memory: 140.4 MB (Top 35.37%)\nclass BookMyShow {\n /**\n Segment tree class to store sum of a range and maximum available seats in a row\n **/\n static class SegTree{\n long sum[]; // store sum of seats in a range\n long segTree[]; // store maximum seats in a range\n int m, n;\n public SegTree(int n, int m) {\n this.m = m;\n this.n = n;\n segTree = new long[4*n];\n sum = new long[4*n];\n build(0, 0, n-1, m);\n }\n\n private void build(int index, int lo, int hi, long val){\n if(lo == hi){\n segTree[index] = val; // initialize segement tree with initial seat capacity\n sum[index] = val; // initialize \"sum\" with initial seat capacity of a row\n return;\n }\n int mid = (lo + hi)/2;\n build(2*index +1, lo, mid, val); // build left sub tree\n build(2*index +2, mid+1, hi, val); // build right sub tree\n segTree[index] = Math.max(segTree[2*index + 1], segTree[2*index + 2]); // maximum seats in a row for subtrees\n sum[index] = sum[2*index + 1] + sum[2*index + 2]; // sum of seats in a range\n }\n\n private void update(int index, int lo, int hi, int pos, int val){\n /**\n Method to update segment tree based on the available seats in a row\n **/\n if(lo == hi){\n segTree[index] = val;\n sum[index] = val;\n return;\n }\n int mid = (lo + hi) / 2;\n if (pos <= mid) { // position to update is in left\n update(2 * index + 1, lo, mid, pos, val);\n } else { // position to update is in right\n update(2 * index + 2, mid+1, hi, pos, val);\n }\n // update segment tree and \"sum\" based on the update in \"pos\" index\n segTree[index] = Math.max(segTree[2*index + 1] , segTree[2*index + 2]);\n sum[index] = sum[2*index + 1] + sum[2*index + 2];\n }\n\n public void update(int pos, int val){\n update(0, 0, n - 1 , pos, val);\n }\n\n public int gatherQuery(int k, int maxRow){\n return gatherQuery(0, 0, n - 1 , k, maxRow);\n }\n\n private int gatherQuery(int index, int lo, int hi, int k, int maxRow){\n /**\n Method to check if seats are available in a single row\n **/\n if(segTree[index] < k || lo > maxRow)\n return -1;\n if(lo == hi) return lo;\n int mid = (lo + hi) / 2;\n int c = gatherQuery(2*index + 1, lo, mid, k, maxRow);\n if(c == -1){\n c = gatherQuery(2*index + 2, mid +1, hi, k, maxRow);\n }\n return c;\n }\n\n public long sumQuery(int k, int maxRow){\n return sumQuery(0, 0, n-1, k, maxRow);\n }\n\n private long sumQuery(int index, int lo, int hi, int l, int r){\n if(lo > r || hi < l ) return 0; // not in range\n if(lo >= l && hi <= r) return sum[index]; // in range\n int mid = (lo + hi)/2;\n return sumQuery(2*index+1, lo, mid, l, r) + sumQuery(2*index+2, mid+1, hi, l, r);\n }\n }\n\n SegTree segTree;\n int[] rowSeats; // stores avaiable seats in a row, helps to find the vacant seat in a row\n\n public BookMyShow(int n, int m) {\n segTree = new SegTree(n, m);\n rowSeats = new int[n];\n Arrays.fill(rowSeats, m); // initialize vacant seats count to \"m\" for all the rows\n }\n\n public int[] gather(int k, int maxRow) {\n int row = segTree.gatherQuery(k, maxRow); // find row which has k seats\n if(row == -1) return new int[]{}; // can't find a row with k seats\n int col = segTree.m - rowSeats[row]; // find column in the row which has k seats\n rowSeats[row] -= k; // reduce the seats\n segTree.update(row, rowSeats[row]); // update the segment tree\n return new int[]{row, col};\n\n }\n\n public boolean scatter(int k, int maxRow) {\n long sum = segTree.sumQuery(0, maxRow); // find the sum for the given range [0, maxRow]\n if(sum < k) return false; // can't find k seats in [0, maxRow]\n\n for(int i=0; i<=maxRow && k !=0 ; i++){\n if(rowSeats[i] > 0){ // if current row has seats then allocate those seats\n long t = Math.min(rowSeats[i], k);\n rowSeats[i] -= t;\n k -= t;\n segTree.update(i,rowSeats[i]); // update the segment tree\n }\n }\n return true;\n }\n}", + "title": "2286. Booking Concert Tickets in Groups", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A concert hall has n rows numbered from 0 to n - 1 , each with m seats, numbered from 0 to m - 1 . You need to design a ticketing system that can allocate seats in the following cases: Note that the spectators are very picky. Hence: Implement the BookMyShow class:", + "description_images": [], + "constraints": [ + "If a group of k spectators can sit together in a row.", + "If every member of a group of k spectators can get a seat. They may or may not sit together." + ], + "examples": [ + { + "text": "Example 1: Input[\"BookMyShow\", \"gather\", \"gather\", \"scatter\", \"scatter\"]\n[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]Output[null, [0, 0], [], true, false]ExplanationBookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \nbms.gather(4, 0); // return [0, 0]\n // The group books seats [0, 3] of row 0. \nbms.gather(2, 0); // return []\n // There is only 1 seat left in row 0,\n // so it is not possible to book 2 consecutive seats. \nbms.scatter(5, 1); // return True\n // The group books seat 4 of row 0 and seats [0, 3] of row 1. \nbms.scatter(5, 1); // return False\n // There is only one seat left in the hall.", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self, start, end):\n self.s = start\n self.e = end\n self.left = None\n self.right = None\n self.total = 0 # for range sum query\n self.mx = 0 # for range max query\n \nclass SegTree:\n def __init__(self, start, end, val):\n \n def build(l, r):\n if l > r:\n return None\n if l == r:\n node = Node(l, r)\n node.total = val\n node.mx = val\n return node\n node = Node(l, r)\n m = (l + r) // 2\n node.left = build(l, m)\n node.right = build(m+1, r)\n node.mx = max(node.left.mx, node.right.mx)\n node.total = node.left.total + node.right.total\n return node\n \n self.root = build(start, end)\n \n\t# update the total remain seats and the max remain seats for each node (range) in the segment tree\n def update(self, index, val):\n \n def updateHelper(node):\n if node.s == node.e == index:\n node.total -= val\n node.mx -= val\n return\n m = (node.s + node.e) // 2\n if index <= m:\n updateHelper(node.left)\n elif index > m:\n updateHelper(node.right)\n node.mx = max(node.left.mx, node.right.mx)\n node.total = node.left.total + node.right.total\n return\n \n updateHelper(self.root)\n \n def maxQuery(self, k, maxRow, seats):\n \n def queryHelper(node):\n if node.s == node.e:\n\t\t\t\t# check if the row number is less than maxRow and the number of remains seats is greater or equal than k\n if node.e > maxRow or node.total < k:\n return []\n if node.e <= maxRow and node.total >= k:\n return [node.e, seats - node.total]\n\t\t\t# we want to greedily search the left subtree to get the smallest row which has enough remain seats\n if node.left.mx >= k:\n return queryHelper(node.left)\n return queryHelper(node.right)\n \n return queryHelper(self.root)\n \n def sumQuery(self, endRow):\n \n def queryHelper(node, left, right):\n if left <= node.s and node.e <= right:\n return node.total\n m = (node.s + node.e) // 2\n if right <= m:\n return queryHelper(node.left, left, right)\n elif left > m:\n return queryHelper(node.right, left, right)\n return queryHelper(node.left, left, m) + queryHelper(node.right, m+1, right)\n \n return queryHelper(self.root, 0, endRow)\n \nclass BookMyShow:\n\n def __init__(self, n: int, m: int):\n self.m = m\n self.seg = SegTree(0, n-1, m)\n\t\t# record the remain seats at each row\n self.seats = [m] * n\n\t\t# record the index of the smallest row that has remain seats > 0\n self.startRow = 0\n \n def gather(self, k: int, maxRow: int) -> List[int]:\n res = self.seg.maxQuery(k, maxRow, self.m)\n if res:\n row = res[0]\n self.seg.update(row, k)\n self.seats[row] -= k\n return res\n\n def scatter(self, k: int, maxRow: int) -> bool:\n if self.seg.sumQuery(maxRow) < k:\n return False\n else:\n i = self.startRow\n total = 0\n while total < k:\n prevTotal = total\n total += self.seats[i]\n if total < k:\n\t\t\t\t\t# use up all the seats at ith row\n self.seg.update(i, self.seats[i])\n self.seats[i] = 0\n i += 1\n self.startRow = i\n elif total >= k:\n\t\t\t\t\t# occupy (k - prevTotal) seats at ith row\n self.seg.update(i, k - prevTotal)\n self.seats[i] -= k - prevTotal\n return True\n", + "title": "2286. Booking Concert Tickets in Groups", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Formally, the three rules for our grammar: Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents .", + "description_images": [], + "constraints": [ + "Single letters represent a singleton set containing that word. R(\"a\") = {\"a\"} R(\"w\") = {\"w\"}", + "R(\"a\") = {\"a\"}", + "R(\"w\") = {\"w\"}", + "When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"} R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}", + "R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"} R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}", + "R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}", + "R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}" + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"{a,b}{c,{d,e}}\"\nOutput:[\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"{{a,z},a{b,c},{ab,z}}\"\nOutput:[\"a\",\"ab\",\"ac\",\"z\"]\nExplanation:Each distinct word is written only once in the final answer.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 41.79%) | Memory: 50.4 MB (Top 43.28%)\nclass Solution {\n // To Get the value of index traversed in a recursive call.\n int index = 0;\n\n public List braceExpansionII(String expression) {\n List result = util(0, expression);\n Set set = new TreeSet<>();\n set.addAll(result);\n return new ArrayList<>(set);\n }\n\n List util(int startIndex, String expression) {\n // This represents processed List in the current recursion.\n List currentSet = new ArrayList<>();\n boolean isAdditive = false;\n String currentString = \"\";\n // This represents List that is being processed and not yet merged to currentSet.\n List currentList = new ArrayList<>();\n\n for (int i = startIndex; i < expression.length(); ++i) {\n\n if (expression.charAt(i) == ',') {\n isAdditive = true;\n if (currentString != \"\" && currentList.size() == 0) {\n currentSet.add(currentString);\n }\n\n else if (currentList.size() > 0) {\n for (var entry : currentList) {\n currentSet.add(entry);\n }\n }\n\n currentString = \"\";\n currentList = new ArrayList<>();\n } else if (expression.charAt(i) >= 'a' && expression.charAt(i) <= 'z') {\n if (currentList.size() > 0) {\n List tempStringList = new ArrayList<>();\n for (var entry : currentList) {\n tempStringList.add(entry + expression.charAt(i));\n }\n currentList = tempStringList;\n } else {\n currentString = currentString + expression.charAt(i);\n }\n } else if (expression.charAt(i) == '{') {\n List list = util(i + 1, expression);\n // System.out.println(list);\n // Need to merge the returned List. It could be one of the following.\n // 1- ..., {a,b,c}\n // 2- a{a,b,c}\n // 3- {a,b,c}{d,e,f}\n // 3- {a,b,c}d\n if (i > startIndex && expression.charAt(i - 1) == ',') {\n // Case 1\n currentList = list;\n } else {\n if (currentList.size() > 0) {\n List tempList = new ArrayList<>();\n for (var entry1 : currentList) {\n for (var entry2 : list) {\n // CASE 3\n tempList.add(entry1 + currentString + entry2);\n }\n }\n\n // System.out.println(currentList);\n currentList = tempList;\n currentString = \"\";\n }\n\n else if (currentString != \"\") {\n List tempList = new ArrayList<>();\n for (var entry : list) {\n // case 2\n tempList.add(currentString + entry);\n }\n\n currentString = \"\";\n currentList = tempList;\n } else {\n // CASE 1\n currentList = list;\n }\n }\n\n // Increment i to end of next recursion's processing.\n i = index;\n } else if (expression.charAt(i) == '}') {\n if (currentString != \"\") {\n currentSet.add(currentString);\n }\n\n // {a{b,c,d}}\n if (currentList.size() > 0) {\n for (var entry : currentList) {\n\n currentSet.add(entry + currentString);\n }\n currentList = new ArrayList<>();\n }\n\n index = i;\n return new ArrayList<>(currentSet);\n }\n }\n\n if (currentList.size() > 0) {\n\n currentSet.addAll(currentList);\n }\n\n // {...}a\n if (currentString != \"\") {\n\n List tempSet = new ArrayList<>();\n if (currentSet.size() > 0) {\n for (var entry : currentSet) {\n tempSet.add(entry + currentString);\n }\n\n currentSet = tempSet;\n } else {\n currentSet = new ArrayList<>();\n currentSet.add(currentString);\n }\n }\n\n return new ArrayList<>(currentSet);\n }\n}", + "title": "1096. Brace Expansion II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Formally, the three rules for our grammar: Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents .", + "description_images": [], + "constraints": [ + "Single letters represent a singleton set containing that word. R(\"a\") = {\"a\"} R(\"w\") = {\"w\"}", + "R(\"a\") = {\"a\"}", + "R(\"w\") = {\"w\"}", + "When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"} R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}", + "R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"} R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}", + "R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}", + "R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}" + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"{a,b}{c,{d,e}}\"\nOutput:[\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"{{a,z},a{b,c},{ab,z}}\"\nOutput:[\"a\",\"ab\",\"ac\",\"z\"]\nExplanation:Each distinct word is written only once in the final answer.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n s = list(reversed(\"{\" + expression + \"}\"))\n \n def full_word(): \n cur = [] \n while s and s[-1].isalpha(): \n cur.append(s.pop()) \n return \"\".join(cur)\n \n def _expr(): \n res = set() \n if s[-1].isalpha(): \n res.add(full_word()) \n elif s[-1] == \"{\": \n s.pop() # remove open brace\n res.update(_expr()) \n while s and s[-1] == \",\": \n s.pop() # remove comma \n res.update(_expr()) \n s.pop() # remove close brace \n while s and s[-1] not in \"},\": \n res = {e + o for o in _expr() for e in res}\n return res \n \n return sorted(_expr()) \n", + "title": "1096. Brace Expansion II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a palindromic string of lowercase English letters palindrome , replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b . For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd' .", + "description_images": [], + "constraints": [ + "1 <= palindrome.length <= 1000", + "palindrome consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:palindrome = \"abccba\"\nOutput:\"aaccba\"\nExplanation:There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.", + "image": null + }, + { + "text": "Example 2: Input:palindrome = \"a\"\nOutput:\"\"\nExplanation:There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String breakPalindrome(String palindrome) {\n \n int left = 0;\n int right = palindrome.length()-1;\n \n if(palindrome.length()==1)\n return \"\";\n \n while(left> wall) \n {\n HashMap edge_frequency = new HashMap<>(); //HashMap to store the number of common edges among the rows\n int max_frequency = 0; //Variable to store the frequency of most occuring edge\n \n for(int row=0; row int:\n m = len(wall)\n ctr = {}\n res = m\n for i in range(m):\n n = len(wall[i])\n curr = 0\n for j in range(n - 1):\n curr += wall[i][j]\n x = ctr.get(curr, m) - 1\n ctr[curr] = x\n res = min(res, x)\n return res\n", + "title": "554. Brick Wall", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary grid , where each 1 represents a brick and 0 represents an empty space. A brick is stable if: You are also given an array hits , which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (row i , col i ) . The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall . Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result , where each result[i] is the number of bricks that will fall after the i th erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.", + "description_images": [], + "constraints": [ + "It is directly connected to the top of the grid, or", + "At least one other brick in its four adjacent cells is stable ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\nOutput:[2]\nExplanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\nOutput:[0,0]\nExplanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 84.7%) | Memory: 57.45 MB (Top 26.3%)\n\nclass Solution {\n int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};\n\n public int[] hitBricks(int[][] grid, int[][] hits) {\n //marking all the hits that has a brick with -1\n for(int i=0;i=0;i--){\n int row = hits[i][0];\n int col = hits[i][1];\n \n //hit is at empty space so continue\n if(grid[row][col] == 0)\n continue;\n \n //marking it with 1, this signifies that a brick is present in an unstable state and will be restored in the future\n grid[row][col] = 1;\n // checking brick stability, if it's unstable no need to visit the neighbours\n if(!isStable(grid, row, col))\n continue;\n\t\t\t\n\t\t\t//So now as our brick is stable we can restore all the bricks connected to it\n //mark all the unstable bricks as stable and get the count\n res[i] = markAndCountStableBricks(grid, hits[i][0], hits[i][1])-1; //Subtracting 1 from the total count, as we don't wanna include the starting restored brick\n }\n \n return res;\n }\n \n private int markAndCountStableBricks(int[][] grid, int row, int col){\n if(grid[row][col] == 0 || grid[row][col] == -1)\n return 0;\n \n grid[row][col] = 2;\n int stableBricks = 1;\n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2)\n continue;\n \n stableBricks += markAndCountStableBricks(grid, r, c);\n }\n \n return stableBricks;\n }\n \n private boolean isStable(int[][] grid, int row, int col){\n if(row == 0)\n return true;\n \n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 2)\n return true;\n }\n \n return false;\n }\n}", + "title": "803. Bricks Falling When Hit", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n binary grid , where each 1 represents a brick and 0 represents an empty space. A brick is stable if: You are also given an array hits , which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (row i , col i ) . The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall . Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result , where each result[i] is the number of bricks that will fall after the i th erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.", + "description_images": [], + "constraints": [ + "It is directly connected to the top of the grid, or", + "At least one other brick in its four adjacent cells is stable ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\nOutput:[2]\nExplanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\nOutput:[0,0]\nExplanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7285 ms (Top 5.13%) | Memory: 29.8 MB (Top 5.13%)\nfrom collections import defaultdict\n\nclass Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n parent = defaultdict()\n sz = defaultdict(lambda:1)\n empty = set()\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n pi = find(i)\n pj = find(j)\n if pi != pj:\n parent[pi] = pj\n sz[pj] += sz[pi]\n row = len(grid)\n col = len(grid[0])\n for r in range(row):\n for c in range(col):\n parent[(r,c)] = (r,c)\n parent[(row,col)] = (row,col)\n for r, c in hits:\n if grid[r][c]:\n grid[r][c] = 0\n else:\n empty.add((r,c))\n for r in range(row):\n for c in range(col):\n if not grid[r][c]:\n continue\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r, c),(r+dr, c+dc))\n if r == 0:\n union((r,c),(row,col))\n res = [0]*len(hits)\n for i in range(len(hits)-1,-1,-1):\n r, c = hits[i]\n if (r,c) in empty:\n continue\n grid[r][c] = 1\n curbricks = sz[find((row,col))]\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r,c),(r+dr,c+dc))\n if r == 0:\n union((r,c),(row,col))\n nextbricks = sz[find((row,col))]\n if nextbricks > curbricks:\n res[i] = nextbricks - curbricks - 1\n return res", + "title": "803. Bricks Falling When Hit", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: Given two integers startValue and target , return the minimum number of operations needed to display target on the calculator .", + "description_images": [], + "constraints": [ + "multiply the number on display by 2 , or", + "subtract 1 from the number on display." + ], + "examples": [ + { + "text": "Example 1: Input:startValue = 2, target = 3\nOutput:2\nExplanation:Use double operation and then decrement operation {2 -> 4 -> 3}.", + "image": null + }, + { + "text": "Example 2: Input:startValue = 5, target = 8\nOutput:2\nExplanation:Use decrement and then double {5 -> 4 -> 8}.", + "image": null + }, + { + "text": "Example 3: Input:startValue = 3, target = 10\nOutput:3\nExplanation:Use double, decrement and double {3 -> 6 -> 5 -> 10}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 78.77%)\nclass Solution {\n public int brokenCalc(int startValue, int target) {\n if(startValue >= target) return startValue - target;\n if(target % 2 == 0){\n return 1 + brokenCalc(startValue, target / 2);\n }\n return 1 + brokenCalc(startValue, target + 1);\n }\n}", + "title": "991. Broken Calculator", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: Given two integers startValue and target , return the minimum number of operations needed to display target on the calculator .", + "description_images": [], + "constraints": [ + "multiply the number on display by 2 , or", + "subtract 1 from the number on display." + ], + "examples": [ + { + "text": "Example 1: Input:startValue = 2, target = 3\nOutput:2\nExplanation:Use double operation and then decrement operation {2 -> 4 -> 3}.", + "image": null + }, + { + "text": "Example 2: Input:startValue = 5, target = 8\nOutput:2\nExplanation:Use decrement and then double {5 -> 4 -> 8}.", + "image": null + }, + { + "text": "Example 3: Input:startValue = 3, target = 10\nOutput:3\nExplanation:Use double, decrement and double {3 -> 6 -> 5 -> 10}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def brokenCalc(self, startValue, target):\n \"\"\"\n :type startValue: int\n :type target: int\n :rtype: int\n \"\"\"\n res = 0\n while target > startValue:\n res += 1\n if target % 2:\n target += 1\n else:\n target //= 2\n return res + startValue - target\n", + "title": "991. Broken Calculator", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and goal , return true if you can swap two letters in s so the result is equal to goal , otherwise, return false . Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j] .", + "description_images": [], + "constraints": [ + "For example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab\", goal = \"ba\"\nOutput:true\nExplanation:You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", goal = \"ab\"\nOutput:false\nExplanation:The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\", goal = \"aa\"\nOutput:true\nExplanation:You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 90.24%) | Memory: 43 MB (Top 54.79%)\nclass Solution {\n public boolean buddyStrings(String s, String goal) {\n char a = '\\u0000', b = '\\u0000';\n char c = '\\u0000', d = '\\u0000';\n int lenS = s.length();\n int lenGoal = goal.length();\n boolean flag = true;\n HashSet hset = new HashSet<>();\n\n if(lenS != lenGoal)\n return false;\n\n if(s.equals(goal)){\n for(int i = 0; i < lenS; i++){\n if(!hset.contains(s.charAt(i))){\n hset.add(s.charAt(i));\n }\n else\n return true;\n }\n return false;\n }\n else{\n for(int i = 0; i < lenS; i++){\n if(s.charAt(i) == goal.charAt(i)){\n continue;\n }\n if(a == '\\u0000'){\n a = s.charAt(i);\n c = goal.charAt(i);\n continue;\n }\n if(b == '\\u0000'){\n b = s.charAt(i);\n d = goal.charAt(i);\n continue;\n }\n return false;\n }\n\n if(a == d && c == b && a != '\\u0000')\n return true;\n\n return false;\n }\n }\n}", + "title": "859. Buddy Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and goal , return true if you can swap two letters in s so the result is equal to goal , otherwise, return false . Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j] .", + "description_images": [], + "constraints": [ + "For example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab\", goal = \"ba\"\nOutput:true\nExplanation:You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", goal = \"ab\"\nOutput:false\nExplanation:The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\", goal = \"aa\"\nOutput:true\nExplanation:You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 48.33%) | Memory: 14.1 MB (Top 96.59%)\n\nfrom collections import Counter\n\nclass Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n if len(s) != len(goal):\n return False\n diffCharactersCount = 0\n diffCharactersInS = []\n diffCharactersInGoal = []\n for i in range(len(s)):\n if s[i] != goal[i]:\n diffCharactersCount += 1\n diffCharactersInS.append(s[i])\n diffCharactersInGoal.append(goal[i])\n if diffCharactersCount == 2:\n # if there are only 2 different characters, then they should be swappable\n if ((diffCharactersInS[0] == diffCharactersInGoal[1]) and (diffCharactersInS[1] == diffCharactersInGoal[0])):\n return True\n return False\n elif diffCharactersCount == 0:\n # if there is atleast one repeating character in the string then its possible for swap\n counts = Counter(s)\n for k,v in counts.items():\n if v > 1:\n return True\n # if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings\n return False\n", + "title": "859. Buddy Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array target and an integer n . You have an empty stack with the two following operations: You also have a stream of the integers in the range [1, n] . Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target . You should follow the following rules: Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them .", + "description_images": [], + "constraints": [ + "\"Push\" : pushes an integer to the top of the stack.", + "\"Pop\" : removes the integer on the top of the stack." + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,3], n = 3\nOutput:[\"Push\",\"Push\",\"Pop\",\"Push\"]\nExplanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].", + "image": null + }, + { + "text": "Example 2: Input:target = [1,2,3], n = 3\nOutput:[\"Push\",\"Push\",\"Push\"]\nExplanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].", + "image": null + }, + { + "text": "Example 3: Input:target = [1,2], n = 4\nOutput:[\"Push\",\"Push\"]\nExplanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List buildArray(int[] target, int n) {\n List result=new ArrayList<>();\n int i=1,j=0;\n while(j List[str]:\n temp = []\n result = []\n x = target[-1]\n for i in range(1,x+1):\n temp.append(i)\n for i in range(len(temp)):\n if temp[i] in target:\n result.append(\"Push\")\n elif temp[i] not in target:\n result.append(\"Push\")\n result.append(\"Pop\")\n return result\n", + "title": "1441. Build an Array With Stack Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a zero-based permutation nums ( 0-indexed ), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 ( inclusive ).", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] < nums.length", + "The elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,2,1,5,3,4]\nOutput:[0,1,2,4,5,3]\nExplanation:The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,0,1,2,3,4]\nOutput:[4,5,0,1,2,3]\nExplanation:The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] buildArray(int[] nums) {\n int n=nums.length;\n for(int i=0;i List[int]:\n for i in range(len(nums)): \n if nums[nums[i]] <= len(nums):\n nums[i] = nums[nums[i]] * 1000 + nums[i]\n else:\n nums[i] = mod(nums[nums[i]],1000) * 1000 + nums[i]\n \n for i in range(len(nums)):\n nums[i] = nums[i] // 1000\n \n return nums\n", + "title": "1920. Build Array from Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given three integers n , m and k . Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "arr has exactly n integers.", + "1 <= arr[i] <= m where (0 <= i < n) .", + "After applying the mentioned algorithm to arr , the value search_cost is equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3, k = 1\nOutput:6\nExplanation:The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 2, k = 3\nOutput:0\nExplanation:There are no possible arrays that satisify the mentioned conditions.", + "image": null + }, + { + "text": "Example 3: Input:n = 9, m = 1, k = 1\nOutput:1\nExplanation:The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfArrays(int n, int m, int k) {\n int M = (int)1e9+7, ans = 0;\n int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side\n for (int i = 1; i <= m; i++){\n dp[i][1]=1; // base case \n }\n for (int i = 2; i <= n; i++){\n int[][] next = new int[m+1][k+1];\n for (int j = 1; j <= m; j++){ // for the current max value\n for (int p = 1; p <= m; p++){ // previous max value\n for (int w = 1; w <= k; w++){ // for all possible k\n if (j>p){ // if current max is larger, update next[j][w] from dp[p][w-1]\n next[j][w]+=dp[p][w-1];\n next[j][w]%=M;\n }else{ // otherwise, update next[p][w] from dp[p][w]\n next[p][w]+=dp[p][w];\n next[p][w]%=M;\n }\n }\n }\n }\n dp=next;\n }\n for (int i = 1; i <= m; i++){ // loop through max that has k and sum them up.\n ans += dp[i][k];\n ans %= M;\n }\n return ans;\n }\n}\n", + "title": "1420. Build Array Where You Can Find The Maximum Exactly K Comparisons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given three integers n , m and k . Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "arr has exactly n integers.", + "1 <= arr[i] <= m where (0 <= i < n) .", + "After applying the mentioned algorithm to arr , the value search_cost is equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3, k = 1\nOutput:6\nExplanation:The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 2, k = 3\nOutput:0\nExplanation:There are no possible arrays that satisify the mentioned conditions.", + "image": null + }, + { + "text": "Example 3: Input:n = 9, m = 1, k = 1\nOutput:1\nExplanation:The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfArrays(self, n: int, m: int, k: int) -> int:\n @cache\n def dp(a,b,c):\n if a==n: return c==k\n return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1))\n return dp(0,0,0)%(10**9+7)\n", + "title": "1420. Build Array Where You Can Find The Maximum Exactly K Comparisons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: Given an integer n , return the minimum possible number of boxes touching the floor.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/04/3-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/4-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/10-boxes.png" + ], + "constraints": [ + "You can place the boxes anywhere on the floor.", + "If box x is placed on top of the box y , then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3\nExplanation:The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:3\nExplanation:The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 3: Input:n = 10\nOutput:6\nExplanation:The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n static final double ONE_THIRD = 1.0d / 3.0d;\n\n public int minimumBoxes(int n) {\n int k = findLargestTetrahedralNotGreaterThan(n);\n int used = tetrahedral(k);\n int floor = triangular(k);\n int unused = (n - used);\n if (unused == 0) {\n return floor;\n }\n int r = findSmallestTriangularNotLessThan(unused);\n return (floor + r);\n }\n\n private final int findLargestTetrahedralNotGreaterThan(int te) {\n int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD));\n while (tetrahedral(a) > te) {\n a--;\n }\n return a;\n }\n\n private final int findSmallestTriangularNotLessThan(int t) {\n int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2)));\n while (triangular(a) < t) {\n a++;\n }\n return a;\n }\n\n private final int tetrahedral(int a) {\n return (int) ratio(product(a, a + 1, a + 2), 6);\n }\n\n private final int triangular(int a) {\n return (int) ratio(product(a, a + 1), 2);\n }\n\n private final long product(long... vals) {\n long product = 1L;\n for (long val : vals) {\n product *= val;\n }\n return product;\n }\n\n private final long ratio(long a, long b) {\n return (a / b);\n }\n\n}\n", + "title": "1739. Building Boxes", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: Given an integer n , return the minimum possible number of boxes touching the floor.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/04/3-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/4-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/10-boxes.png" + ], + "constraints": [ + "You can place the boxes anywhere on the floor.", + "If box x is placed on top of the box y , then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3\nExplanation:The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:3\nExplanation:The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 3: Input:n = 10\nOutput:6\nExplanation:The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 24.24%) | Memory: 13.9 MB (Top 54.55%)\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n r = 0\n while (n_upper := r*(r+1)*(r+2)//6) < n:\n r += 1\n m = r*(r+1)//2\n for i in range(r, 0, -1):\n if (n_upper - i) < n:\n break\n n_upper -= i\n m -= 1\n return m", + "title": "1739. Building Boxes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i th round, you toggle every i bulb. For the n th round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:1\nExplanation:At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg" + }, + { + "text": "Example 2: Input:n = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.20 MB (Top 33.55%)\n\nclass Solution {\n public int bulbSwitch(int n) {\n return (int)Math.sqrt(n);\n }\n}\n", + "title": "319. Bulb Switcher", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i th round, you toggle every i bulb. For the n th round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:1\nExplanation:At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg" + }, + { + "text": "Example 2: Input:n = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n return int(sqrt(n))\n", + "title": "319. Bulb Switcher", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses , return the number of different possible statuses after performing all presses button presses .", + "description_images": [], + "constraints": [ + "Button 1: Flips the status of all the bulbs.", + "Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ... ).", + "Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ... ).", + "Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ... )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, presses = 1\nOutput:2\nExplanation:Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2", + "image": null + }, + { + "text": "Example 2: Input:n = 2, presses = 1\nOutput:3\nExplanation:Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3", + "image": null + }, + { + "text": "Example 3: Input:n = 3, presses = 1\nOutput:4\nExplanation:Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int flipLights(int n, int presses) {\n //1, 2 -> 3\n //1, 3 -> 2\n //2, 3 -> 1\n //all on, all off, even on, odd on, 3k+1 on, 3k+0+2 on, 3k+1 w/ 2, 3k+1 w/ 3\n if (n == 2 && presses == 1) return 3;\n if (presses == 1) return Math.min(1 << Math.min(4, n), 4); //i chose 4 arbitarily, just has to be big enough to cover small number and less than 31\n if (presses == 2) return Math.min(1 << Math.min(4, n), 7);\n if (presses >= 3) return Math.min(1 << Math.min(4, n), 8);\n return 1;\n }\n}\n", + "title": "672. Bulb Switcher II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses , return the number of different possible statuses after performing all presses button presses .", + "description_images": [], + "constraints": [ + "Button 1: Flips the status of all the bulbs.", + "Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ... ).", + "Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ... ).", + "Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ... )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, presses = 1\nOutput:2\nExplanation:Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2", + "image": null + }, + { + "text": "Example 2: Input:n = 2, presses = 1\nOutput:3\nExplanation:Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3", + "image": null + }, + { + "text": "Example 3: Input:n = 3, presses = 1\nOutput:4\nExplanation:Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 30 ms (Top 97.1%) | Memory: 16.43 MB (Top 14.4%)\n\nclass Solution:\n def flipLights(self, n: int, m: int) -> int:\n # Reduce n to at most 3, since any action performed more than 3 times\n # will result in a pattern that has already been counted\n n = min(n, 3)\n if m == 0:\n return 1\n elif m == 1:\n # For m=1, there are only 2 outcomes for n=1, 3 outcomes for n=2, and 4 outcomes for n=3\n return [2, 3, 4][n - 1]\n elif m == 2:\n # For m=2, there are only 2 outcomes for n=1, 4 outcomes for n=2, and 7 outcomes for n=3\n return [2, 4, 7][n - 1]\n else:\n # For m>=3, there are only 2 outcomes for n=1, 4 outcomes for n=2, and 8 outcomes for n=3\n return [2, 4, 8][n - 1]\n", + "title": "672. Bulb Switcher II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: Given the secret number secret and your friend's guess guess , return the hint for your friend's guess . The hint should be formatted as \"xAyB\" , where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.", + "description_images": [], + "constraints": [ + "The number of \"bulls\", which are digits in the guess that are in the correct position.", + "The number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"1807\", guess = \"7810\"\nOutput:\"1A3B\"\nExplanation:Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"", + "image": null + }, + { + "text": "Example 2: Input:secret = \"1123\", guess = \"0111\"\nOutput:\"1A1B\"\nExplanation:Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.58%) | Memory: 41.90 MB (Top 54.72%)\n\nclass Solution {\n public String getHint(String secret, String guess) {\n int bulls = 0, cows = 0;\n\n int[] secretFreq = new int[10],\n guessFreq = new int[10];\n\n for (int i = 0; i < secret.length(); i++) {\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n\n if (s == g) bulls++;\n else {\n secretFreq[s - '0']++;\n guessFreq[g - '0']++;\n }\n }\n\n for (int i = 0; i < 10; i++) {\n cows += Math.min(secretFreq[i], guessFreq[i]);\n }\n\n return bulls + \"A\" + cows + \"B\";\n }\n}\n\n// TC: O(n), SC: O(1)\n", + "title": "299. Bulls and Cows", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: Given the secret number secret and your friend's guess guess , return the hint for your friend's guess . The hint should be formatted as \"xAyB\" , where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.", + "description_images": [], + "constraints": [ + "The number of \"bulls\", which are digits in the guess that are in the correct position.", + "The number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"1807\", guess = \"7810\"\nOutput:\"1A3B\"\nExplanation:Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"", + "image": null + }, + { + "text": "Example 2: Input:secret = \"1123\", guess = \"0111\"\nOutput:\"1A1B\"\nExplanation:Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n # Setup counts for bulls and cows\n bulls = cows = 0\n \n # Copy secret and guess into lists that are easier to work with\n secretCopy = list(secret)\n guessCopy = list(guess)\n \n # In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls\n for i in range(len(secret)):\n \n # If they match, bulls += 1 and pop() the letters from the copy lists via their .index()\n if secret[i] == guess[i]:\n bulls += 1\n secretCopy.pop(secretCopy.index(secret[i]))\n guessCopy.pop(guessCopy.index(guess[i]))\n \n \n # Count() the letters remaining in secret and guess lists\n secretCounter = Counter(secretCopy)\n guessCounter = Counter(guessCopy)\n \n # Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed\n # secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters\n # Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters\n dif = secretCounter - (secretCounter - guessCounter)\n \n # The .total() of the dif Counter is the number of cows\n cows = dif.total()\n\n # return the formatted string with req. info\n return f'{bulls}A{cows}B'\n", + "title": "299. Bulls and Cows", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,5,8]\nOutput:167\nExplanation:nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5]\nOutput:10", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxCoins(int[] nums) {\n int n = nums.length;\n \n// adding 1 to the front and back\n int[] temp = new int[n + 2]; \n temp[0] = 1;\n for(int i = 1; i < temp.length - 1; i++){\n temp[i] = nums[i-1];\n }\n temp[temp.length - 1] = 1;\n nums = temp;\n \n// memoization\n int[][] dp = new int[n+1][n+1];\n for(int[] row : dp){\n Arrays.fill(row, -1);\n }\n \n// result\n return f(1, n, nums, dp);\n }\n \n int f(int i, int j, int[] a, int[][] dp){\n if(i > j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n \n int max = Integer.MIN_VALUE;\n for(int n = i; n <= j; n++){\n int coins = a[i-1] * a[n] * a[j+1] + f(i, n-1, a, dp) + f(n+1, j, a, dp);\n max = Math.max(max, coins);\n }\n return dp[i][j] = max;\n }\n}\n\n// Time Complexity: O(N * N * N) ~ O(N^3);\n// Space Complexity: O(N^2) + O(N);", + "title": "312. Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,5,8]\nOutput:167\nExplanation:nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5]\nOutput:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3739 ms (Top 77.47%) | Memory: 34.10 MB (Top 46.9%)\n\nclass Solution:\n def maxCoins(self, nums):\n A = [1] + nums + [1]\n \n @lru_cache(None)\n def dfs(i, j):\n return max([A[i]*A[k]*A[j] + dfs(i,k) + dfs(k,j) for k in range(i+1, j)] or [0])\n \n return dfs(0, len(A) - 1)\n", + "title": "312. Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the i th bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target . You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target . Return -1 if it is not possible.", + "description_images": [], + "constraints": [ + "For example, if routes[0] = [1, 5, 7] , this means that the 0 th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever." + ], + "examples": [ + { + "text": "Example 1: Input:routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput:2\nExplanation:The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.", + "image": null + }, + { + "text": "Example 2: Input:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 990 ms (Top 43.31%) | Memory: 53.60 MB (Top 12.36%)\n\nclass Solution:\n from collections import defaultdict, deque\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # Base case\n if source == target:\n return 0\n # Creating graph or routes\n graph = defaultdict(set)\n \n # Since index represents bus_number on a route\n # suppose i is bus number and stops are the values present at that index\n for bus_number, stops in enumerate(routes):\n # for each stop adding buses going to that stop\n for stop in stops:\n graph[stop].add(bus_number)\n \n # Using bfs\n bfs = deque([(source, 0)])\n \n # visited stops \n seen_stops = set()\n # visited buses\n seen_buses = set()\n \n while bfs:\n stop, count = bfs.popleft()\n # Resulting case\n if stop == target:\n return count\n \n # Since our graph stores all buses going to a stop\n # We will iterate for every bus\n for bus_number in graph[stop]:\n # We dont want to travel in same bus as we might stuck into loop and reach nowhere\n if bus_number not in seen_buses:\n seen_buses.add(bus_number)\n \n # Now we are in a bus, so we will travel all the stops that bus goes to but again, we only want to go to stops we haven't visited\n for stop in routes[bus_number]:\n if stop not in seen_stops:\n seen_stops.add(stop)\n bfs.append((stop, count + 1))\n return -1\n", + "title": "815. Bus Routes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upper i , percent i ] means that the i th tax bracket has an upper bound of upper i and is taxed at a rate of percent i . The brackets are sorted by upper bound (i.e. upper i-1 < upper i for 0 < i < brackets.length ). Tax is calculated as follows: You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "The first upper 0 dollars earned are taxed at a rate of percent 0 .", + "The next upper 1 - upper 0 dollars earned are taxed at a rate of percent 1 .", + "The next upper 2 - upper 1 dollars earned are taxed at a rate of percent 2 .", + "And so on." + ], + "examples": [ + { + "text": "Example 1: Input:brackets = [[3,50],[7,10],[12,25]], income = 10\nOutput:2.65000\nExplanation:Based on your income, you have 3 dollars in the 1sttax bracket, 4 dollars in the 2ndtax bracket, and 3 dollars in the 3rdtax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.", + "image": null + }, + { + "text": "Example 2: Input:brackets = [[1,0],[4,25],[5,50]], income = 2\nOutput:0.25000\nExplanation:Based on your income, you have 1 dollar in the 1sttax bracket and 1 dollar in the 2ndtax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.", + "image": null + }, + { + "text": "Example 3: Input:brackets = [[2,50]], income = 0\nOutput:0.00000\nExplanation:You have no income to tax, so you have to pay a total of $0 in taxes.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 45.10 MB (Top 7.1%)\n\nclass Solution {\n public double calculateTax(int[][] brackets, int income) {\n int prevIncome = 0;\n double res = 0;\n for(int i =0; i income){\n res += (income*brackets[i][1]/100.0);\n income = 0;\n }else{\n res += (diff*brackets[i][1])/100;\n income -= diff;\n }\n prevIncome = brackets[i][0];\n if(income == 0) return res;\n //System.out.println(prevIncome+\" \"+res+ \" \"+ income +\" \"+ diff + \" \"+(diff*brackets[i][1]/100));\n }\n return res;\n }\n}\n", + "title": "2303. Calculate Amount Paid in Taxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upper i , percent i ] means that the i th tax bracket has an upper bound of upper i and is taxed at a rate of percent i . The brackets are sorted by upper bound (i.e. upper i-1 < upper i for 0 < i < brackets.length ). Tax is calculated as follows: You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "The first upper 0 dollars earned are taxed at a rate of percent 0 .", + "The next upper 1 - upper 0 dollars earned are taxed at a rate of percent 1 .", + "The next upper 2 - upper 1 dollars earned are taxed at a rate of percent 2 .", + "And so on." + ], + "examples": [ + { + "text": "Example 1: Input:brackets = [[3,50],[7,10],[12,25]], income = 10\nOutput:2.65000\nExplanation:Based on your income, you have 3 dollars in the 1sttax bracket, 4 dollars in the 2ndtax bracket, and 3 dollars in the 3rdtax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.", + "image": null + }, + { + "text": "Example 2: Input:brackets = [[1,0],[4,25],[5,50]], income = 2\nOutput:0.25000\nExplanation:Based on your income, you have 1 dollar in the 1sttax bracket and 1 dollar in the 2ndtax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.", + "image": null + }, + { + "text": "Example 3: Input:brackets = [[2,50]], income = 0\nOutput:0.00000\nExplanation:You have no income to tax, so you have to pay a total of $0 in taxes.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 95.72%) | Memory: 13.9 MB (Top 34.37%)\n\nclass Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n taxtot=0\n if(brackets[0][0]0 and i(brackets[i][0]-brackets[i-1][0])):\n taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]\n income-=brackets[i][0]-brackets[i-1][0]\n else:\n taxtot+=income*brackets[i][1]\n income=0\n i+=1\n return taxtot/100", + "title": "2303. Calculate Amount Paid in Taxes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of digits and an integer k . A round can be completed if the length of s is greater than k . In one round, do the following: Return s after all rounds have been completed .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "2 <= k <= 100", + "s consists of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11111222223\", k = 3\nOutput:\"135\"\nExplanation:- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00000000\", k = 3\nOutput:\"000\"\nExplanation:We divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 32.40%) | Memory: 40.8 MB (Top 89.31%)\nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k) s = gen(s,k);\n return s;\n }\n public String gen(String s,int k){\n String res = \"\";\n for(int i=0;i < s.length();){\n int count = 0,num=0;\n while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++));\n res+=num;\n }\n return res;\n }\n}", + "title": "2243. Calculate Digit Sum of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting of digits and an integer k . A round can be completed if the length of s is greater than k . In one round, do the following: Return s after all rounds have been completed .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "2 <= k <= 100", + "s consists of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11111222223\", k = 3\nOutput:\"135\"\nExplanation:- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00000000\", k = 3\nOutput:\"000\"\nExplanation:We divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = ''\n for e in set_3:\n val = 0\n for n in e:\n val += int(n)\n s += str(val)\n return s\n", + "title": "2243. Calculate Digit Sum of a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Hercy wants to save money for his first car. He puts money in the Leetcode bank every day . He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday . Given n , return the total amount of money he will have in the Leetcode bank at the end of the n th day.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:10\nExplanation:After the 4thday, the total is 1 + 2 + 3 + 4 = 10.", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:37\nExplanation:After the 10thday, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2ndMonday, Hercy only puts in $2.", + "image": null + }, + { + "text": "Example 3: Input:n = 20\nOutput:96\nExplanation:After the 20thday, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.1 MB (Top 94.89%)\nclass Solution {\n public int totalMoney(int n) {\n int m=n/7; //(no.of full weeks)\n // first week 1 2 3 4 5 6 7 (sum is 28 i.e. 7*(i+3) if i=1)\n // second week 2 3 4 5 6 7 8 (sum is 35 i.e. 7*(i+3) if i=2)\n //.... so on\n int res=0; //for result\n //calculating full weeks\n for(int i=1;i<=m;i++){\n res+=7*(i+3);\n }\n //calculating left days\n for(int i=7*m;i int:\n return sum(starmap(add,zip(\n starmap(floordiv, zip(range(n), repeat(7, n))),\n cycle((1,2,3,4,5,6,7))\n )))\n\n", + "title": "1716. Calculate Money in Leetcode Bank", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings queries and a string pattern , return a boolean array answer where answer[i] is true if queries[i] matches pattern , and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.", + "description_images": [], + "constraints": [ + "1 <= pattern.length, queries.length <= 100", + "1 <= queries[i].length <= 100", + "queries[i] and pattern consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput:[true,false,true,true,false]\nExplanation:\"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput:[true,false,true,false,false]\nExplanation:\"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".", + "image": null + }, + { + "text": "Example 3: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput:[false,true,false,false,false]\nExplanation:\"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 33.0%) | Memory: 40.70 MB (Top 50.3%)\n\nclass Solution {\n public List camelMatch(String[] queries, String pattern) {\n List list = new ArrayList<>();\n\n for (var q : queries) {\n int index = 0;\n boolean flag = true;\n for (var c : q.toCharArray()) {\n if(index < pattern.length() && c == pattern.charAt(index)){\n index++;\n continue;\n }\n if(c >= 'A' && c <= 'Z'){\n if(index >= pattern.length() || c != pattern.charAt(index)){\n flag = false;\n break;\n }\n }\n }\n flag = flag && index == pattern.length();\n list.add(flag);\n }\n return list;\n }\n}", + "title": "1023. Camelcase Matching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings queries and a string pattern , return a boolean array answer where answer[i] is true if queries[i] matches pattern , and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.", + "description_images": [], + "constraints": [ + "1 <= pattern.length, queries.length <= 100", + "1 <= queries[i].length <= 100", + "queries[i] and pattern consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput:[true,false,true,true,false]\nExplanation:\"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput:[true,false,true,false,false]\nExplanation:\"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".", + "image": null + }, + { + "text": "Example 3: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput:[false,true,false,false,false]\nExplanation:\"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n res, N = [], len(pattern)\n\t\t\n for query in queries:\n\t\t\n if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N:\n res.append(False)\n \n else:\n res.append(True)\n\t\t\t\t\n return res\n \n \n\t\t\n def LCS(self, A, B):\n N, M = len(A), len(B)\n d = [[0 for _ in range(M+1)] for _ in range(N+1)]\n\n for i in range(1, N+1):\n for j in range(1, M+1):\n\t\t\t\n if A[i - 1] == B[j - 1]:\n d[i][j] = 1 + d[i-1][j-1]\n\n else:\n d[i][j] = max(d[i-1][j], d[i][j-1])\n return d[-1][-1]\n\n\n \n def upLetter(self, w):\n count = 0\n for c in w:\n if c.isupper():\n count += 1\n return count\n\n", + "title": "1023. Camelcase Matching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , your goal is to convert s into t in k moves or less. During the i th ( 1 <= i <= k ) move you can: Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a' ). Shifting a character by i means applying the shift operations i times. Remember that any index j can be picked at most once. Return true if it's possible to convert s into t in no more than k moves, otherwise return false .", + "description_images": [], + "constraints": [ + "Choose any index j (1-indexed) from s , such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.", + "Do nothing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"input\", t = \"ouput\", k = 9\nOutput:true\nExplanation:In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\", t = \"bcd\", k = 10\nOutput:false\nExplanation:We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\", t = \"bbb\", k = 27\nOutput:true\nExplanation:In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 58.97%) | Memory: 54.5 MB (Top 69.23%)\nclass Solution {\n public boolean canConvertString(String s, String t, int k) {\n //if strings lengths not equal return false\n if(s.length()!=t.length())return false;\n //array to count number of times a difference can repeat\n int b[]=new int[26];\n int h=k/26;\n int h1=k%26;\n //count of each number from 1 to 26 from 1 to k\n for(int i=0;i<26;i++){\n b[i]+=h;\n if(i<=h1)b[i]++;\n }\n\n int i=0;\n while(i bool:\n if len(s) != len(t):\n return False\n\n cycles, extra = divmod(k, 26)\n shifts = [cycles + (shift <= extra) for shift in range(26)]\n\n for cs, ct in zip(s, t):\n shift = (ord(ct) - ord(cs)) % 26\n if shift == 0:\n continue\n if not shifts[shift]:\n return False\n shifts[shift] -= 1\n\n return True", + "title": "1540. Can Convert String in K Moves", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the \"100 game\" two players take turns adding, to a running total, any integer from 1 to 10 . The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal , return true if the first player to move can force a win, otherwise, return false . Assume both players play optimally .", + "description_images": [], + "constraints": [ + "1 <= maxChoosableInteger <= 20", + "0 <= desiredTotal <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:maxChoosableInteger = 10, desiredTotal = 11\nOutput:false\nExplanation:No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.", + "image": null + }, + { + "text": "Example 2: Input:maxChoosableInteger = 10, desiredTotal = 0\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:maxChoosableInteger = 10, desiredTotal = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int numlimit, tgt;\n public boolean canIWin(int maxChoosableInteger, int desiredTotal) {\n numlimit = maxChoosableInteger;\n tgt = desiredTotal;\n \n int maxsum = (numlimit*(numlimit+1))/2;\n if(maxsum < tgt)\n return false;\n \n int dp[] = new int[(1<= tgt) || !solve((mask|(1<= 100. Given two integers maxChoosableInteger and desiredTotal , return true if the first player to move can force a win, otherwise, return false . Assume both players play optimally .", + "description_images": [], + "constraints": [ + "1 <= maxChoosableInteger <= 20", + "0 <= desiredTotal <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:maxChoosableInteger = 10, desiredTotal = 11\nOutput:false\nExplanation:No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.", + "image": null + }, + { + "text": "Example 2: Input:maxChoosableInteger = 10, desiredTotal = 0\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:maxChoosableInteger = 10, desiredTotal = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n remainder = [i+1 for i in range(maxChoosableInteger)] # numbers\n @cache\n def can_win(total, remainder):\n if total >= desiredTotal:\n return False # total is already exceed the desiredTotal. Opponent won. \n \n for num in remainder:\n if can_win(total + num, tuple([n for n in remainder if n != num])) == False: # if opponent lose, I win(return True)\n return True\n return False \n \n if desiredTotal == 0: \n return True \n if sum(remainder) < desiredTotal: # Both of two cannot win.\n return False \n return can_win(0, tuple(remainder))\n", + "title": "464. Can I Win", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr , return true if the array can be rearranged to form an arithmetic progression . Otherwise, return false .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 1000", + "-10^6 <= arr[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1]\nOutput:true\nExplanation:We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,4]\nOutput:false\nExplanation:There is no way to reorder the elements to obtain an arithmetic progression.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 91.15%) | Memory: 43.1 MB (Top 10.07%)\nclass Solution {\n public boolean canMakeArithmeticProgression(int[] arr) {\n if(arr.length < 1)\n return false;\n Arrays.sort(arr);\n int diff = arr[1]-arr[0];\n for(int i=1;i bool:\n arr.sort()\n check = arr[0] - arr[1]\n for i in range(len(arr)-1):\n if arr[i] - arr[i+1] != check:\n return False\n return True\n", + "title": "1502. Can Make Arithmetic Progression From Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and array queries where queries[i] = [left i , right i , k i ] . We may rearrange the substring s[left i ...right i ] for each query and then choose up to k i of them to replace with any lowercase English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is true . Otherwise, the result is false . Return a boolean array answer where answer[i] is the result of the i th query queries[i] . Note that each letter is counted individually for replacement, so if, for example s[left i ...right i ] = \"aaa\" , and k i = 2 , we can only replace two of the letters. Also, note that no query modifies the initial string s . Example :", + "description_images": [], + "constraints": [ + "1 <= s.length, queries.length <= 10^5", + "0 <= left i <= right i < s.length", + "0 <= k i <= s.length", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example : Input:s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput:[true,false,false,true,true]\nExplanation:queries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"lyb\", queries = [[0,1,0],[2,2,1]]\nOutput:[false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 84.38%) | Memory: 106.10 MB (Top 54.69%)\n\nclass Solution \n{ public List canMakePaliQueries(String s, int[][] queries) \n {\n List list = new ArrayList<>();\n \n int n = s.length();\n // prefix map to count number of time each letters have occured to access in queries in O(1)\n //s= a b c d a\n // a 1 1 1 1 2\n // b 0 1 1 1 1\n // c 0 0 1 1 1\n // d 0 0 0 1 1\n // e\n // f\n // .\n // .\n // .\n int[][] map = new int[n+1][26];\n for(int i=0;i List[bool]:\n hash_map = {s[0]: 1}\n x = hash_map\n prefix = [hash_map]\n for i in range(1, len(s)):\n x = x.copy()\n x[s[i]] = x.get(s[i], 0) + 1\n prefix.append(x)\n \n result = []\n for query in queries:\n cnt = 0\n for key, value in prefix[query[1]].items():\n if query[0] > 0:\n x = value - prefix[query[0]-1].get(key, 0)\n else:\n x = value\n if x % 2:\n cnt+=1\n if cnt - 2 * query[2] > 1:\n result.append(False)\n else:\n result.append(True)\n return result\n", + "title": "1177. Can Make Palindrome from Substring", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPlaceFlowers(int[] flowerbed, int n) {\n if(flowerbed[0] != 1){\n n--;\n flowerbed[0] = 1; \n }\n for(int i = 1; i < flowerbed.length; i++){\n if(flowerbed[i - 1] == 1 && flowerbed[i] == 1){\n flowerbed[i - 1] = 0;\n n++;\n }\n if(flowerbed[i - 1] != 1 && flowerbed[i] != 1){\n flowerbed[i] = 1;\n n--;\n }\n }\n return (n <= 0) ? true: false;\n }\n}\n", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:\n f = [0] + flowerbed + [0]\n\n i, could_plant = 1, 0\n while could_plant < n and i < len(f) - 1:\n if f[i + 1]:\n # 0 0 1 -> skip 3\n i += 3\n elif f[i]:\n # 0 1 0 -> skip 2\n i += 2\n elif f[i - 1]:\n # 1 0 0 -> skip 1\n i += 1\n else:\n # 0 0 0 -> plant, becomes 0 1 0 -> skip 2\n could_plant += 1\n i += 2\n\n return n <= could_plant\n", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings . You are giving candies to these children subjected to the following requirements: Return the minimum number of candies you need to have to distribute the candies to the children .", + "description_images": [], + "constraints": [ + "Each child must have at least one candy.", + "Children with a higher rating get more candies than their neighbors." + ], + "examples": [ + { + "text": "Example 1: Input:ratings = [1,0,2]\nOutput:5\nExplanation:You can allocate to the first, second and third child with 2, 1, 2 candies respectively.", + "image": null + }, + { + "text": "Example 2: Input:ratings = [1,2,2]\nOutput:4\nExplanation:You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 14.09%) | Memory: 53.1 MB (Top 8.48%)\nclass Solution {\n public int candy(int[] ratings) {\n\n int[] left = new int[ratings.length];\n Arrays.fill(left, 1);\n\n // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy\n for(int i = 0; i=0; i--){\n if(ratings[i+1] < ratings[i] && right[i] <= right[i+1])\n right[i] = right[i+1]+1;\n }\n int sum = 0;\n for(int i = 0; i int:\n n=len(ratings)\n temp = [1]*n\n\n for i in range(1,n):\n if(ratings[i]>ratings[i-1]):\n temp[i]=temp[i-1]+1\n if(n>1):\n if(ratings[0]>ratings[1]):\n temp[0]=2\n\n for i in range(n-2,-1,-1):\n if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):\n temp[i]=temp[i+1]+1\n\n return sum(temp)", + "title": "135. Candy", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The i th package on the conveyor belt has a weight of weights[i] . Each day, we load the ship with packages on the conveyor belt (in the order given by weights ). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.", + "description_images": [], + "constraints": [ + "1 <= days <= weights.length <= 5 * 10^4", + "1 <= weights[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput:15\nExplanation:A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.", + "image": null + }, + { + "text": "Example 2: Input:weights = [3,2,2,4,1,4], days = 3\nOutput:6\nExplanation:A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4", + "image": null + }, + { + "text": "Example 3: Input:weights = [1,2,3,1,1], days = 4\nOutput:3\nExplanation:1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shipWithinDays(int[] weights, int days) {\n int left = 0;\n int right = 0;\n // left is the biggest element in the array. It's set as the lower boundary.\n // right is the sum of the array, which is the upper limit. \n for (int weight : weights) {\n left = Math.max(weight, left);\n right += weight;\n }\n int res = 0;\n while (left <= right) {\n int mid = (left + right) / 2;\n // make sure mid is a possible value \n if (isPossible(weights, days, mid)) {\n res = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n return res;\n }\n \n public boolean isPossible(int [] weights, int days, int mid) {\n int totalDays = 1;\n int totalWeight = 0;\n for (int i = 0; i < weights.length; i++) {\n totalWeight += weights[i];\n // increase totalDays if totalWeight is larger than mid\n if (totalWeight > mid) {\n totalDays++;\n totalWeight = weights[i]; \n } \n // the problem states all the packages have to ship within `days` days \n if (totalDays > days) {\n return false;\n }\n }\n return true;\n }\n \n}\n", + "title": "1011. Capacity To Ship Packages Within D Days", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The i th package on the conveyor belt has a weight of weights[i] . Each day, we load the ship with packages on the conveyor belt (in the order given by weights ). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.", + "description_images": [], + "constraints": [ + "1 <= days <= weights.length <= 5 * 10^4", + "1 <= weights[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput:15\nExplanation:A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.", + "image": null + }, + { + "text": "Example 2: Input:weights = [3,2,2,4,1,4], days = 3\nOutput:6\nExplanation:A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4", + "image": null + }, + { + "text": "Example 3: Input:weights = [1,2,3,1,1], days = 4\nOutput:3\nExplanation:1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1388 ms (Top 11.51%) | Memory: 17.1 MB (Top 35.27%)\nclass Solution:\n def shipWithinDays(self, weights: List[int], days: int) -> int:\n def calc(m):#function calculate no of days for given weight\n c,s=0,0\n for i in weights:\n if i+s>m:\n c+=1\n s=0\n s+=i\n if s>0:\n c+=1\n return c\n left,right=max(weights),sum(weights)\n while left <=right:\n mid = (left+right)//2\n if calc(mid) > days:\n left = mid+1\n else :\n right = mid -1\n return left", + "title": "1011. Capacity To Ship Packages Within D Days", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title .", + "description_images": [], + "constraints": [ + "If the length of the word is 1 or 2 letters, change all letters to lowercase.", + "Otherwise, change the first letter to uppercase and the remaining letters to lowercase." + ], + "examples": [ + { + "text": "Example 1: Input:title = \"capiTalIze tHe titLe\"\nOutput:\"Capitalize The Title\"\nExplanation:Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 2: Input:title = \"First leTTeR of EACH Word\"\nOutput:\"First Letter of Each Word\"\nExplanation:The word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 3: Input:title = \"i lOve leetcode\"\nOutput:\"i Love Leetcode\"\nExplanation:The word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.1%) | Memory: 41.07 MB (Top 90.8%)\n\nclass Solution {\n\tpublic String capitalizeTitle(String title) {\n\n\t\tchar[] ch = title.toCharArray();\n\t\tint len = ch.length;\n\n\t\tfor(int i = 0; i < len; ++i) {\n\n\t\t\tint firstIndex = i; // store the first index of the word\n\n\t\t\twhile(i < len && ch[i] != ' ') {\n\t\t\t\tch[i] = Character.toLowerCase(ch[i]); // converting the character at ith index to lower case ony by one\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t\n\t\t\t// if word is of length greater than 2, then turn the first character of the word to upper case\n\t\t\tif(i - firstIndex > 2) {\n\t\t\t\tch[firstIndex] = Character.toUpperCase(ch[firstIndex]); // converting the first character of the word to upper case\n\t\t\t}\n\t\t}\n\n\t\treturn String.valueOf(ch); // return the final result by converting the char array into string\n\t}\n}", + "title": "2129. Capitalize the Title", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title .", + "description_images": [], + "constraints": [ + "If the length of the word is 1 or 2 letters, change all letters to lowercase.", + "Otherwise, change the first letter to uppercase and the remaining letters to lowercase." + ], + "examples": [ + { + "text": "Example 1: Input:title = \"capiTalIze tHe titLe\"\nOutput:\"Capitalize The Title\"\nExplanation:Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 2: Input:title = \"First leTTeR of EACH Word\"\nOutput:\"First Letter of Each Word\"\nExplanation:The word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 3: Input:title = \"i lOve leetcode\"\nOutput:\"i Love Leetcode\"\nExplanation:The word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def capitalizeTitle(self, title: str) -> str:\n li = title.split()\n for i,l in enumerate(li):\n if len(l) <= 2:\n li[i] = l.lower()\n else:\n li[i] = l[0].upper() + l[1:].lower()\n return ' '.join(li)", + "title": "2129. Capitalize the Title", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed , both of length n , where position[i] is the position of the i th car and speed[i] is the speed of the i th car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed . The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\nOutput:3\nExplanation:The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\nThe car starting at 0 does not catch up to any other car, so it is a fleet by itself.\nThe 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.\nNote that no other cars meet these fleets before the destination, so the answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 10, position = [3], speed = [3]\nOutput:1\nExplanation:There is only one car, hence there is only one fleet.", + "image": null + }, + { + "text": "Example 3: Input:target = 100, position = [0,2,4], speed = [4,2,1]\nOutput:1\nExplanation:The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\nThen, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 186 ms (Top 36.59%) | Memory: 87.4 MB (Top 48.79%)\nclass Solution {\n class pair implements Comparable{\n int pos;\n double time;\n pair(int pos,double time){\n this.pos=pos;\n this.time=time;\n }\n public int compareTo(pair o){\n return o.pos-this.pos;\n }\n }\n public int carFleet(int target, int[] position, int[] speed) {\n double []arr=new double[position.length];\n for(int i=0;ipq=new PriorityQueue<>();\n for(int i=0;i0){\n pair rem=pq.remove();\n if(updatetime int:\n def computeArrivalTime(curr_pos, curr_speed):\n nonlocal target\n return (target - curr_pos) / curr_speed\n # avoid integer division, as a car may arrive at 5.2s and another at 5.6s\n\n cars = list(zip(position, speed))\n cars.sort(key=lambda x: x[0], reverse=True)\n arrival_bound = None # time upper bound\n fleet = 0\n for pos, sp in cars:\n curr_arrival = computeArrivalTime(pos, sp)\n if not arrival_bound or curr_arrival > arrival_bound:\n arrival_bound = curr_arrival\n fleet += 1\n return fleet\n # time O(n logn): sort = (nlogn); loop = (n)\n # space O(n): depend on sort", + "title": "853. Car Fleet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n , where cars[i] = [position i , speed i ] represents: For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer , where answer[i] is the time, in seconds, at which the i th car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10 -5 of the actual answers are accepted.", + "description_images": [], + "constraints": [ + "position i is the distance between the i th car and the beginning of the road in meters. It is guaranteed that position i < position i+1 .", + "speed i is the initial speed of the i th car in meters per second." + ], + "examples": [ + { + "text": "Example 1: Input:cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput:[1.00000,-1.00000,3.00000,-1.00000]\nExplanation:After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.", + "image": null + }, + { + "text": "Example 2: Input:cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput:[2.00000,1.00000,1.50000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 65.78%) | Memory: 229.1 MB (Top 68.82%)\nclass Solution {\n public double[] getCollisionTimes(int[][] cars) {\n int n = cars.length;\n double[] res = new double[n];\n Arrays.fill(res, -1.0);\n\n // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that\n // after catching c2, we may view c1 as non-existing (cars before c1 may not catches c1);\n\n /** Define a stack storing the index of cars as follows:\n\n Assuming cars c_0, c_1, c_2, ... , c_k are in the stack, they satisfy:\n 1. v0 > v1 > v2 ... > vk where v_i is the velocity of car c_i\n 2. c_(i+1) is the car that c_i vanishes into\n\n Namely, if only these cars exist, then what will happened is that c_0 vanishes into c_1,\n then c_1 vanishes into c_2, ..., c_(k-1) vanishes into c_k;\n */\n Deque stack = new LinkedList<>();\n for (int i = n-1; i >= 0; i--) {\n int[] c1 = cars[i];\n while (!stack.isEmpty()) {\n int j = stack.peekLast();\n int[] c2 = cars[j];\n\n /** If both conditions are satisfied:\n 1. c1 is faster than c2\n 2. c1 catches c2 before c2 vanishes into other car\n\n Then we know that c2 is the car that c1 catches first (i.e., c1 vanishes into c2)\n ==> get the result for c1\n\n Note neither c1 nor c2 is polled out from the stack considering the rule of stack.\n */\n\n if (c1[1] > c2[1] && (res[j] == -1.0 || catchTime(cars, i, j) <= res[j])) {\n res[i] = catchTime(cars, i, j);\n break;\n }\n\n /** Now we have either one of situations\n 1. c1 is slower than c2\n 2. c1 potentially catches c2 AFTER c2 vanishes\n\n Claim: no car before c1 will vanish into c2\n\n 1. ==> cars before c1 will vanish into c1 first before catching c2\n 2. <==> c2 \"vanishes\" into another car even before c1 catches it\n\n Either way, c2 can not be catched by c1 or cars beofre c1 ==> poll it out from stack\n\n */\n stack.pollLast();\n }\n stack.offerLast(i);\n }\n return res;\n }\n\n // time for cars[i] to catch cars[j]\n private double catchTime(int[][] cars, int i, int j) {\n int dist = cars[j][0] - cars[i][0];\n int v = cars[i][1] - cars[j][1];\n\n return (double)dist / v;\n }\n}", + "title": "1776. Car Fleet II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n , where cars[i] = [position i , speed i ] represents: For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer , where answer[i] is the time, in seconds, at which the i th car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10 -5 of the actual answers are accepted.", + "description_images": [], + "constraints": [ + "position i is the distance between the i th car and the beginning of the road in meters. It is guaranteed that position i < position i+1 .", + "speed i is the initial speed of the i th car in meters per second." + ], + "examples": [ + { + "text": "Example 1: Input:cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput:[1.00000,-1.00000,3.00000,-1.00000]\nExplanation:After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.", + "image": null + }, + { + "text": "Example 2: Input:cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput:[2.00000,1.00000,1.50000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Car:\n def __init__(self, pos, speed, idx, prev=None, next=None):\n self.pos = pos\n self.speed = speed\n self.idx = idx\n self.prev = prev\n self.next = next\n\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times\n", + "title": "1776. Car Fleet II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengers i , from i , to i ] indicates that the i th trip has numPassengers i passengers and the locations to pick them up and drop them off are from i and to i respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= trips.length <= 1000", + "trips[i].length == 3", + "1 <= numPassengers i <= 100", + "0 <= from i < to i <= 1000", + "1 <= capacity <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 30.51%) | Memory: 45.4 MB (Top 20.46%)\nclass Solution {\n public boolean carPooling(int[][] trips, int capacity) {\n Map destinationToPassengers = new TreeMap<>();\n for(int[] trip : trips) {\n int currPassengersAtPickup = destinationToPassengers.getOrDefault(trip[1], 0);\n int currPassengersAtDrop = destinationToPassengers.getOrDefault(trip[2], 0);\n destinationToPassengers.put(trip[1], currPassengersAtPickup + trip[0]);\n destinationToPassengers.put(trip[2], currPassengersAtDrop - trip[0]);\n }\n\n int currPassengers = 0;\n for(int passengers : destinationToPassengers.values()) {\n currPassengers += passengers;\n\n if(currPassengers > capacity) {\n return false;\n }\n }\n return true;\n }\n}", + "title": "1094. Car Pooling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengers i , from i , to i ] indicates that the i th trip has numPassengers i passengers and the locations to pick them up and drop them off are from i and to i respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= trips.length <= 1000", + "trips[i].length == 3", + "1 <= numPassengers i <= 100", + "0 <= from i < to i <= 1000", + "1 <= capacity <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n endheap = []\n startheap = []\n \n for i in range(len(trips)):\n endheap.append((trips[i][2],trips[i][0],trips[i][1]))\n startheap.append((trips[i][1],trips[i][0],trips[i][2]))\n heapify(endheap)\n heapify(startheap)\n cur = 0\n while startheap:\n start,num,end = heappop(startheap)\n while start >= endheap[0][0]:\n newend,newnum,newstart = heappop(endheap)\n cur -= newnum\n cur += num\n print(cur)\n if cur >capacity:\n return False\n return True\n \n \n \n \n", + "title": "1094. Car Pooling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 0-indexed integer arrays fronts and backs of length n , where the i th card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero). After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card. Return the minimum possible good integer after flipping the cards . If there are no good integers, return 0 .", + "description_images": [], + "constraints": [ + "n == fronts.length == backs.length", + "1 <= n <= 1000", + "1 <= fronts[i], backs[i] <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:fronts = [1,2,4,4,7], backs = [1,3,4,1,3]\nOutput:2\nExplanation:If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.", + "image": null + }, + { + "text": "Example 2: Input:fronts = [1], backs = [1]\nOutput:0\nExplanation:There are no good integers no matter how we flip the cards, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7624 ms (Top 5.13%) | Memory: 14.1 MB (Top 95.38%)\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n return min([v for v in fronts + backs if v not in set([i for i, j in zip(fronts, backs) if i == j])] or [0])", + "title": "822. Card Flipping Game", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0 . During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1] . Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: Given a graph , and assuming both players play optimally, return", + "description_images": [], + "constraints": [ + "If ever the Cat occupies the same node as the Mouse, the Cat wins.", + "If ever the Mouse reaches the Hole, the Mouse wins.", + "If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg" + }, + { + "text": "Example 2: Input:graph = [[1,3],[0],[3],[0,2]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 911 ms (Top 7.06%) | Memory: 70.7 MB (Top 63.53%)\nclass Solution {\n int TIME_MAX = 200;\n int DRAW = 0;\n int MOUSE_WIN = 1;\n int CAT_WIN = 2;\n public int catMouseGame(int[][] graph) {\n return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]);\n }\n\n private int dfs(int time, int[] p, int[][] graph, Integer[][][] memo){ // p[0] -> mouse position, p[1] -> cat position\n Integer old = memo[time][p[0]][p[1]];\n if (old != null) return old; // all the base cases here\n if (time >= TIME_MAX) return DRAW;\n if (p[0]==0) return MOUSE_WIN;\n if (p[0]==p[1]) return CAT_WIN;\n int state = 0;\n int where = p[time&1];\n int res = DRAW;\n for (int i = 0; i < graph[where].length; i++){\n if ((time&1)==0||graph[where][i]>0){ // if mouse turn or cat turn and the dest is not 0, do ...\n p[time&1]=graph[where][i];\n state |= 1 << dfs(time+1, p, graph, memo);\n if ((time&1)>0&&(state&4)>0 || (time&1)==0&&(state&2)>0) // if mouse's turn & mouse win\n break; // or cat's turn & cat win, then we stop.\n }\n }\n p[time&1]=where; // restore p\n if (((time&1)>0 && (state & 4)>0)||((time&1)==0) && state==4){\n res = CAT_WIN; // cat win when (cat's turn & cat win) or (mouse's turn and state = cat)\n }else if (((time&1)==0 && (state & 2)>0)||(time&1)==1 && state==2){\n res = MOUSE_WIN; // mouse win when (mouse's turn and mouse win) or (cat's turn and state = mouse)\n }\n return memo[time][p[0]][p[1]]=res;\n }\n}", + "title": "913. Cat and Mouse", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0 . During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1] . Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: Given a graph , and assuming both players play optimally, return", + "description_images": [], + "constraints": [ + "If ever the Cat occupies the same node as the Mouse, the Cat wins.", + "If ever the Mouse reaches the Hole, the Mouse wins.", + "If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg" + }, + { + "text": "Example 2: Input:graph = [[1,3],[0],[3],[0,2]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n \n", + "title": "913. Cat and Mouse", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols , where each element is a wall, floor, player (Cat, Mouse), or food. Mouse and Cat play according to the following rules: The game can end in 4 ways: Given a rows x cols matrix grid and two integers catJump and mouseJump , return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false .", + "description_images": [], + "constraints": [ + "Players are represented by the characters 'C' (Cat) ,'M' (Mouse).", + "Floors are represented by the character '.' and can be walked on.", + "Walls are represented by the character '#' and cannot be walked on.", + "Food is represented by the character 'F' and can be walked on.", + "There is only one of each character 'C' , 'M' , and 'F' in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\nOutput:true\nExplanation:Cat cannot catch Mouse on its turn nor can it get the food before Mouse.", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png" + }, + { + "text": "Example 2: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png" + }, + { + "text": "Example 3: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] dx = new int[]{0, 0, 1 ,-1};\n int[] dy = new int[]{-1, 1, 0, 0};\n int m;\n int n;\n int TIME_MAX = 100;\n public boolean canMouseWin(String[] grid, int catJump, int mouseJump) {\n m = grid.length;\n n = grid[0].length();\n int mouseI = 0, mouseJ = 0;\n int catI = 0, catJ = 0;\n for (int i = 0; i < m; i++){\n for (int j = 0; j < n; j++){\n switch(grid[i].charAt(j)){\n case 'M' -> {mouseI = i; mouseJ = j;}\n case 'C' -> {catI = i; catJ = j;}\n }\n }\n }\n return dfs(0, mouseI, mouseJ, catI, catJ, catJump, mouseJump, grid, new Boolean[TIME_MAX+1][m][n][m][n]);\n }\n\n private boolean dfs(int time, int mI, int mJ, int cI, int cJ, int cJump, int mJump, String[] grid, Boolean[][][][][] memo){\n if (grid[mI].charAt(mJ)=='F'){ // mouse got the food -> mouse won\n return true;\n }\n if (grid[cI].charAt(cJ)=='F' || cI==mI&&cJ==mJ || time > TIME_MAX){\n return false; // cat got the food / draw / cat got the mouse -> cat won.\n }\n if (memo[time][mI][mJ][cI][cJ]!=null){\n return memo[time][mI][mJ][cI][cJ];\n }\n boolean mT = time % 2 == 0;\n int jump = mT? mJump : cJump;\n int x = mT? mI : cI;\n int y = mT? mJ : cJ;\n if (!mT&&!dfs(time+1,mI,mJ,cI,cJ,cJump,mJump,grid,memo)){\n return memo[time][mI][mJ][cI][cJ]=false; // cat's turn and cat stays still and cat won\n }\n for (int i = 0; i < 4; i++){\n for (int j = 1; j <= jump; j++){\n int nx = x + dx[i]*j;\n int ny = y + dy[i]*j;\n if (nx < 0 || ny < 0 || nx == m || ny == n || grid[nx].charAt(ny)=='#'){\n break; // note that cat & mouse can't jump over #. I got a WA thinking they can jump over it.\n }\n boolean res = dfs(time+1, mT? nx : mI, mT? ny : mJ, mT? cI : nx, mT? cJ : ny, cJump, mJump, grid, memo);\n if (mT&&res){ // if it is mouse's turn and it can find ONE way to win, then mouse win.\n return memo[time][mI][mJ][cI][cJ]=true;\n }\n if (!mT&&!res){ // if it is cat's turn and it can find ONE way to a draw or cat win, then cat win\n return memo[time][mI][mJ][cI][cJ]=false;\n }\n }\n }\n return memo[time][mI][mJ][cI][cJ]=!mT; // otherwise, return !mT\n }\n}\n", + "title": "1728. Cat and Mouse II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols , where each element is a wall, floor, player (Cat, Mouse), or food. Mouse and Cat play according to the following rules: The game can end in 4 ways: Given a rows x cols matrix grid and two integers catJump and mouseJump , return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false .", + "description_images": [], + "constraints": [ + "Players are represented by the characters 'C' (Cat) ,'M' (Mouse).", + "Floors are represented by the character '.' and can be walked on.", + "Walls are represented by the character '#' and cannot be walked on.", + "Food is represented by the character 'F' and can be walked on.", + "There is only one of each character 'C' , 'M' , and 'F' in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\nOutput:true\nExplanation:Cat cannot catch Mouse on its turn nor can it get the food before Mouse.", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png" + }, + { + "text": "Example 2: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png" + }, + { + "text": "Example 3: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canMouseWin(self, A: List[str], cj: int, mj: int) -> bool:\n # some helper functions:\n xy2i = lambda x, y: x * n + y\n i2xy = lambda i: (i // n, i % n)\n def adj_grid(x0, y0, jump=1):\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n for step in range(jump):\n x, y = x0 + (step+1) * dx, y0 + (step+1) * dy\n if not(0<=x\" where: You are given a string s in the format \":\" , where represents the column c1 , represents the row r1 , represents the column c2 , and represents the row r2 , such that r1 <= r2 and c1 <= c2 . Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2 . The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.", + "description_images": [], + "constraints": [ + " denotes the column number c of the cell. It is represented by alphabetical letters . For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + "For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + " is the row number r of the cell. The r th row is represented by the integer r ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"K1:L2\"\nOutput:[\"K1\",\"K2\",\"L1\",\"L2\"]\nExplanation:The above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/08/ex1drawio.png" + }, + { + "text": "Example 2: Input:s = \"A1:F1\"\nOutput:[\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]\nExplanation:The above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/exam2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List cellsInRange(String s) {\n char sc = s.charAt(0), ec = s.charAt(3);\n char sr = s.charAt(1), er = s.charAt(4);\n List res = new ArrayList<>();\n \n for (char i = sc; i <= ec; ++i){\n for (char j = sr; j <= er; ++j){\n res.add(new String(new char[]{i, j}));\n }\n }\n \n return res;\n }\n}\n", + "title": "2194. Cells in a Range on an Excel Sheet", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A cell (r, c) of an excel sheet is represented as a string \"\" where: You are given a string s in the format \":\" , where represents the column c1 , represents the row r1 , represents the column c2 , and represents the row r2 , such that r1 <= r2 and c1 <= c2 . Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2 . The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.", + "description_images": [], + "constraints": [ + " denotes the column number c of the cell. It is represented by alphabetical letters . For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + "For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + " is the row number r of the cell. The r th row is represented by the integer r ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"K1:L2\"\nOutput:[\"K1\",\"K2\",\"L1\",\"L2\"]\nExplanation:The above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/08/ex1drawio.png" + }, + { + "text": "Example 2: Input:s = \"A1:F1\"\nOutput:[\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]\nExplanation:The above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/exam2drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 33.3%) | Memory: 16.43 MB (Top 7.2%)\n\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n start, end = s.split(':')\n start_letter, start_num = start[0], int(start[-1])\n end_letter, end_num = end[0], int(end[1])\n alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n alphabet_slice = \\\n alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1]\n res = list()\n for el in alphabet_slice:\n res += [el + str(num) for num in range(start_num, end_num + 1)]\n return res", + "title": "2194. Cells in a Range on an Excel Sheet", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n matrix that is initialized to all 0 's. There is also a 2D array indices where each indices[i] = [r i , c i ] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i] , do both of the following: Given m , n , and indices , return the number of odd-valued cells in the matrix after applying the increment to all locations in indices .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "1 <= indices.length <= 100", + "0 <= r i < m", + "0 <= c i < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput:6\nExplanation:Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e1.png" + }, + { + "text": "Example 2: Input:m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput:0\nExplanation:Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e2.png" + } + ], + "follow_up": null, + "solution": "// --------------------- Solution 1 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[][] matrix = new int[m][n];\n \n for(int i = 0; i < indices.length; i++) {\n int row = indices[i][0];\n int col = indices[i][1];\n \n for(int j = 0; j < n; j++) {\n matrix[row][j]++;\n }\n for(int j = 0; j < m; j++) {\n matrix[j][col]++;\n }\n }\n \n int counter = 0;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if(matrix[i][j] % 2 != 0) {\n counter++;\n }\n }\n }\n \n return counter;\n }\n}\n\n// --------------------- Solution 2 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[] row = new int[m];\n int[] col = new int[n];\n \n for(int i = 0; i < indices.length; i++) {\n row[indices[i][0]]++;\n col[indices[i][1]]++;\n }\n \n int counter = 0;\n for(int i : row) {\n for(int j : col) {\n counter += (i + j) % 2 == 0 ? 0 : 1;\n }\n }\n \n return counter;\n }\n}\n", + "title": "1252. Cells with Odd Values in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an m x n matrix that is initialized to all 0 's. There is also a 2D array indices where each indices[i] = [r i , c i ] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i] , do both of the following: Given m , n , and indices , return the number of odd-valued cells in the matrix after applying the increment to all locations in indices .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "1 <= indices.length <= 100", + "0 <= r i < m", + "0 <= c i < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput:6\nExplanation:Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e1.png" + }, + { + "text": "Example 2: Input:m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput:0\nExplanation:Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 40.72%) | Memory: 13.9 MB (Top 91.29%)\nclass Solution:\n def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:\n rows, cols = [False] * row, [False] * col\n\n for index in indices:\n rows[index[0]] = not rows[index[0]]\n cols[index[1]] = not cols[index[1]]\n\n count = 0\n for i in rows:\n for j in cols:\n count += i ^ j\n\n return count", + "title": "1252. Cells with Odd Values in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0 , then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0 . Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0 , then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] < 2 16" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]\nOutput:false\nExplanation:Alice has two choices: erase 1 or erase 2. \nIf she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean xorGame(int[] nums) {\n int x = 0;\n for(int i=0;i bool:\n return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0\n", + "title": "810. Chalkboard XOR Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100 th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the j th glass in the i th row is (both i and j are 0-indexed.)", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png" + ], + "constraints": [ + "0 <= poured <= 10^9", + "0 <= query_glass <= query_row < 100" + ], + "examples": [ + { + "text": "Example 1: Input:poured = 1, query_row = 1, query_glass = 1\nOutput:0.00000\nExplanation:We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.", + "image": null + }, + { + "text": "Example 2: Input:poured = 2, query_row = 1, query_glass = 1\nOutput:0.50000\nExplanation:We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.", + "image": null + }, + { + "text": "Example 3: Input:poured = 100000009, query_row = 33, query_glass = 17\nOutput:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "// Champagne Tower\n// Leetcode: https://leetcode.com/problems/champagne-tower/\n\nclass Solution {\n public double champagneTower(int poured, int query_row, int query_glass) {\n if (poured == 0) return 0;\n double[] memo = new double[101];\n memo[0] = poured;\n for (int i=0; i<100; i++) {\n for (int j=i; j>=0; j--) {\n if (memo[j] > 1) {\n if (i == query_row && j == query_glass) return 1;\n double val = (memo[j] - 1) / 2;\n memo[j+1] += val;\n memo[j] = val;\n } else {\n if (i == query_row && j == query_glass) return memo[query_glass];\n memo[j+1] += 0;\n memo[j] = 0;\n }\n }\n }\n return memo[query_glass];\n }\n}\n", + "title": "799. Champagne Tower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100 th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the j th glass in the i th row is (both i and j are 0-indexed.)", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png" + ], + "constraints": [ + "0 <= poured <= 10^9", + "0 <= query_glass <= query_row < 100" + ], + "examples": [ + { + "text": "Example 1: Input:poured = 1, query_row = 1, query_glass = 1\nOutput:0.00000\nExplanation:We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.", + "image": null + }, + { + "text": "Example 2: Input:poured = 2, query_row = 1, query_glass = 1\nOutput:0.50000\nExplanation:We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.", + "image": null + }, + { + "text": "Example 3: Input:poured = 100000009, query_row = 33, query_glass = 17\nOutput:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 392 ms (Top 9.30%) | Memory: 14.4 MB (Top 11.38%)\nclass Solution:\n def champagneTower(self, poured: int, r: int, c: int) -> float:\n quantity=defaultdict(int)\n quantity[(0,0)]=poured\n for i in range(r+1):\n flag=False\n for j in range(i+1):\n prev_flow=quantity[(i,j)]-1\n if prev_flow<=0:\n continue\n flag=True\n quantity[(i,j)]=1\n quantity[(i+1,j)]+=prev_flow/2\n quantity[(i+1,j+1)]+=prev_flow/2\n if not flag: break\n return quantity[(r,c)]\n", + "title": "799. Champagne Tower", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter . Your goal is to satisfy one of the following three conditions: Return the minimum number of operations needed to achieve your goal.", + "description_images": [], + "constraints": [ + "Every letter in a is strictly less than every letter in b in the alphabet.", + "Every letter in b is strictly less than every letter in a in the alphabet.", + "Both a and b consist of only one distinct letter." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"caa\"\nOutput:2\nExplanation:Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).", + "image": null + }, + { + "text": "Example 2: Input:a = \"dabadd\", b = \"cda\"\nOutput:3\nExplanation:The best way is to make condition 1 true by changing b to \"eee\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 27.1%) | Memory: 44.54 MB (Top 34.2%)\n\nclass Solution {\n public int minCharacters(String a, String b) {\n int[] aCount = new int[26];\n int aMax = 0;\n for (int i = 0; i < a.length(); i++) {\n aCount[a.charAt(i) - 'a']++;\n aMax = Math.max(aMax, aCount[a.charAt(i) - 'a']);\n }\n \n int[] bCount = new int[26];\n int bMax = 0;\n for (int i = 0; i < b.length(); i++) {\n bCount[b.charAt(i) - 'a']++;\n bMax = Math.max(bMax, bCount[b.charAt(i) - 'a']);\n }\n int condition3 = a.length() - aMax + b.length() - bMax;\n \n int globalMin = condition3;\n \n int aTillCurrent = 0;\n int bTillCurrent = 0;\n for (int i = 0; i < 25; i++) {\n aTillCurrent += aCount[i];\n bTillCurrent += bCount[i];\n globalMin = Math.min(globalMin, bTillCurrent + a.length() - aTillCurrent);\n globalMin = Math.min(globalMin, aTillCurrent + b.length() - bTillCurrent);\n }\n \n \n \n return globalMin;\n }\n}", + "title": "1737. Change Minimum Characters to Satisfy One of Three Conditions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter . Your goal is to satisfy one of the following three conditions: Return the minimum number of operations needed to achieve your goal.", + "description_images": [], + "constraints": [ + "Every letter in a is strictly less than every letter in b in the alphabet.", + "Every letter in b is strictly less than every letter in a in the alphabet.", + "Both a and b consist of only one distinct letter." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"caa\"\nOutput:2\nExplanation:Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).", + "image": null + }, + { + "text": "Example 2: Input:a = \"dabadd\", b = \"cda\"\nOutput:3\nExplanation:The best way is to make condition 1 true by changing b to \"eee\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 115 ms (Top 83.64%) | Memory: 17.50 MB (Top 38.79%)\n\nclass Solution:\n def minCharacters(self, a: str, b: str) -> int:\n pa, pb = [0]*26, [0]*26\n for x in a: pa[ord(x)-97] += 1\n for x in b: pb[ord(x)-97] += 1\n \n ans = len(a) - max(pa) + len(b) - max(pb) # condition 3\n for i in range(25): \n pa[i+1] += pa[i]\n pb[i+1] += pb[i]\n ans = min(ans, pa[i] + len(b) - pb[i]) # condition 2\n ans = min(ans, len(a) - pa[i] + pb[i]) # condition 1\n return ans \n", + "title": "1737. Change Minimum Characters to Satisfy One of Three Conditions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= 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" + ], + "examples": [ + { + "text": "Example 1: 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\nOutput:700\nExplanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png" + }, + { + "text": "Example 2: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput:200\nExplanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png" + }, + { + "text": "Example 3: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput:500\nExplanation:The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n // Initialize Prices arr with infinity & src 0\n int[] prices = new int[n];\n for(int i = 0; i < n; i++)\n prices[i] = Integer.MAX_VALUE;\n prices[src] = 0;\n \n // Build Adj list {key: src | val: dst+price}\n Map> flightsMap = new HashMap<>();\n for(int[] flight : flights){\n int flightSrc = flight[0];\n int flightDst = flight[1];\n int flightPrice = flight[2];\n \n List flightsList = flightsMap.getOrDefault(flightSrc, new ArrayList<>());\n flightsList.add(new int[]{flightDst, flightPrice});\n flightsMap.put(flightSrc, flightsList);\n }\n \n // Start Bellman ford Algo\n Queue q = new LinkedList<>();\n q.offer(src);\n while(k >= 0 && !q.isEmpty()){\n int[] tempPrices = new int[n]; // Temporary Prices Arr\n for(int i = 0; i < n; i++)\n tempPrices[i] = prices[i];\n \n int size = q.size();\n for(int i = 0; i < size; i++){\n int curSrc = q.poll();\n int curPrice = prices[curSrc];\n List curFlightsList = flightsMap.getOrDefault(curSrc, new ArrayList<>());\n for(int[] flight : curFlightsList){\n int flightDst = flight[0];\n int flightPrice = flight[1];\n int newPrice = curPrice + flightPrice;\n if(newPrice < tempPrices[flightDst]){\n tempPrices[flightDst] = newPrice;\n q.offer(flightDst);\n }\n }\n }\n for(int i = 0; i < n; i++) // Copy Temp Prices to Original Price Arr\n prices[i] = tempPrices[i];\n k--;\n }\n int totalPrice = prices[dst];\n return totalPrice == Integer.MAX_VALUE? -1 : totalPrice;\n }\n}\n", + "title": "787. Cheapest Flights Within K Stops", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= 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" + ], + "examples": [ + { + "text": "Example 1: 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\nOutput:700\nExplanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png" + }, + { + "text": "Example 2: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput:200\nExplanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png" + }, + { + "text": "Example 3: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput:500\nExplanation:The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n\t\tgraph = defaultdict(list)\n\t\tfor u,v,w in flights: graph[u].append((v,w))\n\n\t\tpq = [(0,src,0)]\n\t\tdis = [float('inf')]*n\n\n\t\twhile pq:\n\t\t\tc,n,l = heappop(pq)\n\t\t\tif n==dst: return c\n\t\t\tif l > k or l>= dis[n]: continue\n\t\t\tdis[n] = l\n\t\t\tfor v,w in graph[n]:\n\t\t\t\theappush(pq,(c+w,v,l+1))\n\t\treturn -1\n", + "title": "787. Cheapest Flights Within K Stops", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces , where the integers in pieces are distinct . Your goal is to form arr by concatenating the arrays in pieces in any order . However, you are not allowed to reorder the integers in each array pieces[i] . Return true if it is possible to form the array arr from pieces . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= pieces.length <= arr.length <= 100", + "sum(pieces[i].length) == arr.length", + "1 <= pieces[i].length <= arr.length", + "1 <= arr[i], pieces[i][j] <= 100", + "The integers in arr are distinct .", + "The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [15,88], pieces = [[88],[15]]\nOutput:true\nExplanation:Concatenate [15] then [88]", + "image": null + }, + { + "text": "Example 2: Input:arr = [49,18,16], pieces = [[16,18,49]]\nOutput:false\nExplanation:Even though the numbers match, we cannot reorder pieces[0].", + "image": null + }, + { + "text": "Example 3: Input:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput:true\nExplanation:Concatenate [91] then [4,64] then [78]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFormArray(int[] arr, int[][] pieces) {\n HashMap hm = new HashMap();\n for(int[] list:pieces)\n hm.put(list[0],list);\n \n int index = 0;\n while(index=arr.length || val!=arr[index])\n return false;\n index++;\n }\n }\n return true;\n }\n}\n", + "title": "1640. Check Array Formation Through Concatenation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces , where the integers in pieces are distinct . Your goal is to form arr by concatenating the arrays in pieces in any order . However, you are not allowed to reorder the integers in each array pieces[i] . Return true if it is possible to form the array arr from pieces . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= pieces.length <= arr.length <= 100", + "sum(pieces[i].length) == arr.length", + "1 <= pieces[i].length <= arr.length", + "1 <= arr[i], pieces[i][j] <= 100", + "The integers in arr are distinct .", + "The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [15,88], pieces = [[88],[15]]\nOutput:true\nExplanation:Concatenate [15] then [88]", + "image": null + }, + { + "text": "Example 2: Input:arr = [49,18,16], pieces = [[16,18,49]]\nOutput:false\nExplanation:Even though the numbers match, we cannot reorder pieces[0].", + "image": null + }, + { + "text": "Example 3: Input:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput:true\nExplanation:Concatenate [91] then [4,64] then [78]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n keys, ans = {}, []\n for piece in pieces:\n keys[piece[0]] = piece\n for a in arr:\n if a in keys:\n ans.extend(keys[a])\n return ''.join(map(str, arr)) == ''.join(map(str, ans))\n", + "title": "1640. Check Array Formation Through Concatenation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a complete binary tree . In a complete binary tree , every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:true\nExplanation:Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,null,7]\nOutput:false\nExplanation:The node with value 7 isn't as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 49.17%) | Memory: 42.4 MB (Top 73.50%)\nclass Solution {\n public boolean isCompleteTree(TreeNode root) {\n boolean end = false;\n Queue queue = new LinkedList<>();\n queue.offer(root);\n while(!queue.isEmpty()) {\n TreeNode currentNode = queue.poll();\n if(currentNode == null) {\n end = true;\n } else {\n if(end) {\n return false;\n }\n queue.offer(currentNode.left);\n queue.offer(currentNode.right);\n }\n }\n return true;\n }\n}", + "title": "958. Check Completeness of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, determine if it is a complete binary tree . In a complete binary tree , every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:true\nExplanation:Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,null,7]\nOutput:false\nExplanation:The node with value 7 isn't as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n\t\t# if not root: return True\n\t\tdef node_count(root):\n\t\t\tif not root: return 0\n\t\t\treturn 1 + node_count(root.left) + node_count(root.right)\n\n\t\tdef isCBT(root,i,count):\n\t\t\tif not root: return True\n\t\t\tif i>=count: return False\n\t\t\treturn isCBT(root.left,2*i+1,count) and isCBT(root.right,2*i+2,count)\n\n\n\t\treturn isCBT(root,0,node_count(root))", + "title": "958. Check Completeness of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false .", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"\nOutput:true\nExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"\nOutput:true\nExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"\nOutput:false\nExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 30.84%) | Memory: 44.80 MB (Top 40.5%)\n\nclass Solution {\n public boolean canBeValid(String s, String locked) {\n int n = s.length();\n if (n % 2 != 0) return false;\n \n int possibleOpens = 0;\n int fixedCloses = 0;\n \n for (int i = 0; i < n; i ++) {\n if (s.charAt(i) == '(' || locked.charAt(i) == '0') {\n possibleOpens++;\n } else {\n fixedCloses++;\n }\n \n if (fixedCloses > possibleOpens) return false;\n }\n \n int possibleCloses = 0;\n int fixedOpens = 0;\n \n for (int i = n - 1; i >= 0; i--) {\n if (s.charAt(i) == ')' || locked.charAt(i) == '0') {\n possibleCloses++;\n } else {\n fixedOpens++;\n }\n \n if (fixedOpens > possibleCloses) return false;\n }\n \n return true;\n }\n}\n", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false .", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"\nOutput:true\nExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"\nOutput:true\nExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"\nOutput:false\nExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canBeValid(String s, String locked) {\n int n = s.length();\n if (n % 2 != 0) return false;\n \n int possibleOpens = 0;\n int fixedCloses = 0;\n \n for (int i = 0; i < n; i ++) {\n if (s.charAt(i) == '(' || locked.charAt(i) == '0') {\n possibleOpens++;\n } else {\n fixedCloses++;\n }\n \n if (fixedCloses > possibleOpens) return false;\n }\n \n int possibleCloses = 0;\n int fixedOpens = 0;\n \n for (int i = n - 1; i >= 0; i--) {\n if (s.charAt(i) == ')' || locked.charAt(i) == '0') {\n possibleCloses++;\n } else {\n fixedOpens++;\n }\n \n if (fixedOpens > possibleCloses) return false;\n }\n \n return true;\n }\n}\n", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false .", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"\nOutput:true\nExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"\nOutput:true\nExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"\nOutput:false\nExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 460 ms (Top 26.24%) | Memory: 15.4 MB (Top 86.61%)\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n def validate(s: str, locked: str, op: str) -> bool:\n bal, wild = 0, 0\n for i in range(len(s)):\n if locked[i] == \"1\":\n bal += 1 if s[i] == op else -1\n else:\n wild += 1\n if wild + bal < 0:\n return False\n return bal <= wild\n return len(s) % 2 == 0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')')", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n ) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1 .", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "1 <= n <= 10^5", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"abc\", s2 = \"xya\"\nOutput:true\nExplanation:\"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abe\", s2 = \"acd\"\nOutput:false\nExplanation:All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"leetcodee\", s2 = \"interview\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkIfCanBreak(String s1, String s2) {\n int n = s1.length();\n char[] one = s1.toCharArray();\n char[] two = s2.toCharArray();\n Arrays.sort(one);\n Arrays.sort(two);\n if(check(one,two,n) || check(two,one,n)){\n return true;\n }\n return false;\n }\n public boolean check(char[] one,char[] two,int n){\n for(int i=0;itwo[i]-'a'){\n return false;\n }\n }\n return true;\n }\n}", + "title": "1433. Check If a String Can Break Another String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n ) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1 .", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "1 <= n <= 10^5", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"abc\", s2 = \"xya\"\nOutput:true\nExplanation:\"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abe\", s2 = \"acd\"\nOutput:false\nExplanation:All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"leetcodee\", s2 = \"interview\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n s1, s2 = sorted(s1), sorted(s2)\n return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2))\n", + "title": "1433. Check If a String Can Break Another String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s and an integer k , return true if every binary code of length k is a substring of s . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s[i] is either '0' or '1' .", + "1 <= k <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110110\", k = 2\nOutput:true\nExplanation:The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0110\", k = 1\nOutput:true\nExplanation:The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"0110\", k = 2\nOutput:false\nExplanation:The binary code \"00\" is of length 2 and does not exist in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean hasAllCodes(String s, int k) {\n HashSet hs=new HashSet();\n for(int i=0;i<=s.length()-k;i++){\n hs.add(s.substring(i,i+k));\n }\n if(hs.size() == Math.pow(2,k))return true;\n return false;\n }\n}\n", + "title": "1461. Check If a String Contains All Binary Codes of Size K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary string s and an integer k , return true if every binary code of length k is a substring of s . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s[i] is either '0' or '1' .", + "1 <= k <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110110\", k = 2\nOutput:true\nExplanation:The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0110\", k = 1\nOutput:true\nExplanation:The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"0110\", k = 2\nOutput:false\nExplanation:The binary code \"00\" is of length 2 and does not exist in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n \n Z = set()\n\n for i in range(len(s)-k+1):\n Z.add(s[i:i+k])\n \n if len(Z) == 2**k:\n return True\n\n return False", + "title": "1461. Check If a String Contains All Binary Codes of Size K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sentence that consists of some words separated by a single space , and a searchWord , check if searchWord is a prefix of any word in sentence . Return the index of the word in sentence ( 1-indexed ) where searchWord is a prefix of this word . If searchWord is a prefix of more than one word, return the index of the first word (minimum index) . If there is no such word return -1 . A prefix of a string s is any leading contiguous substring of s .", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 100", + "1 <= searchWord.length <= 10", + "sentence consists of lowercase English letters and spaces.", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"i love eating burger\", searchWord = \"burg\"\nOutput:4\nExplanation:\"burg\" is prefix of \"burger\" which is the 4th word in the sentence.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"this problem is an easy problem\", searchWord = \"pro\"\nOutput:2\nExplanation:\"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"i am tired\", searchWord = \"you\"\nOutput:-1\nExplanation:\"you\" is not a prefix of any word in the sentence.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 44.68%) | Memory: 41.8 MB (Top 51.62%)\nclass Solution {\n public int isPrefixOfWord(String sentence, String searchWord) {\n if(!sentence.contains(searchWord))\n return -1;\n boolean y=false;\n String[] str=sentence.split(\" \");\n\n for(int i=0;i bool:\n pre = -k - 1\n for i, v in enumerate(nums):\n if v:\n if i - pre < k + 1:\n return False\n else:\n pre = i\n return True\n \n", + "title": "1437. Check If All 1's Are at Least Length K Places Away", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of only the characters 'a' and 'b' , return true if every 'a' appears before every 'b' in the string . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"\nOutput:true\nExplanation:The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\"\nOutput:false\nExplanation:There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbb\"\nOutput:true\nExplanation:There are no 'a's, hence, every 'a' appears before every 'b' and we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkString(String s) {\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'b'){\n for(int j = i+1; j < s.length(); j++){\n if(s.charAt(j) == 'a'){\n return false;\n }\n }\n }\n }\n return true;\n }\n}\n", + "title": "2124. Check if All A's Appears Before All B's", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s consisting of only the characters 'a' and 'b' , return true if every 'a' appears before every 'b' in the string . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"\nOutput:true\nExplanation:The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\"\nOutput:false\nExplanation:There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbb\"\nOutput:true\nExplanation:There are no 'a's, hence, every 'a' appears before every 'b' and we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkString(self, s: str) -> bool:\n if \"ba\" in s:\n return False\n else:\n return True\n", + "title": "2124. Check if All A's Appears Before All B's", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return true if s is a good string, or false otherwise . A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abacbc\"\nOutput:true\nExplanation:The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabb\"\nOutput:false\nExplanation:The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean areOccurrencesEqual(String s) {\n int[] freq = new int[26];\n \n for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++;\n\n int val = freq[s.charAt(0) - 'a'];\n for (int i = 0; i < 26; i++)\n if (freq[i] != 0 && freq[i] != val) return false; \n\n return true;\n }\n}\n", + "title": "1941. Check if All Characters Have Equal Number of Occurrences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return true if s is a good string, or false otherwise . A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abacbc\"\nOutput:true\nExplanation:The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabb\"\nOutput:false\nExplanation:The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n", + "title": "1941. Check if All Characters Have Equal Number of Occurrences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array ranges and two integers left and right . Each ranges[i] = [start i , end i ] represents an inclusive interval between start i and end i . Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges . Return false otherwise . An integer x is covered by an interval ranges[i] = [start i , end i ] if start i <= x <= end i .", + "description_images": [], + "constraints": [ + "1 <= ranges.length <= 50", + "1 <= start i <= end i <= 50", + "1 <= left <= right <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput:true\nExplanation:Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.", + "image": null + }, + { + "text": "Example 2: Input:ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput:false\nExplanation:21 is not covered by any range.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 85.31%) | Memory: 41.7 MB (Top 83.50%)\nclass Solution {\n public boolean isCovered(int[][] ranges, int left, int right) {\n boolean flag = false;\n for (int i=left; i<=right; i++) {\n for (int[] arr: ranges) {\n if (i >= arr[0] && i <= arr[1]) {\n flag = true;\n break;\n }\n }\n if (!flag) return false;\n flag = false;\n }\n\n return true;\n }\n}", + "title": "1893. Check if All the Integers in a Range Are Covered", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array ranges and two integers left and right . Each ranges[i] = [start i , end i ] represents an inclusive interval between start i and end i . Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges . Return false otherwise . An integer x is covered by an interval ranges[i] = [start i , end i ] if start i <= x <= end i .", + "description_images": [], + "constraints": [ + "1 <= ranges.length <= 50", + "1 <= start i <= end i <= 50", + "1 <= left <= right <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput:true\nExplanation:Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.", + "image": null + }, + { + "text": "Example 2: Input:ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput:false\nExplanation:21 is not covered by any range.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n \n \n t=[0]*(60)\n \n for i in ranges:\n \n t[i[0]]+=1\n t[i[1]+1]-=1\n \n for i in range(1,len(t)):\n t[i] += t[i-1]\n \n return min(t[left:right+1])>=1\n \n \n \n \n \n", + "title": "1893. Check if All the Integers in a Range Are Covered", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An original string, consisting of lowercase English letters, can be encoded by the following steps: For example, one way to encode an original string \"abcdefghijklmnop\" might be: Given two encoded strings s1 and s2 , consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2 . Otherwise, return false . Note : The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3 .", + "description_images": [], + "constraints": [ + "Arbitrarily split it into a sequence of some number of non-empty substrings.", + "Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).", + "Concatenate the sequence as the encoded string." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"internationalization\", s2 = \"i18n\"\nOutput:true\nExplanation:It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n -> Split: [\"internationalization\"]\n -> Do not replace any element\n -> Concatenate: \"internationalization\", which is s1.\n- \"internationalization\"\n -> Split: [\"i\", \"nternationalizatio\", \"n\"]\n -> Replace: [\"i\", \"18\", \"n\"]\n -> Concatenate: \"i18n\", which is s2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"l123e\", s2 = \"44\"\nOutput:true\nExplanation:It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n -> Split: [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n -> Replace: [\"l\", \"1\", \"2\", \"3\", \"e\"]\n -> Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n -> Split: [\"leet\", \"code\"]\n -> Replace: [\"4\", \"4\"]\n -> Concatenate: \"44\", which is s2.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a5b\", s2 = \"c5b\"\nOutput:false\nExplanation:It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 624 ms (Top 51.93%) | Memory: 473.4 MB (Top 35.91%)\n/**\nCases:\n\ndiff > 0 meaning we need to pick more chars in s1\ndiff < 0 meaning we need to pick more chars in s2\n\n-1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999\n\n1. s1[i] == s2[j] and diff = 0\n increment i+1 and j+1\n\n2. if s1[i] is not digit and diff > 0 then increment i i+1, diff\n3. if s2[j] is not digit and diff < 0 then increment j j+1, diff\n4. if s1[i] is digit then get digit value and decrement diff val as we have covered such chars in the s1 string\n and increment i i+1, diff-val\n5. if s2[j] is digit then get digit value and increment diff val as we need to cover such chars in the s2 string and\n increment j, j+1, diff+val\n\n 01234\ns1 = l123e\ns2 = 44\n\ni: 0\nj: 0\ndiff: 0\n // Wildcard matching on s2[j]\n val = 4, diff = 0+4 j = 1\n\n i: 0\n j: 1\n diff: 4\n // Literal matching on s1[i]\n increment ith pointer as ith is a literal and we can move on to next char in s1 and decrement diff\n\n i: 1\n j: 1\n diff: 3\n // Wildcard matching on s1[i]\n val = 1 diff = 3-1 = 2 increment i\n\n i: 2\n j: 1\n diff: 2\n // Wildcard matching on s1[i]\n val = 2 diff = 2-2 = 0 increment i\n\n i: 3\n j: 1\n diff: 0\n // Wildcard matching on s1[i]\n val=3 diff = 0-3 = -3, increment i\n\n i: 4\n j: 1\n diff: -3\n // Wildcard matching on s2[j]\n val = 4 diff = -3+4 =1 increment j\n\n i: 4\n j: 2\n diff: 1\n // Literal matching on s1[i]\n decrement i-1 and increment i\n\n i=5\n j=2\n diff==0 return true\n dp[4][2][1] = true\n return true\n return dp[4][1][1000-3] = true\n return dp[3][1][0] = true\n\n i: 2\n j: 1\n diff: 2\n return dp[2][1][2] = true\n return true\n\n i: 0\n j: 1\n diff: 4\n return dp[0][1][4] = true\n return true\n*/\n\nclass Solution {\n //112ms\n public boolean possiblyEquals(String s1, String s2) {\n return helper(s1.toCharArray(), s2.toCharArray(), 0, 0, 0, new Boolean[s1.length()+1][s2.length()+1][2001]);\n }\n\n boolean helper(char[] s1, char[] s2, int i, int j, int diff, Boolean[][][] dp) {\n if(i == s1.length && j == s2.length) {\n return diff == 0;\n }\n\n if(dp[i][j][diff+1000] != null)\n return dp[i][j][diff+1000];\n\n // if both i and j are at the same location and chars are same then simply increment both pointers\n if(i < s1.length && j < s2.length && diff == 0 && s1[i] == s2[j]) {\n if(helper(s1, s2, i+1, j+1, diff, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // if s1[i] is literal and diff > 0 then increment i and decrement diff by 1\n if(i < s1.length && !Character.isDigit(s1[i]) && diff > 0 && helper(s1, s2, i+1, j, diff-1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // if s2[j] is literal and diff < 0 then increment j and increment diff by 1\n // as we are done with the current jth char\n if(j < s2.length && !Character.isDigit(s2[j]) && diff < 0 && helper(s1, s2, i, j+1, diff+1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // wildcard matching in s1\n // if s1 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = i, val = 0; k < i + 4 && k < s1.length && Character.isDigit(s1[k]); k++) {\n val = val * 10 + s1[k] -'0';\n if(helper(s1, s2, k+1, j, diff-val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // wildcard matching in s2\n // if s2 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = j, val = 0; k < j + 4 && k < s2.length && Character.isDigit(s2[k]); k++) {\n val = val * 10 + s2[k] -'0';\n if(helper(s1, s2, i, k+1, diff+val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n return dp[i][j][diff+1000] = false;\n }\n}", + "title": "2060. Check if an Original String Exists Given Two Encoded Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An original string, consisting of lowercase English letters, can be encoded by the following steps: For example, one way to encode an original string \"abcdefghijklmnop\" might be: Given two encoded strings s1 and s2 , consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2 . Otherwise, return false . Note : The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3 .", + "description_images": [], + "constraints": [ + "Arbitrarily split it into a sequence of some number of non-empty substrings.", + "Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).", + "Concatenate the sequence as the encoded string." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"internationalization\", s2 = \"i18n\"\nOutput:true\nExplanation:It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n -> Split: [\"internationalization\"]\n -> Do not replace any element\n -> Concatenate: \"internationalization\", which is s1.\n- \"internationalization\"\n -> Split: [\"i\", \"nternationalizatio\", \"n\"]\n -> Replace: [\"i\", \"18\", \"n\"]\n -> Concatenate: \"i18n\", which is s2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"l123e\", s2 = \"44\"\nOutput:true\nExplanation:It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n -> Split: [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n -> Replace: [\"l\", \"1\", \"2\", \"3\", \"e\"]\n -> Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n -> Split: [\"leet\", \"code\"]\n -> Replace: [\"4\", \"4\"]\n -> Concatenate: \"44\", which is s2.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a5b\", s2 = \"c5b\"\nOutput:false\nExplanation:It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1026 ms (Top 83.52%) | Memory: 55.5 MB (Top 82.18%)\nfrom functools import lru_cache\nclass Solution:\n def possiblyEquals(self, s1: str, s2: str) -> bool:\n\n def getValidPrefixLength(s,start):\n end = start\n while end < len(s) and s[end].isdigit(): end += 1\n return end\n\n @lru_cache(None)\n def possibleLengths(s):\n \"\"\"Return all possible lengths represented by numeric string s.\"\"\"\n ans = {int(s)}\n for i in range(1, len(s)):\n # add all lengths by splitting numeric string s at i\n ans |= {x+y for x in possibleLengths(s[:i]) for y in possibleLengths(s[i:])}\n return ans\n\n @lru_cache(None)\n def dp(i, j, diff):\n \"\"\"Return True if s1[i:] matches s2[j:] with given differences.\"\"\"\n\n # If both have reached end return true if none of them are leading\n if i == len(s1) and j == len(s2): return diff == 0\n\n # s1 has not reached end and s1 starts with a digit\n if i < len(s1) and s1[i].isdigit():\n i2 = getValidPrefixLength(s1,i)\n for L in possibleLengths(s1[i:i2]):\n # substract since lead of s2 decreases by L\n if dp(i2, j, diff-L): return True\n\n # s2 has not reached end and s2 starts with a digit\n elif j < len(s2) and s2[j].isdigit():\n j2 = getValidPrefixLength(s2,j)\n for L in possibleLengths(s2[j:j2]):\n # add since lead of s2 increase by L\n if dp(i, j2, diff+L): return True\n\n # if none of them have integer prefix or a lead over the other\n elif diff == 0:\n # if only one of them has reached end or current alphabets are not the same\n if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False\n # skip same alphabets\n return dp(i+1, j+1, 0)\n\n # if none of them have integer prefix & s2 lead over s1\n elif diff > 0:\n # no s1 to balance s2's lead\n if i == len(s1): return False\n # move s1 pointer forward and reduce diff\n return dp(i+1, j, diff-1)\n\n # if none of them have integer prefix & s1 lead over s2\n else:\n # no s2 to balance s1's lead\n if j == len(s2): return False\n # move s2 pointer forward and increase diff\n return dp(i, j+1, diff+1)\n\n # start with starts of both s1 and s2 with no lead by any of them\n return dp(0, 0, 0)", + "title": "2060. Check if an Original String Exists Given Two Encoded Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:true\nExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]\nOutput:false\nExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:true\nExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 54.56%)\nclass Solution {\n public boolean check(int[] nums) {\n // here we compare all the neighbouring elemnts and check whether they are in somewhat sorted\n // there will be a small change due to rotation in the array at only one place.\n // so if there are irregularities more than once, return false\n // else return true;\n int irregularities = 0;\n int length = nums.length;\n for (int i=0; i nums[(i + 1) % length])\n irregularities += 1;\n }\n return irregularities > 1 ? false : true;\n }\n}", + "title": "1752. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:true\nExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]\nOutput:false\nExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:true\nExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def check(self, num: List[int]) -> bool:\n ct=0\n for i in range(1,len(num)):\n if num[i-1]>num[i]:\n ct+=1\n if num[len(num)-1]>num[0]:\n ct+=1\n return ct<=1", + "title": "1752. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr of even length n and an integer k . We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k . Return true If you can find a way to do that or false otherwise .", + "description_images": [], + "constraints": [ + "arr.length == n", + "1 <= n <= 10^5", + "n is even.", + "-10^9 <= arr[i] <= 10^9", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput:true\nExplanation:Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5,6], k = 7\nOutput:true\nExplanation:Pairs are (1,6),(2,5) and(3,4).", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6], k = 10\nOutput:false\nExplanation:You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 78.2%) | Memory: 60.02 MB (Top 5.2%)\n\nclass Solution {\n public boolean canArrange(int[] arr, int k) {\n int[] frequency = new int[k];\n for(int num : arr){\n num %= k;\n if(num < 0) num += k;\n frequency[num]++;\n }\n if(frequency[0]%2 != 0) return false;\n \n for(int i = 1; i <= k/2; i++)\n if(frequency[i] != frequency[k-i]) return false;\n\t\t\t\n return true;\n }\n}", + "title": "1497. Check If Array Pairs Are Divisible by k", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of integers arr of even length n and an integer k . We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k . Return true If you can find a way to do that or false otherwise .", + "description_images": [], + "constraints": [ + "arr.length == n", + "1 <= n <= 10^5", + "n is even.", + "-10^9 <= arr[i] <= 10^9", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput:true\nExplanation:Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5,6], k = 7\nOutput:true\nExplanation:Pairs are (1,6),(2,5) and(3,4).", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6], k = 10\nOutput:false\nExplanation:You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 556 ms (Top 81.4%) | Memory: 30.00 MB (Top 97.8%)\n\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[1]\n #since we have odd number of complimenting residues,\n #we should also care about residue=0 and residue=k//2\n \n i,j =1,k-1\n pairs = 0\n while i0 and i==j:\n pairs+=count[i]/2\n pairs+= count[0]/2\n n = len(arr)\n return pairs == n//2", + "title": "1497. Check If Array Pairs Are Divisible by k", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s ​​​​​without leading zeros , return true ​​​ if s contains at most one contiguous segment of ones . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] ​​​​ is either '0' or '1' .", + "s[0] is '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001\"\nOutput:false\nExplanation:The ones do not form a contiguous segment.", + "image": null + }, + { + "text": "Example 2: Input:s = \"110\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkOnesSegment(String s) {\n return !s.contains(\"01\");\n }\n}\n", + "title": "1784. Check if Binary String Has at Most One Segment of Ones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary string s ​​​​​without leading zeros , return true ​​​ if s contains at most one contiguous segment of ones . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] ​​​​ is either '0' or '1' .", + "s[0] is '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001\"\nOutput:false\nExplanation:The ones do not form a contiguous segment.", + "image": null + }, + { + "text": "Example 2: Input:s = \"110\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 66.03%) | Memory: 13.8 MB (Top 52.02%)\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return \"01\" not in s", + "title": "1784. Check if Binary String Has at Most One Segment of Ones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n ( inclusive ). Given an n x n integer matrix matrix , return true if the matrix is valid . Otherwise, return false .", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 100", + "1 <= matrix[i][j] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[3,1,2],[2,3,1]]\nOutput:true\nExplanation:In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/example1drawio.png" + }, + { + "text": "Example 2: Input:matrix = [[1,1,1],[1,2,3],[1,2,3]]\nOutput:false\nExplanation:In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 50.77%) | Memory: 92.4 MB (Top 46.57%)\nclass Solution {\n public boolean checkValid(int[][] matrix) {\n int n = matrix.length;\n int num = (n*(n+1))/2; // SUM of n number 1 to n;\n\n for(int i=0; i hs = new HashSet();\n HashSet hs1 = new HashSet();\n\n int m = num; int k = num;\n\n for(int j = 0; j bool:\n lst = [0]*len(matrix)\n for i in matrix:\n if len(set(i)) != len(matrix):\n return False\n for j in range(len(i)):\n lst[j] += i[j]\n return len(set(lst)) == 1\n", + "title": "2133. Check if Every Row and Column Contains All Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of positive integers. Your task is to select some subset of nums , multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [12,5,7,23]\nOutput:true\nExplanation:Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [29,6,10]\nOutput:true\nExplanation:Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,6]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isGoodArray(int[] nums) {\n int gcd = nums[0];\n for(int i =1; i bool:\n def gcd(a,b):\n while a:\n a, b = b%a, a\n return b\n return reduce(gcd,nums)==1", + "title": "1250. Check If It Is a Good Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array coordinates , coordinates[i] = [x, y] , where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/15/untitled-diagram-2.jpg", + "https://assets.leetcode.com/uploads/2019/10/09/untitled-diagram-1.jpg" + ], + "constraints": [ + "2 <= coordinates.length <= 1000", + "coordinates[i].length == 2", + "-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4", + "coordinates contains no duplicate point." + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkStraightLine(int[][] coordinates) {\n int x1=coordinates[0][0];\n int y1=coordinates[0][1];\n \n int x2=coordinates[1][0];\n int y2=coordinates[1][1];\n \n float slope;\n if(x2-x1 == 0)\n {\n slope=Integer.MAX_VALUE;\n }\n else\n {\n slope=(y2-y1)/(float)(x2-x1);\n }\n for(int i=0;i bool:\n n = len(grid)\n for i in range(n):\n for j in range(n):\n if i==j or (i+j) ==n-1:\n if grid[i][j] == 0:\n return False\n elif grid[i][j] != 0: \n return False\n return True;\n", + "title": "2319. Check if Matrix Is X-Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 8 x 8 grid board , where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.' , white cells are represented by 'W' , and black cells are represented by 'B' . Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color , and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal .", + "description_images": [], + "constraints": [ + "board.length == board[r].length == 8", + "0 <= rMove, cMove < 8", + "board[rMove][cMove] == '.'", + "color is either 'B' or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\nOutput:true\nExplanation:'.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid11.png" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\nOutput:false\nExplanation:While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.24 MB (Top 69.6%)\n\nclass Solution {\n public boolean checkMove(char[][] board, int rMove, int cMove, char color) {\n\n int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};\n\n for(int[] d : direction)\n {\n if(dfs(board,rMove,cMove,color,d,1))\n return true;\n }\n return false;\n }\n\n public boolean dfs(char[][] board, int r, int c, char color,int[] direcn,int len)\n {\n\n int nr = r + direcn[0];\n int nc = c + direcn[1];\n\n if( nr<0 || nc<0 || nr>7 || nc>7) return false;\n\n if(board[nr][nc] == color)\n {\n if(len>=2) return true;\n else\n return false;\n }\n else\n {\n if(board[nr][nc] == '.')\n { \n return false;\n }\n return dfs(board,nr,nc,color,direcn,len+1);\n }\n }\n}", + "title": "1958. Check if Move is Legal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 8 x 8 grid board , where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.' , white cells are represented by 'W' , and black cells are represented by 'B' . Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color , and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal .", + "description_images": [], + "constraints": [ + "board.length == board[r].length == 8", + "0 <= rMove, cMove < 8", + "board[rMove][cMove] == '.'", + "color is either 'B' or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\nOutput:true\nExplanation:'.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid11.png" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\nOutput:false\nExplanation:While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 82 ms (Top 35.62%) | Memory: 14 MB (Top 54.79%)\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n directions = [False] * 8\n moves = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),\n (-1, -1), (0, -1), (1, -1)]\n opposite_color = \"W\" if color == \"B\" else \"B\"\n\n for d in range(8):\n r, c = rMove + moves[d][0], cMove + moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite_color:\n directions[d] = True\n\n for step in range(2, 8):\n if not any(d for d in directions):\n return False\n for d in range(8):\n if directions[d]:\n r, c = rMove + step * moves[d][0], cMove + step * moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8:\n if board[r][c] == color:\n return True\n elif board[r][c] == \".\":\n directions[d] = False\n else:\n directions[d] = False\n return False", + "title": "1958. Check if Move is Legal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M ). More formally check if there exists two indices i and j such that :", + "description_images": [], + "constraints": [ + "i != j", + "0 <= i, j < arr.length", + "arr[i] == 2 * arr[j]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,2,5,3]\nOutput:true\nExplanation:N= 10is the double of M= 5,that is,10 = 2 * 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,1,14,11]\nOutput:true\nExplanation:N= 14is the double of M= 7,that is,14 = 2 * 7.", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,1,7,11]\nOutput:false\nExplanation:In this case does not exist N and M, such that N = 2 * M.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 76.57%) | Memory: 42.30 MB (Top 45.56%)\n\nclass Solution {\n public boolean checkIfExist(int[] arr) {\n\t int n = arr.length;\n for (int i = 0; i < n; i++) \n for (int j = 0; j < n; j++) \n if (i != j && arr[i] == 2 * arr[j]) \n return true;\n\n return false;\n }\n}\n\n// TC: O(n ^ 2), SC: O(1)\n", + "title": "1346. Check If N and Its Double Exist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M ). More formally check if there exists two indices i and j such that :", + "description_images": [], + "constraints": [ + "i != j", + "0 <= i, j < arr.length", + "arr[i] == 2 * arr[j]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,2,5,3]\nOutput:true\nExplanation:N= 10is the double of M= 5,that is,10 = 2 * 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,1,14,11]\nOutput:true\nExplanation:N= 14is the double of M= 7,that is,14 = 2 * 7.", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,1,7,11]\nOutput:false\nExplanation:In this case does not exist N and M, such that N = 2 * M.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def checkIfExist(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n '''\n 执行用时:24 ms, 在所有 Python 提交中击败了59.63%的用户\n 内存消耗:13 MB, 在所有 Python 提交中击败了58.72%的用户\n '''\n arr = sorted(arr) # 排序\n for i in range(len(arr) - 1): # 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现\n l = 0\n r = len(arr) - 1\n while (l <= r):\n mid = int((l + r) / 2) # 目前位置\n val1 = arr[mid] # 目前位置的数值\n val2 = arr[i] * 2 # 要寻找的目标\n if(val1 == val2 and mid != i): # arr[mid] 必須和 arr[i] * 2 且不同位置\n return True\n elif(val2 < val1): # 目标在目前位置的左边,所以要往左边找\n r = mid - 1\n else: # 目标在目前位置的右边,所以要往右边找\n l = mid + 1\n return False\n", + "title": "1346. Check If N and Its Double Exist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n , the digit i occurs num[i] times in num , otherwise return false .", + "description_images": [], + "constraints": [ + "n == num.length", + "1 <= n <= 10", + "num consists of digits." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1210\"\nOutput:true\nExplanation:num[0] = '1'. The digit 0 occurs once in num.\nnum[1] = '2'. The digit 1 occurs twice in num.\nnum[2] = '1'. The digit 2 occurs once in num.\nnum[3] = '0'. The digit 3 occurs zero times in num.\nThe condition holds true for every index in \"1210\", so return true.", + "image": null + }, + { + "text": "Example 2: Input:num = \"030\"\nOutput:false\nExplanation:num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\nnum[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\nnum[2] = '0'. The digit 2 occurs zero times in num.\nThe indices 0 and 1 both violate the condition, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean digitCount(String num) {\n int[] freqArr = new int[10]; // n = 10 given in constraints;\n \n \n for(char ch : num.toCharArray()){\n freqArr[ch-'0']++;\n }\n \n for(int i=0;i bool:\n d = Counter(num)\n for i in range(len(num)):\n if int(num[i])!=d.get(str(i), 0):\n return False\n return True\n", + "title": "2283. Check if Number Has Equal Digit Count and Digit Value", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:true\nExplanation:12 = 31+ 32", + "image": null + }, + { + "text": "Example 2: Input:n = 91\nOutput:true\nExplanation:91 = 30+ 32+ 34", + "image": null + }, + { + "text": "Example 3: Input:n = 21\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 41.31%) | Memory: 41.4 MB (Top 27.03%)\n\nclass Solution {\n public boolean checkPowersOfThree(int n) {\n //max power of 3\n int maxPower = (int)(Math.log(n) / Math.log(3));\n\n //save all the power of 3 from 0 to maxPower\n // 3^0, 3^1, 3^2 .... 3^maxPower\n int[] threePower = new int[maxPower + 1];\n threePower[0] = 1;\n for(int i = 1; i <= maxPower; i++){\n threePower[i] = threePower[i - 1] * 3;\n }\n\n //Intuition\n //if we subtract n with every power of 3\n //at the end if n is zero, then it is sum of power 3\n\n //subtract n with power of 3,\n //if n is graeter than power\n for(int i = maxPower; i >= 0; i--){\n //n is greater/equal to power 3\n if(n >= threePower[i]){\n n -= threePower[i];\n }\n }\n\n return n == 0;\n }\n}", + "title": "1780. Check if Number is a Sum of Powers of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:true\nExplanation:12 = 31+ 32", + "image": null + }, + { + "text": "Example 2: Input:n = 91\nOutput:true\nExplanation:91 = 30+ 32+ 34", + "image": null + }, + { + "text": "Example 3: Input:n = 21\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 10.08%) | Memory: 17.20 MB (Top 9.7%)\n\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while n > 1:\n n, r = divmod(n, 3)\n if r == 2: return False\n return True\n", + "title": "1780. Check if Number is a Sum of Powers of Three", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s ). Return true if so, or false otherwise .", + "description_images": [], + "constraints": [ + "For example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\nOutput:true\nExplanation:The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example1.png" + }, + { + "text": "Example 2: Input:s = \"hello world 5 x 5\"\nOutput:false\nExplanation:The numbers in s are:5,5. They are not strictly increasing.", + "image": null + }, + { + "text": "Example 3: Input:s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\nOutput:false\nExplanation:The numbers in s are: 7,51,50, 60. They are not strictly increasing.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 29.63%) | Memory: 43.3 MB (Top 11.10%)\n// Space Complexity: O(1)\n// Time Complexity: O(n)\nclass Solution {\n public boolean areNumbersAscending(String s) {\n int prev = 0;\n\n for(String token: s.split(\" \")) {\n try {\n int number = Integer.parseInt(token);\n if(number <= prev)\n return false;\n prev = number;\n }\n catch(Exception e) {}\n }\n\n return true;\n }\n}", + "title": "2042. Check if Numbers Are Ascending in a Sentence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s ). Return true if so, or false otherwise .", + "description_images": [], + "constraints": [ + "For example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\nOutput:true\nExplanation:The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example1.png" + }, + { + "text": "Example 2: Input:s = \"hello world 5 x 5\"\nOutput:false\nExplanation:The numbers in s are:5,5. They are not strictly increasing.", + "image": null + }, + { + "text": "Example 3: Input:s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\nOutput:false\nExplanation:The numbers in s are: 7,51,50, 60. They are not strictly increasing.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 38.18%) | Memory: 13.8 MB (Top 55.89%)\nclass Solution:\n def areNumbersAscending(self, s):\n nums = re.findall(r'\\d+', s)\n return nums == sorted(set(nums), key=int)", + "title": "2042. Check if Numbers Are Ascending in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 100", + "s1.length == s2.length", + "s1 and s2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"bank\", s2 = \"kanb\"\nOutput:true\nExplanation:For example, swap the first character with the last character of s2 to make \"bank\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"attack\", s2 = \"defend\"\nOutput:false\nExplanation:It is impossible to make them equal with one string swap.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"kelb\", s2 = \"kelb\"\nOutput:true\nExplanation:The two strings are already equal, so no string swap operation is required.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean areAlmostEqual(String s1, String s2) {\n \n int[] s1Array = new int[26];\n int[] s2Array = new int[26];\n int counter = 0;\n for(int i = 0;i 2)\n return false;\n s1Array[s -'a']++;\n s2Array[ss -'a']++;\n }\n return Arrays.equals(s1Array, s2Array);\n }\n}", + "title": "1790. Check if One String Swap Can Make Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 100", + "s1.length == s2.length", + "s1 and s2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"bank\", s2 = \"kanb\"\nOutput:true\nExplanation:For example, swap the first character with the last character of s2 to make \"bank\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"attack\", s2 = \"defend\"\nOutput:false\nExplanation:It is impossible to make them equal with one string swap.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"kelb\", s2 = \"kelb\"\nOutput:true\nExplanation:The two strings are already equal, so no string swap operation is required.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 36 ms (Top 83.5%) | Memory: 16.25 MB (Top 70.5%)\n\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]", + "title": "1790. Check if One String Swap Can Make Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an array of strings words , determine whether s is a prefix string of words . A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length . Return true if s is a prefix string of words , or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "1 <= s.length <= 1000", + "words[i] and s consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput:true\nExplanation:s can be made by concatenating \"i\", \"love\", and \"leetcode\" together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput:false\nExplanation:It is impossible to make s using a prefix of arr.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.41%) | Memory: 42.90 MB (Top 8.98%)\n\nclass Solution {\n public boolean isPrefixString(String s, String[] words) {\n StringBuilder res = new StringBuilder (\"\");\n for (String word : words) {\n res.append (word);\n if (s.equals (res.toString()))\n return true;\n if (s.indexOf (res.toString()) == -1)\n return false;\n }\n return false;\n }\n}\n", + "title": "1961. Check If String Is a Prefix of Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s and an array of strings words , determine whether s is a prefix string of words . A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length . Return true if s is a prefix string of words , or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "1 <= s.length <= 1000", + "words[i] and s consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput:true\nExplanation:s can be made by concatenating \"i\", \"love\", and \"leetcode\" together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput:false\nExplanation:It is impossible to make s using a prefix of arr.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \n a = ''\n \n for i in words:\n \n a += i\n \n if a == s:\n return True\n if not s.startswith(a):\n break\n \n return False \n", + "title": "1961. Check If String Is a Prefix of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , transform string s into string t using the following operation any number of times: Return true if it is possible to transform s into t . Otherwise, return false . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "Choose a non-empty substring in s and sort it in place so the characters are in ascending order . For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" .", + "For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"84532\", t = \"34852\"\nOutput:true\nExplanation:You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"34521\", t = \"23415\"\nOutput:true\nExplanation:You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"12345\", t = \"12435\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isTransformable(String s, String t) {\n if (!equal(s, t)) return false;\n int[] countS = new int[10];\n int[] countT = new int[10];\n int[][] prev = new int[10][10];\n int[][] after = new int[10][10];\n \n for (int i = 0; i < s.length(); i++) {\n int s1 = s.charAt(i) - '0';\n int t1 = t.charAt(i) - '0';\n countS[s1]++;\n countT[t1]++;\n \n\t\t\t// This step is to calculate how many digit less than s1/t1 occur before time i\n\t\t\t// Store the frequency pair into 2-d array\n for (int j = 0; j < s1; j++) {\n if (countS[j] == 0) continue;\n prev[j][s1] += countS[j];\n\n }\n \n for (int j = 0; j < t1; j++) {\n if (countT[j] == 0) continue; \n after[j][t1] += countT[j];\n }\n \n }\n \n for (int i = 0; i <= 8; i++) {\n for (int j = i + 1; j <= 9; j++) {\n if (prev[i][j] == 0) continue;\n\t\t\t\t// Check if any ascending pair's frequency has been reduced after modified.\n if (after[i][j] < prev[i][j]) return false;\n }\n }\n \n return true;\n }\n \n\t// Judge whether the two strings has the same digits\n public boolean equal(String s, String t) {\n char[] sc = s.toCharArray();\n char[] tc = t.toCharArray();\n Arrays.sort(sc);\n Arrays.sort(tc);\n \n for (int i = 0; i < s.length(); i++) {\n if (sc[i] != tc[i]) return false;\n }\n \n return true;\n }\n}\n", + "title": "1585. Check If String Is Transformable With Substring Sort Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , transform string s into string t using the following operation any number of times: Return true if it is possible to transform s into t . Otherwise, return false . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "Choose a non-empty substring in s and sort it in place so the characters are in ascending order . For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" .", + "For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"84532\", t = \"34852\"\nOutput:true\nExplanation:You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"34521\", t = \"23415\"\nOutput:true\nExplanation:You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"12345\", t = \"12435\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n index = defaultdict(list)\n for i, c in enumerate(s):\n index[c].append(i)\n curpos = defaultdict(int)\n for c in t:\n if curpos[c] == len(index[c]): return False\n for i in range(int(c)):\n i = str(i)\n if curpos[i] < len(index[i]) and index[i][curpos[i]] < index[c][curpos[c]]:\n return False\n curpos[c] += 1\n return True", + "title": "1585. Check If String Is Transformable With Substring Sort Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram , or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 1000", + "sentence consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"thequickbrownfoxjumpsoverthelazydog\"\nOutput:true\nExplanation:sentence contains at least one of every letter of the English alphabet.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"leetcode\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkIfPangram(String sentence) {\n int seen = 0;\n for(char c : sentence.toCharArray()) {\n int ci = c - 'a';\n seen = seen | (1 << ci);\n }\n return seen == ((1 << 26) - 1);\n }\n}", + "title": "1832. Check if the Sentence Is Pangram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram , or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 1000", + "sentence consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"thequickbrownfoxjumpsoverthelazydog\"\nOutput:true\nExplanation:sentence contains at least one of every letter of the English alphabet.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"leetcode\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n return len(set(sentence))==26", + "title": "1832. Check if the Sentence Is Pangram", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given an m x n matrix of parentheses grid . A valid parentheses string path in the grid is a path satisfying all of the following conditions: Return true if there exists a valid parentheses string path in the grid. Otherwise, return false .", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]\nOutput:true\nExplanation:The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string \"()(())\".\nThe second path shown results in the valid parentheses string \"((()))\".\nNote that there may be other valid parentheses string paths.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[\")\",\")\"],[\"(\",\"(\"]]\nOutput:false\nExplanation:The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 538 ms (Top 16.66%) | Memory: 372.3 MB (Top 5.18%)\nclass Solution {\n static Boolean[][][] dp;\n public boolean hasValidPath(char[][] grid) {\n int m = grid.length, n = grid[0].length;\n dp = new Boolean[101][101][201]; // [row][col][open-close]\n if(grid[0][0] == ')'){ // cannot start with ')'\n return false;\n }\n if(grid[m-1][n-1] == '('){ // cannot end with '('\n return false;\n }\n return solve(grid,0,0,m,n,0,0);\n }\n public static boolean solve(char[][] grid,int i,int j,int m,int n,int open,int close){\n if(grid[i][j] == '('){\n open++;\n }\n else{\n close++;\n }\n if(close > open){ // at any point if closeBracket count exceeds openBracket count then return false since this path can never lead to valid paranthesis string\n return false;\n }\n if(i == m-1 && j == n-1){ // on reaching bottom right cell if openCount == closeCount return true else return false\n return open == close;\n }\n if(dp[i][j][open-close] != null){ // check for precomputed overlapping subproblem\n return dp[i][j][open-close];\n }\n if(i == m-1){ // make sure to not go out of the grid in last row\n return dp[i][j][open-close] = solve(grid,i,j+1,m,n,open,close);\n }\n if(j == n-1){ // make sure to not go out of the grid in last col\n return dp[i][j][open-close] = solve(grid,i+1,j,m,n,open,close);\n }\n boolean op = solve(grid,i+1,j,m,n,open,close) || solve(grid,i,j+1,m,n,open,close); // we have two choices to move forward, [i+1][j] or [i][j+1]\n return dp[i][j][open-close] = op;\n }\n}", + "title": "2267. Check if There Is a Valid Parentheses String Path", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given an m x n matrix of parentheses grid . A valid parentheses string path in the grid is a path satisfying all of the following conditions: Return true if there exists a valid parentheses string path in the grid. Otherwise, return false .", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]\nOutput:true\nExplanation:The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string \"()(())\".\nThe second path shown results in the valid parentheses string \"((()))\".\nNote that there may be other valid parentheses string paths.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[\")\",\")\"],[\"(\",\"(\"]]\nOutput:false\nExplanation:The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1143 ms (Top 75.31%) | Memory: 238.70 MB (Top 9.88%)\n\nclass Solution:\n def hasValidPath(self, grid: List[List[str]]) -> bool: \n m = len(grid)\n n = len(grid[0])\n @lru_cache(maxsize=None)\n def hasValidPathInner(x, y, cnt):\n # cnt variable would act as a counter to track \n # the balance of parantheses sequence\n if x == m or y == n or cnt < 0:\n return False\n \n # logic to check the balance of sequence\n cnt += 1 if grid[x][y] == '(' else -1\n \n # if balanced and end of grid, return True\n if x == m - 1 and y == n - 1 and not cnt:\n return True\n \n return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt)\n\n return hasValidPathInner(0, 0, 0)\n", + "title": "2267. Check if There Is a Valid Parentheses String Path", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: Return true if the array has at least one valid partition . Otherwise, return false .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,4,4,5,6]\nOutput:true\nExplanation:The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2]\nOutput:false\nExplanation:There is no valid partition for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 12.25%) | Memory: 82.9 MB (Top 64.19%)\n// Time O(n)\n// Space O(n)\nclass Solution {\n public boolean validPartition(int[] nums) {\n boolean[] dp = new boolean[nums.length+1];\n dp[0]=true; // base case\n for (int i = 2; i <= nums.length; i++){\n dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1\n dp[i]|= i>2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] && dp[i-3]; // cond 2\n dp[i]|= i>2 && nums[i-1]-nums[i-2]==1 && nums[i-2]-nums[i-3]==1 && dp[i-3]; // cond 3\n }\n return dp[nums.length];\n }\n}", + "title": "2369. Check if There is a Valid Partition For The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: Return true if the array has at least one valid partition . Otherwise, return false .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,4,4,5,6]\nOutput:true\nExplanation:The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2]\nOutput:false\nExplanation:There is no valid partition for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 920 ms (Top 32.4%) | Memory: 30.14 MB (Top 95.0%)\n\nclass Solution:\n def validPartition(self, nums: List[int]) -> bool:\n n = len(nums)\n \n dp = [False] * 3\n dp[0] = True # An empty partition is always valid\n\n for i in range(2, n + 1):\n ans = False\n\n if nums[i - 1] == nums[i - 2]:\n ans = ans or dp[(i - 2) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]:\n ans = ans or dp[(i - 3) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2:\n ans = ans or dp[(i - 3) % 3]\n\n dp[i % 3] = ans\n\n return dp[n % 3]", + "title": "2369. Check if There is a Valid Partition For The Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n grid . Each cell of grid represents a street. The street of grid[i][j] can be: You will initially start at the street of the upper-left cell (0, 0) . A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) . The path should only follow the streets . Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise .", + "description_images": [], + "constraints": [ + "1 which means a street connecting the left cell and the right cell.", + "2 which means a street connecting the upper cell and the lower cell.", + "3 which means a street connecting the left cell and the lower cell.", + "4 which means a street connecting the right cell and the lower cell.", + "5 which means a street connecting the left cell and the upper cell.", + "6 which means a street connecting the right cell and the upper cell." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4,3],[6,5,2]]\nOutput:true\nExplanation:As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).", + "image": "https://assets.leetcode.com/uploads/2020/03/05/e1.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,1],[1,2,1]]\nOutput:false\nExplanation:As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)", + "image": "https://assets.leetcode.com/uploads/2020/03/05/e2.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,2]]\nOutput:false\nExplanation:You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 82.7%) | Memory: 66.95 MB (Top 46.9%)\n\nclass Solution {\n public boolean hasValidPath(int[][] grid) {\n int m=grid.length, n=grid[0].length;\n int[][] visited=new int[m][n];\n return dfs(grid, 0, 0, m, n, visited);\n }\n public boolean dfs(int[][] grid, int i, int j, int m, int n, int[][] visited){\n if(i==m-1 && j==n-1) return true;\n if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==1) return false;\n visited[i][j]=1;\n if(grid[i][j]==1){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (j0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else if(grid[i][j]==3){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else{\n if( (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited)) || \n\t\t\t (j bool:\n r,c=len(grid),len(grid[0])\n dic={\n 2:[(-1,0),(1,0)],\n 1:[(0,1),(0,-1)],\n 5:[(-1,0),(0,-1)],\n 3:[(1,0),(0,-1)],\n 6:[(0,1),(-1,0)],\n 4:[(0,1),(1,0)]\n \n }\n q=collections.deque([(0,0)])\n visit=set()\n while q:\n i,j=q.popleft()\n visit.add((i,j))\n if i==r-1 and j==c-1:\n return True\n for x,y in dic[grid[i][j]]:\n nx=i+x\n ny=j+y\n if nx>=0 and nx=0 and ny \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.", + "image": null + }, + { + "text": "Example 2: Input:word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 57.48%) | Memory: 41.5 MB (Top 82.47%)\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2)\n {\n return(String.join(\"\", word1).equals(String.join(\"\", word2)));\n }\n}", + "title": "1662. Check If Two String Arrays are Equivalent", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two string arrays word1 and word2 , return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string.", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 10^3", + "1 <= word1[i].length, word2[i].length <= 10^3", + "1 <= sum(word1[i].length), sum(word2[i].length) <= 10^3", + "word1[i] and word2[i] consist of lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\nOutput:true\nExplanation:word1 represents string \"ab\" + \"c\" -> \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.", + "image": null + }, + { + "text": "Example 2: Input:word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return True if \"\".join(word1) == \"\".join(word2) else False", + "title": "1662. Check If Two String Arrays are Equivalent", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix board , representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: Given a string word , return true if word can be placed in board , or false otherwise .", + "description_images": [], + "constraints": [ + "It does not occupy a cell containing the character '#' .", + "The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board .", + "There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally .", + "There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\nOutput:true\nExplanation:The word \"abc\" can be placed as shown above (top to bottom).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png" + }, + { + "text": "Example 2: Input:board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\nOutput:false\nExplanation:It is impossible to place the word because there will always be a space/letter above or below it.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png" + }, + { + "text": "Example 3: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\nOutput:true\nExplanation:The word \"ca\" can be placed as shown above (right to left).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 522 ms (Top 5.97%) | Memory: 200.3 MB (Top 5.41%)\nclass Solution {\n public boolean placeWordInCrossword(char[][] board, String word) {\n String curr = \"\";\n\n Trie trie = new Trie();\n\n // Insert all horizontal strings\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n if (board[i][j] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[i][j];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n // Insert all vertical strings\n for (int i = 0; i < board[0].length; i++) {\n for (int j = 0; j < board.length; j++) {\n if (board[j][i] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[j][i];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n return trie.isPresent(word);\n }\n\n // Insert string and reverse of string into the trie\n private void insertIntoTrie(Trie trie, String s) {\n trie.insert(s);\n StringBuilder sb = new StringBuilder(s);\n sb.reverse();\n trie.insert(sb.toString());\n }\n\n class TrieNode {\n Map children;\n boolean isEnd;\n\n TrieNode() {\n children = new HashMap<>();\n isEnd = false;\n }\n\n }\n\n class Trie {\n TrieNode root;\n\n Trie() {\n root = new TrieNode();\n }\n\n void insert(String s) {\n TrieNode curr = root;\n\n for (int i = 0; i < s.length(); i++)\n {\n char c = s.charAt(i);\n if (!curr.children.containsKey(c)) {\n curr.children.put(c, new TrieNode());\n }\n\n curr = curr.children.get(c);\n }\n\n curr.isEnd = true;\n }\n\n boolean isPresent(String key) {\n TrieNode curr = root;\n return helper(key, 0, root);\n\n }\n\n boolean helper(String key, int i, TrieNode curr) {\n if (curr == null)\n return false;\n\n if (i == key.length())\n return curr.isEnd;\n\n char c = key.charAt(i);\n return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));\n\n }\n }\n}", + "title": "2018. Check if Word Can Be Placed In Crossword", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n matrix board , representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: Given a string word , return true if word can be placed in board , or false otherwise .", + "description_images": [], + "constraints": [ + "It does not occupy a cell containing the character '#' .", + "The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board .", + "There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally .", + "There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\nOutput:true\nExplanation:The word \"abc\" can be placed as shown above (top to bottom).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png" + }, + { + "text": "Example 2: Input:board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\nOutput:false\nExplanation:It is impossible to place the word because there will always be a space/letter above or below it.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png" + }, + { + "text": "Example 3: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\nOutput:true\nExplanation:The word \"ca\" can be placed as shown above (right to left).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n m, n = len(board), len(board[0])\n W = len(word)\n \n def valid(x, y):\n return 0 <= x < m and 0 <= y < n\n \n def place(x, y, word, direction):\n dx, dy = direction\n for c in word:\n if not valid(x, y) or board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != c):\n return False\n x, y = x+dx, y+dy\n return True\n \n \n for x in range(m):\n for y in range(n):\n if board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != word[0]):\n continue\n \n # left to right\n if (not valid(x, y-1) or board[x][y-1] == '#') and (not valid(x, y+W) or board[x][y+W] == '#') and place(x, y, word, [0, 1]):\n return True\n \n # right to left\n if (not valid(x, y+1) or board[x][y+1] == '#') and (not valid(x, y-W) or board[x][y-W] == '#') and place(x, y, word, [0, -1]):\n return True\n \n # top to bottom\n if (not valid(x-1, y) or board[x-1][y] == '#') and (not valid(x+W, y) or board[x+W][y] == '#') and place(x, y, word, [1, 0]):\n return True\n \n\t\t\t\t# bottom to top\n if (not valid(x+1, y) or board[x+1][y] == '#') and (not valid(x-W, y) or board[x-W][y] == '#') and place(x, y, word, [-1, 0]):\n return True\n \n return False\n", + "title": "2018. Check if Word Can Be Placed In Crossword", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0 , 'b' -> 1 , 'c' -> 2 , etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s , which is then converted into an integer. You are given three strings firstWord , secondWord , and targetWord , each consisting of lowercase English letters 'a' through 'j' inclusive . Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord , or false otherwise.", + "description_images": [], + "constraints": [ + "For example, if s = \"acb\" , we concatenate each letter's letter value, resulting in \"021\" . After converting it, we get 21 ." + ], + "examples": [ + { + "text": "Example 1: Input:firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput:true\nExplanation:The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.", + "image": null + }, + { + "text": "Example 2: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\nOutput:false\nExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.", + "image": null + }, + { + "text": "Example 3: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\nOutput:true\nExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {\n int sumfirst=0, sumsecond=0, sumtarget=0;\n for(char c : firstWord.toCharArray()){\n sumfirst += c-'a';\n sumfirst *= 10;\n }\n for(char c : secondWord.toCharArray()){\n sumsecond += c-'a';\n sumsecond *= 10;\n }\n for(char c : targetWord.toCharArray()){\n sumtarget += c-'a';\n sumtarget *= 10;\n }\n \n return (sumfirst + sumsecond) == sumtarget;\n }\n}", + "title": "1880. Check if Word Equals Summation of Two Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0 , 'b' -> 1 , 'c' -> 2 , etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s , which is then converted into an integer. You are given three strings firstWord , secondWord , and targetWord , each consisting of lowercase English letters 'a' through 'j' inclusive . Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord , or false otherwise.", + "description_images": [], + "constraints": [ + "For example, if s = \"acb\" , we concatenate each letter's letter value, resulting in \"021\" . After converting it, we get 21 ." + ], + "examples": [ + { + "text": "Example 1: Input:firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput:true\nExplanation:The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.", + "image": null + }, + { + "text": "Example 2: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\nOutput:false\nExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.", + "image": null + }, + { + "text": "Example 3: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\nOutput:true\nExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 58.1%) | Memory: 16.21 MB (Top 73.9%)\n\nclass Solution:\n def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n x=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n a=\"\"\n for i in firstWord:\n a=a+str(x.index(i))\n \n b=\"\"\n for i in secondWord:\n b=b+str(x.index(i))\n\n c=\"\"\n for i in targetWord:\n c=c+str(x.index(i))\n if int(a)+int(b)==int(c):\n return True\n return False", + "title": "1880. Check if Word Equals Summation of Two Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , determine if it is valid . A string s is valid if, starting with an empty string t = \"\" , you can transform t into s after performing the following operation any number of times : Return true if s is a valid string, otherwise, return false .", + "description_images": [], + "constraints": [ + "Insert string \"abc\" into any position in t . More formally, t becomes t left + \"abc\" + t right , where t == t left + t right . Note that t left and t right may be empty ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcbc\"\nOutput:true\nExplanation:\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcabcababcc\"\nOutput:true\nExplanation:\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abccba\"\nOutput:false\nExplanation:It is impossible to get \"abccba\" using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValid(String s) {\n \n //Lets see how we can solve that as we know we have only abc in string.\n //Like aabcbc\n // See as that ((b)b) Think a is '(' and c is ')'.\n // If a string is made by using abc only we can remove abc to make it empty also.\n \n //Think in Reverse Way.\n \n \n \n Stack stack = new Stack<>();\n char[] arr = s.toCharArray();\n for (int i = 0; i < arr.length; i++) {\n \n // We have to work only when we get ')' means c.\n \n if(arr[i] == 'c')\n {\n // If we at c means we have 2 elements before us a and b.\n // When we first pop we get b at second pop we get a\n \n // If this all hold true we will delete a and b we are not adding c so c also\n \n if(stack.size()>=2 && stack.pop() == 'b' && stack.pop() == 'a')\n {\n\n }\n else\n {\n \n // If anywhere we get false in any condition that means this is not a valid set i.e. abc pattern is not present.\n \n return false;\n }\n }\n else\n {\n // For a and b we simply add.\n \n stack.push(arr[i]);\n }\n }\n \n //If we have only abc pattern the stack will become empty.\n \n return stack.size()==0;\n }\n}\n", + "title": "1003. Check If Word Is Valid After Substitutions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , determine if it is valid . A string s is valid if, starting with an empty string t = \"\" , you can transform t into s after performing the following operation any number of times : Return true if s is a valid string, otherwise, return false .", + "description_images": [], + "constraints": [ + "Insert string \"abc\" into any position in t . More formally, t becomes t left + \"abc\" + t right , where t == t left + t right . Note that t left and t right may be empty ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcbc\"\nOutput:true\nExplanation:\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcabcababcc\"\nOutput:true\nExplanation:\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abccba\"\nOutput:false\nExplanation:It is impossible to get \"abccba\" using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, s: str) -> bool:\n \n \n ans = ''\n for i in s:\n ans+=i\n while len(ans)>=3:\n if ans[-3:]==\"abc\":\n ans=ans[0:-3]\n else:\n break\n \n if ans=='':\n return True\n else:\n return False", + "title": "1003. Check If Word Is Valid After Substitutions", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3 . Given two strings word1 and word2 , each of length n , return true if word1 and word2 are almost equivalent , or false otherwise . The frequency of a letter x is the number of times it occurs in the string.", + "description_images": [], + "constraints": [ + "n == word1.length == word2.length", + "1 <= n <= 100", + "word1 and word2 consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"aaaa\", word2 = \"bccb\"\nOutput:false\nExplanation:There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcdeef\", word2 = \"abaaacc\"\nOutput:true\nExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cccddabba\", word2 = \"babababab\"\nOutput:true\nExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n public boolean checkAlmostEquivalent(String word1, String word2) {\n Map map = new HashMap();\n for (int i = 0; i < word1.length(); i++) {\n map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1);\n map.put(word2.charAt(i), map.getOrDefault(word2.charAt(i), 0) - 1);\n }\n for (int i : map.values()) { //get value set\n if (i > 3 || i < -3) { \n return false;\n }\n }\n return true;\n }\n}", + "title": "2068. Check Whether Two Strings are Almost Equivalent", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3 . Given two strings word1 and word2 , each of length n , return true if word1 and word2 are almost equivalent , or false otherwise . The frequency of a letter x is the number of times it occurs in the string.", + "description_images": [], + "constraints": [ + "n == word1.length == word2.length", + "1 <= n <= 100", + "word1 and word2 consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"aaaa\", word2 = \"bccb\"\nOutput:false\nExplanation:There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcdeef\", word2 = \"abaaacc\"\nOutput:true\nExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cccddabba\", word2 = \"babababab\"\nOutput:true\nExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkAlmostEquivalent(self, w1: str, w2: str) -> bool:\n\t\treturn all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())\n", + "title": "2068. Check Whether Two Strings are Almost Equivalent", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An undirected graph of n nodes is defined by edgeList , where edgeList[i] = [u i , v i , dis i ] denotes an edge between nodes u i and v i with distance dis i . Note that there may be multiple edges between two nodes. Given an array queries , where queries[j] = [p j , q j , limit j ] , your task is to determine for each queries[j] whether there is a path between p j and q j such that each edge on the path has a distance strictly less than limit j . Return a boolean array answer , where answer.length == queries.length and the j th value of answer is true if there is a path for queries[j] is true , and false otherwise .", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "1 <= edgeList.length, queries.length <= 10^5", + "edgeList[i].length == 3", + "queries[j].length == 3", + "0 <= u i , v i , p j , q j <= n - 1", + "u i != v i", + "p j != q j", + "1 <= dis i , limit j <= 10^9", + "There may be multiple edges between two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\nOutput:[false,true]\nExplanation:The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.", + "image": "https://assets.leetcode.com/uploads/2020/12/08/h.png" + }, + { + "text": "Example 2: Input:n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\nOutput:[true,false]Exaplanation:The above figure shows the given graph.", + "image": "https://assets.leetcode.com/uploads/2020/12/08/q.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n private int[] parents;\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n this.parents = new int[n];\n for (int i = 0; i < n; i++) parents[i] = i;\n \n int m = queries.length;\n \n // storing {u, v, weight, original idx} by increasing weight\n int[][] sortedQueries = new int[m][4];\n for (int i = 0; i < m; i++) {\n sortedQueries[i] = new int[]{queries[i][0], queries[i][1], queries[i][2], i};\n }\n Arrays.sort(sortedQueries, (a,b) -> a[2] - b[2]);\n \n \n // sort edgeList by increasing weight \n Arrays.sort(edgeList, (a,b) -> a[2] - b[2]);\n int idx = 0;\n \n boolean[] res = new boolean[m];\n \n for (int i = 0; i < m; i++) {\n int[] q = sortedQueries[i];\n int w = q[2];\n \n // union all edges with weight less than current query\n while (idx < edgeList.length && edgeList[idx][2] < w) {\n int[] e = edgeList[idx++];\n int u = e[0], v = e[1];\n union(u, v);\n }\n \n int uQuery = q[0], vQuery = q[1], id = q[3];\n res[id] = (find(uQuery) == find(vQuery));\n }\n \n return res;\n }\n \n private void union(int u, int v) {\n int uParent = find(u);\n int vParent = find(v);\n parents[uParent] = vParent;\n }\n \n private int find(int u) {\n while (u != parents[u]) {\n parents[u] = parents[parents[u]];\n u = parents[u];\n }\n return u;\n } \n}\n", + "title": "1697. Checking Existence of Edge Length Limited Paths", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. Return the maximum number of cherries you can collect by following the rules below :", + "description_images": [], + "constraints": [ + "0 means the cell is empty, so you can pass through,", + "1 means the cell contains a cherry that you can pick up and pass through, or", + "-1 means the cell contains a thorn that blocks your way." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput:5\nExplanation:The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.", + "image": "https://assets.leetcode.com/uploads/2020/12/14/grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.2%) | Memory: 44.42 MB (Top 46.1%)\n\nclass Solution {\n public int cherryPickup(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n //For O(N^3) Dp sapce solution\n dp2 = new Integer[m][n][m];\n int ans=solve2(0,0,0,grid,0,m,n);\n if(ans==Integer.MIN_VALUE) return 0;\n return ans;\n }\n \n private Integer[][][] dp2;\n private int solve2(int x1, int y1, int x2, int[][] g, int cpsf, int m, int n){\n int y2 = x1+y1+-x2;\n if(x1>=m||x2>=m||y1>=n||y2>=n||g[x1][y1]==-1||g[x2][y2]==-1) return Integer.MIN_VALUE;\n if(x1==m-1&&y1==n-1) return g[x1][y1];\n //If both p1 and p2 reach (m-1,n-1)\n if(dp2[x1][y1][x2]!=null) return dp2[x1][y1][x2];\n int cherries=0;\n //If both p1 and p2 are at same position then we need to add the cherry only once.\n if(x1==x2&&y1==y2){\n cherries+=g[x1][y1];\n }\n //If p1 and p2 are at different positions then repective cherries can be added.\n else{\n cherries+=g[x1][y1]+g[x2][y2];\n }\n //4 possibilites for p1 and p2 from each point\n int dd=solve2(x1+1,y1,x2+1,g,cpsf+cherries,m,n); //both moves down\n int dr=solve2(x1+1,y1,x2,g,cpsf+cherries,m,n); //p1 moves down and p2 moves right\n int rr=solve2(x1,y1+1,x2,g,cpsf+cherries,m,n); //both moves right \n int rd=solve2(x1,y1+1,x2+1,g,cpsf+cherries,m,n); //p1 moves right and p2 moves down\n \n //We take maximum of 4 possiblities\n int max=Math.max(Math.max(dd,dr), Math.max(rr,rd));\n if(max==Integer.MIN_VALUE) return dp2[x1][y1][x2]=max;\n return dp2[x1][y1][x2]=cherries+=max;\n }\n}\n", + "title": "741. Cherry Pickup", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. Return the maximum number of cherries you can collect by following the rules below :", + "description_images": [], + "constraints": [ + "0 means the cell is empty, so you can pass through,", + "1 means the cell contains a cherry that you can pick up and pass through, or", + "-1 means the cell contains a thorn that blocks your way." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput:5\nExplanation:The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.", + "image": "https://assets.leetcode.com/uploads/2020/12/14/grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 360 ms (Top 100.00%) | Memory: 14 MB (Top 98.73%)\nclass Solution:\n def cherryPickup(self, grid):\n n = len(grid)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n dp[1][1] = grid[0][0]\n for m in range(1, (n << 1) - 1):\n for i in range(min(m, n - 1), max(-1, m - n), -1):\n for p in range(i, max(-1, m - n), -1):\n j, q = m - i, m - p\n if grid[i][j] == -1 or grid[p][q] == -1:\n dp[i + 1][p + 1] = -1\n else:\n dp[i + 1][p + 1] = max(dp[i + 1][p + 1], dp[i][p + 1], dp[i + 1][p], dp[i][p])\n if dp[i + 1][p + 1] != -1: dp[i + 1][p + 1] += grid[i][j] + (grid[p][q] if i != p else 0)\n return max(0, dp[-1][-1])", + "title": "741. Cherry Pickup", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Return the maximum number of cherries collection using both robots by following the rules below :", + "description_images": [], + "constraints": [ + "Robot #1 is located at the top-left corner (0, 0) , and", + "Robot #2 is located at the top-right corner (0, cols - 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\nOutput:24\nExplanation:Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\nCherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\nTotal of cherries: 12 + 12 = 24.", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_1_1802.png" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\nOutput:28\nExplanation:Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\nCherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\nTotal of cherries: 17 + 11 = 28.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/sample_2_1802.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 609 ms (Top 95.65%) | Memory: 24.30 MB (Top 75.94%)\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n \n dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]\n \n def get_next_max(row, col_r1, col_r2):\n res = 0\n for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):\n for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):\n res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])\n\n return res\n \n for row in reversed(range(rows)):\n for col_r1 in range(min(cols, row + 2)):\n for col_r2 in range(max(0, cols - row - 1), cols):\n\n reward = grid[row][col_r1] + grid[row][col_r2]\n if col_r1 == col_r2:\n reward /= 2\n \n dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)\n \n return dp[0][1][cols]\n", + "title": "1463. Cherry Pickup II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row . Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_1.png", + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_3.png" + ], + "constraints": [ + "1 <= n <= 10^9", + "1 <= reservedSeats.length <= min(10*n, 10^4)", + "reservedSeats[i].length == 2", + "1 <= reservedSeats[i][0] <= n", + "1 <= reservedSeats[i][1] <= 10", + "All reservedSeats[i] are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput:4\nExplanation:The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 37 ms (Top 66.38%) | Memory: 70.8 MB (Top 57.25%)\nclass Solution {\n public int maxNumberOfFamilies(int n, int[][] reservedSeats) {\n Map seats = new HashMap<>();\n int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots\n\n for (int[] seat: reservedSeats) {\n int row = seat[0];\n int col = seat[1];\n int[] slots = seats.getOrDefault(row, new int[3]);\n\n if (col >= 2 && col <= 5) { // left slot\n slots[0] = 1;\n }\n if (col >= 4 && col <= 7) { // middle slot\n slots[1] = 1;\n }\n if (col >= 6 && col <= 9) { // right slot\n slots[2] = 1;\n }\n\n seats.put(seat[0], slots);\n }\n\n for (int[] slots: seats.values()) {\n int taken = slots[0] + slots[2];\n\n if (taken == 2) { // both slots at either ends are taken\n if (slots[1] == 0) { // check if middle slot not taken\n availableSlots--; // reduce availableslots by 1 since middle slot is available\n } else {\n availableSlots -= 2; // entire row not available - reduce by 2\n }\n } else if (taken == 1) { // one of the slots at either ends are taken\n availableSlots--; // reduce by 1 since either side of the slots not available\n } else {\n continue; // entire row is available - no need to reduce the available slots\n }\n }\n\n return availableSlots;\n }\n}", + "title": "1386. Cinema Seat Allocation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row . Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_1.png", + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_3.png" + ], + "constraints": [ + "1 <= n <= 10^9", + "1 <= reservedSeats.length <= min(10*n, 10^4)", + "reservedSeats[i].length == 2", + "1 <= reservedSeats[i][0] <= n", + "1 <= reservedSeats[i][1] <= 10", + "All reservedSeats[i] are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput:4\nExplanation:The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxNumberOfFamilies(self, n, reservedSeats):\n \"\"\"\n :type n: int\n :type reservedSeats: List[List[int]]\n :rtype: int\n \"\"\"\n d = defaultdict(set)\n for row,seat in reservedSeats:\n d[row].add(seat)\n \n def row(i):\n a1 = not set((2,3,4,5)).intersection(d[i])\n a2 = not set((6,7,8,9)).intersection(d[i])\n if a1 and a2:\n return 2\n if a1 or a2:\n return 1\n return 1 if not set((4,5,6,7)).intersection(d[i]) else 0\n \n return sum((row(i) for i in d.keys())) + (n-len(d)) * 2\n\n", + "title": "1386. Cinema Seat Allocation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2) , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false . In other words, check if there is any point (x i , y i ) that belongs to the circle and the rectangle at the same time.", + "description_images": [], + "constraints": [ + "1 <= radius <= 2000", + "-10^4 <= xCenter, yCenter <= 10^4", + "-10^4 <= x1 < x2 <= 10^4", + "-10^4 <= y1 < y2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput:true\nExplanation:Circle and rectangle share the point (1,0).", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_4_1728.png" + }, + { + "text": "Example 2: Input:radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_2_1728.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 38.18%) | Memory: 41.1 MB (Top 21.82%)\nclass Solution\n{\n public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2)\n {\n return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2)\n + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius;\n }\n}", + "title": "1401. Circle and Rectangle Overlapping", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2) , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false . In other words, check if there is any point (x i , y i ) that belongs to the circle and the rectangle at the same time.", + "description_images": [], + "constraints": [ + "1 <= radius <= 2000", + "-10^4 <= xCenter, yCenter <= 10^4", + "-10^4 <= x1 < x2 <= 10^4", + "-10^4 <= y1 < y2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput:true\nExplanation:Circle and rectangle share the point (1,0).", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_4_1728.png" + }, + { + "text": "Example 2: Input:radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_2_1728.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n \n def find(a1, a2, aCenter):\n if a1 <= aCenter and aCenter <= a2:\n return 0 \n elif a1 > aCenter:\n return a1 - aCenter\n else:\n return aCenter - a2\n\n return (find(x1, x2, xCenter))**2 + (find(y1, y2, yCenter))**2 <= radius**2 \n\t```", + "title": "1401. Circle and Rectangle Overlapping", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a game involving a circular array of non-zero integers nums . Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i : Since the array is circular , you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Return true if there is a cycle in nums , or false otherwise .", + "description_images": [], + "constraints": [ + "If nums[i] is positive, move nums[i] steps forward , and", + "If nums[i] is negative, move nums[i] steps backward ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,1,2,2]\nOutput:true\nExplanation:There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...\nThe cycle's length is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,2]\nOutput:false\nExplanation:The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-2,1,-1,-2,-2]\nOutput:false\nExplanation:The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 46.1%) | Memory: 40.11 MB (Top 41.3%)\n\nclass Solution {\n public boolean circularArrayLoop(int[] nums) {\n for (int i=0; i 0;\n int slow = i;\n int fast = i; \n do {\n slow = findNextIndex(nums, isForward, slow);\n fast = findNextIndex(nums, isForward, fast);\n if (fast != -1) {\n fast = findNextIndex(nums, isForward, fast);\n }\n } while (slow != -1 && fast != -1 && slow != fast);\n if (slow != -1 && slow == fast) {\n return true;\n }\n }\n return false;\n }\n private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {\n boolean direction = arr[currentIndex] >= 0;\n if (isForward != direction) {\n return -1;\n }\n int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;\n if (nextIndex < 0) {\n nextIndex += arr.length;\n }\n if (nextIndex == currentIndex) {\n nextIndex = -1;\n }\n return nextIndex;\n }\n}", + "title": "457. Circular Array Loop", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a game involving a circular array of non-zero integers nums . Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i : Since the array is circular , you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Return true if there is a cycle in nums , or false otherwise .", + "description_images": [], + "constraints": [ + "If nums[i] is positive, move nums[i] steps forward , and", + "If nums[i] is negative, move nums[i] steps backward ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,1,2,2]\nOutput:true\nExplanation:There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...\nThe cycle's length is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,2]\nOutput:false\nExplanation:The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-2,1,-1,-2,-2]\nOutput:false\nExplanation:The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n n = len(nums)\n for i in range(n):\n seen = set()\n minval = float('inf')\n maxval = float('-inf')\n j = i\n while j not in seen:\n seen.add(j)\n minval = min(minval, nums[j])\n maxval = max(maxval, nums[j])\n k = 1 + abs(nums[j]) // n\n j = (k * n + j + nums[j]) % n\n if j == i and len(seen) > 1 and (minval > 0 or maxval < 0):\n return True\n return False\n", + "title": "457. Circular Array Loop", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given 2 integers n and start . Your task is return any permutation p of (0,1,2.....,2^n -1) such that :", + "description_images": [], + "constraints": [ + "p[0] = start", + "p[i] and p[i+1] differ by only one bit in their binary representation.", + "p[0] and p[2^n -1] must also differ by only one bit in their binary representation." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, start = 3\nOutput:[3,2,0,1]\nExplanation:The binary representation of the permutation is (11,10,00,01). \nAll the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]", + "image": null + }, + { + "text": "Example 2: Input:n = 3, start = 2\nOutput:[2,6,7,5,4,0,1,3]\nExplanation:The binary representation of the permutation is (010,110,111,101,100,000,001,011).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List circularPermutation(int n, int start) {\n List l = new ArrayList();\n int i=0;\n int len = (int)Math.pow(2,n);\n int[] arr = new int[len];\n while(i List[int]:\n gray_code = [x ^ (x >> 1) for x in range(2 ** n)]\n start_i = gray_code.index(start)\n return gray_code[start_i:] + gray_code[:start_i]", + "title": "1238. Circular Permutation in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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?", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:3\nExplanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.00 MB (Top 80.9%)\n\nclass Solution {\n public int climbStairs(int n) {\n int[] memo = new int[n + 1];\n return calculateWays(n, memo);\n }\n \n private int calculateWays(int n, int[] memo) {\n if (n == 1 || n == 2) {\n return n;\n }\n \n if (memo[n] != 0) {\n return memo[n];\n }\n \n memo[n] = calculateWays(n - 1, memo) + calculateWays(n - 2, memo);\n return memo[n];\n }\n}", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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?", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:3\nExplanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n memo ={}\n memo[1] = 1\n memo[2] = 2\n \n def climb(n):\n if n in memo: # if the recurssion already done before first take a look-up in the look-up table\n return memo[n]\n else: # Store the recurssion function in the look-up table and reuturn the stored look-up table function\n memo[n] = climb(n-1) + climb(n-2)\n return memo[n]\n \n return climb(n)", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. 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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput:[[2,4],[1,3],[2,4],[1,3]]\nExplanation:There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: Input:adjList = [[]]\nOutput:[[]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []\nOutput:[]\nExplanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public void dfs(Node node , Node copy , Node[] visited){\n visited[copy.val] = copy;// store the current node at it's val index which will tell us that this node is now visited\n \n// now traverse for the adjacent nodes of root node\n for(Node n : node.neighbors){\n// check whether that node is visited or not\n// if it is not visited, there must be null\n if(visited[n.val] == null){\n// so now if it not visited, create a new node\n Node newNode = new Node(n.val);\n// add this node as the neighbor of the prev copied node\n copy.neighbors.add(newNode);\n// make dfs call for this unvisited node to discover whether it's adjacent nodes are explored or not\n dfs(n , newNode , visited);\n }else{\n// if that node is already visited, retrieve that node from visited array and add it as the adjacent node of prev copied node\n// THIS IS THE POINT WHY WE USED NODE[] INSTEAD OF BOOLEAN[] ARRAY\n copy.neighbors.add(visited[n.val]);\n }\n }\n \n }\n public Node cloneGraph(Node node) {\n if(node == null) return null; // if the actual node is empty there is nothing to copy, so return null\n Node copy = new Node(node.val); // create a new node , with same value as the root node(given node)\n Node[] visited = new Node[101]; // in this question we will create an array of Node(not boolean) why ? , because i have to add all the adjacent nodes of particular vertex, whether it's visited or not, so in the Node[] initially null is stored, if that node is visited, we will store the respective node at the index, and can retrieve that easily.\n Arrays.fill(visited , null); // initially store null at all places\n dfs(node , copy , visited); // make a dfs call for traversing all the vertices of the root node\n return copy; // in the end return the copy node\n }\n}\n", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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. 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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput:[[2,4],[1,3],[2,4],[1,3]]\nExplanation:There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: Input:adjList = [[]]\nOutput:[[]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []\nOutput:[]\nExplanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": " def cloneGraph(self, node: 'Node') -> 'Node':\n \n if node == None:\n return None\n \n new_node = Node(node.val, [])\n \n visited = set()\n \n q = [[node, new_node]]\n visited.add(node.val)\n \n adj_map = {}\n \n adj_map[node] = new_node\n \n while len(q) != 0:\n \n curr = q.pop(0)\n \n \n for n in curr[0].neighbors:\n \n # if n.val not in visited:\n if n not in adj_map and n is not None:\n new = Node(n.val, [])\n curr[1].neighbors.append(new)\n adj_map[n] = new\n else:\n curr[1].neighbors.append(adj_map[n])\n \n if n.val not in visited:\n q.append([n, adj_map[n]])\n visited.add(n.val) \n \n \n return new_node\n\n", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target . If there are multiple, return the lower one.", + "description_images": [], + "constraints": [ + "There must be exactly one ice cream base.", + "You can add one or more types of topping or have no toppings at all.", + "There are at most two of each type of topping." + ], + "examples": [ + { + "text": "Example 1: Input:baseCosts = [1,7], toppingCosts = [3,4], target = 10\nOutput:10\nExplanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.", + "image": null + }, + { + "text": "Example 2: Input:baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\nOutput:17\nExplanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.", + "image": null + }, + { + "text": "Example 3: Input:baseCosts = [3,10], toppingCosts = [2,5], target = 9\nOutput:8\nExplanation:It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.0%) | Memory: 39.60 MB (Top 90.1%)\n\nclass Solution {\n /** Closest cost result */\n int closestCost = Integer.MAX_VALUE;\n /** Difference between closest cost result and target so far */\n int closestCostDiff = Integer.MAX_VALUE;\n\n public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {\n for (int base : baseCosts) {\n dfs(toppingCosts, 0, base, target);\n }\n return closestCost;\n }\n\n public void dfs(int[] toppingCosts, int toppingIndex, int cost, int target) {\n int costDiff = Math.abs(target - cost);\n if (costDiff < closestCostDiff || (costDiff == closestCostDiff && cost < closestCost)) {\n closestCostDiff = costDiff;\n closestCost = cost;\n }\n \n // Since toppings are all positive cost, stop dfs early if cost exceeds target\n if (toppingIndex >= toppingCosts.length || cost > target)\n return;\n\n dfs(toppingCosts, toppingIndex + 1, cost, target);\n dfs(toppingCosts, toppingIndex + 1, cost + toppingCosts[toppingIndex], target);\n dfs(toppingCosts, toppingIndex + 1, cost + 2 * toppingCosts[toppingIndex], target);\n }\n}", + "title": "1774. Closest Dessert Cost", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target . If there are multiple, return the lower one.", + "description_images": [], + "constraints": [ + "There must be exactly one ice cream base.", + "You can add one or more types of topping or have no toppings at all.", + "There are at most two of each type of topping." + ], + "examples": [ + { + "text": "Example 1: Input:baseCosts = [1,7], toppingCosts = [3,4], target = 10\nOutput:10\nExplanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.", + "image": null + }, + { + "text": "Example 2: Input:baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\nOutput:17\nExplanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.", + "image": null + }, + { + "text": "Example 3: Input:baseCosts = [3,10], toppingCosts = [2,5], target = 9\nOutput:8\nExplanation:It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n self.ans = self.diff = float('inf')\n \n n = len(baseCosts)\n m = len(toppingCosts)\n \n \n def solve(sum, target, indx):\n if abs(sum - target) < self.diff:\n self.diff = abs(sum - target)\n self.ans = sum\n elif abs(sum - target) == self.diff:\n self.ans = min(self.ans, sum)\n \n \n if indx == m:\n return\n \n i = indx\n for count in range(3):\n sum += toppingCosts[i]*count\n solve(sum,target,i+1)\n sum -= toppingCosts[i]*count\n \n for i in baseCosts:\n solve(i, target, 0)\n return self.ans\n", + "title": "1774. Closest Dessert Cost", + "topic": "Stack" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer num , find the closest two integers in absolute difference whose product equals num + 1 or num + 2 . Return the two integers in any order.", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 8\nOutput:[3,3]\nExplanation:For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.", + "image": null + }, + { + "text": "Example 2: Input:num = 123\nOutput:[5,25]", + "image": null + }, + { + "text": "Example 3: Input:num = 999\nOutput:[40,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] closestDivisors(int num) {\n int ans[]=new int[2];\n double a=Math.sqrt(num+1);\n double b=Math.sqrt(num+2);\n if(num==1){\n ans[0]=1;\n ans[1]=2;\n return ans;\n }\n else if(a%1==0){\n ans[0]=(int)a;\n ans[1]=(int)b;\n return ans;\n }\n else if(b%1==0){\n ans[0]=(int)b;\n ans[1]=(int)b;\n return ans;\n }\n else{\n int m=(int)Math.sqrt(num);\n int diff1=Integer.MAX_VALUE;\n int y=0,z=0,w=0,f=0;\n for(int i=2;i<=m;i++){\n if((num+1)%i==0){\n y=i;\n z=(num+1)/y;\n int r=Math.abs(y-z);\n if(r List[int]:\n\t\tfor i in range(int((num+2) ** (0.5)), 0, -1): \n\t\t\tif not (num+1) % i: return [i, (num+1)//i] \n\t\t\tif not (num+2) % i: return [i, (num+2)//i] \n\t\treturn []\n", + "title": "1362. Closest Divisors", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomId i , size i ] denotes that there is a room with room number roomId i and size equal to size i . Each roomId i is guaranteed to be unique . You are also given k queries in a 2D array queries where queries[j] = [preferred j , minSize j ] . The answer to the j th query is the room number id of a room such that: If there is a tie in the absolute difference, then use the room with the smallest such id . If there is no such room , the answer is -1 . Return an array answer of length k where answer[j] contains the answer to the j th query .", + "description_images": [], + "constraints": [ + "The room has a size of at least minSize j , and", + "abs(id - preferred j ) is minimized , where abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\nOutput:[3,-1,3]\nExplanation:The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\nOutput:[2,1,3]\nExplanation:The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 164 ms (Top 39.53%) | Memory: 127.2 MB (Top 83.72%)\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decreasing order of room size\n Arrays.sort(indexes, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); // Sort by decreasing order of query minSize\n TreeSet roomIdsSoFar = new TreeSet<>();\n int[] ans = new int[k];\n int i = 0;\n for (int index : indexes) {\n while (i < n && rooms[i][1] >= queries[index][1]) { // Add id of the room which its size >= query minSize\n roomIdsSoFar.add(rooms[i++][0]);\n }\n ans[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0]);\n }\n return ans;\n }\n int searchClosetRoomId(TreeSet treeSet, int preferredId) {\n Integer floor = treeSet.floor(preferredId);\n Integer ceiling = treeSet.ceiling(preferredId);\n int ansAbs = Integer.MAX_VALUE, ans = -1;\n if (floor != null) {\n ans = floor;\n ansAbs = Math.abs(preferredId - floor);\n }\n if (ceiling != null && ansAbs > Math.abs(preferredId - ceiling)) {\n ans = ceiling;\n }\n return ans;\n }\n}", + "title": "1847. Closest Room", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomId i , size i ] denotes that there is a room with room number roomId i and size equal to size i . Each roomId i is guaranteed to be unique . You are also given k queries in a 2D array queries where queries[j] = [preferred j , minSize j ] . The answer to the j th query is the room number id of a room such that: If there is a tie in the absolute difference, then use the room with the smallest such id . If there is no such room , the answer is -1 . Return an array answer of length k where answer[j] contains the answer to the j th query .", + "description_images": [], + "constraints": [ + "The room has a size of at least minSize j , and", + "abs(id - preferred j ) is minimized , where abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\nOutput:[3,-1,3]\nExplanation:The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\nOutput:[2,1,3]\nExplanation:The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1741 ms (Top 100.0%) | Memory: 67.86 MB (Top 93.7%)\n\nclass Solution:\n def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:\n ans = [0] * len(queries)\n \n # sort queries to handle largest size queries first\n q = deque(sorted([(size, room, i) for i, (room, size) in enumerate(queries)], key=lambda a: (-a[0], a[1], a[2])))\n\n # sort rooms by descending size\n rooms = deque(sorted(rooms, key=lambda x: -x[1]))\n\n # current available room ids\n cands = []\n \n \n while q:\n size, room, i = q.popleft()\n # add room ids to candidates as long as top of room size meet the requirements\n while rooms and rooms[0][1] >= size:\n bisect.insort(cands, rooms.popleft()[0])\n \n # if no room size available, return -1\n if not cands: ans[i] = -1\n \n # else use bisect to find optimal room ids\n else:\n loc = bisect.bisect_left(cands, room)\n if loc == 0: ans[i] = cands[loc]\n elif loc == len(cands): ans[i] = cands[-1]\n else: ans[i] = cands[loc - 1] if room - cands[loc - 1] <= cands[loc] - room else cands[loc]\n \n return ans", + "title": "1847. Closest Room", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums and an integer goal . You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal . That is, if the sum of the subsequence's elements is sum , then you want to minimize the absolute difference abs(sum - goal) . Return the minimum possible value of abs(sum - goal) . Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 40", + "-10^7 <= nums[i] <= 10^7", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,-7,3,5], goal = 6\nOutput:0\nExplanation:Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,-9,15,-2], goal = -5\nOutput:1\nExplanation:Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], goal = -7\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] arr;\n public int minAbsDifference(int[] nums, int goal) {\n arr = nums;\n int n = nums.length;\n \n \n List first = new ArrayList<>();\n List second = new ArrayList<>();\n \n generate(0,n/2,0, first); //generate all possible subset sums from half the array\n generate(n/2, n , 0, second);//generate all possible subset sums from the second half of the array\n \n \n Collections.sort(first);\n int ans = Integer.MAX_VALUE;\n \n \n for(int secondSetSum : second ) {\n int left = goal - secondSetSum; // How far off are we from the desired goal?\n \n if(first.get(0) > left) { // all subset sums from first half are too big => Choose the smallest\n ans = (int)(Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal)));\n continue;\n }\n if(first.get(first.size() - 1) < left) { // all subset sums from first half are too small => Choose the largest\n ans = (int)(Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal)));\n continue;\n }\n int pos = Collections.binarySearch(first, left);\n if(pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal\n return 0;\n else // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1)\n pos = -1 * (pos + 1);\n int low = pos - 1;\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(low) - goal)); // Checking for the floor value (largest sum < goal)\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(pos) - goal)); //Checking for the ceiling value (smallest sum > goal)\n }\n return ans;\n }\n\n /**\n * Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick \n */\n void generate(int i, int end, int sum, List listOfSubsetSums) {\n if (i == end) {\n listOfSubsetSums.add(sum); //add\n return;\n }\n generate(i + 1, end, sum + arr[i], set);\n generate(i + 1, end, sum, set);\n \n }\n \n \n \n}\n", + "title": "1755. Closest Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer goal . You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal . That is, if the sum of the subsequence's elements is sum , then you want to minimize the absolute difference abs(sum - goal) . Return the minimum possible value of abs(sum - goal) . Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 40", + "-10^7 <= nums[i] <= 10^7", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,-7,3,5], goal = 6\nOutput:0\nExplanation:Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,-9,15,-2], goal = -5\nOutput:1\nExplanation:Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], goal = -7\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n\n # When goal 0 we can just choose no elements \n if goal == 0: return 0\n\n n = len(nums)\n mid = n // 2\n # Split the list in 2 parts and then find all possible subset sums \n # T = O(2^n/2) to build all subset sums\n leftList = nums[:mid]\n leftSums = []\n rightList = nums[mid:]\n rightSums = []\n\n # T = O(2^n/2) to build all subset sums (we only consider half list)\n def buildSubsetSums(usedNums, numsToChooseFrom, ind, storeIn):\n if ind == len(numsToChooseFrom):\n # We also keep elements with sum 0 to deal with cases like this where we don't select nums\n # List: [1,2,3], Target: -7 (choosing no elements will give a sum close to goal)\n # We can also have cases where we want to take only 1 element from the list\n # so sum 0 for left and right list needs to be an option\n storeIn.append(sum(usedNums))\n return \n\n usedNums.append(numsToChooseFrom[ind])\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n usedNums.pop()\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n\n\n buildSubsetSums([], leftList, 0, leftSums)\n buildSubsetSums([], rightList, 0, rightSums)\n # 2^n/2 log(2^n/2) = n/2 * 2^n/2 time to sort\n rightSums.sort()\n\n diff = float('inf')\n\n # Loop runs 2^n/2 times and inside binary search tale n/2 time \n # So total time is n/2 * 2^n/2\n for leftSum in leftSums:\n complement = goal - leftSum\n # Bisect left takes log(2^n/2) = n/2 search time\n idx = bisect.bisect_left(rightSums, complement)\n\n for i in [idx - 1, idx, idx + 1]:\n if 0 <= i < len(rightSums):\n finalSum = leftSum + rightSums[i]\n diff = min(diff, abs(goal - finalSum))\n \n # Over all time complexity is - n/2 * 2^n/2\n # 1. Making subset sums will take - 2^n/2\n # 2. Sorting right list takes - 2^n/2 * n/2\n # 3. Iterating one list and finding closest complement in other \n # takes n/2 * 2^n/2\n # Space will be O(n/2) for the list and call stack for building subset \n return diff\n\n", + "title": "1755. Closest Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The factorial of a positive integer n is the product of all positive integers less than or equal to n . We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*' , divide '/' , add '+' , and subtract '-' in this order. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11 . Given an integer n , return the clumsy factorial of n .", + "description_images": [], + "constraints": [ + "For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:7\nExplanation:7 = 4 * 3 / 2 + 1", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:12\nExplanation:12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 67.15%) | Memory: 13.9 MB (Top 59.65%)\nclass Solution:\n def clumsy(self, n: int) -> int:\n if(n>2):\n sum=n*(n-1)//(n-2)+(n-3)\n else:\n sum=n\n for i in range(n-4,0,-4):\n if(i<3):\n sum=sum-i\n break;\n sum=sum-(i)*(i-1)//(i-2)+(i-3)\n\n return sum", + "title": "1006. Clumsy Factorial", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 300", + "1 <= coins[i] <= 5000", + "All the values of coins are unique .", + "0 <= amount <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:amount = 5, coins = [1,2,5]\nOutput:4\nExplanation:there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1", + "image": null + }, + { + "text": "Example 2: Input:amount = 3, coins = [2]\nOutput:0\nExplanation:the amount of 3 cannot be made up just with coins of 2.", + "image": null + }, + { + "text": "Example 3: Input:amount = 10, coins = [10]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 47.6%) | Memory: 43.93 MB (Top 22.2%)\n\nclass Solution {\n public int coinChange(int[] coins, int amount) {\n int m=coins.length,n=amount;\n int dp[][]=new int[m+1][n+1];\n for(int j=0;j<=n;j++){\n dp[0][j]=0;\n }\n for(int i=0;i<=m;i++){\n dp[i][0]=0;\n }\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n int t1 = Integer.MAX_VALUE;\n if ((i-1) == 0) {\n if (j % coins[i-1] == 0) {\n dp[i][j]= j / coins[i-1];\n } else {\n dp[i][j]= (int)1e9;\n }\n } \n else {\n int t2 = dp[i-1][j];\n if (coins[i-1] <= j) {\n t1 = dp[i][j-coins[i-1]] + 1; \n }\n dp[i][j]= Math.min(t1, t2);\n }\n }\n }\n if(dp[m][n]>=1e9)\n return -1;\n else\n return dp[m][n];\n }\n }\n \n ", + "title": "518. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 300", + "1 <= coins[i] <= 5000", + "All the values of coins are unique .", + "0 <= amount <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:amount = 5, coins = [1,2,5]\nOutput:4\nExplanation:there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1", + "image": null + }, + { + "text": "Example 2: Input:amount = 3, coins = [2]\nOutput:0\nExplanation:the amount of 3 cannot be made up just with coins of 2.", + "image": null + }, + { + "text": "Example 3: Input:amount = 10, coins = [10]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 724 ms (Top 91.98%) | Memory: 17.70 MB (Top 44.11%)\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n numCoins = len(coins)\n \n # Values in this array equal the number of coins needed to achieve the cost of the index\n minCoins = [amount + 1] * (amount + 1)\n minCoins[0] = 0\n \n # Loop through every needed amount\n for i in range(amount + 1):\n # Loop through every coin value\n for coin in coins:\n # Check that the coin is not bigger than the current amount\n if coin <= i:\n # minCoins[i]: number of coins needed to make amount i\n # minCoins[i-coin]: number of coins needed to make the amount before adding \n # the current coin to it (+1 to add the current coin)\n minCoins[i] = min(minCoins[i], minCoins[i-coin] + 1)\n \n # Check if any combination of coins was found to create the amount\n if minCoins[amount] == amount + 1:\n return -1\n \n # Return the optimal number of coins to create the amount\n return minCoins[amount]\n", + "title": "518. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid , and three integers row , col , and color . Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color . Return the final grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j], color <= 1000", + "0 <= row < m", + "0 <= col < n" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput:[[3,3],[3,2]]", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput:[[1,3,3],[2,3,3]]", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput:[[2,2,2],[2,1,2],[2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] colorBorder(int[][] grid, int row, int col, int color) {\n dfs(grid,row,col,grid[row][col]);\n for(int i = 0;i=grid.length||coldash>=grid[0].length||\n Math.abs(grid[rowdash][coldash])!=color)\n {\n continue;\n }\n count++;\n \n if(grid[rowdash][coldash]==color)\n {\n dfs(grid,rowdash,coldash,color);\n }\n \n }\n if(count==4)\n {\n grid[row][col] = color;\n }\n \n }\n}\n", + "title": "1034. Coloring A Border", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid , and three integers row , col , and color . Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color . Return the final grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j], color <= 1000", + "0 <= row < m", + "0 <= col < n" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput:[[3,3],[3,2]]", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput:[[1,3,3],[2,3,3]]", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput:[[2,2,2],[2,1,2],[2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 136 ms (Top 91.96%) | Memory: 14.4 MB (Top 28.67%)\n\nclass Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n\n rows, cols = len(grid), len(grid[0])\n border_color = grid[row][col]\n border = []\n\n # Check if a node is a border node or not\n def is_border(r, c):\n if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n return True\n\n for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n nr, nc = r + dr, c + dc\n if grid[nr][nc] != border_color:\n return True\n return False\n\n def dfs(r, c):\n if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color:\n return\n visited.add((r, c))\n\n if is_border(r, c):\n border.append((r, c))\n\n dfs(r + 1, c)\n dfs(r - 1, c)\n dfs(r, c + 1)\n dfs(r, c - 1)\n\n visited = set()\n dfs(row, col)\n for r, c in border:\n grid[r][c] = color\n return grid", + "title": "1034. Coloring A Border", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "1 <= candidates[i] <= 200", + "All elements of candidates are distinct .", + "1 <= target <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7\nOutput:[[2,2,3],[7]]\nExplanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8\nOutput:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 69.68%) | Memory: 45.9 MB (Top 24.67%)\nclass Solution {\n public List> combinationSum(int[] candidates, int target) {\n List cur = new ArrayList<>();\n List> result = new ArrayList<>();\n Arrays.sort(candidates);\n dfs(0, candidates, target, 0, cur, result);\n return result;\n }\n public void dfs(int start, int[] candidates, int target, int sum, List cur, List> result){\n if(sum == target){\n result.add(new ArrayList<>(cur));\n return;\n }\n for(int i = start; i < candidates.length; i++) {\n if(sum + candidates[i] <= target) {\n cur.add(candidates[i]);\n dfs(i, candidates, target, sum + candidates[i], cur, result);\n cur.remove((cur.size()- 1));\n }\n }\n return;\n }\n}", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "1 <= candidates[i] <= 200", + "All elements of candidates are distinct .", + "1 <= target <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7\nOutput:[[2,2,3],[7]]\nExplanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8\nOutput:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 82.54%) | Memory: 14.1 MB (Top 72.96%)\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n\n path = []\n answer = []\n def dp(idx, total):\n if total == target:\n answer.append(path[:])\n return\n if total > target:\n return\n\n for i in range(idx, len(candidates)):\n path.append(candidates[i])\n dp(i, total + candidates[i])\n path.pop()\n\n dp(0, 0)\n return answer\n", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8\nOutput:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5\nOutput:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 12.41%) | Memory: 43.5 MB (Top 81.01%)\nclass Solution {\n public List> combinationSum2(int[] candidates, int target) {\n List> res = new ArrayList<>();\n List path = new ArrayList<>();\n // O(nlogn)\n Arrays.sort(candidates);\n boolean[] visited = new boolean[candidates.length];\n helper(res, path, candidates, visited, target, 0);\n return res;\n }\n private void helper(List> res,\n List path, int[] candidates,\n boolean[] visited, int remain, int currIndex\n ){\n if (remain == 0){\n res.add(new ArrayList<>(path));\n return;\n }\n if (remain < 0){\n return;\n }\n\n for(int i = currIndex; i < candidates.length; i++){\n if (visited[i]){\n continue;\n }\n if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){\n continue;\n }\n int curr = candidates[i];\n path.add(curr);\n visited[i] = true;\n helper(res, path, candidates, visited, remain - curr, i + 1);\n path.remove(path.size() - 1);\n\n visited[i] = false;\n }\n }\n}", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8\nOutput:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5\nOutput:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 204 ms (Top 15.17%) | Memory: 14.1 MB (Top 23.77%)\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n res = []\n def dfs(nums,summ,curr):\n if summ>=target:\n if summ == target:\n res.append(curr)\n return\n for i in range(len(nums)):\n if i !=0 and nums[i]==nums[i-1]:\n continue\n dfs(nums[i+1:],summ+nums[i],curr+[nums[i]])\n dfs(sorted(candidates),0,[])\n return res", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order.", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7\nOutput:[[1,2,4]]\nExplanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9\nOutput:[[1,2,6],[1,3,5],[2,3,4]]\nExplanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1\nOutput:[]\nExplanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.54%) | Memory: 41.2 MB (Top 80.80%)\n\n//Recursion\n\nclass Solution {\n public List> combinationSum3(int k, int n) {\n List> ans = new ArrayList>();\n //int[] arr = new int{1,2,3,4,5,6,7,8,9};\n List ds = new ArrayList<>();\n helper(1, n, k, ds, ans);\n return ans;\n }\n private static void helper(int i, int tar, int k, List ds, List> ans){\n //base\n if(k == 0) {\n if(tar == 0){\n ans.add(new ArrayList<>(ds));\n }\n return;\n }\n if(tar == 0) return; //bcz if k is not zero and tar is zero then no possible valid combination\n if(i > tar) return;\n if(i > 9) return;\n\n //Take\n if(i <= tar) {\n ds.add(i);\n helper(i+1, tar - i, k-1 , ds, ans);\n ds.remove(ds.size()-1);\n }\n // Not take\n helper(i+1 , tar, k , ds, ans);\n\n return;\n }\n}", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order.", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7\nOutput:[[1,2,4]]\nExplanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9\nOutput:[[1,2,6],[1,3,5],[2,3,4]]\nExplanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1\nOutput:[]\nExplanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n \n def solve(self,k,target,ans,temp,idx,nums):\n \n if idx==len(nums):\n if target==0 and k==0:\n ans.append(list(temp))\n return\n \n if nums[idx]<=target:\n \n temp.append(nums[idx])\n self.solve(k-1,target-nums[idx],ans,temp,idx+1,nums)\n temp.pop()\n \n self.solve(k,target,ans,temp,idx+1,nums)\n \n\n \n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n \n ans = []\n temp = []\n idx = 0\n nums = list(range(1,10))\n \n self.solve(k,n,ans,temp,idx,nums)\n return ans\n \n", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of distinct integers nums and a target integer target , return the number of possible combinations that add up to target . The test cases are generated so that the answer can fit in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 1000", + "All the elements of nums are unique .", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], target = 4\nOutput:7\nExplanation:The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9], target = 3\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int combinationSum4(int[] nums, int target) {\n Integer[] memo = new Integer[target + 1];\n return recurse(nums, target, memo);\n }\n \n public int recurse(int[] nums, int remain, Integer[] memo){\n \n if(remain < 0) return 0;\n if(memo[remain] != null) return memo[remain];\n if(remain == 0) return 1;\n \n int ans = 0;\n for(int i = 0; i < nums.length; i++){\n ans += recurse(nums, remain - nums[i], memo);\n }\n \n memo[remain] = ans;\n return memo[remain];\n }\n}\n", + "title": "377. Combination Sum IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of distinct integers nums and a target integer target , return the number of possible combinations that add up to target . The test cases are generated so that the answer can fit in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 1000", + "All the elements of nums are unique .", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], target = 4\nOutput:7\nExplanation:The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9], target = 3\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n dp = [0] * (target+1)\n dp[0] = 1\n for i in range(1, target+1):\n for num in nums: \n num_before = i - num\n if num_before >= 0:\n dp[i] += dp[num_before]\n return dp[target]\n", + "title": "377. Combination Sum IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2\nOutput:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1\nOutput:[[1]]\nExplanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combine(int n, int k) {\n List> subsets=new ArrayList<>();\n generatesubsets(1,n,new ArrayList(),subsets,k);\n return subsets;\n }\n void generatesubsets(int start,int n,List current,List> subsets,int k){\n if(current.size()==k){\n subsets.add(new ArrayList(current));\n }\n for(int i=start;i<=n;i++){\n current.add(i);\n generatesubsets(i+1,n,current,subsets,k);\n current.remove(current.size()-1);\n }\n }\n}\n", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2\nOutput:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1\nOutput:[[1]]\nExplanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return itertools.combinations(range(1, n+1), k)", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s . For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c' , which has a frequency of 2. You are given an array of strings words and another array of query strings queries . For each query queries[i] , count the number of words in words such that f(queries[i]) < f(W) for each W in words . Return an integer array answer , where each answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 2000", + "1 <= words.length <= 2000", + "1 <= queries[i].length, words[i].length <= 10", + "queries[i][j] , words[i][j] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput:[1]\nExplanation:On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput:[1,2]\nExplanation:On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.83%) | Memory: 46.8 MB (Top 47.53%)\nclass Solution {\n public int[] numSmallerByFrequency(String[] queries, String[] words) {\n int[] ans = new int[queries.length];\n int[] freq = new int[words.length];\n for (int i = 0; i < words.length; i++) {\n freq[i] = freqOfSmallest(words[i]);\n }\n Arrays.sort(freq);\n int k = 0;\n for (String query : queries) {\n int target = freqOfSmallest(query);\n ans[k++] = binarySearch(freq, target);\n }\n return ans;\n }\n public int freqOfSmallest(String s) {\n int[] freq = new int[26];\n char min = 'z';\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n freq[c - 'a'] += 1;\n if (c < min) {\n min = c;\n }\n }\n return freq[min - 'a'];\n }\n public int binarySearch(int[] arr, int target) {\n int idx = arr.length;\n int lo = 0;\n int hi = idx - 1;\n int mid;\n while (lo <= hi) {\n mid = (lo + hi) / 2;\n if (arr[mid] <= target) {\n lo = mid + 1;\n } else {\n idx = mid;\n hi = mid - 1;\n }\n }\n return arr.length - idx;\n }\n}", + "title": "1170. Compare Strings by Frequency of the Smallest Character", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s . For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c' , which has a frequency of 2. You are given an array of strings words and another array of query strings queries . For each query queries[i] , count the number of words in words such that f(queries[i]) < f(W) for each W in words . Return an integer array answer , where each answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 2000", + "1 <= words.length <= 2000", + "1 <= queries[i].length, words[i].length <= 10", + "queries[i][j] , words[i][j] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput:[1]\nExplanation:On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput:[1,2]\nExplanation:On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n def _f(s):\n d = Counter(s)\n d =dict(sorted(d.items(), key=lambda item: item[0]))\n for x in d:\n return d[x]\n \n freq = []\n for w in words:\n n1 = _f(w)\n freq.append(n1)\n \n freq.sort(reverse=True)\n\n res = []\n for q in queries:\n n = _f(q)\n c=0\n for n1 in freq:\n if n < n1:\n c+=1\n else:\n break\n res.append(c)\n \n return res\n", + "title": "1170. Compare Strings by Frequency of the Smallest Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two version numbers, version1 and version2 , compare them. Version numbers consist of one or more revisions joined by a dot '.' . Each revision consists of digits and may contain leading zeros . Every revision contains at least one character . Revisions are 0-indexed from left to right , with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order . Revisions are compared using their integer value ignoring any leading zeros . This means that revisions 1 and 001 are considered equal . If a version number does not specify a revision at an index, then treat the revision as 0 . For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1 . Return the following:", + "description_images": [], + "constraints": [], + "examples": [ + { + "text": "Example 1: Input:version1 = \"1.01\", version2 = \"1.001\"\nOutput:0\nExplanation:Ignoring leading zeroes, both \"01\" and \"001\" represent the same integer \"1\".", + "image": null + }, + { + "text": "Example 2: Input:version1 = \"1.0\", version2 = \"1.0.0\"\nOutput:0\nExplanation:version1 does not specify revision 2, which means it is treated as \"0\".", + "image": null + }, + { + "text": "Example 3: Input:version1 = \"0.1\", version2 = \"1.1\"\nOutput:-1\nExplanation:version1's revision 0 is \"0\", while version2's revision 0 is \"1\". 0 < 1, so version1 < version2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compareVersion(String version1, String version2) {\n\t//Here we are going to Split the numbers by . but since we cannot do that in java we will replace . with # and then do it \n version1=version1.replace('.', '#');\n version2=version2.replace('.', '#');\n \n String v1[]=version1.split(\"#\");\n String v2[]=version2.split(\"#\");\n \n int i=0;\n \n\t\t\n while(ii2){\n return 1;\n }\n i++;\n }\n\t\t//if all the statments are false then at last we can say that they are equal\n return 0;\n }\n String removezero(String s){\n String result =\"\";\n int i =0;\n while(i int:\n v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.'))) \n for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):\n if rev1 == rev2:\n continue\n\n return -1 if rev1 < rev2 else 1 \n\n return 0", + "title": "165. Compare Version Numbers", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer n , return its complement .", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:0\nExplanation:7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.", + "image": null + }, + { + "text": "Example 3: Input:n = 10\nOutput:5\nExplanation:10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 20.2%) | Memory: 39.34 MB (Top 43.8%)\n\nclass Solution {\n public int bitwiseComplement(int n) {\n String bin = Integer.toBinaryString(n);\n String res = \"\";\n for(char c :bin.toCharArray())\n {\n if( c == '1')\n res += \"0\";\n else\n res += \"1\";\n }\n return Integer.parseInt(res, 2);\n }\n}", + "title": "1009. Complement of Base 10 Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer n , return its complement .", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:0\nExplanation:7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.", + "image": null + }, + { + "text": "Example 3: Input:n = 10\nOutput:5\nExplanation:10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 52.6%) | Memory: 17.10 MB (Top 12.47%)\n\nclass Solution:\n def bitwiseComplement(self, n: int) -> int:\n cnt=0\n ans=0\n if n==0:\n return 1\n while n>0:\n if n&1:\n cnt+=1\n else:\n ans =ans +(2**cnt)\n cnt+=1\n n=n>>1\n return ans\n", + "title": "1009. Complement of Base 10 Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class:", + "description_images": [], + "constraints": [ + "CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.", + "int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode .", + "TreeNode get_root() Returns the root node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n[[[1, 2]], [3], [4], []]Output[null, 1, 2, [1, 2, 3, 4]]ExplanationCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3); // return 1\ncBTInserter.insert(4); // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]", + "image": "https://assets.leetcode.com/uploads/2021/08/03/lc-treeinsert.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 23.02%) | Memory: 47.3 MB (Top 32.61%)\nclass CBTInserter {\n\n private TreeNode root;\n private int total;\n\n private int count(TreeNode root) {\n if (root == null) return 0;\n return 1+count(root.left)+count(root.right);\n }\n\n public CBTInserter(TreeNode root) {\n this.root = root;\n total = count(root);\n }\n\n private int insertBinary(int val, int k, int right) {\n int left = 0;\n var ptr = root;\n while (left < right) {\n if (left == right -1) {\n if (ptr.left == null) ptr.left = new TreeNode(val);\n else ptr.right = new TreeNode(val);\n return ptr.val;\n }\n int mid = (right-left) / 2 + left;\n if (mid >= k ) {\n ptr = ptr.left;\n right = mid;\n } else if (mid < k) {\n left = mid+1;\n ptr = ptr.right;\n }\n }\n return 0;\n }\n\n public int insert(int val) {\n int depth = 0;\n int n = total;\n while(n > 0) {\n depth++;\n n /= 2;\n }\n if ((1< int:\n \n parent = self.parent_keeper[0]\n \n\t\t# Insert with leftward compact, to meet the definition of complete binary tree\n\t\t\n if not parent.left:\n parent.left = TreeNode( v )\n self.parent_keeper.append( parent.left )\n else:\n parent.right = TreeNode( v )\n self.parent_keeper.append( parent.right )\n \n # current parent is completed with two child now, pop parent from parent keeper on the head\n self.parent_keeper.popleft()\n \n return parent.val\n \n\n def get_root(self) -> TreeNode:\n \n return self.root\n", + "title": "919. Complete Binary Tree Inserter", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A complex number can be represented as a string on the form \" real + imaginary i\" where: Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications .", + "description_images": [], + "constraints": [ + "real is the real part and is an integer in the range [-100, 100] .", + "imaginary is the imaginary part and is an integer in the range [-100, 100] .", + "i 2 == -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"1+1i\", num2 = \"1+1i\"\nOutput:\"0+2i\"\nExplanation:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput:\"0+-2i\"\nExplanation:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String complexNumberMultiply(String num1, String num2) {\n int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+')));\n int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1));\n int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+')));\n int val4 = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1));\n \n return \"\" + (val1*val3 - val2*val4) + \"+\" + (val1*val4 + val3*val2) + \"i\";\n }\n}\n", + "title": "537. Complex Number Multiplication", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A complex number can be represented as a string on the form \" real + imaginary i\" where: Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications .", + "description_images": [], + "constraints": [ + "real is the real part and is an integer in the range [-100, 100] .", + "imaginary is the imaginary part and is an integer in the range [-100, 100] .", + "i 2 == -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"1+1i\", num2 = \"1+1i\"\nOutput:\"0+2i\"\nExplanation:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput:\"0+-2i\"\nExplanation:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n i1=num1.index('+')\n i2=num2.index('+')\n a=int(num1[0:i1])\n x=int(num2[0:i2])\n b=int(num1[i1+1:len(num1)-1])\n y=int(num2[i2+1:len(num2)-1])\n ans1=a*x+(-1)*b*y\n ans2=a*y+b*x\n return str(ans1)+'+'+(str(ans2)+'i')", + "title": "537. Complex Number Multiplication", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words ( without duplicates ), return all the concatenated words in the given list of words . A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= words[i].length <= 30", + "words[i] consists of only lowercase English letters.", + "All the strings of words are unique .", + "1 <= sum(words[i].length) <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\nOutput:[\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\nExplanation:\"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cat\",\"dog\",\"catdog\"]\nOutput:[\"catdog\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 46.55%) | Memory: 48.10 MB (Top 75.28%)\n\nclass Solution {\npublic List findAllConcatenatedWordsInADict(String[] words) {\n //sort the array in asc order of word length, since longer words are formed by shorter words.\n Arrays.sort(words, (a,b) -> a.length() - b.length());\n\n List result = new ArrayList<>();\n\n //list of shorter words \n HashSet preWords = new HashSet<>();\n\n for(int i=0; i< words.length; i++){\n //Word Break-I problem.\n if(topDown(words[i], preWords, 0, new Boolean[words[i].length()])) {\n result.add(words[i]);\n }\n preWords.add(words[i]);\n }\n return result;\n }\n\nprivate boolean topDown(String s, HashSet wordDict, int startIndex, Boolean[] memo) {\n if(wordDict.isEmpty()) {\n return false;\n }\n // if we reach the beyond the string, then return true\n // s = \"leetcode\" when \"code\" is being checked in the IF() of the loop, we reach endIndex == s.length(), \n // and wordDict.contains(\"code\") => true and topDown(s, wordDict, endIndex, memo) needs to return true. \n if(startIndex == s.length()) {\n return true;\n }\n \n // memo[i] = true means => that the substring from index i can be segmented. \n // memo[startIndex] means => wordDict contains substring from startIndex and it can be segemented.\n if(memo[startIndex] != null) { //Boolean[] array's default value is \"null\"\n return memo[startIndex];\n }\n \n for(int endIndex = startIndex + 1; endIndex <= s.length(); endIndex++) {\n if(wordDict.contains(s.substring(startIndex, endIndex)) && topDown(s, wordDict, endIndex, memo)) {\n memo[startIndex] = true;\n return true;\n }\n }\n memo[startIndex] = false;\n return false;\n}\n} \n", + "title": "472. Concatenated Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings words ( without duplicates ), return all the concatenated words in the given list of words . A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= words[i].length <= 30", + "words[i] consists of only lowercase English letters.", + "All the strings of words are unique .", + "1 <= sum(words[i].length) <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\nOutput:[\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\nExplanation:\"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cat\",\"dog\",\"catdog\"]\nOutput:[\"catdog\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n \n set_words = set(words)\n\n def check(word, seen):\n if word == '':\n return True\n for i in range(len(word) if seen else len(word) - 1):\n if word[:i+1] in set_words:\n if check(word[i+1:], seen | {word[:i+1]}):\n return True\n return False\n\n return [word for word in words if check(word, set())]\n", + "title": "472. Concatenated Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums of length n , you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n ( 0-indexed ). Specifically, ans is the concatenation of two nums arrays. Return the array ans .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]\nOutput:[1,2,1,1,2,1]\nExplanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,1]\nOutput:[1,3,2,1,1,3,2,1]\nExplanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 7.82%) | Memory: 50.1 MB (Top 50.44%)\nclass Solution {\n public int[] getConcatenation(int[] nums) {\n int[] ans = new int[2 * nums.length];\n for(int i = 0; i < nums.length; i++){\n ans[i] = ans[i + nums.length] = nums[i];\n }\n\n return ans;\n }\n}", + "title": "1929. Concatenation of Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums of length n , you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n ( 0-indexed ). Specifically, ans is the concatenation of two nums arrays. Return the array ans .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]\nOutput:[1,2,1,1,2,1]\nExplanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,1]\nOutput:[1,3,2,1,1,3,2,1]\nExplanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 139 ms (Top 57.29%) | Memory: 14.1 MB (Top 65.51%)\nclass Solution(object):\n def getConcatenation(self, nums):\n return nums * 2", + "title": "1929. Concatenation of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:1\nExplanation:\"1\" in binary corresponds to the decimal value 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:27\nExplanation:In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.", + "image": null + }, + { + "text": "Example 3: Input:n = 12\nOutput:505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109+ 7, the result is 505379714.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 613 ms (Top 30.00%) | Memory: 117.4 MB (Top 18.57%)\nclass Solution {\n public int concatenatedBinary(int n) {\n long res = 0;\n for (int i = 1; i <= n; i++) {\n res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007;\n }\n return (int) res;\n }\n}", + "title": "1680. Concatenation of Consecutive Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:1\nExplanation:\"1\" in binary corresponds to the decimal value 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:27\nExplanation:In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.", + "image": null + }, + { + "text": "Example 3: Input:n = 12\nOutput:505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109+ 7, the result is 505379714.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def concatenatedBinary(self, n: int) -> int:\n modulo = 10 ** 9 + 7\n shift = 0 # tracking power of 2\n res = 0\n \n for i in range(1, n+1):\n if i & (i - 1) == 0: # see if num reaches a greater power of 2\n shift += 1\n res = ((res << shift) + i) % modulo # do the simulation\n \n return res", + "title": "1680. Concatenation of Consecutive Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s , return the power of s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"\nOutput:2\nExplanation:The substring \"ee\" is of length 2 with the character 'e' only.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbcccddddeeeeedcba\"\nOutput:5\nExplanation:The substring \"eeeee\" is of length 5 with the character 'e' only.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 40.49%) | Memory: 42.4 MB (Top 68.55%)\nclass Solution {\n public int maxPower(String s) {\n // O(n), assuming the access to every char is O(1)\n // iterate through characters\n // if char(n) == char(n+1) counter++\n // if counter > max, max = counter\n // else counter = 1 // 1 is init value because otherwise the compared char itself is not counted\n\n int maxConsecutive = 1; // 1 is init value because otherwise the compared char itself is not counted\n int counterConsecutive = 1;\n for(int i = 0; i< s.length()-1; i++){\n if(s.charAt(i) == s.charAt(i+1)){\n counterConsecutive++;\n maxConsecutive = Math.max(counterConsecutive, maxConsecutive);\n } else {\n counterConsecutive = 1;\n }\n }\n\n return maxConsecutive;\n }\n}", + "title": "1446. Consecutive Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s , return the power of s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"\nOutput:2\nExplanation:The substring \"ee\" is of length 2 with the character 'e' only.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbcccddddeeeeedcba\"\nOutput:5\nExplanation:The substring \"eeeee\" is of length 5 with the character 'e' only.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 30 ms (Top 32.1%) | Memory: 13.25 MB (Top 75.9%)\n\nclass Solution(object):\n def maxPower(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n stack=[]\n mxpow=0\n for i in s:\n if stack and stack[-1]!=i:\n mxpow=max(mxpow,len(stack))\n stack=[]\n stack.append(i)\n else:\n stack.append(i)\n mxpow=max(mxpow,len(stack))\n return mxpow", + "title": "1446. Consecutive Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of ways you can write n as the sum of consecutive positive integers.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:5 = 2 + 3", + "image": null + }, + { + "text": "Example 2: Input:n = 9\nOutput:3\nExplanation:9 = 4 + 5 = 2 + 3 + 4", + "image": null + }, + { + "text": "Example 3: Input:n = 15\nOutput:4\nExplanation:15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 75.69%) | Memory: 41.1 MB (Top 34.74%)\nclass Solution {\n\n public int consecutiveNumbersSum(int n) {\n final double eightN = (8d * ((double) n)); // convert to double because 8n can overflow int\n final int maxTriangular = (int) Math.floor((-1d + Math.sqrt(1d + eightN)) / 2d);\n int ways = 1;\n int triangular = 1;\n for (int m = 2; m <= maxTriangular; ++m) {\n triangular += m;\n final int difference = n - triangular;\n if ((difference % m) == 0) {\n ways++;\n }\n }\n return ways;\n }\n\n}", + "title": "829. Consecutive Numbers Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of ways you can write n as the sum of consecutive positive integers.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation:5 = 2 + 3", + "image": null + }, + { + "text": "Example 2: Input:n = 9\nOutput:3\nExplanation:9 = 4 + 5 = 2 + 3 + 4", + "image": null + }, + { + "text": "Example 3: Input:n = 15\nOutput:4\nExplanation:15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 82.13%) | Memory: 16.60 MB (Top 56.38%)\n\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n csum=0\n result=0\n for i in range(1,n+1):\n csum+=i-1\n if csum>=n:\n break\n if (n-csum)%i==0:\n result+=1\n return result\n", + "title": "829. Consecutive Numbers Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j] , where i < j , the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2,-10,5,20], k = 2\nOutput:37\nExplanation:The subsequence is [10, 2, 5, 20].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-2,-3], k = 1\nOutput:-1\nExplanation:The subsequence must be non-empty, so we choose the largest number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,-2,-10,-5,20], k = 2\nOutput:23\nExplanation:The subsequence is [10, -2, -5, 20].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 172 ms (Top 12.84%) | Memory: 123.7 MB (Top 41.81%)\nclass Solution {\n public int constrainedSubsetSum(int[] nums, int k) {\n int n=nums.length;\n int[] dp=new int[n];\n int res=nums[0];\n Queue queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap\n\n Arrays.fill(dp,Integer.MIN_VALUE);\n dp[0]=nums[0];\n queue.offer(0);\n\n for(int j=1;j int:\n deque = []\n for i, num in enumerate(nums):\n \n while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i]\n deque.pop(0)\n \n if deque: # compute the max sum we can get at index i\n nums[i] = nums[deque[0]] + num\n \n while(deque and nums[deque[-1]] < nums[i]): \n # delet all the sequence that smaller than current sum, becaus there will never be\n # considers ==> smaller than current sequence, and end before current sequence\n deque.pop()\n \n if nums[i] > 0: # if nums[i] < 0, it can't be a useful prefix sum \n \tdeque.append(i)\n \n return max(nums)", + "title": "1425. Constrained Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree ), construct the tree and return its root . It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val , and any descendant of Node.right has a value strictly greater than Node.val . A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left , then traverses Node.right .", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 100", + "1 <= preorder[i] <= 1000", + "All the values of preorder are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [8,5,1,7,10,12]\nOutput:[8,5,10,1,7,null,12]", + "image": "https://assets.leetcode.com/uploads/2019/03/06/1266.png" + }, + { + "text": "Example 2: Input:preorder = [1,3]\nOutput:[1,null,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 66.41%) | Memory: 42.3 MB (Top 45.67%)\nclass Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n return bst(preorder, 0, preorder.length-1);\n }\n\n public TreeNode bst(int[] preorder, int start, int end){\n if(start > end) return null;\n\n TreeNode root = new TreeNode(preorder[start]);\n int breakPoint = start+1;\n while(breakPoint <= end && preorder[breakPoint] < preorder[start]){\n breakPoint++;\n }\n\n root.left = bst(preorder, start+1, breakPoint-1);\n root.right = bst(preorder, breakPoint, end);\n return root;\n }\n}", + "title": "1008. Construct Binary Search Tree from Preorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree ), construct the tree and return its root . It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val , and any descendant of Node.right has a value strictly greater than Node.val . A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left , then traverses Node.right .", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 100", + "1 <= preorder[i] <= 1000", + "All the values of preorder are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [8,5,1,7,10,12]\nOutput:[8,5,10,1,7,null,12]", + "image": "https://assets.leetcode.com/uploads/2019/03/06/1266.png" + }, + { + "text": "Example 2: Input:preorder = [1,3]\nOutput:[1,null,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n\t\tif not preorder:\n\t\t\treturn None\n\t\tnode = preorder.pop(0)\n\t\troot = TreeNode(node)\n\t\tl = []\n\t\tr = []\n\n\t\tfor val in preorder:\n\t\t\tif val < node:\n\t\t\t\tl.append(val)\n\t\t\telse:\n\t\t\t\tr.append(val)\n\n\t\troot.left = self.bstFromPreorder(l)\n\t\troot.right = self.bstFromPreorder(r)\n\t\treturn root", + "title": "1008. Construct Binary Search Tree from Preorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree .", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] io; int[] po;\n int n; // nth post order node \n public TreeNode buildTree(int[] inorder, int[] postorder) {\n this.n = inorder.length-1; this.io = inorder; this.po = postorder; \n return buildTree(0, n); \n }\n public TreeNode buildTree(int low, int high) {\n if(n < 0 || low > high) return null;\n int currNode = po[n--];\n int idxInInorder = low;\n TreeNode root = new TreeNode(currNode); \n if(low == high) return root; // no more nodes\n \n while(io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder\n root.right = buildTree(idxInInorder+1, high);\n root.left = buildTree(low, idxInInorder-1);\n return root; \n }\n}\n", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree .", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n\n def buildTree(self, inorder, postorder):\n \"\"\"\n 7\n 2\n -8 \n :type inorder: List[int]\n :type postorder: List[int]\n :rtype: TreeNode\n ([-4,-10,3,-1], [7]) ((11,-8,2), [7])\n \"\"\"\n currentSplits = [(inorder, [], [])]\n nodeDirectory = {}\n finalSplits = []\n for nodeVal in reversed(postorder):\n nodeDirectory[nodeVal] = TreeNode(nodeVal)\n for splits, nodes, directions in reversed(currentSplits):\n removing = None\n if nodeVal in splits:\n removing = (splits, nodes, directions)\n left = splits[:splits.index(nodeVal)]\n right = splits[splits.index(nodeVal)+1:]\n currentSplits.append((left, nodes+[nodeVal], directions + ['left']))\n if len(left) <= 1:\n finalSplits.append((left, nodes+[nodeVal], directions + ['left']))\n currentSplits.append((right, nodes+[nodeVal], directions + ['right']))\n if len(right) <= 1:\n finalSplits.append((right, nodes+[nodeVal], directions + ['right']))\n break\n if removing:\n currentSplits.remove(removing)\n finalSplits = [splits for splits in finalSplits if splits[0]]\n\n while finalSplits:\n nodeVal, nodes, directions = finalSplits.pop()\n bottomNode = nodeDirectory[nodeVal[0]] if nodeVal else None\n while nodes:\n attachingNode = nodeDirectory[nodes.pop()]\n attachingDir = directions.pop()\n if attachingDir == 'left':\n attachingNode.left = bottomNode\n else:\n attachingNode.right = bottomNode\n bottomNode = attachingNode\n return nodeDirectory[postorder[-1]]\n", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Map inMap;\n int curIndex = 0;\n int[] preOrder;\n public TreeNode buildTree(int[] preorder, int[] inorder) {\n preOrder = preorder;\n inMap = new HashMap<>();\n for(int i=0; i e) return null;\n int curNode = preOrder[curIndex++];\n TreeNode root = new TreeNode(curNode);\n int inRoot = inMap.get(curNode);\n root.left = dfs(s, inRoot-1);\n root.right = dfs(inRoot+1, e);\n return root;\n }\n}\n", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 274 ms (Top 36.07%) | Memory: 88.6 MB (Top 22.22%)\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n if not preorder or not inorder:\n return None\n\n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1:mid+1], inorder[:mid])\n root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])\n return root", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree . If there exist multiple answers, you can return any of them.", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 30", + "1 <= preorder[i] <= preorder.length", + "All the values of preorder are unique .", + "postorder.length == preorder.length", + "1 <= postorder[i] <= postorder.length", + "All the values of postorder are unique .", + "It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput:[1,2,3,4,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg" + }, + { + "text": "Example 2: Input:preorder = [1], postorder = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 63.11%) | Memory: 44.6 MB (Top 8.84%)\nclass Solution\n{\n public TreeNode constructFromPrePost(int[] preorder, int[] postorder)\n {\n // O(n) time | O(h) space\n if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null;\n\n TreeNode root = new TreeNode(preorder[0]);\n int mid = 0;\n\n if(preorder.length == 1) return root;\n\n // update mid\n for(int i = 0; i < postorder.length; i++)\n {\n if(preorder[1] == postorder[i])\n {\n mid = i;\n break;\n }\n }\n\n root.left = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1, 1 + mid + 1),\n Arrays.copyOfRange(postorder, 0, mid + 1));\n\n root.right = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1 + mid + 1, preorder.length),\n Arrays.copyOfRange(postorder, mid + 1, postorder.length - 1));\n return root;\n }\n}", + "title": "889. Construct Binary Tree from Preorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree . If there exist multiple answers, you can return any of them.", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 30", + "1 <= preorder[i] <= preorder.length", + "All the values of preorder are unique .", + "postorder.length == preorder.length", + "1 <= postorder[i] <= postorder.length", + "All the values of postorder are unique .", + "It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput:[1,2,3,4,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg" + }, + { + "text": "Example 2: Input:preorder = [1], postorder = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n\n def build(preorder, preStart, preEnd, postorder, postStart, postEnd):\n if preStart > preEnd:\n return\n elif preStart == preEnd:\n return TreeNode(preorder[preStart])\n \n rootVal = preorder[preStart]\n leftRootVal = preorder[preStart + 1]\n index = valToIndex[leftRootVal]\n root = TreeNode(rootVal)\n leftSize = index - postStart + 1\n \n root.left = build(preorder, preStart + 1, preStart + leftSize,\npostorder, postStart, index)\n root.right = build(preorder, preStart + leftSize + 1, preEnd,\npostorder, index + 1, postEnd - 1)\n \n return root\n \n valToIndex = {}\n for i in range(len(postorder)):\n valToIndex[postorder[i]] = i\n \n return build(preorder, 0, len(preorder) - 1, postorder, 0, len(postorder) - 1)\n", + "title": "889. Construct Binary Tree from Preorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s and an integer k , return true if you can use all the characters in s to construct k palindrome strings or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"annabelle\", k = 2\nOutput:true\nExplanation:You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 3\nOutput:false\nExplanation:It is impossible to construct 3 palindromes using all the characters of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"true\", k = 4\nOutput:true\nExplanation:The only possible solution is to put each character in a separate string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 25.64%) | Memory: 42.9 MB (Top 94.32%)\nclass Solution {\n public boolean canConstruct(String s, int k) {\n if(k==s.length())\n {\n return true;\n }\n else if(k>s.length())\n {\n return false;\n }\n Map map=new HashMap();\n for(int i=0;iele:map.entrySet())\n {\n if((ele.getValue()%2)==1)\n {\n odd++;\n }\n }\n return (odd<=k);\n }\n}", + "title": "1400. Construct K Palindrome Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and an integer k , return true if you can use all the characters in s to construct k palindrome strings or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"annabelle\", k = 2\nOutput:true\nExplanation:You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 3\nOutput:false\nExplanation:It is impossible to construct 3 palindromes using all the characters of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"true\", k = 4\nOutput:true\nExplanation:The only possible solution is to put each character in a separate string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 67.79%) | Memory: 17.30 MB (Top 13.48%)\n\nfrom collections import Counter\n\nclass Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n if k > len(s):\n return False\n h = Counter(s)\n countOdd = 0\n for value in h.values():\n if value % 2:\n countOdd += 1\n if countOdd > k:\n return False\n return True\n", + "title": "1400. Construct K Palindrome Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree. Return the root of the Quad-Tree representing the grid . Notice that you can assign the value of a node to True or False when isLeaf is False , and both are accepted in the answer. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's.", + "isLeaf : True if the node is leaf node on the tree or False if the node has the four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:[[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation:The explanation of this example is shown below:\nNotice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nOutput:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a QuadTree node.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n \n public Node() {\n this.val = false;\n this.isLeaf = false;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = topLeft;\n this.topRight = topRight;\n this.bottomLeft = bottomLeft;\n this.bottomRight = bottomRight;\n }\n};\n*/\n\nclass Solution {\n public Node construct(int[][] grid) {\n return helper(grid,0,grid.length-1,0,grid.length-1);\n }\n Node helper(int[][] grid,int l,int r,int t,int b){\n if(l==r){\n if(grid[t][l]==1)return new Node(true,true);\n else return new Node(false,true);\n }\n if(allOnes(grid,l,r,t,b)){\n Node res=new Node(true,true);\n return res;\n }\n if(allZeros(grid,l,r,t,b)){\n Node res=new Node(false,true);\n return res;\n }\n Node tl=helper(grid,l,(l+r)/2,t,(t+b)/2);\n Node tr=helper(grid,((l+r+1)/2),r,t,(t+b)/2);\n Node bl=helper(grid,l,(l+r)/2,(t+b+1)/2,b);\n Node br=helper(grid,((l+r+1)/2),r,(t+b+1)/2,b);\n return new Node(true,false,tl,tr,bl,br);\n }\n boolean allOnes(int[][] grid,int l,int r,int t,int b){\n //System.out.println(l+\" \"+r+\" \"+t+\" \"+b);\n for(int i=t;i<=b;i++){\n for(int j=l;j<=r;j++){\n if(grid[i][j]!=1){return false;}\n }\n \n }\n \n return true;\n }\n boolean allZeros(int[][] grid,int l,int r,int t,int b){\n for(int i=t;i<=b;i++){\n for(int j=l;j<=r;j++){\n if(grid[i][j]!=0)return false;\n }\n }\n return true;\n }\n}\n", + "title": "427. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree. Return the root of the Quad-Tree representing the grid . Notice that you can assign the value of a node to True or False when isLeaf is False , and both are accepted in the answer. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's.", + "isLeaf : True if the node is leaf node on the tree or False if the node has the four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:[[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation:The explanation of this example is shown below:\nNotice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nOutput:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a QuadTree node.\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\"\"\"\n\nclass Solution:\n def construct(self, grid: List[List[int]]) -> 'Node':\n def is_grid_a_leaf(mylist, n):\n x = mylist[0][0]\n for i in range(n):\n for j in range(n):\n if mylist[i][j] != x:\n return (0,0)\n return (1,x)\n \n def tree_builder(currlist) -> 'Node':\n node = Node()\n n = len(currlist)\n node.isLeaf, node.val = is_grid_a_leaf(currlist, n)\n \n if node.isLeaf:\n node.topLeft = node.topRight = node.bottomLeft = node.bottomRight = None\n else:\n top_left = [[row[i] for i in range(n//2)] for row in currlist[0:n//2]]\n top_right= [[row[i] for i in range(n//2,n)] for row in currlist[0:n//2]]\n bot_left = [[row[i] for i in range(n//2)] for row in currlist[n//2:n]]\n bot_right= [[row[i] for i in range(n//2,n)] for row in currlist[n//2:n]]\n node.topLeft = tree_builder(top_left)\n node.topRight = tree_builder(top_right)\n node.bottomLeft = tree_builder(bot_left)\n node.bottomRight = tree_builder(bot_right)\n return node\n \n return tree_builder(grid)", + "title": "427. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4]\nOutput:\"1(2(4))(3)\"\nExplanation:Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the unnecessary empty parenthesis pairs. And it will be \"1(2(4))(3)\"", + "image": "https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]\nOutput:\"1(2()(4))(3)\"\nExplanation:Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.", + "image": "https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n void tree2str(TreeNode* root,string &s) {\n if(!root) return;\n \n s+=to_string(root->val);\n \n if(!root->left && !root->right) return;\n \n s.push_back('('); tree2str(root->left,s); s.push_back(')');\n \n if(root->right){\n s.push_back('('); tree2str(root->right,s); s.push_back(')');\n }\n } \npublic:\n string tree2str(TreeNode* root) {\n string ans = \"\";\n tree2str(root,ans);\n return ans;\n }\n};\n", + "title": "606. Construct String from Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and an integer repeatLimit . Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row . You do not have to use all characters from s . Return the lexicographically largest repeatLimitedString possible . A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b . If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.", + "description_images": [], + "constraints": [ + "1 <= repeatLimit <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cczazcc\", repeatLimit = 3\nOutput:\"zzcccac\"\nExplanation:We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\nNote that the string \"zzcccca\" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababab\", repeatLimit = 2\nOutput:\"bbabaa\"\nExplanation:We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\nNote that the string \"bbabaaa\" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 93.53%) | Memory: 64.8 MB (Top 62.59%)\nclass Solution {\n public String repeatLimitedString(String s, int repeatLimit) {\n int[] counter = new int[26];\n int max = 0;\n for (char ch : s.toCharArray()) {\n int curr = ch - 'a';\n max = Math.max(max, curr);\n counter[curr]++;\n }\n int repeated = 0;\n StringBuilder builder = new StringBuilder();\n while (max >= 0) {\n builder.append((char)('a' + max));\n counter[max]--;\n repeated++;\n if (counter[max] == 0) {\n max = findNextMax(counter, max - 1);\n repeated = 0;\n continue;\n }\n if (repeated == repeatLimit) {\n // Greedy, use the next possible char once and get back to curr.\n // if no other char available, the curr word is the largest subsequence.\n int lower = findNextMax(counter, max - 1);\n if (lower < 0) {\n return builder.toString();\n }\n builder.append((char)('a' + lower));\n counter[lower]--;\n repeated = 0;\n }\n }\n return builder.toString();\n }\n\n private int findNextMax(int[] counter, int from) {\n int curr = from;\n while (curr >= 0) {\n if (counter[curr] > 0) {\n return curr;\n }\n curr--;\n }\n return curr;\n }\n}", + "title": "2182. Construct String With Repeat Limit", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s and an integer repeatLimit . Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row . You do not have to use all characters from s . Return the lexicographically largest repeatLimitedString possible . A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b . If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.", + "description_images": [], + "constraints": [ + "1 <= repeatLimit <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cczazcc\", repeatLimit = 3\nOutput:\"zzcccac\"\nExplanation:We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\nNote that the string \"zzcccca\" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababab\", repeatLimit = 2\nOutput:\"bbabaa\"\nExplanation:We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\nNote that the string \"bbabaaa\" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heappush, heappop\nfrom collections import defaultdict\n\nclass Solution:\n def repeatLimitedString(self, string: str, k: int) -> str:\n \"\"\"\n look close to the problem:\n it's lexicographically largest \n not \"longest\"\n \"\"\"\n appear, times = defaultdict(), defaultdict()\n pq, stack = [], []\n for s in string:\n appear[s] = appear.get(s, 0) + 1\n \n for s in appear:\n pq.append((-ord(s), appear[s]))\n \n heapify(pq)\n appear.clear()\n \n while pq:\n char, num = heappop(pq)\n s = chr(-char)\n if s in times and times[s] == k: # if reach the repeatedLimit\n if not pq:\n return ''.join(stack)\n char2, num2 = heappop(pq)\n token = chr(-char2)\n stack.append(token)\n if num2 - 1 > 0:\n heappush(pq, (char2, num2 - 1))\n heappush(pq, (char, num))\n del times[s]\n times[token] = 1\n continue\n if stack and stack[-1] != s:\n # reset times\n del times[stack[-1]]\n stack.append(s)\n times[s] = times.get(s, 0) + 1\n \n if num - 1 > 0:\n heappush(pq, (char, num - 1))\n return ''.join(stack) \n", + "title": "2182. Construct String With Repeat Limit", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : Return true if it is possible to construct the target array from arr , otherwise, return false .", + "description_images": [], + "constraints": [ + "let x be the sum of all elements currently in your array.", + "choose index i , such that 0 <= i < n and set the value of arr at index i to x .", + "You may repeat this procedure as many times as needed." + ], + "examples": [ + { + "text": "Example 1: Input:target = [9,3,5]\nOutput:true\nExplanation:Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done", + "image": null + }, + { + "text": "Example 2: Input:target = [1,1,1,2]\nOutput:false\nExplanation:Impossible to create target array from [1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:target = [8,5]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 47.45%) | Memory: 56.9 MB (Top 77.47%)\n\nclass Solution {\n public boolean isPossible(int[] target) {\n if(target.length==1) return target[0]==1;\n\n PriorityQueue que = new PriorityQueue(Collections.reverseOrder());\n int totsum = 0;\n\n for(int i=0;i bool:\n if len(target) == 1:\n return target == [1]\n res = sum(target)\n heap = [-elem for elem in target]\n heapify(heap)\n while heap[0]<-1:\n maximum = -heappop(heap)\n res -= maximum\n\n if res == 1:\n return True\n x = maximum % res\n if x == 0 or (x != 1 and x == maximum):\n return False\n\n res += x\n heappush(heap,-x)\n return True", + "title": "1354. Construct Target Array With Multiple Sums", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer n , find a sequence that satisfies all of the following: The distance between two numbers on the sequence, a[i] and a[j] , is the absolute difference of their indices, |j - i| . Return the lexicographically largest sequence . It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b . For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5 .", + "description_images": [], + "constraints": [ + "The integer 1 occurs once in the sequence.", + "Each integer between 2 and n occurs twice in the sequence.", + "For every integer i between 2 and n , the distance between the two occurrences of i is exactly i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[3,1,2,3,2]\nExplanation:[2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[5,3,1,4,3,5,2,4,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.69%) | Memory: 42.2 MB (Top 11.27%)\nclass Solution {\n\n public int[] constructDistancedSequence(int n) {\n int[] ans = new int[n * 2 - 1];\n boolean[] visited = new boolean[n + 1];\n calc(0, ans, visited, n);\n return ans;\n }\n\n private boolean calc(int index, int[] ans, boolean[] visited, int n) {\n if (index == ans.length) {\n return true;\n }\n if (ans[index] != 0) return calc(index + 1, ans, visited, n); // value already assigned in this position. So go ahead with the next index.\n else {\n // we start from n to 1 since we need to find out the lexicographically largest sequence.\n for (int i = n; i >= 1; i--) {\n if (visited[i]) continue;\n visited[i] = true;\n ans[index] = i;\n if (i == 1) {\n if (calc(index + 1, ans, visited, n)) return true;\n } else if (index + i < ans.length && ans[index + i] == 0) {\n ans[i + index] = i; // assigning the second occurence of i in the desired position i.e, (current index + i )\n if (calc(index + 1, ans, visited, n)) return true; // largest possible sequence satisfying the given conditions found.\n ans[index + i] = 0;\n }\n ans[index] = 0;\n visited[i] = false;\n }\n\n }\n return false;\n }\n }\n", + "title": "1718. Construct the Lexicographically Largest Valid Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , find a sequence that satisfies all of the following: The distance between two numbers on the sequence, a[i] and a[j] , is the absolute difference of their indices, |j - i| . Return the lexicographically largest sequence . It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b . For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5 .", + "description_images": [], + "constraints": [ + "The integer 1 occurs once in the sequence.", + "Each integer between 2 and n occurs twice in the sequence.", + "For every integer i between 2 and n , the distance between the two occurrences of i is exactly i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[3,1,2,3,2]\nExplanation:[2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[5,3,1,4,3,5,2,4,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n self.ans = None\n def dfs(path, used, i):\n self.steps += 1\n if i == len(path):\n self.ans = path[:]\n return True\n if path[i] != 0:\n return dfs(path, used, i + 1)\n my_ans = [0]\n for x in range(n, 0, -1):\n if x in used:\n continue\n if x == 1:\n path[i] = x\n used.add(1)\n \n if dfs(path, used, i + 1):\n return True\n \n path[i] = 0\n used.remove(1)\n if i + x < len(path) and path[i + x] == 0:\n path[i + x] = path[i] = x\n used.add(x)\n \n if dfs(path, used, i + 1):\n return True\n \n path[i + x] = path[i] = 0\n used.remove(x)\n\n return False\n\n dfs([0] * (1 + 2 * (n - 1)), set(), 0)\n \n return self.ans\n", + "title": "1718. Construct the Lexicographically Largest Valid Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.", + "description_images": [], + "constraints": [ + "1 <= area <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:area = 4\nOutput:[2,2]\nExplanation:The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.", + "image": null + }, + { + "text": "Example 2: Input:area = 37\nOutput:[37,1]", + "image": null + }, + { + "text": "Example 3: Input:area = 122122\nOutput:[427,286]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] constructRectangle(int area) {\n int minDiff = Integer.MAX_VALUE;\n int[] result = new int[2];\n \n for (int w = 1; w*w <= area; w++) {\n if (area % w == 0) {\n int l = area / w;\n int diff = l - w;\n if (diff < minDiff) {\n result[0] = l;\n result[1] = w;\n minDiff = diff;\n }\n }\n }\n \n return result;\n }\n}\n", + "title": "492. Construct the Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.", + "description_images": [], + "constraints": [ + "1 <= area <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:area = 4\nOutput:[2,2]\nExplanation:The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.", + "image": null + }, + { + "text": "Example 2: Input:area = 37\nOutput:[37,1]", + "image": null + }, + { + "text": "Example 3: Input:area = 122122\nOutput:[427,286]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 39 ms (Top 86.68%) | Memory: 13.9 MB (Top 58.98%)\nclass Solution:\n def constructRectangle(self, area: int):\n y = Solution.mySqrt(area)\n for i in range(y, 0, -1):\n if not area%i:\n return [int(area/i), i]\n\n def mySqrt(x):\n if x == 0:\n return 0\n n = x\n count = 0\n while True:\n count += 1\n root = 0.5 * (n + (x / n))\n if abs(root - n) < 0.9:\n break\n n = root\n return int(root)", + "title": "492. Construct the Rectangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected , where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie . Return the number of walls used to quarantine all the infected regions . If the world will become fully infected, return the number of walls used.", + "description_images": [], + "constraints": [ + "m == isInfected.length", + "n == isInfected[i].length", + "1 <= m, n <= 50", + "isInfected[i][j] is either 0 or 1 .", + "There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round." + ], + "examples": [ + { + "text": "Example 1: Input:isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]\nOutput:10\nExplanation:There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" + }, + { + "text": "Example 2: Input:isInfected = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:4\nExplanation:Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" + }, + { + "text": "Example 3: Input:isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]\nOutput:13\nExplanation:The region on the left only builds two new walls.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[][] DIR = new int[][]{\n {1, 0}, {-1, 0}, {0, 1}, {0, -1}\n };\n \n public int containVirus(int[][] isInfected) {\n int m = isInfected.length, n = isInfected[0].length;\n int ans = 0;\n \n while( true ) {\n // infected regions, sorted desc according to the number of nearby \n // uninfected nodes\n PriorityQueue pq = new PriorityQueue();\n // already visited cells\n boolean[][] visited = new boolean[m][n];\n \n // find regions\n for(int i=0; i {\n public List infected;\n public List uninfected;\n public int wallsRequired;\n \n public Region() {\n infected = new ArrayList();\n uninfected = new ArrayList();\n }\n \n public void addInfected(int row, int col) {\n infected.add(new int[]{ row, col });\n }\n \n public void addUninfected(int row, int col) {\n uninfected.add(new int[]{ row, col });\n }\n \n @Override\n public int compareTo(Region r2) {\n return Integer.compare(r2.uninfected.size(), uninfected.size());\n }\n}\n\n", + "title": "749. Contain Virus", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected , where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie . Return the number of walls used to quarantine all the infected regions . If the world will become fully infected, return the number of walls used.", + "description_images": [], + "constraints": [ + "m == isInfected.length", + "n == isInfected[i].length", + "1 <= m, n <= 50", + "isInfected[i][j] is either 0 or 1 .", + "There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round." + ], + "examples": [ + { + "text": "Example 1: Input:isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]\nOutput:10\nExplanation:There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" + }, + { + "text": "Example 2: Input:isInfected = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:4\nExplanation:Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" + }, + { + "text": "Example 3: Input:isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]\nOutput:13\nExplanation:The region on the left only builds two new walls.", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area\n if 0<=i int:\n ans, i, j = 0, 0, len(H)-1\n while (i < j):\n if H[i] <= H[j]:\n res = H[i] * (j - i)\n i += 1\n else:\n res = H[j] * (j - i)\n j -= 1\n if res > ans: ans = res\n return ans\n\n", + "title": "11. Container With Most Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,3,4,3,2,4,2]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 27.66%) | Memory: 57.30 MB (Top 21.08%)\n\nclass Solution {\n public boolean containsDuplicate(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int i = 1; i < n; i++) {\n if (nums[i] == nums[i - 1])\n return true;\n }\n return false;\n }\n}\n", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,3,4,3,2,4,2]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 714 ms (Top 44.74%) | Memory: 26.1 MB (Top 5.18%)\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return len(nums) != len(set(nums))", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsNearbyDuplicate(int[] nums, int k) {\n HashMap map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) {\n return true;\n }\n map.put(nums[i], i);\n }\n return false;\n }\n}\n", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 632 ms (Top 95.72%) | Memory: 27.2 MB (Top 74.47%)\nclass Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n seen = {}\n for i, n in enumerate(nums):\n if n in seen and i - seen[n] <= k:\n return True\n seen[n] = i\n return False", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and two integers k and t , return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^4", + "0 <= t <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3, t = 0\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1, t = 2\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,9,1,5,9], k = 2, t = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 75.62%) | Memory: 55.00 MB (Top 92.14%)\n\n/**\n * Sliding Window solution using Buckets\n *\n * Time Complexity: O(N)\n *\n * Space Complexity: O(min(N, K+1))\n *\n * N = Length of input array. K = Input difference between indexes.\n */\nclass Solution {\n public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {\n if (nums == null || nums.length < 2 || k < 1 || t < 0) {\n return false;\n }\n\n HashMap buckets = new HashMap<>();\n // The bucket size is t+1 as the ranges are from 0..t, t+1..2t+1, ..\n long bucketSize = (long) t + 1;\n\n for (int i = 0; i < nums.length; i++) {\n // Making sure only K buckets exists in map.\n if (i > k) {\n long lastBucket = ((long) nums[i - k - 1] - Integer.MIN_VALUE) / bucketSize;\n buckets.remove(lastBucket);\n }\n\n long remappedNum = (long) nums[i] - Integer.MIN_VALUE;\n long bucket = remappedNum / bucketSize;\n\n // If 2 numbers belong to same bucket\n if (buckets.containsKey(bucket)) {\n return true;\n }\n\n // If numbers are in adjacent buckets and the difference between them is at most\n // t.\n if (buckets.containsKey(bucket - 1) && remappedNum - buckets.get(bucket - 1) <= t) {\n return true;\n }\n if (buckets.containsKey(bucket + 1) && buckets.get(bucket + 1) - remappedNum <= t) {\n return true;\n }\n\n buckets.put(bucket, remappedNum);\n }\n\n return false;\n }\n}\n", + "title": "220. Contains Duplicate III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and two integers k and t , return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^4", + "0 <= t <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3, t = 0\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1, t = 2\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,9,1,5,9], k = 2, t = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 779 ms (Top 16.27%) | Memory: 17.7 MB (Top 35.86%)\nfrom sortedcontainers import SortedList\nclass Solution:\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n sl = SortedList()\n for i in range(len(nums)):\n if i > k: sl.remove(nums[i-k-1])\n idxl = sl.bisect_left(nums[i]-t)\n idxr = sl.bisect_right(nums[i]+t)\n if idxl != idxr: return True\n sl.add(nums[i])\n return False", + "title": "220. Contains Duplicate III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums , return the maximum length of a contiguous subarray with an equal number of 0 and 1 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1]\nOutput:2\nExplanation:[0, 1] is the longest contiguous subarray with an equal number of 0 and 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0]\nOutput:2\nExplanation:[0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n # dictionary\n prefixSum = {0: -1}\n total = 0\n maxlength = 0\n \n for index, value in enumerate(nums):\n if value == 0:\n total -= 1\n else:\n total += 1\n if total not in prefixSum.keys():\n prefixSum[total] = index\n else:\n maxlength = max(maxlength, index-prefixSum[total]) \n return maxlength\n", + "title": "525. Contiguous Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k , or false otherwise . An integer x is a multiple of k if there exists an integer n such that x = n * k . 0 is always a multiple of k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= sum(nums[i]) <= 2 31 - 1", + "1 <= k <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [23,2,4,6,7], k = 6\nOutput:true\nExplanation:[2, 4] is a continuous subarray of size 2 whose elements sum up to 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [23,2,6,4,7], k = 6\nOutput:true\nExplanation:[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.", + "image": null + }, + { + "text": "Example 3: Input:nums = [23,2,6,4,7], k = 13\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n boolean t[]=new boolean[nums.length+1];\n Arrays.fill(t,false);\n return help(nums.length,nums,k,0,0,t);\n }\n public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){\n if(size>=2&&sum%k==0){\n return true;\n }\n if(i==0){\n return false;\n }\n if(t[i-1]!=false){\n return t[i-1];\n }\n if(size>0){\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t);\n }\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t)||help(i-1,nums,k,sum,size,t);\n }\n}\n---------------------------------------------------------------------------------------------\nclass Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n int sum=0;\n HashMaph=new HashMap<>();\n h.put(0,-1);\n for(int i=0;i=2){\n return true;\n }\n h.put(sum,h.getOrDefault(sum,i));\n } \n return false;\n }\n}\n", + "title": "523. Continuous Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k , or false otherwise . An integer x is a multiple of k if there exists an integer n such that x = n * k . 0 is always a multiple of k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= sum(nums[i]) <= 2 31 - 1", + "1 <= k <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [23,2,4,6,7], k = 6\nOutput:true\nExplanation:[2, 4] is a continuous subarray of size 2 whose elements sum up to 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [23,2,6,4,7], k = 6\nOutput:true\nExplanation:[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.", + "image": null + }, + { + "text": "Example 3: Input:nums = [23,2,6,4,7], k = 13\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n psum = {0:-1}\n currentSum = 0\n for i in range(len(nums)):\n currentSum += nums[i]\n remainder = currentSum % k\n if remainder not in psum:\n psum[remainder] = i\n else:\n if i - psum[remainder] > 1:\n return True\n return False\n", + "title": "523. Continuous Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original , and two integers, m and n . You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original . The elements from indices 0 to n - 1 ( inclusive ) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 ( inclusive ) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible .", + "description_images": [], + "constraints": [ + "1 <= original.length <= 5 * 10^4", + "1 <= original[i] <= 10^5", + "1 <= m, n <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:original = [1,2,3,4], m = 2, n = 2\nOutput:[[1,2],[3,4]]\nExplanation:The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png" + }, + { + "text": "Example 2: Input:original = [1,2,3], m = 1, n = 3\nOutput:[[1,2,3]]\nExplanation:The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.", + "image": null + }, + { + "text": "Example 3: Input:original = [1,2], m = 1, n = 1\nOutput:[]\nExplanation:There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 59.22%) | Memory: 55.50 MB (Top 5.02%)\n\nclass Solution {\n public int[][] construct2DArray(int[] original, int m, int n) { \n if (original.length != m * n) return new int[0][];\n \n int[][] ans = new int[m][n];\n int currRow = 0, currCol = 0;\n \n for (int num : original) {\n ans[currRow][currCol++] = num;\n \n if (currCol == n) {\n currCol = 0;\n currRow++;\n }\n }\n \n return ans;\n }\n}\n\n// TC: O(n), SC: O(m * n)\n", + "title": "2022. Convert 1D Array Into 2D Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original , and two integers, m and n . You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original . The elements from indices 0 to n - 1 ( inclusive ) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 ( inclusive ) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible .", + "description_images": [], + "constraints": [ + "1 <= original.length <= 5 * 10^4", + "1 <= original[i] <= 10^5", + "1 <= m, n <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:original = [1,2,3,4], m = 2, n = 2\nOutput:[[1,2],[3,4]]\nExplanation:The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png" + }, + { + "text": "Example 2: Input:original = [1,2,3], m = 1, n = 3\nOutput:[[1,2,3]]\nExplanation:The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.", + "image": null + }, + { + "text": "Example 3: Input:original = [1,2], m = 1, n = 1\nOutput:[]\nExplanation:There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] construct2DArray(int[] original, int m, int n) {\n if(m * n != original.length) {\n return new int[0][0];\n }\n int[][] answer = new int[m][n];\n int rCount = 0, cCount = 0, len = original.length;\n for(int i=0;i List[List[int]]:\n ans = []\n if len(original) == m*n: \n for i in range(0, len(original), n): \n ans.append(original[i:i+n])\n return ans \n", + "title": "2022. Convert 1D Array Into 2D Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer num , return a string representing its hexadecimal representation . For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem.", + "description_images": [], + "constraints": [ + "-2 31 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 26\nOutput:\"1a\"", + "image": null + }, + { + "text": "Example 2: Input:num = -1\nOutput:\"ffffffff\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 60.13%)\nclass Solution {\n public String toHex(int num) {\n if(num == 0) return \"0\";\n\n boolean start = true;\n\n StringBuilder sb = new StringBuilder();\n\n for(int i = 28; i >= 0; i -= 4) {\n int digit = (num >> i) & 15;\n if(digit > 9) {\n char curr = (char)(digit%10 + 'a');\n sb.append(curr);\n start = false;\n } else if(digit != 0) {\n char curr = (char)(digit + '0');\n sb.append(curr);\n start = false;\n } else {//digit == 0\n if(start == false) { //avoid case: 00001a\n sb.append('0');\n }\n }\n\n }\n return sb.toString();\n }\n}", + "title": "405. Convert a Number to Hexadecimal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return a string representing its hexadecimal representation . For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem.", + "description_images": [], + "constraints": [ + "-2 31 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 26\nOutput:\"1a\"", + "image": null + }, + { + "text": "Example 2: Input:num = -1\nOutput:\"ffffffff\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 33 ms (Top 88.95%) | Memory: 13.8 MB (Top 62.28%)\nclass Solution:\n def toHex(self, num: int) -> str:\n ret = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n ans = \"\"\n\n if num < 0:\n num = pow(2,32) +num\n\n if num == 0:\n return \"0\"\n while num > 0:\n ans = ret[num%16] +ans\n num = num//16\n\n return ans", + "title": "405. Convert a Number to Hexadecimal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1 . The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list.", + "description_images": [], + "constraints": [ + "The Linked List is not empty.", + "Number of nodes will not exceed 30 .", + "Each node's value is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,0,1]\nOutput:5\nExplanation:(101) in base 2 = (5) in base 10", + "image": "https://assets.leetcode.com/uploads/2019/12/05/graph-1.png" + }, + { + "text": "Example 2: Input:head = [0]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 64.79%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int getDecimalValue(ListNode head) {\n head = reverse(head);\n int ans = 0;\n int pow = 0;\n ListNode temp = head;\n while(temp != null){\n ans = ans + temp.val * (int) Math.pow(2,pow++);\n temp = temp.next;\n }\n\n return ans;\n }\n public ListNode reverse(ListNode head){\n ListNode prev = null;\n ListNode pres = head;\n ListNode Next = pres.next;\n\n while(pres != null){\n pres.next = prev;\n prev = pres;\n pres = Next;\n if(Next != null){\n Next = Next.next;\n }\n }\n\n head = prev;\n return head;\n }\n}", + "title": "1290. Convert Binary Number in a Linked List to Integer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1 . The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list.", + "description_images": [], + "constraints": [ + "The Linked List is not empty.", + "Number of nodes will not exceed 30 .", + "Each node's value is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,0,1]\nOutput:5\nExplanation:(101) in base 2 = (5) in base 10", + "image": "https://assets.leetcode.com/uploads/2019/12/05/graph-1.png" + }, + { + "text": "Example 2: Input:head = [0]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def getDecimalValue(self, head: ListNode) -> int:\n res = 0\n po = 0\n stack = []\n node = head\n while node:\n stack.append(node.val)\n node = node.next\n res = 0\n for i in reversed(stack):\n res += i*(2**po)\n po += 1\n return res\n", + "title": "1290. Convert Binary Number in a Linked List to Integer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]", + "image": "https://assets.leetcode.com/uploads/2019/05/02/tree.png" + }, + { + "text": "Example 2: Input:root = [0,null,1]\nOutput:[1,null,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode convertBST(TreeNode root) {\n if(root!=null) {\n\n\n List nodesValues = new ArrayList<>();\n helperNodesVales(root, nodesValues);\n traverseAndAdd(root, nodesValues);\n\n return root;\n }\n return null;\n }\n\n private void helperNodesVales(TreeNode root, List nodesValues) {\n if (root != null) {\n nodesValues.add(root.val);\n }\n if (root.right != null) {\n helperNodesVales(root.right, nodesValues);\n }\n if (root.left != null) {\n helperNodesVales(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n\n private void traverseAndAdd(TreeNode root, List nodesValues) {\n if (root != null) {\n int rootVal = root.val;\n for (int i = 0; i < nodesValues.size(); i++) {\n if (nodesValues.get(i) > rootVal)\n root.val += nodesValues.get(i);\n }\n }\n if (root.right != null) {\n traverseAndAdd(root.right, nodesValues);\n }\n if (root.left != null) {\n traverseAndAdd(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n}\n\n\n\n", + "title": "538. Convert BST to Greater Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]", + "image": "https://assets.leetcode.com/uploads/2019/05/02/tree.png" + }, + { + "text": "Example 2: Input:root = [0,null,1]\nOutput:[1,null,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n ans = []\n def inorder(node):\n if not node:\n return node\n inorder(node.left)\n ans.append(node.val)\n inorder(node.right)\n def dfs(node):\n if not node:\n return None\n idx = ans.index(node.val)\n node.val = node.val + sum(ans[idx+1:])\n dfs(node.left)\n dfs(node.right)\n\n inorder(root)\n dfs(root)\n return root\n \n", + "title": "538. Convert BST to Greater Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n , return a list of two integers [A, B] where : The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them.", + "description_images": [], + "constraints": [ + "A and B are No-Zero integers .", + "A + B = n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[1,1]\nExplanation:A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.", + "image": null + }, + { + "text": "Example 2: Input:n = 11\nOutput:[2,9]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] getNoZeroIntegers(int n) {\n int B;\n for (int A = 1; A < n; ++A) {\n B = n - A;\n if (!(A + \"\").contains(\"0\") && !(B + \"\").contains(\"0\"))\n return new int[] {A, B};\n }\n return new int[]{};\n}\n}\n", + "title": "1317. Convert Integer to the Sum of Two No-Zero Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n , return a list of two integers [A, B] where : The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them.", + "description_images": [], + "constraints": [ + "A and B are No-Zero integers .", + "A + B = n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[1,1]\nExplanation:A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.", + "image": null + }, + { + "text": "Example 2: Input:n = 11\nOutput:[2,9]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(1,n//2+1):\n first = str(i)\n second = str(n-i)\n if \"0\" not in first and \"0\" not in second:\n return [i, n-i]\n", + "title": "1317. Convert Integer to the Sum of Two No-Zero Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree . A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]\nOutput:[0,-3,9,-10,null,5]\nExplanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]\nOutput:[3,1]\nExplanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 33.54%) | Memory: 45.2 MB (Top 7.46%)\nclass Solution {\n public TreeNode sortedArrayToBST(int[] nums) {\n if (nums.length == 0) return null;\n var mid = nums.length / 2;\n var root = new TreeNode(nums[mid]);\n var left_array = Arrays.copyOfRange(nums, 0, mid);\n var right_array = Arrays.copyOfRange(nums, mid + 1, nums.length);\n root.left = sortedArrayToBST(left_array);\n root.right = sortedArrayToBST(right_array);\n return root;\n }\n}", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree . A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]\nOutput:[0,-3,9,-10,null,5]\nExplanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]\nOutput:[3,1]\nExplanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def formNodes(self,nums, l,r):\n if l > r:\n return None\n else:\n mid = l+(r-l)//2\n node = TreeNode(nums[mid])\n node.left = self.formNodes(nums, l,mid-1)\n node.right = self.formNodes(nums, mid+1,r)\n return node\n \n \n def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:\n return self.formNodes(nums, 0,len(nums)-1)\n", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list where elements are sorted in ascending order , convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.", + "description_images": [], + "constraints": [ + "The number of nodes in head is in the range [0, 2 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [-10,-3,0,5,9]\nOutput:[0,-3,9,-10,null,5]\nExplanation:One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" + }, + { + "text": "Example 2: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public TreeNode sortedListToBST(ListNode head) {\n \n ListNode tmp = head;\n ArrayList treelist = new ArrayList<>();\n \n while(tmp != null) {\n treelist.add(tmp.val);\n tmp = tmp.next;\n }\n \n return createTree(treelist, 0, treelist.size()-1);\n }\n \n public TreeNode createTree(ArrayList treelist, int start, int end) {\n \n if(start > end)\n return null;\n \n int mid = start + (end-start)/2;\n \n TreeNode node = new TreeNode(treelist.get(mid));//getNode(treelist.get(mid));\n \n node.left = createTree(treelist, start, mid-1);\n node.right = createTree(treelist, mid+1, end);\n return node;\n }\n}\n", + "title": "109. Convert Sorted List to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the head of a singly linked list where elements are sorted in ascending order , convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.", + "description_images": [], + "constraints": [ + "The number of nodes in head is in the range [0, 2 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [-10,-3,0,5,9]\nOutput:[0,-3,9,-10,null,5]\nExplanation:One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" + }, + { + "text": "Example 2: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:\n arr = []\n while head:\n arr.append(head.val)\n head = head.next\n def dfs(left, right):\n if left > right: return\n m = (left + right)//2\n return TreeNode(arr[m], dfs(left, m-1), dfs(m+1, right))\n return dfs(0, len(arr)-1)", + "title": "109. Convert Sorted List to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of network towers towers , where towers[i] = [x i , y i , q i ] denotes the i th network tower with location (x i , y i ) and quality factor q i . All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance . You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius . Outside that distance, the signal becomes garbled, and the tower is not reachable . The signal quality of the i th tower at a coordinate (x, y) is calculated with the formula ⌊q i / (1 + d)⌋ , where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. Return the array [c x , c y ] representing the integral coordinate (c x , c y ) where the network quality is maximum. If there are multiple coordinates with the same network quality , return the lexicographically minimum non-negative coordinate. Note:", + "description_images": [], + "constraints": [ + "A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: x1 < x2 , or x1 == x2 and y1 < y2 .", + "x1 < x2 , or", + "x1 == x2 and y1 < y2 .", + "⌊val⌋ is the greatest integer less than or equal to val (the floor function)." + ], + "examples": [ + { + "text": "Example 1: Input:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput:[2,1]\nExplanation:At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/untitled-diagram.png" + }, + { + "text": "Example 2: Input:towers = [[23,11,21]], radius = 9\nOutput:[23,11]\nExplanation:Since there is only one tower, the network quality is highest right at the tower's location.", + "image": null + }, + { + "text": "Example 3: Input:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput:[1,2]\nExplanation:Coordinate (1, 2) has the highest network quality.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 84.85%) | Memory: 41.90 MB (Top 33.33%)\n\nclass Solution {\n public int[] bestCoordinate(int[][] towers, int radius) {\n int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0;\n int[] res = new int[2];\n for(int[] t : towers) {\n minX = Math.min(minX, t[0]);\n maxX = Math.max(maxX, t[0]);\n minY = Math.min(minY, t[1]);\n maxY = Math.max(maxY, t[1]);\n }\n for(int i = minX; i <= maxX; i++) {\n for(int j = minY; j <= maxY; j++) {\n int sum = 0;\n for(int[] t : towers) {\n int d = (t[0] - i) *(t[0] - i) + (t[1] - j) *(t[1] - j);\n if(d <= radius * radius) {\n sum += t[2] /(1+ Math.sqrt(d)); \n }\n }\n if(sum > max) {\n max = sum;\n res = new int[]{i,j};\n }\n }\n }\n return res;\n }\n}\n", + "title": "1620. Coordinate With Maximum Network Quality", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of network towers towers , where towers[i] = [x i , y i , q i ] denotes the i th network tower with location (x i , y i ) and quality factor q i . All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance . You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius . Outside that distance, the signal becomes garbled, and the tower is not reachable . The signal quality of the i th tower at a coordinate (x, y) is calculated with the formula ⌊q i / (1 + d)⌋ , where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. Return the array [c x , c y ] representing the integral coordinate (c x , c y ) where the network quality is maximum. If there are multiple coordinates with the same network quality , return the lexicographically minimum non-negative coordinate. Note:", + "description_images": [], + "constraints": [ + "A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: x1 < x2 , or x1 == x2 and y1 < y2 .", + "x1 < x2 , or", + "x1 == x2 and y1 < y2 .", + "⌊val⌋ is the greatest integer less than or equal to val (the floor function)." + ], + "examples": [ + { + "text": "Example 1: Input:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput:[2,1]\nExplanation:At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/untitled-diagram.png" + }, + { + "text": "Example 2: Input:towers = [[23,11,21]], radius = 9\nOutput:[23,11]\nExplanation:Since there is only one tower, the network quality is highest right at the tower's location.", + "image": null + }, + { + "text": "Example 3: Input:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput:[1,2]\nExplanation:Coordinate (1, 2) has the highest network quality.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n return max(\n (\n (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius),\n [x, y]) for x in range(51) for y in range(51)\n ),\n key=lambda x: (x[0], -x[1][0], -x[1][1])\n )[1]\n", + "title": "1620. Coordinate With Maximum Network Quality", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Your code will only be given the head of the original linked list.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]\nOutput:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]\nOutput:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public Node copyRandomList(Node head) {\n \n if(head == null)\n return null;\n \n HashMap map = new HashMap<>();\n \n //node to be returned\n Node ans = new Node(head.val);\n \n //temproary pointer to the ans node\n Node tempAns = ans;\n \n Node temp = head;\n \n map.put(head,ans);\n temp = temp.next;\n \n \n //loop to store the lookalike new nodes of the original ones\n //create the new list side by side\n while(temp != null){\n Node x = new Node(temp.val);\n map.put(temp,x);\n tempAns.next = x;\n tempAns = x;\n temp = temp.next;\n }\n \n //repointing them to the start\n temp = head;\n tempAns = ans;\n \n //will have lookup of O(1) for the random nodes;\n while(temp!=null){\n tempAns.random = map.get(temp.random);\n tempAns = tempAns.next;\n temp = temp.next;\n }\n \n return ans;\n \n }\n}\n", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Your code will only be given the head of the original linked list.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]\nOutput:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]\nOutput:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\nclass Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n \n \n \n # ll=res\n # k=0\n # ind=0\n # kmk=1\n jj=None\n g=defaultdict(lambda:-1)\n k=0\n hh=head\n while(head):\n res=Node(head.val)\n if k==0:\n jj=res\n\n if k==1:\n prev.next=res\n \n g[head]=res\n prev=res\n k=1\n head=head.next\n \n # print(g)\n \n # for i in g:\n # print(i.val,g[i].val)\n \n kk=jj\n mm=jj\n # print(head)\n while(hh):\n if hh.random!=None:\n \n jj.random=g[hh.random]\n else:\n jj.random=None\n hh=hh.next\n \n jj=jj.next \n # head=head.next\n kkk=kk\n # while(kk):\n # print(kk.val)\n # kk=kk.next\n \n return kkk\n# if g[ind]!=-1:\n# g[ind].random=res\n \n# res=Node(head.val)\n# if kmk==1:\n# ll=res\n# kmk=0\n# mm=head.next\n# if mm:\n \n# jk=Node(mm.val)\n# res.next=jk\n# if head.random !=None:\n# g[head.random]=res\n# else:\n# res.random=None\n# head=head.next\n# ind+=1\n# # res=res.next\n \n# return ll\n \n # if k==0:\n # res.val=head.val\n # mm=head.next\n \n \n \n \n \n", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n flights that are labeled from 1 to n . You are given an array of flight bookings bookings , where bookings[i] = [first i , last i , seats i ] represents a booking for flights first i through last i ( inclusive ) with seats i seats reserved for each flight in the range. Return an array answer of length n , where answer[i] is the total number of seats reserved for flight i .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "1 <= bookings.length <= 2 * 10^4", + "bookings[i].length == 3", + "1 <= first i <= last i <= n", + "1 <= seats i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput:[10,55,45,25,25]\nExplanation:Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]", + "image": null + }, + { + "text": "Example 2: Input:bookings = [[1,2,10],[2,2,15]], n = 2\nOutput:[10,25]\nExplanation:Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] corpFlightBookings(int[][] bookings, int n) {\n // nums all equals to zero\n int[] nums = new int[n];\n // construct the diffs\n Difference df = new Difference(nums);\n\n for (int[] booking : bookings) {\n // pay attention to the index\n int i = booking[0] - 1;\n int j = booking[1] - 1;\n int val = booking[2];\n // increase nums[i..j] by val\n df.increment(i, j, val);\n }\n // return the final array\n return df.result();\n }\n\n class Difference {\n // diff array\n private int[] diff;\n\n public Difference(int[] nums) {\n assert nums.length > 0;\n diff = new int[nums.length];\n // construct the diffs\n diff[0] = nums[0];\n for (int i = 1; i < nums.length; i++) {\n diff[i] = nums[i] - nums[i - 1];\n }\n }\n\n // increase nums[i..j] by val\n public void increment(int i, int j, int val) {\n diff[i] += val;\n if (j + 1 < diff.length) {\n diff[j + 1] -= val;\n }\n }\n\n public int[] result() {\n int[] res = new int[diff.length];\n // contract the diff array based on the result\n res[0] = diff[0];\n for (int i = 1; i < diff.length; i++) {\n res[i] = res[i - 1] + diff[i];\n }\n return res;\n }\n }\n\n}\n", + "title": "1109. Corporate Flight Bookings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n flights that are labeled from 1 to n . You are given an array of flight bookings bookings , where bookings[i] = [first i , last i , seats i ] represents a booking for flights first i through last i ( inclusive ) with seats i seats reserved for each flight in the range. Return an array answer of length n , where answer[i] is the total number of seats reserved for flight i .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "1 <= bookings.length <= 2 * 10^4", + "bookings[i].length == 3", + "1 <= first i <= last i <= n", + "1 <= seats i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput:[10,55,45,25,25]\nExplanation:Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]", + "image": null + }, + { + "text": "Example 2: Input:bookings = [[1,2,10],[2,2,15]], n = 2\nOutput:[10,25]\nExplanation:Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n\t\tflights = [0]*n\n\t\tfor start,end,seats in bookings:\n\t\t\tflights[start-1] += seats\n\t\t\tif end < n: flights[end] -= seats\n\t\tfor i in range(n-1):\n\t\t\tflights[i+1] += flights[i]\n\t\treturn flights", + "title": "1109. Corporate Flight Bookings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of distinct positive integers locations where locations[i] represents the position of city i . You are also given integers start , finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i , you can pick any city j such that j != i and 0 <= j < locations.length and move to city j . Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]| . Please notice that |x| denotes the absolute value of x . Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish ). Return the count of all possible routes from start to finish . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "2 <= locations.length <= 100", + "1 <= locations[i] <= 10^9", + "All integers in locations are distinct .", + "0 <= start, finish < locations.length", + "1 <= fuel <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\nOutput:4\nExplanation:The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3", + "image": null + }, + { + "text": "Example 2: Input:locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput:5\nExplanation:The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5", + "image": null + }, + { + "text": "Example 3: Input:locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput:0\nExplanation:It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 78.44%) | Memory: 41.8 MB (Top 95.21%)\n\n/*\n\nUsing DFS and Memo :\n\n1. We will start from start pos provided and will dfs travel to each other location .\n2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling\n3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path\n4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing .\n\n*/\n\nclass Solution {\n\n int mod = (int)Math.pow(10,9) + 7 ;\n int[][] dp ;\n\n public int countRoutes(int[] locations, int start, int finish, int fuel) {\n\n dp = new int[locations.length][fuel+1] ;\n\n for(int[] row : dp){\n Arrays.fill(row , -1) ;\n }\n\n return dfs(locations , start , finish , fuel);\n }\n\n public int dfs(int[] locations , int cur_location , int finish , int fuel){\n\n if(fuel < 0){\n return 0 ;\n }\n\n if(dp[cur_location][fuel] != -1){\n return dp[cur_location][fuel] ;\n }\n\n int result = 0 ;\n\n if(cur_location == finish){\n result++ ;\n }\n\n for(int i=0 ; i 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3", + "image": null + }, + { + "text": "Example 2: Input:locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput:5\nExplanation:The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5", + "image": null + }, + { + "text": "Example 3: Input:locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput:0\nExplanation:It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3516 ms (Top 53.70%) | Memory: 22.1 MB (Top 43.52%)\n\nfrom bisect import bisect_left\nfrom functools import lru_cache\nclass Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n start = locations[start]\n end = locations[finish]\n locations.sort()\n start = bisect_left(locations, start)\n end = bisect_left(locations, end)\n @lru_cache(None)\n def dfs(i, fuel):\n if fuel == 0 and i == end: return 1\n res = 0\n if i == end: res += 1\n j = i-1\n while j>=0 and abs(locations[j]-locations[i]) <= fuel:\n res += dfs(j, fuel-abs(locations[j]-locations[i]))\n j -= 1\n j = i+1\n while j int:\n total = 1\n mod = 10 ** 9 + 7\n for k in reversed(range(2, n + 1)):\n total = total * ((2 * k - 1) * (2 * k - 2) // 2 + 2 * k - 1)\n total = total % mod\n return total\n", + "title": "1359. Count All Valid Pickup and Delivery Options", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you \"say\" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. For example, the saying and conversion for digit string \"3322251\" : Given a positive integer n , return the n th term of the count-and-say sequence .", + "description_images": [], + "constraints": [ + "countAndSay(1) = \"1\"", + "countAndSay(n) is the way you would \"say\" the digit string from countAndSay(n-1) , which is then converted into a different digit string." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:\"1\"\nExplanation:This is the base case.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:\"1211\"\nExplanation:countAndSay(1) = \"1\"\ncountAndSay(2) = say \"1\" = one 1 = \"11\"\ncountAndSay(3) = say \"11\" = two 1's = \"21\"\ncountAndSay(4) = say \"21\" = one 2 + one 1 = \"12\" + \"11\" = \"1211\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String countSay(int n, String[] mapper) {\n if (n == 1) return mapper[1];\n else {\n String say = \"\";\n if (mapper[n-1] != null) say += mapper[n-1];\n else say += countSay(n-1, mapper);\n String count = \"\";\n int cache = Integer.parseInt(say.substring(0, 1));\n int cntr = 1;\n if (say.length() < 2) {\n count += \"1\" + Integer.toString(cache);\n } else {\n for(int i=1;i str:\n if n==1:\n return \"1\"\n \n x=self.countAndSay(n-1)\n count=1\n cur=x[0]\n res=\"\"\n for i in range(1,len(x)):\n if cur==x[i]:\n count+=1\n else:\n res+=str(count)+str(cur)\n count=1\n cur=x[i]\n \n res+=str(count)+str(cur)\n return res\n", + "title": "38. Count and Say", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums of length n and an integer k , return the number of pairs (i, j) such that:", + "description_images": [], + "constraints": [ + "0 <= i < j <= n - 1 and", + "nums[i] * nums[j] is divisible by k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], k = 2\nOutput:7\nExplanation:The 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 5\nOutput:0\nExplanation:There does not exist any pair of indices whose corresponding product is divisible by 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 282 ms (Top 52.2%) | Memory: 55.61 MB (Top 63.3%)\n\n//The condition given to us is (a*b % k==0)\n// So we can rewrite the above condition that if any factor of k is present in a and any other factor of k is present in b then their multiplication will be divisble by k\n\n// so gcd(a,k) * gcd(b,k) % k==0 \n\n\nclass Solution {\n public long countPairs(int[] nums, int k) {\n long ans=0;\n HashMap hm=new HashMap<>();\n for(int val:nums){\n int gcd1=gcd(val,k);\n \n for(int gcd2:hm.keySet()){\n if((long)gcd1*gcd2 % k==0){\n ans+=hm.get(gcd2);\n }\n }\n \n hm.put(gcd1,hm.getOrDefault(gcd1,0)+1);\n }\n \n return ans;\n }\n \n //function to calculate gcd \n \n public int gcd(int n1,int n2)\n {\n while(n1%n2!=0){\n int rem=n1%n2;\n n1=n2;\n n2=rem;\n }\n return n2;\n }\n}", + "title": "2183. Count Array Pairs Divisible by K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums of length n and an integer k , return the number of pairs (i, j) such that:", + "description_images": [], + "constraints": [ + "0 <= i < j <= n - 1 and", + "nums[i] * nums[j] is divisible by k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], k = 2\nOutput:7\nExplanation:The 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 5\nOutput:0\nExplanation:There does not exist any pair of indices whose corresponding product is divisible by 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n counter = Counter() #hashmap dicitionary of python\n ans = 0\n n = len(nums)\n \n for i in range(n):\n x = math.gcd(k,nums[i]) #ex: 10 = k and we have nums[i] as 12 so gcd will be 2\n want = k // x #what do we want from upper ex: we need 5\n for num in counter:\n if num % want == 0: #so if we find a number that is divisible by 5 then we can multiply it to 12 and make it a factor of 10 for ex we find 20 so it will be 240 which is divisible by 10 hence we will add it to answer\n ans += counter[num] #we are adding the freq as we can find no of numbers that have same factor\n counter[x] += 1 #here we are increasing the freq of 2 so that if we find 5 next time we can add these to the answer\n return ans\n\t\t```", + "title": "2183. Count Array Pairs Divisible by K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1 i , c1 i , r2 i , c2 i ] denotes that the i th artifact is buried in the subgrid where: You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it. Given a 0-indexed 2D integer array dig where dig[i] = [r i , c i ] indicates that you will excavate the cell (r i , c i ) , return the number of artifacts that you can extract . The test cases are generated such that:", + "description_images": [], + "constraints": [ + "(r1 i , c1 i ) is the coordinate of the top-left cell of the i th artifact and", + "(r2 i , c2 i ) is the coordinate of the bottom-right cell of the i th artifact." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]\nOutput:1\nExplanation:The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.\nThere is 1 artifact that can be extracted, namely the red artifact.\nThe blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.\nThus, we return 1.", + "image": "https://assets.leetcode.com/uploads/2019/09/16/untitled-diagram.jpg" + }, + { + "text": "Example 2: Input:n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]\nOutput:2\nExplanation:Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2019/09/16/untitled-diagram-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 198 ms (Top 10.48%) | Memory: 160.5 MB (Top 45.16%)\nclass Solution {\n public int digArtifacts(int n, int[][] artifacts, int[][] dig) {\n HashSet set = new HashSet<>();\n for (int d[] : dig) set.add(d[0] + \" \" + d[1]);\n int c = 0;\n for (int a[] : artifacts) {\n boolean done = true;\n for (int i = a[0]; i <= a[2]; i++) {\n for (int j = a[1]; j <= a[3]; j++) {\n if (!set.contains(i + \" \" + j)) done = false;\n }\n }\n if (done) c++;\n }\n return c;\n }\n}\n//TC = O(DIG + N^2)", + "title": "2201. Count Artifacts That Can Be Extracted", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , where every two consecutive vertical bars '|' are grouped into a pair . In other words, the 1 st and 2 nd '|' make a pair, the 3 rd and 4 th '|' make a pair, and so forth. Return the number of '*' in s , excluding the '*' between each pair of '|' . Note that each '|' will belong to exactly one pair.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters, vertical bars '|' , and asterisks '*' .", + "s contains an even number of vertical bars '|' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"l|*e*et|c**o|*de|\"\nOutput:2\nExplanation:The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iamprogrammer\"\nOutput:0\nExplanation:In this example, there are no asterisks in s. Therefore, we return 0.", + "image": null + }, + { + "text": "Example 3: Input:s = \"yo|uar|e**|b|e***au|tifu|l\"\nOutput:5\nExplanation:The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 7.47%) | Memory: 42.1 MB (Top 50.88%)\nclass Solution {\n public int countAsterisks(String s) {\n boolean insidePipe = false;\n int count = 0;\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == '|'){\n insidePipe = !insidePipe;\n }\n if(!insidePipe && s.charAt(i) == '*'){\n count++;\n }\n }\n return count;\n }\n}", + "title": "2315. Count Asterisks", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , where every two consecutive vertical bars '|' are grouped into a pair . In other words, the 1 st and 2 nd '|' make a pair, the 3 rd and 4 th '|' make a pair, and so forth. Return the number of '*' in s , excluding the '*' between each pair of '|' . Note that each '|' will belong to exactly one pair.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters, vertical bars '|' , and asterisks '*' .", + "s contains an even number of vertical bars '|' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"l|*e*et|c**o|*de|\"\nOutput:2\nExplanation:The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iamprogrammer\"\nOutput:0\nExplanation:In this example, there are no asterisks in s. Therefore, we return 0.", + "image": null + }, + { + "text": "Example 3: Input:s = \"yo|uar|e**|b|e***au|tifu|l\"\nOutput:5\nExplanation:The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Added on 2022-08-18 15:51:55.040392\n\nvar countAsterisks = function(s) {\n let green=true, count=0;\n for(let i=0; i= curRunLength)\n {\n count++ ;\n }\n }\n return count ;\n }\n}", + "title": "696. Count Binary Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary string s , return the number of non-empty substrings that have the same number of 0 's and 1 's, and all the 0 's and all the 1 's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110011\"\nOutput:6\nExplanation:There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10101\"\nOutput:4\nExplanation:There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 133 ms (Top 63.3%) | Memory: 16.65 MB (Top 94.0%)\n\nclass Solution:\n def countBinarySubstrings(self, s: str) -> int:\n \n # previous continuous occurrence, current continuous occurrence\n pre_cont_occ, cur_cont_occ = 0, 1\n \n # counter for binary substrings with equal 0s and 1s\n counter = 0\n \n\t\t# scan each character pair in s\n for idx in range(1, len(s)):\n \n if s[idx] == s[idx-1]:\n \n # update current continuous occurrence\n cur_cont_occ += 1\n \n else:\n # update counter of binary substrings between prevous character group and current character group\n counter += min(pre_cont_occ, cur_cont_occ)\n\n # update previous as current's continuous occurrence\n pre_cont_occ = cur_cont_occ\n \n # reset current continuous occurrence to 1\n cur_cont_occ = 1\n \n # update for last time\n counter += min(pre_cont_occ, cur_cont_occ)\n \n return counter", + "title": "696. Count Binary Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n . directions[i] can be either 'L' , 'R' , or 'S' denoting whether the i th car is moving towards the left , towards the right , or staying at its current point respectively. Each moving car has the same speed . The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road .", + "description_images": [], + "constraints": [ + "When two cars moving in opposite directions collide with each other, the number of collisions increases by 2 .", + "When a moving car collides with a stationary car, the number of collisions increases by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:directions = \"RLRSLL\"\nOutput:5\nExplanation:The collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5.", + "image": null + }, + { + "text": "Example 2: Input:directions = \"LLRR\"\nOutput:0\nExplanation:No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 59.94%) | Memory: 54.1 MB (Top 76.37%)\n/*\ncars on left side which are moving in left direction are never going to collide,\nSimilarly, cars on right side which are moving right side are never going to collide.\n\nIn between them every car is going to collide.\n*/\n\nclass Solution {\n public int countCollisions(String directions) {\n int left = 0, right = directions.length() - 1;\n\n while (left < directions.length() && directions.charAt(left) == 'L') {\n left++;\n }\n\n while (right >= 0 && directions.charAt(right) == 'R') {\n right--;\n }\n\n int count = 0;\n for (int i = left; i <= right; i++) {\n if (directions.charAt(i) != 'S') {\n count++;\n }\n }\n //combining these three loops - TC : O(N).\n\n return count;\n }\n}", + "title": "2211. Count Collisions on a Road", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n . directions[i] can be either 'L' , 'R' , or 'S' denoting whether the i th car is moving towards the left , towards the right , or staying at its current point respectively. Each moving car has the same speed . The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road .", + "description_images": [], + "constraints": [ + "When two cars moving in opposite directions collide with each other, the number of collisions increases by 2 .", + "When a moving car collides with a stationary car, the number of collisions increases by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:directions = \"RLRSLL\"\nOutput:5\nExplanation:The collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5.", + "image": null + }, + { + "text": "Example 2: Input:directions = \"LLRR\"\nOutput:0\nExplanation:No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countCollisions(self, directions: str) -> int:\n return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))\n", + "title": "2211. Count Collisions on a Road", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two string arrays words1 and words2 , return the number of strings that appear exactly once in each of the two arrays.", + "description_images": [], + "constraints": [ + "1 <= words1.length, words2.length <= 1000", + "1 <= words1[i].length, words2[j].length <= 30", + "words1[i] and words2[j] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\nOutput:2\nExplanation:- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\nOutput:0\nExplanation:There are no strings that appear in each of the two arrays.", + "image": null + }, + { + "text": "Example 3: Input:words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\nOutput:1\nExplanation:The only string that appears exactly once in each of the two arrays is \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countWords(String[] words1, String[] words2)\n {\n HashMap map1 = new HashMap<>();\n HashMap map2 = new HashMap<>();\n\t\t\n for(String word : words1)\n map1.put(word,map1.getOrDefault(word,0)+1);\n for(String word : words2)\n map2.put(word,map2.getOrDefault(word,0)+1);\n\t\t\t\n int count = 0;\n for(String word : words1)\n if(map1.get(word) == 1 && map2.getOrDefault(word,0) == 1)\n count++;\n return count;\n }\n}\n", + "title": "2085. Count Common Words With One Occurrence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two string arrays words1 and words2 , return the number of strings that appear exactly once in each of the two arrays.", + "description_images": [], + "constraints": [ + "1 <= words1.length, words2.length <= 1000", + "1 <= words1[i].length, words2[j].length <= 30", + "words1[i] and words2[j] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\nOutput:2\nExplanation:- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\nOutput:0\nExplanation:There are no strings that appear in each of the two arrays.", + "image": null + }, + { + "text": "Example 3: Input:words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\nOutput:1\nExplanation:The only string that appears exactly once in each of the two arrays is \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef countWords(self, words1: List[str], words2: List[str]) -> int:\n\t\tcount = Counter(words1 + words2)\n\t\treturn len([word for word in count if count[word] == 2 and word in words1 and word in words2])\n", + "title": "2085. Count Common Words With One Occurrence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 50.7 MB (Top 10.84%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n static int count = 0;\n\n static void Postorder(TreeNode root){\n if(root == null){\n return;\n }\n Postorder(root.left);\n Postorder(root.right);\n count++;\n }\n\n public int countNodes(TreeNode root) {\n count = 0;\n Postorder(root);\n return count;\n }\n}", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 73 ms (Top 66.36%) | Memory: 23.80 MB (Top 18.91%)\n\nclass Solution:\n # @param {TreeNode} root\n # @return {integer}\n def countNodes(self, root):\n if not root:\n return 0\n leftDepth = self.getDepth(root.left)\n rightDepth = self.getDepth(root.right)\n if leftDepth == rightDepth:\n return pow(2, leftDepth) + self.countNodes(root.right)\n else:\n return pow(2, rightDepth) + self.countNodes(root.left)\n \n def getDepth(self, root):\n if not root:\n return 0\n return 1 + self.getDepth(root.left)", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a 1 , a 2 , ... and b 1 , b 2 , ... are different if there is some i for which a i != b i .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' , 'b' , 'c' , or 'd' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bccb\"\nOutput:6\nExplanation:The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\nOutput:104860361\nExplanation:There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 61.21%) | Memory: 50.70 MB (Top 75.86%)\n\nclass Solution {\n public int countPalindromicSubsequences(String str) {\n int[] pre = new int[str.length()];\n\t\tHashMap map = new HashMap<>();\n\t\tint mod = 1000000007;\n\t\tfor(int i = 0; i < str.length(); i++) {\n\t\t\tchar ch = str.charAt(i);\n\t\t\tif(map.containsKey(ch))\n\t\t\t\tpre[i] = map.get(ch);\n\t\t\telse\n\t\t\t\tpre[i] = -1;\n\t\t\tmap.put(ch, i);\n\t\t}\n\t\t\n\t\tint[] next = new int[str.length()];\n\t\tmap = new HashMap<>();\n\t\tfor(int i = str.length() - 1; i >= 0; i--) {\n\t\t\tchar ch = str.charAt(i);\n\t\t\tif(map.containsKey(ch))\n\t\t\t\tnext[i] = map.get(ch);\n\t\t\telse\n\t\t\t\tnext[i] = Integer.MAX_VALUE;\n\t\t\tmap.put(ch, i);\n\t\t}\n\t\t\n\t\tint[][] dp = new int[str.length()][str.length()];\n\t\t\n\t\tfor(int g = 0; g < dp.length; g++) {\n\t\t\tfor(int i = 0, j = g; j < dp[0].length; i++, j++) {\n\t\t\t\tif(g == 0)\n\t\t\t\t\tdp[i][j] = 1;\n\t\t\t\telse if(g == 1)\n\t\t\t\t\tdp[i][j] = 2;\n\t\t\t\telse {\n\t\t\t\t\tif(str.charAt(i) == str.charAt(j)) {\n\t\t\t\t\t\tint n = next[i];\n\t\t\t\t\t\tint p = pre[j];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(n > p)\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) + 2) % mod;\n\t\t\t\t\t\telse if(n == p)\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) + 1) % mod;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) - dp[n+1][p-1]) % mod;\n\t\t\t\t\t}else\n\t\t\t\t\t\tdp[i][j] = (dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]) % mod;\n\t\t\t\t}\n if(dp[i][j] < 0)\n dp[i][j] += mod;\n\t\t\t}\n\t\t}\n\t\treturn dp[0][dp[0].length - 1] % mod;\n }\n}\n", + "title": "730. Count Different Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a 1 , a 2 , ... and b 1 , b 2 , ... are different if there is some i for which a i != b i .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' , 'b' , 'c' , or 'd' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bccb\"\nOutput:6\nExplanation:The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\nOutput:104860361\nExplanation:There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n \n N = len(s)\n mod = 10**9 + 7\n memo = {}\n \n def backTrack(start,end):\n \n if start >= N or end < 0: return 0\n \n key = (start,end) \n \n if key in memo: return memo[key]\n \n strn = s[start:end+1]\n\n memo[key] = 0\n\n for char in \"abcd\":\n if not char in strn: continue\n i = start + strn.index(char)\n j = start + strn.rindex(char)\n memo[key] += backTrack(i+1,j-1) + 2 if i != j else 1\n \n memo[key] %= mod\n \n return memo[key]\n \n return backTrack(0,N-1)\n\n", + "title": "730. Count Different Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of elements that have both a strictly smaller and a strictly greater element appear in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [11,7,2,15]\nOutput:2\nExplanation:The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear innums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,3,3,90]\nOutput:2\nExplanation:The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear innums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countElements(int[] nums) {\n int nmin=Integer.MAX_VALUE;\n int nmax=Integer.MIN_VALUE;\n for(int a:nums)\n {\n nmin=Math.min(a,nmin);\n nmax=Math.max(a,nmax);\n }\n int count=0;\n for(int a:nums)\n {\n if(a>nmin && a int:\n M = max(nums)\n m = min(nums)\n return sum(1 for i in nums if m> hMap = new HashMap<>();\n int count = 0;\n for(int i = 0 ; i < nums.length ; i++){\n if(!hMap.containsKey(nums[i])){\n List l = new ArrayList<>();\n l.add(i);\n hMap.put(nums[i],l);\n }else{\n List v = hMap.get(nums[i]);\n for(Integer j : v){\n if((i*j)%k == 0) count++;\n }\n v.add(i);\n hMap.put(nums[i],v);\n }\n }\n return count;\n }\n}", + "title": "2176. Count Equal and Divisible Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,2,2,1,3], k = 2\nOutput:4\nExplanation:There are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 1\nOutput:0\nExplanation:Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c\n", + "title": "2176. Count Equal and Divisible Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1 ) or barren (represented by a 0 ). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[1,1,1,1]]\nOutput:2\nExplanation:The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,1,1]]\nOutput:2\nExplanation:The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/2.JPG" + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]\nOutput:13\nExplanation:There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/3.JPG" + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 60.00%) | Memory: 67.7 MB (Top 80.00%)\nclass Solution {\n public int countPyramids(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n int[][] rev = new int[m][n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) rev[m - i - 1][j] = grid[i][j];\n }\n return cal(grid) + cal(rev);\n }\n private int cal(int[][] grid) {\n int m = grid.length, n = grid[0].length, res = 0;\n for (int i = 1; i < m; ++i) {\n for (int j = 0, cnt = 0; j < n; ++j) {\n if (0 != grid[i][j]) cnt++;\n else cnt = 0;\n if (0 == cnt || 0 == j) continue;\n grid[i][j] = Math.min(grid[i - 1][j - 1] + 1, (cnt + 1) >> 1);\n res += grid[i][j] - 1;\n }\n }\n return res;\n }\n}", + "title": "2088. Count Fertile Pyramids in a Land", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1 ) or barren (represented by a 0 ). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[1,1,1,1]]\nOutput:2\nExplanation:The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,1,1]]\nOutput:2\nExplanation:The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/2.JPG" + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]\nOutput:13\nExplanation:There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPyramids(self, grid): \n # dp[i][j] represents the number of layers of the largest pyramid with (i, j) as the vertex.\n # Note that the 1-level pyramid is invalid in the problem, so it should be removed when summing.\n # Note that if grid[i][j] is 0, dp[i][j] will always be 0.\n # The dp recurrence formula is dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 1\n m, n, dp, cnt = len(grid), len(grid[0]), copy.deepcopy(grid), 0\n # triangle\n for i in range(m - 2, -1, -1):\n for j in range(1, n - 1):\n if dp[i][j] > 0 and dp[i + 1][j] > 0:\n dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 1\n cnt += dp[i][j] - 1\n # inverted triangle\n dp = grid\n for i in range(1, m):\n for j in range(1, n - 1):\n if dp[i][j] > 0 and dp[i - 1][j] > 0:\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j + 1]) + 1\n cnt += dp[i][j] - 1\n return cnt\n", + "title": "2088. Count Fertile Pyramids in a Land", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i ​​​​​​th ​​​​ ​​​​ item of food, return the number of different good meals you can make from this list modulo 10^9 + 7 . Note that items with different indices are considered different even if they have the same deliciousness value.", + "description_images": [], + "constraints": [ + "1 <= deliciousness.length <= 10^5", + "0 <= deliciousness[i] <= 2 20" + ], + "examples": [ + { + "text": "Example 1: Input:deliciousness = [1,3,5,7,9]\nOutput:4\nExplanation:The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "image": null + }, + { + "text": "Example 2: Input:deliciousness = [1,1,1,3,3,3,7]\nOutput:15\nExplanation:The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 160 ms (Top 78.2%) | Memory: 55.21 MB (Top 66.3%)\n\nclass Solution {\n int mod = 1000000007;\n public int countPairs(int[] arr) {\n Map map = new HashMap<>();\n int n = arr.length;\n long res = 0;\n for (int num : arr) {\n int power = 1;\n for (int i = 0; i < 22; i++) {\n if (map.containsKey(power - num)) {\n res += map.get(power - num);\n res %= mod;\n }\n power *= 2;\n }\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n return (int) res;\n }\n}", + "title": "1711. Count Good Meals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i ​​​​​​th ​​​​ ​​​​ item of food, return the number of different good meals you can make from this list modulo 10^9 + 7 . Note that items with different indices are considered different even if they have the same deliciousness value.", + "description_images": [], + "constraints": [ + "1 <= deliciousness.length <= 10^5", + "0 <= deliciousness[i] <= 2 20" + ], + "examples": [ + { + "text": "Example 1: Input:deliciousness = [1,3,5,7,9]\nOutput:4\nExplanation:The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "image": null + }, + { + "text": "Example 2: Input:deliciousness = [1,1,1,3,3,3,7]\nOutput:15\nExplanation:The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n pows = [2 ** i for i in range(0,22)] # form our list of powers of 2\n dp_seen = {} # dict to store what we've seen - dynamic programming solution for time requirement\n count = 0 # to store the answer\n\n for j in range(0, len(deliciousness)):\n for i in range(0, len(pows)):\n if pows[i] - deliciousness[j] in dp_seen: # \"if we find a previous deliciousness[j] as pows[i] - deliciousness[j], then we will add dp_seen[deliciousness[j]] to count\"\n count += dp_seen[pows[i] - deliciousness[j]]\n if deliciousness[j] in dp_seen:\n dp_seen[deliciousness[j]] += 1 \n else:\n dp_seen[deliciousness[j]] = 1\n \n return count % (10**9 + 7) # the arbitrary modulo, presumably to reduce the answer size\n\t\t```", + "title": "1711. Count Good Meals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]\nOutput:4\nExplanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]\nOutput:3\nExplanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1\nExplanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 50.3 MB (Top 97.37%)\nclass Solution {\n int ans = 0;\n public int goodNodes(TreeNode root) {\n if (root == null) return 0;\n dfs(root, root.val);\n return ans;\n }\n\n void dfs(TreeNode root, int mx) {\n if (root == null) return;\n\n mx = Math.max(mx, root.val);\n if(mx <= root.val) ans++;\n\n dfs(root.left, mx);\n dfs(root.right, mx);\n\n }\n}", + "title": "1448. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]\nOutput:4\nExplanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]\nOutput:3\nExplanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1\nExplanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 132 ms (Top 87.49%) | Memory: 31.70 MB (Top 89.21%)\n\nclass Solution:\n def goodNodes(self, root: TreeNode) -> int:\n # Our counter for the good nodes.\n count = 0\n \n def helper(node, m):\n nonlocal count\n\t\t\t# If we run out of nodes return.\n if not node:\n return\n\t\t\t# If the current node val is >= the largest observed in the path thus far.\n if node.val >= m:\n\t\t\t # Add 1 to the count and update the max observed value.\n count += 1\n m = max(m, node.val)\n\t\t\t# Traverse l and r subtrees.\n helper(node.left, m)\n helper(node.right, m)\n \n helper(root, root.val)\n return count\n", + "title": "1448. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime ( 2 , 3 , 5 , or 7 ). Given an integer n , return the total number of good digit strings of length n . Since the answer may be large, return it modulo 10^9 + 7 . A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.", + "description_images": [], + "constraints": [ + "For example, \"2582\" is good because the digits ( 2 and 8 ) at even positions are even and the digits ( 5 and 2 ) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:5\nExplanation:The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:400", + "image": null + }, + { + "text": "Example 3: Input:n = 50\nOutput:564908303", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod=(int)1e9+7;\n public int countGoodNumbers(long n) {\n long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd\n long second=n/2;//second power would be n/2 only irrespective of even or odd\n long mul1=power(5,first)%mod;//5 power n/2\n long mul2=power(4,second)%mod;//4 power n/2\n long ans=1;\n ans=(ans*mul1)%mod;//computing total product\n ans=(second!=0)?(ans*mul2)%mod:ans;//computing total product\n return (int)(ans%mod);\n }\n public long power(long x,long y){// this method computes pow(x,y) in O(logn) using divide & conquer\n long temp;\n if(y==0) return 1;//base case (x power 0 = 1)\n temp=power(x,y/2);//computing power for pow(x,y/2) -> divide & conquer step\n if(y%2==0) return (temp*temp)%mod; //using that result of subproblem (2 power 2 = 2 power 1 * 2 power 1)\n else return (x*temp*temp)%mod;//using that result of subproblem (2 power 3 = 2 power 1 * 2 power 1 * 2)\n\t\t// if y is odd, x power y = x power y/2 * x power y/2 * x\n\t\t// if y is even, x power y = x power y/2 * x power y/2\n }\n}\n", + "title": "1922. Count Good Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime ( 2 , 3 , 5 , or 7 ). Given an integer n , return the total number of good digit strings of length n . Since the answer may be large, return it modulo 10^9 + 7 . A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.", + "description_images": [], + "constraints": [ + "For example, \"2582\" is good because the digits ( 2 and 8 ) at even positions are even and the digits ( 5 and 2 ) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:5\nExplanation:The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:400", + "image": null + }, + { + "text": "Example 3: Input:n = 50\nOutput:564908303", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countGoodNumbers(self, n: int) -> int:\n ans = 1\n rem = n % 2\n n -= rem\n ans = pow(20, n//2, 10**9 + 7)\n if rem == 1:\n ans *= 5\n return ans % (10**9 + 7)\n", + "title": "1922. Count Good Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , and three integers a , b and c . You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: Where |x| denotes the absolute value of x . Return the number of good triplets .", + "description_images": [], + "constraints": [ + "0 <= i < j < k < arr.length", + "|arr[i] - arr[j]| <= a", + "|arr[j] - arr[k]| <= b", + "|arr[i] - arr[k]| <= c" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\nOutput:4\nExplanation:There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,3], a = 0, b = 0, c = 1\nOutput:0\nExplanation:No triplet satisfies all conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 25.39%) | Memory: 41.4 MB (Top 78.10%)\nclass Solution {\n public int countGoodTriplets(int[] arr, int a, int b, int c) {\n int total = 0;\n for (int i = 0; i < arr.length - 2; i++){\n for (int j = i+1; j < arr.length - 1; j++){\n for (int k = j+1; k < arr.length; k++){\n if (helper(arr[i], arr[j]) <= a &&\n helper(arr[j], arr[k]) <= b &&\n helper(arr[k], arr[i]) <= c)\n total++;\n }\n }\n }\n return total;\n }\n\n private static int helper(int x, int y) {\n return Math.abs(x - y);\n }\n}", + "title": "1534. Count Good Triplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , and three integers a , b and c . You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: Where |x| denotes the absolute value of x . Return the number of good triplets .", + "description_images": [], + "constraints": [ + "0 <= i < j < k < arr.length", + "|arr[i] - arr[j]| <= a", + "|arr[j] - arr[k]| <= b", + "|arr[i] - arr[k]| <= c" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\nOutput:4\nExplanation:There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,3], a = 0, b = 0, c = 1\nOutput:0\nExplanation:No triplet satisfies all conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1794 ms (Top 11.20%) | Memory: 13.8 MB (Top 87.90%)\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n count = 0\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n for k in range(j+1,len(arr)):\n if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k]-arr[i])<=c:\n count+=1\n return count", + "title": "1534. Count Good Triplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n , both of which are permutations of [0, 1, ..., n - 1] . A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2 . In other words, if we consider pos1 v as the index of the value v in nums1 and pos2 v as the index of the value v in nums2 , then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1 , such that pos1 x < pos1 y < pos1 z and pos2 x < pos2 y < pos2 z . Return the total number of good triplets .", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "3 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= n - 1", + "nums1 and nums2 are permutations of [0, 1, ..., n - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,0,1,3], nums2 = [0,1,2,3]\nOutput:1\nExplanation:There are 4 triplets (x,y,z) such that pos1x< pos1y< pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x< pos2y< pos2z. Hence, there is only 1 good triplet.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\nOutput:4\nExplanation:The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long goodTriplets(int[] nums1, int[] nums2) {\n int n= nums1.length;\n int indices[]= new int[n];\n for(int i=0;i0;i--)\n {\n right[i]=R.sum(n)-R.sum(B[i-1]);\n R.update(B[i-1],1);\n }\n long ans=0l;\n for(int i=0;i<=n;i++)\n {\n ans+=left[i]*right[i];\n }\n return ans;\n }\n}\nclass Fenw\n{\n long[]farr;\n int n;\n Fenw(int n)\n {\n this.n=n;\n farr=new long[n+1];\n }\n void update(int index, int val)\n {\n int c=0;\n for(int i=index;i<=n;i+=(i&-i))\n {\n c++;\n farr[i]+=val;\n }\n }\n \n long sum(int index)\n {\n long ans=0l;\n for(int i=index;i>0;i-=(i&-i))\n {\n ans+=farr[i];\n }\n return ans;\n }\n}", + "title": "2179. Count Good Triplets in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n , both of which are permutations of [0, 1, ..., n - 1] . A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2 . In other words, if we consider pos1 v as the index of the value v in nums1 and pos2 v as the index of the value v in nums2 , then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1 , such that pos1 x < pos1 y < pos1 z and pos2 x < pos2 y < pos2 z . Return the total number of good triplets .", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "3 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= n - 1", + "nums1 and nums2 are permutations of [0, 1, ..., n - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,0,1,3], nums2 = [0,1,2,3]\nOutput:1\nExplanation:There are 4 triplets (x,y,z) such that pos1x< pos1y< pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x< pos2y< pos2z. Hence, there is only 1 good triplet.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\nOutput:4\nExplanation:The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\nclass Solution:\n def goodTriplets(self, A: List[int], B: List[int]) -> int:\n # Index of a (from A) in B.\n pos = [0] * len(A) \n for idx, b in enumerate(B):\n pos[b] = idx\n \n # Build pre_a[i]: number of elements on a[i]'s left in both A and B.\n # pos_in_b: sorted indexes (in B) of all the visited elements in A.\n pos_in_b, pre_a = SortedList([pos[A[0]]]), [0] \n for a in A[1:]: \n pos_in_b.add(pos[a])\n pre_a.append(pos_in_b.bisect_left(pos[a]))\n \n # Build suf_a[i]: number of elements on a[i]'s right in both A and B.\n pos_in_b, suf_a = SortedList([pos[A[-1]]]), [0]\n for a in reversed(A[:len(A)-1]):\n idx = pos_in_b.bisect(pos[a])\n suf_a.append(len(pos_in_b) - idx)\n pos_in_b.add(pos[a])\n suf_a.reverse()\n \n # Sum up all unique triplets centered on A[i].\n ans = 0\n for x, y in zip(pre_a, suf_a):\n ans += x * y\n return ans\n", + "title": "2179. Count Good Triplets in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i] . Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i] . Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j] . Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,1,1,6,5]\nOutput:3\nExplanation:At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,6,5,5,4,1]\nOutput:0\nExplanation:At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countHillValley(int[] nums) {\n int result = 0;\n \n\t\t// Get head start. Find first index for which nums[index] != nums[index-1]\n\t\tint start = 1;\n\t\twhile(start < nums.length && nums[start] == nums[start-1])\n\t\t\tstart++;\n\n\t\tint prev = start-1; //index of prev different value num\n\t\tfor(int i=start; i nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number\n\t\t\t\t\tresult++;\n\t\t\t\tif(nums[i] < nums[prev] && nums[i] < nums[i+1])\n\t\t\t\t\tresult++;\n\t\t\t\tprev = i; // Now your current number will become prev number.\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}", + "title": "2210. Count Hills and Valleys in an Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed integer array nums . An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i] . Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i] . Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j] . Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,1,1,6,5]\nOutput:3\nExplanation:At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,6,5,5,4,1]\nOutput:0\nExplanation:At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHillValley(self, nums: List[int]) -> int:\n c = 0\n i = 1\n while i nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):\n c += 1\n i = j\n return c\n", + "title": "2210. Count Hills and Valleys in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an empty set of intervals, implement a data structure that can: Implement the CountIntervals class: Note that an interval [left, right] denotes all the integers x where left <= x <= right .", + "description_images": [], + "constraints": [ + "Add an interval to the set of intervals.", + "Count the number of integers that are present in at least one interval." + ], + "examples": [ + { + "text": "Example 1: Input[\"CountIntervals\", \"add\", \"add\", \"count\", \"add\", \"count\"]\n[[], [2, 3], [7, 10], [], [5, 8], []]Output[null, null, null, 6, null, 8]ExplanationCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3); // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count(); // return 6\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8); // add [5, 8] to the set of intervals.\ncountIntervals.count(); // return 8\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 5 and 6 are present in the interval [5, 8].\n // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n // the integers 9 and 10 are present in the interval [7, 10].", + "image": null + } + ], + "follow_up": null, + "solution": "class CountIntervals {\n \n //for storing intervals\n TreeMap map=new TreeMap<>();\n int count=0;\n public CountIntervals() {\n }\n \n public void add(int left, int right) {\n //we are taking left side as reference and calculating ans\n \n //this is the current length\n int add=right-left+1;\n \n //var is the default data type\n //lowerentry gives the value of smaller(smaller largest) entry compared to (left+1)\n //we added +1 bcz there may be a case where left is present in a map\n //lowerentry gives the value(that is)=left){\n //positions are map.left <= left <= min(map.right,right) <= max(map.right,right)\n \n//examples: (1) (2) (3)\n// ____________ _________ _______________ (map)\n// ___________ ________ ____ (our)\n \n //now, left become the smallest value which in this case is map.left\n left=left_bound.getKey();\n \n //same as right become the maximum value\n right=Math.max(left_bound.getValue(),right);\n \n //value overlap means curr answer(add) also change\n //we already calculated the map value (covered area) and added into ans variable\n //calculate/add the new uncovered value\n // right - map.right\n //max(right,map.right) - map.right\n //we are not adding +1 bcz that is already handled by overlaping area\n add=right-left_bound.getValue();\n \n //this is taken so we have to remove\n //at last we added the largest area (which is stored int left,right)\n map.remove(left_bound.getKey());\n }\n \n //check is right overlaping\n //if yes then take the correct values\n //higherEntry gives the largest(largest smallest) value in map\n //we are not taking left+1 bcz that condition is already been satisfied\n //eg. left=5 map contains (5,value)\n //condition is checked in left_bound\n //i.getKey()<=right means curr is beneath our map.left and covering area(overlaping)\n for(var i=map.higherEntry(left); i!=null && i.getKey()<=right; i=map.higherEntry(left)){\n //left <= map.left <= min(right,map.right) <= max(right,map.right)\n \n \n//examples: (1) (2) (3)\n// ____________ _________ _______ (map)\n// ___________ ________ _________________ (our)\n \n \n //now we have our add which is current ans but some area is overlaping\n //so we have to subtract overlaping area\n //+1 bcz [2,5] we have 4 position (2,3,4,5) ; 5-2=>3 ; we ned to add 1\n add-=Math.min(right,i.getValue())-i.getKey()+1;\n \n //right value become the largest among them\n right=Math.max(right,i.getValue());\n \n //we have taken care this entry and calculated left and right now we don't need\n map.remove(i.getKey());\n }\n \n //we pushed the values\n //this entry can be essential for next calls\n map.put(left,right);\n \n //add the current ans\n count+=add;\n \n \n }\n \n public int count() {\n return count;\n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = new CountIntervals();\n * obj.add(left,right);\n * int param_2 = obj.count();\n */\n", + "title": "2276. Count Integers in Intervals", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an empty set of intervals, implement a data structure that can: Implement the CountIntervals class: Note that an interval [left, right] denotes all the integers x where left <= x <= right .", + "description_images": [], + "constraints": [ + "Add an interval to the set of intervals.", + "Count the number of integers that are present in at least one interval." + ], + "examples": [ + { + "text": "Example 1: Input[\"CountIntervals\", \"add\", \"add\", \"count\", \"add\", \"count\"]\n[[], [2, 3], [7, 10], [], [5, 8], []]Output[null, null, null, 6, null, 8]ExplanationCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3); // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count(); // return 6\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8); // add [5, 8] to the set of intervals.\ncountIntervals.count(); // return 8\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 5 and 6 are present in the interval [5, 8].\n // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n // the integers 9 and 10 are present in the interval [7, 10].", + "image": null + } + ], + "follow_up": null, + "solution": "class CountIntervals:\n\n def __init__(self):\n\t# initialize the merged intervals list as below to handle edge cases\n self.interv = [(-inf, -inf), (inf, inf)]\n self.cov = 0 \n\n def add(self, left: int, right: int) -> None:\n \n interv = self.interv\n \n\t\t# find the left most position for inserting of the new potentially merged interval\n\t\t# we use `left - 1` because the interval coverage is inclusive\n li = bisect.bisect_left(interv, left - 1, key=itemgetter(1))\n lval = min(interv[li][0], left)\n\t\t\n\t\t# find the right most position for inserting the new potentially merged interval\n\t\t# we use `right + 1` because the interval coverage is inclusive\n ri = bisect.bisect_right(interv, right + 1, key=itemgetter(0))\n rval = max(interv[ri - 1][1], right)\n\n\t\t# find the coverage of the intervals that will be replaced by the new interval\n to_delete = 0\n for _ in range(li, ri):\n to_delete += interv[_][1] - interv[_][0] + 1\n \n\t\t# udpate the coverage\n self.cov += rval - lval + 1 - to_delete\n interv[li: ri] = [(lval, rval)]\n\n def count(self) -> int:\n return self.cov\n", + "title": "2276. Count Integers in Intervals", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer num , return the number of positive integers less than or equal to num whose digit sums are even . The digit sum of a positive integer is the sum of all its digits.", + "description_images": [], + "constraints": [ + "1 <= num <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:num = 4\nOutput:2\nExplanation:The only integers less than or equal to 4 whose digit sums are even are 2 and 4.", + "image": null + }, + { + "text": "Example 2: Input:num = 30\nOutput:14\nExplanation:The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.76%) | Memory: 40.70 MB (Top 10.24%)\n\nclass Solution\n{\n public int countEven(int num)\n {\n int count = 0;\n for(int i = 1; i <= num; i++)\n if(sumDig(i))\n count++;\n return count;\n }\n private boolean sumDig(int n)\n {\n int sum = 0;\n while(n > 0)\n {\n sum += n % 10;\n n /= 10;\n }\n\t\treturn (sum&1) == 0 ? true : false;\n }\n}\n", + "title": "2180. Count Integers With Even Digit Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer num , return the number of positive integers less than or equal to num whose digit sums are even . The digit sum of a positive integer is the sum of all its digits.", + "description_images": [], + "constraints": [ + "1 <= num <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:num = 4\nOutput:2\nExplanation:The only integers less than or equal to 4 whose digit sums are even are 2 and 4.", + "image": null + }, + { + "text": "Example 2: Input:num = 30\nOutput:14\nExplanation:The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countEven(self, num: int) -> int:\n if num%2!=0:\n return (num//2)\n s=0\n t=num\n while t:\n s=s+(t%10)\n t=t//10\n if s%2==0:\n return num//2\n else:\n return (num//2)-1\n", + "title": "2180. Count Integers With Even Digit Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array items , where each items[i] = [type i , color i , name i ] describes the type, color, and name of the i th item. You are also given a rule represented by two strings, ruleKey and ruleValue . The i th item is said to match the rule if one of the following is true: Return the number of items that match the given rule .", + "description_images": [], + "constraints": [ + "ruleKey == \"type\" and ruleValue == type i .", + "ruleKey == \"color\" and ruleValue == color i .", + "ruleKey == \"name\" and ruleValue == name i ." + ], + "examples": [ + { + "text": "Example 1: Input:items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"\nOutput:1\nExplanation:There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].", + "image": null + }, + { + "text": "Example 2: Input:items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"\nOutput:2\nExplanation:There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 61.48%) | Memory: 56.3 MB (Top 75.54%)\nclass Solution {\n public int countMatches(List> items, String ruleKey, String ruleValue) {\n int res = 0;\n\n for(int i = 0 ;i int:\n d = {'type': 0, 'color': 1, 'name': 2}\n return sum(1 for item in items if item[d[ruleKey]] == ruleValue)\n", + "title": "1773. Count Items Matching a Rule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:4\nExplanation:There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:2\nExplanation:There are 2 groups [1], [2] of size 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countLargestGroup(int n) {\n Map map=new HashMap<>();\n for(int i=1;i<=n;i++){\n int x=sum(i);\n map.put(x,map.getOrDefault(x,0)+1);\n }\n int max=Collections.max(map.values());\n int c=0;\n for(int i:map.values()){\n if(i==max) c++;\n }\n return c;\n }\n public int sum(int g){\n int summ=0;\n while(g!=0){\n int rem=g%10;\n summ+=rem;\n g/=10;\n }\n return summ;\n }\n}```", + "title": "1399. Count Largest Group", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:4\nExplanation:There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:2\nExplanation:There are 2 groups [1], [2] of size 1.", + "image": null + } + ], + "follow_up": null, + "solution": "def compute(num):\n\tif num < 10:\n\t\treturn num\n\n\tnewVal = 0\n\n\twhile num > 0:\n\t\tlast = num % 10\n\t\tnewVal += last\n\t\tnum /= 10\n\n\treturn newVal\n\nclass Solution(object):\n\tdef countLargestGroup(self, n):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tmyMap = {}\n\n\t\tfor i in range(1, n + 1):\n\t\t\tval = compute(i)\n\n\t\t\tif val in myMap.keys():\n\t\t\t\tmyMap.get(val).append(i)\n\t\t\telse:\n\t\t\t\tmyMap[val] = [i]\n\n\t\tmaxLen = 0\n\n\t\tfor n in myMap.values():\n\t\t\tmaxLen = max(maxLen, len(n))\n\n\t\tans = 0\n\n\t\tfor n in myMap.values():\n\t\t\tif len(n) == maxLen:\n\t\t\t\tans += 1\n\n\t\treturn ans\n", + "title": "1399. Count Largest Group", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array circles where circles[i] = [x i , y i , r i ] represents the center (x i , y i ) and radius r i of the i th circle drawn on a grid, return the number of lattice points that are present inside at least one circle . Note:", + "description_images": [], + "constraints": [ + "A lattice point is a point with integer coordinates.", + "Points that lie on the circumference of a circle are also considered to be inside it." + ], + "examples": [ + { + "text": "Example 1: Input:circles = [[2,2,1]]\nOutput:5\nExplanation:The figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-11.png" + }, + { + "text": "Example 2: Input:circles = [[2,2,2],[3,4,1]]\nOutput:16\nExplanation:The figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-22.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countLatticePoints(int[][] circles) {\n Set answer = new HashSet();\n \n for (int[] c : circles) {\n int x = c[0], y = c[1], r = c[2];\n \n // traversing over all the points that lie inside the smallest square capable of containing the whole circle\n for (int xx = x - r; xx <= x + r; xx++)\n for (int yy = y - r; yy <= y + r; yy++)\n if ((r * r) >= ((x - xx) * (x - xx)) + ((y - yy) * (y - yy)))\n answer.add(xx + \":\" + yy);\n }\n \n return answer.size();\n }\n}\n", + "title": "2249. Count Lattice Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D integer array circles where circles[i] = [x i , y i , r i ] represents the center (x i , y i ) and radius r i of the i th circle drawn on a grid, return the number of lattice points that are present inside at least one circle . Note:", + "description_images": [], + "constraints": [ + "A lattice point is a point with integer coordinates.", + "Points that lie on the circumference of a circle are also considered to be inside it." + ], + "examples": [ + { + "text": "Example 1: Input:circles = [[2,2,1]]\nOutput:5\nExplanation:The figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-11.png" + }, + { + "text": "Example 2: Input:circles = [[2,2,2],[3,4,1]]\nOutput:16\nExplanation:The figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-22.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countLatticePoints(self, c: List[List[int]]) -> int:\n ans,m=0,[0]*40401\n c=set(((x,y,r) for x,y,r in c))\n for x, y, r in c:\n for i in range(x-r, x+r+1):\n d=int(sqrt(r*r-(x-i)*(x-i)))\n m[i*201+y-d:i*201+y+d+1]=[1]*(d+d+1)\n return sum(m)\n", + "title": "2249. Count Lattice Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 100", + "-100 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput:8\nExplanation:There are 8 negatives number in the matrix.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[3,2],[1,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countNegatives(int[][] grid) {\n int m = grid.length ;\n int n = grid[0].length ;\n int c = 0;\n int count = 0;\n int r = m-1;\n while( r >= 0 && c < n ) {\n if (grid[r][c] < 0 ) {\n r--;\n count += n - c;\n } else{\n c++;\n }\n }\n return count;\n }\n}\n\n", + "title": "1351. Count Negative Numbers in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 100", + "-100 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput:8\nExplanation:There are 8 negatives number in the matrix.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[3,2],[1,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 252 ms (Top 17.18%) | Memory: 15.1 MB (Top 10.42%)\nclass Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n\n for i in grid:\n low = 0\n high = len(i) - 1\n\n while low <= high:\n mid = (low+high)//2\n if i[mid] < 0:\n high = mid - 1\n elif i[mid] >= 0:\n low = mid + 1\n count += (len(i) - low)\n return count", + "title": "1351. Count Negative Numbers in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x . For example, rev(123) = 321 , and rev(120) = 21 . A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices . Since that number can be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "0 <= i < j < nums.length", + "nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [42,11,1,97]\nOutput:2\nExplanation:The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [13,10,35,24,76]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 85.52%) | Memory: 58.10 MB (Top 25.69%)\n\nclass Solution {\n public int countNicePairs(int[] nums) {\n final int mod = 1000000007;\n int len = nums.length;\n for (int i = 0; i < len; i++) {\n nums[i] = nums[i] - reverse(nums[i]);\n }\n Arrays.sort(nums);\n long res = 0;\n for (int i = 0; i < len - 1; i++) {\n long count = 1;\n while (i < len - 1 && nums[i] == nums[i + 1]) {\n count++;\n i++;\n }\n res = (res % mod + (count * (count - 1)) / 2) % mod;\n }\n\n return (int) (res % mod);\n }\n private int reverse(int num) {\n int rev = 0;\n while (num > 0) {\n rev = rev * 10 + num % 10;\n num /= 10;\n }\n return rev;\n }\n}\n", + "title": "1814. Count Nice Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x . For example, rev(123) = 321 , and rev(120) = 21 . A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices . Since that number can be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "0 <= i < j < nums.length", + "nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [42,11,1,97]\nOutput:2\nExplanation:The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [13,10,35,24,76]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 500 ms (Top 94.22%) | Memory: 26.90 MB (Top 76.37%)\n\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n res = 0\n count = {}\n mod = 10**9 + 7\n \n for n in nums:\n rev = int(str(n)[::-1])\n cur = count.get(n - rev, 0)\n res += cur\n count[n - rev] = 1 + cur\n\n return res % mod\n", + "title": "1814. Count Nice Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree . Note:", + "description_images": [], + "constraints": [ + "The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.", + "A subtree of root is a tree consisting of root and all of its descendants." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,8,5,0,1,null,6]\nOutput:5\nExplanation:For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:1\nExplanation:For the node with value 1: The average of its subtree is 1 / 1 = 1.", + "image": "https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int res = 0;\n public int averageOfSubtree(TreeNode root) {\n dfs(root);\n return res;\n }\n \n private int[] dfs(TreeNode node) {\n if(node == null) {\n return new int[] {0,0};\n }\n \n int[] left = dfs(node.left);\n int[] right = dfs(node.right);\n \n int currSum = left[0] + right[0] + node.val;\n int currCount = left[1] + right[1] + 1;\n \n if(currSum / currCount == node.val) {\n res++;\n }\n \n return new int[] {currSum, currCount};\n }\n}\n", + "title": "2265. Count Nodes Equal to Average of Subtree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree . Note:", + "description_images": [], + "constraints": [ + "The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.", + "A subtree of root is a tree consisting of root and all of its descendants." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,8,5,0,1,null,6]\nOutput:5\nExplanation:For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:1\nExplanation:For the node with value 1: The average of its subtree is 1 / 1 = 1.", + "image": "https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n \n \n def calculate_average(root):\n if root:\n self.summ+=root.val\n self.nodecount+=1\n calculate_average(root.left)\n calculate_average(root.right)\n \n \n def calculate_for_each_node(root):\n if root:\n self.summ = 0\n self.nodecount = 0\n calculate_average(root)\n if ((self.summ)//(self.nodecount)) == root.val:\n self.count+=1 \n calculate_for_each_node(root.left)\n calculate_for_each_node(root.right)\n \n \n self.count = 0\n calculate_for_each_node(root) \n return self.count\n\n", + "title": "2265. Count Nodes Equal to Average of Subtree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1 . You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i . Since node 0 is the root, parents[0] == -1 . Each node has a score . To find the score of a node, consider if the node and the edges connected to it were removed . The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score .", + "description_images": [], + "constraints": [ + "n == parents.length", + "2 <= n <= 10^5", + "parents[0] == -1", + "0 <= parents[i] <= n - 1 for i != 0", + "parents represents a valid binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,2,0,2,0]\nOutput:3\nExplanation:- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,2,0]\nOutput:2\nExplanation:- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 95.33%) | Memory: 67.90 MB (Top 73.63%)\n\nclass Solution {\n /** Algorithm/Theory\n 1. An efficient first step is to build the tree. This way, we can post-order traverse it and determine the product of non-empty subtrees\n 2. Use a simple Node[] array to map node order/value to Node content.\n set node[0] to be the parent.\n loop from 1 to n and if the current node[i] is null, set it as new node. If the parent is null, initialize node[parent[i]].\n set node[parent[i]].left or .right to node[i], depending if left or right is already set.\n 3. Continue post-order traversal. \n - if on a leaf, that leaf will make a score of total -1. Check against the current highest score and set. Return 1 as that leaft has only 1 node\n - if not on a leaf, apply post-oder to left and right.\n 4. After 3b) for each parent node, determine its number of nodes from its subtree: 1 + left + right.\n 6. Once 5 is done, determine the highest score that node will generate.\n This will be Math.max(1, onLeft) * Math.max(1, onRight) * Math.max(1, (totalNodes - nrOfNodesFromSubtree)).\n Basically we are multiplying the remaining 3 groups of nodes that are formed from the removal of that node (left, right, above).\n Pay attention to multiply with 1 (not with 0). The root will have no \"above\" nodes so total - nodesOnSubtree will return 0.\n */\n public int countHighestScoreNodes(int[] parents) {\n Node[] nodes = buildTree(parents);\n long[] highestScore = {0,0};\n countHighestScore(nodes[0], highestScore, parents.length);\n return (int)highestScore[1];\n }\n\n private int countHighestScore(Node node, long[] highestScore, int total) {\n if (node != null) {\n if (node.left == null && node.right == null) {\n // a leaf will have 1 node under(itself) and will produce a total nodes - 1 score.\n if (highestScore[0] == total - 1) {\n highestScore[1]++;\n } else if (highestScore[0] < total - 1) {\n highestScore[0] = total - 1;\n highestScore[1] = 1;\n }\n return 1;\n } else {\n // apply post-order and see how many nodes are left and right\n int onLeft = countHighestScore(node.left, highestScore, total);\n int onRight = countHighestScore(node.right, highestScore, total);\n int totalSubtree = onLeft + onRight + 1;\n // if left or right is null, replace it with 1, multiplication by 1\n long possibleScore = (long) (Math.max(1, onLeft)) * Math.max(onRight, 1)\n * Math.max(1, total - totalSubtree);\n if (highestScore[0] == possibleScore) {\n highestScore[1]++;\n } else if (highestScore[0] < possibleScore) {\n highestScore[0] = possibleScore;\n highestScore[1] = 1;\n }\n return totalSubtree;\n }\n }\n return 0;\n }\n\n private Node[] buildTree(int[] parents) {\n Node[] nodes = new Node[parents.length];\n nodes[0] = new Node();\n for (int i = 1; i < parents.length; i++) {\n // create current node\n if (nodes[i] == null) {\n nodes[i] = new Node();\n }\n // create parent node\n if (nodes[parents[i]] == null) {\n nodes[parents[i]] = new Node();\n }\n // link parent node left or right to this child node.\n if (nodes[parents[i]].left == null) {\n nodes[parents[i]].left = nodes[i];\n } else {\n nodes[parents[i]].right = nodes[i];\n }\n }\n return nodes;\n }\n\n private static class Node {\n Node left;\n Node right;\n }\n}\n", + "title": "2049. Count Nodes With the Highest Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1 . You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i . Since node 0 is the root, parents[0] == -1 . Each node has a score . To find the score of a node, consider if the node and the edges connected to it were removed . The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score .", + "description_images": [], + "constraints": [ + "n == parents.length", + "2 <= n <= 10^5", + "parents[0] == -1", + "0 <= parents[i] <= n - 1 for i != 0", + "parents represents a valid binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,2,0,2,0]\nOutput:3\nExplanation:- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,2,0]\nOutput:2\nExplanation:- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n graph = collections.defaultdict(list)\n for node, parent in enumerate(parents): # build graph\n graph[parent].append(node)\n n = len(parents) # total number of nodes\n d = collections.Counter()\n def count_nodes(node): # number of children node + self\n p, s = 1, 0 # p: product, s: sum\n for child in graph[node]: # for each child (only 2 at maximum)\n res = count_nodes(child) # get its nodes count\n p *= res # take the product\n s += res # take the sum\n p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)\n d[p] += 1 # count the product\n return s + 1 # return number of children node + 1 (self)\n count_nodes(0) # starting from root (0)\n return d[max(d.keys())] # return max count\n", + "title": "2049. Count Nodes With the Highest Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i] . Return the total number of bad pairs in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,3,3]\nOutput:5\nExplanation:The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]\nOutput:0\nExplanation:There are no bad pairs.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 94.02%) | Memory: 55.7 MB (Top 95.47%)\nclass Solution {\n public long countBadPairs(int[] nums) {\n HashMap seen = new HashMap<>();\n long count = 0;\n for(int i = 0; i < nums.length; i++){\n int diff = i - nums[i];\n if(seen.containsKey(diff)){\n count += (i - seen.get(diff));\n }else{\n count += i;\n }\n seen.put(diff, seen.getOrDefault(diff, 0) + 1);\n }\n return count;\n }\n}", + "title": "2364. Count Number of Bad Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i] . Return the total number of bad pairs in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,3,3]\nOutput:5\nExplanation:The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]\nOutput:0\nExplanation:There are no bad pairs.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBadPairs(self, nums: List[int]) -> int:\n nums_len = len(nums)\n count_dict = dict()\n for i in range(nums_len):\n nums[i] -= i\n if nums[i] not in count_dict:\n count_dict[nums[i]] = 0\n count_dict[nums[i]] += 1\n \n count = 0\n for key in count_dict:\n count += math.comb(count_dict[key], 2)\n return math.comb(nums_len, 2) - count\n", + "title": "2364. Count Number of Bad Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return the number of homogenous substrings of s . Since the answer may be too large, return it modulo 10^9 + 7 . A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbcccaa\"\nOutput:13\nExplanation:The homogenous substrings are listed as below:\n\"a\" appears 3 times.\n\"aa\" appears 1 time.\n\"b\" appears 2 times.\n\"bb\" appears 1 time.\n\"c\" appears 3 times.\n\"cc\" appears 2 times.\n\"ccc\" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.", + "image": null + }, + { + "text": "Example 2: Input:s = \"xy\"\nOutput:2\nExplanation:The homogenous substrings are \"x\" and \"y\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"zzzzz\"\nOutput:15", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 22.57%) | Memory: 50.5 MB (Top 79.00%)\nclass Solution {\n public int countHomogenous(String s) {\n int res = 1;\n int carry = 1;\n int mod = 1000000007;\n for(int i =1;i int:\n res, count, n = 0, 1, len(s)\n for i in range(1,n):\n if s[i]==s[i-1]:\n count+=1\n else:\n if count>1:\n res+=(count*(count-1)//2)\n count=1 \n if count>1:\n res+=(count*(count-1)//2)\n return (res+n)%(10**9+7)", + "title": "1759. Count Number of Homogenous Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR . An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] ( 0-indexed ).", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 16", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1]\nOutput:2\nExplanation:The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]\nOutput:7\nExplanation:All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23- 1 = 7 total subsets.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5]\nOutput:6\nExplanation:The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countMaxOrSubsets(int[] nums) {\n \n subsets(nums, 0, 0);\n return count;\n }\n \n int count = 0;\n int maxOR = 0;\n \n private void subsets(int[] arr, int vidx, int OR){\n \n if(vidx == arr.length){\n \n if(OR == maxOR){\n count ++;\n }else if(OR > maxOR){\n count = 1;\n maxOR = OR;\n }\n \n return;\n }\n \n // include\n subsets(arr, vidx+1, OR | arr[vidx]);\n \n // exclude\n subsets(arr, vidx+1, OR);\n }\n}\n", + "title": "2044. Count Number of Maximum Bitwise-OR Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR . An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] ( 0-indexed ).", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 16", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1]\nOutput:2\nExplanation:The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]\nOutput:7\nExplanation:All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23- 1 = 7 total subsets.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5]\nOutput:6\nExplanation:The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \n def dfs(i,val):\n if maxBit == val : return 1<<(len(nums)-i)\n if i == len(nums): return 0\n return dfs(i+1,val|nums[i]) + dfs(i+1,val)\n maxBit = 0\n for i in nums: maxBit |= i\n return dfs(0,0)\n", + "title": "2044. Count Number of Maximum Bitwise-OR Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3\nOutput:2\nExplanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1\nOutput:0\nExplanation:There is no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.36%) | Memory: 75.4 MB (Top 41.15%)\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int i = 0;\n int j = 0;\n int odd = 0;\n int result = 0;\n int temp = 0;\n\n /*\n Approach : two pointer + sliding window technique\n\n step 1 : we have fix i and moving j until our count of odd numbers == k\n step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i\n\n why temp?\n from reducing the size of subarray we will count all the possible subarray from between i and j\n but when i encounter a odd element the odd count will reduce and that while will stop executing\n\n now there are two possible cases\n 1.The leftover elements have a odd number\n 2.The leftover elements do not have any odd number\n\n 1. if our leftover elements have a odd number\n then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed\n that's why temp = 0;\n\n 2. if out leftover elements do not have any odd element left\n then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays\n */\n while(j< nums.length){\n if(nums[j]%2 != 0)\n {\n odd++;\n //if leftover elements have odd element then new window is formed so we set temp = 0;\n temp = 0;\n }\n while(odd ==k){\n temp++;\n if(nums[i] %2 != 0)\n odd--;\n i++;\n }\n //if no leftover elements is odd, each element will part in forming subarray\n //so include them\n result += temp;\n j++;\n\n }\n return result;\n }\n}", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3\nOutput:2\nExplanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1\nOutput:0\nExplanation:There is no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 628 ms (Top 69.2%) | Memory: 18.88 MB (Top 60.5%)\n\nclass Solution(object):\n\tdef numberOfSubarrays(self, nums, k):\n\t\t\"\"\"\n\t\te.g. k = 2\n\t\tnums = [2, 2, 1, 2, 1, 2, 2]\n\t\tindex= 0 1 2 3 4 5 6\n\t\t2 even numbers to left of first 1\n\t\t2 even numbers to right of last 1\n\t\ttotal number of subarrays = pick between 0-2 numbers on left, then, pick between 0-2 numbers on right\n\t\ti.e (left+1) (right+1)\n\t\tThen slide window to next set of 2 odd numbers\n\t\t\"\"\"\n\n\t\todds = []\n\n\t\tfor i in range(len(nums)):\n\t\t\tif nums[i] & 1:\n\t\t\t\todds.append(i) #' Find index of all odd numbers '\n\n\t\todds = [-1] + odds + [len(nums)] #' Handle edge cases '\n\t\tnice = 0\n\n\t\tfor i in range(1, len(odds)-k):\n\t\t\tleft = odds[i] - odds[i-1] - 1 #' Number of 'left' even numbers '\n\t\t\tright = odds[i+k] - odds[i+k-1] - 1 #' Number of 'right' even numbers '\n\t\t\tnice += (left+1)*(right+1) #' Total sub-arrays in current window '\n\n\t\treturn nice\n ", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k . The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0 .", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,1], k = 1\nOutput:4\nExplanation:The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3], k = 3\nOutput:0\nExplanation:There are no pairs with an absolute difference of 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5,4], k = 2\nOutput:3\nExplanation:The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 51.83%) | Memory: 44.1 MB (Top 44.46%)\nclass Solution {\n public int countKDifference(int[] nums, int k) {\n Map map = new HashMap<>();\n int res = 0;\n\n for(int i = 0;i< nums.length;i++){\n if(map.containsKey(nums[i]-k)){\n res+= map.get(nums[i]-k);\n }\n if(map.containsKey(nums[i]+k)){\n res+= map.get(nums[i]+k);\n }\n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n\n return res;\n }\n}", + "title": "2006. Count Number of Pairs With Absolute Difference K", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array nums and an integer k , return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k . The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0 .", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,1], k = 1\nOutput:4\nExplanation:The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3], k = 3\nOutput:0\nExplanation:There are no pairs with an absolute difference of 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5,4], k = 2\nOutput:3\nExplanation:The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n counter += seen[tmp2]\n \n seen[num] += 1\n \n return counter\n", + "title": "2006. Count Number of Pairs With Absolute Difference K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array rectangles where rectangles[i] = [l i , h i ] indicates that i th rectangle has a length of l i and a height of h i . You are also given a 2D integer array points where points[j] = [x j , y j ] is a point with coordinates (x j , y j ) . The i th rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (l i , h i ) . Return an integer array count of length points.length where count[j] is the number of rectangles that contain the j th point. The i th rectangle contains the j th point if 0 <= x j <= l i and 0 <= y j <= h i . Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.", + "description_images": [], + "constraints": [ + "1 <= rectangles.length, points.length <= 5 * 10^4", + "rectangles[i].length == points[j].length == 2", + "1 <= l i , x j <= 10^9", + "1 <= h i , y j <= 100", + "All the rectangles are unique .", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\nOutput:[2,1]\nExplanation:The first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example1.png" + }, + { + "text": "Example 2: Input:rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\nOutput:[1,3]\nExplanation:The first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1094 ms (Top 10.04%) | Memory: 110.7 MB (Top 25.95%)\nclass Solution {\n public int[] countRectangles(int[][] rectangles, int[][] points) {\n int max = Integer.MIN_VALUE;\n\n TreeMap> rects = new TreeMap<>();\n for(int[] rect : rectangles) {\n if (!rects.containsKey(rect[1])) {\n rects.put(rect[1], new ArrayList());\n }\n\n rects.get(rect[1]).add(rect[0]);\n max = Math.max(max, rect[1]);\n }\n\n for(int k : rects.keySet()) {\n Collections.sort(rects.get(k));\n }\n\n int[] ans = new int[points.length];\n for(int i = 0; i < points.length; i++) {\n if (points[i][1] > max) {\n continue;\n }\n\n int count = 0;\n\n for(int key : rects.subMap(points[i][1], max + 1).keySet()) {\n List y = rects.get(key);\n\n count += binarySearch(y, points[i][0]);\n }\n\n ans[i] = count;\n }\n\n return ans;\n }\n\n private int binarySearch(List vals, int val) {\n int lo = 0;\n int hi = vals.size() - 1;\n int id = -1;\n\n while(lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n\n if (vals.get(mid) < val) {\n lo = mid + 1;\n } else {\n id = mid;\n hi = mid - 1;\n }\n }\n\n if (id < 0) {\n return 0;\n }\n\n return vals.size() - id;\n }\n}", + "title": "2250. Count Number of Rectangles Containing Each Point", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array rectangles where rectangles[i] = [l i , h i ] indicates that i th rectangle has a length of l i and a height of h i . You are also given a 2D integer array points where points[j] = [x j , y j ] is a point with coordinates (x j , y j ) . The i th rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (l i , h i ) . Return an integer array count of length points.length where count[j] is the number of rectangles that contain the j th point. The i th rectangle contains the j th point if 0 <= x j <= l i and 0 <= y j <= h i . Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.", + "description_images": [], + "constraints": [ + "1 <= rectangles.length, points.length <= 5 * 10^4", + "rectangles[i].length == points[j].length == 2", + "1 <= l i , x j <= 10^9", + "1 <= h i , y j <= 100", + "All the rectangles are unique .", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\nOutput:[2,1]\nExplanation:The first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example1.png" + }, + { + "text": "Example 2: Input:rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\nOutput:[1,3]\nExplanation:The first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def binarySearch(self, arr, target):\n left, right = 0, len(arr)\n ans = None\n while left < right:\n mid = left + ((right-left)//2)\n if arr[mid] >= target:\n # Potential answer found! Now try to minimize it iff possible.\n ans = mid\n right = mid\n else:\n left = mid + 1\n return ans\n \n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n # Sort rectangles based on the lengths\n rectangles.sort() \n # Group rectangles by their height in increasing order of their length\n lengths = {}\n for x,y in rectangles:\n if y in lengths:\n lengths[y].append(x)\n else:\n lengths[y] = [x]\n \n heights = sorted(list(lengths.keys()))\n \n count = [0] * len(points)\n \n for idx, point in enumerate(points):\n x, y = point\n # Get the min height rectangle that would accommodate the y coordinate of current point.\n minHeightRectIdx = self.binarySearch(heights, y)\n if minHeightRectIdx is not None:\n for h in heights[minHeightRectIdx:]:\n # Get the Min length rectangle that would accommodate the x coordinate of current point for all h height rectangles.\n minLenRectIdx = self.binarySearch(lengths[h], x)\n if minLenRectIdx is not None:\n count[idx] += len(lengths[h]) - minLenRectIdx\n \n return count\n", + "title": "2250. Count Number of Rectangles Containing Each Point", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sequence is special if it consists of a positive number of 0 s, followed by a positive number of 1 s, then a positive number of 2 s. Given an array nums (consisting of only integers 0 , 1 , and 2 ), return the number of different subsequences that are special . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.", + "description_images": [], + "constraints": [ + "For example, [0,1,2] and [0,0,1,1,1,2] are special.", + "In contrast, [2,1,0] , [1] , and [0,1,2,0] are not special." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,2]\nOutput:3\nExplanation:The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,0,0]\nOutput:0\nExplanation:There are no special subsequences in [2,2,0,0].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,0,1,2]\nOutput:7\nExplanation:The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 33.85%) | Memory: 118.7 MB (Top 84.62%)\nclass Solution {\n public int countSpecialSubsequences(int[] nums) {\n long z = 0; //starting and ending with zero\n long zo = 0; //starting with zero and ending with One\n long zot = 0;//starting with zero and ending Two\n int mod = 1000000007;\n for (int i : nums) {\n if (i == 0) {\n z = ((2*z) % mod + 1) % mod; //zero = 2*zero+1\n } else if (i == 1) {\n zo = ((2 * zo) % mod + z % mod) % mod; //zero = 2*zeroOne+zero\n } else {\n zot = ((2 * zot) % mod + zo % mod) % mod; //zeroOneTwo = 2*zeroOneTwo+zeroOne\n }\n }\n return (int)(zot%mod);\n }\n}", + "title": "1955. Count Number of Special Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sequence is special if it consists of a positive number of 0 s, followed by a positive number of 1 s, then a positive number of 2 s. Given an array nums (consisting of only integers 0 , 1 , and 2 ), return the number of different subsequences that are special . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.", + "description_images": [], + "constraints": [ + "For example, [0,1,2] and [0,0,1,1,1,2] are special.", + "In contrast, [2,1,0] , [1] , and [0,1,2,0] are not special." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,2]\nOutput:3\nExplanation:The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,0,0]\nOutput:0\nExplanation:There are no special subsequences in [2,2,0,0].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,0,1,2]\nOutput:7\nExplanation:The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4322 ms (Top 46.43%) | Memory: 18 MB (Top 47.62%)\nclass Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n if not nums:\n return 0\n\n last_0 = 0\n last_1 = 0\n last_2 = 0\n\n for i in nums:\n if i == 0:\n last_0 = (2*last_0 + 1)% 1000000007\n elif i == 1:\n last_1 = (last_0 + 2*last_1) % 1000000007\n elif i == 2:\n last_2 = (last_1 + 2*last_2) % 1000000007\n return last_2 % 1000000007", + "title": "1955. Count Number of Special Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).", + "description_images": [], + "constraints": [ + "Choose 3 soldiers with index ( i , j , k ) with rating ( rating[i] , rating[j] , rating[k] ).", + "A team is valid if: ( rating[i] < rating[j] < rating[k] ) or ( rating[i] > rating[j] > rating[k] ) where ( 0 <= i < j < k < n )." + ], + "examples": [ + { + "text": "Example 1: Input:rating = [2,5,3,4,1]\nOutput:3\nExplanation:We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).", + "image": null + }, + { + "text": "Example 2: Input:rating = [2,1,3]\nOutput:0\nExplanation:We can't form any team given the conditions.", + "image": null + }, + { + "text": "Example 3: Input:rating = [1,2,3,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Smaller * Larger Solution\n// sum of #smaller * #larger\n// Time complexity: O(N^2)\n// Space complexity: O(1)\nclass Solution {\n public int numTeams(int[] rating) {\n final int N = rating.length;\n int res = 0;\n for (int i = 1; i < N; i++) {\n res += smaller(rating, i, -1) * larger(rating, i, 1);\n res += larger(rating, i, -1) * smaller(rating, i, 1);\n }\n return res;\n }\n \n private int smaller(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] < t) count++;\n i += diff;\n }\n return count;\n }\n \n private int larger(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] > t) count++;\n i += diff;\n }\n return count;\n }\n}\n", + "title": "1395. Count Number of Teams", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).", + "description_images": [], + "constraints": [ + "Choose 3 soldiers with index ( i , j , k ) with rating ( rating[i] , rating[j] , rating[k] ).", + "A team is valid if: ( rating[i] < rating[j] < rating[k] ) or ( rating[i] > rating[j] > rating[k] ) where ( 0 <= i < j < k < n )." + ], + "examples": [ + { + "text": "Example 1: Input:rating = [2,5,3,4,1]\nOutput:3\nExplanation:We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).", + "image": null + }, + { + "text": "Example 2: Input:rating = [2,1,3]\nOutput:0\nExplanation:We can't form any team given the conditions.", + "image": null + }, + { + "text": "Example 3: Input:rating = [1,2,3,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numTeams(self, ratings: List[int]) -> int:\n upper_dps = [0 for _ in range(len(ratings))]\n lower_dps = [0 for _ in range(len(ratings))]\n \n count = 0\n for i in range(len(ratings)):\n for j in range(i):\n if ratings[j] < ratings[i]:\n count += upper_dps[j]\n upper_dps[i] += 1\n else:\n count += lower_dps[j]\n lower_dps[i] += 1\n \n return count\n", + "title": "1395. Count Number of Teams", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, to add the letter 's' , Alice has to press '7' four times. Similarly, to add the letter 'k' , Alice has to press '5' twice.", + "Note that the digits '0' and '1' do not map to any letters, so Alice does not use them." + ], + "examples": [ + { + "text": "Example 1: Input:pressedKeys = \"22233\"\nOutput:8\nExplanation:The possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.", + "image": null + }, + { + "text": "Example 2: Input:pressedKeys = \"222222222222222222222222222222222222\"\nOutput:82876089\nExplanation:There are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109+ 7, we return 2082876103 % (109+ 7) = 82876089.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 90.12%) | Memory: 45.20 MB (Top 64.2%)\n\nclass Solution {\n int mod = (1000000007);\n\n public int countTexts(String pressedKeys) {\n int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 };\n int n = pressedKeys.length();\n int[] dp = new int[n + 1];\n dp[n] = 1;\n\n for (int ind = n - 1; ind >= 0; ind--) {\n int count = 0;\n int num = pressedKeys.charAt(ind) - '0';\n int rep = key[num];\n for (int i = 0; i < rep && ind + i < pressedKeys.length() && pressedKeys.charAt(ind) == pressedKeys.charAt(ind + i); i++) {\n count += dp[ind+i+1];\n count %= mod;\n }\n dp[ind] = count;\n }\n return dp[0];\n }\n}\n", + "title": "2266. Count Number of Texts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, to add the letter 's' , Alice has to press '7' four times. Similarly, to add the letter 'k' , Alice has to press '5' twice.", + "Note that the digits '0' and '1' do not map to any letters, so Alice does not use them." + ], + "examples": [ + { + "text": "Example 1: Input:pressedKeys = \"22233\"\nOutput:8\nExplanation:The possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.", + "image": null + }, + { + "text": "Example 2: Input:pressedKeys = \"222222222222222222222222222222222222\"\nOutput:82876089\nExplanation:There are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109+ 7, we return 2082876103 % (109+ 7) = 82876089.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2740 ms (Top 30.44%) | Memory: 19.5 MB (Top 65.22%)\nclass Solution(object):\n def countTexts(self, pressedKeys):\n \"\"\"\n :type pressedKeys: str\n :rtype: int\n \"\"\"\n dp = [1] + [0]*len(pressedKeys)\n mod = 10**9 + 7\n for i, n in enumerate(pressedKeys):\n dp[i+1] = dp[i]\n # check if is continous\n if i >= 1 and pressedKeys[i-1] == n:\n dp[i+1] += dp[i-1]\n dp[i+1] %= mod\n if i >= 2 and pressedKeys[i-2] == n:\n dp[i+1] += dp[i-2]\n dp[i+1] %= mod\n # Special case for '7' and '9' that can have 4 characters combination\n if i >= 3 and pressedKeys[i-3] == n and (n == \"7\" or n == \"9\"):\n dp[i+1] += dp[i-3]\n dp[i+1] %= mod\n return dp[-1]", + "title": "2266. Count Number of Texts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a street with n * 2 plots , where there are n plots on each side of the street. The plots on each side are numbered from 1 to n . On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street . Since the answer may be very large, return it modulo 10^9 + 7 . Note that if a house is placed on the i th plot on one side of the street, a house can also be placed on the i th plot on the other side of the street.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:4\nExplanation:Possible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:9\nExplanation:The 9 possible arrangements are shown in the diagram above.", + "image": "https://assets.leetcode.com/uploads/2022/05/12/arrangements.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod = (int)1e9+7;\n public int countHousePlacements(int n) {\n \n if(n == 1)\n return 4;\n if(n == 2)\n return 9;\n long a = 2;\n long b = 3;\n if(n==1)\n return (int)(a%mod);\n if(n==2)\n return (int)(b%mod);\n long c=0;\n for(int i=3;i<=n;i++)\n {\n c = (a+b)%mod;\n a=b%mod;\n b=c%mod;\n }\n \n return (int)((c*c)%mod);\n }\n}\n", + "title": "2320. Count Number of Ways to Place Houses", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a street with n * 2 plots , where there are n plots on each side of the street. The plots on each side are numbered from 1 to n . On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street . Since the answer may be very large, return it modulo 10^9 + 7 . Note that if a house is placed on the i th plot on one side of the street, a house can also be placed on the i th plot on the other side of the street.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:4\nExplanation:Possible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:9\nExplanation:The 9 possible arrangements are shown in the diagram above.", + "image": "https://assets.leetcode.com/uploads/2022/05/12/arrangements.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHousePlacements(self, n: int) -> int:\n \n \n @lru_cache(None)\n def rec(i, k):\n \n # i is the index of the house \n # k is the state of last house, 1 if there was a house on the last index else 0\n \n if i>=n:\n return 1\n \n elif k==0:\n return rec(i+1,1) + rec(i+1,0)\n \n else:\n return rec(i+1,0)\n \n \n \n #l1 are the combinations possible in lane 1, the final answer will be the square \n\t\t#of of l1 as for every combination of l1 there will be \"l1\" combinations in lane2.\n \n l1 = rec(1,0) + rec(1,1)\n \n \n mod = 10**9 +7\n return pow(l1, 2, mod) #use this when there is mod involved along with power \n \n", + "title": "2320. Count Number of Ways to Place Houses", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the count of all numbers with unique digits, x , where 0 <= x < 10 n .", + "description_images": [], + "constraints": [ + "0 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:91\nExplanation:The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.90 MB (Top 52.99%)\n\nclass Solution {\n public int countNumbersWithUniqueDigits(int n) \n {\n\t/*\n\t 9 * 9 + 10 for n = 2\n 9 * 9 * 8 + 10 for n = 3\n 9 * 9 * 8 * 7 + 10 for n = 4\n 9 * 9 * 8 * 7 * 6 + 10 for n = 5\n\t*/\t\n if(n == 0)\n return 1;\n \n if(n == 1)\n return 10;\n \n int product =9;\n int result = 10;\n \n for(int i=2; i<=n; i++)\n {\n product = product * (11-i);\n result += product;\n }\n \n return result;\n }\n}\n", + "title": "357. Count Numbers with Unique Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the count of all numbers with unique digits, x , where 0 <= x < 10 n .", + "description_images": [], + "constraints": [ + "0 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:91\nExplanation:The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n \n if n == 0:\n return 1\n \n table = [0]*(n+1)\n \n table[0] = 1\n table[1] = 9\n \n for i in range(2, n+1):\n table[i] = table[i-1]*(11-i)\n \n return sum(table)\n", + "title": "357. Count Numbers with Unique Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two non-negative integers low and high . Return the count of odd numbers between low and high (inclusive) .", + "description_images": [], + "constraints": [ + "0 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 3, high = 7\nOutput:3\nExplanation:The odd numbers between 3 and 7 are [3,5,7].", + "image": null + }, + { + "text": "Example 2: Input:low = 8, high = 10\nOutput:1\nExplanation:The odd numbers between 8 and 10 are [9].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 5.10%)\nclass Solution {\n public int countOdds(int low, int high) {\n if(low%2==0 && high%2==0){\n return (high-low)/2;\n }\n return (high-low)/2+1;\n }\n}", + "title": "1523. Count Odd Numbers in an Interval Range", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two non-negative integers low and high . Return the count of odd numbers between low and high (inclusive) .", + "description_images": [], + "constraints": [ + "0 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 3, high = 7\nOutput:3\nExplanation:The odd numbers between 3 and 7 are [3,5,7].", + "image": null + }, + { + "text": "Example 2: Input:low = 8, high = 10\nOutput:1\nExplanation:The odd numbers between 8 and 10 are [9].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countOdds(self, low: int, high: int) -> int: \n total_nums = high - low\n \n answer = total_nums // 2\n \n if low % 2 == 1 and high % 2 == 1:\n return answer + 1\n \n if low % 2 == 1:\n answer = answer + 1\n \n if high % 2 == 1:\n answer = answer + 1\n \n return answer\n", + "title": "1523. Count Odd Numbers in an Interval Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer n , the number of teams in a tournament that has strange rules: Return the number of matches played in the tournament until a winner is decided.", + "description_images": [], + "constraints": [ + "If the current number of teams is even , each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.", + "If the current number of teams is odd , one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:6\nExplanation:Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.", + "image": null + }, + { + "text": "Example 2: Input:n = 14\nOutput:13\nExplanation:Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfMatches(int n) {\n\t\t// This is the problem's base case; we know that if n == 1,\n\t\t// the number of matches played must be 0, since the last team left\n\t\t// can't play a match against themselves.\n if (n == 1) return 0;\n \n\t\t// We declare an int to hold our recursive solution.\n int res;\n\t\t\n\t\t// We initialize res using a recursive call, reducing n \n\t\t// as described in the problem.\n if (n % 2 == 0) {\n res = numberOfMatches(n / 2);\n\t\t\t// After the recursive call is executed, we add the appropriate value to \n\t\t\t// our solution variable.\n res += n / 2;\n }\n else {\n res = numberOfMatches((n - 1) / 2 + 1);\n res += (n - 1) / 2;\n }\n \n\t\t// Our initial call to numberOfMatches()\n\t\t// will return the total number of matches \n\t\t// added to res in each recursive call.\n return res;\n }\n}\n", + "title": "1688. Count of Matches in Tournament", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n , the number of teams in a tournament that has strange rules: Return the number of matches played in the tournament until a winner is decided.", + "description_images": [], + "constraints": [ + "If the current number of teams is even , each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.", + "If the current number of teams is odd , one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:6\nExplanation:Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.", + "image": null + }, + { + "text": "Example 2: Input:n = 14\nOutput:13\nExplanation:Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef numberOfMatches(self, n: int) -> int:\n\t\treturn n - 1", + "title": "1688. Count of Matches in Tournament", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and two integers lower and upper , return the number of range sums that lie in [lower, upper] inclusive . Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "-10^5 <= lower <= upper <= 10^5", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,5,-1], lower = -2, upper = 2\nOutput:3\nExplanation:The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0], lower = 0, upper = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 26.64%) | Memory: 76.2 MB (Top 86.68%)\nclass Solution {\n public int countRangeSum(int[] nums, int lower, int upper) {\n int n = nums.length, ans = 0;\n long[] pre = new long[n+1];\n for (int i = 0; i < n; i++){\n pre[i+1] = nums[i] + pre[i];\n }\n Arrays.sort(pre);\n int[] bit = new int[pre.length+2];\n long sum = 0;\n for (int i = 0; i < n; i++){\n update(bit, bs(sum, pre), 1);\n sum += nums[i];\n ans += sum(bit, bs(sum-lower, pre)) - sum(bit, bs(sum-upper-1, pre));\n }\n return ans;\n }\n\n private int bs(long sum, long[] pre){ // return the index of first number bigger than sum\n int lo = 0, hi = pre.length;\n while(lo < hi){\n int mid = (lo+hi) >> 1;\n if (pre[mid]>sum){\n hi=mid;\n }else{\n lo=mid+1;\n }\n }\n return lo;\n }\n\n private void update(int[] bit, int idx, int inc){\n for (++idx; idx < bit.length; idx += idx & -idx){\n bit[idx] += inc;\n }\n }\n\n private int sum(int[] bit, int idx){\n int ans = 0;\n for (++idx; idx > 0; idx -= idx & -idx){\n ans += bit[idx];\n }\n return ans;\n }\n}", + "title": "327. Count of Range Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and two integers lower and upper , return the number of range sums that lie in [lower, upper] inclusive . Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "-10^5 <= lower <= upper <= 10^5", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,5,-1], lower = -2, upper = 2\nOutput:3\nExplanation:The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0], lower = 0, upper = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n acc = list(accumulate(nums))\n ans = a = 0\n for n in nums:\n a += n\n ans += sum(1 for x in acc if lower <= x <= upper)\n acc.pop(0)\n lower += n\n upper += n\n return ans\n", + "title": "327. Count of Range Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,6,1]\nOutput:[2,1,1,0]\nExplanation:To the right of 5 there are2smaller elements (2 and 1).\nTo the right of 2 there is only1smaller element (1).\nTo the right of 6 there is1smaller element (1).\nTo the right of 1 there is0smaller element.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-1]\nOutput:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 97.6%) | Memory: 57.69 MB (Top 69.7%)\n\nclass Solution { \n public List countSmaller(int[] nums) {\n int min = 20001;\n int max = -1;\n for (int num : nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n \n min--;\n int[] count = new int[max-min+1];\n Integer[] result = new Integer[nums.length];\n for (int i = nums.length-1; i >=0; i--) {\n int k = nums[i]-min-1;\n int c = 0;\n do {\n c += count[k];\n k -= (-k&k);\n } while (k > 0);\n result[i] = c;\n \n k = nums[i]-min;\n while (k < count.length) {\n count[k]++;\n k += (-k&k);\n }\n }\n \n return Arrays.asList(result);\n }\n}", + "title": "315. Count of Smaller Numbers After Self", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,6,1]\nOutput:[2,1,1,0]\nExplanation:To the right of 5 there are2smaller elements (2 and 1).\nTo the right of 2 there is only1smaller element (1).\nTo the right of 6 there is1smaller element (1).\nTo the right of 1 there is0smaller element.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-1]\nOutput:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6019 ms (Top 15.52%) | Memory: 35.5 MB (Top 33.31%)\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n # build the binary indexed tree\n num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0\n tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1\n\n result = [0] * len(nums)\n\n # iterate from right to left\n for result_index in range(len(nums) - 1, -1, -1):\n n = nums[result_index]\n # add 10**4 to n to account for negative numbers\n i = n + 10 ** 4\n\n # convert to 1-based index for the tree\n i += 1\n # perform range sum query of buckets [-inf, n-1], where n is current number\n # because we want n - 1 for range sum query of [-inf, n-1], not n, subtract 1 from i:\n i -= 1\n\n val = 0\n while i != 0:\n val += tree[i]\n # get parent node by subtracting least significant set bit\n i -= i & -i\n\n result[result_index] = val\n\n # update the binary indexed tree with new bucket\n i = n + 10 ** 4\n i += 1\n while i < len(tree):\n tree[i] += 1\n # get next node to update by adding the least significant set bit\n i += i & -i\n\n return result", + "title": "315. Count of Smaller Numbers After Self", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two non-negative integers num1 and num2 . In one operation , if num1 >= num2 , you must subtract num2 from num1 , otherwise subtract num1 from num2 . Return the number of operations required to make either num1 = 0 or num2 = 0 .", + "description_images": [], + "constraints": [ + "For example, if num1 = 5 and num2 = 4 , subtract num2 from num1 , thus obtaining num1 = 1 and num2 = 4 . However, if num1 = 4 and num2 = 5 , after one operation, num1 = 4 and num2 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 2, num2 = 3\nOutput:3\nExplanation:- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.", + "image": null + }, + { + "text": "Example 2: Input:num1 = 10, num2 = 10\nOutput:1\nExplanation:- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 69.19%)\nclass Solution {\n public int countOperations(int num1, int num2) {\n int count=0;\n while(num1!=0 && num2!=0){\n if(num1= num2 , you must subtract num2 from num1 , otherwise subtract num1 from num2 . Return the number of operations required to make either num1 = 0 or num2 = 0 .", + "description_images": [], + "constraints": [ + "For example, if num1 = 5 and num2 = 4 , subtract num2 from num1 , thus obtaining num1 = 1 and num2 = 4 . However, if num1 = 4 and num2 = 5 , after one operation, num1 = 4 and num2 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 2, num2 = 3\nOutput:3\nExplanation:- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.", + "image": null + }, + { + "text": "Example 2: Input:num1 = 10, num2 = 10\nOutput:1\nExplanation:- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 87.66%) | Memory: 17.40 MB (Top 8.01%)\n\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n count = 0\n while num1 != 0 and num2 != 0:\n if num1 >= num2:\n num1 -= num2\n else:\n num2 -= num1\n count +=1\n return count\n", + "title": "2169. Count Operations to Obtain Zero", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an undirected graph defined by an integer n , the number of nodes, and a 2D integer array edges , the edges in the graph, where edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . You are also given an integer array queries . Let incident(a, b) be defined as the number of edges that are connected to either node a or b . The answer to the j th query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: Return an array answers such that answers.length == queries.length and answers[j] is the answer of the j th query . Note that there can be multiple edges between the same two nodes.", + "description_images": [], + "constraints": [ + "a < b", + "incident(a, b) > queries[j]" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput:[6,5]\nExplanation:The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/winword_2021-06-08_00-58-39.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput:[10,10,9,8,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 80.0%) | Memory: 92.30 MB (Top 62.86%)\n\nclass Solution {\n // Time : O(E + N + Q)\n // Space : O(N + E)\n public int[] countPairs(int n, int[][] edges, int[] queries) {\n // Key: edge ID Value: count of duplicate edge\n Map edgeCount = new HashMap<>();\n // degree[i] : number of edge for node i (0-indexed)\n int[] degree = new int[n];\n \n for (int[] e : edges) { // recording all edges ==> O(E) Time / Space\n int u = e[0] - 1;\n int v = e[1] - 1;\n degree[u]++;\n degree[v]++;\n \n int eId = Math.min(u, v) * n + Math.max(u, v);\n edgeCount.put(eId, edgeCount.getOrDefault(eId, 0) + 1);\n }\n \n // Key: Degree Value: Frequency (number of nodes with that degree)\n Map degreeCount = new HashMap<>(); // ==> O(U) Time / Space\n int maxDegree = 0;\n for (int d : degree) {\n degreeCount.put(d, degreeCount.getOrDefault(d, 0) + 1);\n maxDegree = Math.max(maxDegree, d);\n }\n \n \n int[] count = new int[2 * maxDegree + 1]; \n \n for (int d1 : degreeCount.keySet()) { // O(E)-time (seems to be O(U ^ 2))\n for (int d2 : degreeCount.keySet()) {\n count[d1 + d2] += (d1 == d2) ? degreeCount.get(d1) * (degreeCount.get(d1)- 1) \n : degreeCount.get(d1) * degreeCount.get(d2);\n }\n }\n for (int i = 0; i < count.length; i++) count[i] /= 2; // each pair is counted twice\n \n \n for (int e : edgeCount.keySet()) { // O(E)-time\n int u = e / n;\n int v = e % n; \n \n count[degree[u] + degree[v]]--;\n count[degree[u] + degree[v] - edgeCount.get(e)]++;\n }\n \n for (int i = count.length - 2; i >= 0; i--) { // O(U)-time \n count[i] += count[i+1];\n }\n \n \n int[] res = new int[queries.length]; // O(Q)-time\n for (int q = 0; q < queries.length; q++) {\n res[q] = ((queries[q] + 1) >= count.length) ? 0 : count[queries[q] + 1];\n }\n return res;\n }\n}\n", + "title": "1782. Count Pairs Of Nodes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an undirected graph defined by an integer n , the number of nodes, and a 2D integer array edges , the edges in the graph, where edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . You are also given an integer array queries . Let incident(a, b) be defined as the number of edges that are connected to either node a or b . The answer to the j th query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: Return an array answers such that answers.length == queries.length and answers[j] is the answer of the j th query . Note that there can be multiple edges between the same two nodes.", + "description_images": [], + "constraints": [ + "a < b", + "incident(a, b) > queries[j]" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput:[6,5]\nExplanation:The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/winword_2021-06-08_00-58-39.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput:[10,10,9,8,6]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n p_c = [0] * (n+1) # point counter\n e_c = defaultdict(int) # edge counter\n \n for a,b in edges:\n p_c[a] += 1\n p_c[b] += 1\n if a=0;i--){\n // count all the element whose xor is less the low\n int cnt1=trie.maxXor(nums[i],low);\n // count all the element whose xor is less the high+1\n int cnt2=trie.maxXor(nums[i],high+1);\n trie.add(nums[i]);\n cnt+=cnt2-cnt1;\n }\n return cnt;\n }\n}\nclass Trie{\n private Node root;\n Trie(){\n root=new Node();\n }\n public void add(int x){\n Node cur=root;\n for(int i=31;i>=0;i--){\n int bit=(x>>i)&1;\n if(!cur.contains(bit)){\n cur.put(bit);\n }\n cur.inc(bit);\n cur=cur.get(bit);\n }\n }\n public int maxXor(int x,int limit){\n int low_cnt=0;\n Node cur=root;\n for(int i=31;i>=0 && cur!=null;i--){\n int bit=(x>>i)&(1);\n int req=(limit>>i)&1;\n if(req==1){\n if(cur.contains(bit)){\n low_cnt+=cur.get(bit).cnt;\n }\n cur=cur.get(1-bit);\n }else{\n cur=cur.get(bit);\n }\n\n }\n return low_cnt;\n\n }\n}\nclass Node{\n private Node links[];\n int cnt;\n Node(){\n links=new Node[2];\n cnt=0;\n }\n public void put(int bit){\n links[bit]=new Node();\n }\n public Node get(int bit){\n return links[bit];\n }\n public boolean contains(int bit){\n return links[bit]!=null;\n }\n public void inc(int bit){\n links[bit].cnt++;\n }\n}", + "title": "1803. Count Pairs With XOR in a Range", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a (0-indexed) integer array nums and two integers low and high , return the number of nice pairs . A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] <= 2 * 10^4", + "1 <= low <= high <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,2,7], low = 2, high = 6\nOutput:6\nExplanation:All nice pairs (i, j) are as follows:\n - (0, 1): nums[0] XOR nums[1] = 5 \n - (0, 2): nums[0] XOR nums[2] = 3\n - (0, 3): nums[0] XOR nums[3] = 6\n - (1, 2): nums[1] XOR nums[2] = 6\n - (1, 3): nums[1] XOR nums[3] = 3\n - (2, 3): nums[2] XOR nums[3] = 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,4,2,1], low = 5, high = 14\nOutput:8\nExplanation:All nice pairs (i, j) are as follows:\n​​​​​ - (0, 2): nums[0] XOR nums[2] = 13\n  - (0, 3): nums[0] XOR nums[3] = 11\n  - (0, 4): nums[0] XOR nums[4] = 8\n  - (1, 2): nums[1] XOR nums[2] = 12\n  - (1, 3): nums[1] XOR nums[3] = 10\n  - (1, 4): nums[1] XOR nums[4] = 9\n  - (2, 3): nums[2] XOR nums[3] = 6\n  - (2, 4): nums[2] XOR nums[4] = 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1588 ms (Top 85.61%) | Memory: 20.60 MB (Top 80.3%)\n\nclass Solution:\n def countPairs(self, nums, low, high):\n return self._countPairs(nums, high + 1) - self._countPairs(nums, low)\n \n def _countPairs(self, nums, high):\n res = 0\n for k in range(31, -1, -1):\n target = high >> k\n if target & 1 == 0:\n continue\n target -= 1\n counter = Counter(num >> k for num in nums)\n for mask in counter:\n res += counter[mask] * counter[target ^ mask]\n if mask == target ^ mask:\n res -= counter[mask]\n return res // 2\n", + "title": "1803. Count Pairs With XOR in a Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string array words and a string s , where words[i] and s comprise only of lowercase English letters . Return the number of strings in words that are a prefix of s . A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, s.length <= 10", + "words[i] and s consist of lowercase English letters only ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\nOutput:3\nExplanation:The strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"a\"], s = \"aa\"\nOutput:2\nExplanation:Both of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPrefixes(String[] words, String s) {\n int i = 0;\n int j = 0;\n int count = 0;\n for(int k = 0; k < words.length; k++){\n if(words[k].length() > s.length()){\n continue;\n }\n \n while(i < words[k].length() && words[k].charAt(i) == s.charAt(j)){\n i++;\n j++;\n }\n if(i == words[k].length()){\n count++;\n }\n i = 0;\n j = 0;\n }\n return count;\n }\n}\n", + "title": "2255. Count Prefixes of a Given String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string array words and a string s , where words[i] and s comprise only of lowercase English letters . Return the number of strings in words that are a prefix of s . A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, s.length <= 10", + "words[i] and s consist of lowercase English letters only ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\nOutput:3\nExplanation:The strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"a\"], s = \"aa\"\nOutput:2\nExplanation:Both of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 25.9%) | Memory: 16.47 MB (Top 86.6%)\n\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n return len([i for i in words if s.startswith(i)])", + "title": "2255. Count Prefixes of a Given String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of prime numbers that are strictly less than n .", + "description_images": [], + "constraints": [ + "0 <= n <= 5 * 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:4\nExplanation:There are 4 prime numbers less than 10, they are 2, 3, 5, 7.", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPrimes(int n) {\n boolean check[]=new boolean[n];int count=0;\n for(int i=2;i int:\n # Prerequisite:\n # What is prime number. What are they just the starting. \n \n truth = [True]*n # making a list of lenght n. And keep all the values as True.\n if n<2: # as 0 & 1 are not prime numbers. \n return 0\n truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.\n \n i=2 # As we know 0 & 1 are not prime.\n while i*i0){\n count++;\n }\n }\n return count;\n }\n public void check(int sr,int sc,int [][]grid){\n int mbox=sr*grid[0].length+sc;\n for(int i=sr;irank[y]){\n parent[y]=x;\n }else if(rank[y]>rank[x]){\n parent[x]=y;\n }else{\n parent[x]=y;\n rank[y]++;\n }\n }\n}", + "title": "1267. Count Servers that Communicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a map of a server center, represented as a m * n integer matrix grid , where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-6.jpg", + "https://assets.leetcode.com/uploads/2019/11/13/untitled-diagram-4.jpg", + "https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-1-3.jpg" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m <= 250", + "1 <= n <= 250", + "grid[i][j] == 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]\nOutput:0\nExplanation:No servers can communicate with others.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0],[1,1]]\nOutput:3\nExplanation:All three servers can communicate with at least one other server.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput:4\nExplanation:The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n def helper(row,col,count):\n for c in range(len(grid[0])):\n if c == col:\n continue\n if grid[row][c] == 1:\n count += 1\n return count\n for r in range(len(grid)):\n if r == row:\n continue\n if grid[r][col] == 1:\n count += 1\n return count\n return count\n count = 0\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 1:\n count = helper(row,col,count)\n return count\n", + "title": "1267. Count Servers that Communicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of strings of length n that consist only of vowels ( a , e , i , o , u ) and are lexicographically sorted . A string s is lexicographically sorted if for all valid i , s[i] is the same as or comes before s[i+1] in the alphabet.", + "description_images": [], + "constraints": [ + "1 <= n <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:5\nExplanation:The 5 sorted strings that consist of vowels only are[\"a\",\"e\",\"i\",\"o\",\"u\"].", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:15\nExplanation:The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.", + "image": null + }, + { + "text": "Example 3: Input:n = 33\nOutput:66045", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.04 MB (Top 74.4%)\n\nclass Solution {\n public int countVowelStrings(int n) {\n int a=1,e=1,i=1,o=1,u=1;\n for(int k=1;k int:\n dp = [[0] * 6 for _ in range(n+1)]\n for i in range(1, 6):\n dp[1][i] = i\n\n for i in range(2, n+1):\n dp[i][1]=1\n for j in range(2, 6):\n dp[i][j] = dp[i][j-1] + dp[i-1][j]\n\n return dp[n][5]", + "title": "1641. Count Sorted Vowel Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums , return the number of distinct quadruplets (a, b, c, d) such that:", + "description_images": [], + "constraints": [ + "nums[a] + nums[b] + nums[c] == nums[d] , and", + "a < b < c < d" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,6]\nOutput:1\nExplanation:The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,4,5]\nOutput:0\nExplanation:There are no such quadruplets in [3,3,6,4,5].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,5]\nOutput:4\nExplanation:The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countQuadruplets(int[] nums) {\n int res = 0;\n int len = nums.length;\n \n Map count = new HashMap<>();\n count.put(nums[len-1] - nums[len-2], 1);\n \n for (int b = len - 3; b >= 1; b--) {\n for (int a = b - 1; a >= 0; a--) {\n res += count.getOrDefault(nums[a] + nums[b], 0);\n }\n \n for (int x = len - 1; x > b; x--) {\n count.put(nums[x] - nums[b], count.getOrDefault(nums[x] - nums[b], 0) + 1);\n }\n }\n \n return res;\n }\n}\n", + "title": "1995. Count Special Quadruplets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a 0-indexed integer array nums , return the number of distinct quadruplets (a, b, c, d) such that:", + "description_images": [], + "constraints": [ + "nums[a] + nums[b] + nums[c] == nums[d] , and", + "a < b < c < d" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,6]\nOutput:1\nExplanation:The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,4,5]\nOutput:0\nExplanation:There are no such quadruplets in [3,3,6,4,5].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,5]\nOutput:4\nExplanation:The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 640 ms (Top 64.4%) | Memory: 17.10 MB (Top 9.2%)\n\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n return sum([1 for a, b, c, d in combinations(nums, 4) if a + b + c == d])", + "title": "1995. Count Special Quadruplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 300", + "1 <= arr[0].length <= 300", + "0 <= arr[i][j] <= 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix =\n[\n  [0,1,1,1],\n  [1,1,1,1],\n  [0,1,1,1]\n]\nOutput:15\nExplanation:There are10squares of side 1.\nThere are4squares of side 2.\nThere is1square of side 3.\nTotal number of squares = 10 + 4 + 1 =15.", + "image": null + }, + { + "text": "Example 2: Input:matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]\nOutput:7\nExplanation:There are6squares of side 1. \nThere is1square of side 2. \nTotal number of squares = 6 + 1 =7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 97.02%) | Memory: 55.30 MB (Top 24.22%)\n\nclass Solution \n{\n public int countSquares(int[][] matrix)\n {\n int n=matrix.length;\n int m=matrix[0].length;\n int dp[][]=new int[n][m];\n for(int i=0;i int:\n\n m = len(matrix)\n n = len(matrix[0])\n\n dp = [[0 for _ in range(n)] for _ in range(m)]\n total = 0\n\n for i in range(m):\n for j in range(n):\n\n if i == 0:\n dp[i][j] = matrix[0][j]\n\n elif j == 0:\n dp[i][j] = matrix[i][0]\n\n else:\n if matrix[i][j] == 1:\n dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j])\n\n total += dp[i][j]\n\n return total", + "title": "1277. Count Square Submatrices with All Ones", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A square triple (a,b,c) is a triple where a , b , and c are integers and a 2 + b 2 = c 2 . Given an integer n , return the number of square triples such that 1 <= a, b, c <= n .", + "description_images": [], + "constraints": [ + "1 <= n <= 250" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation: The square triples are (3,4,5) and (4,3,5).", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countTriples(int n) {\n int c = 0;\n for(int i=1 ; i<=n ; i++){\n for(int j=i+1 ; j<=n ; j++){\n int sq = ( i * i) + ( j * j);\n int r = (int) Math.sqrt(sq);\n if( r*r == sq && r <= n )\n c += 2;\n }\n }\n return c;\n }\n}\n", + "title": "1925. Count Square Sum Triples", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A square triple (a,b,c) is a triple where a , b , and c are integers and a 2 + b 2 = c 2 . Given an integer n , return the number of square triples such that 1 <= a, b, c <= n .", + "description_images": [], + "constraints": [ + "1 <= n <= 250" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:2\nExplanation: The square triples are (3,4,5) and (4,3,5).", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countTriples(self, n: int) -> int:\n c = 0\n for i in range(1, n+1):\n for j in range(i+1, n+1):\n sq = i*i + j*j\n r = int(sq ** 0.5)\n if ( r*r == sq and r <= n ):\n c +=2\n return c\n", + "title": "1925. Count Square Sum Triples", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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]]\nOutput:3\nExplanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/10/test1.png" + }, + { + "text": "Example 2: 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]]\nOutput:2\nExplanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 10.84%) | Memory: 133.6 MB (Top 38.64%)\nclass Solution {\n public int countSubIslands(int[][] grid1, int[][] grid2) {\n int m = grid1.length;\n int n = grid1[0].length;\n boolean[][] vis = new boolean[m][n];\n int count = 0;\n int[] dir = {1, 0, -1, 0, 1};\n\n for(int i = 0; i < m; ++i) {\n for(int j = 0; j < n; ++j) {\n if(grid2[i][j] == 0 || vis[i][j])\n continue;\n\n Queue queue = new LinkedList<>();\n boolean flag = true;\n vis[i][j] = true;\n\n queue.add(new int[] {i, j});\n\n while(!queue.isEmpty()) {\n int[] vtx = queue.remove();\n\n if(grid1[vtx[0]][vtx[1]] == 0)\n flag = false;\n\n for(int k = 0; k < 4; ++k) {\n int x = vtx[0] + dir[k];\n int y = vtx[1] + dir[k + 1];\n\n if(x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && !vis[x][y]) {\n vis[x][y] = true;\n\n queue.add(new int[] {x, y});\n }\n }\n }\n\n if(flag)\n ++count;\n }\n }\n\n return count;\n }\n}", + "title": "1905. Count Sub Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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]]\nOutput:3\nExplanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/10/test1.png" + }, + { + "text": "Example 2: 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]]\nOutput:2\nExplanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countSubIslands(self, grid1, grid2):\n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n return \n grid2[i][j]=0\n dfs(i+1,j)\n dfs(i-1,j)\n dfs(i,j+1)\n dfs(i,j-1)\n # here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed \n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1 and grid1[i][j]==0:\n dfs(i,j)\n\t\t#now we just need to count the islands left over \t\t\t\n count=0\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1:\n \n dfs(i,j)\n count+=1\n return count \n\t\t", + "title": "1905. Count Sub Islands", + "topic": "Graph" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The score of an array is defined as the product of its sum and its length. Given a positive integer array nums and an integer k , return the number of non-empty subarrays of nums whose score is strictly less than k . A subarray is a contiguous sequence of elements within an array.", + "description_images": [], + "constraints": [ + "For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3,5], k = 10\nOutput:6\nExplanation:The 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 5\nOutput:5\nExplanation:Every subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.0%) | Memory: 61.40 MB (Top 26.22%)\n\nclass Solution {\n public long countSubarrays(int[] nums, long k) {\n int i=0;\n int j=0;\n long max = 0;\n long operation = 0;\n\n while(j < nums.length){\n operation += nums[j];\n while(operation*(j-i+1) >= k){\n operation -= nums[i];\n i++;\n }\n max += j-i+1;\n j++;\n }\n return max;\n\n }\n}\n", + "title": "2302. Count Subarrays With Score Less Than K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The score of an array is defined as the product of its sum and its length. Given a positive integer array nums and an integer k , return the number of non-empty subarrays of nums whose score is strictly less than k . A subarray is a contiguous sequence of elements within an array.", + "description_images": [], + "constraints": [ + "For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3,5], k = 10\nOutput:6\nExplanation:The 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 5\nOutput:5\nExplanation:Every subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1779 ms (Top 5.03%) | Memory: 31.30 MB (Top 6.6%)\n\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n sum, res, j = 0, 0, 0\n for i, n in enumerate(nums):\n sum += n\n while sum * (i - j + 1) >= k:\n sum -= nums[j]\n j += 1\n res += i - j + 1\n return res\n", + "title": "2302. Count Subarrays With Score Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the number of submatrices that have all ones .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 150", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput:13\nExplanation:There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput:24\nExplanation:There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 78.37%) | Memory: 45.40 MB (Top 34.13%)\n\nclass Solution {\n private int n;\n private int res = 0;\n \n public int numSubmat(int[][] mat) {\n this.n = mat[0].length;\n \n // dp[j] : the height (number of consecutive '1's) of column j \n int[] dp = new int[n];\n for (int i = 0; i < mat.length; i++) {\n // calculating (updating) heights\n for (int j = 0; j < n; j++) {\n dp[j] = mat[i][j] == 1 ? dp[j] + 1 : 0;\n }\n enumerateRowByMinHeight(dp);\n }\n return res;\n }\n\n public void enumerateRowByMinHeight(int[] dp) {\n // monotonic stack storing indices : for index p < q in stack, dp[p] < dp[q]\n Deque stack = new LinkedList<>();\n stack.offerLast(-1);\n\n for (int j = 0; j < n; j++) {\n while (stack.peekLast() != -1 && dp[stack.peekLast()] >= dp[j]) {\n int idx = stack.pollLast();\n res += dp[idx] * (idx - stack.peekLast()) * (j - idx);\n }\n stack.offerLast(j);\n }\n while (stack.peekLast() != -1) {\n int idx = stack.pollLast();\n res += dp[idx] * (idx - stack.peekLast()) * (n - idx);\n }\n }\n}\n", + "title": "1504. Count Submatrices With All Ones", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an m x n binary matrix mat , return the number of submatrices that have all ones .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 150", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput:13\nExplanation:There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput:24\nExplanation:There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n from dataclasses import dataclass\n @dataclass\n class Cell:\n left: int = 0\n top: int = 0\n \n n = len(mat)\n m = len(mat[0]) \n dp = [[Cell() for _ in range(m + 1)] for _ in range(n + 1)]\n \n ans = 0\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n if mat[i - 1][j - 1]: \n dp[i][j].top = 1 + dp[i - 1][j].top\n dp[i][j].left = 1 + dp[i][j - 1].left\n \n min_height = dp[i][j].top\n for k in range(dp[i][j].left):\n min_height = min(min_height, dp[i][j-k].top)\n ans += min_height \n return ans\n", + "title": "1504. Count Submatrices With All Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t . In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \" compute r\" and \" computa tion\" only differ by the 'e' / 'a' , so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 100", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\", t = \"baba\"\nOutput:6\nExplanation:The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", t = \"bb\"\nOutput:3\nExplanation:The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.", + "image": null + } + ], + "follow_up": null, + "solution": "// version 1 : O(mn) space\nclass Solution {\n public int countSubstrings(String s, String t) {\n int m = s.length(), n = t.length();\n\n int[][][] dp = new int[m][n][2];\n \n int res = 0;\n // first col s[0:i] match t[0:0]\n for (int i = 0; i < m; i++) {\n dp[i][0][0] = (s.charAt(i) == t.charAt(0)) ? 1 : 0;\n dp[i][0][1] = (s.charAt(i) == t.charAt(0)) ? 0 : 1;\n res += dp[i][0][1];\n }\n \n \n // first row s[0:0] match t[0:j]\n for (int j = 1; j < n; j++) {\n dp[0][j][0] = (s.charAt(0) == t.charAt(j)) ? 1 : 0;\n dp[0][j][1] = (s.charAt(0) == t.charAt(j)) ? 0 : 1;\n res += dp[0][j][1];\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j][0] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][0] + 1 : 0;\n dp[i][j][1] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][1] : dp[i-1][j-1][0] + 1;\n res += dp[i][j][1];\n }\n }\n\n return res;\n }\n}\n", + "title": "1638. Count Substrings That Differ by One Character", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s and t , find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t . In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \" compute r\" and \" computa tion\" only differ by the 'e' / 'a' , so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 100", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\", t = \"baba\"\nOutput:6\nExplanation:The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", t = \"bb\"\nOutput:3\nExplanation:The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n res = 0\n for i in range(len(s)):\n for j in range(len(t)):\n miss, pos = 0, 0\n while i + pos < len(s) and j + pos < len(t) and miss < 2:\n miss += s[i + pos] != t[j + pos]\n res += miss == 1\n pos += 1\n return res\n", + "title": "1638. Count Substrings That Differ by One Character", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n cities numbered from 1 to n . You are given an array edges of size n-1 , where edges[i] = [u i , v i ] represents a bidirectional edge between cities u i and v i . There exists a unique path between each pair of cities. In other words, the cities form a tree . A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1 , find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d . Return an array of size n-1 where the d th element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d . Notice that the distance between the two cities is the number of edges in the path between them.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/p1.png" + ], + "constraints": [ + "2 <= n <= 15", + "edges.length == n-1", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "All pairs (u i , v i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,3],[2,4]]\nOutput:[3,4,0]\nExplanation:The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\nNo subtree has two nodes where the max distance between them is 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]]\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[1,2],[2,3]]\nOutput:[2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 232 ms (Top 14.5%) | Memory: 44.30 MB (Top 38.1%)\n\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n \n ArrayList[] graph = (ArrayList[]) new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(int i=0;i0)\n {\n darr[d-1]++;\n }\n }\n \n return darr;\n \n }\n \n int getmax(int mask , ArrayList[] graph)\n {\n \n int maxd = -1;\n \n for(int i=0;i<15;i++)\n { \n if( (mask & (1<[] graph , int mask)\n {\n \n \n Queue q\n = new LinkedList<>();\n q.add(node);\n int dist = -1;\n int curr = mask;\n \n while(!q.isEmpty())\n {\n dist++;\n \n for(int l=q.size()-1;l>=0;l--) { \n int z1 = q.peek();\n curr = curr ^ (1< List[int]:\n def floydwarshall(n, edges):\n D = [[float('inf')]*n for _ in range(n)]\n for u, v in edges:\n D[u-1][v-1] = 1\n D[v-1][u-1] = 1\n for v in range(n):\n D[v][v] = 0\n for k in range(n):\n for i in range(n):\n for j in range(n):\n D[i][j] = min(D[i][j],D[i][k]+D[k][j])\n return D\n\n G = defaultdict(list)\n for v, w in edges:\n G[v-1].append(w-1)\n G[w-1].append(v-1)\n\n def dfs(G, v, V, visited):\n if v in visited: return\n visited.add(v)\n for w in G[v]:\n if w in V:\n dfs(G, w, V, visited)\n\n def check_connected(G, V):\n if not V: return False\n root = next(iter(V))\n visited = set()\n dfs(G, root, V, visited)\n return visited == V\n\n def max_distance(D, V):\n res = 0\n for v in V:\n for w in V:\n res = max(res, D[v][w])\n return res\n\n def solve(include, idx, ans, G, D):\n if idx == n:\n V = set(v for v in range(n) if include[v])\n if check_connected(G, V):\n d = max_distance(D, V)\n if d >= 1:\n ans[d-1] += 1\n else:\n solve(include, idx+1, ans, G, D)\n include[idx] = True\n solve(include, idx+1, ans, G, D)\n include[idx] = False\n\n D = floydwarshall(n, edges)\n include = [False] * n\n ans = [0]*(n-1)\n solve(include, 0, ans, G, D)\n return ans\n", + "title": "1617. Count Subtrees With Max Distance Between Cities", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of n integers differences , which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1) . More formally, call the hidden sequence hidden , then we have that differences[i] = hidden[i + 1] - hidden[i] . You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0 .", + "description_images": [], + "constraints": [ + "For example, given differences = [1, -3, 4] , lower = 1 , upper = 6 , the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 ( inclusive ). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6 . [1, 2, 3, 4] is not possible since the differences are not correct.", + "[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.", + "[5, 6, 3, 7] is not possible since it contains an element greater than 6 .", + "[1, 2, 3, 4] is not possible since the differences are not correct." + ], + "examples": [ + { + "text": "Example 1: Input:differences = [1,-3,4], lower = 1, upper = 6\nOutput:2\nExplanation:The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:differences = [3,-4,5,1,-2], lower = -4, upper = 5\nOutput:4\nExplanation:The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.", + "image": null + }, + { + "text": "Example 3: Input:differences = [4,-7,2], lower = 3, upper = 6\nOutput:0\nExplanation:There are no possible hidden sequences. Thus, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArrays(int[] differences, int lower, int upper) {\n ArrayList ans = new ArrayList<>();\n ans.add(lower); \n int mn = lower;\n int mx = lower;\n \n for (int i = 0; i < differences.length; i++) {\n int d = differences[i];\n ans.add(d + ans.get(ans.size() - 1));\n mn = Math.min(mn, ans.get(ans.size() - 1));\n mx = Math.max(mx, ans.get(ans.size() - 1));\n }\n\n int add = lower - mn;\n \n for (int i = 0; i < ans.size(); i++) {\n ans.set(i, ans.get(i) + add);\n }\n \n for (int i = 0; i < ans.size(); i++) {\n if (ans.get(i) < lower || upper < ans.get(i)) {\n return 0;\n }\n }\n \n int add2 = upper - mx;\n \n return add2 - add + 1;\n }\n}\n", + "title": "2145. Count the Hidden Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of n integers differences , which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1) . More formally, call the hidden sequence hidden , then we have that differences[i] = hidden[i + 1] - hidden[i] . You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0 .", + "description_images": [], + "constraints": [ + "For example, given differences = [1, -3, 4] , lower = 1 , upper = 6 , the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 ( inclusive ). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6 . [1, 2, 3, 4] is not possible since the differences are not correct.", + "[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.", + "[5, 6, 3, 7] is not possible since it contains an element greater than 6 .", + "[1, 2, 3, 4] is not possible since the differences are not correct." + ], + "examples": [ + { + "text": "Example 1: Input:differences = [1,-3,4], lower = 1, upper = 6\nOutput:2\nExplanation:The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:differences = [3,-4,5,1,-2], lower = -4, upper = 5\nOutput:4\nExplanation:The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.", + "image": null + }, + { + "text": "Example 3: Input:differences = [4,-7,2], lower = 3, upper = 6\nOutput:0\nExplanation:There are no possible hidden sequences. Thus, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n l = [0]\n for i in differences:\n l.append(l[-1]+i)\n return max(0,(upper-lower+1)-(max(l)-min(l)))\n", + "title": "2145. Count the Hidden Sequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words . A string is consistent if all characters in the string appear in the string allowed . Return the number of consistent strings in the array words .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= allowed.length <= 26", + "1 <= words[i].length <= 10", + "The characters in allowed are distinct .", + "words[i] and allowed contain only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]\nOutput:2\nExplanation:Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.", + "image": null + }, + { + "text": "Example 2: Input:allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]\nOutput:7\nExplanation:All strings are consistent.", + "image": null + }, + { + "text": "Example 3: Input:allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]\nOutput:4\nExplanation:Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 73.10%) | Memory: 54.7 MB (Top 46.20%)\nclass Solution {\n public int countConsistentStrings(String allowed, String[] words) {\n Set allowedSet = new HashSet<>();\n for(int i=0;i allowedSet, String word){\n for (int i = 0; i < word.length(); i++){\n if(!allowedSet.contains(word.charAt(i))) return false;\n }\n return true;\n }\n}", + "title": "1684. Count the Number of Consistent Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words . A string is consistent if all characters in the string appear in the string allowed . Return the number of consistent strings in the array words .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= allowed.length <= 26", + "1 <= words[i].length <= 10", + "The characters in allowed are distinct .", + "words[i] and allowed contain only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]\nOutput:2\nExplanation:Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.", + "image": null + }, + { + "text": "Example 2: Input:allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]\nOutput:7\nExplanation:All strings are consistent.", + "image": null + }, + { + "text": "Example 3: Input:allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]\nOutput:4\nExplanation:Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 236 ms (Top 95.16%) | Memory: 16 MB (Top 85.69%)\nclass Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n allowed = set(allowed)\n count = 0\n\n for word in words:\n for letter in word:\n if letter not in allowed:\n count += 1\n break\n\n return len(words) - count", + "title": "1684. Count the Number of Consistent Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers n and maxValue , which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Return the number of distinct ideal arrays of length n . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Every arr[i] is a value from 1 to maxValue , for 0 <= i < n .", + "Every arr[i] is divisible by arr[i - 1] , for 0 < i < n ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, maxValue = 5\nOutput:10\nExplanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, maxValue = 3\nOutput:11\nExplanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nddistinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nddistinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int M =(int)1e9+7;\n public int idealArrays(int n, int maxValue) {\n long ans = 0;\n int N = n+maxValue;\n long[] inv = new long[N];\n long[] fact = new long[N];\n long[] factinv = new long[N];\n inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1;\n for (int i = 2; i < N; i++){ // mod inverse\n inv[i]=M-M/i*inv[M%i]%M;\n fact[i]=fact[i-1]*i%M;\n factinv[i]=factinv[i-1]*inv[i]%M;\n }\n for (int i = 1; i <= maxValue; i++){\n int tmp = i;\n Map map = new HashMap<>();\n for (int j = 2; j*j<= tmp; j++){\n while(tmp%j==0){ // prime factorization.\n tmp/=j;\n map.merge(j, 1, Integer::sum);\n }\n }\n if (tmp>1){\n map.merge(tmp, 1, Integer::sum);\n }\n long gain=1;\n for (int val : map.values()){ // arranges all the primes.\n gain *= comb(n+val-1, val, fact, factinv);\n gain %= M;\n }\n ans += gain;\n ans %= M;\n }\n\n return (int)ans;\n }\n\n private long comb(int a, int b, long[] fact, long[] factinv){\n return fact[a]*factinv[b]%M*factinv[a-b]%M;\n }\n}\n", + "title": "2338. Count the Number of Ideal Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers n and maxValue , which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Return the number of distinct ideal arrays of length n . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Every arr[i] is a value from 1 to maxValue , for 0 <= i < n .", + "Every arr[i] is divisible by arr[i - 1] , for 0 < i < n ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, maxValue = 5\nOutput:10\nExplanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, maxValue = 3\nOutput:11\nExplanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nddistinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nddistinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "from math import sqrt\n\nclass Solution:\n def primesUpTo(self, n):\n primes = set(range(2, n + 1))\n for i in range(2, n):\n if i in primes:\n it = i * 2\n while it <= n:\n if it in primes:\n primes.remove(it)\n it += i\n\n return primes\n\n def getPrimeFactors(self, n, primes):\n ret = {}\n sq = int(math.sqrt(n))\n\n for p in primes:\n if n in primes:\n ret[n] = 1\n break\n\n while n % p == 0:\n ret[p] = ret.get(p, 0) + 1\n n //= p\n\n if n <= 1:\n break\n\n return ret\n \n def idealArrays(self, n: int, maxValue: int) -> int:\n mod = 10**9 + 7\n ret = 0\n primes = self.primesUpTo(maxValue)\n \n for num in range(1, maxValue + 1):\n # find number of arrays that can end with num\n # for each prime factor, we can add it at any index i that we want\n pf = self.getPrimeFactors(num, primes)\n cur = 1\n for d in pf:\n ct = pf[d]\n v = n\n # there are (n + 1) choose k ways to add k prime factors\n for add in range(1, ct):\n v *= (n + add)\n v //= (add + 1)\n \n cur = (cur * v) % mod\n \n ret = (ret + cur) % mod\n \n return ret\n", + "title": "2338. Count the Number of Ideal Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We define str = [s, n] as the string str which consists of the string s concatenated n times. We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1 . You are given two strings s1 and s2 and two integers n1 and n2 . You have the two strings str1 = [s1, n1] and str2 = [s2, n2] . Return the maximum integer m such that str = [str2, m] can be obtained from str1 .", + "description_images": [], + "constraints": [ + "For example, str == [\"abc\", 3] ==\"abcabcabc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n dp = []\n for i in range(len(s2)):\n start = i\n cnt = 0\n for j in range(len(s1)):\n if s1[j] == s2[start]:\n start += 1\n if start == len(s2):\n start = 0\n cnt += 1\n dp.append((start,cnt))\n res = 0\n next = 0\n for _ in range(n1):\n res += dp[next][1]\n next = dp[next][0]\n return res // n2\n\t\t\n", + "title": "466. Count The Repetitions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr . We want to select three indices i , j and k where (0 <= i < j <= k < arr.length) . Let's define a and b as follows: Note that ^ denotes the bitwise-xor operation. Return the number of triplets ( i , j and k ) Where a == b .", + "description_images": [], + "constraints": [ + "a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]", + "b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,3,1,6,7]\nOutput:4\nExplanation:The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,1,1,1]\nOutput:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 85.89%) | Memory: 41.5 MB (Top 67.63%)\nclass Solution {\n public int countTriplets(int[] arr) {\n int count=0;\n\n for(int i=0;i int:\n s = [0]\n n = len(arr)\n if n <= 1:\n return 0 \n for i in range(n):\n s.append(s[-1]^arr[i])\n # a = s[i] ^ s[j], b = s[j] ^ s[k+1] \n count = defaultdict(int)\n # a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0 \n # <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1])\n # <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1]\n \n res = 0 \n # len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k\n for i in range(n-1):\n for k in range(i+1, n):\n if s[i] == s[k+1]:\n res += (k-i)\n return res \n", + "title": "1442. Count Triplets That Can Form Two Arrays of Equal XOR", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [row i , col i ] and walls[j] = [row j , col j ] represent the positions of the i th guard and j th wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 10^5", + "2 <= m * n <= 10^5", + "1 <= guards.length, walls.length <= 5 * 10^4", + "2 <= guards.length + walls.length <= m * n", + "guards[i].length == walls[j].length == 2", + "0 <= row i , row j < m", + "0 <= col i , col j < n", + "All the positions in guards and walls are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\nOutput:7\nExplanation:The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example1drawio2.png" + }, + { + "text": "Example 2: Input:m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\nOutput:4\nExplanation:The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countUnguarded(int m, int n, int[][] guards, int[][] walls)\n {\n int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};\n char[][] grid= new char[m][n];\n int count = m*n - guards.length - walls.length;\n for(int[] wall : walls)\n {\n int x = wall[0], y = wall[1];\n grid[x][y] = 'W';\n }\n for(int[] guard : guards)\n {\n int x = guard[0], y = guard[1];\n grid[x][y] = 'G';\n }\n for(int[] point : guards)\n {\n for(int dir[] : dirs)\n {\n int x = point[0] + dir[0];\n int y = point[1] + dir[1];\n while(!(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 'G' || grid[x][y] == 'W'))\n {\n if(grid[x][y] != 'P')\n count--;\n grid[x][y] = 'P';\n x += dir[0];\n y += dir[1];\n }\n }\n }\n return count;\n }\n}\n", + "title": "2257. Count Unguarded Cells in the Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [row i , col i ] and walls[j] = [row j , col j ] represent the positions of the i th guard and j th wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 10^5", + "2 <= m * n <= 10^5", + "1 <= guards.length, walls.length <= 5 * 10^4", + "2 <= guards.length + walls.length <= m * n", + "guards[i].length == walls[j].length == 2", + "0 <= row i , row j < m", + "0 <= col i , col j < n", + "All the positions in guards and walls are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\nOutput:7\nExplanation:The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example1drawio2.png" + }, + { + "text": "Example 2: Input:m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\nOutput:4\nExplanation:The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n dp = [[0] * n for _ in range(m)]\n for x, y in guards+walls:\n dp[x][y] = 1\n \n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n \n for x, y in guards:\n for dx, dy in directions:\n curr_x = x\n curr_y = y\n \n while 0 <= curr_x+dx < m and 0 <= curr_y+dy < n and dp[curr_x+dx][curr_y+dy] != 1:\n curr_x += dx\n curr_y += dy\n dp[curr_x][curr_y] = 2\n \n return sum(1 for i in range(m) for j in range(n) if dp[i][j] == 0) \n", + "title": "2257. Count Unguarded Cells in the Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a list of preferences for n friends, where n is always even . For each person i , preferences[i] contains a list of friends sorted in the order of preference . In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1 . All the friends are divided into pairs. The pairings are given in a list pairs , where pairs[i] = [x i , y i ] denotes x i is paired with y i and y i is paired with x i . However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but: Return the number of unhappy friends .", + "description_images": [], + "constraints": [ + "x prefers u over y , and", + "u prefers x over v ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput:2\nExplanation:Friend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput:0\nExplanation:Both friends 0 and 1 are happy.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.12%) | Memory: 64.00 MB (Top 67.65%)\n\nclass Solution {\n public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {\n int[][] rankings = new int[n][n]; // smaller the value, higher the preference\n int[] pairedWith = new int[n];\n for (int i = 0; i < n; i++) {\n for (int rank = 0; rank < n - 1; rank++) {\n int j = preferences[i][rank];\n rankings[i][j] = rank; // person \"i\" views person \"j\" with rank\n }\n }\n int unhappy = 0;\n for (int[] pair : pairs) {\n int a = pair[0], b = pair[1];\n pairedWith[a] = b;\n pairedWith[b] = a;\n }\n for (int a = 0; a < n; a++) {\n // \"a\" prefers someone else\n if (rankings[a][pairedWith[a]] != 0) {\n for (int b = 0; b < n; b++) {\n // \"b\" prefers to be with \"a\" over their current partner\n // \"a\" prefers to be with \"b\" over their current partner\n if (b != a\n && rankings[b][a] < rankings[b][pairedWith[b]]\n && rankings[a][b] < rankings[a][pairedWith[a]]) {\n unhappy++;\n break;\n }\n }\n }\n }\n return unhappy;\n }\n}\n", + "title": "1583. Count Unhappy Friends", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of preferences for n friends, where n is always even . For each person i , preferences[i] contains a list of friends sorted in the order of preference . In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1 . All the friends are divided into pairs. The pairings are given in a list pairs , where pairs[i] = [x i , y i ] denotes x i is paired with y i and y i is paired with x i . However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but: Return the number of unhappy friends .", + "description_images": [], + "constraints": [ + "x prefers u over y , and", + "u prefers x over v ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput:2\nExplanation:Friend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput:0\nExplanation:Both friends 0 and 1 are happy.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n dd = {}\n \n for i,x in pairs:\n dd[i] = preferences[i][:preferences[i].index(x)]\n dd[x] = preferences[x][:preferences[x].index(i)]\n \n ans = 0\n \n for i in dd:\n for x in dd[i]:\n if i in dd[x]:\n ans += 1\n break\n \n return ans\n", + "title": "1583. Count Unhappy Friends", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let's define a function countUniqueChars(s) that returns the number of unique characters on s . Given a string s , return the sum of countUniqueChars(t) where t is a substring of s . The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too.", + "description_images": [], + "constraints": [ + "For example, calling countUniqueChars(s) if s = \"LEETCODE\" then \"L\" , \"T\" , \"C\" , \"O\" , \"D\" are the unique characters since they appear only once in s , therefore countUniqueChars(s) = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABC\"\nOutput:10\nExplanation:All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10", + "image": null + }, + { + "text": "Example 2: Input:s = \"ABA\"\nOutput:8\nExplanation:The same as example 1, exceptcountUniqueChars(\"ABA\") = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LEETCODE\"\nOutput:92", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n ans = 0\n idx_recorder = collections.defaultdict(list)\n n = len(s)\n \n # record the index for every character\n # s = \"ABCA\"\n # {\n # \"A\": [0, 3],\n # \"B\": [1],\n # \"C\": [2],\n # }\n for idx in range(len(s)):\n c = s[idx]\n idx_recorder[c].append(idx)\n \n \n def helper(idxes):\n ans = 0\n\n for i in range(len(idxes)):\n # Count the number of substring which contain the character without duplicating\n # get the left, right value to compute the result.\n # \n # Take the middle A (idx=3) as example\n # s = 'AxxAxxxAxx'\n # -\n # left = 3 - 0 = 3 \n # right = 7 - 3 = 4\n #\n # The number of substring which contain this A (idx=3) without containing\n # other A is 3 * 4 = 12\n \n if i == 0:\n # If it is a first one: it means that there is\n # no duplicate character in left\n left = idxes[i] + 1\n else:\n left = idxes[i] - idxes[i-1]\n \n if i == len(idxes) - 1:\n # If it is a last one: it means that there is\n # no duplicate character in right side\n right = n - idxes[i]\n else:\n right = idxes[i+1] - idxes[i]\n \n ans += left * right\n \n return ans\n \n ans = 0\n for c in idx_recorder:\n ans += helper(idx_recorder[c])\n return ans\n", + "title": "828. Count Unique Characters of All Substrings of a Given String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . Return the number of pairs of different nodes that are unreachable from each other .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput:0\nExplanation:There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-3.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput:14\nExplanation:There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 56.92%) | Memory: 193.9 MB (Top 33.32%)\nclass Solution {\n public long countPairs(int n, int[][] edges) {\n //Building Graph\n ArrayList < ArrayList < Integer >> graph = new ArrayList < > ();\n for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ());\n for (int arr[]: edges) {\n graph.get(arr[0]).add(arr[1]);\n graph.get(arr[1]).add(arr[0]);\n }\n boolean visited[] = new boolean[n];\n long res = 0;\n int prev = 0;\n int count[] = {\n 0\n };\n for (int i = 0; i < graph.size(); i++) { // Running for loop on all connected components of graph\n if (visited[i] == true) continue; // if the node is alredy reached by any of other vertex then we don't need to terverse it again\n dfs(graph, i, visited, count);\n long a = n - count[0]; // (total - current count)\n long b = count[0] - prev; // (current count - prev )\n prev = count[0]; // Now Store count to prev\n res += (a * b);\n }\n return res;\n }\n void dfs(ArrayList < ArrayList < Integer >> graph, int v, boolean vis[], int count[]) {\n vis[v] = true;\n count[0]++; //for counting connected nodes\n for (int child: graph.get(v)) {\n if (!vis[child]) {\n dfs(graph, child, vis, count);\n }\n }\n }\n}", + "title": "2316. Count Unreachable Pairs of Nodes in an Undirected Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . Return the number of pairs of different nodes that are unreachable from each other .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput:0\nExplanation:There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-3.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput:14\nExplanation:There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2311 ms (Top 90.13%) | Memory: 73.8 MB (Top 86.18%)\n'''\n* Make groups of nodes which are connected\n eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\n\n 0 ---- 2 1 --- 6 3\n | |\n | |\n 5 ---- 4\n\n groups will be {0: 4, 1: 2, 3: 1},\n i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3\n\n* Now, we have [4, 2, 1] as no of nodes in each group, we have to multiply each of no. with remaining\n ans = (4 * 2 + 4 * 1) + (2 * 1)\n but calculating ans this way will give TLE.\n\n* if we notice, (4 * 2 + 4 * 1) + (2 * 1), we can combine, equation like this,\n 4 * 2 + (4 + 2) * 1, using this, we can reduce complexity.\n so, if we have count of groups array as [a, b, c, d], ans will be,\n ans = a * b + (a + b) * c + (a + b + c) * d\n\n* will use, union for generating groups.\n* ps, you can modify UnionFind class as per your need. Have implemented full union-find for beginners.\n'''\n\nclass UnionFind:\n def __init__(self, size):\n self.root = [i for i in range(size)]\n self.rank = [1] * size\n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootX] < self.rank[rootY]:\n self.root[rootX] = rootY\n else:\n self.root[rootY] = rootX\n self.rank[rootX] += 1\n\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]]) -> int:\n dsu = UnionFind(n)\n for u, v in edges:\n dsu.union(u, v)\n C = Counter([dsu.find(i) for i in range(n)])\n groupCounts = list(C.values())\n ans = 0\n firstGroupCount = groupCounts[0]\n for i in range(1, len(groupCounts)):\n ans += firstGroupCount * groupCounts[i]\n firstGroupCount += groupCounts[i]\n return ans", + "title": "2316. Count Unreachable Pairs of Nodes in an Undirected Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) and has all five vowels present in it. Given a string word , return the number of vowel substrings in word .", + "description_images": [], + "constraints": [ + "1 <= word.length <= 100", + "word consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiouu\"\nOutput:2\nExplanation:The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"unicornarihan\"\nOutput:0\nExplanation:Not all 5 vowels are present, so there are no vowel substrings.", + "image": null + }, + { + "text": "Example 3: Input:word = \"cuaieuouac\"\nOutput:7\nExplanation:The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countVowelSubstrings(String word)\n {\n int vow = 0;\n int n = word.length();\n Set set = new HashSet<>();\n for(int i = 0; i < n-4; i++)\n {\n set.clear();\n for(int j = i; j < n; j++)\n {\n char ch = word.charAt(j);\n if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')\n {\n set.add(ch);\n if(set.size() == 5)\n vow++;\n }\n else\n break;\n }\n }\n return vow;\n }\n}\n", + "title": "2062. Count Vowel Substrings of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) and has all five vowels present in it. Given a string word , return the number of vowel substrings in word .", + "description_images": [], + "constraints": [ + "1 <= word.length <= 100", + "word consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiouu\"\nOutput:2\nExplanation:The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"unicornarihan\"\nOutput:0\nExplanation:Not all 5 vowels are present, so there are no vowel substrings.", + "image": null + }, + { + "text": "Example 3: Input:word = \"cuaieuouac\"\nOutput:7\nExplanation:The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countVowelSubstrings(self, word: str) -> int:\n vowels = {'a','e','i','o','u'}\n pointer = 0\n res = 0\n if len(word) <= 4:\n return 0\n while pointer != len(word)-4:\n # if set(list(word[pointer:pointer+5])) == vowels:\n # temp = 1\n # res += 1\n # while set(list(word[pointer:pointer+temp+5])) == vowels and pointer+temp+4 != len(word):\n # res += 1\n # temp += 1\n # elif word[pointer] in vowels:\n # temp = 1\n # while set(list(word[pointer:pointer+5+temp])) != vowels:\n # temp += 1\n # res += 1\n # pointer += 1\n temp = 0\n if word[pointer] in vowels:\n while temp+pointer != len(word)-4:\n test_1 = set(list(word[pointer:pointer+temp+5]))\n test_2 = word[pointer:pointer+temp+5]\n if set(list(word[pointer:pointer+temp+5])).issubset(vowels): \n if set(list(word[pointer:pointer+temp+5])) == vowels:\n res += 1\n temp+=1\n else:\n break\n \n pointer += 1\n return res\n\n ", + "title": "2062. Count Vowel Substrings of a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , your task is to count how many strings of length n can be formed under the following rules: Since the answer may be too large, return it modulo 10^9 + 7.", + "description_images": [], + "constraints": [ + "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'." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:5\nExplanation:All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:10\nExplanation:All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".", + "image": null + }, + { + "text": "Example 3: Input:n = 5\nOutput:68", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 32.30%) | Memory: 52.8 MB (Top 39.76%)\nclass Solution {\n private long[][] dp;\n private int mod = (int)1e9 + 7;\n\n public int countVowelPermutation(int n) {\n dp = new long[6][n+1];\n if(n == 1) return 5;\n\n for(int i = 0; i < 5; i++)\n dp[i][0] = 1;\n\n helper(n,'z');\n return (int)dp[5][n];\n }\n\n private long helper(int n, char vowel)\n {\n long ans = 0;\n if(n == 0) return 1;\n\n if(vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels\n {\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'i') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[5][n] = ans;\n }\n // from here as per our assumptions of Vowels we will make calls & store results\n else if(vowel == 'a') // for Nth number we would store Result for \"a\" in dp[0][n]\n {\n if(dp[0][n] != 0) return dp[0][n];\n ans = (ans + helper(n-1,'e'))%mod;\n dp[0][n] = ans;\n }\n\n else if(vowel == 'e') // for Nth number we would store Result for \"e\" in dp[1][n]\n {\n if(dp[1][n] != 0) return dp[1][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'i'))%mod;\n dp[1][n] = ans;\n }\n\n else if(vowel == 'i') // for Nth number we would store Result for \"i\" in dp[2][n]\n {\n if(dp[2][n] != 0) return dp[2][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[2][n] = ans;\n }\n\n else if(vowel == 'o') // for Nth number we would store Result for \"o\" in dp[3][n]\n {\n if(dp[3][n] != 0) return dp[3][n];\n ans = (ans + helper(n-1,'i') + helper(n-1,'u'))%mod;\n dp[3][n] = ans;\n }\n\n else // for Nth number we would store Result for \"u\" in dp[4][n]\n {\n if(dp[4][n] != 0) return dp[4][n];\n ans = (ans + helper(n-1,'a'))%mod;\n dp[4][n] = ans;\n }\n\n return ans;\n }\n}", + "title": "1220. Count Vowels Permutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , your task is to count how many strings of length n can be formed under the following rules: Since the answer may be too large, return it modulo 10^9 + 7.", + "description_images": [], + "constraints": [ + "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'." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:5\nExplanation:All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:10\nExplanation:All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".", + "image": null + }, + { + "text": "Example 3: Input:n = 5\nOutput:68", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 249 ms (Top 78.97%) | Memory: 19.8 MB (Top 29.73%)\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n # dp[i][j] means the number of strings of length i that ends with the j-th vowel.\n dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]\n moduler = math.pow(10, 9) + 7\n for i in range(1, n):\n # For vowel a\n dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler\n # For vowel e\n dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler\n # For vowel i\n dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler\n # For vowel o\n dp[i][3] = (dp[i - 1][2]) % moduler\n # For vowel u\n dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler\n\n return int(sum(dp[-1]) % moduler)", + "title": "1220. Count Vowels Permutation", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n , prevRoom , where prevRoom[i] indicates that you must build room prevRoom[i] before building room i , and these two rooms must be connected directly . Room 0 is already built, so prevRoom[0] = -1 . The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0 . You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected . You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == prevRoom.length", + "2 <= n <= 10^5", + "prevRoom[0] == -1", + "0 <= prevRoom[i] < n for all 1 <= i < n", + "Every room is reachable from room 0 once all the rooms are built." + ], + "examples": [ + { + "text": "Example 1: Input:prevRoom = [-1,0,1]\nOutput:1\nExplanation:There is only one way to build the additional rooms: 0 → 1 → 2", + "image": "https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" + }, + { + "text": "Example 2: Input:prevRoom = [-1,0,0,1,2]\nOutput:6\nExplanation:The 6 ways are:\n0 → 1 → 3 → 2 → 4\n0 → 2 → 4 → 1 → 3\n0 → 1 → 2 → 3 → 4\n0 → 1 → 2 → 4 → 3\n0 → 2 → 1 → 3 → 4\n0 → 2 → 1 → 4 → 3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int M = (int)1e9+7;\n public int waysToBuildRooms(int[] prevRoom) {\n int n = prevRoom.length;\n long[] fact = new long[n];\n long[] invFact = new long[n];\n long[] inv = new long[n];\n fact[1]=fact[0]=invFact[0]=invFact[1]=inv[1]=1;\n for (int i = 2; i < n; i++){ // modInverse \n fact[i] = fact[i-1]*i%M;\n inv[i] = M-M/i*inv[M%i]%M;\n invFact[i] = invFact[i-1]*inv[i]%M;\n }\n\n Map> map = new HashMap<>();\n for (int i = 0; i < n; i++){ // add an edge from parent to child\n map.computeIfAbsent(prevRoom[i], o -> new ArrayList<>()).add(i);\n }\n\n long[] ans = new long[]{1};\n solve(0, fact, invFact, map, ans);\n return (int)ans[0];\n }\n\n private int solve(int i, long[] fact, long[] invFact, Map> map, long[] ans){\n int sum = 0;\n for (int next : map.getOrDefault(i, List.of())){\n int cur = solve(next, fact, invFact, map, ans);\n ans[0] = ans[0] * invFact[cur] % M; // divide fact[cur] -> multiply invFact[cur]\n sum += cur;\n }\n ans[0] = ans[0] * fact[sum] % M;\n return sum+1;\n }\n}\n", + "title": "1916. Count Ways to Build Rooms in an Ant Colony", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n , prevRoom , where prevRoom[i] indicates that you must build room prevRoom[i] before building room i , and these two rooms must be connected directly . Room 0 is already built, so prevRoom[0] = -1 . The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0 . You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected . You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == prevRoom.length", + "2 <= n <= 10^5", + "prevRoom[0] == -1", + "0 <= prevRoom[i] < n for all 1 <= i < n", + "Every room is reachable from room 0 once all the rooms are built." + ], + "examples": [ + { + "text": "Example 1: Input:prevRoom = [-1,0,1]\nOutput:1\nExplanation:There is only one way to build the additional rooms: 0 → 1 → 2", + "image": "https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" + }, + { + "text": "Example 2: Input:prevRoom = [-1,0,0,1,2]\nOutput:6\nExplanation:The 6 ways are:\n0 → 1 → 3 → 2 → 4\n0 → 2 → 4 → 1 → 3\n0 → 1 → 2 → 3 → 4\n0 → 1 → 2 → 4 → 3\n0 → 2 → 1 → 3 → 4\n0 → 2 → 1 → 4 → 3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4732 ms (Top 93.33%) | Memory: 177.5 MB (Top 6.67%)\nclass Solution:\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(prevRoom)\n\n mod_inverses = [1] * (n + 1)\n factorials = [1] * (n + 1)\n inverse_factorials = [1] * (n + 1)\n\n for x in range(2, n + 1): # Precompute all factorials and inverse factorials needed in O(1) time each\n mod_inverses[x] = mod - mod // x * mod_inverses[mod % x] % mod\n factorials[x] = (x * factorials[x - 1]) % mod\n inverse_factorials[x] = (mod_inverses[x] * inverse_factorials[x - 1]) % mod\n\n children = collections.defaultdict(list) # Convert parent list to children lists\n for i, x in enumerate(prevRoom[1:], 1):\n children[x].append(i)\n\n def postorder(curr: int) -> Tuple[int, int]:\n if curr not in children: # Leaf has ways, size both 1\n return 1, 1\n tot_size = 1\n tot_ways = 1\n for child in children[curr]:\n ways, size_of = postorder(child)\n tot_ways *= ways * inverse_factorials[size_of]\n tot_size += size_of\n tot_ways *= factorials[tot_size-1]\n return tot_ways % mod, tot_size\n\n return postorder(0)[0]", + "title": "1916. Count Ways to Build Rooms in an Ant Colony", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D integer array, queries . For each queries[i] , where queries[i] = [n i , k i ] , find the number of different ways you can place positive integers into an array of size n i such that the product of the integers is k i . As the number of ways may be too large, the answer to the i th query is the number of ways modulo 10^9 + 7 . Return an integer array answer where answer.length == queries.length , and answer[i] is the answer to the i th query.", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 10^4", + "1 <= n i , k i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [[2,6],[5,1],[73,660]]\nOutput:[4,1,50734910]\nExplanation:Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109+ 7 = 50734910.", + "image": null + }, + { + "text": "Example 2: Input:queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput:[1,2,3,10,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 72.7%) | Memory: 45.86 MB (Top 86.3%)\n\nclass Solution {\n // List of primes upto sqrt(10e4)\n int[] PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };\n // Factors of integers upto 13\n int[][] SMALL_INT_FACTORS = { null, {1}, {2}, {3}, {2,2}, {5}, {2,3}, {7}, {2,2,2}, {3,3}, {2,5}, {11}, {2,2,3}, {13} };\n \n public int[] waysToFillArray(int[][] queries) {\n int n = queries.length;\n int[] ans = new int[n];\n for(int i=0; i 1) // If any prime greater than sqrt(10e4) is a remaining factor of num\n ans = multiply(ans, k);\n return (int) ans;\n }\n \n // In how many ways can we split an integer n into k non-negative numbers?\n // Answer = combin(n+k-1, k-1) (11th grade math; non-trivial but google-able)\n // combin(n+k-1, k-1) smoothly turns into combin(n+k-1, n)\n private long getSplitCount(int n, int k) {\n int a = n+k-1, b = k-1;\n if((b << 1) > a) b = a - b;\n return comb(a, b);\n }\n \n \n // combin(n, r) = (n . n-1 . n-2 . n-3 ... n-r+1)/(1 . 2 . 3 ... r)\n // Brute force division:\n // We exploit the fact that r in this problem is at max 13\n // We try to cancel common prime factors of numerator and denominator terms\n // This leaves us with numerator elements alone (thus avoiding mod related issues wrt division)\n private long comb(int n, int r) {\n int[] numerators = new int[r];\n for(int i=0, j=n; i List[int]:\n mod = 10 ** 9 + 7\n \n def dfs(n, val):\n if (n, val) not in self.dp:\n if n == 1: return 1\n temp = 1\n for k in range(val//2, 0, -1):\n if val % k == 0:\n temp += dfs(n-1, val // k)\n self.dp[n, val] = temp % mod\n return self.dp[n, val]\n \n res = []\n for n, val in queries:\n res.append(dfs(n, val))\n return res\n", + "title": "1735. Count Ways to Make Array With Product", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed arrays of strings startWords and targetWords . Each string consists of lowercase English letters only. For each string in targetWords , check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords . The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords . Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.", + "description_images": [], + "constraints": [ + "For example, if the string is \"abc\" , the letters 'd' , 'e' , or 'y' can be added to it, but not 'a' . If 'd' is added, the resulting string will be \"abcd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\nOutput:2\nExplanation:- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n Note that \"act\" does exist in startWords, but wemustappend one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.", + "image": null + }, + { + "text": "Example 2: Input:startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\nOutput:1\nExplanation:- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int wordCount(String[] startWords, String[] targetWords) {\n int n = startWords.length;\n int count = 0;\n Set set = new HashSet<>();\n \n //1. store lexicographically sorted letters of startword in set\n for(String start: startWords){\n char[] sAr = start.toCharArray();\n Arrays.sort(sAr);\n set.add(new String(sAr));\n }\n int m = targetWords.length;\n boolean ans = false;\n for(int i = 0; i < m; i++){\n //2. sort lexicographically letters of targetword and store in new string s\n char[] tAr = targetWords[i].toCharArray();\n Arrays.sort(tAr);\n int k = tAr.length;\n String s = String.valueOf(tAr);\n \n ans = false;\n for(int j = 0; j < k; j++){\n //3. make a new string by omitting one letter from word and check if it is present in set than increase count value\n String str = s.substring(0,j) + s.substring(j+1);\n if(set.contains(str)){\n count++;\n break;\n }\n }\n }\n return count; \n }\n \n}\n", + "title": "2135. Count Words Obtained After Adding a Letter", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed arrays of strings startWords and targetWords . Each string consists of lowercase English letters only. For each string in targetWords , check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords . The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords . Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.", + "description_images": [], + "constraints": [ + "For example, if the string is \"abc\" , the letters 'd' , 'e' , or 'y' can be added to it, but not 'a' . If 'd' is added, the resulting string will be \"abcd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\nOutput:2\nExplanation:- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n Note that \"act\" does exist in startWords, but wemustappend one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.", + "image": null + }, + { + "text": "Example 2: Input:startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\nOutput:1\nExplanation:- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Brute Force\n# O(S * T); S := len(startWors); T := len(targetWords)\n# TLE\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n cnt = 0\n for target in targetWords:\n for start in startWords:\n if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1:\n cnt += 1\n break\n return cnt\n\n# Sort + HashSet Lookup\n# O(S + T) Time\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n # Sort each start word and add it to a hash set\n startWords_sorted = set()\n # O(S*26*log(26))\n for word in startWords:\n startWords_sorted.add(\"\".join(sorted(list(word))))\n \n # sort each target word and add it to a list\n # O(T*26*log(26))\n targetWords_sorted = []\n for word in targetWords:\n targetWords_sorted.append(sorted(list(word)))\n \n # for each sorted target word, we remove a single character and \n # check if the resulting word is in the startWords_sorted\n # if it is, we increment cnt and break the inner loop\n # otherwise we keep removing until we either find a hit or reach the\n # end of the string\n # O(T*26) = O(T)\n cnt = 0\n for target in targetWords_sorted:\n for i in range(len(target)):\n w = target[:i] + target[i+1:]\n w = \"\".join(w)\n if w in startWords_sorted:\n cnt += 1\n break\n \n return cnt\n\n# Using Bit Mask\n# O(S + T) Time\n# Similar algorithm as the one above, implemented using a bit mask to avoid the sorts\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n start_set = set()\n # O(S * 26)\n for word in startWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n start_set.add(m)\n \n # O(T * 2 * 26)\n cnt = 0\n for word in targetWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n \n for ch in word:\n i = ord(ch) - ord('a')\n if m ^ (1 << i) in start_set:\n cnt += 1\n break\n return cnt\n", + "title": "2135. Count Words Obtained After Adding a Letter", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[0,1,1]\nExplanation:0 --> 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[0,1,1,2,1,2]\nExplanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.97%) | Memory: 46.2 MB (Top 98.87%)\n\nclass Solution {\n\n public void count(int n, int[] a, int k)\n {\n int i;\n for(i=k ; i 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[0,1,1,2,1,2]\nExplanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBits(self, n: int) -> List[int]:\n # We know that all exponential values of two have 1 bit turned on, the rest are turned off.\n # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed \n # into smaller numbers where we already have found the # of 1s, for example.\n # F(3) = F(2^1) + F(1) = 1 + 1 = 3\n # F(4) = F(2^2) + F(0) = 1 + 0. ( Even thought we havent defined F(4) = F(2^2), by the previous established)\n # comment, we can safely say that all F(2^X) has only 1 bit so thats where F(4) would be = 1\n # F(5) = F(2^2) + F(1) = 1 + 1 = 2\n # F(6) = F(2^2) + F(2) = F(4) + F(2) = 1 + 1\n # The relation countinues for all following numbers\n \n # This solution is O(N)\n # With O(1) extra space ( considering dp is the returned answer )\n \n dp = [0]\n\t\t\n for i in range(1, n + 1):\n exponent = int(math.log(i) / math.log(2))\n num = 2**exponent\n decimal = i % (num)\n if num == i:\n dp.append(1)\n else:\n dp.append(dp[num] + dp[decimal])\n return(dp)\n", + "title": "338. Counting Bits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings words and a string pref . Return the number of strings in words that contain pref as a prefix . A prefix of a string s is any leading contiguous substring of s .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length, pref.length <= 100", + "words[i] and pref consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"pay\",\"attention\",\"practice\",\"attend\"],pref= \"at\"\nOutput:2\nExplanation:The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"win\",\"loops\",\"success\"],pref= \"code\"\nOutput:0\nExplanation:There are no strings that contain \"code\" as a prefix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int prefixCount(String[] words, String pref) {\n int c = 0;\n for(String s : words) {\n if(s.indexOf(pref)==0) \n c++;\n }\n return c; \n }\n}\n", + "title": "2185. Counting Words With a Given Prefix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words and a string pref . Return the number of strings in words that contain pref as a prefix . A prefix of a string s is any leading contiguous substring of s .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length, pref.length <= 100", + "words[i] and pref consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"pay\",\"attention\",\"practice\",\"attend\"],pref= \"at\"\nOutput:2\nExplanation:The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"win\",\"loops\",\"success\"],pref= \"code\"\nOutput:0\nExplanation:There are no strings that contain \"code\" as a prefix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(word.find(pref) == 0 for word in words)\n", + "title": "2185. Counting Words With a Given Prefix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the i th seat. The couples are numbered in order, the first couple being (0, 1) , the second couple being (2, 3) , and so on with the last couple being (2n - 2, 2n - 1) . Return the minimum number of swaps so that every couple is sitting side by side . A swap consists of choosing any two people, then they stand up and switch seats.", + "description_images": [], + "constraints": [ + "2n == row.length", + "2 <= n <= 30", + "n is even.", + "0 <= row[i] < 2n", + "All the elements of row are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = [0,2,1,3]\nOutput:1\nExplanation:We only need to swap the second (row[1]) and third (row[2]) person.", + "image": null + }, + { + "text": "Example 2: Input:row = [3,2,0,1]\nOutput:0\nExplanation:All couples are already seated side by side.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwapsCouples(int[] row) { // Union -Find pairs for 2\n Map parents=new HashMap<>();\n int count=0;\n for(int i=0;i7 , also place smaller number as parent for eg)//0,4 ; 1,3\n parents.put(i,i+1);\n }\n return count;\n }\n}\n", + "title": "765. Couples Holding Hands", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the i th seat. The couples are numbered in order, the first couple being (0, 1) , the second couple being (2, 3) , and so on with the last couple being (2n - 2, 2n - 1) . Return the minimum number of swaps so that every couple is sitting side by side . A swap consists of choosing any two people, then they stand up and switch seats.", + "description_images": [], + "constraints": [ + "2n == row.length", + "2 <= n <= 30", + "n is even.", + "0 <= row[i] < 2n", + "All the elements of row are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = [0,2,1,3]\nOutput:1\nExplanation:We only need to swap the second (row[1]) and third (row[2]) person.", + "image": null + }, + { + "text": "Example 2: Input:row = [3,2,0,1]\nOutput:0\nExplanation:All couples are already seated side by side.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 84.03%) | Memory: 17.30 MB (Top 39.5%)\n\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n loc = {x: i for i, x in enumerate(row)}\n ans = 0\n for i in range(0, len(row), 2): \n p = row[i] - 1 if row[i]&1 else row[i]+1\n if row[i+1] != p: \n ans += 1\n ii = loc[p]\n loc[row[i+1]], loc[row[ii]] = loc[row[ii]], loc[row[i+1]] # swap mappings\n row[i+1], row[ii] = row[ii], row[i+1] # swap values \n return ans \n", + "title": "765. Couples Holding Hands", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Return true if you can finish all courses. Otherwise, return false .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:true\nExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput:false\nExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFinish(int numCourses, int[][] prerequisites) {\n int n = numCourses;\n boolean [] visited = new boolean[n];\n boolean [] dfsVisited = new boolean[n];\n \n List> adj = createAdjList(n,prerequisites);\n for(int i=0;i> adj,boolean [] visited,boolean[] dfsVisited){\n \n visited[s]=true;\n dfsVisited[s]=true;\n \n for(int v:adj.get(s)){\n if(visited[v]==false){\n if(isCycle(v,adj,visited,dfsVisited)){\n return true;\n } \n }else if(visited[v]==true && dfsVisited[v]==true) {\n return true;\n } \n }\n dfsVisited[s]=false;\n return false;\n }\n \n private List> createAdjList(int n,int[][] prerequisites){\n List> adj = new ArrayList();\n \n for(int i=0;i());\n }\n for(int[] e : prerequisites){\n adj.get(e[1]).add(e[0]);\n }\n return adj;\n }\n}\n", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . Return true if you can finish all courses. Otherwise, return false .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:true\nExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput:false\nExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n \n pre = {} # course: list of prerequisites\n dep = {} # course: list of dependents\n for p in prerequisites:\n if p[0] not in pre:\n pre[p[0]] = set()\n if p[1] not in dep:\n dep[p[1]] = set()\n pre[p[0]].add(p[1])\n dep[p[1]].add(p[0])\n\n # Kahn's algorithm\n l = []\n s = set()\n for i in range(numCourses):\n if i not in dep: # if no dependents (incoming edge)\n s.add(i) \n while s:\n n = s.pop()\n l.append(n)\n if n in pre: # if n has prerequisites\n for m in pre[n]: # for each prerequisites m\n dep[m].remove(n) # remove n from m's dependents list\n if not dep[m]: # if m has no more dependents\n s.add(m)\n \n return len(l) == numCourses", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . 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 .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:[0,1]\nExplanation: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].", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput:[0,2,1,3]\nExplanation: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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] findOrder(int numCourses, int[][] prerequisites) {\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n for (int i = 0; i < numCourses; i++) {\n graph.put(i, new HashSet());\n }\n \n for (int[] pair : prerequisites) {\n graph.get(pair[1]).add(pair[0]);\n inDegree[pair[0]]++;\n }\n \n // BFS - Kahn's Algorithm - Topological Sort\n Queue bfsContainer = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0) {\n bfsContainer.add(i); \n }\n }\n \n int count = 0;\n int[] ans = new int[numCourses];\n while (!bfsContainer.isEmpty()) {\n int curr = bfsContainer.poll();\n ans[count++] = curr;\n for (Integer num : graph.get(curr)) {\n inDegree[num]--;\n if (inDegree[num] == 0) {\n bfsContainer.add(num);\n }\n }\n }\n \n if (count < numCourses) {\n return new int[] {};\n } else {\n return ans;\n }\n }\n}\n", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . 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 .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:[0,1]\nExplanation: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].", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput:[0,2,1,3]\nExplanation: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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n d = {i:[] for i in range(numCourses)}\n \n for crs, prereq in prerequisites:\n d[crs].append(prereq)\n \n visit, cycle = set(), set()\n output = []\n def dfs(crs):\n if crs in cycle:\n return False\n if crs in visit:\n return True\n \n cycle.add(crs)\n for nei in d[crs]:\n if not dfs(nei):\n return False\n cycle.remove(crs)\n visit.add(crs)\n output.append(crs)\n return True\n \n for crs in range(numCourses):\n if not dfs(crs):\n return []\n return output\n \n", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n different online courses numbered from 1 to n . You are given an array courses where courses[i] = [duration i , lastDay i ] indicate that the i th course should be taken continuously for duration i days and must be finished before or on lastDay i . You will start on the 1 st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take .", + "description_images": [], + "constraints": [ + "1 <= courses.length <= 10^4", + "1 <= duration i , lastDay i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput:3\n\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1stcourse, it costs 100 days so you will finish it on the 100thday, and ready to take the next course on the 101stday.\nSecond, take the 3rdcourse, it costs 1000 days so you will finish it on the 1100thday, and ready to take the next course on the 1101stday. \nThird, take the 2ndcourse, it costs 200 days so you will finish it on the 1300thday. \nThe 4thcourse cannot be taken now, since you will finish it on the 3300thday, which exceeds the closed date.", + "image": null + }, + { + "text": "Example 2: Input:courses = [[1,2]]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:courses = [[3,2],[4,3]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 83.06%) | Memory: 54.60 MB (Top 52.82%)\n\nclass Solution {\n public int scheduleCourse(int[][] C) {\n Arrays.sort(C, (a,b) -> a[1] - b[1]);\n PriorityQueue pq = new PriorityQueue<>((a,b) -> b - a);\n int total = 0;\n for (int[] course : C) {\n int dur = course[0], end = course[1];\n if (dur + total <= end) {\n total += dur;\n pq.add(dur);\n } else if (pq.size() > 0 && pq.peek() > dur) {\n total += dur - pq.poll();\n pq.add(dur);\n }\n }\n return pq.size();\n }\n}\n", + "title": "630. Course Schedule III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n different online courses numbered from 1 to n . You are given an array courses where courses[i] = [duration i , lastDay i ] indicate that the i th course should be taken continuously for duration i days and must be finished before or on lastDay i . You will start on the 1 st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take .", + "description_images": [], + "constraints": [ + "1 <= courses.length <= 10^4", + "1 <= duration i , lastDay i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput:3\n\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1stcourse, it costs 100 days so you will finish it on the 100thday, and ready to take the next course on the 101stday.\nSecond, take the 3rdcourse, it costs 1000 days so you will finish it on the 1100thday, and ready to take the next course on the 1101stday. \nThird, take the 2ndcourse, it costs 200 days so you will finish it on the 1300thday. \nThe 4thcourse cannot be taken now, since you will finish it on the 3300thday, which exceeds the closed date.", + "image": null + }, + { + "text": "Example 2: Input:courses = [[1,2]]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:courses = [[3,2],[4,3]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n bool static cmp(vector &a,vector&b) {\n return a[1] < b[1];\n }\n int scheduleCourse(vector>& courses) {\n sort(courses.begin(),courses.end(),cmp);\n int sm = 0;\n priority_queue pq;\n for(int i=0; icourses[i][1]) { \n sm-=pq.top(); // remove the biggest invalid course duration!\n pq.pop();\n }\n }\n return pq.size();\n }\n};\n", + "title": "630. Course Schedule III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 a i first if you want to take course b i . Prerequisites can also be indirect . If course a is a prerequisite of course b , and course b is a prerequisite of course c , then course a is a prerequisite of course c . You are also given an array queries where queries[j] = [u j , v j ] . For the j th query, you should answer whether course u j is a prerequisite of course v j or not. Return a boolean array answer , where answer[j] is the answer to the j th query.", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput:[false,true]\nExplanation:The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-1-graph.jpg" + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput:[false,false]\nExplanation:There are no prerequisites, and each course is independent.", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput:[true,true]", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-3-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1518 ms (Top 5.07%) | Memory: 118.7 MB (Top 6.29%)\nclass Solution {\n public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {\n // Generating Map\n Map> graph = new HashMap<>();\n for(int e[]: prerequisites){\n graph.putIfAbsent(e[0], new ArrayList<>());\n graph.get(e[0]).add(e[1]);\n }\n\n List list = new ArrayList<>();\n // Appling DFS for every query to get result\n for(int[] q: queries){\n list.add(isPre(q[0], q[1], graph, new HashSet<>()));\n }\n return list;\n }\n // Check if src comes before dst using DFS\n private boolean isPre(int src, int dst, Map> adj, Set visited){\n if(visited.contains(src)) return false;\n visited.add(src);\n for(int neigh: adj.getOrDefault(src, new ArrayList<>())){\n if(neigh == dst || isPre(neigh, dst, adj, visited)) return true;\n }\n return false;\n }\n}", + "title": "1462. Course Schedule IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 a i first if you want to take course b i . Prerequisites can also be indirect . If course a is a prerequisite of course b , and course b is a prerequisite of course c , then course a is a prerequisite of course c . You are also given an array queries where queries[j] = [u j , v j ] . For the j th query, you should answer whether course u j is a prerequisite of course v j or not. Return a boolean array answer , where answer[j] is the answer to the j th query.", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput:[false,true]\nExplanation:The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-1-graph.jpg" + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput:[false,false]\nExplanation:There are no prerequisites, and each course is independent.", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput:[true,true]", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-3-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n one approach I can think of is, given a graph, \n the query[a, b] will be true if there exists a path from a to b in the graph\n else a will not be a prerequisite of b\n but this approach may not scale as the # of queries will increase\n \"\"\"\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n graph = {node: set() for node in range(numCourses)}\n for pre in prerequisites:\n graph[pre[0]].add(pre[1])\n \n def path(cur_node, node_b):\n if cur_node == node_b:\n return True\n for neighbor in graph[cur_node]:\n if path(neighbor, node_b):\n return True\n return False\n \n ans = []\n for query in queries:\n # see if there is a path from query[0] to query[1]\n ans.append(path(query[0], query[1]))\n return ans\n", + "title": "1462. Course Schedule IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y , return true if the nodes corresponding to the values x and y in the tree are cousins , or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0 , and children of each depth k node are at the depth k + 1 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "1 <= Node.val <= 100", + "Each node has a unique value.", + "x != y", + "x and y are exist in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4], x = 4, y = 3\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3,null,4], x = 2, y = 3\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/02/13/q1248-03.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 42.36%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isCousins(TreeNode root, int x, int y) {\n \n //If any of x or y is at root, it means they can't be at same depth. Return false.\n if(root.val == x || root.val == y) return false;\n \n \n Deque queue = new LinkedList<>();\n queue.offer(root);\n \n boolean xFound = false;\n boolean yFound = false;\n \n int parentX = 0;\n int parentY = 0;\n \n //Do level-order traversal until x or y is found or queue is empty.\n while(!queue.isEmpty() && !xFound && !yFound){\n \n int size = queue.size();\n\t\t\t\n //Traverse that level.\n while(size-- > 0){\n TreeNode node = queue.poll();\n\t\t\t\t\n //if x or y is found at left/right, save the parent and set the \"found\" flag to true.\n //This flag will break the loop as soon as any one (x or y) is found. \n\t\t\t\t//we don't need to go deeper to find second if it isn't found at this level.\n\t\t\t\t\n if(node.left != null) {\n queue.offer(node.left);\n \n if(node.left.val == x){\n parentX = node.val;\n xFound = true;\n }\n if(node.left.val == y){\n parentY = node.val;\n yFound = true;\n }\n \n }\n\n if(node.right != null) {\n queue.offer(node.right);\n \n if(node.right.val == x){\n parentX = node.val;\n xFound = true;\n }\n if(node.right.val == y){\n parentY = node.val;\n yFound = true;\n }\n }\n }\n \n }\n return xFound && yFound && parentX != parentY;\n }\n}\n", + "title": "993. Cousins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y , return true if the nodes corresponding to the values x and y in the tree are cousins , or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0 , and children of each depth k node are at the depth k + 1 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "1 <= Node.val <= 100", + "Each node has a unique value.", + "x != y", + "x and y are exist in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4], x = 4, y = 3\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3,null,4], x = 2, y = 3\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/02/13/q1248-03.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n ans = False\n def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:\n def dfs(node, depth):\n if self.ans or not node: return 0\n if node.val == x or node.val == y: return depth\n l = dfs(node.left, depth+1)\n r = dfs(node.right, depth+1)\n if not (l and r): return l or r\n if l == r and l != depth + 1: self.ans = True\n return 0\n \n dfs(root, 0)\n return self.ans\n", + "title": "993. Cousins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1] . The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it .", + "description_images": [], + "constraints": [ + "For example, the correct password is \"345\" and you enter in \"012345\" : After typing 0 , the most recent 3 digits is \"0\" , which is incorrect. After typing 1 , the most recent 3 digits is \"01\" , which is incorrect. After typing 2 , the most recent 3 digits is \"012\" , which is incorrect. After typing 3 , the most recent 3 digits is \"123\" , which is incorrect. After typing 4 , the most recent 3 digits is \"234\" , which is incorrect. After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks.", + "After typing 0 , the most recent 3 digits is \"0\" , which is incorrect.", + "After typing 1 , the most recent 3 digits is \"01\" , which is incorrect.", + "After typing 2 , the most recent 3 digits is \"012\" , which is incorrect.", + "After typing 3 , the most recent 3 digits is \"123\" , which is incorrect.", + "After typing 4 , the most recent 3 digits is \"234\" , which is incorrect.", + "After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 2\nOutput:\"10\"\nExplanation:The password is a single digit, so enter each digit. \"01\" would also unlock the safe.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 2\nOutput:\"01100\"\nExplanation:For each possible password:\n- \"00\" is typed in starting from the 4thdigit.\n- \"01\" is typed in starting from the 1stdigit.\n- \"10\" is typed in starting from the 3rddigit.\n- \"11\" is typed in starting from the 2nddigit.\nThus \"01100\" will unlock the safe. \"01100\", \"10011\", and \"11001\" would also unlock the safe.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 5.23%) | Memory: 124.1 MB (Top 5.06%)\n\nclass Solution {\n String ans;\n public String crackSafe(int n, int k) {\n int minLen = (int)Math.pow(k, n) + (n -1);\n\n dfs(\"\", n ,k, new HashSet(),minLen);\n return ans;\n }\n\n private void dfs(String s, int n, int k, HashSetvisited,int minLen){\n if (s.length() == minLen){\n ans = s;\n return;\n }\n if (s.length() > minLen){return;}\n\n for (int i = 0; i < k; i++){\n s += String.valueOf(i);\n String lastN = s.substring(Math.max(0,s.length() - n), s.length());\n //If already in hashset, rollback and continue;\n if (visited.contains(lastN)){\n s = s.substring(0, s.length() - 1);\n continue;}\n if(lastN.length() == n){ // only put n length string in hashset\n visited.add(lastN);\n }\n\n dfs(s,n,k,visited,minLen);\n if (visited.size() == minLen - n + 1){return;} // if hashset contains all possible combinations just return\n visited.remove(lastN);\n s = s.substring(0, s.length() - 1);\n }\n\n }\n}\n", + "title": "753. Cracking the Safe", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1] . The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it .", + "description_images": [], + "constraints": [ + "For example, the correct password is \"345\" and you enter in \"012345\" : After typing 0 , the most recent 3 digits is \"0\" , which is incorrect. After typing 1 , the most recent 3 digits is \"01\" , which is incorrect. After typing 2 , the most recent 3 digits is \"012\" , which is incorrect. After typing 3 , the most recent 3 digits is \"123\" , which is incorrect. After typing 4 , the most recent 3 digits is \"234\" , which is incorrect. After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks.", + "After typing 0 , the most recent 3 digits is \"0\" , which is incorrect.", + "After typing 1 , the most recent 3 digits is \"01\" , which is incorrect.", + "After typing 2 , the most recent 3 digits is \"012\" , which is incorrect.", + "After typing 3 , the most recent 3 digits is \"123\" , which is incorrect.", + "After typing 4 , the most recent 3 digits is \"234\" , which is incorrect.", + "After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 2\nOutput:\"10\"\nExplanation:The password is a single digit, so enter each digit. \"01\" would also unlock the safe.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 2\nOutput:\"01100\"\nExplanation:For each possible password:\n- \"00\" is typed in starting from the 4thdigit.\n- \"01\" is typed in starting from the 1stdigit.\n- \"10\" is typed in starting from the 3rddigit.\n- \"11\" is typed in starting from the 2nddigit.\nThus \"01100\" will unlock the safe. \"01100\", \"10011\", and \"11001\" would also unlock the safe.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 121 ms (Top 27.97%) | Memory: 27.9 MB (Top 17.84%)\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n seen=set()\n def dfs(s,last_n):\n if len(seen)==(k**n): return s\n if len(last_n)();\n for(var log : logs){\n if(log.equals(\"../\")){\n if(!stack.empty())\n stack.pop();\n }else if(log.equals(\"./\")){\n\n }else{\n stack.push(log);\n }\n }\n return stack.size();\n }\n}", + "title": "1598. Crawler Log Folder", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: You are given a list of strings logs where logs[i] is the operation performed by the user at the i th step. The file system starts in the main folder, then the operations in logs are performed. Return the minimum number of operations needed to go back to the main folder after the change folder operations.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/09/sample_11_1957.png", + "https://assets.leetcode.com/uploads/2020/09/09/sample_22_1957.png" + ], + "constraints": [ + "\"../\" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder ).", + "\"./\" : Remain in the same folder.", + "\"x/\" : Move to the child folder named x (This folder is guaranteed to always exist )." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\nOutput:2\nExplanation:Use this change folder operation \"../\" 2 times and go back to the main folder.", + "image": null + }, + { + "text": "Example 2: Input:logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:logs = [\"d1/\",\"../\",\"../\",\"../\"]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n m='../'\n r='./'\n\t\t#create an empty stack\n stk=[]\n\t\t#iterate through the list\n for i in logs:\n\t\t\t#if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack\n if(i==m):\n if(len(stk)>0):\n stk.pop()\n\t\t\t#else if Remain in the same folder (./) operator occurs, do nothing and move to next element in list\n elif(i==r):\n continue\n\t\t\t#else add element to the stack\n else:\n stk.append(i)\n\t\t#now return the size of the stack which would be the minimum number of operations needed to go back to the main folder\n return(len(stk))\n\t\t```", + "title": "1598. Crawler Log Folder", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parent i , child i , isLeft i ] indicates that parent i is the parent of child i in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root . The test cases will be generated such that the binary tree is valid .", + "description_images": [], + "constraints": [ + "If isLeft i == 1 , then child i is the left child of parent i .", + "If isLeft i == 0 , then child i is the right child of parent i ." + ], + "examples": [ + { + "text": "Example 1: Input:descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput:[50,20,80,15,17,19]\nExplanation:The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png" + }, + { + "text": "Example 2: Input:descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput:[1,2,null,null,3,4]\nExplanation:The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode createBinaryTree(int[][] descriptions) {\n HashMap map=new HashMap<>();\n HashSet children=new HashSet<>();\n for(int[] info:descriptions)\n {\n int parent=info[0],child=info[1];\n boolean isLeft=info[2]==1?true:false;\n TreeNode parentNode=null;\n TreeNode childNode=null;\n if(map.containsKey(parent))\n parentNode=map.get(parent);\n else\n parentNode=new TreeNode(parent);\n if(map.containsKey(child))\n childNode=map.get(child);\n else\n childNode=new TreeNode(child);\n if(isLeft)\n parentNode.left=childNode;\n else\n parentNode.right=childNode;\n map.put(parent,parentNode);\n map.put(child,childNode);\n children.add(child);\n \n }\n TreeNode root=null;\n for(int info[]:descriptions)\n {\n if(!children.contains(info[0]))\n {\n root=map.get(info[0]);\n break;\n }\n }\n return root;\n }\n \n \n}", + "title": "2196. Create Binary Tree From Descriptions", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parent i , child i , isLeft i ] indicates that parent i is the parent of child i in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root . The test cases will be generated such that the binary tree is valid .", + "description_images": [], + "constraints": [ + "If isLeft i == 1 , then child i is the left child of parent i .", + "If isLeft i == 0 , then child i is the right child of parent i ." + ], + "examples": [ + { + "text": "Example 1: Input:descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput:[50,20,80,15,17,19]\nExplanation:The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png" + }, + { + "text": "Example 2: Input:descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput:[1,2,null,null,3,4]\nExplanation:The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n hashmap = {}\n nodes = set()\n children = set()\n for parent,child,isLeft in descriptions:\n nodes.add(parent)\n nodes.add(child)\n children.add(child)\n if parent not in hashmap:\n hashmap[parent] = TreeNode(parent)\n if child not in hashmap:\n hashmap[child] = TreeNode(child)\n if isLeft:\n hashmap[parent].left = hashmap[child]\n if not isLeft:\n hashmap[parent].right = hashmap[child]\n \n for node in nodes:\n if node not in children:\n return hashmap[node]\n\n\n\n", + "title": "2196. Create Binary Tree From Descriptions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k . Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer.", + "description_images": [], + "constraints": [ + "m == nums1.length", + "n == nums2.length", + "1 <= m, n <= 500", + "0 <= nums1[i], nums2[i] <= 9", + "1 <= k <= m + n" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\nOutput:[9,8,6,5,3]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [6,7], nums2 = [6,0,4], k = 5\nOutput:[6,7,6,0,4]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [3,9], nums2 = [8,9], k = 3\nOutput:[9,8,9]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 39.80%) | Memory: 117.7 MB (Top 6.97%)\nclass Solution {\n public int[] maxNumber(int[] nums1, int[] nums2, int k) {\n String ans=\"\";\n for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq\n String one = solve(nums1, i); // find the best seq matching len of i\n String two = solve(nums2, k-i); // len of k-i\n StringBuilder sb = new StringBuilder();\n int a = 0, b = 0;\n while(a < i || b < k-i){ // merge it to the max\n sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));\n }\n if (sb.toString().compareTo(ans)>0){ // if better, we replace.\n ans=sb.toString();\n }\n }\n int[] res = new int[k];\n for (int i = 0; i < k;++i){\n res[i]=ans.charAt(i)-'0';\n }\n return res;\n }\n\n private String solve(int[] arr, int k){\n Deque stack = new ArrayDeque<>();\n for (int i = 0;ik&&stack.peek() List[int]:\n m = len(nums1)\n n = len(nums2)\n dp = {}\n \n # get the max number string with \"length\" from index \"i\" in nums1 and index \"j\" in nums2\n # using number string to easy to compare\n def getMaxNumberString(i, j, length):\n if length == 0:\n return \"\"\n \n # using memoization to optimize for the overlapping subproblems\n key = (i, j, length)\n if key in dp:\n return dp[key]\n \n # greedy to find the possible max digit from nums1 and nums2\n # 1) bigger digit in the higher position of the number will get bigger number\n # 2) at the same time, we need to ensure that we still have enough digits to form a number with \"length\" digits\n \n # try to find the possible max digit from index i in nums1\n index1 = None\n for ii in range(i, m):\n if (m - ii + n - j) < length:\n break\n if index1 is None or nums1[index1] < nums1[ii]:\n index1 = ii\n \n # try to find the possible max digit from index j in nums2\n index2 = None\n for jj in range(j, n):\n if (m - i + n - jj) < length:\n break\n if index2 is None or nums2[index2] < nums2[jj]:\n index2 = jj\n \n maxNumberStr = None\n if index1 is not None and index2 is not None:\n if nums1[index1] > nums2[index2]:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif nums1[index1] < nums2[index2]:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n else:\n # get the same digit from nums1 and nums2, so need to try two cases and get the max one \n maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1))\n elif index1 is not None:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif index2 is not None:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n \n dp[key] = maxNumberStr\n return maxNumberStr\n\n result_str = getMaxNumberString(0, 0, k)\n \n # number string to digit array\n result = []\n for c in result_str:\n result.append(int(c))\n \n return result", + "title": "321. Create Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array instructions , you are asked to create a sorted array from the elements in instructions . You start with an empty container nums . For each element from left to right in instructions , insert it into nums . The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5] , the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3 , element 5 is greater than 3 ) and nums will become [1,2,3,3,5] . Return the total cost to insert all elements from instructions into nums . Since the answer may be large, return it modulo 10^9 + 7", + "description_images": [], + "constraints": [ + "The number of elements currently in nums that are strictly less than instructions[i] .", + "The number of elements currently in nums that are strictly greater than instructions[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = [1,5,6,2]\nOutput:1\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\nThe total cost is 0 + 0 + 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:instructions = [1,2,3,6,5,4]\nOutput:3\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:instructions = [1,3,3,3,2,4,2,1,2]\nOutput:4\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 90.0%) | Memory: 59.11 MB (Top 43.3%)\n\nclass Fenwick {\n public int[] tree; //Binary indexed Tree array\n \n //initialize a new Fenwick tree of size length\n public Fenwick(int length) {\n tree = new int[length];\n }\n \n //Returns the sum of values in an array from range [0, i]\n public int sum(int i) {\n int sum = 0;\n while(i > 0) {\n sum += tree[i];\n i = i - (i & -i); //flip the last set bit using 2's compliment\n }\n return sum;\n }\n \n //Returns sum of values in the given range [start, end]\n public int sumRange(int start, int end) {\n return sum(end) - sum(start - 1);\n }\n \n //updates the value at index i by \"k\" in tree\n public void update(int i, int k) {\n while(i < tree.length) {\n tree[i] += k;\n i = i + (i & -i); //add last set bit\n }\n }\n}\nclass Solution {\n public int createSortedArray(int[] instructions) {\n //check for valid instructions\n if(instructions.length == 0) {\n return 0;\n }\n \n /*\n to check for values strictly greater than any ith value in the instructions, we \n need to find the largest value in the instructions, this will denote the range \n\t\t\tof values in the Fenwick tree\n */\n int max = 0;\n for(int value : instructions) {\n if(value > max) {\n max = value;\n }\n }\n \n /*\n initialize a Fenwick Tree structure to allow for the search of all values strictly less than and \n strictly greater than instructions[i].\n \n since we need the tree to be 1 indexed, we add 1 to max\n */\n Fenwick tree = new Fenwick(max + 1);\n int cost = 0;\n \n for(int i = 0; i < instructions.length;i++) {\n int current_value = instructions[i];\n \n //get all the values less and greater than current_value\n int strictly_less = tree.sumRange(0, current_value - 1);\n int strictly_greater = tree.sumRange(current_value + 1, max);\n \n //update cost\n cost += Math.min(strictly_less, strictly_greater);\n \n //cost may be large so we mod it with 10^9 + 7\n cost = cost % ((int)1e9 + 7);\n \n //update the current_value's count in the FW tree\n tree.update(current_value, 1);\n }\n \n return cost;\n }\n}", + "title": "1649. Create Sorted Array through Instructions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array instructions , you are asked to create a sorted array from the elements in instructions . You start with an empty container nums . For each element from left to right in instructions , insert it into nums . The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5] , the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3 , element 5 is greater than 3 ) and nums will become [1,2,3,3,5] . Return the total cost to insert all elements from instructions into nums . Since the answer may be large, return it modulo 10^9 + 7", + "description_images": [], + "constraints": [ + "The number of elements currently in nums that are strictly less than instructions[i] .", + "The number of elements currently in nums that are strictly greater than instructions[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = [1,5,6,2]\nOutput:1\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\nThe total cost is 0 + 0 + 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:instructions = [1,2,3,6,5,4]\nOutput:3\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:instructions = [1,3,3,3,2,4,2,1,2]\nOutput:4\nExplanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5781 ms (Top 22.88%) | Memory: 36.00 MB (Top 13.56%)\n\nclass Fenwick:\n \"\"\"Fenwick tree aka binary indexed tree\"\"\"\n def __init__(self, n):\n self.nums = [0]*(n+1)\n \n def sum(self, k): \n ans = 0\n while k: \n ans += self.nums[k]\n k &= k-1\n return ans \n \n def add(self, i, x): \n i += 1\n while i < len(self.nums): \n self.nums[i] += x\n i += i & -i\n\n\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n ans = 0\n fen = Fenwick(10**5)\n freq = {} # frequency of each instructions\n for i, x in enumerate(instructions): \n less = fen.sum(x)\n more = i - freq.get(x, 0) - less\n ans += min(less, more)\n fen.add(x, 1)\n freq[x] = 1 + freq.get(x, 0)\n return ans % 1_000_000_007\n", + "title": "1649. Create Sorted Array through Instructions", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two arrays of integers nums and index . Your task is to create target array under the following rules: Return the target array. It is guaranteed that the insertion operations will be valid.", + "description_images": [], + "constraints": [ + "Initially target array is empty.", + "From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.", + "Repeat the previous step until there are no elements to read in nums and index." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,3,4], index = [0,1,2,2,1]\nOutput:[0,4,1,3,2]\nExplanation:nums index target\n0 0 [0]\n1 1 [0,1]\n2 2 [0,1,2]\n3 2 [0,1,3,2]\n4 1 [0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,0], index = [0,1,2,3,0]\nOutput:[0,1,2,3,4]\nExplanation:nums index target\n1 0 [1]\n2 1 [1,2]\n3 2 [1,2,3]\n4 3 [1,2,3,4]\n0 0 [0,1,2,3,4]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], index = [0]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def createTargetArray(self, nums, index):\n \n def merge(arr, low, mid, high):\n L, R = arr[low:mid+1], arr[mid+1:high+1]\n i = j = 0\n k = low\n \n while i < len(L) and j < len(R):\n if L[i][0] + j >= R[j][0]:\n arr[k] = R[j]\n j += 1\n else:\n L[i][0] += j\n arr[k] = L[i]\n i += 1\n k += 1\n \n while i < len(L):\n L[i][0] += j\n arr[k] = L[i]\n i += 1; k += 1\n \n while j < len(R):\n arr[k] = R[j]\n j += 1; k += 1\n \n \n def mergeSort(arr, low, high):\n if low < high:\n mid = (low + high) // 2\n mergeSort(arr, low, mid)\n mergeSort(arr, mid + 1, high)\n merge(arr, low, mid, high)\n \n arr = [[index[i], nums[i]] for i in range(len(nums))]\n mergeSort(arr, 0, len(nums) - 1)\n \n for x in arr:\n nums[x[0]] = x[1]\n \n return nums", + "title": "1389. Create Target Array in the Given Order", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [a i , b i ] represents a connection between servers a i and b i . Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "n - 1 <= connections.length <= 10^5", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no repeated connections." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput:[[1,3]]\nExplanation:[[3,1]] is also accepted.", + "image": "https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png" + }, + { + "text": "Example 2: Input:n = 2, connections = [[0,1]]\nOutput:[[0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 74.61%) | Memory: 107.90 MB (Top 55.73%)\n\nclass Solution {\n // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection\n public List> criticalConnections(int n, List> connections) {\n List[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(List oneConnection :connections) {\n graph[oneConnection.get(0)].add(oneConnection.get(1));\n graph[oneConnection.get(1)].add(oneConnection.get(0));\n }\n int timer[] = new int[1];\n List> results = new ArrayList<>();\n boolean[] visited = new boolean[n];\n int []timeStampAtThatNode = new int[n]; \n criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode);\n return results;\n }\n \n \n public void criticalConnectionsUtil(List[] graph, int parent, int node, int timer[], boolean[] visited, List> results, int []timeStampAtThatNode) {\n visited[node] = true;\n timeStampAtThatNode[node] = timer[0]++;\n int currentTimeStamp = timeStampAtThatNode[node];\n \n for(int oneNeighbour : graph[node]) {\n if(oneNeighbour == parent) continue;\n if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode);\n timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]);\n if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour));\n }\n \n \n }\n \n}\n", + "title": "1192. Critical Connections in a Network", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [a i , b i ] represents a connection between servers a i and b i . Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "n - 1 <= connections.length <= 10^5", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no repeated connections." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput:[[1,3]]\nExplanation:[[3,1]] is also accepted.", + "image": "https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png" + }, + { + "text": "Example 2: Input:n = 2, connections = [[0,1]]\nOutput:[[0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \n dic = collections.defaultdict(list)\n for c in connections:\n u, v = c\n dic[u].append(v)\n dic[v].append(u)\n \n \n timer = 0\n \n depth, lowest, parent, visited = [float(\"inf\")]*n, [float(\"inf\")]*n, [float(\"inf\")]*n, [False]*n\n res = []\n \n def find(u):\n \n nonlocal timer\n \n visited[u] = True\n depth[u], lowest[u] = timer, timer\n timer += 1\n \n for v in dic[u]: \n \n if not visited[v]:\n parent[v] = u\n find(v)\n if lowest[v]>depth[u]:\n res.append([u,v])\n \n if parent[u]!=v:\n lowest[u] = min(lowest[u], lowest[v])\n \n find(0)\n return res\n ", + "title": "1192. Critical Connections in a Network", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order , then x should occur before y in the permuted string. Return any permutation of s that satisfies this property .", + "description_images": [], + "constraints": [ + "1 <= order.length <= 26", + "1 <= s.length <= 200", + "order and s consist of lowercase English letters.", + "All the characters of order are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:order = \"cba\", s = \"abcd\"\nOutput:\"cbad\"\nExplanation:\"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.", + "image": null + }, + { + "text": "Example 2: Input:order = \"cbafg\", s = \"abcd\"\nOutput:\"cbad\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 38.18%)\n\nclass Solution {\n public String customSortString(String X, String Y) {\n //char count of string Y\n int[] charCount = new int[26];\n for(char c : Y.toCharArray()){\n charCount[c - 'a']++;\n }\n \n StringBuilder sb = new StringBuilder();\n \n //first store char in same order of String X\n for(char c : X.toCharArray()){\n while(charCount[c - 'a'] --> 0){\n sb.append(c);\n }\n }\n \n //now store remaining char of string Y\n for(int i = 0; i < 26; i++){\n char c = (char)('a' + i);\n while(charCount[i] --> 0){\n sb.append(c);\n }\n }\n \n return sb.toString();\n }\n}\n", + "title": "791. Custom Sort String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order , then x should occur before y in the permuted string. Return any permutation of s that satisfies this property .", + "description_images": [], + "constraints": [ + "1 <= order.length <= 26", + "1 <= s.length <= 200", + "order and s consist of lowercase English letters.", + "All the characters of order are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:order = \"cba\", s = \"abcd\"\nOutput:\"cbad\"\nExplanation:\"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.", + "image": null + }, + { + "text": "Example 2: Input:order = \"cbafg\", s = \"abcd\"\nOutput:\"cbad\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 328 ms (Top 5.22%) | Memory: 13.9 MB (Top 17.87%)\nclass Solution:\n def customSortString(self, order: str, s: str) -> str:\n charValue = [0] * 26\n for i in range(len(order)):\n idx = ord(order[i]) - ord('a')\n charValue[idx] = 26 - i\n\n arrS = []\n n = 0\n for c in s:\n arrS.append(c)\n n += 1\n\n sorted = False\n while not sorted:\n sorted = True\n for i in range(n - 1):\n if charValue[ord(arrS[i]) - ord('a')] < charValue[ord(arrS[i + 1]) - ord('a')]:\n sorted = False\n arrS[i], arrS[i + 1] = arrS[i + 1], arrS[i]\n\n return ''.join(arrS)", + "title": "791. Custom Sort String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix: In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off. You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell). Starting from the point (0, 0) , return the minimum steps you need to walk to cut off all the trees . If you cannot cut off all the trees, return -1 . Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.", + "description_images": [], + "constraints": [ + "0 means the cell cannot be walked through.", + "1 represents an empty cell that can be walked through.", + "A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height." + ], + "examples": [ + { + "text": "Example 1: Input:forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput:6\nExplanation:Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.", + "image": "https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg" + }, + { + "text": "Example 2: Input:forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput:-1\nExplanation:The trees in the bottom row cannot be accessed as the middle row is blocked.", + "image": "https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg" + }, + { + "text": "Example 3: Input:forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput:6\nExplanation:You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 273 ms (Top 92.8%) | Memory: 44.58 MB (Top 18.0%)\n\nclass Solution {\n //approach: 1st store all the positions in the min heap acc. to their height\n //now start removing the elements from the heap and calculate their dis using bfs\n // if at any point we cann't reach at the next position return -1;\n // else keep on adding the distances and return;\n public int cutOffTree(List> forest) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n for(int i=0;i1)\n pq.add(new int[]{i,j});\n }\n }\n int ans=0;\n int curr[]={0,0};\n while(pq.size()>0){\n int[] temp=pq.poll();\n int dis=calcDis(forest,curr,temp);\n //System.out.println(dis+\" \"+temp.height);\n if(dis==-1)\n return -1;\n ans+=dis;\n curr=temp;\n }\n return ans;\n }\n int calcDis(List> forest,int start[],int end[]){\n int n=forest.size(),m=forest.get(0).size();\n boolean vis[][]=new boolean[n][m];\n Queue queue=new LinkedList<>();\n queue.add(start);\n vis[start[0]][start[1]]=true;\n int dis=0;\n while(queue.size()>0){\n int len =queue.size();\n while(len-->0){\n int temp[]=queue.remove();\n int r=temp[0],c=temp[1];\n if(r==end[0] && c==end[1])\n return dis;\n if(r+1=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n queue.add(new int[]{r-1,c});\n vis[r-1][c]=true;\n }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n queue.add(new int[]{r,c-1});\n vis[r][c-1]=true;\n }if(c+1 int:\n a = []\n n = len(forest)\n m = len(forest[0])\n for i in range(n):\n for j in range(m):\n if forest[i][j] > 1:\n a.append(forest[i][j])\n a.sort()\n \n s = 0\n ux = 0\n uy = 0\n for h in a:\n dist = [[None] * m for i in range(n)]\n q = deque()\n q.append((ux, uy))\n dist[ux][uy] = 0\n while q:\n ux, uy = q.popleft()\n if forest[ux][uy] == h:\n break\n d = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n for dx, dy in d:\n vx = ux + dx\n vy = uy + dy\n if vx < 0 or vx >= n or vy < 0 or vy >= m:\n continue\n if forest[vx][vy] == 0:\n continue\n if dist[vx][vy] is None:\n q.append((vx, vy))\n dist[vx][vy] = dist[ux][uy] + 1\n if forest[ux][uy] == h:\n s += dist[ux][uy]\n else:\n return -1\n return s\n", + "title": "675. Cut Off Trees for Golf Event", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid ​​​, where m and n are both even integers, and an integer k . The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "Both m and n are even integers.", + "1 <= grid[i][j] <= 5000", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[40,10],[30,20]], k = 1\nOutput:[[10,20],[40,30]]\nExplanation:The figures above represent the grid at every state.", + "image": "https://assets.leetcode.com/uploads/2021/06/19/rod2.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\nOutput:[[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\nExplanation:The figures above represent the grid at every state.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] rotateGrid(int[][] grid, int k) {\n int m = grid.length, n = grid[0].length, noOfLayers = Math.min(m/2, n/2); \n // Peeling each layer one by one\n for(int layerNo = 0; layerNo < noOfLayers; layerNo++){\n // Please suggest if you have better way to find perimeter of matrix on a given layer!\n int perimeter = (m-(2*layerNo)) + (n-(2*layerNo)-1) + (m-(2*layerNo)-1) + (n-(2*layerNo)-2); \n int[] layer = new int[perimeter]; // this out be use to store that particular layer\n readLayer(grid, layer, layerNo, m, n); // this will read the layer\n writeLayer(grid, layer, layerNo, m, n, k); // this will rotate it by k and write back the layer \n }\n return grid;\n }\n \n public void readLayer(int[][] grid, int[] layer, int layerNo, int m, int n){\n int count = 0, r = layerNo, c = layerNo;\n m--; n--;\n // read left a -> c\n for(int i = layerNo; i < n - layerNo; i++) layer[count++] = grid[layerNo][i];\n // read down c -> i\n for(int i = layerNo; i < m - layerNo; i++) layer[count++] = grid[i][n-layerNo];\n // read right i -> g\n for(int i = n-layerNo; i > layerNo; i--) layer[count++] = grid[m-layerNo][i];\n // read up g -> a\n for(int i = m-layerNo; i > layerNo; i--) layer[count++] = grid[i][layerNo];\n }\n \n public void writeLayer(int[][] grid, int[] layer, int layerNo, int m, int n, int k){\n m--; n--;\n int len = layer.length, count = k; \n // write left a -> c\n for(int i = layerNo; i < n - layerNo; i++){\n count %= len; // reason if goes out of length start back from 0\n grid[layerNo][i] = layer[count++];\n }\n // write down c -> i\n for(int i = layerNo; i < m - layerNo; i++){\n count %= len;\n grid[i][n-layerNo] = layer[count++];\n } \n // write right i -> g\n for(int i = n-layerNo; i > layerNo; i--){\n count %= len;\n grid[m-layerNo][i] = layer[count++];\n }\n // write up g -> a\n for(int i = m-layerNo; i > layerNo; i--){\n count %= len;\n grid[i][layerNo] = layer[count++];\n } \n }\n \n \n}\n", + "title": "1914. Cyclically Rotating a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n integer matrix grid ​​​, where m and n are both even integers, and an integer k . The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "Both m and n are even integers.", + "1 <= grid[i][j] <= 5000", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[40,10],[30,20]], k = 1\nOutput:[[10,20],[40,30]]\nExplanation:The figures above represent the grid at every state.", + "image": "https://assets.leetcode.com/uploads/2021/06/19/rod2.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\nOutput:[[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\nExplanation:The figures above represent the grid at every state.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n n = len(grid)\n m = len(grid[0])\n \n i, j = 0, 0\n bottom, right = n-1, m-1 \n while i < n//2 and j < m//2:\n temp = []\n for x in range(j, right):\n temp.append(grid[i][x])\n for x in range(i, bottom):\n temp.append(grid[x][right])\n for x in range(right, j, -1):\n temp.append(grid[bottom][x])\n for x in range(bottom, i, -1):\n temp.append(grid[x][j])\n \n \n indx = 0\n for x in range(j, right):\n grid[i][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(i, bottom):\n grid[x][right] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(right, j, -1):\n grid[bottom][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(bottom, i, -1):\n grid[x][j] = temp[(k + indx)%len(temp)]\n indx += 1\n \n i += 1\n j += 1\n bottom -= 1\n right -= 1\n return grid\n", + "title": "1914. Cyclically Rotating a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= temperatures.length <= 10^5", + "30 <= temperatures[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:temperatures = [73,74,75,71,69,72,76,73]\nOutput:[1,1,4,2,1,1,0,0]", + "image": null + }, + { + "text": "Example 2: Input:temperatures = [30,40,50,60]\nOutput:[1,1,1,0]", + "image": null + }, + { + "text": "Example 3: Input:temperatures = [30,60,90]\nOutput:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 207 ms (Top 22.03%) | Memory: 127.9 MB (Top 72.12%)\nclass Solution {\n public int[] dailyTemperatures(int[] temperatures) {\n HashMaphm=new HashMap<>();\n Stackst=new Stack<>();\n for(int i=0;i0&&temperatures[i]>temperatures[st.peek()]){\n hm.put(st.pop(),i);\n }\n st.push(i);\n }\n int []ans=new int[temperatures.length];\n for(int i=0;i T[s[-1]]:\n ans[s[-1]] = cur - s[-1]\n s.pop()\n s.append(cur)\n return ans\n", + "title": "739. Daily Temperatures", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a data stream input of non-negative integers a 1 , a 2 , ..., a n , summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class:", + "description_images": [], + "constraints": [ + "SummaryRanges() Initializes the object with an empty stream.", + "void addNum(int val) Adds the integer val to the stream.", + "int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start i , end i ] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]Output[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]ExplanationSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1); // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3); // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7); // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2); // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 169 ms (Top 23.71%) | Memory: 73.9 MB (Top 52.59%)\nclass SummaryRanges {\n\n Map st;\n Map end;\n Set pending;\n int[][] prev = new int[0][];\n Set seen = new HashSet<>();\n int INVALID = -1;\n public SummaryRanges() {\n st = new HashMap<>();\n end= new HashMap<>();\n pending = new HashSet<>();\n }\n\n public void addNum(int val) { // [TC: O(1)]\n if (!seen.contains(val)){ // only add if not seen.\n pending.add(val); // pending processing list\n }\n }\n\n public int[][] getIntervals() { // [TC: O(pending list length (= k)) best case (all merges), O(n)+O(klogk) worst case (all inserts)]\n Set addSet = new HashSet<>();\n for (int n : pending){\n if (st.containsKey(n+1)&&end.containsKey(n-1)){ // merge intervals on both ends, a new interval form -> add to addSet\n int[] s = st.get(n+1);\n int[] e = end.get(n-1);\n int[] m = new int[]{e[0], s[1]};\n st.remove(n+1);\n end.remove(n-1);\n st.put(m[0], m);\n end.put(m[1], m);\n s[0]=e[0]=INVALID;\n addSet.remove(s); // may be in addSet, remove them\n addSet.remove(e);\n addSet.add(m);\n }else if (st.containsKey(n+1)){ // merge with the next interval, no other action required.\n st.get(n+1)[0]--;\n st.put(n, st.get(n+1));\n st.remove(n+1);\n }else if (end.containsKey(n-1)){ // merge with the previous interval, no other action required.\n end.get(n-1)[1]++;\n end.put(n, end.get(n-1));\n end.remove(n-1);\n }else{ // new interval -> add to AddSet\n int[] m = new int[]{n, n};\n addSet.add(m);\n st.put(n, m);\n end.put(n, m);\n }\n }\n\n seen.addAll(pending);\n pending.clear(); // remember to clear the pending list.\n\n if (!addSet.isEmpty()){ // IF there is no new intervals to insert, we SKIP this.\n List addList = new ArrayList<>(addSet);\n addList.sort(Comparator.comparingInt(o -> o[0]));\n int i = 0, j = 0; // two pointers because both prev & addList are sorted.\n List ans = new ArrayList<>();\n while(i < prev.length || j < addList.size()){\n if (i < prev.length && prev[i][0]==INVALID){\n i++;\n }else if (j == addList.size() || i < prev.length && prev[i][0]addList.get(j)[0]){\n ans.add(addList.get(j++));\n }\n }\n prev = ans.toArray(new int[0][]);\n }\n\n return prev;\n }\n}", + "title": "352. Data Stream as Disjoint Intervals", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a data stream input of non-negative integers a 1 , a 2 , ..., a n , summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class:", + "description_images": [], + "constraints": [ + "SummaryRanges() Initializes the object with an empty stream.", + "void addNum(int val) Adds the integer val to the stream.", + "int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start i , end i ] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]Output[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]ExplanationSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1); // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3); // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7); // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2); // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]", + "image": null + } + ], + "follow_up": null, + "solution": "class SummaryRanges:\n def __init__(self):\n self.intervals = []\n def addNum(self, val: int) -> None:\n left, right = 0, len(self.intervals) - 1\n while left <= right:\n mid = (left + right) // 2\n e = self.intervals[mid]\n if e[0] <= val <= e[1]: return\n elif val < e[0]:right = mid - 1\n else:left = mid + 1\n pos = left\n self.intervals.insert(pos, [val, val])\n if pos + 1 < len(self.intervals) and val + 1 == self.intervals[pos+1][0]:\n self.intervals[pos][1] = self.intervals[pos+1][1]\n del self.intervals[pos+1]\n if pos - 1 >= 0 and val - 1 == self.intervals[pos-1][1]:\n self.intervals[pos-1][1] = self.intervals[pos][1]\n del self.intervals[pos]\n\n def getIntervals(self) -> List[List[int]]:\n return self.intervals\n", + "title": "352. Data Stream as Disjoint Intervals", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day , month and year respectively. Return the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"} .", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:day = 31, month = 8, year = 2019\nOutput:\"Saturday\"", + "image": null + }, + { + "text": "Example 2: Input:day = 18, month = 7, year = 1999\nOutput:\"Sunday\"", + "image": null + }, + { + "text": "Example 3: Input:day = 15, month = 8, year = 1993\nOutput:\"Sunday\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String dayOfTheWeek(int day, int month, int year) {\n String[] week = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n year--;\n int total = (year/4)*366+(year-year/4)*365;\n int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n year++;\n if(year%4==0 && year!=2100){\n months[1]++;\n }\n for(int i=0;i str:\n LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5\n DAYS = (\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\n difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR), (day, month, year))\n return DAYS[(difference + DAY) % 7]\n\n def daysBetweenDates(self, date1: tuple, date2: tuple) -> int:\n LOWEST_YEAR = 1971\n\n def daysSinceLowest(date: tuple) -> int:\n day, month, year = date\n\n isLeapYear = lambda x: 1 if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else 0\n\n days: int = 0\n # days between the LOWEST_YEAR and year\n days += 365 * (year - LOWEST_YEAR) + sum(map(isLeapYear, range(LOWEST_YEAR, year)))\n # days between year and exact date\n daysInMonth = (31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n days += sum(daysInMonth[:month - 1]) + day\n return days\n\n return abs(daysSinceLowest(date1) - daysSinceLowest(date2))", + "title": "1185. Day of the Week", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year .", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"\nOutput:9\nExplanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"\nOutput:41", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 18.15%) | Memory: 44.20 MB (Top 65.48%)\n\nclass Solution {\n public int dayOfYear(String date) {\n int days = 0;\n int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};\n String[] year = date.split(\"-\");\n int y = Integer.valueOf(year[0]);\n int month = Integer.valueOf(year[1]);\n int day = Integer.valueOf(year[2]);\n boolean leap = false;\n for(int i = 0; i < month-1; i++){\n days = days+arr[i];\n }\n days = days+day;\n if(y%4==0){\n if(y%100==0){\n if(y%400==0){\n leap = true;\n }\n else{\n leap = false;\n }\n }\n else{\n leap = true;\n }\n }\n else{\n leap = false;\n }\n if(leap==true && month>2){\n System.out.println(\"Leap Year\");\n days = days+1;\n }\n return days;\n }\n}\n", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year .", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"\nOutput:9\nExplanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"\nOutput:41", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int dayOfYear(String date) {\n int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n int year = (date.charAt(0)-48)*1000+(date.charAt(1)-48)*100+(date.charAt(2)-48)*10+date.charAt(3)-48;\n if(year%4==0 && year!=1900){\n months[1]++;\n }\n int ans = 0;\n for(int i=0;i<((date.charAt(5)-48)*10)+date.charAt(6)-48-1;i++){\n ans += months[i];\n }\n ans += (date.charAt(8)-48)*10+date.charAt(9)-48;\n return ans;\n }\n}", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year .", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"\nOutput:9\nExplanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"\nOutput:41", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 123 ms (Top 44.98%) | Memory: 14 MB (Top 32.35%)\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}\n year=int(date[:4])\n if year%4==0:\n if year%100==0:\n if year%400==0:\n d[2]=29\n else:\n d[2]=29\n month=int(date[5:7])\n day=int(date[8:])\n ans=0\n for i in range(1,month+1):\n ans+=d[i]\n return ans-(d[month]-day)", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"\nOutput:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"\nOutput:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"\nOutput:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 46.14%) | Memory: 16.20 MB (Top 85.67%)\n\nclass Solution:\n def decodeString(self, s):\n it, num, stack = 0, 0, [\"\"]\n while it < len(s):\n if s[it].isdigit():\n num = num * 10 + int(s[it])\n elif s[it] == \"[\":\n stack.append(num)\n num = 0\n stack.append(\"\")\n elif s[it] == \"]\":\n str1 = stack.pop()\n rep = stack.pop()\n str2 = stack.pop()\n stack.append(str2 + str1 * rep)\n else:\n stack[-1] += s[it] \n it += 1 \n return \"\".join(stack)\n", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"\nOutput:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"\nOutput:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"\nOutput:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.88%) | Memory: 41.8 MB (Top 72.85%)\nclass Solution {\n public String decodeString(String s) {\n\n int bb = s.indexOf('['); // location of beginning bracket\n int nbb = s.indexOf('[', bb + 1); // location of next beginning bracket\n int eb = s.indexOf(']'); // location of ending bracket\n\n int n = 0; // number of times to repeat\n int nl = 1; // number of digits for n\n char nd; // next digit\n\n String insert = \"\"; // repeated string\n String end = \"\"; // remainder of string after repeated portion\n\n while (bb != -1) { // while the string contains a beginning bracket\n\n while (nbb < eb && nbb > bb) { // while the next beginning bracket is before the ending bracket\n bb = nbb; // update location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // update location of next beginning bracket\n }\n\n nl = 1; // reset length of n\n while (bb - nl >= 0) { // while there are characters in front of the beginning bracket\n nd = s.charAt(bb - nl); // next digit\n if (nd <= '9' && nd >= '0') { // if next digit is an integer\n n += (int)(nd - '0') * Math.pow(10, nl - 1); // update value of n\n nl++; // increment length of n\n }\n else break; // not an integer\n }\n\n insert = s.substring(bb + 1, eb); // set repeated string\n end = s.substring(eb + 1); // set remainder of string\n s = s.substring(0, bb - nl + 1); // remove everything after the digits\n\n while (n > 0) {\n s += insert; // add repeated string n times\n n--;\n }\n s += end; // add remainder of string\n\n bb = s.indexOf('['); // new location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // new location of next beginning bracket\n eb = s.indexOf(']'); // new location of ending bracket\n }\n return s;\n }\n}", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"\nOutput:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"\nOutput:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"\nOutput:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeString(self, s: str) -> str:\n stk = []\n \n for i in range(len(s)):\n \n if s[i] != ']':\n stk.append(s[i]) \n else:\n strr = ''\n while stk[-1] != '[':\n strr = stk.pop() + strr\n stk.pop()\n \n num = ''\n while stk and stk[-1].isdigit():\n num = stk.pop() + num\n \n stk.append(int(num) * strr)\n \n return ''.join(stk)\n \n \n ", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the strings key and message , which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Return the decoded message .", + "description_images": [], + "constraints": [ + "For example, given key = \" hap p y bo y\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ( 'h' -> 'a' , 'a' -> 'b' , 'p' -> 'c' , 'y' -> 'd' , 'b' -> 'e' , 'o' -> 'f' )." + ], + "examples": [ + { + "text": "Example 1: Input:key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\nOutput:\"this is a secret\"\nExplanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"thequickbrownfoxjumpsover thelazydog\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex1new4.jpg" + }, + { + "text": "Example 2: Input:key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\nOutput:\"the five boxing wizards jump quickly\"\nExplanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 48.65%) | Memory: 44.7 MB (Top 35.73%)\nclass Solution {\n public String decodeMessage(String key, String message) {\n StringBuilder ans = new StringBuilder();//Using String Builder to append the string\n key = key.replaceAll(\" \", \"\");\n //Removing the spaces\n HashMap letters = new HashMap<>();\n //Mapping the key into a hashmap.\n char original = 'a';\n for (int i = 0; i < key.length() ; i++) {\n if (!letters.containsKey(key.charAt(i))){\n letters.put(key.charAt(i),original++);\n }\n }\n //After the first pass all the letters of the key will be mapped with their respective original letters.\n for (int i = 0; i < message.length(); i++) {\n if (letters.containsKey(message.charAt(i))){\n //Now replacing the letters of the message with appropriate letter according to the key\n ans.append(letters.get(message.charAt(i)));\n }else{\n ans.append(message.charAt(i));\n //This is for characters other than the letters in the key example a space \" \"\n //They will not be replaced by any letters hence original letter is appended into the StringBuilder\n }\n }\n return ans.toString();\n }\n}", + "title": "2325. Decode the Message", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the strings key and message , which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Return the decoded message .", + "description_images": [], + "constraints": [ + "For example, given key = \" hap p y bo y\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ( 'h' -> 'a' , 'a' -> 'b' , 'p' -> 'c' , 'y' -> 'd' , 'b' -> 'e' , 'o' -> 'f' )." + ], + "examples": [ + { + "text": "Example 1: Input:key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\nOutput:\"this is a secret\"\nExplanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"thequickbrownfoxjumpsover thelazydog\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex1new4.jpg" + }, + { + "text": "Example 2: Input:key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\nOutput:\"the five boxing wizards jump quickly\"\nExplanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 94.64%) | Memory: 17.30 MB (Top 36.34%)\n\nclass Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n mapping = {' ': ' '}\n i = 0\n res = ''\n letters = 'abcdefghijklmnopqrstuvwxyz'\n \n for char in key:\n if char not in mapping:\n mapping[char] = letters[i]\n i += 1\n \n for char in message:\n res += mapping[char]\n \n return res", + "title": "2325. Decode the Message", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows . originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText . The arrow indicates the order in which the cells are filled. All empty cells are filled with ' ' . The number of columns is chosen such that the rightmost column will not be empty after filling in originalText . encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText , then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = \"cipher\" and rows = 3 , then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\" . Given the encoded string encodedText and number of rows rows , return the original string originalText . Note: originalText does not have any trailing spaces ' ' . The test cases are generated such that there is only one possible originalText .", + "description_images": [], + "constraints": [ + "0 <= encodedText.length <= 10^6", + "encodedText consists of lowercase English letters and ' ' only.", + "encodedText is a valid encoding of some originalText that does not have trailing spaces.", + "1 <= rows <= 1000", + "The testcases are generated such that there is only one possible originalText ." + ], + "examples": [ + { + "text": "Example 1: Input:encodedText = \"ch ie pr\", rows = 3\nOutput:\"cipher\"\nExplanation:This is the same example described in the problem description.", + "image": null + }, + { + "text": "Example 2: Input:encodedText = \"iveo eed l te olc\", rows = 4\nOutput:\"i love leetcode\"\nExplanation:The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/exam1.png" + }, + { + "text": "Example 3: Input:encodedText = \"coding\", rows = 1\nOutput:\"coding\"\nExplanation:Since there is only 1 row, both originalText and encodedText are the same.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/eg2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 15.7%) | Memory: 54.11 MB (Top 92.9%)\n\nclass Solution {\n public String decodeCiphertext(String str, int rows) {\n\n //first find column size!!\n \tint cols=str.length()/rows;\n \tStringBuilder res=new StringBuilder(),new_res=new StringBuilder();;\n \tfor(int i=0;i=0;i--) {\n \n if(fg==0&&res.charAt(i)==' ')\n continue;\n fg=1;\n new_res.append(res.charAt(i));\n }\n return new_res.reverse().toString();\n }\n}", + "title": "2075. Decode the Slanted Ciphertext", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows . originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText . The arrow indicates the order in which the cells are filled. All empty cells are filled with ' ' . The number of columns is chosen such that the rightmost column will not be empty after filling in originalText . encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText , then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = \"cipher\" and rows = 3 , then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\" . Given the encoded string encodedText and number of rows rows , return the original string originalText . Note: originalText does not have any trailing spaces ' ' . The test cases are generated such that there is only one possible originalText .", + "description_images": [], + "constraints": [ + "0 <= encodedText.length <= 10^6", + "encodedText consists of lowercase English letters and ' ' only.", + "encodedText is a valid encoding of some originalText that does not have trailing spaces.", + "1 <= rows <= 1000", + "The testcases are generated such that there is only one possible originalText ." + ], + "examples": [ + { + "text": "Example 1: Input:encodedText = \"ch ie pr\", rows = 3\nOutput:\"cipher\"\nExplanation:This is the same example described in the problem description.", + "image": null + }, + { + "text": "Example 2: Input:encodedText = \"iveo eed l te olc\", rows = 4\nOutput:\"i love leetcode\"\nExplanation:The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/exam1.png" + }, + { + "text": "Example 3: Input:encodedText = \"coding\", rows = 1\nOutput:\"coding\"\nExplanation:Since there is only 1 row, both originalText and encodedText are the same.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n n = len(encodedText)\n cols = n // rows\n step = cols + 1\n res = \"\"\n \n for i in range(cols):\n for j in range(i, n, step):\n res += encodedText[j]\n \n return res.rstrip()", + "title": "2075. Decode the Slanted Ciphertext", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . Given a string s containing only digits, return the number of ways to decode it . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"12\"\nOutput:2\nExplanation:\"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).", + "image": null + }, + { + "text": "Example 2: Input:s = \"226\"\nOutput:3\nExplanation:\"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).", + "image": null + }, + { + "text": "Example 3: Input:s = \"06\"\nOutput:0\nExplanation:\"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numDecodings(String s) {\n int[]dp = new int[s.length() + 1];\n dp[0] = 1;\n dp[1] = s.charAt(0) == '0' ? 0 : 1;\n \n for(int i = 2;i<=s.length();i++) {\n int oneDigit = Integer.valueOf(s.substring(i-1,i));\n int twoDigit = Integer.valueOf(s.substring(i-2,i));\n \n if(oneDigit >= 1) {\n dp[i] += dp[i - 1];\n }\n if(twoDigit >= 10 && twoDigit <= 26) {\n dp[i] += dp[i - 2];\n }\n }\n return dp[s.length()];\n }\n}\n", + "title": "91. Decode Ways", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . Given a string s containing only digits, return the number of ways to decode it . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"12\"\nOutput:2\nExplanation:\"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).", + "image": null + }, + { + "text": "Example 2: Input:s = \"226\"\nOutput:3\nExplanation:\"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).", + "image": null + }, + { + "text": "Example 3: Input:s = \"06\"\nOutput:0\nExplanation:\"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 48 ms (Top 59.57%) | Memory: 14.1 MB (Top 30.54%)\nclass Solution:\n def numDecodings(self, s: str) -> int:\n if s[0] == '0' or '00' in s:\n return 0\n l = len(s)\n if l == 1:\n return 1\n elif l == 2:\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n return 1\n else:\n return 0\n else:\n if int(s) <= 26:\n return 2\n else:\n return 1\n dp = [1]\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n dp.append(1)\n else:\n return 0\n else:\n if int(s[:2]) <= 26:\n dp.append(2)\n else:\n dp.append(1)\n for i in range(2, l):\n num = 0\n if s[i] == '0':\n if s[i-1] != '1' and s[i-1] != '2':\n return 0\n else:\n num = dp[i-2]\n elif s[i-1] == '1' or (s[i-1] == '2' and int(f'{s[i-1]}{s[i]}') <= 26):\n num = dp[i-1]+dp[i-2]\n else:\n num = dp[i-1]\n dp.append(num)\n return dp[l-1]", + "title": "91. Decode Ways", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ( '0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\" , \"12\" , \"13\" , \"14\" , \"15\" , \"16\" , \"17\" , \"18\" , or \"19\" . Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent. Given a string s consisting of digits and '*' characters, return the number of ways to decode it . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"*\"\nOutput:9\nExplanation:The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1*\"\nOutput:18\nExplanation:The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"2*\"\nOutput:15\nExplanation:The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1171 ms (Top 5.16%) | Memory: 49 MB (Top 90.58%)\nclass Solution {\n public int numDecodings(String s) {\n int[] dp = new int[s.length()+1];\n dp[0]=1;\n int M = (int)1e9+7;\n for (int i = 1; i <= s.length(); i++){\n for (int j = 1; j <= 26; j++){\n if (j<10 && (s.charAt(i-1)-'0'==j||s.charAt(i-1)=='*')){ // 1 digit -> if they are equal or if *\n dp[i]+=dp[i-1];\n dp[i]%=M;\n }\n if (i>1&&j>=10&&ok(j,s.substring(i-2,i))){ // ok() function handles 2 digits\n dp[i]+=dp[i-2];\n dp[i]%=M;\n }\n }\n }\n return dp[s.length()];\n }\n\n private boolean ok(int val, String s){ // TRUE if the value s represents can equal to val.\n return (s.equals(\"**\") && val%10 > 0\n || s.charAt(0)=='*' && val%10==s.charAt(1)-'0'\n || s.charAt(1)=='*' && val/10==s.charAt(0)-'0' && val % 10 > 0\n || !s.contains(\"*\") && Integer.parseInt(s)==val);\n }\n}", + "title": "639. Decode Ways II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ( '0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\" , \"12\" , \"13\" , \"14\" , \"15\" , \"16\" , \"17\" , \"18\" , or \"19\" . Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent. Given a string s consisting of digits and '*' characters, return the number of ways to decode it . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"*\"\nOutput:9\nExplanation:The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1*\"\nOutput:18\nExplanation:The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"2*\"\nOutput:15\nExplanation:The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 180 ms (Top 97.4%) | Memory: 21.20 MB (Top 53.7%)\n\nclass Solution:\n def numDecodings(self, s: str):\n if s[0] == '0': return 0\n cMap = {'0':0, '*': 9, '**': 15, '1*': 9, '2*': 6} #{char(s) : multiplier} mapping\n for i in range(1, 27): cMap[str(i)] = 1\n for i in range(0, 7): cMap['*'+str(i)] = 2\n for i in range(7, 10): cMap['*'+str(i)] = 1\n \n dp = [0]*(len(s)+1)\n dp[0], dp[-1] = cMap[s[0]] , 1\n \n for i in range(1, len(s)):\n dp[i] += (cMap[s[i]]*dp[i-1] + cMap.get(s[i-1:i+1],0)*dp[i-2])%(10**9 + 7)\n if not dp[i]: return 0\n \n return dp[-2]", + "title": "639. Decode Ways II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = arr[i] XOR arr[i + 1] . For example, if arr = [1,0,2,1] , then encoded = [1,2,3] . You are given the encoded array. You are also given an integer first , that is the first element of arr , i.e. arr[0] . Return the original array arr . It can be proved that the answer exists and is unique.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^4", + "encoded.length == n - 1", + "0 <= encoded[i] <= 10^5", + "0 <= first <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [1,2,3], first = 1\nOutput:[1,0,2,1]\nExplanation:If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,2,7,3], first = 4\nOutput:[4,2,0,7,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 83.89%) | Memory: 55.1 MB (Top 84.00%)\nclass Solution {\n public int[] decode(int[] encoded, int first) {\n int[] ans = new int[encoded.length + 1];\n ans[0] = first;\n for (int i = 0; i < encoded.length; i++) {\n ans[i + 1] = ans[i] ^ encoded[i];\n }\n return ans;\n }\n}", + "title": "1720. Decode XORed Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = arr[i] XOR arr[i + 1] . For example, if arr = [1,0,2,1] , then encoded = [1,2,3] . You are given the encoded array. You are also given an integer first , that is the first element of arr , i.e. arr[0] . Return the original array arr . It can be proved that the answer exists and is unique.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^4", + "encoded.length == n - 1", + "0 <= encoded[i] <= 10^5", + "0 <= first <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [1,2,3], first = 1\nOutput:[1,0,2,1]\nExplanation:If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,2,7,3], first = 4\nOutput:[4,2,0,7,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]\n", + "title": "1720. Decode XORed Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd . It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = perm[i] XOR perm[i + 1] . For example, if perm = [1,3,2] , then encoded = [2,1] . Given the encoded array, return the original array perm . It is guaranteed that the answer exists and is unique.", + "description_images": [], + "constraints": [ + "3 <= n < 10^5", + "n is odd.", + "encoded.length == n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [3,1]\nOutput:[1,2,3]\nExplanation:If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,5,4,6]\nOutput:[2,4,1,5,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decode(int[] encoded) {\n int n = encoded.length+1, all = 0;\n for(int i = 1; i <= n; ++i){//a^b^c^d^e^f^g^h^i\n all ^= i;\n }\n int x = 0;\n for(int v : encoded){//a^b b^c c^d d^e e^f f^g g^h h^i = a^i\n x ^= v;\n }\n int mid = all^x; //a^b^c^d^e^f^g^h^i ^ a^i = b^c^d^e^f^g^h\n for(int i = 1, j = encoded.length-2; i < j;i += 2, j -= 2){\n //(b^c^d^e^f^g^h) ^ (b^c ^ g^h ^ d^e ^ e^f) = e\n mid ^= encoded[i]^encoded[j];\n }\n int[] ans = new int[n];\n ans[n/2] = mid;\n //a b c d e f g h i\n //a^b b^c c^d d^e e^f f^g g^h h^i\n for(int i = n/2+1; i < n; ++i){\n ans[i] = encoded[i-1]^ans[i-1];\n }\n for(int i = n/2-1; i >= 0; --i){\n ans[i] = encoded[i]^ans[i+1];\n }\n return ans;\n }\n}\n", + "title": "1734. Decode XORed Permutation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd . It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = perm[i] XOR perm[i + 1] . For example, if perm = [1,3,2] , then encoded = [2,1] . Given the encoded array, return the original array perm . It is guaranteed that the answer exists and is unique.", + "description_images": [], + "constraints": [ + "3 <= n < 10^5", + "n is odd.", + "encoded.length == n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [3,1]\nOutput:[1,2,3]\nExplanation:If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,5,4,6]\nOutput:[2,4,1,5,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1921 ms (Top 32.18%) | Memory: 33.8 MB (Top 16.09%)\n\nfrom functools import reduce\nfrom operator import xor\n\nclass Solution:\n\n def decode(self, encoded: List[int]) -> List[int]:\n n = len(encoded) + 1\n a = reduce(xor, range(1, n+1))\n b = reduce(xor, encoded[1::2])\n result = [a ^ b]\n for y in encoded:\n result.append(result[-1] ^ y)\n return result", + "title": "1734. Decode XORed Permutation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an encoded string s . To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: Given an integer k , return the k th letter ( 1-indexed) in the decoded string .", + "description_images": [], + "constraints": [ + "If the character read is a letter, that letter is written onto the tape.", + "If the character read is a digit d , the entire current tape is repeatedly written d - 1 more times in total." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet2code3\", k = 10\nOutput:\"o\"\nExplanation:The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10thletter in the string is \"o\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ha22\", k = 5\nOutput:\"h\"\nExplanation:The decoded string is \"hahahaha\".\nThe 5thletter is \"h\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a2345678999999999999999\", k = 1\nOutput:\"a\"\nExplanation:The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1stletter is \"a\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String decodeAtIndex(String s, int k) {\n long sz = 0;\n for (char ch : s.toCharArray()){ // total length\n sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;\n }\n --k; // make it 0 index based.\n for (int i = s.length() - 1; true; i--){\n if (Character.isLetter(s.charAt(i)) && --sz == k){ // found!\n return \"\"+s.charAt(i);\n }else if(Character.isDigit(s.charAt(i))){\n sz /= (s.charAt(i) - '0');\n k %= sz; // we are at the end of a multplied string, we can mod k with sz.\n }\n }\n }\n}\n", + "title": "880. Decoded String at Index", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an encoded string s . To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: Given an integer k , return the k th letter ( 1-indexed) in the decoded string .", + "description_images": [], + "constraints": [ + "If the character read is a letter, that letter is written onto the tape.", + "If the character read is a digit d , the entire current tape is repeatedly written d - 1 more times in total." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet2code3\", k = 10\nOutput:\"o\"\nExplanation:The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10thletter in the string is \"o\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ha22\", k = 5\nOutput:\"h\"\nExplanation:The decoded string is \"hahahaha\".\nThe 5thletter is \"h\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a2345678999999999999999\", k = 1\nOutput:\"a\"\nExplanation:The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1stletter is \"a\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n idx = {}\n acclens = [0]\n prevd = 1\n j = 0\n for i, c in enumerate(S + '1'):\n if c.isalpha():\n idx[acclens[-1] * prevd + j] = i\n j += 1\n else:\n acclens.append(acclens[-1] * prevd + j)\n prevd = int(c)\n j = 0\n k = K - 1\n for al in reversed(acclens[1:]):\n k %= al\n if k in idx:\n return S[idx[k]]\n return None # should never reach this\n", + "title": "880. Decoded String at Index", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0 ).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "nums.length % 2 == 0", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[2,4,4,4]\nExplanation:The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,3]\nOutput:[1,3,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decompressRLElist(int[] nums) {\n ArrayList arr = new ArrayList<>();\n for (int i = 0; i+1 < nums.length; i += 2) {\n for (int j = 0; j < nums[i]; ++j) {\n arr.add(nums[i+1]);\n }\n }\n int[] res = new int[arr.size()];\n for (int i = 0; i < res.length; ++i) res[i] = arr.get(i);\n return res;\n }\n}\n", + "title": "1313. Decompress Run-Length Encoded List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0 ).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "nums.length % 2 == 0", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[2,4,4,4]\nExplanation:The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,3]\nOutput:[1,3,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decompressRLElist(self, nums: List[int]) -> List[int]:\n answer = []\n \n for i in range(0, len(nums), 2):\n for j in range(0, nums[i]):\n answer.append(nums[i + 1])\n \n return answer\n", + "title": "1313. Decompress Run-Length Encoded List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1 . An array A is a zigzag array if either: Return the minimum number of moves to transform the given array nums into a zigzag array.", + "description_images": [], + "constraints": [ + "Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...", + "OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ..." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:2\nExplanation:We can decrease 2 to 0 or 3 to 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,6,1,6,2]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /*\n firstly, check elements in odd indices are greater than its neighbours.\n if not, decrease its neigbours and update the cost.\n \n do same thing for even indices, because there can be two combinations as indicated in question.\n */\n \n private int calculateCost(int[] nums, int start){\n int res = 0;\n int n = nums.length;\n int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.\n \n for(int i=start;i= cur){\n res += prev-cur +1;\n arr[i-1] = cur-1;\n } \n \n if(next >= cur){\n res += next-cur +1;\n arr[i+1] = cur-1;\n }\n }\n return res;\n }\n \n public int movesToMakeZigzag(int[] nums) {\n return Math.min(calculateCost(nums, 0), calculateCost(nums,1));\n }\n}\n", + "title": "1144. Decrease Elements To Make Array Zigzag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1 . An array A is a zigzag array if either: Return the minimum number of moves to transform the given array nums into a zigzag array.", + "description_images": [], + "constraints": [ + "Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...", + "OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ..." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:2\nExplanation:We can decrease 2 to 0 or 3 to 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,6,1,6,2]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solve(self,arr,n,x):\n idx = 1\n ans = 0\n while idx < n:\n if idx == 0: idx += 1\n if idx % 2 == x:\n if arr[idx-1] >= arr[idx]:\n ans += arr[idx-1] - arr[idx] + 1\n arr[idx-1] = arr[idx] - 1\n idx = idx-1\n else:\n idx = idx+1\n else:\n if arr[idx-1] <= arr[idx]:\n ans += arr[idx] - arr[idx - 1] + 1\n arr[idx] = arr[idx-1] - 1\n idx += 1 \n return ans\n \n def movesToMakeZigzag(self, nums: List[int]) -> int:\n ans1 = self.solve([x for x in nums],len(nums),0)\n ans2 = self.solve([x for x in nums],len(nums),1)\n return min(ans1,ans2)\n", + "title": "1144. Decrease Elements To Make Array Zigzag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s formed by digits and '#' . We want to map s to English lowercase characters as follows: Return the string formed after mapping . The test cases are generated so that a unique mapping will always exist.", + "description_images": [], + "constraints": [ + "Characters ( 'a' to 'i' ) are represented by ( '1' to '9' ) respectively.", + "Characters ( 'j' to 'z' ) are represented by ( '10#' to '26#' ) respectively." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10#11#12\"\nOutput:\"jkab\"\nExplanation:\"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1326#\"\nOutput:\"acz\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.3%) | Memory: 40.72 MB (Top 56.6%)\n\nclass Solution {\n public String freqAlphabets(String str) {\n HashMap map = new HashMap<>();\n int k = 1;\n for (char ch = 'a'; ch <= 'z'; ch++) {\n if (ch < 'j')\n map.put(String.valueOf(k++), ch);\n else\n map.put(String.valueOf(k++)+\"#\", ch);\n }\n \n StringBuilder sb = new StringBuilder();\n int i = str.length() - 1;\n while (i >= 0) {\n if (str.charAt(i) == '#') {\n sb.append(map.get(str.substring(i - 2, i+1)));\n i -= 3;\n } else {\n sb.append(map.get(str.substring(i, i + 1)));\n i--;\n }\n }\n \n return sb.reverse().toString();\n }\n}", + "title": "1309. Decrypt String from Alphabet to Integer Mapping", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s formed by digits and '#' . We want to map s to English lowercase characters as follows: Return the string formed after mapping . The test cases are generated so that a unique mapping will always exist.", + "description_images": [], + "constraints": [ + "Characters ( 'a' to 'i' ) are represented by ( '1' to '9' ) respectively.", + "Characters ( 'j' to 'z' ) are represented by ( '10#' to '26#' ) respectively." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10#11#12\"\nOutput:\"jkab\"\nExplanation:\"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1326#\"\nOutput:\"acz\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n for i in range(26,0,-1): s = s.replace(str(i)+\"#\"*(i>9),chr(96+i))\n return s", + "title": "1309. Decrypt String from Alphabet to Integer Mapping", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput:15", + "image": "https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" + }, + { + "text": "Example 2: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput:19", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 8.75%) | Memory: 59.3 MB (Top 36.23%)\nclass Solution {\n public int height(TreeNode root)\n {\n if(root == null)\n return 0;\n return Math.max(height(root.left), height(root.right)) + 1;\n }\n public int deepestLeavesSum(TreeNode root) {\n if(root == null) return 0;\n if(root.left == null && root.right == null) return root.val;\n Queue q = new LinkedList<>();\n q.add(root);\n q.add(null);\n int hght = height(root);\n int sum = 0;\n while(q.size()>0 && q.peek()!=null)\n {\n TreeNode temp = q.remove();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n if(q.peek() == null)\n {\n q.remove();\n q.add(null);\n hght--;\n }\n if(hght == 1)\n {\n while(q.size()>0 && q.peek()!=null)\n {\n sum+=q.remove().val;\n }\n }\n\n }\n return sum;\n }\n}", + "title": "1302. Deepest Leaves Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput:15", + "image": "https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" + }, + { + "text": "Example 2: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput:19", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n \n \"\"\"\n THOUGHT PROCESS:\n 1) find the height of the tree, this way we would know how deep we need to go.\n 2) we need a counter to check how deep we are and this is not available in deepestLeavesSum so we create a new function deepestLeave.\n 3) now we go in depth, if we are at bottom, we return the value, we recursively visit both left and right nodes.\n \n \"\"\"\n \n def height(self, root):\n if root is None:\n return 0\n else:\n x, y = 1, 1\n if root.left:\n x = self.height(root.left)+1\n if root.right:\n y = self.height(root.right)+1\n \n return max(x, y)\n \n \n def deepestLeave(self, root, depth):\n \n if root is None:\n return 0\n \n if root.left is None and root.right is None:\n if depth == 1:\n return root.val\n \n return self.deepestLeave(root.left, depth-1) + self.deepestLeave(root.right, depth-1)\n \n def deepestLeavesSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.deepestLeave(root, self.height(root))\n \n \n \n \n \n", + "title": "1302. Deepest Leaves Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a valid (IPv4) IP address , return a defanged version of that IP address. A defanged IP address replaces every period \".\" with \"[.]\" .", + "description_images": [], + "constraints": [ + "The given address is a valid IPv4 address." + ], + "examples": [ + { + "text": "Example 1: Input:address = \"1.1.1.1\"\nOutput:\"1[.]1[.]1[.]1\"", + "image": null + }, + { + "text": "Example 2: Input:address = \"255.100.50.0\"\nOutput:\"255[.]100[.]50[.]0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String defangIPaddr(String address) {\n return address.replace(\".\",\"[.]\");\n }\n}\n", + "title": "1108. Defanging an IP Address", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a valid (IPv4) IP address , return a defanged version of that IP address. A defanged IP address replaces every period \".\" with \"[.]\" .", + "description_images": [], + "constraints": [ + "The given address is a valid IPv4 address." + ], + "examples": [ + { + "text": "Example 1: Input:address = \"1.1.1.1\"\nOutput:\"1[.]1[.]1[.]1\"", + "image": null + }, + { + "text": "Example 2: Input:address = \"255.100.50.0\"\nOutput:\"255[.]100[.]50[.]0\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 6.11%) | Memory: 16.10 MB (Top 75.91%)\n\nclass Solution:\n\tdef defangIPaddr(self, address: str) -> str:\n\t\treturn address.replace('.', '[.]')\n", + "title": "1108. Defanging an IP Address", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k . To decrypt the code, you must replace every number. All the numbers are replaced simultaneously . As code is circular, the next element of code[n-1] is code[0] , and the previous element of code[0] is code[n-1] . Given the circular array code and an integer key k , return the decrypted code to defuse the bomb !", + "description_images": [], + "constraints": [ + "If k > 0 , replace the i th number with the sum of the next k numbers.", + "If k < 0 , replace the i th number with the sum of the previous k numbers.", + "If k == 0 , replace the i th number with 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:code = [5,7,1,4], k = 3\nOutput:[12,10,16,13]\nExplanation:Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.", + "image": null + }, + { + "text": "Example 2: Input:code = [1,2,3,4], k = 0\nOutput:[0,0,0,0]\nExplanation:When k is zero, the numbers are replaced by 0.", + "image": null + }, + { + "text": "Example 3: Input:code = [2,4,9,3], k = -2\nOutput:[12,5,6,13]\nExplanation:The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of thepreviousnumbers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decrypt(int[] code, int k) {\n int[] res = new int[code.length];\n if (k == 0) return res;\n //Define the initial window and initial sum\n int start = 1, end = k, sum = 0;\n if (k < 0) {//If k < 0, the starting point will be end of the array.\n k = -k;\n start = code.length - k;\n end = code.length - 1;\n }\n for (int i = start; i <= end; i++) sum += code[i];\n //Scan through the code array as i moving to the right, update the window sum.\n for (int i = 0; i < code.length; i++) {\n res[i] = sum;\n sum -= code[(start++) % code.length];\n sum += code[(++end) % code.length];\n }\n return res;\n }\n}\n", + "title": "1652. Defuse the Bomb", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty array of non-negative integers nums , the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums , that has the same degree as nums .", + "description_images": [], + "constraints": [ + "nums.length will be between 1 and 50,000.", + "nums[i] will be an integer between 0 and 49,999." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3,1]\nOutput:2\nExplanation:The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,3,1,4,2]\nOutput:6\nExplanation:The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 84.55%) | Memory: 49.70 MB (Top 5.99%)\n\nclass Solution {\n public int findShortestSubArray(int[] nums) {\n // The int is an array of [firstEncounter, lastEncounter, frequency]\n HashMap map = new HashMap<>();\n for(int i = 0; i < nums.length; i++){\n\n // If the key does not exist in the map, we put it with the first encounter and last encounter set to the current position, 'i', and the freqency 1\n if(!map.containsKey(nums[i])){\n map.put(nums[i], new int[]{i, i, 1});\n } \n\n // If it does exist, we update the last encounter to the current position and we increase the frequency by 1\n else {\n int[] arr = map.get(nums[i]);\n arr[1] = i;\n arr[2]++;\n map.put(nums[i], arr);\n }\n }\n // Maximim frequency\n int maxFreq = Integer.MIN_VALUE;\n\n // Minimum distance\n int minDist = Integer.MAX_VALUE;\n\n // Going through all the values of the HashMap\n for(int[] value : map.values()){\n // value[0] = the first encounter index\n // value[1] = the last encounter index\n // value[2] = frequency\n\n // If the frecuency is greater than the maxFreq, then we update it and also set the minDist\n if(value[2] > maxFreq){\n maxFreq = value[2];\n minDist = value[1] - value[0] + 1;\n } \n\n // If the frecuency is equal to the current max, we take the minimum between the exiting minDist and the minimum distance for the current value\n else if(value[2] == maxFreq){\n minDist = Math.min(minDist, value[1] - value[0] + 1);\n }\n }\n return minDist;\n }\n}\n", + "title": "697. Degree of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a non-empty array of non-negative integers nums , the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums , that has the same degree as nums .", + "description_images": [], + "constraints": [ + "nums.length will be between 1 and 50,000.", + "nums[i] will be an integer between 0 and 49,999." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3,1]\nOutput:2\nExplanation:The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,3,1,4,2]\nOutput:6\nExplanation:The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 198 ms (Top 78.1%) | Memory: 18.99 MB (Top 16.6%)\n\nclass Solution:\n def findShortestSubArray(self, nums):\n # Group indexes by element type\n d = defaultdict(list)\n for i,x in enumerate(nums):\n d[x].append(i)\n #\n # Find highest Degree\n m = max([ len(v) for v in d.values() ])\n #\n # Find shortest span for max. degree\n best = len(nums)\n for v in d.values():\n if len(v)==m:\n best = min(best,v[-1]-v[0]+1)\n return best", + "title": "697. Degree of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You want to maximize the number of points you get by performing the following operation any number of times: Return the maximum number of points you can earn by applying the above operation some number of times .", + "description_images": [], + "constraints": [ + "Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,2]\nOutput:6\nExplanation:You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,3,3,3,4]\nOutput:9\nExplanation:You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 44.61%) | Memory: 44.9 MB (Top 82.96%)\nclass Solution {\n public int deleteAndEarn(int[] nums) {\n Arrays.sort(nums);\n int onePreviousAgo = 0;\n int previous = 0;\n for(int i = 0; i < nums.length; i++) {\n int sum = 0;\n // On hop there's no constraint to add the previous value\n if(i > 0 && nums[i-1] < nums[i] - 1) {\n onePreviousAgo = previous;\n }\n // Accumulate equal values\n while(i < nums.length - 1 && nums[i] == nums[i+1]) {\n sum += nums[i];\n i++;\n }\n int currentPrevious = previous;\n previous = Math.max(\n onePreviousAgo + nums[i] + sum,\n previous\n );\n onePreviousAgo = currentPrevious;\n // System.out.println(nums[i] + \":\" + previous);\n }\n return previous;\n }\n}", + "title": "740. Delete and Earn", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . You want to maximize the number of points you get by performing the following operation any number of times: Return the maximum number of points you can earn by applying the above operation some number of times .", + "description_images": [], + "constraints": [ + "Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,2]\nOutput:6\nExplanation:You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,3,3,3,4]\nOutput:9\nExplanation:You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n count = Counter(nums)\n m = max(nums)\n memo = {}\n def choose(num):\n if num > m:\n return 0\n if num not in count:\n count[num] = 0\n if num in memo:\n return memo[num]\n memo[num] = max(choose(num + 1), num * count[num] + choose(num + 2))\n return memo[num]\n \n return choose(1)\n\n# time and space complexity\n# n = max(nums)\n# time: O(n)\n# space: O(n)\n \n \n", + "title": "740. Delete and Earn", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s , delete the minimum possible number of characters from s to make it fancy . Return the final string after the deletion . It can be shown that the answer will always be unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leeetcode\"\nOutput:\"leetcode\"\nExplanation:Remove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabaaaa\"\nOutput:\"aabaa\"\nExplanation:Remove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\"\nOutput:\"aab\"\nExplanation:No three consecutive characters are equal, so return \"aab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String makeFancyString(String s) {\n char prev = s.charAt (0);\n int freq = 1;\n StringBuilder res = new StringBuilder ();\n res.append (s.charAt (0));\n for (int i = 1; i < s.length (); i++) {\n if (s.charAt (i) == prev)\n freq++;\n else {\n prev = s.charAt (i);\n freq = 1;\n }\n if (freq < 3)\n res.append (s.charAt (i));\n }\n return res.toString ();\n }\n}\n", + "title": "1957. Delete Characters to Make Fancy String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s , delete the minimum possible number of characters from s to make it fancy . Return the final string after the deletion . It can be shown that the answer will always be unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leeetcode\"\nOutput:\"leetcode\"\nExplanation:Remove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabaaaa\"\nOutput:\"aabaa\"\nExplanation:Remove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\"\nOutput:\"aab\"\nExplanation:No three consecutive characters are equal, so return \"aab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeFancyString(self, s: str) -> str:\n if len(s) < 3:\n return s\n ans = ''\n ans += s[0]\n ans += s[1]\n for i in range(2,len(s)):\n if s[i] != ans[-1] or s[i] != ans[-2]:\n ans += s[i]\n return ans\n", + "title": "1957. Delete Characters to Make Fancy String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of n strings strs , all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as: You want to delete the columns that are not sorted lexicographically . In the above example (0-indexed), columns 0 ( 'a' , 'b' , 'c' ) and 2 ( 'c' , 'e' , 'e' ) are sorted while column 1 ( 'b' , 'c' , 'a' ) is not, so you would delete column 1. Return the number of columns that you will delete .", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 1000", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"cba\",\"daf\",\"ghi\"]\nOutput:1\nExplanation:The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"a\",\"b\"]\nOutput:0\nExplanation:The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput:3\nExplanation:The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.", + "image": null + }, + { + "text": "abc\nbce\ncae", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 91.77%) | Memory: 42.4 MB (Top 94.00%)\nclass Solution {\n public int minDeletionSize(String[] strs) {\n int count = 0;\n for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column\n for(int j = 0; j < strs.length-1; j++){\n if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(i)){\n continue;\n }else{\n count++;\n break;\n }\n }\n }\n return count;\n }\n}", + "title": "944. Delete Columns to Make Sorted", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of n strings strs , all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as: You want to delete the columns that are not sorted lexicographically . In the above example (0-indexed), columns 0 ( 'a' , 'b' , 'c' ) and 2 ( 'c' , 'e' , 'e' ) are sorted while column 1 ( 'b' , 'c' , 'a' ) is not, so you would delete column 1. Return the number of columns that you will delete .", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 1000", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"cba\",\"daf\",\"ghi\"]\nOutput:1\nExplanation:The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"a\",\"b\"]\nOutput:0\nExplanation:The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput:3\nExplanation:The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.", + "image": null + }, + { + "text": "abc\nbce\ncae", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 330 ms (Top 23.27%) | Memory: 14.6 MB (Top 66.82%)\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n cols={}\n l=len(strs)\n l_s = len(strs[0])\n delete = set()\n for i in range(l):\n for col in range(l_s):\n if col in cols:\n if cols[col]>strs[i][col]:\n delete.add(col)\n cols[col] = strs[i][col]\n return len(delete)", + "title": "944. Delete Columns to Make Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of n strings strs , all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3} , then the final array after deletions is [\"bef\", \"vyz\"] . Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1] ). Return the minimum possible value of answer.length .", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"ca\",\"bb\",\"ac\"]\nOutput:1\nExplanation:After deleting the first column, strs = [\"a\", \"b\", \"c\"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"xc\",\"yb\",\"za\"]\nOutput:0\nExplanation:strs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput:3\nExplanation:We have to delete every column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDeletionSize(String[] strs) {\n boolean[] sorted = new boolean[strs.length];\n int res = 0;\n for(int i = 0;istrs[j+1].charAt(i)){\n res++;\n break;\n } \n }\n if(j int:\n n = len(strs)\n col_size = len(strs[0])\n # a b c d e f g h i j k l m n o p q r s t u v w x y z\n \n i = 0\n ans = 0\n \n def getRemoved(idx):\n # removing the idx column \n for x in range(n): \n strs[x] = strs[x][:idx] + strs[x][idx+1:]\n \n while i < col_size:\n tmp = strs[0][:i+1]\n flag = True\n similar = False\n \n for j in range(1,n): \n if strs[j][:i+1] < tmp :\n # previous element is larger ( unsorted )\n flag = False\n break\n \n elif strs[j][:i+1] > tmp : \n # previous element is smaller ( sorted )\n tmp = strs[j][:i+1]\n \n else:\n # previous element is equal ( not clear )\n tmp = strs[j][:i+1]\n similar = True\n \n if flag == True and similar == False:\n # all are sorted and we are ready to return ans\n return ans\n \n elif flag == True and similar == True:\n # all are sorted but can't be decided for further columns. check for next col\n i += 1\n \n elif flag == False:\n # unsorted column = removal\n getRemoved(i)\n # increment the answer and since we removed i th col decrement col_size\n ans += 1\n col_size -= 1\n \n return ans\n", + "title": "955. Delete Columns to Make Sorted II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n strings strs , all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3} , then the final array after deletions is [\"bef\", \"vyz\"] . Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]) , and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]) , and so on). Return the minimum possible value of answer.length .", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"babca\",\"bbazb\"]\nOutput:3\nExplanation:After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"edcba\"]\nOutput:4\nExplanation:If we delete less than 4 columns, the only row will not be lexicographically sorted.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"ghi\",\"def\",\"abc\"]\nOutput:0\nExplanation:All rows are already lexicographically sorted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 95.45%) | Memory: 16.80 MB (Top 79.55%)\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n n = len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n valid = True\n for a in strs:\n if a[j] > a[i]: \n valid = False\n break\n if valid:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n", + "title": "960. Delete Columns to Make Sorted III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths , where paths[i] is an array representing an absolute path to the i th folder in the file system. Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical , then mark the folders as well as all their subfolders. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order .", + "description_images": [], + "constraints": [ + "For example, [\"one\", \"two\", \"three\"] represents the path \"/one/two/three\" ." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"a\"],[\"c\"],[\"d\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"d\",\"a\"]]\nOutput:[[\"d\"],[\"d\",\"a\"]]\nExplanation:The file structure is as shown.\nFolders \"/a\" and \"/c\" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named \"b\".", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder1.jpg" + }, + { + "text": "Example 2: Input:paths = [[\"a\"],[\"c\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"a\",\"b\",\"x\"],[\"a\",\"b\",\"x\",\"y\"],[\"w\"],[\"w\",\"y\"]]\nOutput:[[\"c\"],[\"c\",\"b\"],[\"a\"],[\"a\",\"b\"]]\nExplanation:The file structure is as shown. \nFolders \"/a/b/x\" and \"/w\" (and their subfolders) are marked for deletion because they both contain an empty folder named \"y\".\nNote that folders \"/a\" and \"/c\" are identical after the deletion, but they are not deleted because they were not marked beforehand.", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder2.jpg" + }, + { + "text": "Example 3: Input:paths = [[\"a\",\"b\"],[\"c\",\"d\"],[\"c\"],[\"a\"]]\nOutput:[[\"c\"],[\"c\",\"d\"],[\"a\"],[\"a\",\"b\"]]\nExplanation:All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter.", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder3.jpg" + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self):\n self.children = defaultdict(Node)\n self.hash = ''\n self.deleted = False\n \n def add(self, path, i=0):\n if i != len(path):\n self.children[path[i]].add(path, i + 1)\n \n def calc_hash(self, hashes, name='root'):\n for child_name, child in sorted(self.children.items()):\n self.hash += f'{child.calc_hash(hashes, child_name)}+'\n if self.hash:\n hashes[self.hash].append(self)\n return f'{name}({self.hash})'\n \n def to_list(self, lst, path=[]):\n for name, node in self.children.items():\n if not node.deleted:\n lst.append(path + [name])\n node.to_list(lst, path + [name])\n\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n root = Node()\n for path in paths:\n root.add(path)\n hash_to_nodes = defaultdict(list)\n root.calc_hash(hash_to_nodes)\n for nodes in hash_to_nodes.values():\n if len(nodes) > 1:\n for node in nodes:\n node.deleted = True\n res = []\n root.to_list(res)\n return res\n", + "title": "1948. Delete Duplicate Folders in System", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a binary tree root and an integer target , delete all the leaf nodes with value target . Note that once you delete a leaf node with value target , if its parent node becomes a leaf node and has the value target , it should also be deleted (you need to continue doing that until you cannot).", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png", + "https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png", + "https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3000] .", + "1 <= Node.val, target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,2,null,2,4], target = 2\nOutput:[1,null,3,null,4]\nExplanation:Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).", + "image": null + }, + { + "text": "Example 2: Input:root = [1,3,3,3,2], target = 3\nOutput:[1,3,null,null,2]", + "image": null + }, + { + "text": "Example 3: Input:root = [1,2,null,2,null,2], target = 2\nOutput:[1]\nExplanation:Leaf nodes in green with value (target = 2) are removed at each step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode removeLeafNodes(TreeNode root, int target) {\n if(root==null)\n return root;\n root.left = removeLeafNodes(root.left,target);\n root.right = removeLeafNodes(root.right,target);\n if(root.left == null && root.right == null && root.val == target)\n root = null;\n return root;\n }\n}", + "title": "1325. Delete Leaves With a Given Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root and an integer target , delete all the leaf nodes with value target . Note that once you delete a leaf node with value target , if its parent node becomes a leaf node and has the value target , it should also be deleted (you need to continue doing that until you cannot).", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png", + "https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png", + "https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3000] .", + "1 <= Node.val, target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,2,null,2,4], target = 2\nOutput:[1,null,3,null,4]\nExplanation:Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).", + "image": null + }, + { + "text": "Example 2: Input:root = [1,3,3,3,2], target = 3\nOutput:[1,3,null,null,2]", + "image": null + }, + { + "text": "Example 3: Input:root = [1,2,null,2,null,2], target = 2\nOutput:[1]\nExplanation:Leaf nodes in green with value (target = 2) are removed at each step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:\n if not root:\n return None\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target)\n if not root.left and not root.right and root.val == target:\n return None\n return root\n", + "title": "1325. Delete Leaves With a Given Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3\nOutput:[5,4,6,2,null,null,7]\nExplanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0\nOutput:[5,3,6,2,4,null,7]\nExplanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.92 MB (Top 83.3%)\n\nclass Solution {\n public TreeNode deleteNode(TreeNode root, int key) {\n if(root==null) return null;\n \n if(keyroot.val){\n root.right = deleteNode(root.right,key);\n return root;\n }\n \n else{\n if(root.left==null){\n return root.right;\n }\n else if(root.right==null){\n return root.left;\n }\n else{\n TreeNode min = root.right;\n while(min.left!=null){\n min = min.left;\n }\n \n root.val = min.val;\n root.right = deleteNode(root.right,min.val);\n return root;\n }\n }\n }\n}", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3\nOutput:[5,4,6,2,null,null,7]\nExplanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0\nOutput:[5,3,6,2,4,null,7]\nExplanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\ndef deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n\ndef find_inorder(root, key):\n\n\tif root is None :\n\t\treturn []\n\n\treturn find_inorder(root.left, key) + [root.val] + find_inorder(root.right, key)\n\ndef find_preorder(root, key):\n\n\tif root is None:\n\t\treturn []\n\n\treturn [root.val] + find_preorder(root.left,key) + find_preorder(root.right, key)\n\npreorder = find_preorder(root, key)\n\ntry:\n\tpreorder.remove(key)\nexcept:\n\treturn root\n\ninorder = find_inorder(root, key)\n\ninorder.remove(key)\n\n\n\n\nhashmap = {}\n\nfor i in range(len(inorder)):\n\tkey = inorder[i]\n\thashmap[key] = i\n\ndef buildTree(left, right):\n\n\tif left > right:\n\t\treturn \n\n\tval = inorder[left]\n\troot = TreeNode(val)\n\n\tindex = hashmap[val]\n\n\troot.left = buildTree(left, index-1)\n\troot.right = buildTree(index+1, right)\n\n\treturn root\n\nN = len(inorder)\nnew_tree = buildTree(0,N-1)\n\nreturn new_tree\n\n\n", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list.", + "description_images": [], + "constraints": [ + "The number of the nodes in the given list is in the range [2, 1000] .", + "-1000 <= Node.val <= 1000", + "The value of each node in the list is unique .", + "The node to be deleted is in the list and is not a tail node" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,5,1,9], node = 5\nOutput:[4,1,9]\nExplanation:You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node1.jpg" + }, + { + "text": "Example 2: Input:head = [4,5,1,9], node = 1\nOutput:[4,5,9]\nExplanation:You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 44.5 MB (Top 10.41%)\nclass Solution {\n public void deleteNode(ListNode node) {\n\n // 4 5 1 9 : Node = 5\n\n node.val = node.next.val;\n\n //Copy next node val to current node.\n //4 1 1 9\n // ------------\n\n //Point node.next = node.next.next\n // 4 -----> 1 ----> 9\n\n node.next = node.next.next;\n // 4 1 9\n }\n}", + "title": "237. Delete Node in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list.", + "description_images": [], + "constraints": [ + "The number of the nodes in the given list is in the range [2, 1000] .", + "-1000 <= Node.val <= 1000", + "The value of each node in the list is unique .", + "The node to be deleted is in the list and is not a tail node" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,5,1,9], node = 5\nOutput:[4,1,9]\nExplanation:You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node1.jpg" + }, + { + "text": "Example 2: Input:head = [4,5,1,9], node = 1\nOutput:[4,5,9]\nExplanation:You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 87.58%) | Memory: 17.70 MB (Top 6.02%)\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteNode(self, node):\n node.val = node.next.val\n node.next = node.next.next\n", + "title": "237. Delete Node in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete , we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order.", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree is at most 1000 .", + "Each node has a distinct value between 1 and 1000 .", + "to_delete.length <= 1000", + "to_delete contains distinct values between 1 and 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput:[[1,2,null,4],[6],[7]]", + "image": "https://assets.leetcode.com/uploads/2019/07/01/screen-shot-2019-07-01-at-53836-pm.png" + }, + { + "text": "Example 2: Input:root = [1,2,4,null,3], to_delete = [3]\nOutput:[[1,2,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 5.29%) | Memory: 51.1 MB (Top 5.85%)\nclass Solution {\n\n HashMap> parent_val_child_nodes_map;\n HashMap child_val_parent_node_map;\n\n public List delNodes(TreeNode root, int[] to_delete) {\n\n // initialize map\n parent_val_child_nodes_map = new HashMap<> ();\n child_val_parent_node_map = new HashMap<> ();\n\n // fill map\n dfsFillMap(root);\n\n // traverse to_delete to find those that do not have parent after deleting it\n List res = new ArrayList<> ();\n\n // actually deleting nodes\n for (int delete_val : to_delete) {\n\n // if the node has parent\n if (child_val_parent_node_map.containsKey(delete_val)) {\n TreeNode parent_node = child_val_parent_node_map.get(delete_val);\n if (parent_node.left != null && parent_node.left.val == delete_val) {\n parent_node.left = null;\n }\n\n if (parent_node.right != null && parent_node.right.val == delete_val) {\n parent_node.right = null;\n }\n }\n }\n\n // add root to the list first because root has no parent\n // only if root.val is not in to_delete\n if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) {\n res.add(root);\n }\n\n // add other nodes that do not have parent\n for (int delete_val : to_delete) {\n if (parent_val_child_nodes_map.containsKey(delete_val)) {\n for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) {\n\n // make sure the add node is not in to_delete\n int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val;\n if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) {\n res.add(parent_val_child_nodes_map.get(delete_val).get(i));\n }\n }\n }\n }\n\n return res;\n }\n\n public void dfsFillMap(TreeNode root) {\n\n if (root == null) {\n return;\n }\n\n if (root.left != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.left);\n\n child_val_parent_node_map.putIfAbsent(root.left.val, root);\n dfsFillMap(root.left);\n }\n\n if (root.right != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.right);\n\n child_val_parent_node_map.putIfAbsent(root.right.val, root);\n dfsFillMap(root.right);\n }\n\n return;\n }\n}", + "title": "1110. Delete Nodes And Return Forest", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete , we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order.", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree is at most 1000 .", + "Each node has a distinct value between 1 and 1000 .", + "to_delete.length <= 1000", + "to_delete contains distinct values between 1 and 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput:[[1,2,null,4],[6],[7]]", + "image": "https://assets.leetcode.com/uploads/2019/07/01/screen-shot-2019-07-01-at-53836-pm.png" + }, + { + "text": "Example 2: Input:root = [1,2,4,null,3], to_delete = [3]\nOutput:[[1,2,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traverse(self,node,par):\n if node:\n self.parent[node.val] = par\n self.traverse(node.left,node)\n self.traverse(node.right,node)\n \n def deleteNode(self,toDelete):\n node = None\n par = self.parent[toDelete]\n if par.val == toDelete:\n node = par\n elif par.left and par.left.val == toDelete:\n node = par.left\n elif par.right and par.right.val == toDelete:\n node = par.right\n if node.left: \n self.unique[node.left] = True\n if node.right: \n self.unique[node.right] = True\n \n if node in self.unique: self.unique.pop(node)\n if node != self.parent[toDelete]:\n if par.left == node: par.left = None\n else: par.right = None\n\n \n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n self.parent = {}\n self.traverse(root,root)\n self.unique = {root:True}\n for node in to_delete:\n self.deleteNode(node)\n return self.unique\n", + "title": "1110. Delete Nodes And Return Forest", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings word1 and word2 , return the minimum number of steps required to make word1 and word2 the same . In one step , you can delete exactly one character in either string.", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 500", + "word1 and word2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"sea\", word2 = \"eat\"\nOutput:2\nExplanation:You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"leetcode\", word2 = \"etco\"\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 23.73%) | Memory: 46.5 MB (Top 77.36%)\nclass Solution {\n public int minDistance(String word1, String word2) {\n int n = word1.length();\n int m = word2.length();\n\n int[][]dp = new int[n+1][m+1];\n\n for(int i = 0; i int:\n m = len(word1)\n n = len(word2)\n a = []\n for i in range(m+1):\n a.append([])\n for j in range(n+1):\n a[-1].append(0)\n \n for i in range(m):\n for j in range(n):\n if word1[i]==word2[j]:\n a[i+1][j+1] = 1 + a[i][j]\n else:\n a[i+1][j+1] = max( a[i][j+1], a[i+1][j])\n\t\t\t\t\t\n return m + n - ( 2 * a [-1][-1] )", + "title": "583. Delete Operation for Two Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x .", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]\nOutput:[1,3,4,1,2,6]\nExplanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]\nOutput:[1,2,4]\nExplanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]\nOutput:[2]\nExplanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 31.33%) | Memory: 218.3 MB (Top 51.88%)\nclass Solution {\n public ListNode deleteMiddle(ListNode head) {\n // Base Condition\n if(head == null || head.next == null) return null;\n // Pointers Created\n ListNode fast = head;\n ListNode slow = head;\n ListNode prev = head;\n\n while(fast != null && fast.next != null){\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n }\n prev.next = slow.next;\n return head;\n }\n}", + "title": "2095. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x .", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]\nOutput:[1,3,4,1,2,6]\nExplanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]\nOutput:[1,2,4]\nExplanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]\nOutput:[2]\nExplanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2948 ms (Top 45.50%) | Memory: 60.7 MB (Top 40.45%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head: return head\n if head and not head.next: return None\n\n prev = ListNode(0, head)\n slow = fast = head\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n\n prev.next = slow.next\n return head", + "title": "2095. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes , where boxes[i] = [ports ​​i ​, weight i ] , and three integers portsCount , maxBoxes , and maxWeight . The boxes need to be delivered in the order they are given . The ship will follow these steps: The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.", + "description_images": [], + "constraints": [ + "ports ​​i is the port where you need to deliver the i th box and weights i is the weight of the i th box.", + "portsCount is the number of ports.", + "maxBoxes and maxWeight are the respective box and weight limits of the ship." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput:4\nExplanation:The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).", + "image": null + }, + { + "text": "Example 2: Input:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput:6\nExplanation:The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput:6\nExplanation:The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {\n int[] diffCity = new int[boxes.length+1];\n int[] weights = new int[boxes.length+1];\n \n for (int i = 0; i < boxes.length; i++) {\n diffCity[i+1] = diffCity[i] + ((i != 0 && boxes[i][0] == boxes[i-1][0]) ? 0 : 1);\n weights[i+1] = weights[i] + boxes[i][1];\n }\n int[] dp = new int[boxes.length+1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n diffCity[0] = 1;\n for (int i = 1; i <= boxes.length; i++) { // offset by 1 since our above logic reaches dp[-1]\n for (int j = i - 1; j >= 0; j--) {\n int dC= diffCity[i] - diffCity[j+1]; // computes # of different cities from i to j. (add 1 to j is necessary here)\n int w = weights[i] - weights[j]; \n int b = i - j;\n if (b <= maxBoxes && w <= maxWeight) {\n dp[i] = Math.min(dp[i], 2 + dC + dp[j]); \n }\n }\n }\n return dp[boxes.length];\n }\n}\n", + "title": "1687. Delivering Boxes from Storage to Ports", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes , where boxes[i] = [ports ​​i ​, weight i ] , and three integers portsCount , maxBoxes , and maxWeight . The boxes need to be delivered in the order they are given . The ship will follow these steps: The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.", + "description_images": [], + "constraints": [ + "ports ​​i is the port where you need to deliver the i th box and weights i is the weight of the i th box.", + "portsCount is the number of ports.", + "maxBoxes and maxWeight are the respective box and weight limits of the ship." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput:4\nExplanation:The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).", + "image": null + }, + { + "text": "Example 2: Input:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput:6\nExplanation:The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput:6\nExplanation:The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2593 ms (Top 36.11%) | Memory: 66.70 MB (Top 22.22%)\n\nfrom sortedcontainers import SortedList as MonoQueue\nclass Solution:\n def boxDelivering(self, A, __, B, W):\n n = len(A)\n def slidingWindow():\n l=0\n cW = 0\n for r in range(n):\n cW+=A[r][1]\n while cW>W or r-l+1>B:\n cW-=A[l][1]\n l+=1\n yield l,r\n Seg=MonoQueue(key=lambda t:t[1])\n addAll = 0\n olddp = 0\n for l,r in slidingWindow():\n if r!=0:\n addAll+= ( A[r][0]!=A[r-1][0] )\n Seg.add((r, olddp-addAll+2))\n while Seg[0][0]> splitPainting(int[][] segments) {\n // Create a TreeMap to store the segment start and end points as keys\n // and the accumulated color values as values\n TreeMap tm = new TreeMap<>();\n \n // Process each segment\n for (int[] seg : segments) {\n // Increment the color value at the segment start point\n tm.put((long) seg[0], tm.getOrDefault((long) seg[0], 0L) + (long) seg[2]);\n \n // Decrement the color value at the segment end point\n tm.put((long) seg[1], tm.getOrDefault((long) seg[1], 0L) - (long) seg[2]);\n }\n \n // Create a list to store the non-overlapping segments of mixed colors\n List> ans = new ArrayList<>();\n \n // Variables to keep track of accumulated color value and segment state\n long acc = 0L;\n boolean st = true;\n List currentSegment = null;\n \n // Traverse the TreeMap entries\n for (var entry : tm.entrySet()) {\n // Update the accumulated color value\n acc += entry.getValue();\n \n // If the previous segment was not starting, update its end point\n if (!st) {\n currentSegment.set(1, entry.getKey());\n st = !st;\n }\n \n // If the current segment is starting and has a positive accumulated color value,\n // create a new segment and add it to the answer list\n if (st && acc > 0) {\n currentSegment = new ArrayList<>();\n currentSegment.add(entry.getKey());\n currentSegment.add(-1L);\n currentSegment.add(acc);\n ans.add(currentSegment);\n st = !st;\n }\n }\n \n return ans;\n }\n}\n\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments , where segments[i] = [start i , end i , color i ] represents the half-closed segment [start i , end i ) with color i as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [left j , right j , mix j ] describes a half-closed segment [left j , right j ) with the mixed color sum of mix j . Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order . A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b .", + "description_images": [], + "constraints": [ + "For example, if colors 2 , 4 , and 6 are mixed, then the resulting mixed color is {2,4,6} ." + ], + "examples": [ + { + "text": "Example 1: Input:segments = [[1,4,5],[4,7,7],[1,7,9]]\nOutput:[[1,4,14],[4,7,16]]\nExplanation:The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/1.png" + }, + { + "text": "Example 2: Input:segments = [[1,7,9],[6,8,15],[8,10,7]]\nOutput:[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation:The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/2.png" + }, + { + "text": "Example 3: Input:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput:[[1,4,12],[4,7,12]]\nExplanation:The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "image": "https://assets.leetcode.com/uploads/2021/07/04/c1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n //class for segments \n class Seg{\n int val,end;\n int color;\n boolean isStart;\n public Seg(int val,int end,int color, boolean isStart){\n this.val = val;\n this.end = end;\n this.color = color;\n this.isStart = isStart; \n }\n public String toString(){\n return \"[\" + val+\" \"+end+\" \"+color+\" \"+isStart+\"]\";\n }\n }\n public List> splitPainting(int[][] segments) {\n List> res = new ArrayList();\n \n List list = new ArrayList();\n \n //making a list of segments\n for(int[] segment : segments){\n list.add(new Seg(segment[0],segment[1],segment[2],true));\n list.add(new Seg(segment[1],segment[1],segment[2],false)); \n }\n \n //Sorting the segments\n Collections.sort(list,(a,b)->{return a.val-b.val;});\n \n //System.out.println(list);\n \n //Iterating over list to combine the elements\n for(Seg curr: list){\n int len = res.size();\n if(curr.isStart){\n //if the segment is starting there could be three ways \n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if starting point of two things is same\n List temp = res.get(len-1);\n temp.set(1,Math.max(temp.get(1),curr.end));\n temp.set(2,(long)(temp.get(2)+curr.color));\n }else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a start in between create a new segment of different color \n List prev = res.get(len-1);\n prev.set(1,(long)curr.val);\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)(prev.get(2)+curr.color));\n res.add(temp);\n }else{\n //Add a new value if nothing is present in result\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)curr.color);\n res.add(temp);\n }\n }else{\n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if ending point of 2 segments is same\n Long prevColor = res.get(len-1).get(2);\n res.get(len-1).set(2,(long)(prevColor-curr.color));\n }\n else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a ending in between create a new segment of different color \n Long prevColor = res.get(len-1).get(2);\n Long prevEnd = res.get(len-1).get(1);\n res.get(len-1).set(1,(long)curr.val);\n \n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)prevEnd); temp.add((long)(prevColor-curr.color));\n res.add(temp);\n }\n }\n //System.out.println(res+\" \"+curr);\n \n }\n //System.out.println(res);\n return res; \n \n }\n}\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments , where segments[i] = [start i , end i , color i ] represents the half-closed segment [start i , end i ) with color i as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [left j , right j , mix j ] describes a half-closed segment [left j , right j ) with the mixed color sum of mix j . Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order . A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b .", + "description_images": [], + "constraints": [ + "For example, if colors 2 , 4 , and 6 are mixed, then the resulting mixed color is {2,4,6} ." + ], + "examples": [ + { + "text": "Example 1: Input:segments = [[1,4,5],[4,7,7],[1,7,9]]\nOutput:[[1,4,14],[4,7,16]]\nExplanation:The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/1.png" + }, + { + "text": "Example 2: Input:segments = [[1,7,9],[6,8,15],[8,10,7]]\nOutput:[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation:The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/2.png" + }, + { + "text": "Example 3: Input:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput:[[1,4,12],[4,7,12]]\nExplanation:The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "image": "https://assets.leetcode.com/uploads/2021/07/04/c1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n mix, res, last_i = DefaultDict(int), [], 0\n for start, end, color in segments:\n mix[start] += color\n mix[end] -= color\n for i in sorted(mix.keys()):\n if last_i in mix and mix[last_i]:\n res.append([last_i, i, mix[last_i]])\n mix[i] += mix[last_i]\n last_i = i\n return res\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a food rating system that can do the following: Implement the FoodRatings class: Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order.", + "description_images": [], + "constraints": [ + "Modify the rating of a food item listed in the system.", + "Return the highest-rated food item for a type of cuisine in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]Output[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]ExplanationFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // Both \"sushi\" and \"ramen\" have a rating of 16.\n // However, \"ramen\" is lexicographically smaller than \"sushi\".", + "image": null + } + ], + "follow_up": null, + "solution": "class FoodRatings {\n HashMap> cuiToFood = new HashMap();\n HashMap foodToRat = new HashMap();\n HashMap foodToCui = new HashMap();\n public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {\n for(int i = 0; i < foods.length; i++){\n TreeSet foodOfThisCuisine = cuiToFood.getOrDefault(cuisines[i], new TreeSet ((a,b)->\n foodToRat.get(a).equals(foodToRat.get(b)) ? a.compareTo(b) : foodToRat.get(b)-foodToRat.get(a)));\n\t\t\t\n\t\t\t// Both comparators are equal\n\t\t\t/* new Comparator(){\n @Override\n public int compare(String a, String b){\n int aRat = foodToRat.get(a);\n int bRat = foodToRat.get(b);\n \n if(aRat != bRat) return bRat - aRat; // largest rating first\n for(int i = 0; i < Math.min(a.length(), b.length()); i++){\n if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i);\n }\n return a.length() - b.length();\n }\n })\n\t\t\t*/\n \n foodToRat.put(foods[i], ratings[i]);\n foodOfThisCuisine.add(foods[i]);\n foodToCui.put(foods[i], cuisines[i]); \n \n cuiToFood.put(cuisines[i], foodOfThisCuisine);\n }\n }\n \n // CompareTo() is used to compare whether 2 strings are equal in hashSet! So remove, change value of key in HashMap, then insert again\n public void changeRating(String food, int newRating) {\n String cui = foodToCui.get(food);\n TreeSet foodOfThisCui = cuiToFood.get(cui);\n foodOfThisCui.remove(food);\n foodToRat.put(food, newRating);\n \n foodOfThisCui.add(food);\n cuiToFood.put(cui, foodOfThisCui);\n }\n \n public String highestRated(String cuisine) {\n return cuiToFood.get(cuisine).first();\n }\n}\n", + "title": "2353. Design a Food Rating System", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a food rating system that can do the following: Implement the FoodRatings class: Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order.", + "description_images": [], + "constraints": [ + "Modify the rating of a food item listed in the system.", + "Return the highest-rated food item for a type of cuisine in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]Output[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]ExplanationFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // Both \"sushi\" and \"ramen\" have a rating of 16.\n // However, \"ramen\" is lexicographically smaller than \"sushi\".", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heappop, heappush\n\nclass RatedFood:\n def __init__(self, rating, food):\n self.rating = rating\n self.food = food\n \n def __lt__(self, other):\n if other.rating == self.rating:\n return self.food < other.food\n return self.rating < other.rating\n\nclass FoodRatings:\n def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n self.cuis_to_score_heap = defaultdict(list)\n self.food_to_latest_ratings = defaultdict(int)\n self.food_to_cuis = defaultdict(str)\n \n for food, cuis, rating in zip(foods, cuisines, ratings):\n self.food_to_cuis[food] = cuis\n self.food_to_latest_ratings[food] = rating\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food))\n \n \n\n def changeRating(self, food: str, newRating: int) -> None:\n self.food_to_latest_ratings[food] = newRating\n cuis = self.food_to_cuis[food]\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food))\n \n\n def highestRated(self, cuisine: str) -> str:\n while True:\n ratedFood = heappop(self.cuis_to_score_heap[cuisine])\n if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating):\n\t\t\t\n\t\t\t\t# because the food item is still valid, we put it back into the heap\n heappush(self.cuis_to_score_heap[cuisine], ratedFood)\n\t\t\t\t\n return ratedFood.food\n", + "title": "2353. Design a Food Rating System", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a number container system that can do the following: Implement the NumberContainers class:", + "description_images": [], + "constraints": [ + "Insert or Replace a number at the given index in the system.", + "Return the smallest index for the given number in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]Output[null, -1, null, null, null, null, 1, null, 2]ExplanationNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class NumberContainers {\n \n Map> map;\n Map m;\n public NumberContainers() {\n map=new HashMap<>();\n m=new HashMap<>();\n \n }\n public void change(int index, int number) {\n m.put(index,number);\n if(!map.containsKey(number)) map.put(number,new TreeSet<>());\n map.get(number).add(index);\n }\n \n public int find(int number) {\n if(!map.containsKey(number)) return -1;\n for(Integer a:map.get(number)){\n if(m.get(a)==number) return a;\n }\n return -1;\n }\n}\n", + "title": "2349. Design a Number Container System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a number container system that can do the following: Implement the NumberContainers class:", + "description_images": [], + "constraints": [ + "Insert or Replace a number at the given index in the system.", + "Return the smallest index for the given number in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]Output[null, -1, null, null, null, null, 1, null, 2]ExplanationNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class NumberContainers:\n def __init__(self):\n self.numbersByIndex = {}\n self.numberIndexes = defaultdict(set)\n self.numberIndexesHeap = defaultdict(list)\n\n def change(self, index: int, number: int) -> None:\n if index in self.numbersByIndex:\n if number != self.numbersByIndex[index]:\n self.numberIndexes[self.numbersByIndex[index]].remove(index)\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n else:\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n\n def find(self, number: int) -> int:\n while self.numberIndexesHeap[number] and self.numberIndexesHeap[number][0] not in self.numberIndexes[number]:\n heappop(self.numberIndexesHeap[number]) # make sure the smallest index in heap is still an index for number\n return self.numberIndexesHeap[number][0] if self.numberIndexesHeap[number] else -1\n\n", + "title": "2349. Design a Number Container System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a stack which supports the following operations. Implement the CustomStack class:", + "description_images": [], + "constraints": [ + "CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize .", + "void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize .", + "int pop() Pops and returns the top of stack or -1 if the stack is empty.", + "void inc(int k, int val) Increments the bottom k elements of the stack by val . If there are less than k elements in the stack, just increment all the elements in the stack." + ], + "examples": [ + { + "text": "Example 1: Input[\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]Output[null,null,null,2,null,null,null,null,null,103,202,201,-1]ExplanationCustomStack customStack = new CustomStack(3); // Stack is Empty []\ncustomStack.push(1); // stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.push(3); // stack becomes [1, 2, 3]\ncustomStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100); // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100); // stack becomes [201, 202, 103]\ncustomStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]\ncustomStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []\ncustomStack.pop(); // return -1 --> Stack is empty return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 70.94%) | Memory: 50.6 MB (Top 37.77%)\n\nclass CustomStack {\n\n int[] stack;\n int top;\n\n public CustomStack(int maxSize) {\n\n //intialise the stack and the top\n stack= new int[maxSize];\n top=-1;\n }\n\n public void push(int x) {\n\n // if the stack is full just skip\n if( top==stack.length-1) return;\n\n //add to the stack\n top++;\n stack[top]=x;\n }\n\n public int pop() {\n\n //if stack is empty return -1\n if( top==-1) return -1;\n\n //remove/pop the top element\n top--;\n return stack[top+1];\n\n }\n\n public void increment(int k, int val) {\n\n //got to increment the min of the elements present in the stack and k\n int n= Math.min(top+1,k);\n\n for( int i=0; i Return top of the stack 2, stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.push(3); // stack becomes [1, 2, 3]\ncustomStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100); // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100); // stack becomes [201, 202, 103]\ncustomStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]\ncustomStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []\ncustomStack.pop(); // return -1 --> Stack is empty return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass CustomStack:\n\n\t\tdef __init__(self, maxSize: int):\n\t\t\tself.size = maxSize\n\t\t\tself.stack = []\n\n\t\tdef push(self, x: int) -> None:\n\t\t\tif self.size > len(self.stack):\n\t\t\t\tself.stack.append(x)\n\n\t\tdef pop(self) -> int:\n\t\t\tif self.stack:\n\t\t\t\treturn self.stack.pop()\n\t\t\treturn -1\n\n\t\tdef increment(self, k: int, val: int) -> None:\n\t\t\tlen_stack = len(self.stack)\n\n\t\t\tif len_stack < k:\n\t\t\t\tself.stack[:] = [i + val for i in self.stack]\n\t\t\t\treturn\n\n\t\t\tfor i in range(k):\n\t\t\t\tself.stack[i] += val\n", + "title": "1381. Design a Stack With Increment Operation", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a text editor with a cursor that can do the following: When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds. Implement the TextEditor class:", + "description_images": [], + "constraints": [ + "Add text to where the cursor is.", + "Delete text from where the cursor is (simulating the backspace key).", + "Move the cursor either left or right." + ], + "examples": [ + { + "text": "Example 1: Input[\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n[[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]Output[null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]ExplanationTextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\ntextEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\ntextEditor.deleteText(4); // return 4\n // The current text is \"leet|\". \n // 4 characters were deleted.\ntextEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \ntextEditor.cursorRight(3); // return \"etpractice\"\n // The current text is \"leetpractice|\". \n // The cursor cannot be moved beyond the actual text and thus did not move.\n // \"etpractice\" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return \"leet\"\n // The current text is \"leet|practice\".\n // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n // The current text is \"|practice\".\n // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return \"\"\n // The current text is \"|practice\".\n // The cursor cannot be moved beyond the actual text and thus did not move. \n // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return \"practi\"\n // The current text is \"practi|ce\".\n // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 380 ms (Top 41.73%) | Memory: 138.9 MB (Top 59.95%)\nclass TextEditor {\n StringBuilder res;\n int pos=0;\n\n public TextEditor() {\n res = new StringBuilder();\n }\n\n public void addText(String text) {\n res.insert(pos,text);\n pos += text.length();\n }\n\n public int deleteText(int k) {\n int tmp = pos;\n pos -= k;\n if(pos<0) pos=0;\n res.delete(pos,tmp);\n return tmp-pos;\n }\n\n public String cursorLeft(int k) {\n pos-=k;\n if(pos<0) pos = 0;\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n\n public String cursorRight(int k) {\n pos+=k;\n if(pos>res.length()) pos = res.length();\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n}\n", + "title": "2296. Design a Text Editor", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a text editor with a cursor that can do the following: When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds. Implement the TextEditor class:", + "description_images": [], + "constraints": [ + "Add text to where the cursor is.", + "Delete text from where the cursor is (simulating the backspace key).", + "Move the cursor either left or right." + ], + "examples": [ + { + "text": "Example 1: Input[\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n[[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]Output[null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]ExplanationTextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\ntextEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\ntextEditor.deleteText(4); // return 4\n // The current text is \"leet|\". \n // 4 characters were deleted.\ntextEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \ntextEditor.cursorRight(3); // return \"etpractice\"\n // The current text is \"leetpractice|\". \n // The cursor cannot be moved beyond the actual text and thus did not move.\n // \"etpractice\" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return \"leet\"\n // The current text is \"leet|practice\".\n // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n // The current text is \"|practice\".\n // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return \"\"\n // The current text is \"|practice\".\n // The cursor cannot be moved beyond the actual text and thus did not move. \n // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return \"practi\"\n // The current text is \"practi|ce\".\n // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 1865 ms (Top 50.36%) | Memory: 27.8 MB (Top 82.98%)\nclass TextEditor:\n\n def __init__(self):\n self.s = ''\n self.cursor = 0\n\n def addText(self, text: str) -> None:\n self.s = self.s[:self.cursor] + text + self.s[self.cursor:]\n self.cursor += len(text)\n\n def deleteText(self, k: int) -> int:\n new_cursor = max(0, self.cursor - k)\n noOfChars = k if self.cursor - k >= 0 else self.cursor\n self.s = self.s[:new_cursor] + self.s[self.cursor:]\n self.cursor = new_cursor\n return noOfChars\n\n def cursorLeft(self, k: int) -> str:\n self.cursor = max(0, self.cursor - k)\n start = max(0, self.cursor-10)\n return self.s[start:self.cursor]\n\n def cursorRight(self, k: int) -> str:\n self.cursor = min(len(self.s), self.cursor + k)\n start = max(0, self.cursor - 10)\n return self.s[start:self.cursor]", + "title": "2296. Design a Text Editor", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class WordDictionary {\n private class Node{\n boolean last;\n Node[] sub;\n Node(){\n last = false;\n sub = new Node[26];\n }\n }\n Node root;\n public WordDictionary() {\n root = new Node();\n \n }\n \n public void addWord(String word) {\n Node temp = root;\n for(char c : word.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n temp.sub[index] = new Node();\n temp = temp.sub[index];\n }\n temp.last = true;\n }\n \n public boolean search(String word) {\n Node temp = root;\n return dfs(temp, word, 0);\n }\n private boolean dfs(Node node, String word, int i){\n if(i == word.length())\n return node.last; \n \n int index = word.charAt(i)-'a';\n if(word.charAt(i) == '.'){\n for(int j = 0; j < 26; j++){\n if(node.sub[j] != null)\n if(dfs(node.sub[j], word, i+1))\n return true;\n }\n return false;\n }\n else if(node.sub[index] == null)\n return false;\n return dfs(node.sub[index], word, i+1);\n }\n}\n", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode:\n \n def __init__(self, val):\n self.val = val\n self.children = {}\n self.isEnd = False\n\n\nclass WordDictionary:\n\n def __init__(self):\n self.root = TrieNode(\"*\")\n \n def addWord(self, word: str) -> None:\n \n curr = self.root\n \n for c in word:\n \n if c not in curr.children:\n curr.children[c] = TrieNode(c)\n \n curr = curr.children[c]\n \n curr.isEnd = True\n \n def search(self, word: str) -> bool:\n \n def dfs(root, word):\n curr = root\n\n for i in range(len(word)):\n\n if word[i] == \".\":\n for l in curr.children.values():\n if dfs(l, word[i+1:]) == True:\n return True\n \n return False\n\n if word[i] not in curr.children:\n return False\n\n curr = curr.children[word[i]]\n\n return curr.isEnd\n \n return dfs(self.root, word)\n", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is an ATM machine that stores banknotes of 5 denominations: 20 , 50 , 100 , 200 , and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. Implement the ATM class:", + "description_images": [], + "constraints": [ + "For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.", + "However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100 . Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote." + ], + "examples": [ + { + "text": "Example 1: Input[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]Output[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]ExplanationATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.", + "image": null + } + ], + "follow_up": null, + "solution": "class ATM {\n\tlong[] notes = new long[5]; // Note: use long[] instead of int[] to avoid getting error in large testcases\n\tint[] denoms;\n\tpublic ATM() {\n\t\tdenoms = new int[]{ 20,50,100,200,500 }; // create an array to represent money value.\n\t}\n\n\tpublic void deposit(int[] banknotesCount) {\n\t\tfor(int i = 0; i < banknotesCount.length; i++){\n\t\t\tnotes[i] += banknotesCount[i]; // add new deposit money to existing\n\t\t}\n\t}\n\n\tpublic int[] withdraw(int amount) { \n\t\tint[] result = new int[5]; // create result array to store quantity of each notes we will be using to withdraw \"amount\"\n\t\tfor(int i = 4; i >= 0; i--){\n\t\t\tif(amount >= denoms[i] ){ \n\t\t\t\tint quantity = (int) Math.min(notes[i], amount / denoms[i]); // pick the minimum quanity. because if say, amount/denoms[i] gives 3 but you only have 1 note. so you have to use 1 only instead of 3 \n\t\t\t\tamount -= denoms[i] * quantity; // amount left = 100\n\t\t\t\tresult[i] = quantity;\n\t\t\t}\n\t\t}\n\t\tif(amount != 0){ return new int[]{-1}; }\n\t\tfor(int i = 0; i < 5; i++){ notes[i] -= result[i]; } // deduct the quantity we have used.\n\t\treturn result;\n\t}\n}\n", + "title": "2241. Design an ATM Machine", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an ATM machine that stores banknotes of 5 denominations: 20 , 50 , 100 , 200 , and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. Implement the ATM class:", + "description_images": [], + "constraints": [ + "For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.", + "However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100 . Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote." + ], + "examples": [ + { + "text": "Example 1: Input[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]Output[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]ExplanationATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 906 ms (Top 67.28%) | Memory: 18 MB (Top 21.66%)\nclass ATM:\n def __init__(self):\n self.cash = [0] * 5\n self.values = [20, 50, 100, 200, 500]\n\n def deposit(self, banknotes_count: List[int]) -> None:\n for i, n in enumerate(banknotes_count):\n self.cash[i] += n\n\n def withdraw(self, amount: int) -> List[int]:\n res = []\n for val, n in zip(self.values[::-1], self.cash[::-1]):\n need = min(n, amount // val)\n res = [need] + res\n amount -= (need * val)\n if amount == 0:\n self.deposit([-x for x in res])\n return res\n else:\n return [-1]\n", + "title": "2241. Design an ATM Machine", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id . Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/11/10/q1.gif" + ], + "constraints": [ + "OrderedStream(int n) Constructs the stream to take n values.", + "String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order." + ], + "examples": [ + { + "text": "Example: Input[\"OrderedStream\", \"insert\", \"insert\", \"insert\", \"insert\", \"insert\"]\n[[5], [3, \"ccccc\"], [1, \"aaaaa\"], [2, \"bbbbb\"], [5, \"eeeee\"], [4, \"ddddd\"]]Output[null, [], [\"aaaaa\"], [\"bbbbb\", \"ccccc\"], [], [\"ddddd\", \"eeeee\"]]Explanation// Note that the values ordered by ID is [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"].\nOrderedStream os = new OrderedStream(5);\nos.insert(3, \"ccccc\"); // Inserts (3, \"ccccc\"), returns [].\nos.insert(1, \"aaaaa\"); // Inserts (1, \"aaaaa\"), returns [\"aaaaa\"].\nos.insert(2, \"bbbbb\"); // Inserts (2, \"bbbbb\"), returns [\"bbbbb\", \"ccccc\"].\nos.insert(5, \"eeeee\"); // Inserts (5, \"eeeee\"), returns [].\nos.insert(4, \"ddddd\"); // Inserts (4, \"ddddd\"), returns [\"ddddd\", \"eeeee\"].\n// Concatentating all the chunks returned:\n// [] + [\"aaaaa\"] + [\"bbbbb\", \"ccccc\"] + [] + [\"ddddd\", \"eeeee\"] = [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"]\n// The resulting order is the same as the order above.", + "image": null + } + ], + "follow_up": null, + "solution": "class OrderedStream:\n\n def __init__(self, n: int):\n self.seen = {}\n self.ptr = 1\n\n def insert(self, id: int, value: str) -> List[str]:\n seen, ptr = self.seen, self.ptr\n \n seen[id] = value\n result = []\n while ptr in seen:\n result.append(seen[ptr])\n del seen[ptr]\n ptr += 1\n \n self.ptr = ptr\n return result\n\n\n# Your OrderedStream object will be instantiated and called as such:\n# obj = OrderedStream(n)\n# param_1 = obj.insert(id,value)\n", + "title": "1656. Design an Ordered Stream", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime . If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime . Implement the AuthenticationManager class: Note that if a token expires at time t , and another action happens on time t ( renew or countUnexpiredTokens ), the expiration takes place before the other actions.", + "description_images": [], + "constraints": [ + "AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive .", + "generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.", + "renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId , the request is ignored, and nothing happens.", + "countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime." + ], + "examples": [ + { + "text": "Example 1: Input[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]Output[null, null, null, 1, null, null, null, 0]ExplanationAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager withtimeToLive= 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 therenewrequest is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so therenewrequest is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/copy-of-pc68_q2.png" + } + ], + "follow_up": null, + "solution": "class AuthenticationManager {\n private int ttl;\n private Map map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n this.map = new HashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + this.ttl);\n }\n \n public void renew(String tokenId, int currentTime) {\n Integer expirationTime = this.map.getOrDefault(tokenId, null);\n if (expirationTime == null || expirationTime <= currentTime)\n return;\n \n generate(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (Map.Entry entry: this.map.entrySet())\n if (entry.getValue() > currentTime)\n count++;\n \n return count;\n }\n}\n\n", + "title": "1797. Design Authentication Manager", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime . If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime . Implement the AuthenticationManager class: Note that if a token expires at time t , and another action happens on time t ( renew or countUnexpiredTokens ), the expiration takes place before the other actions.", + "description_images": [], + "constraints": [ + "AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive .", + "generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.", + "renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId , the request is ignored, and nothing happens.", + "countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime." + ], + "examples": [ + { + "text": "Example 1: Input[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]Output[null, null, null, 1, null, null, null, 0]ExplanationAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager withtimeToLive= 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 therenewrequest is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so therenewrequest is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/copy-of-pc68_q2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 732 ms (Top 5.07%) | Memory: 15.5 MB (Top 65.88%)\nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive and create dictionary\n\n def generate(self, tokenId, currentTime):\n self.token[tokenId] = currentTime # store tokenId with currentTime\n\n def renew(self, tokenId, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n self.token[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n c = 0\n for i in self.token:\n if self.token[i]>limit: # count unexpired tokens\n c+=1\n return c", + "title": "1797. Design Authentication Manager", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A Bitset is a data structure that compactly stores bits. Implement the Bitset class:", + "description_images": [], + "constraints": [ + "Bitset(int size) Initializes the Bitset with size bits, all of which are 0 .", + "void fix(int idx) Updates the value of the bit at the index idx to 1 . If the value was already 1 , no change occurs.", + "void unfix(int idx) Updates the value of the bit at the index idx to 0 . If the value was already 0 , no change occurs.", + "void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.", + "boolean all() Checks if the value of each bit in the Bitset is 1 . Returns true if it satisfies the condition, false otherwise.", + "boolean one() Checks if there is at least one bit in the Bitset with value 1 . Returns true if it satisfies the condition, false otherwise.", + "int count() Returns the total number of bits in the Bitset which have value 1 .", + "String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the i th index should coincide with the value at the i th bit of the Bitset." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bitset\", \"fix\", \"fix\", \"flip\", \"all\", \"unfix\", \"flip\", \"one\", \"unfix\", \"count\", \"toString\"]\n[[5], [3], [1], [], [], [0], [], [], [0], [], []]Output[null, null, null, null, false, null, null, true, null, 2, \"01010\"]ExplanationBitset bs = new Bitset(5); // bitset = \"00000\".\nbs.fix(3); // the value at idx = 3 is updated to 1, so bitset = \"00010\".\nbs.fix(1); // the value at idx = 1 is updated to 1, so bitset = \"01010\". \nbs.flip(); // the value of each bit is flipped, so bitset = \"10101\". \nbs.all(); // return False, as not all values of the bitset are 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"00101\".\nbs.flip(); // the value of each bit is flipped, so bitset = \"11010\". \nbs.one(); // return True, as there is at least 1 index with value 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"01010\".\nbs.count(); // return 2, as there are 2 bits with value 1.\nbs.toString(); // return \"01010\", which is the composition of bitset.", + "image": null + } + ], + "follow_up": null, + "solution": "class Bitset {\n int size;\n Set one = new HashSet<>();\n Set zero = new HashSet<>();\n public Bitset(int size) {\n this.size = size;\n for(int i=0;i s = one;\n one = zero;\n zero = s;\n }\n \n public boolean all() {\n return one.size() == size;\n }\n \n public boolean one() {\n return one.size()>=1;\n }\n \n public int count() {\n return one.size();\n }\n \n public String toString() {\n StringBuilder sb= new StringBuilder();\n for(int i=0;i 0\n\n def count(self):\n return self.cnt\n\n def toString(self):\n a = bin(self.a)[2:]\n return a[::-1] + '0' * (self.size - len(a))", + "title": "2166. Design Bitset", + "topic": "Hash Table" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example: Input:[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"leetcode.com\"],[\"google.com\"],[\"facebook.com\"],[\"youtube.com\"],[1],[1],[1],[\"linkedin.com\"],[2],[2],[7]]\nOutput:[null,null,null,null,\"facebook.com\",\"google.com\",\"facebook.com\",null,\"linkedin.com\",\"google.com\",\"leetcode.com\"]\nExplanation:BrowserHistory browserHistory = new BrowserHistory(\"leetcode.com\");\nbrowserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 122 ms (Top 39.97%) | Memory: 81.7 MB (Top 80.48%)\nclass BrowserHistory {\n int current;\n ArrayList history;\n public BrowserHistory(String homepage) {\n this.history = new ArrayList<>();\n history.add(homepage);\n this.current = 0;\n }\n\n public void visit(String url) {\n while (history.size()-1 > current) {//delete forward history\n history.remove(history.size()-1);//which means delete everything beyond our current website\n }\n history.add(url);\n ++current;\n }\n\n public String back(int steps) {\n if (steps>current) current = 0;//if we can't get enough back, we return first thing in our history\n else current -= steps;//if there will be no arrayindexoutofrange error, go back\n return history.get(current);//return current webpage\n }\n\n public String forward(int steps) {\n //if we are going to move more than our arraylist, then we will return the last element\n if (steps+current>=history.size()) current = history.size() - 1;\n else current += steps;//if there will be no arrayindexoutofrange error, go forward!\n return history.get(current);//return the current webpage\n }\n}\n\n/**\n * Your BrowserHistory object will be instantiated and called as such:\n * BrowserHistory obj = new BrowserHistory(homepage);\n * obj.visit(url);\n * String param_2 = obj.back(steps);\n * String param_3 = obj.forward(steps);\n */", + "title": "1472. Design Browser History", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example: Input:[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"leetcode.com\"],[\"google.com\"],[\"facebook.com\"],[\"youtube.com\"],[1],[1],[1],[\"linkedin.com\"],[2],[2],[7]]\nOutput:[null,null,null,null,\"facebook.com\",\"google.com\",\"facebook.com\",null,\"linkedin.com\",\"google.com\",\"leetcode.com\"]\nExplanation:BrowserHistory browserHistory = new BrowserHistory(\"leetcode.com\");\nbrowserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 702 ms (Top 9.12%) | Memory: 16.8 MB (Top 36.03%)\nclass Node:\n def __init__(self, val):\n self.val = val\n self.prev = None\n self.next = None\n\nclass BrowserHistory:\n def __init__(self, web):\n self.Node = Node(web)\n self.ptr = self.Node\n\n def visit(self, web):\n self.newWeb = Node(web)\n self.newWeb.prev = self.ptr\n self.ptr.next = self.newWeb\n self.ptr = self.ptr.next\n\n def back(self, steps):\n i = 0\n while i < steps:\n if self.ptr.prev:\n self.ptr = self.ptr.prev\n else:\n break\n i += 1\n return self.ptr.val\n\n def forward(self, steps):\n i = 0\n while i < steps:\n if self.ptr.next:\n self.ptr = self.ptr.next\n else:\n break\n i += 1\n return self.ptr.val", + "title": "1472. Design Browser History", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class:", + "description_images": [], + "constraints": [ + "MyCircularDeque(int k) Initializes the deque with a maximum size of k .", + "boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.", + "int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.", + "boolean isEmpty() Returns true if the deque is empty, or false otherwise.", + "boolean isFull() Returns true if the deque is full, or false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 2, true, true, true, 4]ExplanationMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCircularDeque {\npublic:\n \n deque dq;\n \n int max_size;\n \n MyCircularDeque(int k) {\n \n max_size = k; \n }\n \n bool insertFront(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_front(value);\n \n return true;\n }\n \n return false;\n }\n \n bool insertLast(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_back(value);\n \n return true;\n }\n \n return false;\n }\n \n bool deleteFront() {\n \n if(dq.size() > 0)\n {\n dq.pop_front();\n \n return true;\n }\n \n return false;\n }\n \n bool deleteLast() {\n \n if(dq.size() > 0)\n {\n dq.pop_back();\n \n return true;\n }\n \n return false; \n }\n \n int getFront() {\n \n if(dq.size() > 0)\n return dq.front();\n \n return -1;\n }\n \n int getRear() {\n \n if(dq.size() > 0)\n return dq.back();\n \n return -1;\n }\n \n bool isEmpty() {\n \n return dq.empty();\n }\n \n bool isFull() {\n \n return dq.size() == max_size;\n }\n};\n", + "title": "641. Design Circular Deque", + "topic": "Queue" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class:", + "description_images": [], + "constraints": [ + "MyCircularDeque(int k) Initializes the deque with a maximum size of k .", + "boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.", + "int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.", + "boolean isEmpty() Returns true if the deque is empty, or false otherwise.", + "boolean isFull() Returns true if the deque is full, or false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 2, true, true, true, 4]ExplanationMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 91.39%) | Memory: 18.00 MB (Top 39.07%)\n\nclass MyCircularDeque:\n def __init__(self, k: int):\n self.queue = [None] * k\n self.max_size = k\n self.head = 0\n self.tail = 0\n self.size = 0\n\n def insertFront(self, value: int) -> bool:\n if self.isFull():\n return False\n self.head = (self.head - 1) % self.max_size\n self.queue[self.head] = value\n self.size += 1\n return True\n\n def insertLast(self, value: int) -> bool:\n if self.isFull():\n return False\n self.queue[self.tail] = value\n self.tail = (self.tail + 1) % self.max_size\n self.size += 1\n return True\n\n def deleteFront(self) -> bool:\n if self.isEmpty():\n return False\n self.head = (self.head + 1) % self.max_size\n self.size -= 1\n return True\n\n def deleteLast(self) -> bool:\n if self.isEmpty():\n return False\n self.tail = (self.tail - 1) % self.max_size\n self.size -= 1\n return True\n\n def getFront(self) -> int:\n if self.isEmpty():\n return -1\n return self.queue[self.head]\n\n def getRear(self) -> int:\n if self.isEmpty():\n return -1\n return self.queue[(self.tail - 1) % self.max_size]\n\n def isEmpty(self) -> bool:\n return self.size == 0\n\n def isFull(self) -> bool:\n return self.size == self.max_size\n\n", + "title": "641. Design Circular Deque", + "topic": "Queue" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implementation the MyCircularQueue class: You must solve the problem without using the built-in queue data structure in your programming language.", + "description_images": [], + "constraints": [ + "MyCircularQueue(k) Initializes the object with the size of the queue to be k .", + "int Front() Gets the front item from the queue. If the queue is empty, return -1 .", + "int Rear() Gets the last item from the queue. If the queue is empty, return -1 .", + "boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.", + "boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.", + "boolean isEmpty() Checks whether the circular queue is empty or not.", + "boolean isFull() Checks whether the circular queue is full or not." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 3, true, true, true, 4]ExplanationMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 38.7%) | Memory: 44.24 MB (Top 53.3%)\n\nclass MyCircularQueue {\n\n private int front;\n private int rear;\n private int[] arr;\n private int cap;\n \n private int next(int i){ // to get next idx after i in circular queue\n return (i+1)%cap;\n }\n private int prev(int i){ // to get prev idx before i in circular queue\n return (i+cap-1)%cap;\n }\n \n\t// rest is as simple as implmenting a normal queue using array.\n public MyCircularQueue(int k) {\n arr = new int[k];\n cap=k;\n front=-1;\n rear=-1;\n }\n \n public boolean enQueue(int value) {\n if(isFull())return false;\n if(front==-1){\n front=0;\n rear=0;\n arr[rear]=value;\n return true;\n }\n rear = next(rear);\n arr[rear]=value;\n return true;\n }\n \n public boolean deQueue() {\n if(isEmpty())return false;\n if(front==rear){\n front=-1;\n rear=-1;\n return true;\n }\n front=next(front);\n return true;\n }\n \n public int Front() {\n if(front==-1)return -1;\n return arr[front];\n }\n \n public int Rear() {\n if(rear==-1)return -1;\n return arr[rear];\n }\n \n public boolean isEmpty() {\n return front==-1;\n }\n \n public boolean isFull() {\n return front!=-1 && next(rear)==front;\n }\n}", + "title": "622. Design Circular Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implementation the MyCircularQueue class: You must solve the problem without using the built-in queue data structure in your programming language.", + "description_images": [], + "constraints": [ + "MyCircularQueue(k) Initializes the object with the size of the queue to be k .", + "int Front() Gets the front item from the queue. If the queue is empty, return -1 .", + "int Rear() Gets the last item from the queue. If the queue is empty, return -1 .", + "boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.", + "boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.", + "boolean isEmpty() Checks whether the circular queue is empty or not.", + "boolean isFull() Checks whether the circular queue is full or not." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 3, true, true, true, 4]ExplanationMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 66 ms (Top 68.44%) | Memory: 18.10 MB (Top 5.6%)\n\nclass MyCircularQueue:\n def __init__(self, k: int):\n self.data = [0] * k\n self.maxSize = k\n self.head = 0\n self.tail = -1\n def enQueue(self, val: int) -> bool:\n if self.isFull(): return False\n self.tail = (self.tail + 1) % self.maxSize\n self.data[self.tail] = val\n return True\n def deQueue(self) -> bool:\n if self.isEmpty(): return False\n if self.head == self.tail: self.head, self.tail = 0, -1\n else: self.head = (self.head + 1) % self.maxSize\n return True\n def Front(self) -> int:\n return -1 if self.isEmpty() else self.data[self.head]\n def Rear(self) -> int:\n return -1 if self.isEmpty() else self.data[self.tail]\n def isEmpty(self) -> bool:\n return self.tail == -1\n def isFull(self) -> bool:\n return not self.isEmpty() and (self.tail + 1) % self.maxSize == self.head\n", + "title": "622. Design Circular Queue", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:", + "description_images": [], + "constraints": [ + "FrontMiddleBack() Initializes the queue.", + "void pushFront(int val) Adds val to the front of the queue.", + "void pushMiddle(int val) Adds val to the middle of the queue.", + "void pushBack(int val) Adds val to the back of the queue.", + "int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1 .", + "int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1 .", + "int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]\nOutput:[null, null, null, null, null, 1, 3, 4, 2, -1]\nExplanation:FrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1,2]\nq.pushMiddle(3); // [1,3, 2]\nq.pushMiddle(4); // [1,4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 73.3%) | Memory: 44.18 MB (Top 74.0%)\n\nclass FrontMiddleBackQueue {\n\n Deque dq1, dq2;\n public FrontMiddleBackQueue() { \n dq1 = new ArrayDeque();\n dq2 = new ArrayDeque();\n }\n \n public void pushFront(int val) {\n dq1.addFirst(val);\n } \n \n public void pushBack(int val) {\n dq2.addLast(val);\n } \n \n public void pushMiddle(int val) {\n while(dq1.size() + 1 < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size())\n dq2.addFirst(dq1.removeLast()); \n dq1.addLast(val); \n } \n \n public int popFront() {\n if(!dq1.isEmpty())\n return dq1.removeFirst();\n if(!dq2.isEmpty())\n return dq2.removeFirst();\n return -1; \n } \n \n public int popMiddle() {\n if(dq1.isEmpty() && dq2.isEmpty())\n return -1; \n while(dq1.size() < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size() + 1)\n dq2.addFirst(dq1.removeLast());\n return !dq1.isEmpty() ? dq1.removeLast() : dq2.removeFirst();\n } \n \n public int popBack() {\n if(!dq2.isEmpty())\n return dq2.removeLast();\n if(!dq1.isEmpty())\n return dq1.removeLast();\n return -1; \n } \n}", + "title": "1670. Design Front Middle Back Queue", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:", + "description_images": [], + "constraints": [ + "FrontMiddleBack() Initializes the queue.", + "void pushFront(int val) Adds val to the front of the queue.", + "void pushMiddle(int val) Adds val to the middle of the queue.", + "void pushBack(int val) Adds val to the back of the queue.", + "int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1 .", + "int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1 .", + "int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]\nOutput:[null, null, null, null, null, 1, 3, 4, 2, -1]\nExplanation:FrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1,2]\nq.pushMiddle(3); // [1,3, 2]\nq.pushMiddle(4); // [1,4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 176 ms (Top 11.57%) | Memory: 14.6 MB (Top 46.27%)\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.front = deque()\n self.back = deque()\n\n def _correct_size(self):\n while len(self.back) > len(self.front):\n self.front.append(self.back.popleft())\n\n while len(self.front) > len(self.back) + 1:\n self.back.appendleft(self.front.pop())\n\n def pushFront(self, val: int) -> None:\n self.front.appendleft(val)\n self._correct_size()\n\n def pushMiddle(self, val: int) -> None:\n if len(self.front) > len(self.back):\n self.back.appendleft(self.front.pop())\n self.front.append(val)\n self._correct_size()\n\n def pushBack(self, val: int) -> None:\n self.back.append(val)\n self._correct_size()\n\n def popFront(self) -> int:\n front = self.front if self.front else self.back\n ret = front.popleft() if front else -1\n self._correct_size()\n return ret\n\n def popMiddle(self) -> int:\n ret = self.front.pop() if self.front else -1\n self._correct_size()\n return ret\n\n def popBack(self) -> int:\n back = self.back if self.back else self.front\n ret = back.pop() if back else -1\n self._correct_size()\n return ret", + "title": "1670. Design Front Middle Back Queue", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class:", + "description_images": [], + "constraints": [ + "MyHashMap() initializes the object with an empty map.", + "void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value .", + "int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key .", + "void remove(key) removes the key and its corresponding value if the map contains the mapping for the key ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]Output[null, null, null, 1, -1, null, 1, null, -1]ExplanationMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class MyHashMap {\n\n\t/** Initialize your data structure here. */\n\tLinkedList[] map;\n\tpublic static int SIZE = 769;\n\tpublic MyHashMap() {\n\t\tmap = new LinkedList[SIZE];\n\t}\n\n\t/** value will always be non-negative. */\n\tpublic void put(int key, int value) {\n\t\tint bucket = key % SIZE;\n\t\tif(map[bucket] == null) {\n\t\t\tmap[bucket] = new LinkedList();\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key){\n\t\t\t\t\tentry.val = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tpublic int get(int key) {\n\t\tint bucket = key % SIZE;\n\t\tLinkedList entries = map[bucket];\n\t\tif(entries == null) return -1;\n\t\tfor(Entry entry : entries) {\n\t\t\tif(entry.key == key) return entry.val;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tpublic void remove(int key) {\n\t\tint bucket = key % SIZE;\n\t\tEntry toRemove = null;\n\t\tif(map[bucket] == null) return;\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key) {\n\t\t\t\t\ttoRemove = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(toRemove == null) return;\n\t\t\tmap[bucket].remove(toRemove);\n\t\t}\n\t}\n}\n\nclass Entry {\n\tpublic int key;\n\tpublic int val;\n\n\tpublic Entry(int key, int val){\n\t\tthis.key = key;\n\t\tthis.val = val;\n\t}\n}", + "title": "706. Design HashMap", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class:", + "description_images": [], + "constraints": [ + "MyHashMap() initializes the object with an empty map.", + "void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value .", + "int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key .", + "void remove(key) removes the key and its corresponding value if the map contains the mapping for the key ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]Output[null, null, null, 1, -1, null, 1, null, -1]ExplanationMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 285 ms (Top 33.03%) | Memory: 43.10 MB (Top 5.35%)\n\nclass MyHashMap:\n def __init__(self):\n self.data = [None] * 1000001\n def put(self, key: int, val: int) -> None:\n self.data[key] = val\n def get(self, key: int) -> int:\n val = self.data[key]\n return val if val != None else -1\n def remove(self, key: int) -> None:\n self.data[key] = None\n", + "title": "706. Design HashMap", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class:", + "description_images": [], + "constraints": [ + "void add(key) Inserts the value key into the HashSet.", + "bool contains(key) Returns whether the value key exists in the HashSet or not.", + "void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]Output[null, null, null, true, false, null, true, null, false]ExplanationMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)", + "image": null + } + ], + "follow_up": null, + "solution": "class MyHashSet {\n\tArrayList> list;\n\tint size = 100;\n\n\tpublic MyHashSet() {\n\t\tlist = new ArrayList<>(size);\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tlist.add(new LinkedList());\n\t\t}\n\t}\n\n\tpublic int hash(int key) {\n\t\treturn key % list.size();\n\t}\n\n\tpublic int search(int key) {\n\t\tint i = hash(key);\n\n\t\tLinkedList temp = list.get(i);\n\t\tint ans = -1;\n\n\t\tfor (int j = 0; j < temp.size(); j++) {\n\t\t\tif (key == temp.get(j)) {\n\t\t\t\treturn j;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\n\tpublic void add(int key) {\n\t\tif (search(key) == -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).add(key);\n\t\t}\n\t}\n\n\tpublic void remove(int key) {\n\t\tif (search(key) != -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).remove(Integer.valueOf(key));\n\t\t}\n\t}\n\n\tpublic boolean contains(int key) {\n\t\treturn search(key) != -1;\n\t}\n}", + "title": "705. Design HashSet", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class:", + "description_images": [], + "constraints": [ + "void add(key) Inserts the value key into the HashSet.", + "bool contains(key) Returns whether the value key exists in the HashSet or not.", + "void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]Output[null, null, null, true, false, null, true, null, false]ExplanationMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1864 ms (Top 22.23%) | Memory: 174.5 MB (Top 5.09%)\nclass MyHashSet:\n\n def __init__(self):\n self.hash_list = [0]*10000000\n\n def add(self, key: int) -> None:\n self.hash_list[key]+=1\n\n def remove(self, key: int) -> None:\n self.hash_list[key] = 0\n\n def contains(self, key: int) -> bool:\n if self.hash_list[key] > 0:\n return True\n return False", + "title": "705. Design HashSet", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next . val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed . Implement the MyLinkedList class:", + "description_images": [], + "constraints": [ + "MyLinkedList() Initializes the MyLinkedList object.", + "int get(int index) Get the value of the index th node in the linked list. If the index is invalid, return -1 .", + "void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.", + "void addAtTail(int val) Append a node of value val as the last element of the linked list.", + "void addAtIndex(int index, int val) Add a node of value val before the index th node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted .", + "void deleteAtIndex(int index) Delete the index th node in the linked list, if the index is valid." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]Output[null, null, null, null, 2, null, 3]ExplanationMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 41.30%) | Memory: 50.4 MB (Top 74.99%)\nclass MyLinkedList {\n\n public class ListNode {\n public int val;\n public ListNode next;\n\n public ListNode() {\n\n }\n\n public ListNode(int val) {\n this.val = val;\n }\n\n public ListNode(int val, ListNode next) {\n this.val = val;\n this.next = next;\n }\n }\n\n private ListNode head;\n private ListNode tail;\n private int length;\n\n public MyLinkedList() {\n length = 0;\n }\n\n public int get(int index) {\n if (index > length - 1 || index < 0) return -1;\n int thisIndex = 0;\n ListNode temp = head;\n while (thisIndex != index) {\n temp = temp.next;\n thisIndex++;\n }\n return temp.val;\n }\n\n public void addAtHead(int val) {\n head = new ListNode(val, head);\n length++;\n if (length == 1) tail = head;\n }\n\n public void addAtTail(int val) {\n length++;\n if (length == 1) {\n ListNode onlyNode = new ListNode(val);\n head = onlyNode;\n tail = head;\n return;\n }\n tail.next = new ListNode(val);\n tail = tail.next;\n }\n\n public void addAtIndex(int index, int val) {\n if (index <= length) {\n if (index == 0) {\n addAtHead(val);\n return;\n }\n if (index == length) {\n addAtTail(val);\n return;\n }\n length++;\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n temp.next = new ListNode(val, temp.next);\n }\n }\n\n public void deleteAtIndex(int index) {\n if (index >= length || index < 0) return;\n length--;\n if (index == 0) {\n head = head.next;\n return;\n }\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n if (index == length) {\n tail = temp;\n temp.next = null;\n }\n else temp.next = temp.next.next;\n }\n}", + "title": "707. Design Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next . val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed . Implement the MyLinkedList class:", + "description_images": [], + "constraints": [ + "MyLinkedList() Initializes the MyLinkedList object.", + "int get(int index) Get the value of the index th node in the linked list. If the index is invalid, return -1 .", + "void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.", + "void addAtTail(int val) Append a node of value val as the last element of the linked list.", + "void addAtIndex(int index, int val) Add a node of value val before the index th node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted .", + "void deleteAtIndex(int index) Delete the index th node in the linked list, if the index is valid." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]Output[null, null, null, null, 2, null, 3]ExplanationMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self, val: int):\n self.val = val\n self.next = None\n self.prev = None\n \nclass MyLinkedList:\n def __init__(self):\n self.head = Node(0)\n self.tail = Node(0)\n self.head.next = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n def get(self, index: int) -> int:\n if index < 0 or index >= self.size:\n return -1\n # Distance of index is closer to head\n if index + 1 < self.size - index:\n curr = self.head\n for i in range(index + 1):\n curr = curr.next\n # Distance of index is closer to tail\n else:\n curr = self.tail\n for i in range(self.size - index):\n curr = curr.prev\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.head\n nextNode = self.head.next\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtTail(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.tail.prev\n nextNode = self.tail\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtIndex(self, index: int, val: int) -> None:\n curr = Node(val)\n if index > self.size:\n return\n if index < 0:\n index = 0\n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next\n else:\n nextNode = self.tail\n for i in range(self.size - index):\n nextNode = nextNode.prev\n prevNode = nextNode.prev\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n \n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.size:\n return \n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next.next\n else:\n nextNode = self.tail\n for i in range(self.size - index - 1):\n nextNode = nextNode.prev\n prevNode = nextNode.prev.prev\n self.size -= 1\n prevNode.next = nextNode\n nextNode.prev = prevNode\n\n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)", + "title": "707. Design Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shop i , movie i , price i ] indicates that there is a copy of movie movie i at shop shop i with a rental price of price i . Each shop carries at most one copy of a movie movie i . The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.", + "description_images": [], + "constraints": [ + "Search : Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop i should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.", + "Rent : Rents an unrented copy of a given movie from a given shop.", + "Drop : Drops off a previously rented copy of a given movie at a given shop.", + "Report : Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shop j , movie j ] describes that the j th cheapest rented movie movie j was rented from the shop shop j . The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop j should appear first, and if there is still tie, the one with the smaller movie j should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]Output[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]ExplanationMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class MovieRentingSystem {\n \n Map> map = new HashMap<>();\n\nTreeSet rented = new TreeSet<>(new rcomp());\n\npublic MovieRentingSystem(int n, int[][] entries) {\n for(int entry[] : entries){\n Map map1 = map.getOrDefault(entry[1],new HashMap<>());\n Pair p = new Pair(entry[0],entry[1],entry[2]);\n map1.put(entry[0],p);\n map.put(entry[1],map1);\n }\n}\n\npublic List search(int movie) {\n \n PriorityQueue pq = new PriorityQueue<>(new scomp());\n \n Map map1 = map.getOrDefault(movie,new HashMap<>());\n \n for(Pair p : map1.values()){\n if(p.rent == true){continue;}\n if(pq.size() < 5){pq.add(p);}\n else{\n if(pq.peek().price > p.price){\n pq.poll();\n pq.add(p);\n }else if(pq.peek().price == p.price && pq.peek().shop > p.shop){\n pq.poll();\n pq.add(p);\n }\n }\n }\n \n List ans = new ArrayList<>();\n \n while(!pq.isEmpty()){\n \n Pair p = pq.poll();\n ans.add(0,p.shop);\n }\n \n return ans;\n \n \n}\n\npublic void rent(int shop, int movie) {\n \n Pair p = map.get(movie).get(shop);\n p.rent = true;\n rented.add(p);\n}\n\npublic void drop(int shop, int movie) {\n Pair p = map.get(movie).get(shop);\n p.rent = false;\n rented.remove(p);\n}\n\npublic List> report() {\n List> ans = new ArrayList<>();\n \n for(Pair p : rented){\n List t = new ArrayList<>();\n t.add(p.shop);t.add(p.movie);\n ans.add(t);\n if(ans.size()==5){break;}\n }\n \n return ans;\n }\n}\n\nclass scomp implements Comparator{\n\npublic int compare(Pair a , Pair b){\n if(a.price == b.price){\n return b.shop - a.shop;\n }\n return b.price - a.price;\n }\n}\n\n class rcomp implements Comparator{\n public int compare(Pair a,Pair b){\n if(a.price == b.price){\n if(a.shop == b.shop){\n return a.movie - b.movie;\n }\n return a.shop - b.shop;\n }\n return a.price - b.price;\n }\n} \n\n\nclass Pair{\n\nint shop;\nint movie;\nint price;\nboolean rent;\n\nPair(int shop,int movie,int price){\n this.shop = shop;\n this.movie = movie;\n this.price = price;\n this.rent = false;\n}\n\npublic int hashCode() {\nreturn Objects.hash(shop,movie,price);\n}\n\npublic boolean equals(Object obj)\n{\n Pair obj1 = (Pair)obj;\n if(obj1.shop == shop && obj1.movie==movie && obj1.price == price){\n return true;\n }\n return false;\n }\n}\n", + "title": "1912. Design Movie Rental System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shop i , movie i , price i ] indicates that there is a copy of movie movie i at shop shop i with a rental price of price i . Each shop carries at most one copy of a movie movie i . The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.", + "description_images": [], + "constraints": [ + "Search : Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop i should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.", + "Rent : Rents an unrented copy of a given movie from a given shop.", + "Drop : Drops off a previously rented copy of a given movie at a given shop.", + "Report : Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shop j , movie j ] describes that the j th cheapest rented movie movie j was rented from the shop shop j . The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop j should appear first, and if there is still tie, the one with the smaller movie j should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]Output[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]ExplanationMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4131 ms (Top 50.00%) | Memory: 98.7 MB (Top 51.92%)\nimport sortedcontainers as sc\nclass MovieRentingSystem:\n def __init__(self, n: int, entries: List[List[int]]):\n self.rented = sc.SortedList() # Triples of price, shop, movie\n self.movies = {} # Dictionary mapping movie -> sorted list of (price, shop)\n self.movie_and_shop_to_price = {} # Dictionary mapping (movie, shop) -> price\n\n for shop, movie, price in entries:\n if movie not in self.movies:\n self.movies[movie] = sc.SortedList()\n self.movies[movie].add((price, shop))\n self.movie_and_shop_to_price[movie, shop] = price\n\n def search(self, movie: int) -> List[int]:\n if movie not in self.movies:\n return []\n return [x[1] for x in self.movies[movie][:5]] # Returning the shop numbers\n\n def rent(self, shop: int, movie: int) -> None:\n my_price = self.movie_and_shop_to_price[movie, shop]\n self.rented.add((my_price, shop, movie))\n self.movies[movie].remove((my_price, shop))\n\n def drop(self, shop: int, movie: int) -> None:\n my_price = self.movie_and_shop_to_price[movie, shop]\n self.rented.remove((my_price, shop, movie))\n self.movies[movie].add((my_price, shop))\n\n def report(self) -> List[List[int]]:\n return [x[1:] for x in self.rented[:5]] # Returning the (shop, movie) pairs", + "title": "1912. Design Movie Rental System", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the ParkingSystem class:", + "description_images": [], + "constraints": [ + "ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.", + "bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1 , 2 , and 3 respectively. A car can only park in a parking space of its carType . If there is no space available, return false , else park the car in that size space and return true ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]Output[null, true, true, false, false]ExplanationParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 99.5%) | Memory: 45.00 MB (Top 40.87%)\n\nclass ParkingSystem {\n private int slots[] = new int[3];\n public ParkingSystem(int big, int medium, int small) {\n slots[0] = big;\n slots[1] = medium;\n slots[2] = small;\n }\n \n public boolean addCar(int carType) {\n if(slots[carType-1]>0)\n { \n slots[carType-1]--;\n return true;\n \n }\n return false;\n }\n}\n", + "title": "1603. Design Parking System", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the ParkingSystem class:", + "description_images": [], + "constraints": [ + "ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.", + "bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1 , 2 , and 3 respectively. A car can only park in a parking space of its carType . If there is no space available, return false , else park the car in that size space and return true ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]Output[null, true, true, false, false]ExplanationParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 111 ms (Top 92.4%) | Memory: 16.70 MB (Top 96.9%)\n\nclass ParkingSystem:\n def __init__(self, big: int, medium: int, small: int):\n self.vehicle =[big,medium,small]\n\n def addCar(self, carType: int) -> bool:\n if carType == 1 :\n if self.vehicle[0] > 0:\n self.vehicle[0]-=1\n return True\n elif carType == 2:\n if self.vehicle[1] > 0:\n self.vehicle[1]-=1\n return True\n elif carType == 3:\n if self.vehicle[2] > 0:\n self.vehicle[2]-=1\n return True\n return False", + "title": "1603. Design Parking System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a Skiplist without using any built-in libraries. A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way: Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n) . It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n) . See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list Implement the Skiplist class: Note that duplicates may exist in the Skiplist, your code needs to handle this situation.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/27/1506_skiplist.gif" + ], + "constraints": [ + "Skiplist() Initializes the object of the skiplist.", + "bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.", + "void add(int num) Inserts the value num into the SkipList.", + "bool erase(int num) Removes the value num from the Skiplist and returns true . If num does not exist in the Skiplist, do nothing and return false . If there exist multiple num values, removing any one of them is fine." + ], + "examples": [ + { + "text": "Example 1: Input[\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]Output[null, null, null, null, false, null, true, false, true, false]ExplanationSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 17.56%) | Memory: 57.1 MB (Top 16.13%)\nclass Skiplist {\n\n public static final int MAX_LEVEL = 4;\n\n private final int levels;\n\n private SkipListEntry head;\n\n private SkipListEntry tail;\n\n public Skiplist() {\n this(MAX_LEVEL);\n }\n\n public Skiplist(int levels) {\n this.levels = levels;\n\n //init new SkipList with defined level\n //Firstly, create the root level (level = 0) entry for left (min) and right (max)\n // and linked it\n // LEFT <------------------------------------------------> RIGHT\n SkipListEntry left = new SkipListEntry(Integer.MIN_VALUE, Integer.MIN_VALUE);\n SkipListEntry right = new SkipListEntry(Integer.MAX_VALUE, Integer.MAX_VALUE);\n left.right = right;\n right.left = left;\n\n // After, we can define left and right as the head and tail nodes\n // HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n this.head = left;\n this.tail = right;\n\n // Next, we can define left and right nodes for other levels and linked it\n // 0 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 1 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 2 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 3 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // N HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n for (int i = 1; i < this.levels; i++) {\n left.down = new SkipListEntry(\n Integer.MIN_VALUE,\n Integer.MIN_VALUE,\n null,\n null,\n left,\n null\n );\n left = left.down;\n\n right.down = new SkipListEntry(\n Integer.MAX_VALUE,\n Integer.MAX_VALUE,\n null,\n null,\n right,\n null\n );\n right = right.down;\n\n left.right = right;\n right.left = left;\n }\n }\n\n public boolean search(int target) {\n return this.find(target).key == target;\n }\n\n public void add(int num) {\n // We have to always start from head\n SkipListEntry current = this.head;\n\n // For the searching newNode we have to:\n // 1 - start from the head\n // 2 - go down the bottom level\n while (current.hasDown()) {\n current = current.down;\n }\n\n // 3 - try to find newNode\n while (current.hasRight() && num > current.right.key) {\n current = current.right;\n }\n\n // 4 - if we found newNode on the step 3, we have to do nothing (return;)\n if (num == current.key) {\n return;\n }\n\n // 5 - otherwise, we have to a put new newNode on the right\n SkipListEntry newNode = new SkipListEntry(num, num, current, current.right);\n current.right.left = newNode;\n current.right = newNode;\n\n // 6 - have to go up one level\n // 7 - flip the coin\n // 8 - if on the step 8 true - repeat step 5\n for (int level = this.levels - 2; level >= 0; level--) {\n if (!this.coinFlip(level)) {\n return;\n }\n\n // go up one level and find left node for new level\n while (!current.hasUp() && current.hasLeft()) {\n current = current.left;\n }\n current = current.up;\n\n newNode.up = new SkipListEntry(\n num,\n num,\n current,\n current.right,\n null,\n newNode\n );\n newNode = newNode.up;\n\n current.right.left = newNode;\n current.right = newNode;\n }\n }\n\n public boolean erase(int num) {\n SkipListEntry entry = this.find(num);\n if (entry.key != num) {\n return false;\n }\n\n entry.left.right = entry.right;\n entry.right.left = entry.left;\n\n while ((entry = entry.up) != null) {\n entry.left.right = entry.right;\n entry.right.left = entry.left;\n }\n\n return true;\n }\n\n private SkipListEntry find(int key) {\n // We have to always start from head\n SkipListEntry current = this.head;\n\n // while node has right or down we can go down a level or right\n // 1 - we have to go right and try to find element\n // 2 - if element is not presented at this level, we have to go down a level\n // and repeat step 1\n // 3 - if we found element we have to go down to the bottom\n // if we found element we have to return it, otherwise - return last visited\n while (current != null && current.hasRight()) {\n while (current.hasRight() && key > current.right.key) {\n current = current.right;\n }\n\n if (key == current.right.key) {\n current = current.right;\n while (current.hasDown()) {\n current = current.down;\n }\n\n return current;\n }\n\n current = current.down;\n }\n\n return this.head;\n }\n\n private boolean coinFlip(int level) {\n return ThreadLocalRandom.current().nextInt(this.levels - level) == 0;\n }\n\n public static class SkipListEntry {\n\n private final int key;\n\n private final int value;\n\n private SkipListEntry up;\n\n private SkipListEntry down;\n\n private SkipListEntry left;\n\n private SkipListEntry right;\n\n public SkipListEntry(int key, int value) {\n this(key, value, null, null, null, null);\n }\n\n public SkipListEntry(int key,\n int value,\n SkipListEntry left,\n SkipListEntry right) {\n this(key, value, left, right, null, null);\n }\n\n public SkipListEntry(int key,\n int value,\n SkipListEntry left,\n SkipListEntry right,\n SkipListEntry up,\n SkipListEntry down) {\n this.key = key;\n this.value = value;\n this.left = left;\n this.right = right;\n this.up = up;\n this.down = down;\n }\n\n public int getKey() {\n return this.key;\n }\n\n public int getValue() {\n return this.value;\n }\n\n public SkipListEntry left() {\n if (!this.hasLeft()) {\n return null;\n }\n\n return this.left;\n }\n\n public void setLeft(SkipListEntry entry) {\n this.left = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry right() {\n if (!this.hasRight()) {\n return null;\n }\n\n return this.right;\n }\n\n public void setRight(SkipListEntry entry) {\n this.right = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry up() {\n if (!this.hasUp()) {\n return null;\n }\n\n return this.up;\n }\n\n public void setUp(SkipListEntry entry) {\n this.up = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry getDown() {\n return this.down;\n }\n\n public SkipListEntry down() {\n if (!this.hasDown()) {\n return null;\n }\n\n return this.down;\n }\n\n public void setDown(SkipListEntry entry) {\n this.down = Objects.requireNonNull(entry);\n }\n\n public boolean hasLeft() {\n return this.left != null;\n }\n\n public boolean hasRight() {\n return this.right != null;\n }\n\n public boolean hasUp() {\n return this.up != null;\n }\n\n public boolean hasDown() {\n return this.down != null;\n }\n }\n }", + "title": "1206. Design Skiplist", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a Skiplist without using any built-in libraries. A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way: Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n) . It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n) . See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list Implement the Skiplist class: Note that duplicates may exist in the Skiplist, your code needs to handle this situation.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/27/1506_skiplist.gif" + ], + "constraints": [ + "Skiplist() Initializes the object of the skiplist.", + "bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.", + "void add(int num) Inserts the value num into the SkipList.", + "bool erase(int num) Removes the value num from the Skiplist and returns true . If num does not exist in the Skiplist, do nothing and return false . If there exist multiple num values, removing any one of them is fine." + ], + "examples": [ + { + "text": "Example 1: Input[\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]Output[null, null, null, null, false, null, true, false, true, false]ExplanationSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3867 ms (Top 5.16%) | Memory: 20.8 MB (Top 90.23%)\nclass Skiplist:\n def __init__(self):\n self.data = []\n def search(self, target: int) -> bool:\n if target in self.data:\n return True\n else:\n return False\n def add(self, num: int) -> None:\n self.data.append(num)\n def erase(self, num: int) -> bool:\n for i in range(len(self.data)):\n if self.data[i] == num:\n self.data.pop(i)\n return True\n if num not in self.data:\n return False", + "title": "1206. Design Skiplist", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Twitter\", \"postTweet\", \"getNewsFeed\", \"follow\", \"postTweet\", \"getNewsFeed\", \"unfollow\", \"getNewsFeed\"]\n[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]Output[null, null, [5], null, null, [6, 5], null, [5]]ExplanationTwitter twitter = new Twitter();\ntwitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).\ntwitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]\ntwitter.follow(1, 2); // User 1 follows user 2.\ntwitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).\ntwitter.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.\ntwitter.unfollow(1, 2); // User 1 unfollows user 2.\ntwitter.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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Twitter:\n\n def __init__(self):\n self.tweets = []\n self.friends = defaultdict(list)\n\n def postTweet(self, userId: int, tweetId: int) -> None:\n self.tweets.append([userId, tweetId]) \n\n def getNewsFeed(self, userId: int) -> List[int]:\n try:\n tweets = [x[1] for x in self.tweets if x[0] in [userId]+self.friends[userId]]\n return list(reversed(tweets))[:10]\n except:\n return \n\n def follow(self, followerId: int, followeeId: int) -> None:\n self.friends[followerId].append(followeeId) \n\n def unfollow(self, followerId: int, followeeId: int) -> None:\n try:\n self.friends[followerId].remove(followeeId)\n except:\n pass\n", + "title": "355. Design Twitter", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t 1 then checks out at time t 2 , then t 1 < t 2 . All events happen in chronological order.", + "description_images": [], + "constraints": [ + "void checkIn(int id, string stationName, int t) A customer with a card ID equal to id , checks in at the station stationName at time t . A customer can only be checked into one place at a time.", + "A customer with a card ID equal to id , checks in at the station stationName at time t .", + "A customer can only be checked into one place at a time.", + "void checkOut(int id, string stationName, int t) A customer with a card ID equal to id , checks out from the station stationName at time t .", + "A customer with a card ID equal to id , checks out from the station stationName at time t .", + "double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation . The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation . The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation . There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.", + "Returns the average time it takes to travel from startStation to endStation .", + "The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation .", + "The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation .", + "There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called." + ], + "examples": [ + { + "text": "Example 1: Input[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]Output[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12", + "image": null + }, + { + "text": "Example 2: Input[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]Output[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 92 ms (Top 65.05%) | Memory: 55.90 MB (Top 20.97%)\n\nclass Passenger {\n int checkinTime;\n int checkoutTime;\n String checkinLocation;\n String checkoutLocation;\n\n public Passenger(String checkinLocation, int checkinTime) {\n this.checkinLocation = checkinLocation;\n this.checkinTime = checkinTime;\n }\n\n void checkout(String checkoutLocation, int checkoutTime) {\n this.checkoutLocation = checkoutLocation;\n this.checkoutTime = checkoutTime;\n }\n\n}\n\nclass Route {\n String startStation;\n String endStation;\n int totalNumberOfTrips;\n long totalTimeSpentInTrips;\n\n public Route(String startStation, String endStation) {\n this.startStation = startStation;\n this.endStation = endStation;\n }\n\n double getAverageTime() {\n return (double) totalTimeSpentInTrips / totalNumberOfTrips;\n }\n\n void addTrip(int startTime, int endTime) {\n totalTimeSpentInTrips += endTime - startTime;\n totalNumberOfTrips++;\n }\n}\n\nclass UndergroundSystem {\n\n Map currentPassengerMap;\n Map routeMap;\n\n public UndergroundSystem() {\n currentPassengerMap = new HashMap<>();\n routeMap = new HashMap<>();\n }\n\n public void checkIn(int id, String stationName, int t) {\n if (!currentPassengerMap.containsKey(id)) {\n Passenger passenger = new Passenger(stationName, t);\n currentPassengerMap.put(id, passenger);\n }\n }\n\n public void checkOut(int id, String stationName, int t) {\n if (currentPassengerMap.containsKey(id)) {\n Passenger passenger = currentPassengerMap.get(id);\n passenger.checkout(stationName, t);\n String routeKey = passenger.checkinLocation + \",\" + passenger.checkoutLocation;\n Route route = routeMap.getOrDefault(routeKey, new Route(passenger.checkinLocation, passenger.checkoutLocation));\n route.addTrip(passenger.checkinTime, passenger.checkoutTime);\n routeMap.put(routeKey, route);\n currentPassengerMap.remove(id);\n }\n }\n\n public double getAverageTime(String startStation, String endStation) {\n return routeMap.get(startStation + \",\" + endStation).getAverageTime();\n }\n}\n", + "title": "1396. Design Underground System", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t 1 then checks out at time t 2 , then t 1 < t 2 . All events happen in chronological order.", + "description_images": [], + "constraints": [ + "void checkIn(int id, string stationName, int t) A customer with a card ID equal to id , checks in at the station stationName at time t . A customer can only be checked into one place at a time.", + "A customer with a card ID equal to id , checks in at the station stationName at time t .", + "A customer can only be checked into one place at a time.", + "void checkOut(int id, string stationName, int t) A customer with a card ID equal to id , checks out from the station stationName at time t .", + "A customer with a card ID equal to id , checks out from the station stationName at time t .", + "double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation . The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation . The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation . There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.", + "Returns the average time it takes to travel from startStation to endStation .", + "The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation .", + "The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation .", + "There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called." + ], + "examples": [ + { + "text": "Example 1: Input[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]Output[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12", + "image": null + }, + { + "text": "Example 2: Input[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]Output[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 441 ms (Top 30.19%) | Memory: 23.9 MB (Top 87.19%)\nfrom collections import defaultdict\nclass UndergroundSystem:\n def __init__(self):\n self.checkin = {}\n self.traveltime = defaultdict(dict)\n\n def checkIn(self, id: int, stationName: str, t: int) -> None:\n self.checkin[id] = (stationName, t)\n\n def checkOut(self, id: int, stationName: str, t: int) -> None:\n startStation, startTime = self.checkin[id]\n del self.checkin[id]\n if stationName not in self.traveltime[startStation]:\n self.traveltime[startStation][stationName] = []\n self.traveltime[startStation][stationName].append(t-startTime)\n\n def getAverageTime(self, startStation: str, endStation: str) -> float:\n return sum(self.traveltime[startStation][endStation])/len(self.traveltime[startStation][endStation])", + "title": "1396. Design Underground System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the array paths , where paths[i] = [cityA i , cityB i ] means there exists a direct path going from cityA i to cityB i . Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.", + "description_images": [], + "constraints": [ + "1 <= paths.length <= 100", + "paths[i].length == 2", + "1 <= cityA i .length, cityB i .length <= 10", + "cityA i != cityB i", + "All strings consist of lowercase and uppercase English letters and the space character." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput:\"Sao Paulo\"\nExplanation:Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".", + "image": null + }, + { + "text": "Example 2: Input:paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput:\"A\"\nExplanation:All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".", + "image": null + }, + { + "text": "Example 3: Input:paths = [[\"A\",\"Z\"]]\nOutput:\"Z\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 58.98%) | Memory: 44 MB (Top 40.73%)\nclass Solution {\n public String destCity(List> paths) {\n HashSet set1 = new HashSet<>();\n\n for (int i = 0; i < paths.size(); ++i) {\n set1.add(paths.get(i).get(0));\n }\n for (int i = 0; i < paths.size(); ++i) {\n if (!set1.contains(paths.get(i).get(1))) return paths.get(i).get(1);\n }\n return \"placeholder\";\n }\n}", + "title": "1436. Destination City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the array paths , where paths[i] = [cityA i , cityB i ] means there exists a direct path going from cityA i to cityB i . Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.", + "description_images": [], + "constraints": [ + "1 <= paths.length <= 100", + "paths[i].length == 2", + "1 <= cityA i .length, cityB i .length <= 10", + "cityA i != cityB i", + "All strings consist of lowercase and uppercase English letters and the space character." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput:\"Sao Paulo\"\nExplanation:Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".", + "image": null + }, + { + "text": "Example 2: Input:paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput:\"A\"\nExplanation:All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".", + "image": null + }, + { + "text": "Example 3: Input:paths = [[\"A\",\"Z\"]]\nOutput:\"Z\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 101 ms (Top 25.06%) | Memory: 13.8 MB (Top 81.64%)\nfrom collections import defaultdict\nclass Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n deg = defaultdict(int)\n for v, w in paths:\n deg[v] += 1\n deg[w]\n for v in deg:\n if not deg[v]: return v", + "title": "1436. Destination City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer mass , which represents the original mass of a planet. You are further given an integer array asteroids , where asteroids[i] is the mass of the i th asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order . If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= mass <= 10^5", + "1 <= asteroids.length <= 10^5", + "1 <= asteroids[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mass = 10, asteroids = [3,9,19,5,21]\nOutput:true\nExplanation:One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.", + "image": null + }, + { + "text": "Example 2: Input:mass = 5, asteroids = [4,9,23,4]\nOutput:false\nExplanation:The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 476 ms (Top 5.23%) | Memory: 135.2 MB (Top 5.23%)\nclass Solution {\n public boolean asteroidsDestroyed(int mass, int[] asteroids) {\n PriorityQueue maxHeap = new PriorityQueue<>((a,b)->b-a);\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for(int val:asteroids)\n maxHeap.add(val);\n\n long bigMass = mass;\n\n while(maxHeap.size()>0){\n int curr = maxHeap.poll();\n\n if(bigMass>=curr){\n bigMass+=curr;\n while(minHeap.size()>0 && bigMass>=minHeap.peek()){\n bigMass+=minHeap.poll();\n }\n }\n else{\n minHeap.add(curr);\n }\n }\n\n return minHeap.size()==0 && maxHeap.size()==0;\n }\n}", + "title": "2126. Destroying Asteroids", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer mass , which represents the original mass of a planet. You are further given an integer array asteroids , where asteroids[i] is the mass of the i th asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order . If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= mass <= 10^5", + "1 <= asteroids.length <= 10^5", + "1 <= asteroids[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mass = 10, asteroids = [3,9,19,5,21]\nOutput:true\nExplanation:One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.", + "image": null + }, + { + "text": "Example 2: Input:mass = 5, asteroids = [4,9,23,4]\nOutput:false\nExplanation:The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2207 ms (Top 14.71%) | Memory: 27.8 MB (Top 42.78%)\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n asteroids = sorted(asteroids)\n for i in asteroids:\n if i <= mass:\n mass += i\n else:\n return False\n return True", + "title": "2126. Destroying Asteroids", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We define the usage of capitals in a word to be right when one of the following cases holds: Given a string word , return true if the usage of capitals in it is right.", + "description_images": [], + "constraints": [ + "All letters in this word are capitals, like \"USA\" .", + "All letters in this word are not capitals, like \"leetcode\" .", + "Only the first letter in this word is capital, like \"Google\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"USA\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:word = \"FlaG\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 29.72%) | Memory: 41.4 MB (Top 86.57%)\nclass Solution {\n public boolean detectCapitalUse(String word) {\n int count = 0;\n for(int i=0; i < word.length(); i++){\n if('A' <= word.charAt(i) && word.charAt(i) <= 'Z')\n count++;\n }\n if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt(0) && word.charAt(0) <= 'Z')))\n return true;\n else\n return false;\n }\n}", + "title": "520. Detect Capital", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We define the usage of capitals in a word to be right when one of the following cases holds: Given a string word , return true if the usage of capitals in it is right.", + "description_images": [], + "constraints": [ + "All letters in this word are capitals, like \"USA\" .", + "All letters in this word are not capitals, like \"leetcode\" .", + "Only the first letter in this word is capital, like \"Google\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"USA\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:word = \"FlaG\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def detectCapitalUse(self, word: str) -> bool:\n l=len(word)\n if l==1:\n return True\n if word[0]==word[0].lower() and word[1]==word[1].upper():\n return False\n \n u=False\n if word[0]==word[0].upper():\n if word[1]==word[1].upper():\n u=True\n \n for i in word[2:]:\n if i==i.upper() and u==False:\n return False\n elif i==i.lower() and u==True:\n return False\n return True\n", + "title": "520. Detect Capital", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D array of characters grid of size m x n , you need to find if there exists any cycle consisting of the same value in grid . A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid , otherwise, return false .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/15/1.png", + "https://assets.leetcode.com/uploads/2020/07/15/22.png", + "https://assets.leetcode.com/uploads/2020/07/15/3.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\nOutput:true\nExplanation:There are two valid cycles shown in different colors in the image below:", + "image": null + }, + { + "text": "Example 2: Input:grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\nOutput:true\nExplanation:There is only one valid cycle highlighted in the image below:", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsCycle(char[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n\n\t\t// Create a boolean array of same dimensions to keep track of visited cells\n boolean[][] visited = new boolean[rows][cols];\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {\n return true;\n }\n }\n }\n\n return false;\n }\n \n public boolean dfs(\n char[][] grid,\n boolean[][] visited,\n int i,\n int j,\n int prevI,\n int prevJ,\n char c\n ) {\n\t\t// Check for out of bounds\n if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;\n\n\t\t// Check whether the current char matches the previous char\n if (grid[i][j] != c) return false;\n\t\t\n\t\t// If we stumble upon the same cell, we're guaranteed to have found a cycle!\n if (visited[i][j]) {\n return true;\n }\n \n\t\t// Mark the cell as visited\n visited[i][j] = true;\n \n\t\t// We want to search in the south direction ONLY IF we didn't come from north\n\t\t// Do the same for all four directions\n boolean south = i - prevI != -1;\n boolean north = i - prevI != 1;\n boolean east = j - prevJ != -1;\n boolean west = j - prevJ != 1;\n return\n (south && dfs(grid, visited, i + 1, j, i, j, c)) ||\n (north && dfs(grid, visited, i - 1, j, i, j, c)) ||\n (east && dfs(grid, visited, i, j + 1, i, j, c)) ||\n (west && dfs(grid, visited, i, j - 1, i, j, c));\n }\n}\n", + "title": "1559. Detect Cycles in 2D Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D array of characters grid of size m x n , you need to find if there exists any cycle consisting of the same value in grid . A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid , otherwise, return false .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/15/1.png", + "https://assets.leetcode.com/uploads/2020/07/15/22.png", + "https://assets.leetcode.com/uploads/2020/07/15/3.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\nOutput:true\nExplanation:There are two valid cycles shown in different colors in the image below:", + "image": null + }, + { + "text": "Example 2: Input:grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\nOutput:true\nExplanation:There is only one valid cycle highlighted in the image below:", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n \n def getNeighbours(row,col,char):\n neighbours = []\n if row > 0 and grid[row-1][col] == char and not visited[row-1][col]:\n neighbours.append([row-1,col])\n if col > 0 and grid[row][col-1] == char and not visited[row][col-1]:\n neighbours.append([row,col-1])\n if row < len(grid)-1 and grid[row+1][col] == char and not visited[row+1][col]:\n neighbours.append([row+1,col])\n if col < len(grid[0])-1 and grid[row][col+1] == char and not visited[row][col+1]:\n neighbours.append([row,col+1])\n return neighbours\n \n def dfs(row,col,char,cyclePresent):\n if visited[row][col] or cyclePresent:\n cyclePresent = True\n return cyclePresent\n visited[row][col] = True\n neighbours = getNeighbours(row,col,char)\n for r,c in neighbours:\n cyclePresent = dfs(r,c,char,cyclePresent)\n return cyclePresent\n \n visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\n cyclePresent = False\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if cyclePresent:\n return True\n if visited[row][col]:\n continue\n cyclePresent = dfs(row,col,grid[row][col],cyclePresent)\n \n return cyclePresent\n", + "title": "1559. Detect Cycles in 2D Grid", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of positive integers arr , find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 100", + "1 <= arr[i] <= 100", + "1 <= m <= 100", + "2 <= k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,4,4,4,4], m = 1, k = 3\nOutput:true\nExplanation:The pattern(4)of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\nOutput:true\nExplanation:The pattern(1,2)of length 2 is repeated 2 consecutive times. Another valid pattern(2,1) isalso repeated 2 times.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,1,2,1,3], m = 2, k = 3\nOutput:false\nExplanation:The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public boolean containsPattern(int[] arr, int m, int k) {\n int count = 0;\n for (int i = 0; i < arr.length - m; i++) {\n if (arr[i] == arr[i + m]) {\n count++;\n } else {\n count = 0;\n }\n if (count == m * (k-1)) {\n return true;\n }\n }\n return false;\n }\n}\n", + "title": "1566. Detect Pattern of Length M Repeated K or More Times", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers arr , find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 100", + "1 <= arr[i] <= 100", + "1 <= m <= 100", + "2 <= k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,4,4,4,4], m = 1, k = 3\nOutput:true\nExplanation:The pattern(4)of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\nOutput:true\nExplanation:The pattern(1,2)of length 2 is repeated 2 consecutive times. Another valid pattern(2,1) isalso repeated 2 times.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,1,2,1,3], m = 2, k = 3\nOutput:false\nExplanation:The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n if len(arr) < k*m:\n return False\n \n n = len(arr)\n pattern = arr[0:m]\n repeats = 1\n for i in range(m, n - m + 1, m):\n if arr[i:i+m] != pattern:\n break\n \n repeats += 1\n if repeats >= k:\n return True\n \n return self.containsPattern(arr[1:], m, k)", + "title": "1566. Detect Pattern of Length M Repeated K or More Times", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a stream of points on the X-Y plane. Design an algorithm that: 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:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]Output[null, null, null, null, 1, 0, null, 2]ExplanationDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points", + "image": "https://assets.leetcode.com/uploads/2021/09/01/image.png" + } + ], + "follow_up": null, + "solution": "class DetectSquares {\n List coordinates;\n Map counts;\n \n public DetectSquares() {\n coordinates = new ArrayList<>();\n counts = new HashMap<>();\n }\n \n public void add(int[] point) {\n coordinates.add(point);\n String key = point[0] + \"@\" + point[1];\n counts.put(key, counts.getOrDefault(key, 0) + 1);\n }\n \n public int count(int[] point) {\n int sum = 0, px = point[0], py = point[1];\n for (int[] coordinate : coordinates) {\n int x = coordinate[0], y = coordinate[1];\n if (px == x || py == y || (Math.abs(px - x) != Math.abs(py - y)))\n continue;\n sum += counts.getOrDefault(x + \"@\" + py, 0) * counts.getOrDefault(px + \"@\" + y, 0);\n }\n \n return sum;\n }\n}\n", + "title": "2013. Detect Squares", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a stream of points on the X-Y plane. Design an algorithm that: 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:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]Output[null, null, null, null, 1, 0, null, 2]ExplanationDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points", + "image": "https://assets.leetcode.com/uploads/2021/09/01/image.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 658 ms (Top 42.61%) | Memory: 16 MB (Top 39.48%)\n\"\"\"\nStore every points and number of their appearance\nGroup the points by their x value\n\nGiven a point(x1,y1) to count, try to find p2(x1,y2),p3(x2,y2),p4(x2,y1)\nand add product of their appearances\n\nGo through every points that has same x1(except the point that is the same as (x1,y1), the length of the side of the square is decided by abd(y2-y1).\n\nUse the decided side length to calculate p3 and p4, see if they are in the dict. If do, add product of their appearances.\n\np3 p2 p3`\n\np4 p1 p4`\n\nNotice that p3 and p4 can be on both left side and right side of side (p2,p1)\n\n\"\"\"\nfrom collections import defaultdict\nclass DetectSquares:\n\n def __init__(self):\n self.pts=defaultdict(int)\n self.by_x=defaultdict(set)\n\n def add(self, point: List[int]) -> None:\n self.pts[(point[0],point[1])]+=1\n self.by_x[point[0]].add((point[0],point[1]))\n\n def count(self, p1: List[int]) -> int:\n res=0\n x1,y1=p1[0],p1[1]\n if x1 in self.by_x:\n #p2:x1,y2\n for p2 in self.by_x[x1]:\n x2,y2=p2\n if y1==y2:\n continue\n #length of side of square\n b=abs(y1-y2)\n #left side\n p3=(x1-b,y2)\n p4=(x1-b,y1)\n if p3 in self.pts and p4 in self.pts:\n res+=self.pts[p2]*self.pts[p3]*self.pts[p4]\n #right side\n p3=(x1+b,y2)\n p4=(x1+b,y1)\n if p3 in self.pts and p4 in self.pts:\n res+=self.pts[p2]*self.pts[p3]*self.pts[p4]\n return res\n\n# Your DetectSquares object will be instantiated and called as such:\n# obj = DetectSquares()\n# obj.add(point)\n# param_2 = obj.count(point)", + "title": "2013. Detect Squares", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given coordinates , a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black . The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png" + ], + "constraints": [ + "coordinates.length == 2", + "'a' <= coordinates[0] <= 'h'", + "'1' <= coordinates[1] <= '8'" + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = \"a1\"\nOutput:false\nExplanation:From the chessboard above, the square with coordinates \"a1\" is black, so return false.", + "image": null + }, + { + "text": "Example 2: Input:coordinates = \"h3\"\nOutput:true\nExplanation:From the chessboard above, the square with coordinates \"h3\" is white, so return true.", + "image": null + }, + { + "text": "Example 3: Input:coordinates = \"c7\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean squareIsWhite(String coordinates) {\n return (coordinates.charAt(0) - 'a'+ coordinates.charAt(1) - '0')%2==0 ;\n }\n}\n", + "title": "1812. Determine Color of a Chessboard Square", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given coordinates , a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black . The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png" + ], + "constraints": [ + "coordinates.length == 2", + "'a' <= coordinates[0] <= 'h'", + "'1' <= coordinates[1] <= '8'" + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = \"a1\"\nOutput:false\nExplanation:From the chessboard above, the square with coordinates \"a1\" is black, so return false.", + "image": null + }, + { + "text": "Example 2: Input:coordinates = \"h3\"\nOutput:true\nExplanation:From the chessboard above, the square with coordinates \"h3\" is white, so return true.", + "image": null + }, + { + "text": "Example 3: Input:coordinates = \"c7\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 10.11%) | Memory: 13.8 MB (Top 56.37%)\nclass Solution:\n def squareIsWhite(self, coordinates: str) -> bool:\n return (ord(coordinates[0])+ord(coordinates[1]))%2", + "title": "1812. Determine Color of a Chessboard Square", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' ). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike . Otherwise, return false .", + "description_images": [], + "constraints": [ + "2 <= s.length <= 1000", + "s.length is even.", + "s consists of uppercase and lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"book\"\nOutput:true\nExplanation:a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.", + "image": null + }, + { + "text": "Example 2: Input:s = \"textbook\"\nOutput:false\nExplanation:a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 23.59%) | Memory: 42.5 MB (Top 46.22%)\nclass Solution {\n public boolean halvesAreAlike(String s) {\n //add vowels to the set\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n\n //find the mid\n int mid = s.length() / 2;\n int count = 0;\n //increment the count for left half, decrement count for the second half if its a vowel\n for (int i = 0; i < s.length(); i++)\n count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0;\n //finally count should be 0 to match left and right half\n return count == 0;\n }\n}", + "title": "1704. Determine if String Halves Are Alike", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' ). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike . Otherwise, return false .", + "description_images": [], + "constraints": [ + "2 <= s.length <= 1000", + "s.length is even.", + "s consists of uppercase and lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"book\"\nOutput:true\nExplanation:a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.", + "image": null + }, + { + "text": "Example 2: Input:s = \"textbook\"\nOutput:false\nExplanation:a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.", + "image": null + } + ], + "follow_up": null, + "solution": "vowels = \"aeiouAEIOU\"\n\nclass Solution:\n def halvesAreAlike(self, S: str) -> bool:\n mid, ans = len(S) // 2, 0\n for i in range(mid):\n if S[i] in vowels: ans += 1\n if S[mid+i] in vowels: ans -=1\n return ans == 0\n", + "title": "1704. Determine if String Halves Are Alike", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise.", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"\nOutput:true\nExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"\nOutput:false\nExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"\nOutput:true\nExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"Apply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 51.63%) | Memory: 58.9 MB (Top 49.30%)\nclass Solution {\n private int N = 26;\n public boolean closeStrings(String word1, String word2) {\n // count the English letters\n int[] arr1 = new int[N], arr2 = new int[N];\n for (char ch : word1.toCharArray())\n arr1[ch - 'a']++;\n for (char ch : word2.toCharArray())\n arr2[ch - 'a']++;\n\n // if one has a letter which another one doesn't have, dont exist\n for (int i = 0; i < N; i++) {\n if (arr1[i] == arr2[i]) {\n continue;\n }\n if (arr1[i] == 0 || arr2[i] == 0) {\n return false;\n }\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n for (int i = 0; i < N; i++) {\n if (arr1[i] != arr2[i]) {\n return false;\n }\n }\n return true;\n }\n}", + "title": "1657. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise.", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"\nOutput:true\nExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"\nOutput:false\nExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"\nOutput:true\nExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"Apply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 70.4%) | Memory: 17.77 MB (Top 49.0%)\n\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())", + "title": "1657. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two n x n binary matrices mat and target , return true if it is possible to make mat equal to target by rotating mat in 90-degree increments , or false otherwise.", + "description_images": [], + "constraints": [ + "n == mat.length == target.length", + "n == mat[i].length == target[i].length", + "1 <= n <= 10", + "mat[i][j] and target[i][j] are either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput:true\nExplanation:We can rotate mat 90 degrees clockwise to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid3.png" + }, + { + "text": "Example 2: Input:mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput:false\nExplanation:It is impossible to make mat equal to target by rotating mat.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid4.png" + }, + { + "text": "Example 3: Input:mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput:true\nExplanation:We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/26/grid4.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 6.49%) | Memory: 42.9 MB (Top 12.04%)\nclass Solution {\n public boolean findRotation(int[][] mat, int[][] target) {\n if (mat == target) return true;\n int n = mat.length;\n int[] res[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 90\n for (int j = 0; j < n; j++) {\n res[i][j] = mat[n - 1 - j][i];\n }\n }\n\n int[] res2[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 180\n for (int j = 0; j < n; j++) {\n res2[i][j] = res[n - 1 - j][i];\n }\n }\n\n int[] res3[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 270\n for (int j = 0; j < n; j++) {\n res3[i][j] = res2[n - 1 - j][i];\n }\n }\n\n //compare to 90,180,270 and itself\n if(Arrays.deepEquals(target, res) || Arrays.deepEquals(target, res2) || Arrays.deepEquals(target, res3) || Arrays.deepEquals(target, mat) ){\n return true;\n }\n return false;\n }\n}\n\n// Arrays.deepEquals() use for matrix", + "title": "1886. Determine Whether Matrix Can Be Obtained By Rotation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two n x n binary matrices mat and target , return true if it is possible to make mat equal to target by rotating mat in 90-degree increments , or false otherwise.", + "description_images": [], + "constraints": [ + "n == mat.length == target.length", + "n == mat[i].length == target[i].length", + "1 <= n <= 10", + "mat[i][j] and target[i][j] are either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput:true\nExplanation:We can rotate mat 90 degrees clockwise to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid3.png" + }, + { + "text": "Example 2: Input:mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput:false\nExplanation:It is impossible to make mat equal to target by rotating mat.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid4.png" + }, + { + "text": "Example 3: Input:mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput:true\nExplanation:We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/26/grid4.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n \n # if already equal\n if target == mat:\n return True\n # there are 4 different rotation with 90 deg. \n # We need to check at most 3 more rotation.\n for i in range(3):\n # transpose the matrix by swap row and col values.\n for j in range(len(mat)):\n for k in range(j+1, len(mat)):\n mat[j][k], mat[k][j] = mat[k][j], mat[j][k]\n # Reflect the row by reverse it.\n mat[j] = mat[j][::-1]\n # now the matrix is roteted; check if they're alike.\n if target == mat:\n return True\n return False\n", + "title": "1886. Determine Whether Matrix Can Be Obtained By Rotation", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [x i , y i , r i ] . x i and y i denote the X-coordinate and Y-coordinate of the location of the i th bomb, whereas r i denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs , return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb .", + "description_images": [], + "constraints": [ + "1 <= bombs.length <= 100", + "bombs[i].length == 3", + "1 <= x i , y i , r i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:bombs = [[2,1,3],[6,1,4]]\nOutput:2\nExplanation:The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-3.png" + }, + { + "text": "Example 2: Input:bombs = [[1,1,5],[10,10,5]]\nOutput:1\nExplanation:Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-2.png" + }, + { + "text": "Example 3: Input:bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\nOutput:5\nExplanation:The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/desmos-eg1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 234 ms (Top 36.67%) | Memory: 42.3 MB (Top 94.92%)\nclass Solution {\n /*\n Make directed graph\n u -> v means, v is in the range of u\n check from which node maximum nodes can be reached and return the number of nodes reached\n */\n public int maximumDetonation(int[][] bombs) {\n Map> graph = new HashMap<>();\n\n int n = bombs.length;\n for(int i = 0; i< n; i++){\n graph.put(i, new ArrayList<>());\n for(int j = 0; j< n; j++){\n if(i == j) continue;\n if(inRange(bombs[i], bombs[j]))\n graph.get(i).add(j);\n }\n }\n\n int max = 0;\n for(int i = 0; i< n; i++){\n max = Math.max(max, dfs(i, graph, new HashSet<>()));\n }\n return max;\n }\n\n private boolean inRange(int[] u, int[] v){\n // (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border\n // (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle\n // (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle\n return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);\n }\n\n private int dfs(int node, Map> graph, Set visited){\n if(visited.contains(node)) return 0;\n visited.add(node);\n int res = 0;\n for(int neigh: graph.get(node)){\n res += dfs(neigh, graph, visited);\n }\n return res + 1;\n }\n}", + "title": "2101. Detonate the Maximum Bombs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [x i , y i , r i ] . x i and y i denote the X-coordinate and Y-coordinate of the location of the i th bomb, whereas r i denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs , return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb .", + "description_images": [], + "constraints": [ + "1 <= bombs.length <= 100", + "bombs[i].length == 3", + "1 <= x i , y i , r i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:bombs = [[2,1,3],[6,1,4]]\nOutput:2\nExplanation:The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-3.png" + }, + { + "text": "Example 2: Input:bombs = [[1,1,5],[10,10,5]]\nOutput:1\nExplanation:Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-2.png" + }, + { + "text": "Example 3: Input:bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\nOutput:5\nExplanation:The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/desmos-eg1.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maximumDetonation(self, bombs):\n def count(i):\n dq, ret = [i], [i]\n while len(dq) > 0:\n i = dq.pop()\n for j in adj[i]:\n if j not in ret and j not in dq:\n dq.append(j)\n ret.append(j)\n return len(ret)\n\n adj = collections.defaultdict(list)\n for i in range(len(bombs)):\n for j in range(i + 1, len(bombs)):\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:\n adj[i].append(j)\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:\n adj[j].append(i)\n ret = 0\n for i in range(len(bombs)):\n ret = max(ret, count(i))\n return ret\n", + "title": "2101. Detonate the Maximum Bombs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: Given a string s , reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them .", + "description_images": [], + "constraints": [ + "s[i] == 'I' if perm[i] < perm[i + 1] , and", + "s[i] == 'D' if perm[i] > perm[i + 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"IDID\"\nOutput:[0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:s = \"III\"\nOutput:[0,1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:s = \"DDI\"\nOutput:[3,2,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 7.32%) | Memory: 48.4 MB (Top 38.52%)\nclass Solution {\n public int[] diStringMatch(String s) {\n int low = 0;\n int high = s.length();\n int[] ans = new int[s.length() + 1];\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'I'){\n ans[i] = low++;\n } else{\n ans[i] = high--;\n }\n }\n ans[s.length()] = high;\n return ans;\n }\n}", + "title": "942. DI String Match", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: Given a string s , reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them .", + "description_images": [], + "constraints": [ + "s[i] == 'I' if perm[i] < perm[i + 1] , and", + "s[i] == 'D' if perm[i] > perm[i + 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"IDID\"\nOutput:[0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:s = \"III\"\nOutput:[0,1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:s = \"DDI\"\nOutput:[3,2,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n result = []\n min_ = 0\n max_ = len(s)\n for x in s:\n if x==\"I\":\n result.append(min_)\n min_ += 1\n elif x==\"D\":\n result.append(max_)\n max_ -= 1\n result.append(min_)\n return result\n", + "title": "942. DI String Match", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix mat , return an array of all the elements of the array in a diagonal order .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "-10^5 <= mat[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,2,4,7,5,3,6,8,9]", + "image": "https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]]\nOutput:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 98.1%) | Memory: 45.96 MB (Top 86.5%)\n\n/**\n * Simulate Diagonal Order Traversal\n *\n * r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all\n * on same diagonal with r+c =2. If you check the directions of diagonals, first\n * diagonal is up, second diagonal is down, third one is up and so on..\n * Therefore (r+c)%2 simply determines direction. Even is UP direction. Odd is\n * DOWN direction.\n *\n * Time Complexity: O(M*N)\n *\n * Space Complexity: O(1) without considering result space.\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n public int[] findDiagonalOrder(int[][] matrix) {\n if (matrix == null) {\n throw new IllegalArgumentException(\"Input matrix is null\");\n }\n if (matrix.length == 0 || matrix[0].length == 0) {\n return new int[0];\n }\n\n int rows = matrix.length;\n int cols = matrix[0].length;\n int[] result = new int[rows * cols];\n int r = 0;\n int c = 0;\n\n for (int i = 0; i < result.length; i++) {\n result[i] = matrix[r][c];\n if ((r + c) % 2 == 0) { // Move Up\n if (c == cols - 1) {\n // Reached last column. Now move to below cell in the same column.\n // This condition needs to be checked first due to top right corner cell.\n r++;\n } else if (r == 0) {\n // Reached first row. Now move to next cell in the same row.\n c++;\n } else {\n // Somewhere in middle. Keep going up diagonally.\n r--;\n c++;\n }\n } else { // Move Down\n if (r == rows - 1) {\n // Reached last row. Now move to next cell in same row.\n // This condition needs to be checked first due to bottom left corner cell.\n c++;\n } else if (c == 0) {\n // Reached first columns. Now move to below cell in the same column.\n r++;\n } else {\n // Somewhere in middle. Keep going down diagonally.\n r++;\n c--;\n }\n }\n }\n\n return result;\n }\n}", + "title": "498. Diagonal Traverse", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix mat , return an array of all the elements of the array in a diagonal order .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "-10^5 <= mat[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,2,4,7,5,3,6,8,9]", + "image": "https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]]\nOutput:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:\n flag, rowNum, colNum = True, len(mat), len(mat[0])\n\n total, ans = 0, []\n while total <= rowNum + colNum - 2:\n iLimited = rowNum - 1 if flag else colNum - 1 \n jLimited = colNum - 1 if flag else rowNum - 1\n i = total if total < iLimited else iLimited\n j = total - i\n while i >= 0 and j <= jLimited:\n if flag:\n ans.append(mat[i][j])\n else:\n ans.append(mat[j][i])\n i -= 1\n j += 1\n total += 1\n flag = not flag\n return ans\n", + "title": "498. Diagonal Traverse", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array nums , return all elements of nums in diagonal order as shown in the below images .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i].length <= 10^5", + "1 <= sum(nums[i].length) <= 10^5", + "1 <= nums[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,4,2,7,5,3,8,6,9]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" + }, + { + "text": "Example 2: Input:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" + } + ], + "follow_up": null, + "solution": "\tclass Solution {\npublic int[] findDiagonalOrder(List> nums) {\n HashMap> map = new HashMap();\n \n for(int i = 0 ; i < nums.size() ; i++){\n for(int j = 0 ; j < nums.get(i).size() ; j++){\n int z = i + j;\n if(map.containsKey(z)){\n map.get(z).add(nums.get(i).get(j));\n }else{\n Stack stk = new Stack<>();\n stk.push(nums.get(i).get(j));\n map.put(z , stk);\n }\n }\n }\n ArrayList arr = new ArrayList<>();\n int k = 0;\n while(true){\n if(map.containsKey(k)){\n int size = map.get(k).size();\n while(size-- > 0){\n arr.add(map.get(k).pop());\n }\n k++;\n }else{\n break;\n }\n }\n int[] res = new int[arr.size()];\n for(int i = 0 ; i < res.length ; i++){\n res[i] = arr.get(i);\n }\n \n return res;\n}}\n", + "title": "1424. Diagonal Traverse II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D integer array nums , return all elements of nums in diagonal order as shown in the below images .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i].length <= 10^5", + "1 <= sum(nums[i].length) <= 10^5", + "1 <= nums[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,4,2,7,5,3,8,6,9]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" + }, + { + "text": "Example 2: Input:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t# sort the index of element\n heap = list()\n n = len(nums)\n for i in range(n):\n m = len(nums[i])\n for j in range(m):\n heapq.heappush(heap,[i+j,j,i])\n\t\t\t\t\n\t\t# append the element one by one\n ans = []\n while heap:\n temp = heapq.heappop(heap)\n ans.append(nums[temp[2]][temp[1]])\n return ans\n", + "title": "1424. Diagonal Traverse II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]\nOutput:3\nExplanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.91%) | Memory: 42.9 MB (Top 74.91%)\nclass Solution {\n // Declare Global Variable ans to 0\n int ans = 0;\n // Depth First Search Function\n public int dfs(TreeNode root) {\n if(root == null) return 0;\n // recursive call for left height\n int lh = dfs(root.left);\n // recursive call for right height\n int rh = dfs(root.right);\n\n // update ans\n ans = Math.max(ans, lh + rh);\n\n // return max value\n return Math.max(lh, rh) + 1;\n }\n\n // Diameter of Binary Tree Function\n public int diameterOfBinaryTree(TreeNode root) {\n // Call dfs Function\n dfs(root);\n return ans;\n }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(n)\n*/", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]\nOutput:3\nExplanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 16.95%) | Memory: 16.5 MB (Top 10.21%)\nclass Solution:\n \"\"\"\n Top Down recursion approach: it is sub optimal\n \"\"\"\n def __init__(self):\n self.max_diameter = 0\n def diameter(self, root):\n if root is None:\n return 0\n return self.max_depth(root.left) + self.max_depth(root.right)\n\n def max_depth(self, root):\n if root is None:\n return 0\n return 1 + max(self.max_depth(root.left), self.max_depth(root.right))\n\n def func(self, root):\n if root is not None:\n diameter = self.diameter(root)\n if self.max_diameter < diameter:\n self.max_diameter = diameter\n self.diameterOfBinaryTree(root.left)\n self.diameterOfBinaryTree(root.right)\n\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.func(root)\n return self.max_diameter\n\n \"\"\"\n Better Approach: I can try to approach this problem using bottom up recursion\n \"\"\"\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.diameter = 0\n def fun(root):\n if root is None:\n return 0\n left = fun(root.left)\n right = fun(root.right)\n if left + right > self.diameter:\n self.diameter = left + right\n return max(left, right) + 1\n fun(root)\n return self.diameter", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] ( 1-indexed ) consecutive times. Given an array of integers rollMax and an integer n , return the number of distinct sequences that can be obtained with exact n rolls . Since the answer may be too large, return it modulo 10^9 + 7 . Two sequences are considered different if at least one element differs from each other.", + "description_images": [], + "constraints": [ + "1 <= n <= 5000", + "rollMax.length == 6", + "1 <= rollMax[i] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, rollMax = [1,1,2,2,2,3]\nOutput:34\nExplanation:There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, rollMax = [1,1,1,1,1,1]\nOutput:30", + "image": null + }, + { + "text": "Example 3: Input:n = 3, rollMax = [1,1,1,2,2,3]\nOutput:181", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 149 ms (Top 22.45%) | Memory: 56.7 MB (Top 20.41%)\nclass Solution {\n long[][][] dp;\n int mod = 1_000_000_007;\n public int dieSimulator(int n, int[] rollMax) {\n dp = new long[n + 1][7][16];\n for(long[][] row: dp)\n for(long[] col: row)\n Arrays.fill(col, -1);\n\n return (int)helper(n, 0, 0, rollMax, 0);\n }\n\n private long helper(int n, int dice, int prev, int[] rollMax, int runs)\n {\n if(n == dice)\n return 1;\n\n if(dp[dice][prev][runs] != -1)\n return dp[dice][prev][runs];\n\n long ans = 0;\n int[] temp = rollMax;\n for(int i = 1; i <= 6; i++)\n {\n if(prev != 0 && i == prev && rollMax[i-1] <= runs)\n continue;\n if(i == prev)\n ans = (ans + helper(n, dice + 1, i, rollMax, runs + 1)) % mod;\n else\n ans = (ans + helper(n, dice + 1, i, rollMax, 1)) % mod;\n }\n\n dp[dice][prev][runs] = ans;\n return ans;\n }\n}", + "title": "1223. Dice Roll Simulation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] ( 1-indexed ) consecutive times. Given an array of integers rollMax and an integer n , return the number of distinct sequences that can be obtained with exact n rolls . Since the answer may be too large, return it modulo 10^9 + 7 . Two sequences are considered different if at least one element differs from each other.", + "description_images": [], + "constraints": [ + "1 <= n <= 5000", + "rollMax.length == 6", + "1 <= rollMax[i] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, rollMax = [1,1,2,2,2,3]\nOutput:34\nExplanation:There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, rollMax = [1,1,1,1,1,1]\nOutput:30", + "image": null + }, + { + "text": "Example 3: Input:n = 3, rollMax = [1,1,1,2,2,3]\nOutput:181", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n dp = {}\n def solve(n,last,count):\n if n == 0: return 1\n if (n,last,count) in dp: return dp[(n,last,count)]\n ans = 0\n for i in range(6):\n if last == i:\n if count == rollMax[i]: continue\n ans += solve(n-1,last,count + 1)\n else:\n ans += solve(n-1,i,1)\n dp[(n,last,count)] = ans\n return ans\n \n return solve(n,None,0) % 1000000007\n", + "title": "1223. Dice Roll Simulation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators . You may return the answer in any order . The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 10^4 .", + "description_images": [], + "constraints": [ + "1 <= expression.length <= 20", + "expression consists of digits and the operator '+' , '-' , and '*' .", + "All the integer values in the input expression are in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"2-1-1\"\nOutput:[0,2]\nExplanation:((2-1)-1) = 0 \n(2-(1-1)) = 2", + "image": null + }, + { + "text": "Example 2: Input:expression = \"2*3-4*5\"\nOutput:[-34,-14,-10,-10,10]\nExplanation:(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 79.5%) | Memory: 41.16 MB (Top 75.1%)\n\nclass Solution {\n Map> memo = new HashMap<>();\n public List diffWaysToCompute(String expression) {\n List res = new LinkedList<>();\n if(memo.containsKey(expression)) return memo.get(expression);\n\n for(int i = 0; i left = diffWaysToCompute(expression.substring(0, i));\n List right = diffWaysToCompute(expression.substring(i+1));\n\n //conquer\n for(int a : left){\n for(int b : right){\n if(c == '+'){\n res.add(a+b);\n }else if(c == '-'){\n res.add(a - b);\n }else if(c == '*'){\n res.add(a * b);\n }\n }\n }\n \n }\n }\n //base case, when there is no operator\n if(res.isEmpty()){\n res.add(Integer.parseInt(expression));\n }\n memo.put(expression, res);\n return res; \n }\n}", + "title": "241. Different Ways to Add Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators . You may return the answer in any order . The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 10^4 .", + "description_images": [], + "constraints": [ + "1 <= expression.length <= 20", + "expression consists of digits and the operator '+' , '-' , and '*' .", + "All the integer values in the input expression are in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"2-1-1\"\nOutput:[0,2]\nExplanation:((2-1)-1) = 0 \n(2-(1-1)) = 2", + "image": null + }, + { + "text": "Example 2: Input:expression = \"2*3-4*5\"\nOutput:[-34,-14,-10,-10,10]\nExplanation:(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 49 ms (Top 17.3%) | Memory: 13.54 MB (Top 39.1%)\n\nclass Solution(object):\n def diffWaysToCompute(self, input):\n m = {}\n return self.dfs(input, m)\n \n def dfs(self, input, m):\n if input in m:\n return m[input]\n if input.isdigit():\n m[input] = int(input)\n return [int(input)]\n ret = []\n for i, c in enumerate(input):\n if c in \"+-*\":\n l = self.diffWaysToCompute(input[:i])\n r = self.diffWaysToCompute(input[i+1:])\n ret.extend(eval(str(x)+c+str(y)) for x in l for y in r)\n m[input] = ret\n return ret", + "title": "241. Different Ways to Add Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0 , each of the stacks has the same maximum capacity. Implement the DinnerPlates class:", + "description_images": [], + "constraints": [ + "DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity .", + "void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity .", + "int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.", + "int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty." + ], + "examples": [ + { + "text": "Example 1: Input[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]Output[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\nExplanation:DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.", + "image": null + } + ], + "follow_up": null, + "solution": "class DinnerPlates {\n \n List> stack;\n PriorityQueue leftEmpty;\n PriorityQueue rightNonEmpty;\n int cap;\n public DinnerPlates(int capacity) {\n this.cap = capacity;\n this.stack = new ArrayList<>();\n this.leftEmpty = new PriorityQueue<>();\n this.rightNonEmpty = new PriorityQueue<>(Collections.reverseOrder());\n stack.add(new Stack<>());\n leftEmpty.offer(0);\n }\n \n public void push(int val) {\n while(!leftEmpty.isEmpty() && stack.get(leftEmpty.peek()).size() == cap) leftEmpty.poll();\n if(leftEmpty.isEmpty()) {\n stack.add(new Stack<>());\n leftEmpty.offer(stack.size() - 1);\n }\n Stack s = stack.get(leftEmpty.peek());\n if(s.isEmpty()) rightNonEmpty.offer(leftEmpty.peek());\n s.push(val);\n }\n \n public int pop() {\n while(!rightNonEmpty.isEmpty() && stack.get(rightNonEmpty.peek()).isEmpty()) rightNonEmpty.poll();\n if(rightNonEmpty.isEmpty()) {\n return -1;\n } \n Stack s = stack.get(rightNonEmpty.peek());\n if(s.size() == cap) leftEmpty.offer(rightNonEmpty.peek());\n return s.pop();\n }\n \n public int popAtStack(int index) {\n if(index >= stack.size()) return -1;\n Stack s = stack.get(index);\n if(s.isEmpty()) return -1;\n if(s.size() == cap) leftEmpty.offer(index);\n return s.pop();\n }\n}\n\n/**\n * Your DinnerPlates object will be instantiated and called as such:\n * DinnerPlates obj = new DinnerPlates(capacity);\n * obj.push(val);\n * int param_2 = obj.pop();\n * int param_3 = obj.popAtStack(index);\n */", + "title": "1172. Dinner Plate Stacks", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0 , each of the stacks has the same maximum capacity. Implement the DinnerPlates class:", + "description_images": [], + "constraints": [ + "DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity .", + "void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity .", + "int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.", + "int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty." + ], + "examples": [ + { + "text": "Example 1: Input[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]Output[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\nExplanation:DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.", + "image": null + } + ], + "follow_up": null, + "solution": "class DinnerPlates:\n\n def __init__(self, capacity: int):\n self.heap = []\n self.stacks = []\n self.capacity = capacity\n\n def push(self, val: int) -> None:\n if self.heap:\n index = heapq.heappop(self.heap)\n if index < len(self.stacks):\n self.stacks[index].append(val)\n else:\n self.push(val)\n elif self.stacks:\n lastStack = self.stacks[-1]\n if len(lastStack) != self.capacity:\n lastStack.append(val)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n \n def pop(self) -> int:\n while self.stacks:\n lastStack = self.stacks[-1]\n if lastStack:\n val = lastStack.pop()\n if not lastStack:\n self.stacks.pop()\n return val\n else:\n self.stacks.pop()\n return -1\n\n def popAtStack(self, index: int) -> int:\n if index == len(self.stacks) - 1:\n return self.pop()\n if index < len(self.stacks):\n stack = self.stacks[index]\n if stack:\n val = stack.pop()\n heapq.heappush(self.heap, index)\n return val\n return -1\n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)\n", + "title": "1172. Dinner Plate Stacks", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the array orders , which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerName i ,tableNumber i ,foodItem i ] where customerName i is the name of the customer, tableNumber i is the table customer sit at, and foodItem i is the item customer orders. Return the restaurant's “ display table ” . The “ display table ” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.", + "description_images": [], + "constraints": [ + "1 <= orders.length <= 5 * 10^4", + "orders[i].length == 3", + "1 <= customerName i .length, foodItem i .length <= 20", + "customerName i and foodItem i consist of lowercase and uppercase English letters and the space character.", + "tableNumber i is a valid integer between 1 and 500 ." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]\nOutput:[[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]]\nExplanation:The displaying table looks like:Table,Beef Burrito,Ceviche,Fried Chicken,Water3 ,0 ,2 ,1 ,0\n5 ,0 ,1 ,0 ,1\n10 ,1 ,0 ,0 ,0\nFor the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\nFor the table 5: Carla orders \"Water\" and \"Ceviche\".\nFor the table 10: Corina orders \"Beef Burrito\".", + "image": null + }, + { + "text": "Example 2: Input:orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]\nOutput:[[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]]\nExplanation:For the table 1: Adam and Brianna order \"Canadian Waffles\".\nFor the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".", + "image": null + }, + { + "text": "Example 3: Input:orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]\nOutput:[[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 157 ms (Top 14.06%) | Memory: 126.7 MB (Top 62.50%)\nclass Solution {\n public List> displayTable(List> orders) {\n List> ans = new ArrayList<>();\n List head = new ArrayList<>();\n head.add(\"Table\");\n Map> map = new TreeMap<>();\n for(List s: orders){\n if(!head.contains(s.get(2))) head.add(s.get(2));\n int tbl = Integer.parseInt(s.get(1));\n map.putIfAbsent(tbl, new TreeMap<>());\n if(map.get(tbl).containsKey(s.get(2))){\n Map m = map.get(tbl);\n m.put(s.get(2), m.getOrDefault(s.get(2), 0)+1);\n }else{\n map.get(tbl).put(s.get(2), 1);\n }\n }\n String[] arr = head.toArray(new String[0]);\n Arrays.sort(arr, 1, head.size());\n head = Arrays.asList(arr);\n ans.add(head);\n\n for(Map.Entry> entry: map.entrySet()){\n List l = new ArrayList<>();\n l.add(entry.getKey() + \"\");\n Map m = entry.getValue();\n for(int i=1; i List[List[str]]:\n column = ['Table']\n dish = []\n table_dict = {}\n for order_row in orders : \n if order_row[-1] not in dish :\n dish.append(order_row[-1])\n \n for order_row in orders :\n if order_row[1] not in table_dict.keys() :\n table_dict[order_row[1]] = {}\n for food in dish : \n table_dict[order_row[1]][food] = 0 \n table_dict[order_row[1]][order_row[-1]] += 1\n else : \n table_dict[order_row[1]][order_row[-1]] += 1 \n \n dish.sort()\n column = column + dish \n ans = [column]\n table = []\n childDict = {}\n for key in sorted(table_dict.keys()) : \n table.append(int(key))\n childDict[key] = []\n for value in column : \n if value != 'Table' :\n childDict[key].append(str(table_dict[key][value]))\n table.sort()\n output = [ans[0]]\n for table_num in table : \n childList = [str(table_num)]\n output.append(childList + childDict[str(table_num)])\n return output \n", + "title": "1418. Display Table of Food Orders in a Restaurant", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n . The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg" + ], + "constraints": [ + "1 <= n <= 10^4", + "distance.length == n", + "0 <= start, destination < n", + "0 <= distance[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [1,2,3,4], start = 0, destination = 1\nOutput:1\nExplanation:Distance between 0 and 1 is 1 or 9, minimum is 1.", + "image": null + }, + { + "text": "Example 2: Input:distance = [1,2,3,4], start = 0, destination = 2\nOutput:3\nExplanation:Distance between 0 and 2 is 3 or 7, minimum is 3.", + "image": null + }, + { + "text": "Example 3: Input:distance = [1,2,3,4], start = 0, destination = 3\nOutput:4\nExplanation:Distance between 0 and 3 is 6 or 4, minimum is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 7.93%) | Memory: 42.8 MB (Top 57.93%)\nclass Solution {\n public int distanceBetweenBusStops(int[] distance, int start, int destination) {\n int firstDistance = 0;\n int secondDistance = 0;\n if (start < destination) {\n //check clockwise rotation\n for (int i = start; i < destination; i++)\n firstDistance += distance[i];\n //check clockwise rotation from destination to end\n for (int i = destination; i < distance.length; i++)\n secondDistance += distance[i];\n //continues checking till start (if needed)\n for (int i = 0; i < start; i++)\n secondDistance += distance[i];\n }\n else {\n for (int i = start; i < distance.length; i++)\n firstDistance += distance[i];\n for (int i = 0; i < destination; i++)\n firstDistance += distance[i];\n for (int i = start - 1; i >= destination; i--)\n secondDistance += distance[i];\n }\n return Math.min(firstDistance, secondDistance);\n }\n}", + "title": "1184. Distance Between Bus Stops", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n . The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg" + ], + "constraints": [ + "1 <= n <= 10^4", + "distance.length == n", + "0 <= start, destination < n", + "0 <= distance[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [1,2,3,4], start = 0, destination = 1\nOutput:1\nExplanation:Distance between 0 and 1 is 1 or 9, minimum is 1.", + "image": null + }, + { + "text": "Example 2: Input:distance = [1,2,3,4], start = 0, destination = 2\nOutput:3\nExplanation:Distance between 0 and 2 is 3 or 7, minimum is 3.", + "image": null + }, + { + "text": "Example 3: Input:distance = [1,2,3,4], start = 0, destination = 3\nOutput:4\nExplanation:Distance between 0 and 3 is 6 or 4, minimum is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n # switch start and destination if destination is before start\n if start>destination: \n start,destination=destination,start\n #find minimum for clockwise and counterclockwise direction\n return min(sum(distance[start:destination]),sum(distance[:start]+distance[destination:]))", + "title": "1184. Distance Between Bus Stops", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a warehouse, there is a row of barcodes, where the i th barcode is barcodes[i] . Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.", + "description_images": [], + "constraints": [ + "1 <= barcodes.length <= 10000", + "1 <= barcodes[i] <= 10000" + ], + "examples": [ + { + "text": "Example 1: Input:barcodes = [1,1,1,2,2,2]\nOutput:[2,1,2,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:barcodes = [1,1,1,1,2,2,3,3]\nOutput:[1,3,1,3,1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] rearrangeBarcodes(int[] barcodes) {\n \n if(barcodes.length <= 2){\n return barcodes ; //Problem says solution always exist.\n }\n \n Map count = new HashMap<>();\n Integer maxKey = null; // Character having max frequency\n \n for(int i: barcodes){\n count.put(i, count.getOrDefault(i, 0) + 1);\n if(maxKey == null || count.get(i) > count.get(maxKey)){\n maxKey = i;\n }\n }\n \n int pos = 0;\n \n //Fill maxChar\n int curr = count.get(maxKey);\n while(curr-- > 0){\n barcodes[pos] = maxKey;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n \n count.remove(maxKey); // Since that character is done, we don't need to fill it again\n \n //Fill the remaining Characters.\n for(int key: count.keySet()){\n curr = count.get(key);\n \n while(curr-- > 0){\n barcodes[pos] = key;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n }\n \n return barcodes;\n }\n}\n", + "title": "1054. Distant Barcodes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a warehouse, there is a row of barcodes, where the i th barcode is barcodes[i] . Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.", + "description_images": [], + "constraints": [ + "1 <= barcodes.length <= 10000", + "1 <= barcodes[i] <= 10000" + ], + "examples": [ + { + "text": "Example 1: Input:barcodes = [1,1,1,2,2,2]\nOutput:[2,1,2,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:barcodes = [1,1,1,1,2,2,3,3]\nOutput:[1,3,1,3,1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1287 ms (Top 5.56%) | Memory: 16.2 MB (Top 67.41%)\n\nimport heapq\n\nclass Solution:\n\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n barcodes_counter = Counter(barcodes)\n if len(barcodes_counter) == len(barcodes):\n return barcodes\n\n barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ]\n heapq.heapify(barcodes_heapq)\n\n idx, prev_count, prev_barcode = 0, 0, 0\n while barcodes_heapq:\n (curr_count, curr_barcode) = heapq.heappop(barcodes_heapq)\n\n barcodes[idx] = curr_barcode\n idx += 1\n curr_count += 1\n\n if prev_count:\n heapq.heappush(barcodes_heapq, (prev_count, prev_barcode))\n\n prev_count, prev_barcode = curr_count, curr_barcode\n\n return barcodes\n", + "title": "1054. Distant Barcodes", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2000", + "text has only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abcabcabc\"\nOutput:3\nExplanation:The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"leetcodeleetcode\"\nOutput:2\nExplanation:The 2 substrings are \"ee\" and \"leetcodeleetcode\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int PRIME = 101;\n private static final int MOD = 1_000_000_007;\n public int distinctEchoSubstrings(String text) {\n int n = text.length();\n \n // dp[i][j] : hash value of text[i:j]\n int[][] dp = new int[n][n];\n for (int i = 0; i < n; i++) {\n long hash = 0;\n for (int j = i; j < n; j++) {\n hash = hash * PRIME + (text.charAt(j) - 'a' + 1);\n hash %= MOD;\n dp[i][j] = (int) hash;\n }\n }\n \n Set set = new HashSet<>();\n int res = 0;\n for (int i = 0; i < n-1; i++) {\n // compare text[i:j] with text[j+1: 2j-i+1]\n for (int j = i; 2*j - i + 1 < n; j++) {\n if (dp[i][j] == dp[j+1][2*j - i+1] && set.add(dp[i][j])) res++;\n }\n }\n \n return res;\n }\n}\n", + "title": "1316. Distinct Echo Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2000", + "text has only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abcabcabc\"\nOutput:3\nExplanation:The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"leetcodeleetcode\"\nOutput:2\nExplanation:The 2 substrings are \"ee\" and \"leetcodeleetcode\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctEchoSubstrings(self, s: str) -> int:\n hash=set()\n n=len(s)\n for i in range(n):\n for j in range(i):\n \n if (i-j)&1==1:\n \n k=(i-j)//2\n \n if s[j:j+k+1]==s[j+k+1:i+1]:\n hash.add(s[j:j+k+1]+s[j+k+1:i+1])\n return len(hash)\n \n \n \n \n", + "title": "1316. Distinct Echo Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return the number of distinct subsequences of s which equals t . A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not). The test cases are generated so that the answer fits on a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 1000", + "s and t consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"rabbbit\", t = \"rabbit\"\nOutput:3\nExplanation:As shown below, there are 3 ways you can generate \"rabbit\" from S.rabbbitrabbbitrabbbit", + "image": null + }, + { + "text": "Example 2: Input:s = \"babgbag\", t = \"bag\"\nOutput:5\nExplanation:As shown below, there are 5 ways you can generate \"bag\" from S.babgbagbabgbagbabgbagbabgbagbabgbag", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]\n int f(int i,int j,String s,String t,int dp[][]){\n //If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found a subsequence)\n if(j<0)\n return 1;\n // if s gets exhausted then there are characters remaining in t which are yet to be matched as s got exhausted they could not be matched so there is no distinct subsequence\n if(i<0){\n return 0;\n }\n if(dp[i][j]!=-1)\n return dp[i][j];\n //If both the characters in s[i] and t[j] match then we have two case\n //1) Either consider the i'th character of s and find the remaining distinct subsequences of s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)\n //2) Do not consider s[i] so we are still at the same j'th character of t as we had not been considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1] i.e. f(i-1,j)\n if(s.charAt(i)==t.charAt(j)){\n dp[i][j]= f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp);\n }\n // If both of them do not match then we consider the 2nd case of matching characters\n else{\n dp[i][j]=f(i-1,j,s,t,dp);\n } \n return dp[i][j];\n }\n public int numDistinct(String s, String t) {\n int n=s.length();\n int m=t.length();\n int dp[][]=new int[n][m];\n for(int i=0;i int:\n if len(t) > len(s):\n return 0\n ls, lt = len(s), len(t)\n res = 0\n dp = [[0] * (ls + 1) for _ in range(lt + 1)]\n for j in range(ls + 1):\n dp[-1][j] = 1\n for i in range(lt - 1, -1, -1):\n for j in range(ls -1 , -1, -1):\n dp[i][j] = dp[i][j + 1]\n if s[j] == t[i]:\n\n dp[i][j] += dp[i + 1][j + 1]\n return dp[0][0]", + "title": "115. Distinct Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s, return the number of distinct non-empty subsequences of s . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"\nOutput:7\nExplanation:The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:6\nExplanation:The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaa\"\nOutput:3\nExplanation:The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 61.84%) | Memory: 42.7 MB (Top 63.49%)\nclass Solution {\n public int distinctSubseqII(String s) {\n int mod = (int)1e9+7;\n //For storing the last occurred index of a character.\n Integer li[] = new Integer[26];\n int n = s.length();\n int[] dp = new int[n+1];\n //one empty string possible for a string of length 0.\n dp[0]=1;\n char[] c = s.toCharArray();\n for(int i=1;i<=n;i++){\n //If the character is first occurred then 2 cases\n //Case 1 : we will not concat the character with previous subsequences\n //Case 2 : we will concat it.\n //Therefore, we multiply 2 with previous count.\n int curr = (2 * (dp[i - 1] % mod)) % mod;\n //Getting the int index from char for checking the previous occurrence in li[]\n int idx=c[i-1]-'a';\n //If previously occurred then we have to subtract the subsequences which are made\n //till li[idx-1] because they would be duplicated and counted twice unnecessarily\n if(li[idx]!=null) dp[i]=(curr -dp[li[idx]-1] +mod)%mod;\n else dp[i]= curr;\n li[idx]=i;\n }\n //Doing -1 because we don't have to count the empty string.\n return dp[n]-1;\n }\n }", + "title": "940. Distinct Subsequences II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s, return the number of distinct non-empty subsequences of s . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"\nOutput:7\nExplanation:The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:6\nExplanation:The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaa\"\nOutput:3\nExplanation:The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctSubseqII(self, s: str) -> int:\n #number of subsequences that startwith each alphabet\n startwith = [0]*26\n for c in s[::-1]:\n startwith[ord(c)-ord('a')] = sum(startwith) + 1\n return sum(startwith)%(10**9+7)\n", + "title": "940. Distinct Subsequences II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice has n candies, where the i th candy is of type candyType[i] . Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has ( n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n , return the maximum number of different types of candies she can eat if she only eats n / 2 of them .", + "description_images": [], + "constraints": [ + "n == candyType.length", + "2 <= n <= 10^4", + "n is even.", + "-10^5 <= candyType[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:candyType = [1,1,2,2,3,3]\nOutput:3\nExplanation:Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.", + "image": null + }, + { + "text": "Example 2: Input:candyType = [1,1,2,3]\nOutput:2\nExplanation:Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.", + "image": null + }, + { + "text": "Example 3: Input:candyType = [6,6,6,6]\nOutput:1\nExplanation:Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int distributeCandies(int[] candyType) {\n Set set = new HashSet<>();\n for (int type : candyType) set.add(type);\n return Math.min(set.size(), candyType.length / 2);\n }\n}\n", + "title": "575. Distribute Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice has n candies, where the i th candy is of type candyType[i] . Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has ( n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n , return the maximum number of different types of candies she can eat if she only eats n / 2 of them .", + "description_images": [], + "constraints": [ + "n == candyType.length", + "2 <= n <= 10^4", + "n is even.", + "-10^5 <= candyType[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:candyType = [1,1,2,2,3,3]\nOutput:3\nExplanation:Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.", + "image": null + }, + { + "text": "Example 2: Input:candyType = [1,1,2,3]\nOutput:2\nExplanation:Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.", + "image": null + }, + { + "text": "Example 3: Input:candyType = [6,6,6,6]\nOutput:1\nExplanation:Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1728 ms (Top 12.88%) | Memory: 16.4 MB (Top 8.29%)\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(set(candyType)), (len(candyType)//2))", + "title": "575. Distribute Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We distribute some number of candies , to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies ) that represents the final distribution of candies.", + "description_images": [], + "constraints": [ + "1 <= candies <= 10^9", + "1 <= num_people <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:candies = 7, num_people = 4\nOutput:[1,2,3,1]\nExplanation:On the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].", + "image": null + }, + { + "text": "Example 2: Input:candies = 10, num_people = 3\nOutput:[5,2,3]\nExplanation:On the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] distributeCandies(int candies, int num_people) {\n int n=num_people;\n int a[]=new int[n];\n int k=1;\n while(candies>0){\n for(int i=0;i=k){\n a[i]+=k;\n candies-=k;\n k++;\n }\n else{\n a[i]+=candies;\n candies=0;\n break;\n }\n }\n }\n return a;\n }\n}", + "title": "1103. Distribute Candies to People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We distribute some number of candies , to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies ) that represents the final distribution of candies.", + "description_images": [], + "constraints": [ + "1 <= candies <= 10^9", + "1 <= num_people <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:candies = 7, num_people = 4\nOutput:[1,2,3,1]\nExplanation:On the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].", + "image": null + }, + { + "text": "Example 2: Input:candies = 10, num_people = 3\nOutput:[5,2,3]\nExplanation:On the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n candy_dict = {}\n for i in range(num_people) : \n candy_dict[i] = 0 \n \n candy, i, totalCandy = 1, 0, 0\n while totalCandy < candies : \n if i >= num_people : \n i = 0\n if candies - totalCandy >= candy : \n candy_dict[i] += candy \n totalCandy += candy\n else : \n candy_dict[i] += candies - totalCandy\n totalCandy += candies - totalCandy\n i += 1 \n candy += 1 \n return candy_dict.values()\n", + "title": "1103. Distribute Candies to People", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= n <= 100", + "0 <= Node.val <= n", + "The sum of all Node.val is n ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,0,0]\nOutput:2\nExplanation:From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree1.png" + }, + { + "text": "Example 2: Input:root = [0,3,0]\nOutput:3\nExplanation:From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 58.67%) | Memory: 43.1 MB (Top 15.04%)\nclass Solution {\n int count = 0;\n public int helper(TreeNode root)\n {\n if(root == null)\n return 0;\n int left = helper(root.left);\n int right = helper(root.right);\n count+= Math.abs(left)+Math.abs(right);\n return (left+right+root.val-1);\n }\n public int distributeCoins(TreeNode root) {\n helper(root);\n return count;\n }\n}", + "title": "979. Distribute Coins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= n <= 100", + "0 <= Node.val <= n", + "The sum of all Node.val is n ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,0,0]\nOutput:2\nExplanation:From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree1.png" + }, + { + "text": "Example 2: Input:root = [0,3,0]\nOutput:3\nExplanation:From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree2.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def distributeCoins(self, root: Optional[TreeNode]) -> int:\n \n def dfs(root):\n if not root:\n return 0,0\n \n net_left,left_walk = dfs(root.left)\n net_right,right_walk = dfs(root.right)\n \n\t\t\t# if any node has extra or deficiency in both cases there has to be a walk of abs(extra) or abs(deficiency)\n\t\t\t\n return net_left+net_right+(root.val-1), left_walk+right_walk+abs(net_left)+abs(net_right)\n return dfs(root)[1]\n", + "title": "979. Distribute Coins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of n integers, nums , where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity , where quantity[i] is the amount of integers the i th customer ordered. Determine if it is possible to distribute nums such that: Return true if it is possible to distribute nums according to the above conditions .", + "description_images": [], + "constraints": [ + "The i th customer gets exactly quantity[i] integers,", + "The integers the i th customer gets are all equal , and", + "Every customer is satisfied." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], quantity = [2]\nOutput:false\nExplanation:The 0thcustomer cannot be given two different integers.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3], quantity = [2]\nOutput:true\nExplanation:The 0thcustomer is given [3,3]. The integers [1,2] are not used.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], quantity = [2,2]\nOutput:true\nExplanation:The 0thcustomer is given [1,1], and the 1st customer is given [2,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 89.01%) | Memory: 60.70 MB (Top 18.68%)\n\nclass Solution {\n public boolean canDistribute(int[] nums, int[] quantity) {\n \n // Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}\n Map freq = new HashMap<>();\n for (int num : nums)\n freq.put(num, freq.getOrDefault(num, 0)+1);\n \n // Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]\n int[] dist = new int[freq.size()];\n int idx = 0;\n for (int f : freq.values())\n dist[idx++] = f;\n \n\t\t// Fullfill the quantities from the biggest quantity to the smallest.\n // If the bigger quantity can't be filled, the program will stop as early as possible.\n Arrays.sort(quantity);\n return rec(dist, quantity, quantity.length-1);\n }\n \n // try to fullfill the j-th order quantity\n private boolean rec(int[] dist, int[] quantity, int j) {\n \n // stop condition. We've fulfilled all the order quantities.\n if (j == -1)\n return true;\n \n Set used = new HashSet<>();\n for (int i = 0 ; i < dist.length ; ++i) {\n\t\t\n\t\t\t// Use a set to make sure that \n\t\t\t// we don't distribute from the same amount to this j-th order for more than once.\n // With this check, the program reduces from 97ms to 25 ms.\n if (dist[i] >= quantity[j] && used.add(dist[i])) {\n dist[i] -= quantity[j];\n if (rec(dist, quantity, j-1))\n return true;\n dist[i] += quantity[j];\n }\n }\n return false;\n }\n}\n", + "title": "1655. Distribute Repeating Integers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n integers, nums , where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity , where quantity[i] is the amount of integers the i th customer ordered. Determine if it is possible to distribute nums such that: Return true if it is possible to distribute nums according to the above conditions .", + "description_images": [], + "constraints": [ + "The i th customer gets exactly quantity[i] integers,", + "The integers the i th customer gets are all equal , and", + "Every customer is satisfied." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], quantity = [2]\nOutput:false\nExplanation:The 0thcustomer cannot be given two different integers.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3], quantity = [2]\nOutput:true\nExplanation:The 0thcustomer is given [3,3]. The integers [1,2] are not used.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], quantity = [2,2]\nOutput:true\nExplanation:The 0thcustomer is given [1,1], and the 1st customer is given [2,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 584 ms (Top 98.04%) | Memory: 28.70 MB (Top 26.47%)\n\nfrom collections import Counter, defaultdict\n\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n quantity.sort(reverse=True)\n freqCounts = defaultdict(int, Counter(Counter(nums).values()))\n def backtrack(i: int = 0) -> bool:\n if i == len(quantity):\n return True\n \n for freq, count in list(freqCounts.items()):\n if freq >= quantity[i] and count > 0:\n freqCounts[freq] -= 1\n freqCounts[freq - quantity[i]] += 1\n if backtrack(i + 1):\n return True\n freqCounts[freq] += 1\n freqCounts[freq - quantity[i]] -= 1\n \n return False\n \n return backtrack()\n", + "title": "1655. Distribute Repeating Integers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s . Given the string s , the size of each group k and the character fill , return a string array denoting the composition of every group s has been divided into, using the above procedure .", + "description_images": [], + "constraints": [ + "The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.", + "For the last group, if the string does not have k characters remaining, a character fill is used to complete the group." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcdefghi\", k = 3, fill = \"x\"\nOutput:[\"abc\",\"def\",\"ghi\"]\nExplanation:The first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdefghij\", k = 3, fill = \"x\"\nOutput:[\"abc\",\"def\",\"ghi\",\"jxx\"]\nExplanation:Similar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 96.0%) | Memory: 42.30 MB (Top 49.23%)\n\nclass Solution {\n public String[] divideString(String s, int k, char fill) {\n //the size of result array\n String[] r = new String[(int) Math.ceil((s.length() * 1.0) / k)];\n int idx;\n //if the last one needs to be filled, then I do it\n if (s.length() % k != 0) {\n idx = s.length() - (s.length() % k);\n StringBuilder sb = new StringBuilder();\n sb.append(s.substring(idx));\n for (int i = sb.length(); i < k; i++) {\n sb.append(fill);\n }\n r[r.length - 1] = sb.toString();\n } else {\n //no need to fill the last, \n //that's why idx is equal to s length\n idx = s.length();\n }\n for (int i = 0; i < idx; i+=k) {\n r[i / k] = s.substring(i, i + k);\n }\n \n return r;\n }\n}\n", + "title": "2138. Divide a String Into Groups of Size k", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s . Given the string s , the size of each group k and the character fill , return a string array denoting the composition of every group s has been divided into, using the above procedure .", + "description_images": [], + "constraints": [ + "The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.", + "For the last group, if the string does not have k characters remaining, a character fill is used to complete the group." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcdefghi\", k = 3, fill = \"x\"\nOutput:[\"abc\",\"def\",\"ghi\"]\nExplanation:The first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdefghij\", k = 3, fill = \"x\"\nOutput:[\"abc\",\"def\",\"ghi\",\"jxx\"]\nExplanation:Similar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 66.92%) | Memory: 17.30 MB (Top 6.27%)\n\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n return [(s+k*fill)[i:i+k] for i in range(0,len(s),k)]\n", + "title": "2138. Divide a String Into Groups of Size k", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and a positive integer k , check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,4,5,6], k = 4\nOutput:true\nExplanation:Array can be divided into [1,2,3,4] and [3,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput:true\nExplanation:Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], k = 3\nOutput:false\nExplanation:Each array should be divided in subarrays of size 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 127 ms (Top 67.88%) | Memory: 81.5 MB (Top 9.11%)\nclass Solution {\n public boolean isPossibleDivide(int[] nums, int k) {\n if (nums.length % k != 0) return false;\n Map countMap = new HashMap<>();\n for (int num : nums) {\n int count = countMap.getOrDefault(num, 0);\n countMap.put(num , count + 1);\n }\n Arrays.sort(nums);\n for (int num : nums) {\n if (!countMap.containsKey(num)) continue;\n int count = countMap.get(num);\n if (count == 1) countMap.remove(num);\n else countMap.put(num, count - 1);\n for (int i = 1; i < k; i++) {\n int next = num + i;\n if (!countMap.containsKey(next)) return false;\n count = countMap.get(next);\n if (count == 1) countMap.remove(next);\n else countMap.put(next, count - 1);\n }\n }\n return true;\n }\n}", + "title": "1296. Divide Array in Sets of K Consecutive Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums and a positive integer k , check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible . Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,4,5,6], k = 4\nOutput:true\nExplanation:Array can be divided into [1,2,3,4] and [3,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput:true\nExplanation:Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], k = 3\nOutput:false\nExplanation:Each array should be divided in subarrays of size 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 304 ms (Top 99.22%) | Memory: 27.60 MB (Top 95.6%)\n\nclass Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n # if we see x, we expect to see x+1 later\n # and then x+2 after that\n # and then x+3 after that\n\n # so maybe we can enqueue (x+1, k-2) === (next number expected, count after x+1)\n # e.g. k == 2: find x, enqueue (x+1, 0)\n \n # for each x:\n # if front of queue has x, pop it. Re-enqueue with rem-1 if rem, else we finished a length k sequence\n # if front of queue has x' < x, we have a gap. return False\n # otherwise we found the start of a new sequence: append (x+1, k-2)\n # meaning we found x (1), we're looking for x+1 (another 1), and after that we should find another k-2 numbers\n\n if k == 1: return True # length 1 sequences are trivial\n\n nums.sort()\n q = deque()\n for n in nums:\n if not q or q[0][0] > n:\n q.append((n+1, k-2))\n elif q[0][0] == n:\n _, rem = q.popleft()\n if rem:\n q.append((n+1, rem-1))\n # else: end of len k sequence\n else:\n return False # found n > next expected, so we can't complete an earlier sequence\n\n if q:\n return False # expected at least one more element to finish a sequence\n else:\n return True\n", + "title": "1296. Divide Array in Sets of K Consecutive Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false .", + "description_images": [], + "constraints": [ + "Each element belongs to exactly one pair.", + "The elements present in a pair are equal ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3,2,2,2]\nOutput:true\nExplanation:There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:false\nExplanation:There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 41.3%) | Memory: 44.12 MB (Top 6.5%)\n\nclass Solution {\n public boolean divideArray(int[] arr) {\n HashMap map = new HashMap<>();\n\n for (int i : arr) map.put(i, map.getOrDefault(i, 0) + 1);\n for (int i : map.keySet()) {\n if (map.get(i) % 2 != 0) return false;\n }\n return true;\n }\n}", + "title": "2206. Divide Array Into Equal Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false .", + "description_images": [], + "constraints": [ + "Each element belongs to exactly one pair.", + "The elements present in a pair are equal ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3,2,2,2]\nOutput:true\nExplanation:There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:false\nExplanation:There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 213 ms (Top 19.18%) | Memory: 14.1 MB (Top 63.60%)\nclass Solution:\n\n def divideArray(self, nums: List[int]) -> bool:\n lena = len(nums)\n count = sum(num//2 for num in Counter(nums).values())\n return (lena/2 == count)\n", + "title": "2206. Divide Array Into Equal Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8 , and -2.7335 would be truncated to -2 . Return the quotient after dividing dividend by divisor . Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1] . For this problem, if the quotient is strictly greater than 2 31 - 1 , then return 2 31 - 1 , and if the quotient is strictly less than -2 31 , then return -2 31 .", + "description_images": [], + "constraints": [ + "-2 31 <= dividend, divisor <= 2 31 - 1", + "divisor != 0" + ], + "examples": [ + { + "text": "Example 1: Input:dividend = 10, divisor = 3\nOutput:3\nExplanation:10/3 = 3.33333.. which is truncated to 3.", + "image": null + }, + { + "text": "Example 2: Input:dividend = 7, divisor = -3\nOutput:-2\nExplanation:7/-3 = -2.33333.. which is truncated to -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divide(int dividend, int divisor) {\n if(dividend == 1<<31 && divisor == -1){\n return Integer.MAX_VALUE;\n }\n boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false;\n \n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n \n int result = 0;\n while(dividend - divisor >= 0){\n int count = 0;\n while(dividend - (divisor << 1 << count) >= 0){\n count++;\n }\n result += 1 < int:\n # Solution 1 - bitwise operator << \n \"\"\"\n positive = (dividend < 0) is (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n\t\tif divisor == 1:\n quotient = dividend\n else: \n\t\t\tquotient = 0\n\t\t\twhile dividend >= divisor:\n\t\t\t\ttemp, i = divisor, 1\n\t\t\t\twhile dividend >= temp:\n\t\t\t\t\tdividend -= temp\n\t\t\t\t\tquotient += i\n\t\t\t\t\ti <<= 1\n\t\t\t\t\ttemp <<= 1\n\n\t\tif not positive:\n\t\t\treturn max(-2147483648, -quotient)\n\t\telse:\n\t\t\treturn min(quotient, 2147483647) \n \"\"\"\n # Solution 2 - cumulative sum - faster than bitwise \n positive = (dividend < 0) == (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor) \n if divisor == 1:\n quotient = dividend\n else: \n quotient = 0\n _sum = divisor\n\n while _sum <= dividend:\n current_quotient = 1\n while (_sum + _sum) <= dividend:\n _sum += _sum\n current_quotient += current_quotient\n dividend -= _sum\n _sum = divisor\n quotient += current_quotient \n if not positive:\n return max(-2147483648, -quotient)\n else:\n return min(quotient, 2147483647) \n", + "title": "29. Divide Two Integers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally .", + "description_images": [], + "constraints": [ + "Choosing any x with 0 < x < n and n % x == 0 .", + "Replacing the number n on the chalkboard with n - x ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:true\nExplanation:Alice chooses 1, and Bob has no more moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:false\nExplanation:Alice chooses 1, Bob chooses 1, and Alice has no more moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean divisorGame(int n) {\n return n%2==0;\n }\n}\n", + "title": "1025. Divisor Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally .", + "description_images": [], + "constraints": [ + "Choosing any x with 0 < x < n and n % x == 0 .", + "Replacing the number n on the chalkboard with n - x ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:true\nExplanation:Alice chooses 1, and Bob has no more moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:false\nExplanation:Alice chooses 1, Bob chooses 1, and Alice has no more moves.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 78.15%) | Memory: 16.60 MB (Top 64.13%)\n\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return n%2 == 0\n", + "title": "1025. Divisor Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:5\nExplanation:The five different ways are show above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.50 MB (Top 29.41%)\n\nclass Solution {\n public int numTilings(int n) {\n long[] dp = new long[n + 3]; dp[0] = 1; dp[1] = 2; dp[2] = 5;\n for (int i = 3; i < n; i ++) {\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007;\n }\n return (int)dp[n - 1];\n }\n}\n", + "title": "790. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:5\nExplanation:The five different ways are show above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 35 ms (Top 93.5%) | Memory: 16.27 MB (Top 85.2%)\n\nclass Solution(object):\n def numTilings(self, n):\n dp = [1, 2, 5] + [0] * n\n for i in range(3, n):\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007\n return dp[n - 1]", + "title": "790. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" .", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"\nOutput:\"Radiant\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"\nOutput:\"Dire\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Two Queues Solution\n// Two queues to store the R index and D index.\n// If the senate can execute his right, the senate is alive and can execute in the next round.\n// Then we can add the senate back to the queue and process in the next round (idx + N).\n// Time complexity: O(N), each loop we add/remove 1 senate in the queue.\n// Space complexity: O(N)\nclass Solution {\n public String predictPartyVictory(String senate) {\n if (senate == null || senate.length() == 0) throw new IllegalArgumentException(\"Invalid input.\");\n final int N = senate.length();\n Queue queR = new ArrayDeque<>(); // store the R index\n Queue queD = new ArrayDeque<>(); // store the D index\n for (int i = 0; i < N; i++) {\n if (senate.charAt(i) == 'R') {\n queR.add(i);\n } else {\n queD.add(i);\n }\n }\n while (!queR.isEmpty() && !queD.isEmpty()) {\n int r = queR.poll();\n int d = queD.poll();\n if (r < d) { // R is alive in the next round.\n queR.add(r + N);\n } else { // D is alive in the next round.\n queD.add(d + N);\n }\n }\n return queR.isEmpty() ? \"Dire\" : \"Radiant\";\n }\n}\n", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" .", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"\nOutput:\"Radiant\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"\nOutput:\"Dire\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 92.53%) | Memory: 16.90 MB (Top 59.64%)\n\nfrom collections import deque\n\nclass Solution:\n def predictPartyVictory(self, senate: str) -> str:\n n = len(senate)\n radiant = deque()\n dire = deque()\n for i, s in enumerate(senate):\n if s == 'R':\n radiant.append(i)\n else:\n dire.append(i)\n while radiant and dire:\n r_idx = radiant.popleft()\n d_idx = dire.popleft()\n if r_idx < d_idx:\n radiant.append(r_idx + n)\n else:\n dire.append(d_idx + n)\n return \"Radiant\" if radiant else \"Dire\"\n\n", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon . The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess . Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.", + "description_images": [], + "constraints": [ + "m == dungeon.length", + "n == dungeon[i].length", + "1 <= m, n <= 200", + "-1000 <= dungeon[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput:7\nExplanation:The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.", + "image": "https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg" + }, + { + "text": "Example 2: Input:dungeon = [[0]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer[][] min;\n public int calculateMinimumHP(int[][] dungeon) {\n min = new Integer[dungeon.length][dungeon[0].length];\n int answer = min(0, 0, dungeon);\n return Math.max(answer, 1);\n }\n public int min(int i, int j, int[][] dungeon){\n if(i > dungeon.length - 1 || j > dungeon[0].length - 1) return 400000;\n if(i == dungeon.length - 1 && j == dungeon[0].length - 1) return - dungeon[i][j] + 1; \n if(min[i][j] == null){\n int down = min(i + 1, j, dungeon);\n int right = min(i, j + 1, dungeon);\n min[i][j] = Math.min(Math.max(right, 1), Math.max(down, 1)) - dungeon[i][j];\n }\n return min[i][j];\n }\n}\n", + "title": "174. Dungeon Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon . The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess . Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.", + "description_images": [], + "constraints": [ + "m == dungeon.length", + "n == dungeon[i].length", + "1 <= m, n <= 200", + "-1000 <= dungeon[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput:7\nExplanation:The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.", + "image": "https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg" + }, + { + "text": "Example 2: Input:dungeon = [[0]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n\n\tdef calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n\n\t\tdp = defaultdict(lambda: inf)\n\t\tdp[(len(dungeon), len(dungeon[0]) - 1)] = 1\n\n\t\tfor i in range(len(dungeon) - 1, -1, -1):\n\n\t\t\tfor j in range(len(dungeon[0]) - 1, -1, -1):\n\n\t\t\t\tdp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i][j]\n\n\t\t\t\tif dp[(i, j)] <= 0:\n\t\t\t\t\tdp[(i, j)] = 1\n\n\t\treturn dp[(0, 0)]", + "title": "174. Dungeon Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a fixed-length integer array arr , duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,2,3,0,4,5,0]\nOutput:[1,0,0,2,3,0,0,4]\nExplanation:After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3]\nOutput:[1,2,3]\nExplanation:After calling your function, the input array is modified to: [1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n // Time Complexity = O(n)\n // Space Complexity = O(1)\n \n public void duplicateZeros(int[] arr) {\n \n // Loop through the array\n for(int i = 0; i < arr.length; i++) {\n \n // Trigger Condition \n if(arr[i] ==0) {\n int j; // auxilliary variable for swapping \n for(j = arr.length-2; j>=i+1; j--) {\n arr[j+1] = arr[j]; // Shift each element by one space\n }\n arr[j+1] = 0; // Duplicating the zero on the consecutive index of i\n i++; // Skipping the duplicated zero index in the array \n }\n }\n } \n}\n", + "title": "1089. Duplicate Zeros", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a fixed-length integer array arr , duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,2,3,0,4,5,0]\nOutput:[1,0,0,2,3,0,0,4]\nExplanation:After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3]\nOutput:[1,2,3]\nExplanation:After calling your function, the input array is modified to: [1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 107 ms (Top 60.66%) | Memory: 14.9 MB (Top 70.68%)\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n \"\"\"\n Do not return anything, modify arr in-place instead.\n \"\"\"\n l = len(arr)\n i,c=0,0\n while i a[1] - b[1]);\n // Max grow + plant time\n int maxTime = 0;\n for (int[] plant : plants) {\n maxTime = Math.max(maxTime, totalPlantTime + plant[1]);\n // After putting this plant at the end of the chain,\n // we can take the current plant time out of the total plant time\n totalPlantTime -= plant[0];\n }\n return maxTime;\n }\n}", + "title": "2136. Earliest Possible Day of Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime , of length n each: From the beginning of day 0 , you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming .", + "description_images": [], + "constraints": [ + "plantTime[i] is the number of full days it takes you to plant the i th seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total.", + "growTime[i] is the number of full days it takes the i th seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever." + ], + "examples": [ + { + "text": "Example 1: Input:plantTime = [1,4,3], growTime = [2,3,1]\nOutput:9\nExplanation:The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 0, plant the 0thseed. The seed grows for 2 full days and blooms on day 3.\nOn days 1, 2, 3, and 4, plant the 1stseed. The seed grows for 3 full days and blooms on day 8.\nOn days 5, 6, and 7, plant the 2ndseed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/1.png" + }, + { + "text": "Example 2: Input:plantTime = [1,2,3,2], growTime = [2,1,2,1]\nOutput:9\nExplanation:The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 1, plant the 0thseed. The seed grows for 2 full days and blooms on day 4.\nOn days 0 and 3, plant the 1stseed. The seed grows for 1 full day and blooms on day 5.\nOn days 2, 4, and 5, plant the 2ndseed. The seed grows for 2 full days and blooms on day 8.\nOn days 6 and 7, plant the 3rdseed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/2.png" + }, + { + "text": "Example 3: Input:plantTime = [1], growTime = [1]\nOutput:2\nExplanation:On day 0, plant the 0thseed. The seed grows for 1 full day and blooms on day 2.\nThus, on day 2, all the seeds are blooming.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n data = list(zip(plantTime, growTime))\n data.sort(key=lambda x: -x[1]) #sort by grow time in descending order\n \n res = 0\n start_time = 0\n for plant, grow in data:\n start_time += plant\n res = max(res, start_time + grow)\n return res\n", + "title": "2136. Earliest Possible Day of Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "Insert a character", + "Delete a character", + "Replace a character" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"horse\", word2 = \"ros\"\nOutput:3\nExplanation:horse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"\nOutput:5\nExplanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int minDistance(String word1, String word2) {\n int m = word1.length();\n int n = word2.length();\n int dp[][] = new int[m][n];\n for(int i=0 ; i rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"\nOutput:5\nExplanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cache\n\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n \n @cache\n def dp(i, j):\n if i == 0:\n return j\n if j == 0:\n return i\n \n l1, l2 = word1[i - 1], word2[j - 1]\n if l1 != l2:\n return 1 + min(\n dp(i, j - 1), # Delete / insert j\n dp(i - 1, j), # Delete / insert i\n dp(i - 1, j - 1) # Replace i or j\n )\n return dp(i - 1, j - 1) \n \n return dp(m, n)\n", + "title": "72. Edit Distance", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:14\nExplanation:One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 32.31%) | Memory: 42.5 MB (Top 12.73%)\nclass Solution {\n public int twoEggDrop(int n) {\n int egg = 2; // hard coded to 2 eggs for this problem\n int[][] dp = new int[n+1][egg+1];\n return eggDrop(n, egg, dp);\n }\n\n int eggDrop(int n, int egg, int[][] dp) {\n if(n <= 2 || egg == 1) return n;\n if(dp[n][egg] != 0) return dp[n][egg];\n int min = n; // when you drop at each floor starting from 1\n for(int i = 1; i < n; i++) {\n int eggBreak = 1 + eggDrop(i-1, egg-1, dp); // drops needed if egg breaks at this floor\n int noEggBreak = 1 + eggDrop(n-i, egg, dp); // drops needed if egg does not break at this floor\n int moves = Math.max(eggBreak, noEggBreak); // since we want certain moves for n floor take max\n min = Math.min(min, moves);\n }\n dp[n][egg] = min;\n return min;\n }\n}", + "title": "1884. Egg Drop With 2 Eggs and N Floors", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:14\nExplanation:One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 37 ms (Top 76.06%) | Memory: 17.40 MB (Top 35.12%)\n\nclass Solution:\n def twoEggDrop(self, n: int) -> int:\n return ceil(((1+n*8)**0.5-1)/2)\n", + "title": "1884. Egg Drop With 2 Eggs and N Floors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findSpecialInteger(int[] arr) {\n HashMaphm=new HashMap<>();\n int comp=arr.length/4;\n for (int i:arr)\n {\n if (!hm.containsKey(i)){hm.put(i,1);}\n else\n {\n int val=hm.get(i);\n val++;\n hm.put(i,val);\n }\n if (hm.get(i)>comp){return i;}\n }\n return 0;\n }\n}", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findSpecialInteger(int[] arr) {\n if (arr.length == 1) {\n return arr[0];\n }\n int count = (int) Math.ceil(arr.length / 4);\n System.out.println(count);\n\n Map map = new HashMap<>();\n\n for (Integer i : arr) {\n map.put(i, map.getOrDefault(i, 0) + 1);\n if (map.get(i) > count) {\n return i;\n }\n }\n return -1;\n }\n}\n", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l=len(arr)\n c=(l//4)+1\n d={}\n for i in arr:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n if d[i]>=c:\n return i\n", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n , where dist[i] is the initial distance in kilometers of the i th monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n , where speed[i] is the speed of the i th monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss , and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.", + "description_images": [], + "constraints": [ + "n == dist.length == speed.length", + "1 <= n <= 10^5", + "1 <= dist[i], speed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,4], speed = [1,1,1]\nOutput:3\nExplanation:In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,1,2,3], speed = [1,1,1,1]\nOutput:1\nExplanation:In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + }, + { + "text": "Example 3: Input:dist = [3,2,4], speed = [5,3,2]\nOutput:1\nExplanation:In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 72.0%) | Memory: 54.86 MB (Top 75.9%)\n\nclass Solution {\n public int eliminateMaximum(int[] dist, int[] speed) {\n \n int n = dist.length;\n \n int[] time = new int[n];\n \n for(int i = 0; i < n; i++){\n time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]);\n }\n \n Arrays.sort(time);\n \n int eliminated = 0;\n\t\t\n\t\t// At i = 0, minute = 0 ( therefore, we can use i in place of minute )\n \n for(int i = 0; i < n; i++){\n\t\t\t \n if(time[i] > i){ // At ith minute, eliminate the first monster arriving after ith minute\n eliminated++;\n }else{\n break; // Monster reached the city\n }\n }\n \n return eliminated;\n }\n}", + "title": "1921. Eliminate Maximum Number of Monsters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n , where dist[i] is the initial distance in kilometers of the i th monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n , where speed[i] is the speed of the i th monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss , and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.", + "description_images": [], + "constraints": [ + "n == dist.length == speed.length", + "1 <= n <= 10^5", + "1 <= dist[i], speed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,4], speed = [1,1,1]\nOutput:3\nExplanation:In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,1,2,3], speed = [1,1,1,1]\nOutput:1\nExplanation:In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + }, + { + "text": "Example 3: Input:dist = [3,2,4], speed = [5,3,2]\nOutput:1\nExplanation:In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])):\n if i > t:\n return i\n return len(dist) \n", + "title": "1921. Eliminate Maximum Number of Monsters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr : Given the integer n , return the last number that remains in arr .", + "description_images": [], + "constraints": [ + "Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.", + "Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.", + "Keep repeating the steps again, alternating left to right and right to left, until a single number remains." + ], + "examples": [ + { + "text": "Example 1: Input:n = 9\nOutput:6\nExplanation:arr = [1, 2,3, 4,5, 6,7, 8,9]\narr = [2,4, 6,8]\narr = [2, 6]\narr = [6]", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lastRemaining(int n) {\n int head = 1;\n int remain = n;\n boolean left = true;\n int step =1;\n \n while(remain > 1){\n if(left || remain%2==1){\n head = head + step;\n }\n remain /= 2;\n step *= 2;\n left = !left;\n }\n return head;\n }\n}\n", + "title": "390. Elimination Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr : Given the integer n , return the last number that remains in arr .", + "description_images": [], + "constraints": [ + "Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.", + "Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.", + "Keep repeating the steps again, alternating left to right and right to left, until a single number remains." + ], + "examples": [ + { + "text": "Example 1: Input:n = 9\nOutput:6\nExplanation:arr = [1, 2,3, 4,5, 6,7, 8,9]\narr = [2,4, 6,8]\narr = [2, 6]\narr = [6]", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lastRemaining(self, n: int) -> int:\n beg = 1\n len = n\n d = 1\n fromleft = True\n\n while len > 1:\n if(fromleft or len%2 == 1):\n beg += d\n d <<= 1\n len >>= 1\n fromleft = not fromleft\n \n return beg\n", + "title": "390. Elimination Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees employees where: Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates .", + "description_images": [], + "constraints": [ + "employees[i].id is the ID of the i th employee.", + "employees[i].importance is the importance value of the i th employee.", + "employees[i].subordinates is a list of the IDs of the direct subordinates of the i th employee." + ], + "examples": [ + { + "text": "Example 1: Input:employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput:11\nExplanation:Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg" + }, + { + "text": "Example 2: Input:employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput:-3\nExplanation:Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private Map idToIndex;\n\n private void populateIdToIndexMap(List employees) { \n for(int idx = 0; idx employees, int id) {\n int currEmpIdx = idToIndex.get(id);\n Employee currEmp = employees.get(currEmpIdx);\n int totalImportance = currEmp.importance;\n for(int child : currEmp.subordinates) {\n totalImportance += dfsGetImportance(employees, child);\n }\n \n return totalImportance;\n }\n \n public int getImportance(List employees, int id) {\n if(employees == null || employees.size() < 1) {\n return 0; \n }\n \n idToIndex = new HashMap<>();\n populateIdToIndexMap(employees);\n return dfsGetImportance(employees, id);\n }\n}\n", + "title": "690. Employee Importance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees employees where: Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates .", + "description_images": [], + "constraints": [ + "employees[i].id is the ID of the i th employee.", + "employees[i].importance is the importance value of the i th employee.", + "employees[i].subordinates is a list of the IDs of the direct subordinates of the i th employee." + ], + "examples": [ + { + "text": "Example 1: Input:employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput:11\nExplanation:Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg" + }, + { + "text": "Example 2: Input:employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput:-3\nExplanation:Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 254 ms (Top 40.58%) | Memory: 15.6 MB (Top 60.31%)\n\"\"\"\n# Definition for Employee.\nclass Employee:\n def __init__(self, id: int, importance: int, subordinates: List[int]):\n self.id = id\n self.importance = importance\n self.subordinates = subordinates\n\"\"\"\n\nclass Solution:\n def dfs(self, graph, employees, empId, totalImportance, visited):\n totalImportance += graph[empId][0]\n visited.add(empId)\n\n for neighbour in graph[empId][1]:\n if neighbour not in visited:\n totalImportance = self.dfs(graph, employees, neighbour, totalImportance, visited)\n\n return totalImportance\n\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n graph = {}\n\n for employeeInfo in employees:\n empId, importance, suboordinates = employeeInfo.id, employeeInfo.importance, employeeInfo.subordinates\n graph[empId] = [importance, suboordinates]\n\n n = len(employees)\n\n if graph[id][1] == []:\n return graph[id][0]\n\n visited = set()\n totalImportance = 0\n totalImportance = self.dfs(graph, employees, id, totalImportance, visited)\n\n return totalImportance", + "title": "690. Employee Importance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk . Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution() Initializes the object of the system.", + "String encode(String longUrl) Returns a tiny URL for the given longUrl .", + "String decode(String shortUrl) Returns the original long URL for the given shortUrl . It is guaranteed that the given shortUrl was encoded by the same object." + ], + "examples": [ + { + "text": "Example 1: Input:url = \"https://leetcode.com/problems/design-tinyurl\"\nOutput:\"https://leetcode.com/problems/design-tinyurl\"\nExplanation:Solution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Codec {\n\n // Encodes a URL to a shortened URL.\n public String encode(String longUrl) {\n return longUrl;\n }\n\n // Decodes a shortened URL to its original URL.\n public String decode(String shortUrl) {\n return shortUrl;\n }\n}\n", + "title": "535. Encode and Decode TinyURL", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk . Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution() Initializes the object of the system.", + "String encode(String longUrl) Returns a tiny URL for the given longUrl .", + "String decode(String shortUrl) Returns the original long URL for the given shortUrl . It is guaranteed that the given shortUrl was encoded by the same object." + ], + "examples": [ + { + "text": "Example 1: Input:url = \"https://leetcode.com/problems/design-tinyurl\"\nOutput:\"https://leetcode.com/problems/design-tinyurl\"\nExplanation:Solution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Codec:\n\n def encode(self, longUrl):\n return longUrl\n\n def decode(self, shortUrl):\n return shortUrl\n", + "title": "535. Encode and Decode TinyURL", + "topic": "Database" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string. A string is encrypted with the following process: Note that in case a character of the string is not present in keys , the encryption process cannot be carried out, and an empty string \"\" is returned. A string is decrypted with the following process: Implement the Encrypter class:", + "description_images": [], + "constraints": [ + "Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values , and dictionary .", + "String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.", + "int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Encrypter\", \"encrypt\", \"decrypt\"]\n[[['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]], [\"abcd\"], [\"eizfeiam\"]]Output[null, \"eizfeiam\", 2]ExplanationEncrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]);\nencrypter.encrypt(\"abcd\"); // return \"eizfeiam\". \n  // 'a' maps to \"ei\", 'b' maps to \"zf\", 'c' maps to \"ei\", and 'd' maps to \"am\".\nencrypter.decrypt(\"eizfeiam\"); // return 2. \n // \"ei\" can map to 'a' or 'c', \"zf\" maps to 'b', and \"am\" maps to 'd'. \n // Thus, the possible strings after decryption are \"abad\", \"cbad\", \"abcd\", and \"cbcd\". \n // 2 of those strings, \"abad\" and \"abcd\", appear in dictionary, so the answer is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Encrypter {\n \n Map encryptedDictCount;\n int[] keys;\n Set dictionary;\n String[] val;\n \n public Encrypter(char[] keys, String[] values, String[] dictionary) {\n this.keys = new int[26];\n encryptedDictCount = new HashMap<>();\n this.val = values.clone();\n this.dictionary = new HashSet<>(Arrays.asList(dictionary));\n \n for(int i=0; i str:\n output = ''\n for char in word1:\n output += self.hashmap[char]\n return output\n\n def decrypt(self, word2: str) -> int:\n return self.dictmap[word2]\n", + "title": "2227. Encrypt and Decrypt Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:", + "description_images": [], + "constraints": [ + " For example, 12 , 0 , and 123 .", + "For example, 12 , 0 , and 123 .", + " <.> For example, 0.5 , 1. , 2.12 , and 123.0001 .", + "For example, 0.5 , 1. , 2.12 , and 123.0001 .", + " <.> <(> <)> For example, 0.1(6) , 1.(9) , 123.00(1212) .", + "For example, 0.1(6) , 1.(9) , 123.00(1212) ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0.(52)\", t = \"0.5(25)\"\nOutput:true\nExplanation:Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0.1666(6)\", t = \"0.166(66)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"0.9(9)\", t = \"1.\"\nOutput:true\nExplanation:\"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.00 MB (Top 31.82%)\n\nclass Solution {\n\n private List ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999);\n\n public boolean isRationalEqual(String S, String T) {\n return Math.abs(computeValue(S) - computeValue(T)) < 1e-9;\n }\n\n private double computeValue(String s) {\n if (!s.contains(\"(\")) {\n return Double.valueOf(s);\n } else {\n double intNonRepeatingValue = Double.valueOf(s.substring(0, s.indexOf('(')));\n int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1;\n int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1;\n int repeatingValue = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')')));\n return intNonRepeatingValue + repeatingValue * Math.pow(0.1, nonRepeatingLength) * ratios.get(repeatingLength);\n }\n }\n}\n", + "title": "972. Equal Rational Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:", + "description_images": [], + "constraints": [ + " For example, 12 , 0 , and 123 .", + "For example, 12 , 0 , and 123 .", + " <.> For example, 0.5 , 1. , 2.12 , and 123.0001 .", + "For example, 0.5 , 1. , 2.12 , and 123.0001 .", + " <.> <(> <)> For example, 0.1(6) , 1.(9) , 123.00(1212) .", + "For example, 0.1(6) , 1.(9) , 123.00(1212) ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0.(52)\", t = \"0.5(25)\"\nOutput:true\nExplanation:Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0.1666(6)\", t = \"0.166(66)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"0.9(9)\", t = \"1.\"\nOutput:true\nExplanation:\"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 69 ms (Top 5.88%) | Memory: 14 MB (Top 23.53%)\nclass Solution:\n # inspired from:\n # https://coolconversion.com/math/recurring-decimals-as-a-fraction/\n # to which we wouldn't have access during interview.\n\n import typing\n def isRationalEqual(self, s: str, t: str) -> bool:\n\n # intuition:\n # write each numbes as fraction: num / den\n # then compare the two fractions.\n\n num1, den1 = self.toFraction(s)\n num2, den2 = self.toFraction(t)\n\n return den1 * num2 == den2 * num1\n\n def toFraction(self, s: str) -> typing.Tuple[int, int]:\n if \".\" not in s:\n return int(s), 1\n\n intp, frac = s.split(\".\")\n # decimal dot, but no repeating part:\n # xyz.abc = xyzabc / 1000\n if \"(\" not in frac:\n ifrac = int(frac) if len(frac) > 0 else 0\n num = int(intp) * (10 ** len(frac)) + ifrac\n den = 10 ** len(frac)\n return num, den\n\n # this is for cases like a.b(c)\n # let n = a.b(c)\n # then, 10^(len(b+c)) * n = abc.(c)\n # and 10^(len(b)) * n = ab.(c)\n # subtract the two, and solve for n:\n # n = (abc - ab) / (10^len(b + c) - 10^len(b))\n frac, repfrac = frac.split(\"(\")\n repfrac = repfrac[:-1]\n\n iintp = int(intp)\n ifrac = int(frac) if len(frac) > 0 else 0\n irep = int(repfrac)\n\n return (\n (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac),\n (10** len(frac+repfrac) - 10 **len(frac))\n )\n ```", + "title": "972. Equal Rational Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (R i , C j ) such that row R i and column C j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array).", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput:1\nExplanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput:3\nExplanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int equalPairs(int[][] grid) {\n HashMap map = new HashMap<>();\n int row = grid.length;\n int col = grid.length;\n for(int i = 0; i < row; i++){\n String res = \"\";\n for(int j = 0; j < col; j++){\n res += \"-\" + grid[i][j];\n }\n map.put(res, map.getOrDefault(res, 0) + 1);\n }\n int cnt = 0;\n for(int j = 0; j < col; j++){\n String res = \"\";\n for(int i = 0; i < row; i++){\n res += \"-\" + grid[i][j];\n }\n cnt += map.getOrDefault(res, 0);\n }\n return cnt;\n }\n}\n", + "title": "2352. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (R i , C j ) such that row R i and column C j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array).", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput:1\nExplanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput:3\nExplanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 467 ms (Top 64.2%) | Memory: 21.54 MB (Top 44.5%)\n\nclass Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n m = defaultdict(int)\n cnt = 0\n\n for row in grid:\n m[str(row)] += 1\n \n for i in range(len(grid[0])):\n col = []\n for j in range(len(grid)):\n col.append(grid[j][i])\n cnt += m[str(col)]\n return cnt\n", + "title": "2352. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two arrays of integers nums1 and nums2 , possibly of different lengths. The values in the arrays are between 1 and 6 , inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6 , inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2 . Return -1 ​​​​​ if it is not possible to make the sum of the two arrays equal.", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput:3\nExplanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput:-1\nExplanation:There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [6,6], nums2 = [1]\nOutput:3\nExplanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 89.13%) | Memory: 97.8 MB (Top 84.45%)\nclass Solution {\n public int minOperations(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length;\n if (m > 6 * n || n > 6 * m) return -1;\n\n int sum1 = 0, sum2 = 0;\n for (int i : nums1) sum1 += i;\n for (int i : nums2) sum2 += i;\n\n int diff = sum1 - sum2;\n if (diff == 0) return 0;\n\n return (diff > 0 ? helper(nums1, nums2, diff)\n : helper(nums2, nums1, -diff));\n }\n\n private int helper(int[] nums1, int[] nums2, int diff) {\n // count[i] : frequency of numbers that can reduce the diff by i\n int[] count = new int[6];\n for (int num : nums1) count[num - 1]++;\n for (int num : nums2) count[6 - num]++;\n\n int res = 0;\n for (int i = 5; i > 0; i--) {\n int c = Math.min(count[i], diff / i + (diff % i == 0 ? 0 : 1));\n\n res += c;\n diff -= c * i;\n\n if (diff <= 0) break;\n }\n return res;\n }\n}", + "title": "1775. Equal Sum Arrays With Minimum Number of Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two arrays of integers nums1 and nums2 , possibly of different lengths. The values in the arrays are between 1 and 6 , inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6 , inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2 . Return -1 ​​​​​ if it is not possible to make the sum of the two arrays equal.", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput:3\nExplanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput:-1\nExplanation:There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [6,6], nums2 = [1]\nOutput:3\nExplanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max \"gain\" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the \"gain\" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1\n", + "title": "1775. Equal Sum Arrays With Minimum Number of Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array trees where trees[i] = [x i , y i ] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed . Return the coordinates of trees that are exactly located on the fence perimeter .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 3000", + "points[i].length == 2", + "0 <= x i , y i <= 100", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\nOutput:[[1,1],[2,0],[3,3],[2,4],[4,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg" + }, + { + "text": "Example 2: Input:points = [[1,2],[2,2],[4,2]]\nOutput:[[4,2],[2,2],[1,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public static class Pair {\n int x;\n int y;\n \n Pair(int x, int y) {\n this.x = x;\n this.y = y;\n }\n \n }\n public int[][] outerTrees(int[][] trees) {\n List points=new ArrayList<>();\n for(int[] point:trees){\n points.add(new Pair(point[0],point[1])); \n }\n\n List res=new ArrayList<>();\n if(points.size()==1){\n return trees;\n }\n int n=points.size();\n Collections.sort(points,(a,b)->a.y==b.y?a.x-b.x:a.y-b.y);\n HashSet> dup=new HashSet<>();\n Stack hull=new Stack<>();\n \n hull.push(points.get(0));\n hull.push(points.get(1));\n \n for(int i=2;i=0;i--){\n Pair top=hull.pop();\n while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){\n top=hull.pop();\n }\n hull.push(top);\n hull.push(points.get(i));\n }\n\n for(Pair p:hull){\n ArrayList tmp=new ArrayList<>();\n tmp.add(p.x);\n tmp.add(p.y);\n if(dup.contains(tmp))continue;\n dup.add(tmp);\n res.add(p);\n }\n\n int[][] ans=new int[res.size()][2];\n int i=0;\n for(Pair p:res){\n ans[i][0]=p.x;\n ans[i][1]=p.y;\n i++;\n }\n \n return ans;\n \n }\n\n public int ccw(Pair a,Pair b,Pair c){\n double cp=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\n if(cp<0)return -1;\n else if(cp>0)return 1;\n else return 0;\n }\n}\n", + "title": "587. Erect the Fence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array trees where trees[i] = [x i , y i ] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed . Return the coordinates of trees that are exactly located on the fence perimeter .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 3000", + "points[i].length == 2", + "0 <= x i , y i <= 100", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\nOutput:[[1,1],[2,0],[3,3],[2,4],[4,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg" + }, + { + "text": "Example 2: Input:points = [[1,2],[2,2],[4,2]]\nOutput:[[4,2],[2,2],[1,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\n \"\"\"Compute the convex hull of a set of points.\n\n Use Andrew's Monotone Chain algorithm, which has order O(N log(N)),\n where N is the number of input points.\n \"\"\"\n\n def cross(self, p, a, b):\n \"\"\"Return the cross product of the vectors p -> a and p -> b.\"\"\"\n return (a[0] - p[0]) * (b[1] - p[1]) \\\n - (a[1] - p[1]) * (b[0] - p[0])\n\n def _convex_hull_monotone_chain(self, points):\n \"\"\"Compute the convex hull of a list of points.\n \n Use Andrew's Monotone Chain algorithm, which is similar to Graham Scan,\n except that it doesn't require sorting the points by angle. This algorithm\n takes O(N log(N)) time, where N is len(points).\n \"\"\"\n # Ensure all points are unique, and sort lexicographically.\n points = list(sorted(set(points)))\n \n # If there are fewer than three points, they must form a hull.\n if len(points) <= 2:\n return points\n \n # Compute the lower and upper portion of the hull.\n lower, upper = [], []\n for out, it in ((lower, points), (upper, reversed(points))):\n for p in it:\n while len(out) >= 2 and self.cross(out[-2], out[-1], p) > 0:\n out.pop()\n out.append(p)\n\n # Concatenate the upper and lower hulls. Remove the last point from each\n # because those points are duplicated in both upper and lower.\n return lower[:-1] + upper[:-1]\n\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Find the convex hull of a collection of points.\n Return a list of indices of points forming the hull in clockwise order,\n starting with the leftmost point.\n \"\"\"\n # Convert input points to tuples.\n points = [tuple(p) for p in trees]\n ans = set()\n for point in self._convex_hull_monotone_chain(points):\n ans.add(point)\n return ans", + "title": "587. Erect the Fence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y) . We start at the source = [s x , s y ] square and want to reach the target = [t x , t y ] square. There is also an array of blocked squares, where each blocked[i] = [x i , y i ] represents a blocked square with coordinates (x i , y i ) . Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves .", + "description_images": [], + "constraints": [ + "0 <= blocked.length <= 200", + "blocked[i].length == 2", + "0 <= x i , y i < 10^6", + "source.length == target.length == 2", + "0 <= s x , s y , t x , t y < 10^6", + "source != target", + "It is guaranteed that source and target are not blocked." + ], + "examples": [ + { + "text": "Example 1: Input:blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\nOutput:false\nExplanation:The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.", + "image": null + }, + { + "text": "Example 2: Input:blocked = [], source = [0,0], target = [999999,999999]\nOutput:true\nExplanation:Because there are no blocked cells, it is possible to reach the target square.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 724 ms (Top 51.43%) | Memory: 118.9 MB (Top 56.19%)\nclass Solution\n{\n static final int limit= 1000000;//boundary check\n\n public boolean isEscapePossible(int[][] blocked, int[] source, int[] target)\n {\n Set blocks= new HashSet<>();//HashSet to reduce the access time from O(N)-> O(1)\n\n for(int block[] : blocked)\n blocks.add(block[0]+ \"-\"+ block[1]);//putting the blocked node into the HashSet to access it at O(1)\n\n return bfsRange(source, target, blocks) && bfsRange(target, source, blocks);//sector division\n\n /*checking for both the case that the source is blocked or the target is blocked\n *if one of them is blocked we return false\n *since it is not practical to traverse each node, it will provide us with TLE\n */\n }\n\n /* Formula ::\n * shortest arc(displacement) of 1/4 sector of circel is a* 2^1/2\n * Area of the triangular sector is 1/2 * ( r{base} * r{height} )\n * Number of minimum shell to cover to move ahed of sector or boundary if possible = 0 + 1 + 2 + 3 + ... + 199 = 19900 (A.P)\n */\n\n public boolean bfsRange(int[] source, int[] target, Set blocks)\n {//we simply do bsf to check the circular quadrant 1/4th boundary of the sector\n\n Set visited= new HashSet<>();//visited hash set is so that we dont visit the visited cell again and the access time is O(1)\n Queue q= new LinkedList<>();//as we use in BT\n\n q.offer(source);//adding the starting BFS node to the Queue\n\n visited.add(source[0] + \"-\" + source[1]);//marking it as visited so that we dont traverse it again\n\n int count= 0;//number of node traverse total outside + inside\n while(!q.isEmpty())\n {//r m* w a*\n int temp[]= q.poll();//poling the node\n count+= 1;//counting the number of node traverse\n\n int trav[][]= {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};//Traversing in 4-Direction\n\n for(int direction[] : trav)\n {\n int i= temp[0] + direction[0];\n int j= temp[1] + direction[1];\n\n String key= (i+ \"-\"+ j);\n\n if(i < 0 || j < 0 || i >= limit || j >= limit || visited.contains(key) || blocks.contains(key))\n continue;//base case 1)checking the index 2)We dont visit the blocked node 3) we dont visit the visited node\n\n if(i == target[0] && j == target[1]) //when we find the target within the boundary(same sector or the quadrand) we just return true //best case saves a lot of time\n return true;\n\n visited.add(key);//marking the node as visited and adding it to the Queue\n\n q.offer(new int[]{i, j});//Expaning the search for path and adding the node\n\n if(count > 19900) //number of cell, crossing the boundary limit\n return true;//path exists from this node\n }\n }\n return false;//no path, to reach the node//boundary blocked us\n }\n}//Please do Upvote, it helps a lot", + "title": "1036. Escape a Large Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y) . We start at the source = [s x , s y ] square and want to reach the target = [t x , t y ] square. There is also an array of blocked squares, where each blocked[i] = [x i , y i ] represents a blocked square with coordinates (x i , y i ) . Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves .", + "description_images": [], + "constraints": [ + "0 <= blocked.length <= 200", + "blocked[i].length == 2", + "0 <= x i , y i < 10^6", + "source.length == target.length == 2", + "0 <= s x , s y , t x , t y < 10^6", + "source != target", + "It is guaranteed that source and target are not blocked." + ], + "examples": [ + { + "text": "Example 1: Input:blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\nOutput:false\nExplanation:The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.", + "image": null + }, + { + "text": "Example 2: Input:blocked = [], source = [0,0], target = [999999,999999]\nOutput:true\nExplanation:Because there are no blocked cells, it is possible to reach the target square.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object): \n def isEscapePossible(self, blocked, source, target):\n \"\"\"\n :type blocked: List[List[int]]\n :type source: List[int]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n \n self.blocked = blocked\n self.source = source\n self.target = target\n \n #hashset of all blocked cells\n self.blocked_dict = {}\n \n #hashset of all visited edges\n self.edge_dict = {}\n \n #min/max x/y coords used for checking if an edge intersects the \"easy path\"\n self.min_x = min(self.source[0],self.target[0])\n self.max_x = max(self.source[0],self.target[0])\n self.min_y = min(self.source[1],self.target[1])\n self.max_y = max(self.source[1],self.target[1])\n \n #iterate through all cells in blocked,\n #and add each cell to the hash set\n for blocked_cell in blocked:\n if blocked_cell[0] in self.blocked_dict:\n self.blocked_dict[blocked_cell[0]][blocked_cell[1]] = None\n else:\n self.blocked_dict[blocked_cell[0]]={blocked_cell[1]:None}\n \n #for each cell in blocked\n for blocked_cell in self.blocked:\n \n #list the faces of blocked_cell that belong to an outline (4 of these at most)\n exposed_faces = self.enumerate_exposed_faces(blocked_cell[0],blocked_cell[1])\n \n #for each of these faces\n for face in exposed_faces:\n \n #check to see if we've already visited the edge while tracing out a loop\n x_edge = face[3]\n y_edge = face[4]\n edge_type = face[5]\n edge_visited = (x_edge in self.edge_dict \n and y_edge in self.edge_dict[x_edge]\n and edge_type in self.edge_dict[x_edge][y_edge])\n \n #if not, then we are looking at a new outline that we haven't seen before\n if not edge_visited: \n \n #count the number of edges of the outline that intersect the \"easy path\"\n num_intervening_edges = self.check_loop(face[0],face[1],face[2])\n \n #if the number of intersections is odd, a path does not exist. return false\n if num_intervening_edges%2==1:\n return False\n \n #if we could not find an outline the separates source from target, return true \n return True\n \n #lists the faces of occupied cell x,y that do not touch other occupied cells\n #these cell faces are edges that belong to one of the outlines that are formed \n #by painting in all occupied cells and grid boundaries\n #there are at most 4 such edges per cell\n def enumerate_exposed_faces(self,x,y):\n out_list = []\n \n #iterate through each neighbor of the cell\n for i in range(4):\n \n #if the neighbor cell is not occupied (blocked), then the corresponding face is a boundary face\n #in which case, add it to the list\n if not self.is_occupied(x+self.dxe[i],y+self.dye[i]):\n \n #there is a little bit of accounting going on to keep track of the correct edge coordinates\n #note that what we are really listing here is a starting grid point (not cell) + starting direction\n #and we also need to take into account that cells are indexed by their bottom left corner\n x_star = x+self.dxe2[i]\n y_star = y+self.dye2[i]\n x_edge_coords = x_star + self.dx_edge_coords[(i+2)%4]\n y_edge_coords = y_star + self.dy_edge_coords[(i+2)%4]\n \n out_list.append([x_star,y_star,i,x_edge_coords,y_edge_coords,self.edge_code_list[i]])\n return out_list\n \n #returns the number of times a given outline intersects the \"easy path\"\n #x_start,y_start is the starting gridpoint on the outline\n #starting_direction is... the starting direction (see __init__ for how it's coded)\n #is_cc is True if traversing in counterclockwise direction, False if clockwise\n #note that (counter)clockwise is referring to the winding number of the whole outline we are tracing\n def check_loop(self,x_start,y_start,starting_direction,is_cc = True):\n #correct the starting direction if it needs to be adjusted\n starting_direction = self.update_edge_direction(x_start,y_start,starting_direction,is_cc)\n direction = starting_direction\n \n x = x_start\n y = y_start\n \n num_intervening_edges = 0\n \n # return False\n touched_grid_boundary = False\n \n #iterate until we either touch the grid boundary\n #or return to where we started\n #this is a do-while, hence the True + break condition\n while True: \n #evaluate next grid point after moving along edge\n x_new = x+self.dxp[direction]\n y_new = y+self.dyp[direction]\n \n #if the edge is on the boundary, do not proceed. break out of the loop\n if self.edge_on_boundary(x,y,x_new,y_new):\n touched_grid_boundary = True\n break\n \n #otherwise, mark the edge as visited\n x_edge_coords = x + self.dx_edge_coords[direction]\n y_edge_coords = y + self.dy_edge_coords[direction]\n edge_coords = [x_edge_coords,y_edge_coords]\n \n #a little bit of a hassle since it's a dictionary of dictionaries of 1-2 element lists\n if x_edge_coords in self.edge_dict:\n if y_edge_coords in self.edge_dict[x_edge_coords]:\n if self.edge_code_list[direction] not in self.edge_dict[x_edge_coords][y_edge_coords]:\n self.edge_dict[x_edge_coords][y_edge_coords].append(self.edge_code_list[direction])\n else:\n self.edge_dict[x_edge_coords][y_edge_coords] = [self.edge_code_list[direction]] \n else:\n self.edge_dict[x_edge_coords] = {y_edge_coords: [self.edge_code_list[direction]]}\n \n \n #check to see if the edge intersects our \"easy path\" from source to target\n #if an intersection has occured, increment the intersection counter\n \n #checks to see if the edge intersects the horizontal portion of the easy path\n #for an edge to do so, it must be vertical, have the same y as source\n #and must have an x between source and target\n if self.edge_code_list[direction]=='v':\n if (self.min_x bool:\n \n dist = lambda x : abs(x[0] - target[0]) + abs(x[1] - target[1])\n\n return dist((0,0)) < min(dist(g) for g in ghosts)\n", + "title": "789. Escape The Ghosts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: You are situated in the top-left cell, (0, 0) , and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1) . Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse . If this is impossible, return -1 . If you can always reach the safehouse regardless of the minutes stayed, return 10^9 . Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).", + "description_images": [], + "constraints": [ + "0 represents grass,", + "1 represents fire,", + "2 represents a wall that you and fire cannot pass through." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput:3\nExplanation:The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex1new.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput:-1\nExplanation:The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex2new2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput:1000000000\nExplanation:The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex3new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 89.41%) | Memory: 45.50 MB (Top 60.0%)\n\nclass Solution {\n public int maximumMinutes(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n \n int[][] times = new int[m][n];\n for(int[] row : times) {\n Arrays.fill(row, Integer.MAX_VALUE);\n }\n \n int[] dir = new int[]{-1, 0, 1, 0, -1};\n \n\t\t// Queue for running BFS\n Deque fires = new ArrayDeque<>();\n\t\t\n for(int row = 0; row < m; row++) {\n for(int col = 0; col < n; col++) {\n if (grid[row][col] == 1) {\n times[row][col] = 0;\n fires.offer(new int[]{row, col});\n }\n }\n }\n \n int time = 1;\n while(!fires.isEmpty()) {\n int size = fires.size();\n \n for(int i = 0; i < size; i++) {\n int[] pos = fires.poll();\n \n for(int j = 0; j < 4; j++) {\n int x = pos[0] + dir[j];\n int y = pos[1] + dir[j + 1];\n \n if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 0 && times[x][y] == Integer.MAX_VALUE) {\n times[x][y] = time;\n fires.offer(new int[]{x, y});\n }\n }\n }\n \n time++;\n }\n \n fires.clear();\n \n int ans = Integer.MAX_VALUE;\n fires.offer(new int[]{0, 0});\n grid[0][0] = 2;\n\n time = 1;\n while(!fires.isEmpty() && grid[m - 1][n - 1] == 0) {\n int size = fires.size();\n \n int t = Integer.MIN_VALUE;\n \n for(int i = 0; i < size && grid[m - 1][n - 1] == 0; i++) {\n int[] pos = fires.poll();\n \n for(int j = 0; j < 4 && grid[m - 1][n - 1] == 0; j++) {\n \n int x = pos[0] + dir[j];\n int y = pos[1] + dir[j + 1];\n\n if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 0 && times[x][y] >= time) {\n if (x == m - 1 && y == n - 1) {\n t = times[x][y] - time;\n grid[x][y] = 2;\n break;\n }\n\n grid[x][y] = 2;\n fires.offer(new int[]{x, y});\n \n\t\t\t\t\t\t// if times[x][y] == Integer.MAX_VALUE, fire will never reach this cell and it will contribute maximum wait time\n t = Math.max(t, times[x][y] == Integer.MAX_VALUE ? 1000000000 : times[x][y] - time - 1);\n }\n }\n }\n \n ans = Math.min(ans, t);\n \n time++;\n }\n \n\t\t// You can never reach the safe house\n if (grid[m - 1][n - 1] != 2) {\n return -1;\n }\n \n\t\t// you can reach the safe house but fire can not\n if (times[m - 1][n - 1] == Integer.MAX_VALUE) {\n return 1000000000;\n }\n \n return ans == Integer.MAX_VALUE || ans == Integer.MIN_VALUE ? -1 : ans;\n }\n}\n", + "title": "2258. Escape the Spreading Fire", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: You are situated in the top-left cell, (0, 0) , and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1) . Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse . If this is impossible, return -1 . If you can always reach the safehouse regardless of the minutes stayed, return 10^9 . Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).", + "description_images": [], + "constraints": [ + "0 represents grass,", + "1 represents fire,", + "2 represents a wall that you and fire cannot pass through." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput:3\nExplanation:The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex1new.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput:-1\nExplanation:The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex2new2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput:1000000000\nExplanation:The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex3new.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maximumMinutes(self, A):\n m, n = len(A), len(A[0])\n inf = 10 ** 10\n d = [[0,1],[1,0],[0,-1],[-1,0]]\n fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1]\n A = [[inf if a < 2 else -1 for a in r] for r in A]\n\n def bfs(queue, seen):\n for i, j, t in queue:\n if seen[i][j] < inf: continue\n seen[i][j] = t\n for di,dj in d:\n x, y = i + di, j + dj\n if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]:\n queue.append([x, y, t + 1])\n \n def die(t):\n seen = [[inf + 10] * n for i in range(m)]\n bfs([[0, 0, t]], seen)\n return seen[-1][-1] > A[-1][-1]\n\n bfs(fires, A)\n A[-1][-1] += 1\n return bisect_left(range(10**9 + 1), True, key=die) - 1\n", + "title": "2258. Escape the Spreading Fire", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a full binary tree with the following properties: The evaluation of a node is as follows: Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children.", + "description_images": [], + "constraints": [ + "Leaf nodes have either the value 0 or 1 , where 0 represents False and 1 represents True .", + "Non-leaf nodes have either the value 2 or 3 , where 2 represents the boolean OR and 3 represents the boolean AND ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3,null,null,0,1]\nOutput:true\nExplanation:The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/05/16/example1drawio1.png" + }, + { + "text": "Example 2: Input:root = [0]\nOutput:false\nExplanation:The root node is a leaf node and it evaluates to false, so we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.4 MB (Top 93.53%)\nclass Solution {\n public boolean evaluateTree(TreeNode root) {\n if(root.val == 1)\n return true;\n if(root.val == 0)\n return false;\n if(root.val == 2)\n return evaluateTree(root.left) || evaluateTree(root.right);\n return evaluateTree(root.left) && evaluateTree(root.right);\n }\n}", + "title": "2331. Evaluate Boolean Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a full binary tree with the following properties: The evaluation of a node is as follows: Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children.", + "description_images": [], + "constraints": [ + "Leaf nodes have either the value 0 or 1 , where 0 represents False and 1 represents True .", + "Non-leaf nodes have either the value 2 or 3 , where 2 represents the boolean OR and 3 represents the boolean AND ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3,null,null,0,1]\nOutput:true\nExplanation:The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/05/16/example1drawio1.png" + }, + { + "text": "Example 2: Input:root = [0]\nOutput:false\nExplanation:The root node is a leaf node and it evaluates to false, so we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 98 ms (Top 35.75%) | Memory: 14.7 MB (Top 20.30%)\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n def recur(node):\n if not node.left and not node.right: #leaf node\n return True if node.val == 1 else False\n left = recur(node.left)\n right = recur(node.right)\n if node.val == 2: #if node is or\n return left or right\n if node.val == 3: #if node is and\n return left and right\n return recur(root)", + "title": "2331. Evaluate Boolean Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput:[6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double[] calcEquation(List> equations, double[] values, List> queries) {\n int len = equations.size();\n Map varMap = new HashMap<>();\n int varCnt = 0;\n for (int i = 0; i < len; i++) {\n if (!varMap.containsKey(equations.get(i).get(0))) {\n varMap.put(equations.get(i).get(0), varCnt++);\n }\n if (!varMap.containsKey(equations.get(i).get(1))) {\n varMap.put(equations.get(i).get(1), varCnt++);\n }\n }\n\n List[] edges = new List[varCnt];\n for (int i = 0; i < varCnt; i++) {\n edges[i] = new ArrayList<>();\n }\n\n for (int i = 0; i < len; i++) {\n int va = varMap.get(equations.get(i).get(0));\n int vb = varMap.get(equations.get(i).get(1));\n edges[va].add(new Pair(vb, values[i]));\n edges[vb].add(new Pair(va, 1.0 / values[i]));\n }\n\n int queriesCnt = queries.size();\n double[] ans = new double[queriesCnt];\n for (int i = 0; i < queriesCnt; i++) {\n List query = queries.get(i);\n double result = -1.0;\n if (varMap.containsKey(query.get(0)) && varMap.containsKey(query.get(1))) {\n int idxA = varMap.get(query.get(0));\n int idxB = varMap.get(query.get(1));\n if (idxA == idxB) {\n result = 1.0;\n } else {\n Queue points = new LinkedList<>();\n points.offer(idxA);\n double[] ratios = new double[varCnt];\n Arrays.fill(ratios, -1.0);\n ratios[idxA] = 1.0;\n while (!points.isEmpty() && ratios[idxB] < 0) {\n int cur = points.poll();\n for (Pair pair : edges[cur]) {\n int y = pair.index;\n double value = pair.value;\n if (ratios[y] < 0) {\n ratios[y] = ratios[cur] * value;\n points.offer(y);\n }\n }\n }\n\n result = ratios[idxB];\n }\n }\n\n ans[i] = result;\n }\n\n return ans;\n }\n\n class Pair {\n int index;\n double value;\n\n public Pair(int index, double value) {\n this.index = index;\n this.value = value;\n }\n }\n}\n", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput:[6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n graph = dict()\n \n for (n, d), v in zip(equations, values):\n if n not in graph:\n graph[n] = []\n if d not in graph:\n graph[d] = []\n \n graph[n].append((d, v))\n graph[d].append((n, 1/v))\n \n def dfs(node, target, product, visited):\n if n not in graph or d not in graph:\n return -1\n \n if node == target:\n return product\n \n visited.add(node)\n \n for neighbor, quotient in graph[node]:\n if neighbor not in visited:\n soln = dfs(neighbor, target, product * quotient, visited)\n if soln != -1:\n return soln\n \n return -1\n \n solns = []\n for n, d in queries:\n solns.append(dfs(n, d, 1, set()))\n \n return solns", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation . Valid operators are + , - , * , and / . Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.", + "description_images": [], + "constraints": [ + "1 <= tokens.length <= 10^4", + "tokens[i] is either an operator: \"+\" , \"-\" , \"*\" , or \"/\" , or an integer in the range [-200, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\nOutput:9\nExplanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\nOutput:6\nExplanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\nOutput:22\nExplanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int evalRPN(String[] tokens) {\n Stack stack = new Stack();\n for(String i: tokens){\n if(i.equals(\"+\") || i.equals(\"-\") || i.equals(\"*\") || i.equals(\"/\")){\n int a = stack.pop();\n int b = stack.pop();\n int temp = 0;\n if(i.equals(\"+\"))\n temp = a+b;\n else if(i.equals(\"-\"))\n temp = b-a;\n else if(i.equals(\"*\"))\n temp = a*b;\n else if(i.equals(\"/\"))\n temp = b/a;\n stack.push(temp);\n }\n else\n stack.push(Integer.parseInt(i));\n }\n return stack.pop();\n }\n}\n", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation . Valid operators are + , - , * , and / . Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.", + "description_images": [], + "constraints": [ + "1 <= tokens.length <= 10^4", + "tokens[i] is either an operator: \"+\" , \"-\" , \"*\" , or \"/\" , or an integer in the range [-200, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\nOutput:9\nExplanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\nOutput:6\nExplanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\nOutput:22\nExplanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n stack = [] \n for i in tokens:\n if i == \"+\":\n stack[-1] = stack[-2] + stack.pop()\n elif i == \"-\":\n stack[-1] = stack[-2] - stack.pop()\n elif i == \"*\":\n stack[-1] = stack[-2] * stack.pop()\n elif i == \"/\":\n stack[-1] = int(stack[-2] / stack.pop())\n else:\n stack.append(int(i))\n \n return stack.pop()\n \n", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [key i , value i ] indicates that key key i has a value of value i . You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key key i , you will: Each key will appear at most once in your knowledge . There will not be any nested brackets in s . Return the resulting string after evaluating all of the bracket pairs.", + "description_images": [], + "constraints": [ + "For example, in the string \"(name)is(age)yearsold\" , there are two bracket pairs that contain the keys \"name\" and \"age\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput:\"bobistwoyearsold\"\nExplanation:The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\nOutput:\"hi?\"\nExplanation:As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\nOutput:\"yesyesyesaaa\"\nExplanation:The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 56.41%) | Memory: 91.9 MB (Top 81.62%)\nclass Solution {\n public String evaluate(String s, List> knowledge) {\n Map map = new HashMap<>();\n for(List ele : knowledge) {\n map.put(ele.get(0), ele.get(1));\n }\n StringBuilder sb = new StringBuilder();\n int b_start = -1;\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) == '(') {\n b_start = i;\n } else if(s.charAt(i) == ')') {\n String key = s.substring(b_start + 1, i);\n sb.append(map.getOrDefault(key, \"?\"));\n b_start = -1;\n } else {\n if(b_start == -1) {\n sb.append(s.charAt(i));\n }\n }\n }\n return sb.toString();\n }\n}", + "title": "1807. Evaluate the Bracket Pairs of a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [key i , value i ] indicates that key key i has a value of value i . You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key key i , you will: Each key will appear at most once in your knowledge . There will not be any nested brackets in s . Return the resulting string after evaluating all of the bracket pairs.", + "description_images": [], + "constraints": [ + "For example, in the string \"(name)is(age)yearsold\" , there are two bracket pairs that contain the keys \"name\" and \"age\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput:\"bobistwoyearsold\"\nExplanation:The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\nOutput:\"hi?\"\nExplanation:As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\nOutput:\"yesyesyesaaa\"\nExplanation:The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n knowledge = dict(knowledge)\n answer, start = [], None\n for i, char in enumerate(s):\n if char == '(': \n start = i + 1\n elif char == ')':\n answer.append(knowledge.get(s[start:i], '?'))\n start = None\n elif start is None: \n answer.append(char)\n return ''.join(answer)\n", + "title": "1807. Evaluate the Bracket Pairs of a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A binary tree is named Even-Odd if it meets the following conditions: Given the root of a binary tree, return true if the binary tree is Even-Odd , otherwise return false .", + "description_images": [], + "constraints": [ + "The root of the binary tree is at level index 0 , its children are at level index 1 , their children are at level index 2 , etc.", + "For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).", + "For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right)." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput:true\nExplanation:The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png" + }, + { + "text": "Example 2: Input:root = [5,4,2,3,3,7]\nOutput:false\nExplanation:The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png" + }, + { + "text": "Example 3: Input:root = [5,9,1,3,5,7]\nOutput:false\nExplanation:Node values in the level 1 should be even integers.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 96.0%) | Memory: 66.10 MB (Top 31.24%)\n\nclass Solution {\n public boolean isEvenOddTree(TreeNode root) {\n Queue qu = new LinkedList<>();\n qu.add(root);\n boolean even = true; // maintain check for levels\n while(qu.size()>0){\n int size = qu.size();\n int prev = (even)?0:Integer.MAX_VALUE; // start prev with 0 to check strictly increasing and Integer_MAX_VALUE to check strictly decreasing \n while(size-->0){\n TreeNode rem = qu.remove();\n if(even){\n if(rem.val%2==0 || rem.val<=prev){ // false if value at even level is even or not strictly increasing \n return false;\n }\n }else{\n if(rem.val%2!=0 || rem.val>=prev){// false if value at odd level is odd or not strictly decreasing\n return false;\n }\n }\n if(rem.left!=null){\n qu.add(rem.left); \n }\n if(rem.right!=null){\n qu.add(rem.right);\n }\n prev=rem.val; //update previous\n \n }\n even = !even; //change level\n } \n return true;\n }\n}\n", + "title": "1609. Even Odd Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A binary tree is named Even-Odd if it meets the following conditions: Given the root of a binary tree, return true if the binary tree is Even-Odd , otherwise return false .", + "description_images": [], + "constraints": [ + "The root of the binary tree is at level index 0 , its children are at level index 1 , their children are at level index 2 , etc.", + "For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).", + "For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right)." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput:true\nExplanation:The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png" + }, + { + "text": "Example 2: Input:root = [5,4,2,3,3,7]\nOutput:false\nExplanation:The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png" + }, + { + "text": "Example 3: Input:root = [5,9,1,3,5,7]\nOutput:false\nExplanation:Node values in the level 1 should be even integers.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png" + } + ], + "follow_up": null, + "solution": "from collections import deque\n# Runtime:838ms 44.05% || Memory: 40.8mb 57.22%\n# O(n) || O(h); where h is the height of the tree\n\nclass Solution:\n def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return False\n\n level = 0\n evenOddLevel = {0:1, 1:0}\n queue = deque([root])\n\n while queue:\n prev = 0\n for _ in range(len(queue)):\n currNode = queue.popleft()\n comparison = {0:prev < currNode.val, 1:prev > currNode.val}\n if currNode.val % 2 != evenOddLevel[level % 2]:\n return False\n else:\n if prev != 0 and comparison[level % 2]:\n prev = currNode.val\n elif prev == 0:\n prev = currNode.val\n else:\n return False\n\n if currNode.left:\n queue.append(currNode.left)\n\n if currNode.right:\n queue.append(currNode.right)\n\n level += 1\n\n return True\n", + "title": "1609. Even Odd Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an exam room with n seats in a single row labeled from 0 to n - 1 . When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0 . Design a class that simulates the mentioned exam room. Implement the ExamRoom class:", + "description_images": [], + "constraints": [ + "ExamRoom(int n) Initializes the object of the exam room with the number of the seats n .", + "int seat() Returns the label of the seat at which the next student will set.", + "void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]Output[null, 0, 9, 4, 2, null, 5]ExplanationExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 87.99%) | Memory: 52.8 MB (Top 24.67%)\nclass ExamRoom {\n\n private final int max;\n private final TreeSet available;\n private final TreeSet taken;\n\n public ExamRoom(int n) {\n this.max = n - 1;\n this.available = new TreeSet<>((a, b) -> {\n var distA = getMinDistance(a);\n var distB = getMinDistance(b);\n return distA == distB ? a.s - b.s : distB - distA;\n });\n this.available.add(new Interval(0, max));\n this.taken = new TreeSet<>();\n }\n\n public int seat() {\n var inter = available.pollFirst();\n var idx = getInsertPosition(inter);\n taken.add(idx);\n if ((idx - 1) - inter.s >= 0)\n available.add(new Interval(inter.s, idx - 1));\n if (inter.e - (idx + 1) >= 0)\n available.add(new Interval(idx + 1, inter.e));\n return idx;\n }\n\n public void leave(int p) {\n taken.remove(p);\n var lo = taken.lower(p);\n if (lo == null)\n lo = -1;\n var hi = taken.higher(p);\n if (hi == null)\n hi = max + 1;\n available.remove(new Interval(lo + 1, p - 1));\n available.remove(new Interval(p + 1, hi - 1));\n available.add(new Interval(lo + 1, hi - 1));\n }\n\n private int getInsertPosition(Interval inter) {\n if (inter.s == 0)\n return 0;\n else if (inter.e == max)\n return max;\n else\n return inter.s + (inter.e - inter.s) / 2;\n }\n\n private int getMinDistance(Interval in) {\n return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2;\n }\n\n private final class Interval {\n private final int s;\n private final int e;\n\n Interval(int s, int e) {\n this.s = s;\n this.e = e;\n }\n\n @Override\n public String toString() {\n return \"[\" + s + \",\" + e + \"]\";\n }\n }\n}", + "title": "855. Exam Room", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an exam room with n seats in a single row labeled from 0 to n - 1 . When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0 . Design a class that simulates the mentioned exam room. Implement the ExamRoom class:", + "description_images": [], + "constraints": [ + "ExamRoom(int n) Initializes the object of the exam room with the number of the seats n .", + "int seat() Returns the label of the seat at which the next student will set.", + "void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]Output[null, 0, 9, 4, 2, null, 5]ExplanationExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 182 ms (Top 65.24%) | Memory: 20.7 MB (Top 5.08%)\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.N = n\n self.pq = []\n self.dict = {}\n self.addSegment(0, self.N - 1)\n\n def seat(self) -> int:\n start, end, distance = heapq.heappop(self.pq)\n self.dict.pop(start, None) #Remove old segment from dictionary\n self.dict.pop(end, None)\n\n if start == end:\n position = start\n\n elif start == 0:\n position = start\n right = self.addSegment(start + 1, end)\n\n elif end == self.N - 1:\n position = end\n left = self.addSegment(start, end - 1)\n\n elif end - start == 1: #ONLY ONE PLACE TO PUT\n position = start\n left = self.addSegment(start + 1, end)\n\n else:\n position = start + (end - start) // 2\n right = self.addSegment(start, position - 1)\n left = self.addSegment(position + 1, end)\n\n return position\n\n def leave(self, p: int) -> None:\n left = self.dict.get(p - 1, None)\n right = self.dict.get(p + 1, None)\n\n new_start = new_end = p\n\n if left:\n self.removeSegment(left)\n new_start = left.start\n\n if right:\n self.removeSegment(right)\n new_end = right.end\n\n self.addSegment(new_start, new_end)\n\n def addSegment(self, start, end):\n segment = Segment(start, end, self.N)\n self.dict[segment.start] = segment\n self.dict[segment.end] = segment\n heapq.heappush(self.pq, segment)\n\n def removeSegment(self, segment):\n self.dict.pop(segment.start, None)\n self.dict.pop(segment.end, None)\n self.pq.remove(segment)\n\nclass Segment():\n def __init__(self, start, end, N):\n self.start = start\n self.end = end\n self.distance = self.calculateDistance(start, end, N)\n\n def __lt__(self, other_segment):\n return self.distance > other_segment.distance if self.distance != other_segment.distance else self.start < other_segment.start\n\n def calculateDistance(self, start, end, N):\n if start == 0:\n return end\n\n if end == N - 1:\n return end - start\n\n else:\n return (end - start) // 2\n\n def __iter__(self):\n return iter((self.start, self.end, self.distance))", + "title": "855. Exam Room", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"\nOutput:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"\nOutput:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 81.25%) | Memory: 42.4 MB (Top 81.68%)\nclass Solution {\n public int titleToNumber(String columnTitle) {\n int n = columnTitle.length();\n int pow = 0;\n int res = 0;\n for(int i = n-1; i >= 0; i--) {\n char c = columnTitle.charAt(i);\n res += (c - 64) * Math.pow(26, pow);\n pow++;\n }\n\n return res;\n }\n}", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"\nOutput:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"\nOutput:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "def let_to_num(char):\n abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n return abc.index(char) + 1\n\nclass Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n ans = 0\n for i in range(len(columnTitle)):\n ans *= 26\n ans += let_to_num(columnTitle[i])\n return ans\n", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701\nOutput:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 36.84%) | Memory: 41.2 MB (Top 58.44%)\nclass Solution {\n public String convertToTitle(int columnNumber) {\n String ans = \"\";\n while(columnNumber > 0){\n columnNumber--;\n ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans;\n columnNumber /= 26;\n }\n return ans;\n }\n}", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701\nOutput:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def convertToTitle(self, num: int) -> str:\n\t\t# We make this lookup list, having A-Z in ascending order\n alpha = [chr(x) for x in range(ord(\"A\"), ord(\"Z\")+1)] # range(65, 90+1) -> 91-65 = 26\n res = \"\"\n\n while num > 0:\n res += alpha[(num-1)%26] # since 0 indexed list, num-1 % 26 gives the index of ch in alpha\n num = (num-1) // 26 \n return res[::-1]\n", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1 . Function calls are stored in a call stack : when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed . Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs , where logs[i] represents the i th log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\" . For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3 , and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2 . Note that a function can be called multiple times, possibly recursively . A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3 . Return the exclusive time of each function in an array, where the value at the i th index represents the exclusive time for the function with ID i .", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "1 <= logs.length <= 500", + "0 <= function_id < n", + "0 <= timestamp <= 10^9", + "No two start events will happen at the same timestamp.", + "No two end events will happen at the same timestamp.", + "Each function has an \"end\" log for each \"start\" log." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\nOutput:[3,4]\nExplanation:Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.", + "image": "https://assets.leetcode.com/uploads/2019/04/05/diag1b.png" + }, + { + "text": "Example 2: Input:n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\nOutput:[8]\nExplanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\nOutput:[7,1]\nExplanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 31.28%) | Memory: 52.6 MB (Top 22.01%)\nclass Solution {\n\n //Time Complexity: O(N) for looping through logs\n //Space Complexity: O(N) for stack\n\n public int[] exclusiveTime(int n, List logs) {\n if (n == 0) {\n return new int[0];\n }\n\n int[] result = new int[n];\n\n Stack> stack = new Stack<>();\n\n for (String s : logs) {\n String[] sArr = s.split(\":\");\n int functionId = Integer.parseInt(sArr[0]);\n String startOrEnd = sArr[1];\n int timestamp = Integer.parseInt(sArr[2]);\n\n if (startOrEnd.equals(\"start\")) {\n\n //calculate previous in-progress length\n if (!stack.empty()) {\n Pair pair = stack.peek();\n int oldFunctionId = pair.getKey();\n int oldTimestamp = pair.getValue();\n result[oldFunctionId] += timestamp - oldTimestamp;\n }\n\n //add new start\n stack.push(new Pair(functionId, timestamp));\n } else {\n //calculate current length\n Pair pair = stack.pop();\n int oldTimestamp = pair.getValue();\n\n result[functionId] += timestamp - oldTimestamp + 1;\n\n //reset previous function's start\n if (!stack.empty()) {\n pair = stack.pop();\n Pair replacementPair = new Pair(pair.getKey(), timestamp + 1);\n stack.push(replacementPair);\n }\n }\n }\n\n return result;\n }\n}", + "title": "636. Exclusive Time of Functions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1 . Function calls are stored in a call stack : when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed . Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs , where logs[i] represents the i th log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\" . For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3 , and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2 . Note that a function can be called multiple times, possibly recursively . A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3 . Return the exclusive time of each function in an array, where the value at the i th index represents the exclusive time for the function with ID i .", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "1 <= logs.length <= 500", + "0 <= function_id < n", + "0 <= timestamp <= 10^9", + "No two start events will happen at the same timestamp.", + "No two end events will happen at the same timestamp.", + "Each function has an \"end\" log for each \"start\" log." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\nOutput:[3,4]\nExplanation:Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.", + "image": "https://assets.leetcode.com/uploads/2019/04/05/diag1b.png" + }, + { + "text": "Example 2: Input:n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\nOutput:[8]\nExplanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\nOutput:[7,1]\nExplanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 78 ms (Top 92.98%) | Memory: 14.2 MB (Top 33.69%)\nclass Solution:\n #T=O(n), S=O(d)\n #n=len of logs, d=depth of stack\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n #init result array to zeroes of length n (function ids)\n res = [0]*n\n stack = []\n #iterate through logs\n for log in logs:\n #split the log\n #function_id: start|end: timestamp\n log = log.split(\":\")\n #type cast function id and timestamp to int type\n id = int(log[0])\n timestamp = int(log[2])\n state = log[1]\n #detect start of a function call\n #stack[function_id, start_timestamp]\n if state == \"start\":\n #stack is non empty\n if stack:\n #get the time taken by last function so far\n res[stack[-1][0]] += timestamp - stack[-1][1]\n #append the current function_id and start timestamp to the stack\n stack.append([id, timestamp])\n else:\n #get the time consumed by current function\n #dont forget to add 1 as the last unit of time should be included\n res[id] += timestamp - stack.pop()[1] + 1\n if stack:\n #update the start time of last function in stack to get the cumulative result\n stack[-1][1] = timestamp + 1\n\n return res", + "title": "636. Exclusive Time of Functions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1) . You are given the integer n and an integer array startPos where startPos = [start row , start col ] indicates that a robot is initially at cell (start row , start col ) . You are also given a 0-indexed string s of length m where s[i] is the i th instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any i th instruction in s . It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the i th instruction in s .", + "description_images": [], + "constraints": [ + "The next instruction will move the robot off the grid.", + "There are no more instructions left to execute." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, startPos = [0,1], s = \"RRDDLU\"\nOutput:[1,5,4,3,1,0]\nExplanation:Starting from startPos and beginning execution from the ithinstruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st: \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th: \"U\". If moving up, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/1.png" + }, + { + "text": "Example 2: Input:n = 2, startPos = [1,1], s = \"LURD\"\nOutput:[4,1,0,0]\nExplanation:- 0th: \"LURD\".\n- 1st: \"URD\".\n- 2nd: \"RD\".\n- 3rd: \"D\".", + "image": "https://assets.leetcode.com/uploads/2021/12/09/2.png" + }, + { + "text": "Example 3: Input:n = 1, startPos = [0,0], s = \"LRUD\"\nOutput:[0,0,0,0]\nExplanation:No matter which instruction the robot begins execution from, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 101 ms (Top 24.39%) | Memory: 46.7 MB (Top 33.10%)\nclass Solution {\n public int[] executeInstructions(int n, int[] startPos, String s) {\n //Make array of length equal to string length\n int ans[]=new int[s.length()];\n\n //Now use two for loops\n for(int i=0;i=n || yIndex<0 || yIndex>=n){\n break;\n }\n else{\n countMoves++;\n }\n }\n\n ans[i]=countMoves;\n\n }\n return ans;\n\n }\n}", + "title": "2120. Execution of All Suffix Instructions Staying in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1) . You are given the integer n and an integer array startPos where startPos = [start row , start col ] indicates that a robot is initially at cell (start row , start col ) . You are also given a 0-indexed string s of length m where s[i] is the i th instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any i th instruction in s . It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the i th instruction in s .", + "description_images": [], + "constraints": [ + "The next instruction will move the robot off the grid.", + "There are no more instructions left to execute." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, startPos = [0,1], s = \"RRDDLU\"\nOutput:[1,5,4,3,1,0]\nExplanation:Starting from startPos and beginning execution from the ithinstruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st: \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th: \"U\". If moving up, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/1.png" + }, + { + "text": "Example 2: Input:n = 2, startPos = [1,1], s = \"LURD\"\nOutput:[4,1,0,0]\nExplanation:- 0th: \"LURD\".\n- 1st: \"URD\".\n- 2nd: \"RD\".\n- 3rd: \"D\".", + "image": "https://assets.leetcode.com/uploads/2021/12/09/2.png" + }, + { + "text": "Example 3: Input:n = 1, startPos = [0,0], s = \"LRUD\"\nOutput:[0,0,0,0]\nExplanation:No matter which instruction the robot begins execution from, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:\n result = []\n for idx in range(len(s)):\n count, row, col = 0, startPos[0],startPos[1]\n while idx < len(s):\n if s[idx] == 'D':\n row += 1\n if row >= n:\n break\n count += 1\n elif s[idx] == 'U':\n row -= 1\n if row < 0:\n break\n count += 1\n elif s[idx] == 'R':\n col += 1\n if col >= n:\n break\n count += 1\n else:\n col -= 1\n if col < 0:\n break\n count += 1\n idx += 1\n result.append(count)\n return result\n", + "title": "2120. Execution of All Suffix Instructions Staying in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string num that contains only digits and an integer target , return all possibilities to insert the binary operators '+' , '-' , and/or '*' between the digits of num so that the resultant expression evaluates to the target value . Note that operands in the returned expressions should not contain leading zeros.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10", + "num consists of only digits.", + "-2 31 <= target <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"123\", target = 6\nOutput:[\"1*2*3\",\"1+2+3\"]\nExplanation:Both \"1*2*3\" and \"1+2+3\" evaluate to 6.", + "image": null + }, + { + "text": "Example 2: Input:num = \"232\", target = 8\nOutput:[\"2*3+2\",\"2+3*2\"]\nExplanation:Both \"2*3+2\" and \"2+3*2\" evaluate to 8.", + "image": null + }, + { + "text": "Example 3: Input:num = \"3456237490\", target = 9191\nOutput:[]\nExplanation:There are no expressions that can be created from \"3456237490\" to evaluate to 9191.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 142 ms (Top 13.4%) | Memory: 44.41 MB (Top 73.2%)\n\nclass Solution {\n String s;\n Listresult;\n int target;\n public void operator(int i,int prev,long prod,long mid,String exp,Listl){\n if(i==l.size()){\n if(mid+prod==target)\n result.add(exp);\n return;\n }\n if(prev==-1){\n operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+\"*\"+l.get(i),l);\n }else if(prev==1){\n operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+\"*\"+l.get(i),l);\n }else{\n operator(i+1,0,prod*l.get(i),mid,exp+\"*\"+l.get(i),l);\n }\n operator(i+1,-1,0,mid+prod-l.get(i),exp+\"-\"+l.get(i),l);\n operator(i+1,1,0,mid+prod+l.get(i),exp+\"+\"+l.get(i),l);\n }\n public void rec(int in,Listl){\n if(in==s.length()){\n operator(1,1,0,l.get(0),l.get(0)+\"\",l);\n return;\n }\n if(s.charAt(in)=='0'){\n l.add(0L);\n rec(in+1,l);\n l.remove(l.size()-1);\n }else{\n for(int i=in;i addOperators(String num, int target) {\n result=new ArrayList<>();\n this.s=num;\n this.target=target;\n rec(0,new ArrayList<>(30));\n return result;\n }\n}", + "title": "282. Expression Add Operators", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string num that contains only digits and an integer target , return all possibilities to insert the binary operators '+' , '-' , and/or '*' between the digits of num so that the resultant expression evaluates to the target value . Note that operands in the returned expressions should not contain leading zeros.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10", + "num consists of only digits.", + "-2 31 <= target <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"123\", target = 6\nOutput:[\"1*2*3\",\"1+2+3\"]\nExplanation:Both \"1*2*3\" and \"1+2+3\" evaluate to 6.", + "image": null + }, + { + "text": "Example 2: Input:num = \"232\", target = 8\nOutput:[\"2*3+2\",\"2+3*2\"]\nExplanation:Both \"2*3+2\" and \"2+3*2\" evaluate to 8.", + "image": null + }, + { + "text": "Example 3: Input:num = \"3456237490\", target = 9191\nOutput:[]\nExplanation:There are no expressions that can be created from \"3456237490\" to evaluate to 9191.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n s=num[0]\n q=[\"+\",\"-\",\"*\",\"\"]\n ans=[]\n def cal(w):\n i=1\n while i \"heeellooo\"", + "\"hi\" -> \"hiiii\"" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\nOutput:1\nExplanation:We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private String getFreqString(String s) {\n int len = s.length();\n StringBuilder freqString = new StringBuilder();\n int currFreq = 1;\n char prevChar = s.charAt(0);\n freqString.append(s.charAt(0));\n for(int i = 1; i0) {\n freqString.append(currFreq);\n }\n \n return freqString.toString();\n }\n \n private boolean isGreaterButLessThanThree(char sChar, char wChar) { \n return sChar > wChar && sChar < '3';\n }\n \n private boolean isStretchy(String s, String word) { \n int sLen = s.length();\n int wordLen = word.length();\n \n if(sLen != wordLen) {\n return false;\n }\n \n for(int i = 0; i \"heeellooo\"", + "\"hi\" -> \"hiiii\"" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\nOutput:1\nExplanation:We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def expressiveWords(self, s: str, words: List[str]) -> int:\n # edge cases\n if len(s) == 0 and len(words) != 0:\n return False\n if len(words) == 0 and len(s) != 0:\n return False\n if len(s) == 0 and len(words) == 0:\n return True\n \n # helper function, compressing string and extract counts\n def compressor(s_word):\n init_string =[s_word[0]]\n array = []\n start = 0\n for i,c in enumerate(s_word):\n if c == init_string[-1]:\n continue\n array.append(i-start)\n start = i\n init_string += c \n array.append(i-start+1) \n return init_string,array\n\n res = len(words)\n s_split, s_array = compressor(s)\n for word in words:\n word_split = ['']\n word_array = []\n word_split,word_array = compressor(word)\n if s_split == word_split:\n for num_s,num_word in zip(s_array,word_array):\n if num_s != num_word and num_s < 3 or num_word > num_s:\n res -= 1\n break\n else:\n res -= 1\n return res", + "title": "809. Expressive Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:0\nExplanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:1\nExplanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trailingZeroes(int n) {\n int count=0;\n while(n>1) {count+=n/5; n=n/5;}\n return count;\n }\n}", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:0\nExplanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:1\nExplanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n res = 0\n for i in range(2, n+1):\n while i > 0 and i%5 == 0:\n i //= 5\n res += 1\n return res", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the i th box of candy that Alice has and bobSizes[j] is the number of candies of the j th box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a n integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange . If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.", + "description_images": [], + "constraints": [ + "1 <= aliceSizes.length, bobSizes.length <= 10^4", + "1 <= aliceSizes[i], bobSizes[j] <= 10^5", + "Alice and Bob have a different total number of candies.", + "There will be at least one valid answer for the given input." + ], + "examples": [ + { + "text": "Example 1: Input:aliceSizes = [1,1], bobSizes = [2,2]\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:aliceSizes = [1,2], bobSizes = [2,3]\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:aliceSizes = [2], bobSizes = [1,3]\nOutput:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\nvector fairCandySwap(vector& aliceSizes, vector& bobSizes) {\n\n sort(bobSizes.begin(),bobSizes.end());\n sort(aliceSizes.begin(),aliceSizes.end());\n\n int sum1=0;\n int sum2=0;\n vector ans;\n for(int i =0 ; i aliceSizes[i]-dif)\n {\n end=mid-1;\n }\n \n } \n }\n \n return ans;\n \n}\n};\n", + "title": "888. Fair Candy Swap", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array cookies , where cookies[i] denotes the number of cookies in the i th bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions .", + "description_images": [], + "constraints": [ + "2 <= cookies.length <= 8", + "1 <= cookies[i] <= 10^5", + "2 <= k <= cookies.length" + ], + "examples": [ + { + "text": "Example 1: Input:cookies = [8,15,10,20,8], k = 2\nOutput:31\nExplanation:One optimal distribution is [8,15,8] and [10,20]\n- The 1stchild receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.\n- The 2ndchild receives [10,20] which has a total of 10 + 20 = 30 cookies.\nThe unfairness of the distribution is max(31,30) = 31.\nIt can be shown that there is no distribution with an unfairness less than 31.", + "image": null + }, + { + "text": "Example 2: Input:cookies = [6,1,3,2,2,4,1,2], k = 3\nOutput:7\nExplanation:One optimal distribution is [6,1], [3,2,2], and [4,1,2]\n- The 1stchild receives [6,1] which has a total of 6 + 1 = 7 cookies.\n- The 2ndchild receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.\n- The 3rdchild receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.\nThe unfairness of the distribution is max(7,7,7) = 7.\nIt can be shown that there is no distribution with an unfairness less than 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.28 MB (Top 98.3%)\n\nclass Solution {\n int ans;\n int count[];\n public int distributeCookies(int[] cookies, int k) {\n ans= Integer.MAX_VALUE;\n count= new int[k];\n\n backtrack(0,cookies, k);\n return ans;\n }\n public void backtrack(int cookieNumber, int[] cookies, int k)\n {\n if(cookieNumber==cookies.length)\n {\n int max= 0;\n for(int i=0; i int:\n ans = float('inf')\n fair = [0]*k\n def rec(i):\n nonlocal ans,fair\n if i == len(cookies):\n ans = min(ans,max(fair))\n return\n\t\t\t# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution\n\t\t\tif ans <= max(fair):\n return\n for j in range(k):\n fair[j] += cookies[i]\n rec(i+1)\n fair[j] -= cookies[i]\n rec(0)\n return ans\n", + "title": "2305. Fair Distribution of Cookies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [left i , sideLength i ] represents the i th square with a side length of sideLength i that is dropped with its left edge aligned with X-coordinate left i . Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis . A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares . Return an integer array ans where ans[i] represents the height described above after dropping the i th square .", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 1000", + "1 <= left i <= 10^8", + "1 <= sideLength i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[1,2],[2,3],[6,1]]\nOutput:[2,5,5]\nExplanation:After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].", + "image": "https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg" + }, + { + "text": "Example 2: Input:positions = [[100,100],[200,100]]\nOutput:[100,100]\nExplanation:After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 89.89%) | Memory: 46.10 MB (Top 5.62%)\n\nclass Solution {\n public List fallingSquares(int[][] positions) {\n SegmentNode root = new SegmentNode(0,Integer.MAX_VALUE,0);\n List ans = new ArrayList<>();\n int max = 0;\n for(int[] p : positions){\n int left = p[0], height = p[1], right = left + height;\n int maxHeight = query(root, left, right) + height;\n max = Math.max(max,maxHeight);\n ans.add(max);\n add(root, left, right, maxHeight);\n }\n return ans;\n }\n public int query(SegmentNode root, int start, int end){\n if(start<=root.start && end>=root.end) return root.maxHeight;\n if(start>=root.end || end<=root.start) return 0;\n if (root.left==null) return root.maxHeight;\n int mid = root.start + (root.end - root.start) / 2;\n if (end <= mid) {\n return query(root.left, start, end);\n } else if (start >= mid) {\n return query(root.right, start, end);\n }\n return Math.max(query(root.left,start,mid),query(root.right,mid,end));\n }\n\n public void add(SegmentNode root, int start, int end, int maxHeight){\n if(start<=root.start && end>=root.end){\n root.maxHeight = maxHeight;\n root.left = null;\n root.right = null;\n return;\n }\n if(start>=root.end || root.start>=end) return;\n if(root.left==null){\n int mid = root.start + (root.end - root.start) / 2;\n root.left = new SegmentNode(root.start,mid,0);\n root.right = new SegmentNode(mid,root.end,0);\n }\n add(root.left,start,end,maxHeight);\n add(root.right,start,end,maxHeight);\n root.maxHeight = Math.max(root.left.maxHeight,root.right.maxHeight);\n }\n}\nclass SegmentNode{\n public SegmentNode left , right;\n public int start, end, maxHeight;\n public SegmentNode(int start, int end, int maxHeight){\n this.start = start;\n this.end = end;\n this.maxHeight = maxHeight;\n }\n}\n", + "title": "699. Falling Squares", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [left i , sideLength i ] represents the i th square with a side length of sideLength i that is dropped with its left edge aligned with X-coordinate left i . Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis . A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares . Return an integer array ans where ans[i] represents the height described above after dropping the i th square .", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 1000", + "1 <= left i <= 10^8", + "1 <= sideLength i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[1,2],[2,3],[6,1]]\nOutput:[2,5,5]\nExplanation:After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].", + "image": "https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg" + }, + { + "text": "Example 2: Input:positions = [[100,100],[200,100]]\nOutput:[100,100]\nExplanation:After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.", + "image": null + } + ], + "follow_up": null, + "solution": "class SegmentTreeNode:\n def __init__(self, low, high):\n self.low = low\n self.high = high\n self.left = None\n self.right = None\n self.max = 0\n\nclass Solution: \n def _build(self, left, right):\n root = SegmentTreeNode(self.coords[left], self.coords[right])\n if left == right:\n return root\n \n mid = (left+right)//2\n root.left = self._build(left, mid)\n root.right = self._build(mid+1, right)\n return root\n \n def _update(self, root, lower, upper, val):\n if not root:\n return\n if lower <= root.high and root.low <= upper:# intersect\n root.max = val\n self._update(root.left, lower, upper, val)\n self._update(root.right, lower, upper, val)\n \n def _query(self, root, lower, upper):\n if lower <= root.low and root.high <= upper:\n return root.max\n if upper < root.low or root.high < lower:\n return 0\n return max(self._query(root.left, lower, upper), self._query(root.right, lower, upper))\n \n def fallingSquares(self, positions: List[List[int]]) -> List[int]:\n\t\t# coordinates compression\n coords = set()\n for left, size in positions:\n right = left+size-1\n coords.add(left)\n coords.add(right)\n self.coords = sorted(list(coords))\n root = self._build(0, len(self.coords)-1)\n \n res = []\n for left, size in positions:\n right = left+size-1\n h = self._query(root, left, right) + size\n res.append(max(res[-1],h)) if res else res.append(h)\n self._update(root, left, right, h)\n return res\n", + "title": "699. Falling Squares", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an API that generates fancy sequences using the append , addAll , and multAll operations. Implement the Fancy class:", + "description_images": [], + "constraints": [ + "Fancy() Initializes the object with an empty sequence.", + "void append(val) Appends an integer val to the end of the sequence.", + "void addAll(inc) Increments all existing values in the sequence by an integer inc .", + "void multAll(m) Multiplies all existing values in the sequence by an integer m .", + "int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7 . If the index is greater or equal than the length of the sequence, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]Output[null, null, null, null, null, 10, null, null, null, 26, 34, 20]ExplanationFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "class Fancy {\n private ArrayList lst;\n private ArrayList add;\n private ArrayList mult;\n private final long MOD = 1000000007;\n\n public Fancy() {\n lst = new ArrayList<>();\n add = new ArrayList<>();\n mult = new ArrayList<>();\n add.add(0L);\n mult.add(1L);\n }\n\n public void append(int val) {\n lst.add((long) val);\n int l = add.size();\n add.add(add.get(l - 1));\n mult.add(mult.get(l - 1));\n }\n\n public void addAll(int inc) {\n int l = add.size();\n add.set(l - 1, add.get(l - 1) + inc);\n }\n\n public void multAll(int m) {\n int l = add.size();\n add.set(l - 1, (add.get(l - 1) * m) % MOD);\n mult.set(l - 1, (mult.get(l - 1) * m) % MOD);\n }\n\n public int getIndex(int idx) {\n if (idx >= lst.size()) return -1;\n\n int l = add.size();\n long m = (mult.get(l - 1) * inverse(mult.get(idx))) % MOD;\n long a = (add.get(l - 1) - (add.get(idx) * m) % MOD + MOD) % MOD;\n return (int) (((lst.get(idx) * m) % MOD + a) % MOD);\n }\n\n long inverse(long a) {\n return pow(a, MOD - 2);\n }\n\n long pow(long a, long n) {\n if (n == 0) return 1;\n if (n % 2 == 0) {\n long t = pow(a, n / 2);\n return (t * t) % MOD;\n } else {\n return (pow(a, n - 1) * a) % MOD;\n }\n }\n}\n", + "title": "1622. Fancy Sequence", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Write an API that generates fancy sequences using the append , addAll , and multAll operations. Implement the Fancy class:", + "description_images": [], + "constraints": [ + "Fancy() Initializes the object with an empty sequence.", + "void append(val) Appends an integer val to the end of the sequence.", + "void addAll(inc) Increments all existing values in the sequence by an integer inc .", + "void multAll(m) Multiplies all existing values in the sequence by an integer m .", + "int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7 . If the index is greater or equal than the length of the sequence, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]Output[null, null, null, null, null, 10, null, null, null, 26, 34, 20]ExplanationFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "def egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\ndef modinv(a, m):\n g, x, y = egcd(a, m)\n return x % m\n\nmod = 1000000007\n\nclass Fancy(object):\n\n def __init__(self):\n self.seq = []\n self.addC = 0\n self.mulC = 1\n \n def append(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.seq.append([val, self.mulC, self.addC])\n \n\n def addAll(self, inc):\n \"\"\"\n :type inc: int\n :rtype: None\n \"\"\"\n self.addC = (self.addC%mod + inc%mod)%mod\n\n def multAll(self, m):\n \"\"\"\n :type m: int\n :rtype: None\n \"\"\"\n self.mulC = (self.mulC%mod * m%mod)%mod\n self.addC = (self.addC%mod * m%mod)%mod\n \n\n def getIndex(self, idx):\n \"\"\"\n :type idx: int\n :rtype: int\n \"\"\"\n if(idx >= len(self.seq)):\n return -1\n \n mulCo = self.seq[idx][1]\n addCo = self.seq[idx][2]\n val = self.seq[idx][0]\n \n inv = modinv(mulCo, mod)\n a = (self.mulC%mod * inv%mod)%mod\n val = (val%mod * a%mod)%mod\n b = (addCo%mod * a%mod)%mod\n val = (val%mod - b%mod)%mod\n val = (val%mod + self.addC%mod)%mod\n \n return val\n", + "title": "1622. Fancy Sequence", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The Fibonacci numbers , commonly denoted F(n) form a sequence, called the Fibonacci sequence , such that each number is the sum of the two preceding ones, starting from 0 and 1 . That is, Given n , calculate F(n) .", + "description_images": [], + "constraints": [ + "0 <= n <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:F(2) = F(1) + F(0) = 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:2\nExplanation:F(3) = F(2) + F(1) = 1 + 1 = 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:3\nExplanation:F(4) = F(3) + F(2) = 2 + 1 = 3.", + "image": null + }, + { + "text": "F(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.00 MB (Top 41.57%)\n\nclass Solution {\n public int fib(int n) {\n if(n == 0)\n return 0;\n if(n == 1)\n return 1;\n int[] Fibonacci = new int[n+1];\n Fibonacci[0] = 0;\n Fibonacci[1] = 1;\n for(int i = 2; i < n+1; i++)\n Fibonacci[i] = Fibonacci[i-1] + Fibonacci[i-2];\n return Fibonacci[n];\n }\n}\n\n", + "title": "509. Fibonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The Fibonacci numbers , commonly denoted F(n) form a sequence, called the Fibonacci sequence , such that each number is the sum of the two preceding ones, starting from 0 and 1 . That is, Given n , calculate F(n) .", + "description_images": [], + "constraints": [ + "0 <= n <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:F(2) = F(1) + F(0) = 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:2\nExplanation:F(3) = F(2) + F(1) = 1 + 1 = 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:3\nExplanation:F(4) = F(3) + F(2) = 2 + 1 = 3.", + "image": null + }, + { + "text": "F(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 80.68%) | Memory: 13.8 MB (Top 55.21%)\nclass Solution:\n def fib(self, n: int) -> int:\n fa = [0, 1]\n\n for i in range(2, n + 1):\n fa.append(fa[i-2] + fa[i-1])\n\n return fa[n]", + "title": "509. Fibonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array books where books[i] = [thickness i , height i ] indicates the thickness and height of the i th book. You are also given an integer shelfWidth . We want to place these books in order onto bookcase shelves that have a total width shelfWidth . We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth , then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner .", + "description_images": [], + "constraints": [ + "For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf." + ], + "examples": [ + { + "text": "Example 1: Input:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4\nOutput:6\nExplanation:The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.", + "image": "https://assets.leetcode.com/uploads/2019/06/24/shelves.png" + }, + { + "text": "Example 2: Input:books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.30 MB (Top 39.5%)\n\nclass Solution {\n public int minHeightShelves(int[][] books, int shelfWidth) {\n int memo[] = new int[books.length];\n return recur(books, shelfWidth, 0, memo);\n }\n \n private int recur(int[][] books, int shelfWidth, int index, int[] memo) {\n \n if (index == books.length) {\n return 0;\n }\n \n if (memo[index] > 0) {\n return memo[index];\n }\n int ans = Integer.MAX_VALUE;\n int height = 0;\n int width = 0;\n \n for (int i = index; i < books.length; i++) {\n width += books[i][0];\n \n if (width > shelfWidth) {\n break;\n }\n height = Math.max(height, books[i][1]);\n ans = Math.min(ans, height + recur(books, shelfWidth, i + 1, memo));\n }\n return memo[index] = ans;\n }\n}\n", + "title": "1105. Filling Bookcase Shelves", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array books where books[i] = [thickness i , height i ] indicates the thickness and height of the i th book. You are also given an integer shelfWidth . We want to place these books in order onto bookcase shelves that have a total width shelfWidth . We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth , then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner .", + "description_images": [], + "constraints": [ + "For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf." + ], + "examples": [ + { + "text": "Example 1: Input:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4\nOutput:6\nExplanation:The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.", + "image": "https://assets.leetcode.com/uploads/2019/06/24/shelves.png" + }, + { + "text": "Example 2: Input:books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minHeightShelves(self, books, shelf_width: int) -> int:\n n, dp = len(books), [float('inf')] * (len(books)+1)\n dp[0] = 0\n\n for i in range(1, n+1):\n max_width, max_height, j = shelf_width, 0, i - 1\n \n while j >= 0 and max_width - books[j][0] >= 0:\n max_width -= books[j][0]\n max_height = max(max_height, books[j][1])\n dp[i] = max_height\n j -= 1\n\n if j >= 0 and max_width - books[j][0] < 0:\n j = i - 1\n dp[i] = float('inf')\n width, height = 0, 0\n while j >= 0 and width + books[j][0] <= shelf_width:\n width = width + books[j][0]\n height = max(books[j][1], height)\n dp[i] = min(dp[i], height + dp[j])\n j -= 1\n\n return dp[n]\n", + "title": "1105. Filling Bookcase Shelves", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array restaurants where restaurants[i] = [id i , rating i , veganFriendly i , price i , distance i ] . You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendly i set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendly i and veganFriendly take value 1 when it is true , and 0 when it is false .", + "description_images": [], + "constraints": [ + "1 <= restaurants.length <= 10^4", + "restaurants[i].length == 5", + "1 <= id i , rating i , price i , distance i <= 10^5", + "1 <= maxPrice, maxDistance <= 10^5", + "veganFriendly i and veganFriendly are 0 or 1.", + "All id i are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput:[3,1,5]\nExplanation:The restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "image": null + }, + { + "text": "Example 2: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput:[4,3,2,1,5]\nExplanation:The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.", + "image": null + }, + { + "text": "Example 3: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput:[4,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 93.75%) | Memory: 58 MB (Top 51.88%)\nclass Restaurant {\n int id, rating;\n Restaurant(int id, int rating) {\n this.id = id;\n this.rating = rating;\n }\n}\n\nclass RestaurantComparator implements Comparator {\n @Override\n public int compare(Restaurant r1, Restaurant r2) {\n return r1.rating == r2.rating ? r2.id - r1.id : r2.rating - r1.rating;\n }\n}\n\nclass Solution {\n public List filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {\n PriorityQueue heap = new PriorityQueue<>(new RestaurantComparator());\n if(veganFriendly == 1) {\n for(int[] restaurant: restaurants) {\n if(restaurant[2] == 1 && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n } else {\n for(int[] restaurant: restaurants) {\n if(restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n }\n List answer = new ArrayList<>();\n while(!heap.isEmpty()) {\n answer.add(heap.poll().id);\n }\n return answer;\n }\n}", + "title": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array restaurants where restaurants[i] = [id i , rating i , veganFriendly i , price i , distance i ] . You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendly i set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendly i and veganFriendly take value 1 when it is true , and 0 when it is false .", + "description_images": [], + "constraints": [ + "1 <= restaurants.length <= 10^4", + "restaurants[i].length == 5", + "1 <= id i , rating i , price i , distance i <= 10^5", + "1 <= maxPrice, maxDistance <= 10^5", + "veganFriendly i and veganFriendly are 0 or 1.", + "All id i are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput:[3,1,5]\nExplanation:The restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "image": null + }, + { + "text": "Example 2: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput:[4,3,2,1,5]\nExplanation:The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.", + "image": null + }, + { + "text": "Example 3: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput:[4,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef f_fcn(self,restaurants, veganFriendly, maxPrice, maxDistance):\n\tf_lst = filter(lambda x: (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or\n\t\t\t\t (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance), restaurants)\n\treturn f_lst\n\ndef h_fcn(self,lst):\n\treturn([lst[0], lst[1]])\n\ndef filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n\n\tres = map(self.h_fcn, self.f_fcn(restaurants, veganFriendly, maxPrice, maxDistance))\n\n\n\treturn map(lambda x: x[0], sorted(res, key=lambda x: (-x[1], -x[0])))\n", + "title": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i] , otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 500", + "1 <= prices[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [8,4,6,2,3]\nOutput:[4,2,4,2,3]\nExplanation:For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. \nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. \nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. \nFor items 3 and 4 you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:[1,2,3,4,5]\nExplanation:In this case, for all items, you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 3: Input:prices = [10,1,1,6]\nOutput:[9,0,1,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 50.03%) | Memory: 44.5 MB (Top 32.12%)\nclass Solution {\n public int[] finalPrices(int[] prices) {\n for(int i = 0; i < prices.length; i++){\n for(int j = i + 1; j < prices.length; j++){\n if(j > i && prices[j] <= prices[i]){\n prices[i] -= prices[j];\n break;\n }\n }\n }\n return prices;\n }\n}", + "title": "1475. Final Prices With a Special Discount in a Shop", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i] , otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 500", + "1 <= prices[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [8,4,6,2,3]\nOutput:[4,2,4,2,3]\nExplanation:For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. \nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. \nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. \nFor items 3 and 4 you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:[1,2,3,4,5]\nExplanation:In this case, for all items, you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 3: Input:prices = [10,1,1,6]\nOutput:[9,0,1,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 83.49%) | Memory: 16.60 MB (Top 61.19%)\n\nclass Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n for i in range(len(prices)):\n for j in range(i+1,len(prices)):\n if prices[j]<=prices[i]:\n prices[i]=prices[i]-prices[j]\n break\n return (prices)\n", + "title": "1475. Final Prices With a Special Discount in a Shop", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a programming language with only four operations and one variable X : Initially, the value of X is 0 . Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations .", + "description_images": [], + "constraints": [ + "++X and X++ increments the value of the variable X by 1 .", + "--X and X-- decrements the value of the variable X by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:operations = [\"--X\",\"X++\",\"X++\"]\nOutput:1\nExplanation:The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X = 0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:operations = [\"++X\",\"++X\",\"X++\"]\nOutput:3\nExplanation:The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\nOutput:0\nExplanation:The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int finalValueAfterOperations(String[] operations) {\n int val = 0;\n for(int i = 0; i int:\n x = 0\n for o in operations:\n if '+' in o:\n x += 1\n else:\n x -= 1\n return x", + "title": "2011. Final Value of Variable After Performing Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "The values of the nodes of the tree are unique.", + "target node is a node from the original tree and is not null ." + ], + "examples": [ + { + "text": "Example 1: Input:tree = [7,4,3,null,null,6,19], target = 3\nOutput:3\nExplanation:In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e1.png" + }, + { + "text": "Example 2: Input:tree = [7], target = 7\nOutput:7", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e2.png" + }, + { + "text": "Example 3: Input:tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e3.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {\n TreeNode[] ref = new TreeNode[]{null};\n dfs(cloned, target, ref);\n return ref[0];\n }\n public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) {\n if (root == null) return;\n if (root.val == target.val) {\n ref[0] = root;\n return;\n } else {\n dfs(root.left, target, ref);\n dfs(root.right, target, ref);\n }\n }\n}\n", + "title": "1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "The values of the nodes of the tree are unique.", + "target node is a node from the original tree and is not null ." + ], + "examples": [ + { + "text": "Example 1: Input:tree = [7,4,3,null,null,6,19], target = 3\nOutput:3\nExplanation:In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e1.png" + }, + { + "text": "Example 2: Input:tree = [7], target = 7\nOutput:7", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e2.png" + }, + { + "text": "Example 3: Input:tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1109 ms (Top 30.14%) | Memory: 24.2 MB (Top 19.53%)\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n def DFS(node1,node2):\n if node1==target:\n return node2\n if node1 and node1.left is None and node1.right is None:\n return\n\n res1 = DFS(node1.left,node2.left) if node1 else None\n if res1 is not None:\n return res1\n res2 = DFS(node1.right,node2.right) if node1 else None\n if res2 is not None:\n return res2\n res=DFS(original,cloned)\n return res", + "title": "1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal , find any peak element mat[i][j] and return the length 2 array [i,j] . You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/08/1.png", + "https://assets.leetcode.com/uploads/2021/06/07/3.png" + ], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 500", + "1 <= mat[i][j] <= 10^5", + "No two adjacent cells are equal." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,4],[3,2]]\nOutput:[0,1]\nExplanation:Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[10,20,15],[21,30,14],[7,16,32]]\nOutput:[1,1]\nExplanation:Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 887 ms (Top 94.77%) | Memory: 48.10 MB (Top 59.48%)\n\nclass Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n m, n = len(mat), len(mat[0])\n l, r = 0, n\n while l <= r:\n mid = (l + r) // 2\n cur_max, left = 0, False\n for i in range(m):\n if i > 0 and mat[i-1][mid] >= mat[i][mid]:\n continue\n if i+1 < m and mat[i+1][mid] >= mat[i][mid]: \n continue\n if mid+1 < n and mat[i][mid+1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], not mat[i][mid] > cur_max\n continue\n if mid > 0 and mat[i][mid-1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], mat[i][mid] > cur_max\n continue\n return [i, mid]\n if left:\n r = mid-1\n else:\n l = mid+1\n return []\n", + "title": "1901. Find a Peak Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Winston was given the above mysterious function func . He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target| . Notice that func should be called with the values l and r where 0 <= l, r < arr.length .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/09/change.png" + ], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "0 <= target <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,12,3,7,15], target = 5\nOutput:2\nExplanation:Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1000000,1000000,1000000], target = 1\nOutput:999999\nExplanation:Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4,8,16], target = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] tree;\n int[] arr;\n int target;\n int min;\n \n public int closestToTarget(int[] arr, int target) {\n int n = arr.length;\n this.arr = arr;\n this.target = target;\n tree = new int[n << 2];\n Arrays.fill(tree, (1 << 31) - 1); // initialize\n min = Integer.MAX_VALUE;\n for (int i = 0; i < n; i++) {\n add(i, 0, n, 0);\n }\n return min;\n }\n private void add(int x, int l, int r, int n) {\n if (l == r) {\n tree[n] = arr[x];\n min = Math.min(min, Math.abs(tree[n] - target));\n return;\n }\n int mid = l + (r - l) / 2;\n if (x <= mid) {\n add(x, l, mid, 2 * n + 1);\n } else {\n add(x, mid + 1, r, 2 * n + 2);\n }\n tree[n] = (tree[2 * n + 1] & tree[2 * n + 2]); // & two subtrees\n min = Math.min(min, Math.abs(tree[n] - target));\n }\n}\n", + "title": "1521. Find a Value of a Mysterious Function Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Winston was given the above mysterious function func . He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target| . Notice that func should be called with the values l and r where 0 <= l, r < arr.length .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/09/change.png" + ], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "0 <= target <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,12,3,7,15], target = 5\nOutput:2\nExplanation:Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1000000,1000000,1000000], target = 1\nOutput:999999\nExplanation:Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4,8,16], target = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1091 ms (Top 49.0%) | Memory: 27.44 MB (Top 83.6%)\n\nclass Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n ans, seen = inf, set()\n for x in arr: \n seen = {ss & x for ss in seen} | {x}\n ans = min(ans, min(abs(ss - target) for ss in seen))\n return ans ", + "title": "1521. Find a Value of a Mysterious Function Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"\nOutput:[0,6]\nExplanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"\nOutput:[0,1,2]\nExplanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n \n public List findAnagrams(String s, String p) {\n int fullMatchCount = p.length();\n Map anagramMap = new HashMap<>();\n \n for (Character c : p.toCharArray())\n anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1);\n \n List result = new ArrayList<>();\n int left = 0, right = 0, currentMatchCount = 0;\n Map currentAnagramMap = new HashMap<>();\n while (right < s.length()) {\n char c = s.charAt(right);\n if (anagramMap.get(c) == null) {\n currentAnagramMap = new HashMap<>();\n right++;\n left = right;\n currentMatchCount = 0;\n continue;\n }\n currentAnagramMap.put(c, currentAnagramMap.getOrDefault(c, 0) + 1);\n currentMatchCount++;\n \n if (currentAnagramMap.get(c) > anagramMap.get(c)) {\n char leftC = s.charAt(left);\n while (leftC != c) {\n currentAnagramMap.put(leftC, currentAnagramMap.get(leftC) - 1);\n left++;\n leftC = s.charAt(left);\n currentMatchCount--;\n }\n left++;\n currentAnagramMap.put(c, currentAnagramMap.get(c) - 1);\n currentMatchCount--;\n }\n \n if (currentMatchCount == fullMatchCount)\n result.add(left);\n \n right++;\n }\n return result;\n }\n}\n", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"\nOutput:[0,6]\nExplanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"\nOutput:[0,1,2]\nExplanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n l='abcdefghijklmnopqrstuvwxyz'\n if len(p)>len(s):\n return []\n d={}\n for x in l:\n d[x]=0\n d1=dict(d)\n d2=dict(d)\n for x in range(len(p)):\n d1[s[x]]+=1\n d2[p[x]]+=1\n l1=[]\n if d1==d2:\n l1=[0]\n #print(d1)\n for x in range(len(p),len(s)):\n d1[s[x]]+=1\n d1[s[x-len(p)]]-=1\n if d1==d2:\n l1.append(x-len(p)+1)\n return l1\n", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice , return an array of all the integers that appears twice . You must write an algorithm that runs in O(n) time and uses only constant extra space.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n", + "Each element in nums appears once or twice ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]\nOutput:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2]\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 36.17%) | Memory: 65.2 MB (Top 76.59%)\nclass Solution {\n public List findDuplicates(int[] nums) {\n List ans = new ArrayList<>();\n for(int i=0;i List[int]:\n res = []\n hm = {}\n # adding entries in hashmap to check frequency\n for i, v in enumerate(nums):\n if v not in hm:\n hm[v] = 1\n else:\n hm[v] += 1\n # checking frequency of item and adding output to an array\n for key, value in hm.items():\n if value > 1:\n res.append(key)\n return res", + "title": "442. Find All Duplicates in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the strings s1 and s2 of size n and the string evil , return the number of good strings . A good string has size n , it is alphabetically greater than or equal to s1 , it is alphabetically smaller than or equal to s2 , and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "s1 <= s2", + "1 <= n <= 500", + "1 <= evil.length <= 50", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\nOutput:51\nExplanation:There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".", + "image": null + }, + { + "text": "Example 2: Input:n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\nOutput:0\nExplanation:All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 72.7%) | Memory: 43.76 MB (Top 33.3%)\n\nclass Solution {\n Integer[][][][] dp;\n int mod = 1000000007;\n int[] lps;\n private int add(int a, int b) {\n return (a % mod + b % mod) % mod;\n }\n private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) {\n if(evI == evil.length) return 0;\n if(cur == s2.length) return 1;\n if(dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] != null) return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI];\n char start = isStrictLower ? s1[cur] : 'a';\n char end = isStrictUpper ? s2[cur] : 'z';\n int res = 0;\n for(char ch = start; ch <= end; ch ++) {\n if(evil[evI] == ch)\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, evI + 1));\n else {\n int j = evI;\n while (j > 0 && evil[j] != ch) j = lps[j - 1];\n if (ch == evil[j]) j++;\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, j));\n }\n }\n return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] = res;\n }\n public int findGoodStrings(int n, String s1, String s2, String evil) {\n char[] arr = s1.toCharArray();\n char[] brr = s2.toCharArray();\n char[] crr = evil.toCharArray();\n lps = new int[crr.length];\n for (int i = 1, j = 0; i < crr.length; i++) {\n while (j > 0 && crr[i] != crr[j]) j = lps[j - 1];\n if (crr[i] == crr[j]) lps[i] = ++j;\n }\n dp = new Integer[n][2][2][crr.length];\n return solve(arr, brr, 0, true, true, crr, 0);\n }\n}", + "title": "1397. Find All Good Strings", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the strings s1 and s2 of size n and the string evil , return the number of good strings . A good string has size n , it is alphabetically greater than or equal to s1 , it is alphabetically smaller than or equal to s2 , and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "s1 <= s2", + "1 <= n <= 500", + "1 <= evil.length <= 50", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\nOutput:51\nExplanation:There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".", + "image": null + }, + { + "text": "Example 2: Input:n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\nOutput:0\nExplanation:All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nclass Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n def srange(a, b):\n return [chr(i) for i in range(ord(a),ord(b)+1)]\n def LPS(pat):\n lps = [0]\n i, target = 1, 0\n while i < len(pat):\n if pat[i] == pat[target]:\n target += 1\n lps.append(target)\n i += 1\n elif target:\n target = lps[target-1]\n else:\n lps.append(0)\n i += 1\n return lps\n lps = LPS(evil)\n M = 10**9+7\n @lru_cache(None)\n def dfs(i, max_matched_idx, lb, rb):\n if max_matched_idx == len(evil): return 0\n if i == n: return 1\n l = s1[i] if lb else 'a'\n r = s2[i] if rb else 'z'\n candidates = srange(l, r)\n res = 0\n for j, c in enumerate(candidates):\n nxt_matched_idx = max_matched_idx\n while evil[nxt_matched_idx] != c and nxt_matched_idx:\n nxt_matched_idx = lps[nxt_matched_idx-1]\n res = (res + dfs(i+1, nxt_matched_idx+(c==evil[nxt_matched_idx]),\n lb = (lb and j == 0), rb = (rb and j==len(candidates)-1)))%M\n return res\n return dfs(0, 0, True, True)", + "title": "1397. Find All Good Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups . No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1) . Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r 1 , c 1 ) and a bottom right corner at (r 2 , c 2 ) is represented by the 4-length array [r 1 , c 1 , r 2 , c 2 ]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land . If there are no groups of farmland, return an empty array. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "m == land.length", + "n == land[i].length", + "1 <= m, n <= 300", + "land consists of only 0 's and 1 's.", + "Groups of farmland are rectangular in shape." + ], + "examples": [ + { + "text": "Example 1: Input:land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput:[[0,0,0,0],[1,1,2,2]]\nExplanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:land = [[1,1],[1,1]]\nOutput:[[0,0,1,1]]\nExplanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 3: Input:land = [[0]]\nOutput:[]\nExplanation:There are no groups of farmland.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-32-24-copy-of-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 59.55%) | Memory: 62.3 MB (Top 88.99%)\nclass Solution {\n int[] arr;\n public int[][] findFarmland(int[][] land) {\n List res = new ArrayList<>();\n for(int i=0;ii).toArray(int[][] :: new);\n }\n public void dfs(int[][] land, int i,int j){\n if(i<0 || j<0 || i>=land.length || j>= land[0].length || land[i][j] == 0) return;\n arr[2] = Math.max(i,arr[2]);\n arr[3] = Math.max(j,arr[3]);\n land[i][j] = 0;\n dfs(land,i-1,j);\n dfs(land,i,j+1);\n dfs(land,i+1,j);\n dfs(land,i,j-1);\n }\n}", + "title": "1992. Find All Groups of Farmland", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups . No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1) . Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r 1 , c 1 ) and a bottom right corner at (r 2 , c 2 ) is represented by the 4-length array [r 1 , c 1 , r 2 , c 2 ]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land . If there are no groups of farmland, return an empty array. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "m == land.length", + "n == land[i].length", + "1 <= m, n <= 300", + "land consists of only 0 's and 1 's.", + "Groups of farmland are rectangular in shape." + ], + "examples": [ + { + "text": "Example 1: Input:land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput:[[0,0,0,0],[1,1,2,2]]\nExplanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:land = [[1,1],[1,1]]\nOutput:[[0,0,1,1]]\nExplanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 3: Input:land = [[0]]\nOutput:[]\nExplanation:There are no groups of farmland.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-32-24-copy-of-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1416 ms (Top 90.80%) | Memory: 33.1 MB (Top 49.64%)\nclass Solution:\n\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n n = len(land)\n m = len(land[0])\n\n groups = []\n visited = set()\n\n for y in range(n):\n for x in range(m):\n if land[y][x] == 0:\n continue\n\n if (y, x) in visited:\n continue\n\n q = collections.deque()\n q.append((y, x))\n visited.add((y, x))\n\n while q:\n cy, cx = q.popleft()\n\n for dy, dx in ((0, 1), (1, 0)):\n if (cy + dy, cx + dx) in visited:\n continue\n\n if 0 <= cy + dy < n and 0 <= cx + dx < m:\n if land[cy + dy][cx + dx] == 1:\n q.append((cy + dy, cx + dx))\n visited.add((cy + dy, cx + dx))\n\n groups.append([y, x, cy, cx])\n\n return groups", + "title": "1992. Find All Groups of Farmland", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and two integers key and k . A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key . Return a list of all k-distant indices sorted in increasing order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 1000", + "key is an integer from the array nums .", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,9,1,3,9,5], key = 9, k = 1\nOutput:[1,2,3,4,5,6]\nExplanation:Here,nums[2] == keyandnums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no jwhere|0 - j| <= kandnums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.Thus, we return [1,2,3,4,5,6] which is sorted in increasing order.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], key = 2, k = 2\nOutput:[0,1,2,3,4]\nExplanation:For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n lis=deque([])\n prev_popped=-1\n for i in range(len(nums)):\n if(nums[i]==key):\n lis.append(i)\n ans=[]\n for i in range(len(nums)):\n if(len(lis)>0 and lis[0]0 and (lis[0]-i)<=k):\n ans.append(i)\n return ans\n", + "title": "2200. Find All K-Distant Indices in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . A number x is lonely when it appears only once , and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,6,5,8]\nOutput:[10,8]\nExplanation:- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,3]\nOutput:[1,5]\nExplanation:- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 100.00%) | Memory: 61.2 MB (Top 97.43%)\nclass Solution {\n public List findLonely(int[] nums) {\n Arrays.sort(nums);\n ArrayList list = new ArrayList<>();\n for (int i = 1; i < nums.length - 1; i++) {\n if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) {\n list.add(nums[i]);\n }\n }\n if (nums.length == 1) {\n list.add(nums[0]);\n }\n if (nums.length > 1) {\n if (nums[0] + 1 < nums[1]) {\n list.add(nums[0]);\n }\n if (nums[nums.length - 2] + 1 < nums[nums.length - 1]) {\n list.add(nums[nums.length - 1]);\n }\n }\n return list;\n }\n}", + "title": "2150. Find All Lonely Numbers in the Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . A number x is lonely when it appears only once , and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,6,5,8]\nOutput:[10,8]\nExplanation:- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,3]\nOutput:[1,5]\nExplanation:- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4306 ms (Top 5.12%) | Memory: 38.2 MB (Top 71.56%)\nclass Solution:\n def findLonely(self, nums: List[int]) -> List[int]:\n m = Counter(nums)\n return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]", + "title": "2150. Find All Lonely Numbers in the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n] , return an array of all the integers in the range [1, n] that do not appear in nums .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]\nOutput:[5,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 62.33%) | Memory: 67.5 MB (Top 39.21%)\nclass Solution {\n public List findDisappearedNumbers(int[] nums) {\n List res = new ArrayList<>();\n // 0 1 2 3 4 5 6 7 <- indx\n // 4 3 2 7 8 2 3 1 <- nums[i]\n for(int i=0;i0) {\n nums[indx] = nums[indx]*-1;\n }\n }\n // 0 1 2 3 4 5 6 7 <- indx\n // -4 -3 -2 -7 8 2 -3 -1 <- nums[i]\n for(int i=0;i0) {\n res.add(i+1);\n }else {\n nums[i] *= -1;\n }\n }\n // [ 5, 6]\n return res;\n }\n}", + "title": "448. Find All Numbers Disappeared in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n] , return an array of all the integers in the range [1, n] that do not appear in nums .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]\nOutput:[5,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n return set(nums) ^ set(range(1,len(nums)+1))\n", + "title": "448. Find All Numbers Disappeared in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\nOutput:[0,1,2,3,5]\nExplanation:At time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.​​​​\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\nOutput:[0,1,3]\nExplanation:At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\nOutput:[0,1,2,3,4]\nExplanation:At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 53.2%) | Memory: 108.54 MB (Top 41.1%)\n\nclass Solution {\n public List findAllPeople(int n, int[][] meetings, int firstPerson) {\n\t\n\t\t// create map\n Map> timeToIndexes = new TreeMap<>();\n int m = meetings.length;\n for (int i = 0; i < m; i++) {\n timeToIndexes.putIfAbsent(meetings[i][2], new ArrayList<>());\n timeToIndexes.get(meetings[i][2]).add(i);\n }\n\t\t\n UF uf = new UF(n);\n\t\t// base\n uf.union(0, firstPerson);\n\t\t\n\t\t// for every time we have a pool of people that talk to each other\n\t\t// if someone knows a secret proir to this meeting - all pool will too\n\t\t// if not - reset unions from this pool\n for (int time : timeToIndexes.keySet()) {\n Set pool = new HashSet<>();\n\t\t\t\n for (int ind : timeToIndexes.get(time)) {\n int[] currentMeeting = meetings[ind];\n uf.union(currentMeeting[0], currentMeeting[1]);\n pool.add(currentMeeting[0]);\n pool.add(currentMeeting[1]);\n }\n\t\t\t\n\t\t\t// meeting that took place now should't affect future\n\t\t\t// meetings if people don't know the secret\n for (int i : pool) if (!uf.connected(0, i)) uf.reset(i);\n }\n\t\t\n\t\t// if the person is conneted to 0 - they know a secret\n List ans = new ArrayList<>();\n for (int i = 0; i < n; i++) if (uf.connected(i,0)) ans.add(i);\n return ans;\n }\n \n\t// regular union find\n private static class UF {\n int[] parent, rank;\n\t\t\n public UF(int n) {\n parent = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n public void union(int p, int q) {\n int rootP = find(p);\n int rootQ = find(q);\n\n if (rootP == rootQ)\n return;\n\n if (rank[rootP] < rank[rootQ]) {\n parent[rootP] = rootQ;\n } else {\n parent[rootQ] = rootP;\n rank[rootP]++;\n }\n }\n \n public int find(int p) {\n while (parent[p] != p) {\n p = parent[parent[p]];\n }\n return p;\n }\n \n public boolean connected(int p, int q) {\n return find(p) == find(q);\n }\n \n public void reset(int p) {\n parent[p] = p;\n rank[p] = 0;\n }\n }\n}", + "title": "2092. Find All People With Secret", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\nOutput:[0,1,2,3,5]\nExplanation:At time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.​​​​\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\nOutput:[0,1,3]\nExplanation:At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\nOutput:[0,1,2,3,4]\nExplanation:At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6190 ms (Top 5.05%) | Memory: 57.3 MB (Top 48.67%)\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n\n class UnionFind:\n def __init__(self):\n self.parents = {}\n self.ranks = {}\n\n def insert(self, x):\n if x not in self.parents:\n self.parents[x] = x\n self.ranks[x] = 0\n\n def find_parent(self, x):\n if self.parents[x] != x:\n self.parents[x] = self.find_parent(self.parents[x])\n return self.parents[x]\n\n def union(self, x, y):\n self.insert(x)\n self.insert(y)\n x, y = self.find_parent(x), self.find_parent(y)\n if x == y:\n return\n if self.ranks[x] > self.ranks[y]:\n self.parents[y] = x\n else:\n self.parents[x] = y\n if self.ranks[x] == self.ranks[y]:\n self.ranks[y] += 1\n\n time2meets = defaultdict(list)\n for x, y, t in meetings:\n time2meets[t].append((x, y))\n time2meets = sorted(time2meets.items())\n\n curr_know = set([0, firstPerson])\n\n for time, meets in time2meets:\n uf = UnionFind()\n for x, y in meets:\n uf.union(x, y)\n\n groups = defaultdict(set)\n for idx in uf.parents:\n groups[uf.find_parent(idx)].add(idx)\n\n for group in groups.values():\n if group & curr_know:\n curr_know.update(group)\n\n return list(curr_know)", + "title": "2092. Find All People With Secret", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients . The i th recipe has the name recipes[i] , and you can create it if you have all the needed ingredients from ingredients[i] . Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes . You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order . Note that two recipes may contain each other in their ingredients.", + "description_images": [], + "constraints": [ + "n == recipes.length == ingredients.length", + "1 <= n <= 100", + "1 <= ingredients[i].length, supplies.length <= 100", + "1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10", + "recipes[i], ingredients[i][j] , and supplies[k] consist only of lowercase English letters.", + "All the values of recipes and supplies combined are unique.", + "Each ingredients[i] does not contain any duplicate values." + ], + "examples": [ + { + "text": "Example 1: Input:recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]\nOutput:[\"bread\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".", + "image": null + }, + { + "text": "Example 2: Input:recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput:[\"bread\",\"sandwich\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".", + "image": null + }, + { + "text": "Example 3: Input:recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput:[\"bread\",\"sandwich\",\"burger\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nWe can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 86.45%) | Memory: 46.50 MB (Top 57.39%)\n\nclass Solution {\n public List findAllRecipes(String[] recipes, List> ingredients, String[] supplies) {\n HashSet sup = new HashSet<>();\n HashMap index = new HashMap<>();\n HashMap> map = new HashMap<>();\n \n // create hashset of supplies\n for(String s: supplies) {\n sup.add(s);\n }\n \n // store index of all recipes\n for(int i = 0; i < recipes.length; i++) {\n index.put(recipes[i], i);\n }\n \n int[] indegree = new int[recipes.length];\n // create a mapping of all the recipes that are Ingredients as well\n // to the recipes they are ingredients for\n for(int i = 0; i < recipes.length; i++) {\n for(String need: ingredients.get(i)) {\n if(sup.contains(need))\n continue;\n \n map.putIfAbsent(need, new ArrayList());\n map.get(need).add(recipes[i]);\n indegree[i]++;\n }\n }\n \n LinkedList q = new LinkedList<>();\n // add all the recipes with indegree 0 to the queue\n for(int i = 0; i < recipes.length; i++) {\n if(indegree[i] == 0) {\n q.add(i);\n }\n }\n \n List cooked = new ArrayList<>();\n while(!q.isEmpty()) {\n int i = q.poll();\n cooked.add(recipes[i]);\n \n if(!map.containsKey(recipes[i])) {\n // if the map does not contain this recipe, this means\n // this recipe is not an ingredient for any other recipe\n // and no further processing is required\n continue;\n }\n \n for(String recipe: map.get(recipes[i])) {\n if(--indegree[index.get(recipe)] == 0) {\n q.add(index.get(recipe));\n }\n }\n }\n \n return cooked;\n }\n}\n", + "title": "2115. Find All Possible Recipes from Given Supplies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients . The i th recipe has the name recipes[i] , and you can create it if you have all the needed ingredients from ingredients[i] . Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes . You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order . Note that two recipes may contain each other in their ingredients.", + "description_images": [], + "constraints": [ + "n == recipes.length == ingredients.length", + "1 <= n <= 100", + "1 <= ingredients[i].length, supplies.length <= 100", + "1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10", + "recipes[i], ingredients[i][j] , and supplies[k] consist only of lowercase English letters.", + "All the values of recipes and supplies combined are unique.", + "Each ingredients[i] does not contain any duplicate values." + ], + "examples": [ + { + "text": "Example 1: Input:recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]\nOutput:[\"bread\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".", + "image": null + }, + { + "text": "Example 2: Input:recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput:[\"bread\",\"sandwich\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".", + "image": null + }, + { + "text": "Example 3: Input:recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput:[\"bread\",\"sandwich\",\"burger\"]\nExplanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nWe can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n\n\t\tgraph = defaultdict(list)\n\t\tin_degree = defaultdict(int)\n\t\tfor r,ing in zip(recipes,ingredients):\n\t\t\tfor i in ing:\n\t\t\t\tgraph[i].append(r)\n\t\t\t\tin_degree[r]+=1\n\n\t\tqueue = supplies[::]\n\t\tres = []\n\t\twhile queue:\n\t\t\ting = queue.pop(0)\n\t\t\tif ing in recipes:\n\t\t\t\tres.append(ing)\n\n\t\t\tfor child in graph[ing]:\n\t\t\t\tin_degree[child]-=1\n\t\t\t\tif in_degree[child]==0:\n\t\t\t\t\tqueue.append(child)\n\n\t\treturn res\n", + "title": "2115. Find All Possible Recipes from Given Supplies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices , sources , and targets , all of length k . To complete the i th replacement operation: For example, if s = \" ab cd\" , indices[i] = 0 , sources[i] = \"ab\" , and targets[i] = \"eee\" , then the result of this replacement will be \" eee cd\" . All replacement operations must occur simultaneously , meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap . Return the resulting string after performing all replacement operations on s . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, a testcase with s = \"abc\" , indices = [0, 1] , and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput:\"eeebffff\"\nExplanation:\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex1.png" + }, + { + "text": "Example 2: Input:s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput:\"eeecd\"\nExplanation:\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {\n \n HashMap subst = new HashMap<>();\n HashMap tgt = new HashMap<>();\n \n for(int i = 0; i< indices.length; i++) {\n subst.put(indices[i], sources[i]);\n tgt.put(indices[i],targets[i]);\n }\n \n Arrays.sort(indices);\n \n String res = \"\";\n int count = 0;\n int avail[] = new int[indices.length];\n for(int i = 0; i< s.length(); i++) {\n if(count < indices.length && i == indices[count] && s.indexOf(subst.get(indices[count]), indices[count]) == indices[count]){\n res = res+\"\"+tgt.get(indices[count]);\n i = i+ subst.get(indices[count]).length()-1;\n count++;\n } else {\n if(count < indices.length && i == indices[count])\n count++;\n res+= s.charAt(i);\n }\n }\n \n return res;\n }\n}\n", + "title": "833. Find And Replace in String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices , sources , and targets , all of length k . To complete the i th replacement operation: For example, if s = \" ab cd\" , indices[i] = 0 , sources[i] = \"ab\" , and targets[i] = \"eee\" , then the result of this replacement will be \" eee cd\" . All replacement operations must occur simultaneously , meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap . Return the resulting string after performing all replacement operations on s . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, a testcase with s = \"abc\" , indices = [0, 1] , and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput:\"eeebffff\"\nExplanation:\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex1.png" + }, + { + "text": "Example 2: Input:s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput:\"eeecd\"\nExplanation:\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n \n inputs = list(zip(indices,sources,targets))\n inputs.sort(key = lambda x: x[0])\n \n offset = 0\n for idx, src, tgt in inputs:\n idx += offset\n if s[idx:idx + len(src)] != src:\n print('hi')\n print(idx)\n continue\n \n offset += len(tgt) - len(src)\n s = s[:idx] + tgt + s[idx+len(src):]\n \n return s\n", + "title": "833. Find And Replace in String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of strings words and a string pattern , return a list of words[i] that match pattern . You may return the answer in any order . A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x) , we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.", + "description_images": [], + "constraints": [ + "1 <= pattern.length <= 20", + "1 <= words.length <= 50", + "words[i].length == pattern.length", + "pattern and words[i] are lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\nOutput:[\"mee\",\"aqq\"]\nExplanation:\"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findAndReplacePattern(String[] words, String pattern) {\n List result=new ArrayList<>();\n for(String word:words) {\n Map map=new HashMap<>();\n Set set=new HashSet<>();\n int i=0;\n for(;i m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 36.0%) | Memory: 16.40 MB (Top 44.2%)\n\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n d={}\n for i,v in enumerate(pattern):\n if v in d:\n d[v].append(i)\n else:\n d|={v:[i]}\n #DICTIONARY CONTAINING LETTERS AND THEIR INDICES\n ans=[]\n for i in words:\n e={}\n for j,v in enumerate(i):\n if v in e:\n e[v].append(j)\n else:\n e|={v:[j]}\n #DICTIONARY CONTAINING LETTERS OF INDICES OF CURRENT WORD\n for u,v in zip(d.values(),e.values()):\n #COMPARING EACH VALUE\n if u!=v:\n break\n #IF SUCCESSFUL APPEND TO ANS\n else:ans.append(i)\n return ans", + "title": "890. Find and Replace Pattern", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2 n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them . An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr . The sum of the elements in sub is one possible subset sum of arr . The sum of an empty array is considered to be 0 . Note: Test cases are generated such that there will always be at least one correct answer.", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "sums.length == 2 n", + "-10^4 <= sums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput:[1,2,-3]\nExplanation:[1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, sums = [0,0,0,0]\nOutput:[0,0]\nExplanation:The only correct answer is [0,0].", + "image": null + }, + { + "text": "Example 3: Input:n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput:[0,-1,4,5]\nExplanation:[0,-1,4,5] is able to achieve the given subset sums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 73 ms (Top 62.96%) | Memory: 85.2 MB (Top 70.37%)\nclass Solution {\n public int[] recoverArray(int n, int[] sums) {\n Arrays.sort(sums);\n int m = sums.length;\n int[] res = new int[n], left = new int[m / 2], right = new int[m / 2];\n for (int i = 0; i < n; ++i) {\n int diff = sums[1] - sums[0], hasZero = 0, p = -1, q = -1, k = 0;\n for (int j = 0; j < m; ++j) {\n if (k <= q && right[k] == sums[j]) k++;\n else {\n if (0 == sums[j]) hasZero = 1;\n left[++p] = sums[j];\n right[++q] = sums[j] + diff;\n }\n }\n if (1 == hasZero) {\n res[i] = diff;\n sums = left;\n } else {\n res[i] = -diff;\n sums = right;\n }\n m /= 2;\n }\n return res;\n }\n}", + "title": "1982. Find Array Given Subset Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2 n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them . An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr . The sum of the elements in sub is one possible subset sum of arr . The sum of an empty array is considered to be 0 . Note: Test cases are generated such that there will always be at least one correct answer.", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "sums.length == 2 n", + "-10^4 <= sums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput:[1,2,-3]\nExplanation:[1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, sums = [0,0,0,0]\nOutput:[0,0]\nExplanation:The only correct answer is [0,0].", + "image": null + }, + { + "text": "Example 3: Input:n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput:[0,-1,4,5]\nExplanation:[0,-1,4,5] is able to achieve the given subset sums.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4011 ms (Top 18.39%) | Memory: 19.7 MB (Top 40.23%)\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n res = [] # Result set\n sums.sort()\n\n while len(sums) > 1:\n num = sums[-1] - sums[-2] # max - secondMax\n countMap = Counter(sums) # Get count of each elements\n excluding = [] # Subset sums that do NOT contain num\n including = [] # Subset sums that contain num\n\n for x in sums:\n if countMap.get(x) > 0:\n excluding.append(x)\n including.append(x+num)\n countMap[x] -= 1\n countMap[x+num] -= 1\n\n # Check validity of excluding set\n if 0 in excluding:\n sums = excluding\n res.append(num)\n else:\n sums = including\n res.append(-1*num)\n\n return res", + "title": "1982. Find Array Given Subset Sums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,null,5,6,null,null,7]\nOutput:7", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int max = Integer.MIN_VALUE;\n int res = -1;\n public int findBottomLeftValue(TreeNode root) {\n check(root,0);\n return res;\n }\n void check(TreeNode root, int h){\n if(root==null)\n return;\n if(h>max){\n max=h;\n res = root.val;\n }\n check(root.left,h+1);\n check(root.right,h+1);\n }\n}", + "title": "513. Find Bottom Left Tree Value", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,null,5,6,null,null,7]\nOutput:7", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n \n res = root.val\n stack = [(0, root)]\n prev_d = 0\n \n while stack:\n \n curr_d, curr_v = stack.pop(0)\n \n if curr_v.left:\n stack.append((curr_d+1, curr_v.left))\n if prev_d != curr_d + 1:\n res = curr_v.left.val\n prev_d = curr_d+1\n \n if curr_v.right:\n stack.append((curr_d+1, curr_v.right))\n if prev_d != curr_d + 1:\n res = curr_v.right.val\n prev_d = curr_d+1\n \n return res\n\t\t\n\t\t# An Upvote will be encouraging\n", + "title": "513. Find Bottom Left Tree Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected star graph consisting of n nodes labeled from 1 to n . A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [u i , v i ] indicates that there is an edge between the nodes u i and v i . Return the center of the given star graph.", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= u i, v i <= n", + "u i != v i", + "The given edges represent a valid star graph." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[2,3],[4,2]]\nOutput:2\nExplanation:As shown in the figure above, node 2 is connected to every other node, so 2 is the center.", + "image": "https://assets.leetcode.com/uploads/2021/02/24/star_graph.png" + }, + { + "text": "Example 2: Input:edges = [[1,2],[5,1],[1,3],[1,4]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n \n \"\"\" From the Constraints: A valid STAR GRAPH is confirmed. \n\t\tThat means the center will be common to every edges. \n\t\tTherefore we can get the center by comparing only first 2 elements\"\"\"\n \n for i in range (1):\n \n # Check if first element of first edge mathches with any element of second edges\n \n if edges[i][0] == edges [i+1][0] or edges[i][0] == edges[i+1][1]:\n return edges[i][0]\n \n #Otherwise second element of first edge will be the answer\n else:\n return edges[i][1]\n", + "title": "1791. Find Center of Star Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from i , then edges[i] == -1 . You are also given two integers node1 and node2 . Return the index of the node that can be reached from both node1 and node2 , such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized . If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1 . Note that edges may contain cycles.", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i", + "0 <= node1, node2 < n" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [2,2,3,-1], node1 = 0, node2 = 1\nOutput:2\nExplanation:The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\nThe maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-2.png" + }, + { + "text": "Example 2: Input:edges = [1,2,-1], node1 = 0, node2 = 2\nOutput:2\nExplanation:The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\nThe maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-4.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3032 ms (Top 5.02%) | Memory: 139.1 MB (Top 14.52%)\nclass Solution:\n def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:\n\n res = float(\"inf\")\n\n def dfs(node, arr, counter=0):\n\n #making sure we haven't visited the node before (i.e., value in the array != -1)\n while arr[node]==-1 and node!=-1:\n\n #assigning how many moves it takes to reach node\n arr[node] = counter\n next_node = edges[node]\n\n #going through each neighbor if exists and updating the counter\n dfs(edges[node], arr, counter+1)\n\n return arr\n\n #find moves to reach nodes from node1\n n1 = [-1 for i in range(len(edges))]\n dfs(node1, n1)\n\n #find moves to reach nodes from node2\n n2 = [-1 for i in range(len(edges))]\n dfs(node2, n2)\n\n answer = -1\n\n for i in range(len(edges)):\n\n #check if the end node is reachable from both starting nodes\n if n1[i]!=-1 and n2[i]!=-1:\n maximum_distance = max(n1[i], n2[i])\n\n #update the distance and the final answer if relevant\n if maximum_distance int:\n return min(nums, key=lambda x: (abs(x), -x))\n \n def findClosestNumber2(self, nums: List[int]) -> int:\n return min(nums, key=lambda x: abs(x - .1))\n \n def findClosestNumber3(self, nums: List[int]) -> int:\n return max((-abs(x), x) for x in nums)[1]\n \n def findClosestNumber4(self, nums: List[int]) -> int:\n return -min(zip(map(abs, nums), map(neg, nums)))[1]\n\n def findClosestNumber5(self, nums: List[int]) -> int:\n a = min(map(abs, nums))\n return a if a in nums else -a\n\n def findClosestNumber6(self, nums: List[int]) -> int:\n a = abs(min(nums, key=abs))\n return a if a in nums else -a\n\n def findClosestNumber7(self, nums: List[int]) -> int:\n x = min(nums, key=abs)\n return x if x >= 0 or -x not in nums else -x\n \n def findClosestNumber8(self, nums: List[int]) -> int:\n return min(sorted(nums, reverse=True), key=abs)\n \n def findClosestNumber9(self, nums: List[int]) -> int: \n a = abs(nums[0])\n for x in nums:\n if x < 0:\n x = -x\n if x < a:\n a = x\n return a if a in nums else -a\n \n def findClosestNumberA(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < 0:\n if x > neg:\n neg = x\n elif x < pos:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberB(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < pos and neg < x:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberC(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x and x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberD(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumber(self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]) -> int:\n name = 'findClosestNumber'\n solutions = [getattr(self, s)\n for s in dir(self)\n if s.startswith(name)\n and s != name]\n expect = dummy = object()\n from time import perf_counter as time\n for i in range(10):\n shuffle(solutions)\n for solution in solutions:\n start = time()\n result = solution(nums)\n end = time()\n if expect is dummy:\n expect = result\n assert result == expect\n timess[solution.__name__][i] += end - start\n testcase[0] += 1\n if testcase[0] == 224:\n for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):\n print(name, *(f'{t*1e3:6.2f} ms' for t in sorted(times)[:3]))\n return\n return result\n\t\t\n", + "title": "2239. Find Closest Number to Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string array words , return an array of all characters that show up in all strings within the words (including duplicates) . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"bella\",\"label\",\"roller\"]\nOutput:[\"e\",\"l\",\"l\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cool\",\"lock\",\"cook\"]\nOutput:[\"c\",\"o\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 42.12%) | Memory: 14.3 MB (Top 6.17%)\nclass Solution:\n def _get_char_counts(self, s: str) -> dict[str]:\n \"\"\"builds a dict of letters : count\"\"\"\n d = {}\n for i in s:\n d[i] = d.get(i,0)+1\n return d\n\n def commonChars(self, words: list[str]) -> list[str]:\n \"\"\"returns a string of letters common between a list of words (including duplicates)\"\"\"\n if not words:\n return\n\n # O(n^2)\n words = [self._get_char_counts(word) for word in words]\n\n # O(nm), set intersection\n common = words[0].keys()\n for other in words[1:]:\n common &= other.keys()\n\n # O(nm), number of common characters across the number of words\n result = []\n for c in common:\n result += [c] * min(count[c] for count in words)\n\n return result", + "title": "1002. Find Common Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1 , and an array edges where edges[i] = [a i , b i , weight i ] represents a bidirectional and weighted edge between nodes a i and b i . A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST) . An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge . On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/06/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/06/04/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= min(200, n * (n - 1) / 2)", + "edges[i].length == 3", + "0 <= a i < b i < n", + "1 <= weight i <= 1000", + "All pairs (a i , b i ) are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput:[[0,1],[2,3,4,5]]\nExplanation:The figure above describes the graph.\nThe following figure shows all the possible MSTs:Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput:[[],[0,1,2,3]]\nExplanation:We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static class UnionFind{\n int[]parent;\n int[]rank;\n int comp = 0;\n UnionFind(int n){\n parent = new int[n];\n rank = new int[n];\n comp = n;\n for(int i=0;i{\n int u;\n int v;\n int wt;\n Edge(int u,int v,int wt){\n this.u = u;\n this.v = v;\n this.wt = wt;\n }\n public int compareTo(Edge o){\n return this.wt - o.wt;\n } \n }\n public int buildMST(int n,int[][]edges,int[]edgeSkip,int[]edgePick){\n PriorityQueue pq = new PriorityQueue<>();\n \n for(int[]edge : edges){\n if(edge == edgeSkip){\n continue;\n }else if(edge == edgePick){\n continue;\n }\n int u = edge[0];\n int v = edge[1];\n int wt = edge[2];\n pq.add(new Edge(u,v,wt));\n }\n \n UnionFind uf = new UnionFind(n);\n int cost = 0;\n \n if(edgePick != null){\n uf.union(edgePick[0],edgePick[1]);\n cost += edgePick[2];\n }\n while(pq.size() > 0){\n Edge rem = pq.remove();\n if(uf.union(rem.u,rem.v) == true){\n cost += rem.wt;\n }\n }\n \n if(uf.isConnected() == true){\n return cost;\n }else{\n return Integer.MAX_VALUE;\n }\n }\n \n public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n int mstCost = buildMST(n,edges,null,null);\n \n ArrayList critical = new ArrayList<>();\n ArrayList pcritical = new ArrayList<>();\n \n for(int i=0;i mstCost){\n critical.add(i); //Critical edge index\n }else{\n int mstCostWithEdge = buildMST(n,edges,null,edge);\n if(mstCostWithEdge > mstCost){\n //redundant\n }else{\n pcritical.add(i); //pseduo critical edge index\n }\n }\n }\n \n List> res = new ArrayList<>();\n res.add(critical);\n res.add(pcritical);\n return res;\n }\n}\n\n\n", + "title": "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1 , and an array edges where edges[i] = [a i , b i , weight i ] represents a bidirectional and weighted edge between nodes a i and b i . A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST) . An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge . On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/06/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/06/04/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= min(200, n * (n - 1) / 2)", + "edges[i].length == 3", + "0 <= a i < b i < n", + "1 <= weight i <= 1000", + "All pairs (a i , b i ) are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput:[[0,1],[2,3,4,5]]\nExplanation:The figure above describes the graph.\nThe following figure shows all the possible MSTs:Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput:[[],[0,1,2,3]]\nExplanation:We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n def find(v, parent):\n if parent[v] != v:\n parent[v] = find(parent[v], parent)\n return parent[v]\n def union(u,v, parent):\n parent[find(u,parent)] = find(v,parent)\n edges = [(u,v,w,i) for i, (u,v,w) in enumerate(edges)]\n edges.sort(key = lambda e:e[2])\n def find_mst_without_this_edge(idx):\n parent = list(range(n))\n res = 0\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx: continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n def find_mst_with_this_edge(idx):\n parent = list(range(n))\n u0, v0, w0, _ = edges[idx]\n res = w0\n union(u0,v0,parent)\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx:\n continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n base_mst_wgt = find_mst_without_this_edge(-1)\n cri, pcri = set(), set()\n for i in range(len(edges)):\n wgt_excl = find_mst_without_this_edge(i)\n if wgt_excl > base_mst_wgt:\n cri.add(edges[i][3])\n else:\n wgt_incl = find_mst_with_this_edge(i)\n if wgt_incl == base_mst_wgt:\n pcri.add(edges[i][3])\n return [cri, pcri]\n", + "title": "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths . You may return the answer in any order . A group of duplicate files consists of at least two files that have the same content. A single directory info string in the input list has the following format: It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory \" root/d1/d2/.../dm\" . Note that n >= 1 and m >= 0 . If m = 0 , it means the directory is just the root directory. The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:", + "description_images": [], + "constraints": [ + "\"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)\"" + ], + "examples": [ + { + "text": "Example 1: Input:paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\nOutput:[[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]", + "image": null + }, + { + "text": "Example 2: Input:paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\nOutput:[[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n vector> findDuplicate(vector& paths) {\n vector> vec1;\n for(int i = 0; i < paths.size(); ++i){\n vector level;\n string temp1 = paths[i];\n string temp2 = \"\";\n for(int j = 0; j < temp1.length(); ++j){\n if(temp1[j] == ' '){\n level.push_back(temp2);\n temp2 = \"\";\n }\n else\n temp2 += temp1[j];\n if(j == temp1.length() - 1)\n level.push_back(temp2);\n }\n vec1.push_back(level);\n }\n unordered_map> ump;\n for(int i = 0; i < vec1.size(); ++i){\n string rootDir = vec1[i][0];\n for(int j = 1; j < vec1[i].size(); ++j){\n string str1 = rootDir, str2 = \"\";\n int pos = -1;\n for(int k = 0; k < vec1[i][j].length(); ++k){\n if(vec1[i][j][k] == '('){\n pos = k;\n break;\n }\n }\n str1 += '/';\n for(int k = 0; k < pos; ++k)\n str1 += vec1[i][j][k];\n str2 = vec1[i][j].substr(pos);\n ump[str2].push_back(str1);\n }\n }\n vector> res;\n for(auto it = ump.begin(); it != ump.end(); ++it)\n if(it->second.size() > 1)\n res.push_back(it->second);\n return res;\n }\n};\n", + "title": "609. Find Duplicate File in System", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return all duplicate subtrees . For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values .", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree will be in the range [1, 10^4]", + "-200 <= Node.val <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,null,2,4,null,null,4]\nOutput:[[2,4],[4]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e1.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,1]\nOutput:[[1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e2.jpg" + }, + { + "text": "Example 3: Input:root = [2,2,2,3,null,3,null]\nOutput:[[2,3],[3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e33.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1783 ms (Top 5.02%) | Memory: 64.5 MB (Top 11.80%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List findDuplicateSubtrees(TreeNode root) {\n List list = new ArrayList();\n HashSet hashes = new HashSet();\n HashSet added = new HashSet();\n\n // for each node, perform a dfs traversal and generate a hash\n // check if the hash already exists in a set,\n // if it does, get the treenode and add it to the list\n Stack s = new Stack();\n\n s.add(root);\n while(!s.isEmpty()){\n TreeNode tmp = s.pop();\n dfs(tmp, \"\", tmp, list, hashes, added);\n\n if(tmp.left != null){\n s.add(tmp.left);\n }\n if(tmp.right != null){\n s.add(tmp.right);\n }\n }\n\n return list;\n\n }\n\n public void dfs(TreeNode parent, String hash, TreeNode root, List list, HashSet set, HashSet added){\n\n Stack stack = new Stack();\n\n stack.add(root);\n //String hash = \"\";\n hash += root.val + \"ROOT,\";\n while(!stack.isEmpty()){\n TreeNode tmp = stack.pop();\n //hash += tmp.val + \",\";\n\n if(tmp.left != null){\n hash += tmp.left.val + \"L,\";\n stack.add(tmp.left);\n }\n else{\n hash+= \"NULLL,\";\n }\n if(tmp.right != null){\n hash += tmp.right.val + \"R,\";\n stack.add(tmp.right);\n }\n else{\n hash+=\"NULLR,\";\n }\n if(tmp.left == null && tmp.right == null && stack.isEmpty()){\n if(set.contains(hash)){\n if(!added.contains(hash)){\n list.add(parent);\n added.add(hash);\n }\n }\n else{\n set.add(hash);\n }\n return;\n }\n\n }\n }\n}", + "title": "652. Find Duplicate Subtrees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return all duplicate subtrees . For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values .", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree will be in the range [1, 10^4]", + "-200 <= Node.val <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,null,2,4,null,null,4]\nOutput:[[2,4],[4]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e1.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,1]\nOutput:[[1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e2.jpg" + }, + { + "text": "Example 3: Input:root = [2,2,2,3,null,3,null]\nOutput:[[2,3],[3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e33.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n ans = []\n path_map = {}\n \n def dfs(node):\n if not node:\n return \"#\"\n \n path = \",\".join([str(node.val), dfs(node.left), dfs(node.right)])\n \n if path in path_map:\n path_map[path] += 1\n if path_map[path] == 2:\n ans.append(node)\n else:\n path_map[path] = 1\n \n return path\n \n \n dfs(root)\n return ans\n", + "title": "652. Find Duplicate Subtrees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1 . Implement the FindElements class:", + "description_images": [], + "constraints": [ + "FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.", + "bool find(int target) Returns true if the target value exists in the recovered binary tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]Output[null,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg" + }, + { + "text": "Example 2: Input[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]Output[null,true,true,false]ExplanationFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg" + }, + { + "text": "Example 3: Input[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]Output[null,true,false,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 75.56%) | Memory: 52.2 MB (Top 77.99%)\nclass FindElements {\n TreeNode tree,nodept;\n public FindElements(TreeNode root) {\n tree=root;\n tree.val=0;\n go(tree);\n }\n\n void go(TreeNode node){\n if(node.left!=null){\n node.left.val=node.val*2+1;\n go(node.left);\n }\n if(node.right!=null){\n node.right.val=node.val*2+2;\n go(node.right);\n }\n }\n\n public boolean find(int target) {\n return doit(target);\n }\n\n boolean doit(int target){\n if(target==0){\n nodept=tree;\n return true;\n }\n boolean f=doit((target-1)/2);\n if(!f)return false;\n if(nodept.left!=null && nodept.left.val==target)\n nodept=nodept.left;\n else if(nodept.right!=null && nodept.right.val==target)\n nodept=nodept.right;\n else f=false;\n return f;\n }\n}", + "title": "1261. Find Elements in a Contaminated Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1 . Implement the FindElements class:", + "description_images": [], + "constraints": [ + "FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.", + "bool find(int target) Returns true if the target value exists in the recovered binary tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]Output[null,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg" + }, + { + "text": "Example 2: Input[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]Output[null,true,true,false]ExplanationFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg" + }, + { + "text": "Example 3: Input[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]Output[null,true,false,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 227 ms (Top 13.41%) | Memory: 18.1 MB (Top 62.12%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass FindElements:\n\n def __init__(self, root: Optional[TreeNode]):\n def recoverTree(root):\n if not root:\n return None\n self.vals.add(root.val)\n if root.left:\n root.left.val = 2 * root.val + 1\n recoverTree(root.left)\n if root.right:\n root.right.val = 2 * root.val + 2\n recoverTree(root.right)\n self.vals = set()\n root.val = 0\n recoverTree(root)\n\n def find(self, target: int) -> bool:\n return target in self.vals\n\n# Your FindElements object will be instantiated and called as such:\n# obj = FindElements(root)\n# param_1 = obj.find(target)", + "title": "1261. Find Elements in a Contaminated Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput:[2,4,5,6]\nExplanation:The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png" + }, + { + "text": "Example 2: Input:graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput:[4]\nExplanation:Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 80.80%) | Memory: 65.9 MB (Top 65.16%)\n\nclass Solution {\n public List eventualSafeNodes(int[][] graph) {\n int n=graph.length;\n List ans=new ArrayList<>();\n\n boolean visited[]=new boolean[n];\n boolean dfsVisited[]=new boolean[n];\n\n boolean nodeCycles[]=new boolean[n];\n\n for(int i=0;i list[int]:\n\n n = len(graph)\n ans = []\n \n for i in range(n):\n if not graph[i]:\n ans.append(i)\n \n def loop(key, loops):\n \n loops.append(key)\n for i in graph[key]:\n if i in loops:\n return False\n elif i in ans: \n continue\n else:\n r = loop(i, loops)\n if r == True: \n continue\n else: \n return False\n\n idx = loops.index(key)\n loops.pop(idx)\n return True\n \n for i in range(n):\n loops = []\n if i in ans:\n continue\n r = loop(i, loops)\n if r == True: ans.append(i)\n \n return sorted(ans)\n", + "title": "802. Find Eventual Safe States", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8\nOutput:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6\nOutput:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0\nOutput:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 22.02%) | Memory: 45.50 MB (Top 10.41%)\n\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = -1, last = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i;\n }\n last = i;\n }\n }\n return new int[]{first, last};\n }\n}\n\n", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8\nOutput:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6\nOutput:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0\nOutput:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n # if target is not in nums list, we simply return [-1,-1]\n\t\tif target not in nums:\n return [-1,-1]\n \n\t\t# create an empty list\n result = []\n\t\t# iterate nums for the first time, if we found nums[i] matches with target\n\t\t# append the index i to result, break the for loop\n\t\t# because we only care the first and last index of target in nums\n for i in range(len(nums)):\n if nums[i] == target:\n result.append(i)\n break\n \n\t\t# loop through nums backward, if we found nums[j] matches target\n\t\t# append j to result and break the for loop\n for j in range(len(nums)-1, -1, -1):\n if nums[j] == target:\n result.append(j)\n break\n \n return result\n\t\t\n\t\t\n", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words , return the first palindromic string in the array . If there is no such string, return an empty string \"\" . A string is palindromic if it reads the same forward and backward.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]\nOutput:\"ada\"\nExplanation:The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"notapalindrome\",\"racecar\"]\nOutput:\"racecar\"\nExplanation:The first and only string that is palindromic is \"racecar\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"def\",\"ghi\"]\nOutput:\"\"\nExplanation:There are no palindromic strings, so the empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String firstPalindrome(String[] words) {\n for (String s : words) {\n StringBuilder sb = new StringBuilder(s);\n if (s.equals(sb.reverse().toString())) {\n return s;\n }\n }\n return \"\";\n }\n}", + "title": "2108. Find First Palindromic String in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words , return the first palindromic string in the array . If there is no such string, return an empty string \"\" . A string is palindromic if it reads the same forward and backward.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]\nOutput:\"ada\"\nExplanation:The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"notapalindrome\",\"racecar\"]\nOutput:\"racecar\"\nExplanation:The first and only string that is palindromic is \"racecar\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"def\",\"ghi\"]\nOutput:\"\"\nExplanation:There are no palindromic strings, so the empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def firstPalindrome(self, words):\n for word in words:\n if word == word[::-1]: return word\n return \"\"\n", + "title": "2108. Find First Palindromic String in the Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter.", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2\nOutput:[2,3]\nExplanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0\nOutput:[0,1,2,3,4]\nExplanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2\nOutput:[]\nExplanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 6.78%) | Memory: 59.90 MB (Top 5.93%)\n\nclass Solution {\n public List goodDaysToRobBank(int[] security, int time) {\n List res = new ArrayList<>();\n if (time == 0) {\n for (int i = 0; i < security.length; i++) res.add(i);\n return res;\n }\n Set set = new HashSet<>();\n int count = 1;\n for (int i = 1; i < security.length; i++) {\n if (security[i] <= security[i - 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time) {\n set.add(i);\n }\n }\n \n count = 1;\n for (int i = security.length - 2; i >= 0; i--) {\n if (security[i] <= security[i + 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time && set.contains(i)) res.add(i);\n }\n return res;\n }\n}\n", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter.", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2\nOutput:[2,3]\nExplanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0\nOutput:[0,1,2,3,4]\nExplanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2\nOutput:[]\nExplanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List goodDaysToRobBank(int[] security, int time) {\n int[] nonincrease = new int[security.length];\n for(int i = 1; i < security.length - time; i++){\n if(security[i]>security[i-1]){\n nonincrease[i] = 0;\n } else {\n nonincrease[i] = nonincrease[i-1] + 1;\n }\n }\n\n int[] nondecrease = new int[security.length];\n for(int i = security.length - 2; i >= time; i--) {\n if(security[i] > security[i + 1]){\n nondecrease[i] = 0;\n } else {\n nondecrease[i] = nondecrease[i + 1] + 1;\n }\n }\n\n ArrayList result = new ArrayList<>();\n for(int i = time; i < security.length - time; i++) {\n if(nonincrease[i] >= time && nondecrease[i] >= time) {\n result.add(i);\n }\n }\n return result;\n\n }\n", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter.", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2\nOutput:[2,3]\nExplanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0\nOutput:[0,1,2,3,4]\nExplanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2\nOutput:[]\nExplanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n decreasing = [0] * len(security)\n increasing = [0] * len(security)\n for i in range(len(security)):\n if i > 0 and security[i - 1] >= security[i]:\n decreasing[i] = decreasing[i - 1] + 1\n for i in reversed(range(len(security))):\n if i < len(security) - 1 and security[i] <= security[i + 1]:\n increasing[i] = increasing[i + 1] + 1\n return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time]", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the greatest common divisor of the smallest number and largest number in nums . The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,9,10]\nOutput:2\nExplanation:The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,5,6,8,3]\nOutput:1\nExplanation:The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3]\nOutput:3\nExplanation:The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 25.8%) | Memory: 42.56 MB (Top 95.7%)\n\nclass Solution {\n public int findGCD(int[] nums) {\n Arrays.sort(nums);\n int n=nums[nums.length-1];\n int result=nums[0];\n while(result>0){\n if(nums[0]%result==0 && n%result==0){\n break;\n }\n result--;\n }\n return result;\n }\n}", + "title": "1979. Find Greatest Common Divisor of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the greatest common divisor of the smallest number and largest number in nums . The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,9,10]\nOutput:2\nExplanation:The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,5,6,8,3]\nOutput:1\nExplanation:The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3]\nOutput:3\nExplanation:The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 282 ms (Top 5.10%) | Memory: 13.9 MB (Top 81.34%)\nclass Solution:\n def findGCD(self, nums: List[int]) -> int:\n i_min = min(nums)\n i_max = max(nums)\n greater = i_max\n while True:\n if greater % i_min == 0 and greater % i_max == 0:\n lcm = greater\n break\n greater += 1\n return int(i_min/(lcm/i_max))", + "title": "1979. Find Greatest Common Divisor of Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination . Given edges and the integers n , source , and destination , return true if there is a valid path from source to destination , or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= u i , v i <= n - 1", + "u i != v i", + "0 <= source, destination <= n - 1", + "There are no duplicate edges.", + "There are no self edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2\nOutput:true\nExplanation:There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2", + "image": "https://assets.leetcode.com/uploads/2021/08/14/validpath-ex1.png" + }, + { + "text": "Example 2: Input:n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\nOutput:false\nExplanation:There is no path from vertex 0 to vertex 5.", + "image": "https://assets.leetcode.com/uploads/2021/08/14/validpath-ex2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1647 ms (Top 68.5%) | Memory: 108.91 MB (Top 50.2%)\n\nclass Solution(object):\n def validPath(self, n, edges, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n visited = [False]*n\n d = {}\n\t\t#store the undirected edges for both vertices\n for i in edges:\n if i[0] in d:\n d[i[0]].append(i[1])\n else:\n d[i[0]] = [i[1]]\n \n if i[1] in d:\n d[i[1]].append(i[0])\n else:\n d[i[1]] = [i[0]]\n #create a queue as we will apply BFS\n q = [start]\n while q:\n curr = q.pop(0) #pop the first element as we do in queue\n if curr == end: #if its the end then we can return True\n return True\n elif curr in d and not visited[curr]: #else if it is not the end then check whether its visited or not\n q.extend(d[curr]) #add the adjacent vertices of the current node to the queue\n visited[curr] = True #mark this curr vertex as visited = True, so that we dont visit this vertex again\n return False #return False if the queue gets empty and we dont reach the end", + "title": "1971. Find if Path Exists in Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "(This problem is an interactive problem .) You may recall that an array arr is a mountain array if and only if: Given a mountain array mountainArr , return the minimum index such that mountainArr.get(index) == target . If such an index does not exist, return -1 . You cannot access the mountain array directly. You may only access the array using a MountainArray interface: Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer . Also, any solutions that attempt to circumvent the judge will result in disqualification.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:array = [1,2,3,4,5,3,1], target = 3\nOutput:2\nExplanation:3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.", + "image": null + }, + { + "text": "Example 2: Input:array = [0,1,2,4,2,1], target = 3\nOutput:-1\nExplanation:3 does not exist inthe array,so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findInMountainArray(int target, MountainArray mountainArr) {\n int peak = findPeak(mountainArr);\n \n int left =binary(0,peak,mountainArr,target,true);\n if(left!=-1){\n return left;\n }\n int right= binary(peak+1,mountainArr.length()-1,mountainArr, target,false);\n return right; \n }\n \n static int findPeak(MountainArray mountainArr){\n int start=0;\n int end =mountainArr.length()-1;\n \n while(startarr.get(mid)){\n if(left){\n low=mid+1;\n }else{\n high=mid-1; \n } \n }else{\n return mid;\n }\n } \n return -1;\n }\n}\n", + "title": "1095. Find in Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "(This problem is an interactive problem .) You may recall that an array arr is a mountain array if and only if: Given a mountain array mountainArr , return the minimum index such that mountainArr.get(index) == target . If such an index does not exist, return -1 . You cannot access the mountain array directly. You may only access the array using a MountainArray interface: Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer . Also, any solutions that attempt to circumvent the judge will result in disqualification.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:array = [1,2,3,4,5,3,1], target = 3\nOutput:2\nExplanation:3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.", + "image": null + }, + { + "text": "Example 2: Input:array = [0,1,2,4,2,1], target = 3\nOutput:-1\nExplanation:3 does not exist inthe array,so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:\n min_index = -1\n peak = self.findpeak(mountain_arr)\n \n min_index = self.binary_search(0, peak, mountain_arr, target, 1)\n if min_index == -1:\n min_index = self.binary_search(peak+1, mountain_arr.length() - 1, mountain_arr, target, -1)\n return min_index\n\n def findpeak(self, mountain_arr):\n start = 0\n end = mountain_arr.length() - 1\n while start < end:\n mid = start + int((end - start)/2)\n if mountain_arr.get(mid) < mountain_arr.get(mid + 1):\n start = mid + 1\n else:\n end = mid\n \n return start\n \n def binary_search(self, start, end, mountain_arr, target, asc):\n while start <= end:\n mid = start + int((end - start)/2)\n mountain_arr_get_mid = mountain_arr.get(mid)\n if target == mountain_arr_get_mid:\n return mid\n if asc == 1:\n if target < mountain_arr_get_mid:\n end = mid - 1\n elif target > mountain_arr_get_mid:\n start = mid + 1\n else:\n if target < mountain_arr_get_mid:\n start = mid + 1\n elif target > mountain_arr_get_mid:\n end = mid - 1\n \n return -1\n\n\n\n\n\n\n", + "title": "1095. Find in Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted integer array arr , two integers k and x , return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if:", + "description_images": [], + "constraints": [ + "|a - x| < |b - x| , or", + "|a - x| == |b - x| and a < b" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 4, x = 3\nOutput:[1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5], k = 4, x = -1\nOutput:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 41.96%) | Memory: 62.2 MB (Top 71.32%)\nclass Solution {\npublic List findClosestElements(int[] arr, int k, int x) {\n List result = new ArrayList<>();\n\n int low = 0, high = arr.length -1;\n\n while(high - low >= k){\n if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x))\n low++;\n else\n high--;\n }\n\n for(int i = low; i <= high; i++)\n result.add(arr[i]);\n\n return result;\n}\n}", + "title": "658. Find K Closest Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sorted integer array arr , two integers k and x , return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if:", + "description_images": [], + "constraints": [ + "|a - x| < |b - x| , or", + "|a - x| == |b - x| and a < b" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 4, x = 3\nOutput:[1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5], k = 4, x = -1\nOutput:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n \n def sorted_distance(value, static_input = x):\n return abs(value - static_input)\n \n distances = []\n result = []\n heapq.heapify(distances)\n \n for l,v in enumerate(arr):\n distances.append((l, sorted_distance(value = v)))\n \n for i in heapq.nsmallest(k, distances, key = lambda x: x[1]):\n result.append(arr[i[0]])\n \n result.sort()\n return result\n \n \n", + "title": "658. Find K Closest Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in ascending order .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput:[[1,2],[1,4],[1,6]]\nExplanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput:[[1,1],[1,1]]\nExplanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2], nums2 = [3], k = 3\nOutput:[[1,3],[2,3]]\nExplanation:All possible pairs are returned from the sequence: [1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 44.52%) | Memory: 128.2 MB (Top 22.61%)\nclass Solution {\n public List> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n PriorityQueue pq = new PriorityQueue<>(\n (a, b) -> (a[0] + a[1]) - (b[0] + b[1])\n );\n for(int i = 0; i < nums1.length && i < k; i++){\n pq.add(new int[]{nums1[i], nums2[0], 0});\n }\n\n List> res = new ArrayList<>();\n for(int i = 0; i < k && !pq.isEmpty(); i++){\n int [] curr = pq.poll();\n res.add(Arrays.asList(curr[0], curr[1]));\n int idx2 = curr[2];\n if(idx2 < nums2.length - 1){\n pq.add(new int[]{curr[0], nums2[idx2 + 1], idx2 + 1});\n }\n }\n return res;\n }\n}", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in ascending order .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput:[[1,2],[1,4],[1,6]]\nExplanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput:[[1,1],[1,1]]\nExplanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2], nums2 = [3], k = 3\nOutput:[[1,3],[2,3]]\nExplanation:All possible pairs are returned from the sequence: [1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1647 ms (Top 67.28%) | Memory: 34.4 MB (Top 27.52%)\nimport heapq\nclass Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n\n ans = []\n\n heapq.heapify(ans)\n\n for i in range(min(k,len(nums1))):\n for j in range(min(k,len(nums2))):\n pairs = [nums1[i],nums2[j]]\n if len(ans)-ans[0][0]:\n break\n heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs])\n heapq.heappop(ans)\n\n res = []\n for i in range(len(ans)):\n res.append(ans[i][1])\n\n return res", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^4", + "0 <= nums[i] <= 10^6", + "1 <= k <= n * (n - 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1], k = 1\nOutput:0\nExplanation:Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1stsmallest distance pair is (1,1), and its distance is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 2\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,6,1], k = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int smallestDistancePair(int[] nums, int k) {\n Arrays.sort(nums);\n int low = 0, high = nums[nums.length-1] - nums[0];\n \n while(low<=high){\n int mid = low + (high-low)/2;\n if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private int noOfDistancesLessThan(int dist,int[] nums){\n int count = 0,i = 0, j = 0;\n while(i 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1stsmallest distance pair is (1,1), and its distance is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 2\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,6,1], k = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heappush, heappop, heapify\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n # pairs = list(combinations(nums, 2))\n \n maxHeap = []\n heapify(maxHeap)\n \n for idx, val1 in enumerate(nums):\n for val2 in nums[idx + 1:]:\n pair = [val1, val2]\n heappush(maxHeap, [-1*abs(pair[0] - pair[1]), pair])\n if len(maxHeap) > k:\n heappop(maxHeap)\n \n return -1*maxHeap[0][0]\n", + "title": "719. Find K-th Smallest Pair Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two positive integers n and k , the binary string S n is formed as follows: Where + denotes the concatenation operation, reverse(x) returns the reversed string x , and invert(x) inverts all the bits in x ( 0 changes to 1 and 1 changes to 0 ). For example, the first four strings in the above sequence are: Return the k th bit in S n . It is guaranteed that k is valid for the given n .", + "description_images": [], + "constraints": [ + "S 1 = \"0\"", + "S i = S i - 1 + \"1\" + reverse(invert(S i - 1 )) for i > 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1\nOutput:\"0\"\nExplanation:S3is \"0111001\".\nThe 1stbit is \"0\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 11\nOutput:\"1\"\nExplanation:S4is \"011100110110001\".\nThe 11thbit is \"1\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2755 ms (Top 5.21%) | Memory: 238.8 MB (Top 5.21%)\nclass Solution {\n private String invert(String s){\n char [] array=s.toCharArray();\n for(int i=0;i 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1\nOutput:\"0\"\nExplanation:S3is \"0111001\".\nThe 1stbit is \"0\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 11\nOutput:\"1\"\nExplanation:S4is \"011100110110001\".\nThe 11thbit is \"1\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n i, s, hash_map = 1, '0', {'1': '0', '0': '1'}\n for i in range(1, n):\n s = s + '1' + ''.join((hash_map[i] for i in s))[::-1]\n return s[k-1]", + "title": "1545. Find Kth Bit in Nth Binary String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D matrix of size m x n , consisting of non-negative integers. You are also given an integer k . The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed) . Find the k th largest value (1-indexed) of all the coordinates of matrix .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "0 <= matrix[i][j] <= 10^6", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[5,2],[1,6]], k = 1\nOutput:7\nExplanation:The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[5,2],[1,6]], k = 2\nOutput:5\nExplanation:The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[5,2],[1,6]], k = 3\nOutput:4\nExplanation:The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 96.62%) | Memory: 250.3 MB (Top 62.84%)\nclass Solution {\n\n private static final Random RAND = new Random(0);\n\n public int kthLargestValue(int[][] matrix, int k) {\n var xor = convertToXorArray(matrix);\n var targetIdx = xor.length - k;\n sortPartially(xor, targetIdx, 0, xor.length);\n return xor[targetIdx];\n }\n\n void sortPartially(int[] nums, int targetIdx, int origLo, int origHi) {\n if (origHi - origLo < 2)\n return;\n\n var pivotIdx = RAND.nextInt(origHi - origLo) + origLo;\n var pivot = nums[pivotIdx];\n swap(nums, origLo, pivotIdx);\n\n var lo = origLo;\n var mid = lo + 1;\n var hi = origHi;\n while (mid < hi) {\n if (pivot < nums[mid])\n swap(nums, mid, --hi);\n else if (pivot > nums[mid])\n swap(nums, mid++, lo++);\n else\n mid++;\n }\n\n if (targetIdx < lo)\n sortPartially(nums, targetIdx, origLo, lo);\n\n sortPartially(nums, targetIdx, mid, origHi);\n }\n\n void swap(int[] n, int p, int q) {\n var tmp = n[p];\n n[p] = n[q];\n n[q] = tmp;\n }\n\n int[] convertToXorArray(int[][] matrix) {\n var rows = matrix.length;\n var cols = matrix[0].length;\n var xor = new int[rows * cols];\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n var xIdx = r * cols + c;\n xor[xIdx] = matrix[r][c];\n if (c > 0)\n xor[xIdx] ^= xor[xIdx - 1];\n }\n }\n\n for (int i = cols; i < xor.length; i++)\n xor[i] ^= xor[i - cols];\n\n return xor;\n }\n}", + "title": "1738. Find Kth Largest XOR Coordinate Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D matrix of size m x n , consisting of non-negative integers. You are also given an integer k . The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed) . Find the k th largest value (1-indexed) of all the coordinates of matrix .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "0 <= matrix[i][j] <= 10^6", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[5,2],[1,6]], k = 1\nOutput:7\nExplanation:The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[5,2],[1,6]], k = 2\nOutput:5\nExplanation:The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[5,2],[1,6]], k = 3\nOutput:4\nExplanation:The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n temp=0\n pq= []\n n = len(matrix)\n m = len(matrix[0])\n \n prefix= [ [0]*m for i in range(n) ]\n \n \n for i in range(n):\n for j in range(m):\n if i==0 or j==0:\n if i==0 and j==0:\n prefix[i][j] = matrix[i][j]\n elif i==0 and j!=0:\n prefix[i][j] ^= prefix[i][j-1]^ matrix[i][j]\n else:\n prefix[i][j]^=prefix[i-1][j]^ matrix[i][j]\n else:\n \n prefix[i][j] ^= prefix[i-1][j] ^ prefix[i][j-1]^matrix[i][j]^prefix[i-1][j-1]\n if len(pq) li=new ArrayList<>();\n\n public List largestValues(TreeNode root) {\n\n if(root==null) return li; //if root is NULL\n\n //using bfs(level-order)\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty()){\n int size=q.size();\n int res=Integer.MIN_VALUE;\n while(size-->0){\n TreeNode temp=q.poll();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n res =Math.max(res,temp.val); //comparing every node in each level to get max\n }\n li.add(res); //adding each level Max value to the list\n }\n return li;\n }\n}", + "title": "515. Find Largest Value in Each Tree Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,3,2,5,3,null,9]\nOutput:[1,3,9]", + "image": "https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3]\nOutput:[1,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def largestValues(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n ans=[]\n q=[]\n q.append(root)\n while q:\n s=len(q)\n t=[]\n for i in range(s):\n n=q.pop(0)\n t.append(n.val)\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n ans.append(max(t))\n return ans\n", + "title": "515. Find Largest Value in Each Tree Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr that represents a permutation of numbers from 1 to n . You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n , the bit at position arr[i] is set to 1 . You are also given an integer m . Find the latest step at which there exists a group of ones of length m . A group of ones is a contiguous substring of 1 's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m . If no such group exists, return -1 .", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= m <= n <= 10^5", + "1 <= arr[i] <= n", + "All integers in arr are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1,2,4], m = 1\nOutput:4\nExplanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,1,5,4,2], m = 2\nOutput:-1\nExplanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int[] par, size, count, bits; \n // par: parent array, tells about whose it the parent of ith element\n // size: it tells the size of component\n // count: it tells the count of islands (1111 etc) of size i;\n // count[3] = 4: ie -> there are 4 islands of size 3\n \n public int find(int u) {\n if (u == par[u]) return u;\n par[u] = find(par[u]);\n return par[u];\n }\n \n public void union(int u, int v) {\n // union is performed over parents of elements not nodes itself\n int p1 = find(u), p2 = find(v);\n if (p1 == p2) return;\n \n // decrease the count of islands of size p1, p2\n count[size[p1]]--;\n count[size[p2]]--;\n \n // now merge\n par[p2] = p1;\n \n // adjust sizes\n size[p1] += size[p2];\n \n // adjust the count of islands of new size ie: size of p1\n count[size[p1]]++;\n }\n \n public int findLatestStep(int[] arr, int m) {\n int n = arr.length;\n par = new int[n + 1];\n size = new int[n + 1];\n count = new int[n + 1];\n bits = new int[n + 2];\n \n for (int i = 0; i < n; i++) {\n par[i] = i;\n size[i] = 1;\n }\n \n int ans = -1;\n for (int i = 0; i < n; i++) {\n int idx = arr[i];\n // set the bit\n bits[idx] = 1;\n // increase the count of islands of size 1\n count[1]++;\n \n if (bits[idx - 1] > 0) {\n union(idx, idx - 1);\n } \n if (bits[idx + 1] > 0) {\n union(idx, idx + 1);\n }\n \n // check if island of size m exists\n if (count[m] > 0) {\n ans = i + 1;\n // as it is 1 based indexing\n }\n }\n return ans;\n }\n}\n\n", + "title": "1562. Find Latest Group of Size M", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array arr that represents a permutation of numbers from 1 to n . You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n , the bit at position arr[i] is set to 1 . You are also given an integer m . Find the latest step at which there exists a group of ones of length m . A group of ones is a contiguous substring of 1 's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m . If no such group exists, return -1 .", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= m <= n <= 10^5", + "1 <= arr[i] <= n", + "All integers in arr are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1,2,4], m = 1\nOutput:4\nExplanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,1,5,4,2], m = 2\nOutput:-1\nExplanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n n = len(arr)\n ans = -1\n if n == m: return m #just in case\n \n# make in \"inverted\" array with artificial ends higher then everything between\n\n sor= [0 for _ in range(n+2)]\n for i in range(n):\n sor[(arr[i])] = i+1 \n sor[0] = sor[n+1] = n+1\n \n# scan and see, if ones in the middle of space of length m appear \n# before ones on its ends,\n# and find the latest of such spaces to disappear, if exists\n\n for i in range(1, n-m+2): \n if all(sor[i-1]>sor[j] and sor[i+m]>sor[j] for j in range(i,i+m)):\n if min(sor[i-1]-1,sor[i+m]-1)>ans: ans = min(sor[i-1]-1,sor[i+m]-1) \n return ans\n", + "title": "1562. Find Latest Group of Size M", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3242415\"\nOutput:5\nExplanation:\"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"12345678\"\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:s = \"213123\"\nOutput:6\nExplanation:\"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestAwesome(String s) {\n Mapmap=new HashMap<>();\n map.put(0,-1);\n \n int state=0;\n int ans=0;\n for(int i=0;i int:\n # li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n li = [2**i for i in range(10)]\n # checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}\n checker = set(li)\n checker.add(0)\n # di: k = prefix xor, v = the first idx I got a new prefix_xor_value.\n di = collections.OrderedDict({0: -1})\n maxLength = prefix_xor = 0\n \n for i in range(len(s)):\n prefix_xor ^= li[int(s[i])]\n # Found a new prefix_xor_value\n if prefix_xor not in di:\n di[prefix_xor] = i\n \n # XOR operation with previous prefix_xor_value\n for key in di.keys():\n if i - di[key] <= maxLength:\n break\n\t\t\t\t# s[di[key] : i] is Awesome Substring\n if key ^ prefix_xor in checker:\n maxLength = i - di[key]\n return maxLength\n \n", + "title": "1542. Find Longest Awesome Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array . If there is no lucky integer return -1 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "1 <= arr[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,3,4]\nOutput:2\nExplanation:The only lucky number in the array is 2 because frequency[2] == 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,2,3,3,3]\nOutput:3\nExplanation:1, 2 and 3 are all lucky numbers, return the largest of them.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,2,2,3,3]\nOutput:-1\nExplanation:There are no lucky numbers in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 12.82%) | Memory: 44.3 MB (Top 18.67%)\nclass Solution {\n public int findLucky(int[] arr) {\n HashMap map = new HashMap<>();\n for(int i : arr){\n map.put(i, map.getOrDefault(i,0)+1);\n }\n System.out.print(map);\n int max = 0;\n for (Map.Entry e : map.entrySet()){\n int temp = 0;\n if(e.getKey() == (int)e.getValue()){\n temp = (int)e.getKey();\n }\n if(max < temp){\n max= temp;\n }\n }\n if(max != 0)return max;\n return -1;\n }\n}", + "title": "1394. Find Lucky Integer in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array . If there is no lucky integer return -1 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "1 <= arr[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,3,4]\nOutput:2\nExplanation:The only lucky number in the array is 2 because frequency[2] == 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,2,3,3,3]\nOutput:3\nExplanation:1, 2 and 3 are all lucky numbers, return the largest of them.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,2,2,3,3]\nOutput:-1\nExplanation:There are no lucky numbers in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n dc = {}\n \n for i in range(len(arr)):\n if arr[i] not in dc:\n dc[arr[i]] = 1\n else:\n dc[arr[i]] = dc[arr[i]] + 1\n mx = -1\n for key,value in dc.items():\n if key == value:\n mx = max(key, mx)\n return mx\n", + "title": "1394. Find Lucky Integer in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Implement the MedianFinder class:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 183 ms (Top 63.97%) | Memory: 124.7 MB (Top 57.27%)\nclass MedianFinder {\n\n PriorityQueue maxHeap;\n PriorityQueue minHeap;\n\n public MedianFinder() {\n maxHeap= new PriorityQueue((a,b)->b-a);\n minHeap= new PriorityQueue();\n }\n\n public void addNum(int num) {\n\n //Pushing\n if ( maxHeap.isEmpty() || ((int)maxHeap.peek() > num) ){\n maxHeap.offer(num);\n }\n else{\n minHeap.offer(num);\n }\n\n //Balancing\n if ( maxHeap.size() > minHeap.size()+ 1){\n minHeap.offer(maxHeap.peek());\n maxHeap.poll();\n }\n else if (minHeap.size() > maxHeap.size()+ 1 ){\n maxHeap.offer(minHeap.peek());\n minHeap.poll();\n }\n\n }\n\n public double findMedian() {\n\n //Evaluating Median\n if ( maxHeap.size() == minHeap.size() ){ // Even Number\n return ((int)maxHeap.peek()+ (int)minHeap.peek())/2.0;\n }\n else{ //Odd Number\n if ( maxHeap.size() > minHeap.size()){\n return (int)maxHeap.peek()+ 0.0;\n }\n else{ // minHeap.size() > maxHeap.size()\n return (int)minHeap.peek()+ 0.0;\n }\n }\n }\n}", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Implement the MedianFinder class:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 705 ms (Top 15.04%) | Memory: 39.30 MB (Top 5.61%)\n\nclass MedianFinder:\n\n def __init__(self):\n ### max heap to store the first half of the list\n self.maxHeap = []\n ### min heap to store the second half of the list\n self.minHeap = []\n\n def addNum(self, num: int) -> None:\n ### push num into the correct heap\n if not self.maxHeap or num <= -self.maxHeap[0]:\n heappush(self.maxHeap, -num)\n else:\n heappush(self.minHeap, num)\n \n ### banance the two heaps so that each of them representing half of the list\n ### for odd length list, len(maxHeap) == len(minHeap)+1\n ### for even length list, len(maxHeap) == len(minHeap)\n if len(self.minHeap) > len(self.maxHeap):\n heappush(self.maxHeap, -heappop(self.minHeap)) \n elif len(self.maxHeap) > len(self.minHeap)+1:\n heappush(self.minHeap, -heappop(self.maxHeap)) \n\n def findMedian(self) -> float:\n \n ### if the length of entire list is even, \n ### get the mean of the two middle values\n if (len(self.maxHeap)+len(self.minHeap))%2==0:\n return (-self.maxHeap[0]+self.minHeap[0])/2\n \n ### when odd, we know that the median is in maxHeap\n return -self.maxHeap[0]\n", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:1\nExplanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]\nOutput:0\nExplanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]\nOutput:11\nExplanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 45.46%) | Memory: 42.8 MB (Top 25.20%)\nclass Solution {\n public int findMin(int[] nums)\n {\n int min=nums[0];\n\n for(int i=0;inums[i])\n {\n min=nums[i];\n }\n }\n return min;\n }\n}", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:1\nExplanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]\nOutput:0\nExplanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]\nOutput:11\nExplanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n if len(nums) == 1 or nums[0] < nums[-1]:\n return nums[0]\n \n l, r = 0, len(nums) - 1\n \n while l <= r:\n mid = l + (r - l) // 2\n \n if mid > 0 and nums[mid - 1] > nums[mid]:\n return nums[mid]\n \n\t\t\t# We compare the middle number and the right index number\n\t\t\t# but why we cannot compare it with the left index number?\n if nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: 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 that may contain duplicates , return the minimum element of this array . You must decrease the overall operation steps as much as possible.", + "description_images": [], + "constraints": [ + "[4,5,6,7,0,1,4] if it was rotated 4 times.", + "[0,1,4,4,5,6,7] if it was rotated 7 times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,0,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 43.6 MB (Top 61.18%)\nclass Solution {\n public int findMin(int[] nums) {\n int l = 0;\n int h = nums.length - 1;\n while (l < h) {\n while (l < h && nums[l] == nums[l + 1])\n ++l;\n while (l < h && nums[h] == nums[h - 1])\n --h;\n int mid = l + (h - l) / 2;\n if (nums[mid] > nums[h]) { // smaller elements are in the right side\n l = mid + 1;\n } else {\n h = mid;\n }\n }\n return nums[l];\n }\n}", + "title": "154. Find Minimum in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: 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 that may contain duplicates , return the minimum element of this array . You must decrease the overall operation steps as much as possible.", + "description_images": [], + "constraints": [ + "[4,5,6,7,0,1,4] if it was rotated 4 times.", + "[0,1,4,4,5,6,7] if it was rotated 7 times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,0,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n return min(nums)\n \n", + "title": "154. Find Minimum in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array jobs , where jobs[i] is the amount of time it takes to complete the i th job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized . Return the minimum possible maximum working time of any assignment.", + "description_images": [], + "constraints": [ + "1 <= k <= jobs.length <= 12", + "1 <= jobs[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:jobs = [3,2,3], k = 3\nOutput:3\nExplanation:By assigning each person one job, the maximum time is 3.", + "image": null + }, + { + "text": "Example 2: Input:jobs = [1,2,4,7,8], k = 2\nOutput:11\nExplanation:Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int result = Integer.MAX_VALUE;\n public int minimumTimeRequired(int[] jobs, int k) {\n int length = jobs.length;\n Arrays.sort(jobs);\n backtrack(jobs, length - 1, new int [k]);\n return result;\n }\n \n public void backtrack(int [] jobs, int current, int [] workers) {\n if (current < 0) {\n result = Math.min(result, Arrays.stream(workers).max().getAsInt());\n return;\n }\n \n if (Arrays.stream(workers).max().getAsInt() >= result)\n return;\n for (int i=0; i 0 && workers[i] == workers[i-1])\n continue;\n // make choice\n workers[i] += jobs[current];\n // backtrack\n backtrack(jobs, current-1, workers);\n // undo the choice\n workers[i] -= jobs[current];\n }\n }\n \n \n}\n", + "title": "1723. Find Minimum Time to Finish All Jobs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array jobs , where jobs[i] is the amount of time it takes to complete the i th job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized . Return the minimum possible maximum working time of any assignment.", + "description_images": [], + "constraints": [ + "1 <= k <= jobs.length <= 12", + "1 <= jobs[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:jobs = [3,2,3], k = 3\nOutput:3\nExplanation:By assigning each person one job, the maximum time is 3.", + "image": null + }, + { + "text": "Example 2: Input:jobs = [1,2,4,7,8], k = 2\nOutput:11\nExplanation:Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 30 ms (Top 99.44%) | Memory: 16.50 MB (Top 63.13%)\n\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n def branchAndBound(i: int):\n nonlocal r\n if i == n:\n r = min(r, max(a))\n return\n visited = set()\n for j in range(k):\n if a[j] in visited:\n continue\n visited.add(a[j])\n if a[j] + jobs[i] >= r:\n continue\n a[j] += jobs[i]\n branchAndBound(i+1)\n a[j] -= jobs[i]\n\n n = len(jobs)\n if n <= k:\n return max(jobs)\n\n # use greed algorithm to get upper bound\n jobs.sort(reverse=True)\n a = list(jobs[:k])\n for job in jobs[k:]:\n m0 = min(a)\n i = a.index(m0)\n a[i] += job\n r = max(a)\n\n a = [0] * k\n branchAndBound(0)\n return r\n", + "title": "1723. Find Minimum Time to Finish All Jobs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6 . n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the i th observation. You are also given the two integers mean and n . Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean . If there are multiple valid answers, return any of them . If no such array exists, return an empty array . The average value of a set of k numbers is the sum of the numbers divided by k . Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m .", + "description_images": [], + "constraints": [ + "m == rolls.length", + "1 <= n, m <= 10^5", + "1 <= rolls[i], mean <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [3,2,4,3], mean = 4, n = 2\nOutput:[6,6]\nExplanation:The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,5,6], mean = 3, n = 4\nOutput:[2,3,2,2]\nExplanation:The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,2,3,4], mean = 6, n = 4\nOutput:[]\nExplanation:It is impossible for the mean to be 6 no matter what the 4 missing rolls are.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 98.11%) | Memory: 61.90 MB (Top 20.33%)\n\nclass Solution {\n public int[] missingRolls(int[] rolls, int mean, int n) {\n \n \tint i,m=rolls.length,sum=0;\n \tfor(i=0;i0?1:0);\n \t\tq--;\n \t}\n \treturn arr;\n }\n}\n", + "title": "2028. Find Missing Observations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6 . n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the i th observation. You are also given the two integers mean and n . Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean . If there are multiple valid answers, return any of them . If no such array exists, return an empty array . The average value of a set of k numbers is the sum of the numbers divided by k . Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m .", + "description_images": [], + "constraints": [ + "m == rolls.length", + "1 <= n, m <= 10^5", + "1 <= rolls[i], mean <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [3,2,4,3], mean = 4, n = 2\nOutput:[6,6]\nExplanation:The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,5,6], mean = 3, n = 4\nOutput:[2,3,2,2]\nExplanation:The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,2,3,4], mean = 6, n = 4\nOutput:[]\nExplanation:It is impossible for the mean to be 6 no matter what the 4 missing rolls are.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)\n if rem == 0:\n if 1 <= missing_val <= 6:\n return [missing_val] * n\n elif 1 <= missing_val < 6:\n return [missing_val + 1] * rem + [missing_val] * (n - rem)\n return []", + "title": "2028. Find Missing Observations", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it . If the tree has more than one mode, return them in any order . Assume a BST is defined as follows:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than or equal to the node's key.", + "The right subtree of a node contains only nodes with keys greater than or equal to the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,2]\nOutput:[2]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg" + }, + { + "text": "Example 2: Input:root = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 17.7%) | Memory: 45.06 MB (Top 9.4%)\n\nclass Solution {\n public int[] findMode(TreeNode root) {\n if(root==null) return new int[0];\n Map map = new HashMap(); //we are taking map to count each and every value of the tree and the no of times they occurs in the tree\n Queue qu = new LinkedList(); // to itereate over the tree\n List list = new ArrayList(); //to save our result into a dynamic arraylist then will convert into static array for return it\n qu.add(root); // add the first root node into queue to iterate over the tree\n while(!qu.isEmpty()) { \n TreeNode tmp = qu.poll(); //we poll out the node which is last inputed to the queue\n if(map.containsKey(tmp.val)) { //we are checking through the map wheather the value this node have already stored into the map or not\n map.put(tmp.val, map.get(tmp.val)+1); //the value is already stored then we just increase the count by 1\n }\n else {\n map.put(tmp.val, 1); //if the value is unique then we store it to the map with the count 1\n }\n if(tmp.left!=null) qu.add(tmp.left); //this way we are checking wheather left node has any value or not respect to the current poped element of queue\n if(tmp.right!=null) qu.add(tmp.right); //the same thing of the above just this is for right node of respective poped out node\n }\n int max = Integer.MIN_VALUE; //we are taking it because of requirement to identify highest no of repeated node available in this tree \n for(Integer key : map.keySet()) { //we are using keySet() for iterating over the map here key is differernt nodes and value is the no of count they have in this tree\n if(map.get(key)>max) { //if anything we find have greater value then previous maximum no of node like 2 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now \n list.clear(); //just to clear previous data that are stored into that list\n max = map.get(key); //now max will replaced by the new no of count of a node\n list.add(key); //we are adding the key which has most no of count\n }\n else if(max==map.get(key)) { //if we found another node which also has present maximum no of node count in the tree\n list.add(key); //we are also adding those key\n }\n }\n\t\t//now we just create an array transfer hole data that arraylist has and then return\n int[] res = new int[list.size()];\n for(int i=0; i max_streak:\n max_streak = curr_streak\n result = [curr_num]\n \n curr_node = curr_node.right\n \n return result\n", + "title": "501. Find Mode in Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return any array containing n unique integers such that they add up to 0 .", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:[-7,-1,1,3,4]\nExplanation:These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:[-1,0,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n int j=0;\n \n for(int i=1;i<=n/2;i++)\n {\n ans[j] = i;\n j++;\n }\n for(int i=1;i<=n/2;i++)\n {\n ans[j] = -i;\n j++;\n }\n if(n%2!=0) ans[j] = 0;\n \n return ans;\n }\n}\n", + "title": "1304. Find N Unique Integers Sum up to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return any array containing n unique integers such that they add up to 0 .", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:[-7,-1,1,3,4]\nExplanation:These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:[-1,0,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumZero(self, n: int) -> List[int]:\n q,p=divmod(n,2)\n if p:\n return list(range(-q, q+1))\n else:\n return list(range(-q,0))+list(range(1,q+1))", + "title": "1304. Find N Unique Integers Sum up to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers, x and y , which represent your current location on a Cartesian grid: (x, y) . You are also given an array points where each points[i] = [a i , b i ] represents that a point exists at (a i , b i ) . A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location . If there are multiple, return the valid point with the smallest index . If there are no valid points, return -1 . The Manhattan distance between two points (x 1 , y 1 ) and (x 2 , y 2 ) is abs(x 1 - x 2 ) + abs(y 1 - y 2 ) .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^4", + "points[i].length == 2", + "1 <= x, y, a i , b i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\nOutput:2\nExplanation:Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 4, points = [[3,4]]\nOutput:0\nExplanation:The answer is allowed to be on the same location as your current location.", + "image": null + }, + { + "text": "Example 3: Input:x = 3, y = 4, points = [[2,3]]\nOutput:-1\nExplanation:There are no valid points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nearestValidPoint(int x, int y, int[][] points) {\n int min=Integer.MAX_VALUE, index=-1, i;\n \n for ( i=0;i no longer needed as index is initialized as -1 in the declartion.\n return index;\n \n }\n}\n", + "title": "1779. Find Nearest Point That Has the Same X or Y Coordinate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers, x and y , which represent your current location on a Cartesian grid: (x, y) . You are also given an array points where each points[i] = [a i , b i ] represents that a point exists at (a i , b i ) . A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location . If there are multiple, return the valid point with the smallest index . If there are no valid points, return -1 . The Manhattan distance between two points (x 1 , y 1 ) and (x 2 , y 2 ) is abs(x 1 - x 2 ) + abs(y 1 - y 2 ) .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^4", + "points[i].length == 2", + "1 <= x, y, a i , b i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\nOutput:2\nExplanation:Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 4, points = [[3,4]]\nOutput:0\nExplanation:The answer is allowed to be on the same location as your current location.", + "image": null + }, + { + "text": "Example 3: Input:x = 3, y = 4, points = [[2,3]]\nOutput:-1\nExplanation:There are no valid points.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 689 ms (Top 99.93%) | Memory: 19.5 MB (Top 5.79%)\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist9 && val<100) || (val>999 && val<10000) || val==100000 )\n count++;\n }\n return count;\n }\n}\n", + "title": "1295. Find Numbers with Even Number of Digits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array nums of integers, return how many of them contain an even number of digits.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [12,345,2,6,7896]\nOutput:2\nExplanation:12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.", + "image": null + }, + { + "text": "Example 2: Input:nums = [555,901,482,1771]\nOutput:1\nExplanation:Only 1771 contains an even number of digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n even_count = 0\n for elem in nums:\n if(len(str(elem))%2 == 0):\n even_count += 1\n return even_count\n \n", + "title": "1295. Find Numbers with Even Number of Digits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original , and then randomly shuffling the resulting array. Given an array changed , return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order .", + "description_images": [], + "constraints": [ + "1 <= changed.length <= 10^5", + "0 <= changed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:changed = [1,3,4,2,6,8]\nOutput:[1,3,4]\nExplanation:One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:changed = [6,3,0,1]\nOutput:[]\nExplanation:changed is not a doubled array.", + "image": null + }, + { + "text": "Example 3: Input:changed = [1]\nOutput:[]\nExplanation:changed is not a doubled array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 93 ms (Top 85.10%) | Memory: 128.6 MB (Top 72.29%)\nclass Solution {\n public int[] findOriginalArray(int[] changed) {\n\n Arrays.sort(changed);\n\n if(changed.length%2!=0) return new int[0];\n\n int mid = changed.length/2;\n\n int[] res = new int[mid];\n\n int[] freq = new int[100001];\n\n for(int no : changed)\n freq[no]++;\n\n int idx=0;\n\n for(int no: changed){\n if(freq[no] > 0 && no*2 <= 100000 && freq[no*2]>0){\n freq[no]--;\n freq[no*2]--;\n res[idx++] = no;\n }\n }\n\n for(int i=0; i List[int]:\n counter = collections.Counter(changed)\n res = []\n for k in counter.keys():\n \n if k == 0:\n # handle zero as special case\n if counter[k] % 2 > 0:\n return []\n res += [0] * (counter[k] // 2)\n \n elif counter[k] > 0:\n x = k\n \n # walk down the chain\n while x % 2 == 0 and x // 2 in counter:\n x = x // 2\n \n # walk up and process all numbers within the chain. mark the counts as 0\n while x in counter:\n if counter[x] > 0:\n res += [x] * counter[x]\n if counter[x+x] < counter[x]:\n return []\n counter[x+x] -= counter[x]\n counter[x] = 0\n x += x\n return res\n", + "title": "2007. Find Original Array From Doubled Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array queries and a positive integer intLength , return an array answer where answer[i] is either the queries[i] th smallest positive palindrome of length intLength or -1 if no such palindrome exists . A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 5 * 10^4", + "1 <= queries[i] <= 10^9", + "1 <= intLength <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [1,2,3,4,5,90], intLength = 3\nOutput:[101,111,121,131,141,999]\nExplanation:The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90thpalindrome of length 3 is 999.", + "image": null + }, + { + "text": "Example 2: Input:queries = [2,4,6], intLength = 4\nOutput:[1111,1331,1551]\nExplanation:The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 121 ms (Top 54.38%) | Memory: 96.6 MB (Top 65.63%)\n\nclass Solution {\n public long[] kthPalindrome(int[] queries, int intLength) {\n long[] res= new long[queries.length];\n for(int i=0;i0)\n palindrome /= 10;\n while (palindrome>0)\n {\n res1=res1*10+(palindrome % 10);\n palindrome /= 10;\n }\n String g=\"\";\n g+=res1;\n if(g.length()!=kdigit)\n return -1;\n return res1;\n}\n}", + "title": "2217. Find Palindrome With Fixed Length", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array queries and a positive integer intLength , return an array answer where answer[i] is either the queries[i] th smallest positive palindrome of length intLength or -1 if no such palindrome exists . A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 5 * 10^4", + "1 <= queries[i] <= 10^9", + "1 <= intLength <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [1,2,3,4,5,90], intLength = 3\nOutput:[101,111,121,131,141,999]\nExplanation:The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90thpalindrome of length 3 is 999.", + "image": null + }, + { + "text": "Example 2: Input:queries = [2,4,6], intLength = 4\nOutput:[1111,1331,1551]\nExplanation:The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n ogLength = intLength\n isOdd = intLength & 1\n if isOdd:\n intLength += 1\n k = intLength // 2\n k = 10 ** (k - 1)\n op = []\n for q in queries:\n pal = str(k + q - 1)\n if isOdd:\n pal += pal[::-1][1:]\n else:\n pal += pal[::-1]\n if len(pal) == ogLength:\n op.append(int(pal))\n else:\n op.append(-1)\n return op\n", + "title": "2217. Find Palindrome With Fixed Length", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:2\nExplanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]\nOutput:5\nExplanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findPeakElement(int[] nums) {\n int start = 0;\n int end = nums.length - 1;\n \n while(start < end){\n int mid = start + (end - start) / 2;\n if(nums[mid] > nums[mid + 1]){\n //It means that we are in decreasing part of the array\n end = mid;\n }\n else{\n //It means that we are in increasing part of the array\n start = mid + 1;\n }\n }\n return start;\n }\n}\n", + "title": "162. Find Peak Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:2\nExplanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]\nOutput:5\nExplanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = [-2**32]+nums+[-2**32]\n l,r = 0,len(nums)-1\n while l <=r:\n m = (l+r)//2\n\t\t\t# we find the target:\n if nums[m] > nums[m-1] and nums[m] > nums[m+1]:\n return m -1\n else:\n if nums[m] int:\n right = sum(nums)\n left = 0\n\n for i in range(len(nums)):\n right -= nums[i]\n left += nums[i - 1] if i > 0 else 0\n\n if right == left: return i\n\n return -1", + "title": "724. Find Pivot Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array matches where matches[i] = [winner i , loser i ] indicates that the player winner i defeated player loser i in a match. Return a list answer of size 2 where: The values in the two lists should be returned in increasing order. Note:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all players that have not lost any matches.", + "answer[1] is a list of all players that have lost exactly one match." + ], + "examples": [ + { + "text": "Example 1: Input:matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\nOutput:[[1,2,10],[4,5,7,8]]\nExplanation:Players 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].", + "image": null + }, + { + "text": "Example 2: Input:matches = [[2,3],[1,3],[5,4],[6,4]]\nOutput:[[1,2,5,6],[]]\nExplanation:Players 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 99.73%) | Memory: 91.90 MB (Top 61.98%)\n\nclass Solution {\n public List> findWinners(int[][] matches) {\n int[] losses = new int[100001];\n\n for (int i = 0; i < matches.length; i++) {\n int win = matches[i][0];\n int loss = matches[i][1];\n\n if (losses[win] == 0) {\n losses[win] = -1;\n } \n\n if (losses[loss] == -1) {\n losses[loss] = 1;\n } else {\n losses[loss]++;\n }\n }\n\n List zeroLoss = new ArrayList<>();\n List oneLoss = new ArrayList<>();\n\n List> result = new ArrayList<>();\n\n for (int i = 0; i < losses.length; i++) {\n if (losses[i] == -1) {\n zeroLoss.add(i);\n } else if (losses[i] == 1) {\n oneLoss.add(i);\n }\n }\n\n result.add(zeroLoss);\n result.add(oneLoss);\n\n return result;\n }\n}\n", + "title": "2225. Find Players With Zero or One Losses", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array matches where matches[i] = [winner i , loser i ] indicates that the player winner i defeated player loser i in a match. Return a list answer of size 2 where: The values in the two lists should be returned in increasing order. Note:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all players that have not lost any matches.", + "answer[1] is a list of all players that have lost exactly one match." + ], + "examples": [ + { + "text": "Example 1: Input:matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\nOutput:[[1,2,10],[4,5,7,8]]\nExplanation:Players 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].", + "image": null + }, + { + "text": "Example 2: Input:matches = [[2,3],[1,3],[5,4],[6,4]]\nOutput:[[1,2,5,6],[]]\nExplanation:Players 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5248 ms (Top 5.11%) | Memory: 68.3 MB (Top 89.11%)\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n winners, losers, table = [], [], {}\n for winner, loser in matches:\n # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.\n # map.get(key, 0) returns map[key] if key exists and 0 if it does not.\n table[winner] = table.get(winner, 0) # Winner\n table[loser] = table.get(loser, 0) + 1\n for k, v in table.items(): # Player k with losses v\n if v == 0:\n winners.append(k) # If player k has no loss ie v == 0\n if v == 1:\n losers.append(k) # If player k has one loss ie v == 1\n return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.", + "title": "2225. Find Players With Zero or One Losses", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a callable function f(x, y) with a hidden formula and a value z , reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z . You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: The function interface is defined like this: We will judge your solution as follows:", + "description_images": [], + "constraints": [ + "f(x, y) < f(x + 1, y)", + "f(x, y) < f(x, y + 1)" + ], + "examples": [ + { + "text": "Example 1: Input:function_id = 1, z = 5\nOutput:[[1,4],[2,3],[3,2],[4,1]]\nExplanation:The hidden formula for function_id = 1 is f(x, y) = x + y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=4 -> f(1, 4) = 1 + 4 = 5.\nx=2, y=3 -> f(2, 3) = 2 + 3 = 5.\nx=3, y=2 -> f(3, 2) = 3 + 2 = 5.\nx=4, y=1 -> f(4, 1) = 4 + 1 = 5.", + "image": null + }, + { + "text": "Example 2: Input:function_id = 2, z = 5\nOutput:[[1,5],[5,1]]\nExplanation:The hidden formula for function_id = 2 is f(x, y) = x * y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=5 -> f(1, 5) = 1 * 5 = 5.\nx=5, y=1 -> f(5, 1) = 5 * 1 = 5.", + "image": null + }, + { + "text": "interface CustomFunction {\npublic:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n};", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int binarySearch(int ans, int x, CustomFunction func){\n int left = 1, right =1000;\n while(left <= right){\n int mid = left + (right -left)/2;\n \n int res = func.f(x, mid);\n \n if(res == ans){\n return mid;\n }\n if(res < ans){\n left = mid+1;\n }else{\n right = mid-1;\n }\n }\n return -1;\n }\n public List> findSolution(CustomFunction customfunction, int z) {\n List> res = new ArrayList<>();\n\n for(int i=1; i<=1000; i++){\n int ans = binarySearch(z, i, customfunction);\n if(ans != -1){\n List temp = new ArrayList<>();\n temp.add(i);\n temp.add(ans);\n res.add(temp);\n }\n if(customfunction.f(i,1) > z){\n break;\n }\n }\n return res;\n }\n}\n", + "title": "1237. Find Positive Integer Solution for a Given Equation", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string array words , where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams , and delete words[i] from words . Keep performing this operation as long as you can select an index that satisfies the conditions. Return words after performing all operations . It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, \"dacb\" is an anagram of \"abdc\" .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]\nOutput:[\"abba\",\"cd\"]\nExplanation:One of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = \"bbaa\" and words[1] = \"baba\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"baba\",\"cd\",\"cd\"].\n- Since words[1] = \"baba\" and words[0] = \"abba\" are anagrams, we choose index 1 and delete words[1].\n Now words = [\"abba\",\"cd\",\"cd\"].\n- Since words[2] = \"cd\" and words[1] = \"cd\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"cd\"].\nWe can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\",\"d\",\"e\"]\nOutput:[\"a\",\"b\",\"c\",\"d\",\"e\"]\nExplanation:No two adjacent strings in words are anagrams of each other, so no operations are performed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List removeAnagrams(String[] words) {\n String prev =\"\";\n List li=new ArrayList<>();\n for(int i=0;i List[str]:\n i = 0\n while i < len(words) - 1:\n if sorted(words[i]) == sorted(words[i + 1]):\n words.remove(words[i + 1])\n continue\n i += 1\n return words", + "title": "2273. Find Resultant Array After Removing Anagrams", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of intervals , where intervals[i] = [start i , end i ] and each start i is unique . The right interval for an interval i is an interval j such that start j >= end i and start j is minimized . Note that i may equal j . Return an array of right interval indices for each interval i . If no right interval exists for interval i , then put -1 at index i .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 2 * 10^4", + "intervals[i].length == 2", + "-10^6 <= start i <= end i <= 10^6", + "The start point of each interval is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2]]\nOutput:[-1]\nExplanation:There is only one interval in the collection, so it outputs -1.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[3,4],[2,3],[1,2]]\nOutput:[-1,0,1]\nExplanation:There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0= 3 is the smallest start that is >= end1= 3.\nThe right interval for [1,2] is [2,3] since start1= 2 is the smallest start that is >= end2= 2.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,4],[2,3],[3,4]]\nOutput:[-1,2,-1]\nExplanation:There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2= 3 is the smallest start that is >= end1= 3.", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n- Time: O(N*log(N))\nLoop through the array with n elements and run binary search with log(N) time for each of them.\n\n- Space: O(N)\nUsed a hashmap map of size N to store the original indeces of intervals\n */\nclass Solution {\n public int[] findRightInterval(int[][] intervals) {\n int n = intervals.length;\n int[] res = new int[n];\n Map map = new HashMap<>();\n for (int i = 0; i < n; i++) {\n map.put(intervals[i], i);\n }\n\n Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n for (int i = 0; i < n; i++) {\n int[] interval = binarySearch(intervals, intervals[i][1], i);\n res[map.get(intervals[i])] = interval == null ? -1 : map.get(interval);\n }\n \n return res;\n }\n\n private int[] binarySearch(int[][] intervals, int target, int start) {\n int l = start, r = intervals.length - 1;\n \n while (l <= r) {\n int m = l + (r - l) / 2;\n if (intervals[m][0] >= target) {\n // keep moving the right boundary to the left to get the first\n // element bigger than target\n r = m - 1;\n } else {\n // if the element we get is bigger than the target, we move the \n // left boundary to look at right part of the array\n l = m + 1;\n }\n }\n return l == intervals.length ? null : intervals[l];\n }\n}\n", + "title": "436. Find Right Interval", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of intervals , where intervals[i] = [start i , end i ] and each start i is unique . The right interval for an interval i is an interval j such that start j >= end i and start j is minimized . Note that i may equal j . Return an array of right interval indices for each interval i . If no right interval exists for interval i , then put -1 at index i .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 2 * 10^4", + "intervals[i].length == 2", + "-10^6 <= start i <= end i <= 10^6", + "The start point of each interval is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2]]\nOutput:[-1]\nExplanation:There is only one interval in the collection, so it outputs -1.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[3,4],[2,3],[1,2]]\nOutput:[-1,0,1]\nExplanation:There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0= 3 is the smallest start that is >= end1= 3.\nThe right interval for [1,2] is [2,3] since start1= 2 is the smallest start that is >= end2= 2.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,4],[2,3],[3,4]]\nOutput:[-1,2,-1]\nExplanation:There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2= 3 is the smallest start that is >= end1= 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 229 ms (Top 99.26%) | Memory: 22.50 MB (Top 16.77%)\n\nclass Solution:\n def findRightInterval(self, intervals):\n ints = sorted([[j,k,i] for i,[j,k] in enumerate(intervals)])\n begs = [i for i,_,_ in ints]\n out = [-1]*len(begs)\n for i,j,k in ints:\n t = bisect.bisect_left(begs, j)\n if t < len(begs):\n out[k] = ints[t][2]\n \n return out\n", + "title": "436. Find Right Interval", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time . The requests are assigned to servers according to a specific algorithm: You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the i th request, and another array load , where load[i] represents the load of the i th request (the time it takes to complete). Your goal is to find the busiest server(s) . A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s) . You may return the IDs in any order.", + "description_images": [], + "constraints": [ + "The i th (0-indexed) request arrives.", + "If all servers are busy, the request is dropped (not handled at all).", + "If the (i % k) th server is available, assign the request to that server.", + "Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the i th server is busy, try to assign the request to the (i+1) th server, then the (i+2) th server, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]\nOutput:[1]\nExplanation:All of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.", + "image": "https://assets.leetcode.com/uploads/2020/09/08/load-1.png" + }, + { + "text": "Example 2: Input:k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput:[0]\nExplanation:The first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.", + "image": null + }, + { + "text": "Example 3: Input:k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput:[0,1,2]\nExplanation:Each server handles a single request, so they are all considered the busiest.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 158 ms (Top 89.09%) | Memory: 61.5 MB (Top 92.12%)\nclass Solution {\n public List busiestServers(int k, int[] arrival, int[] load) {\n\n // use a tree to track available servers\n TreeSet availableServerIdxs = new TreeSet();\n for (int num = 0; num < k; num++) {\n availableServerIdxs.add(num);\n }\n // use a PQ to maintain the availability based on curTime + loadTime and the server index = idx%k\n Queue runningServers = new PriorityQueue<>((a, b)->(a[0] - b[0]));\n\n int[] serverHandledReqCount = new int[k];\n\n for (int idx = 0; idx < arrival.length; idx++) {\n int newTaskCompletionTime = arrival[idx];\n\n // peek if the server's work time is less than or equal to the next task completion time, if it is poll those servers from the running servers queue and add the index of that server to the availableServerIdxs treeSet\n while (!runningServers.isEmpty() && runningServers.peek()[0] <= newTaskCompletionTime) {\n int freedServer = runningServers.poll()[1];\n availableServerIdxs.add(freedServer);\n }\n\n if (availableServerIdxs.size() == 0) continue; // all busy\n\n // to always get the last freed server\n Integer serverIdx = availableServerIdxs.ceiling(idx % k);\n\n if (serverIdx == null) {\n serverIdx = availableServerIdxs.first();\n }\n\n serverHandledReqCount[serverIdx]++;\n availableServerIdxs.remove(serverIdx);\n\n runningServers.offer(new int[] {newTaskCompletionTime + load[idx], serverIdx});\n }\n\n int max = Arrays.stream(serverHandledReqCount).max().getAsInt();\n return IntStream.range(0, k).filter(i -> serverHandledReqCount[i] == max).boxed().collect(Collectors.toList());\n\n //return findMaxesInCounter(counter);\n }\n\n /*\n private List findMaxesInCounter(int[] counter) {\n int max = 0;\n for (int i = 0; i < counter.length; i++) {\n max = Math.max(max, counter[i]);\n }\n List result = new ArrayList<>();\n for (int i = 0; i < counter.length; i++) {\n if (counter[i] == max) {\n result.add(i);\n }\n }\n return result;\n }\n */\n}", + "title": "1606. Find Servers That Handled Most Number of Requests", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time . The requests are assigned to servers according to a specific algorithm: You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the i th request, and another array load , where load[i] represents the load of the i th request (the time it takes to complete). Your goal is to find the busiest server(s) . A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s) . You may return the IDs in any order.", + "description_images": [], + "constraints": [ + "The i th (0-indexed) request arrives.", + "If all servers are busy, the request is dropped (not handled at all).", + "If the (i % k) th server is available, assign the request to that server.", + "Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the i th server is busy, try to assign the request to the (i+1) th server, then the (i+2) th server, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]\nOutput:[1]\nExplanation:All of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.", + "image": "https://assets.leetcode.com/uploads/2020/09/08/load-1.png" + }, + { + "text": "Example 2: Input:k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput:[0]\nExplanation:The first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.", + "image": null + }, + { + "text": "Example 3: Input:k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput:[0,1,2]\nExplanation:Each server handles a single request, so they are all considered the busiest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def busiestServers(self, k: int, A: List[int], B: List[int]) -> List[int]:\n available = list(range(k)) # already a min-heap\n busy = [] \n res = [0] * k\n for i, a in enumerate(A):\n while busy and busy[0][0] <= a: # these are done, put them back as available\n _, x = heapq.heappop(busy)\n heapq.heappush(available, i + (x-i)%k) # invariant: min(available) is at least i, at most i+k-1\n if available: \n j = heapq.heappop(available) % k\n heapq.heappush(busy, (a+B[i],j))\n res[j] += 1\n a = max(res)\n return [i for i in range(k) if res[i] == a]\n", + "title": "1606. Find Servers That Handled Most Number of Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target , return the smallest character in the array that is larger than target . Note that the letters wrap around.", + "description_images": [], + "constraints": [ + "For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:letters = [\"c\",\"f\",\"j\"], target = \"a\"\nOutput:\"c\"", + "image": null + }, + { + "text": "Example 2: Input:letters = [\"c\",\"f\",\"j\"], target = \"c\"\nOutput:\"f\"", + "image": null + }, + { + "text": "Example 3: Input:letters = [\"c\",\"f\",\"j\"], target = \"d\"\nOutput:\"f\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.10 MB (Top 77.94%)\n\nclass Solution {\n public char nextGreatestLetter(char[] letters, char target) {\n char res=letters[0];\n int start=0;\n int end=letters.length-1;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n if(letters[mid]==target)\n {\n start=mid+1;\n }\n else if(target>letters[mid])\n {\n start=mid+1;\n }\n else if(letters[mid]>target)\n {\n res=letters[mid];\n end=mid-1;\n }\n }\n return res;\n \n }\n}\n", + "title": "744. Find Smallest Letter Greater Than Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target , return the smallest character in the array that is larger than target . Note that the letters wrap around.", + "description_images": [], + "constraints": [ + "For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:letters = [\"c\",\"f\",\"j\"], target = \"a\"\nOutput:\"c\"", + "image": null + }, + { + "text": "Example 2: Input:letters = [\"c\",\"f\",\"j\"], target = \"c\"\nOutput:\"f\"", + "image": null + }, + { + "text": "Example 3: Input:letters = [\"c\",\"f\",\"j\"], target = \"d\"\nOutput:\"f\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n beg = 0\n end = len(letters)-1\n while beg <= end:\n mid = (beg+end)//2\n if letters[mid]>target:\n end = mid -1\n else:\n beg = mid +1\n return letters[beg] if beg pq = new PriorityQueue<>((a,b) -> b[0] - a[0]);\n \n for(int i=0; i l = new ArrayList<>();\n \n while(k-- != 0)\n l.add(pq.poll());\n \n Collections.sort(l, (a,b) -> a[1] - b[1]);\n \n int[] res = new int[l.size()];\n \n int index = 0;\n \n for(int[] i: l)\n res[index++] = i[0];\n \n return res;\n }\n}\n", + "title": "2099. Find Subsequence of Length K With the Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k . A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3,3], k = 2\nOutput:[3,3]\nExplanation:The subsequence has the largest sum of 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-2,3,4], k = 3\nOutput:[-1,3,4]\nExplanation:The subsequence has the largest sum of -1 + 3 + 4 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,3,3], k = 2\nOutput:[3,4]\nExplanation:The subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxSubsequence(self, nums, k):\n ret, max_k = [], sorted(nums, reverse=True)[:k]\n for num in nums:\n if num in max_k:\n ret.append(num)\n max_k.remove(num)\n if len(max_k) == 0:\n return ret\n", + "title": "2099. Find Subsequence of Length K With the Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The hash of a 0-indexed string s of length k , given integers p and m , is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26 . You are given a string s and the integers power , modulo , k , and hashValue. Return sub , the first substring of s of length k such that hash(sub, power, modulo) == hashValue . The test cases will be generated such that an answer always exists . A substring is a contiguous non-empty sequence of characters within a string.", + "description_images": [], + "constraints": [ + "hash(s, p, m) = (val(s[0]) * p 0 + val(s[1]) * p 1 + ... + val(s[k-1]) * p k-1 ) mod m ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput:\"ee\"\nExplanation:The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput:\"fbx\"\nExplanation:The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String subStrHash(String s, int power, int modulo, int k, int hashValue) {\n\t\t// calculate all the powers from power^0 till power^k\n\t\t// utilized binary exponentiation\n\t\tlong[] powers = new long[k];\n for (int i = 0; i < k; i++) \n powers[i] = binaryExponentiation(power, i, modulo);\n \n\t\t// pre compute the initial hash from behind.\n\t\t// I have explained at top you why traversing from behind is easy\n long currentHashValue = 0;\n int index = s.length() - 1;\n int powerIndex = k-1;\n while (index >= s.length() - k) {\n\t\t\t// (a+b) % modulo = ( (a % modulo) + (b % modulo) ) % modulo;\n\t\t\t// do it for k times from behind\n currentHashValue += ((s.charAt(index--) - 'a' + 1) % modulo * powers[powerIndex--] % modulo) % modulo;\n }\n currentHashValue %= modulo;\n \n int startIndex = 0;\n if (currentHashValue == hashValue) {\n startIndex = s.length() - k;\n }\n \n\t\t// I have pre computed already for k values from behind. so start from (length of S - k - 1)\n\t\t// Let's take an example of \"leetcode\" itself\n\t\t// \"de\" is pre computed\n\t\t// point is to add one character from behind and remove one from end (Sliding from back to first)\n\t\t// Modular Arithmetic for (a-b) % modulo = ( (a % modulo) - (b % modulo) + modulo) % modulo;\n\t\t// keep tracking of the start index if hash value matches. That's it.\n for (int i = s.length() - k - 1; i >= 0; i--) {\n\t\t\t// below line a --> currentHashValue \n\t\t\t// below line b --> (s.charAt(i+k) - 'a' + 1 * powers[k-1])\n currentHashValue = ((currentHashValue % modulo) - (((s.charAt(i+k) - 'a' + 1) * powers[k-1]) % modulo) + modulo) % modulo;\n\t\t\t// we need to multiply a power once for all\n\t\t\t// MULTIPLICATION\n currentHashValue = currentHashValue * power;\n\t\t\t// Modular Arithmetic for (a+b) % modulo is below line\n currentHashValue = (currentHashValue % modulo + (s.charAt(i) - 'a' + 1) % modulo) % modulo;\n \n if (currentHashValue == hashValue) {\n startIndex = i;\n }\n }\n return s.substring(startIndex, startIndex+k);\n }\n \n private long binaryExponentiation(long a, long b, long mod) {\n a %= mod;\n long result = 1;\n while (b > 0) {\n if (b % 2 == 1)\n result = result * a % mod;\n a = a * a % mod;\n b >>= 1;\n }\n return result;\n }\n}\n", + "title": "2156. Find Substring With Given Hash Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The hash of a 0-indexed string s of length k , given integers p and m , is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26 . You are given a string s and the integers power , modulo , k , and hashValue. Return sub , the first substring of s of length k such that hash(sub, power, modulo) == hashValue . The test cases will be generated such that an answer always exists . A substring is a contiguous non-empty sequence of characters within a string.", + "description_images": [], + "constraints": [ + "hash(s, p, m) = (val(s[0]) * p 0 + val(s[1]) * p 1 + ... + val(s[k-1]) * p k-1 ) mod m ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput:\"ee\"\nExplanation:The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput:\"fbx\"\nExplanation:The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 996 ms (Top 33.98%) | Memory: 14.1 MB (Top 94.23%)\nclass Solution:\n def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n val = lambda ch : ord(ch) - ord(\"a\") + 1\n hash, res, power_k = 0, 0, pow(power, k, mod)\n for i in reversed(range(len(s))):\n hash = (hash * power + val(s[i])) % mod\n if i < len(s) - k:\n hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod\n res = i if hash == hashValue else res\n return s[res:res + k]", + "title": "2156. Find Substring With Given Hash Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums and a target element target . A target index is an index i such that nums[i] == target . Return a list of the target indices of nums after sorting nums in non-decreasing order . If there are no target indices, return an empty list . The returned list must be sorted in increasing order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], target <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,2,3], target = 2\nOutput:[1,2]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,5,2,3], target = 3\nOutput:[3]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,5,2,3], target = 5\nOutput:[4]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 82.14%) | Memory: 43.8 MB (Top 60.21%)\nclass Solution {\n /** Algorithm:\n - Parse the array once and count how many are lesser than target and how many are equal\n - DO NOT sort the array as we don't need it sorted.\n Just to know how many are lesser and how many are equal. O(N) better than O(NlogN - sorting)\n - The response list will have a size = with the number of equal elements (as their positions)\n - Loop from smaller to smaller+equal and add the values into the list. Return the list\n */\n public List targetIndices(int[] nums, int target) {\n int smaller = 0;\n int equal = 0;\n for (int num : nums) {\n if (num < target) {\n smaller++;\n } else if (num == target) {\n equal++;\n }\n }\n List indices = new ArrayList<>(equal);\n for (int i = smaller; i < smaller + equal; i++) {\n indices.add(i);\n }\n return indices;\n }\n}", + "title": "2089. Find Target Indices After Sorting Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and a target element target . A target index is an index i such that nums[i] == target . Return a list of the target indices of nums after sorting nums in non-decreasing order . If there are no target indices, return an empty list . The returned list must be sorted in increasing order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], target <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,2,3], target = 2\nOutput:[1,2]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,5,2,3], target = 3\nOutput:[3]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,5,2,3], target = 5\nOutput:[4]\nExplanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def targetIndices(self, nums, target):\n ans = []\n for i,num in enumerate(sorted(nums)):\n if num == target: ans.append(i)\n return ans\n", + "title": "2089. Find Target Indices After Sorting Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n-1 . Given the array edges where edges[i] = [from i , to i , weight i ] represents a bidirectional and weighted edge between cities from i and to i , and given the integer distanceThreshold . Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold , If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= n * (n - 1) / 2", + "edges[i].length == 3", + "0 <= from i < to i < n", + "1 <= weight i , distanceThreshold <= 10^4", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput:3\nExplanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput:0\nExplanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findTheCity(int n, int[][] edges, int distanceThreshold) {\n int[][] graph = new int[n][n];\n for(int[] row: graph)\n Arrays.fill(row, Integer.MAX_VALUE);\n \n for(int i = 0; i < n; i++)\n graph[i][i] = 0;\n \n for(int[] edge: edges)\n {\n graph[edge[0]][edge[1]] = edge[2];\n graph[edge[1]][edge[0]] = edge[2];\n }\n \n for(int k = 0; k < n; k++)\n {\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < n; j++)\n {\n if(graph[i][k] != Integer.MAX_VALUE && graph[k][j] != Integer.MAX_VALUE)\n {\n if(graph[i][k] + graph[k][j] < graph[i][j])\n graph[i][j] = graph[i][k] + graph[k][j];\n }\n }\n }\n }\n \n int ans = 0;\n int city = Integer.MAX_VALUE;;\n \n for(int i = 0; i < n; i++)\n {\n int current = 0;\n for(int j = 0; j < n; j++)\n {\n if(i != j && graph[i][j] <= distanceThreshold)\n current++;\n }\n if(current <= city)\n {\n ans = i;\n city = current;\n }\n }\n \n return ans;\n }\n}\n", + "title": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cities numbered from 0 to n-1 . Given the array edges where edges[i] = [from i , to i , weight i ] represents a bidirectional and weighted edge between cities from i and to i , and given the integer distanceThreshold . Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold , If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= n * (n - 1) / 2", + "edges[i].length == 3", + "0 <= from i < to i < n", + "1 <= weight i , distanceThreshold <= 10^4", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput:3\nExplanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput:0\nExplanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n matrix = [[float('inf')] * n for _ in range(n)]\n \n # initializing the matrix\n for u, v, w in edges:\n matrix[u][v] = w\n matrix[v][u] = w\n\n for u in range(n):\n matrix[u][u] = 0\n \n for k in range(n):\n for i in range(n):\n for j in range(n):\n if matrix[i][j] > matrix[i][k] + matrix[k][j]:\n matrix[i][j] = matrix[i][k] + matrix[k][j]\n \n # counting reachable cities(neighbor) for every single city \n res = [0] * n\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if 0 < matrix[i][j] <= distanceThreshold:\n res[j] += 1\n return [i for i, x in enumerate(res) if x == min(res)][-1]\n", + "title": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome . If there is a tie, return the smaller one . The closest is defined as the absolute difference minimized between two integers.", + "description_images": [], + "constraints": [ + "1 <= n.length <= 18", + "n consists of only digits.", + "n does not have leading zeros.", + "n is representing an integer in the range [1, 10^18 - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"123\"\nOutput:\"121\"", + "image": null + }, + { + "text": "Example 2: Input:n = \"1\"\nOutput:\"0\"\nExplanation:0 and 2 are the closest palindromes but we return the smallest which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static long pow(long base,long exp){\n long ans = 1;\n for(;exp != 0;){\n if((exp & 1) == 1){\n ans *= base;\n }\n base *= base;\n exp >>= 1;\n }\n return ans;\n }\n public String nearestPalindromic(String n) {\n long num = Long.parseLong(n);\n if(num <= 10){\n return String.valueOf(num - 1);\n }\n long comp[] = new long[5];\n comp[0] = pow(10,n.length() - 1) - 1;\n comp[1] = pow(10,n.length()) + 1;\n int mid = (n.length() + 1) / 2;\n long half = Long.parseLong(n.substring(0,mid));\n long pref[] = {half,half + 1,half - 1};\n for(int i = 0;i < 3;i++){\n StringBuilder st = new StringBuilder(String.valueOf(pref[i]));\n if(n.length() % 2 == 1) st.deleteCharAt(st.length() - 1);\n st.reverse();\n comp[i + 2] = Long.parseLong(String.valueOf(pref[i]) + st.toString()); \n }\n long min = Long.MAX_VALUE;\n long ans = Long.MAX_VALUE;\n for(int i = 0;i < 5;i++){\n long dif = Math.abs(num - comp[i]);\n if(dif != 0 && min > dif){\n min = dif;\n ans = comp[i];\n }\n else if(min == dif) ans = Math.min(ans,comp[i]);\n }\n return String.valueOf(ans);\n }\n}\n", + "title": "564. Find the Closest Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome . If there is a tie, return the smaller one . The closest is defined as the absolute difference minimized between two integers.", + "description_images": [], + "constraints": [ + "1 <= n.length <= 18", + "n consists of only digits.", + "n does not have leading zeros.", + "n is representing an integer in the range [1, 10^18 - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"123\"\nOutput:\"121\"", + "image": null + }, + { + "text": "Example 2: Input:n = \"1\"\nOutput:\"0\"\nExplanation:0 and 2 are the closest palindromes but we return the smallest which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "", + "title": "564. Find the Closest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and t . String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 1000", + "t.length == s.length + 1", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"abcde\"\nOutput:\"e\"\nExplanation:'e' is the letter that was added.", + "image": null + }, + { + "text": "Example 2: Input:s = \"\", t = \"y\"\nOutput:\"y\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public char findTheDifference(String s, String t) {\n char c = 0;\n for(char cs : s.toCharArray()) c ^= cs;\n for(char ct : t.toCharArray()) c ^= ct;\n return c;\n }\n}\n", + "title": "389. Find the Difference", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s and t . String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 1000", + "t.length == s.length + 1", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"abcde\"\nOutput:\"e\"\nExplanation:'e' is the letter that was added.", + "image": null + }, + { + "text": "Example 2: Input:s = \"\", t = \"y\"\nOutput:\"y\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n c = 0\n for cs in s: c ^= ord(cs) #ord is ASCII value\n for ct in t: c ^= ord(ct)\n return chr(c) #chr = convert ASCII into character\n", + "title": "389. Find the Difference", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order.", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]\nOutput:[[1,3],[4,6]]\nExplanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput:[[3],[]]\nExplanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 69.34%) | Memory: 54.7 MB (Top 58.44%)\nclass Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n Set set1 = new HashSet<>(); // create 2 hashsets\n Set set2 = new HashSet<>();\n for(int num : nums1){ set1.add(num); } // add nums1 elements to set1\n for(int num : nums2){ set2.add(num); } // add nums2 elements to set2\n\n List> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return\n resultList.add(new ArrayList<>());\n resultList.add(new ArrayList<>());\n\n for(int num : set1){ // just iterate to all elements of set1\n if(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.\n }\n for(int num : set2){ // just iterate to all elements of set2\n if(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1\n }\n return resultList;\n }\n}", + "title": "2215. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order.", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]\nOutput:[[1,3],[4,6]]\nExplanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput:[[3],[]]\nExplanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 953 ms (Top 29.31%) | Memory: 14.3 MB (Top 52.22%)\nclass Solution(object):\n def findDifference(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[List[int]]\n \"\"\"\n a = []\n for i in range(len(nums1)):\n if nums1[i] not in nums2:\n a.append(nums1[i])\n b = []\n for i in range(len(nums2)):\n if nums2[i] not in nums1:\n b.append(nums2[i])\n\n c = [list(set(a))] + [list(set(b))]\n\n return c", + "title": "2215. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays arr1 and arr2 , and the integer d , return the distance value between the two arrays . The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d .", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 500", + "-1000 <= arr1[i], arr2[j] <= 1000", + "0 <= d <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput:2\nExplanation:For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:|8-10|=2 <= d=2|8-9|=1 <= d=2|8-1|=7 > d=2|8-8|=0 <= d=2", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 68.55%) | Memory: 44.9 MB (Top 25.67%)\nclass Solution {\n public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {\n int x=0,val=0;\n for(int i:arr1){\n for(int j:arr2){\n if(Math.abs(i-j)<=d){\n x--;\n break;\n }\n }\n x++;\n }\n return x;\n }\n}", + "title": "1385. Find the Distance Value Between Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays arr1 and arr2 , and the integer d , return the distance value between the two arrays . The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d .", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 500", + "-1000 <= arr1[i], arr2[j] <= 1000", + "0 <= d <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput:2\nExplanation:For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:|8-10|=2 <= d=2|8-9|=1 <= d=2|8-1|=7 > d=2|8-8|=0 <= d=2", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int:\n\n\t\tresult = 0\n\n\t\tarray2 = sorted(array2)\n\n\t\tfor num in array1:\n\n\t\t\tflag = True\n\n\t\t\tlow = 0\n\t\t\thigh = len(array2)-1\n\n\t\t\twhile low <= high:\n\n\t\t\t\tmid = (low + high) // 2\n\n\t\t\t\tif abs(array2[mid] - num) <= d:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\n\t\t\t\telif array2[mid] > num:\n\t\t\t\t\thigh = mid - 1\n\n\t\t\t\telse:\n\t\t\t\t\tlow = mid + 1;\n\n\t\t\tif flag == True:\n\n\t\t\t\tresult = result + 1\n\n\t\treturn result\n", + "title": "1385. Find the Distance Value Between Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 uses only constant extra space.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findDuplicate(int[] nums) {\n int i = 0; \n while (i < nums.length) {\n\n if (nums[i] != i + 1) {\n int correct = nums[i] - 1;\n if (nums[i] != nums[correct]) {\n swap(nums, i , correct);\n } else {\n return nums[i];\n }\n } else {\n i++;\n }\n }\n return -1;\n }\n static void swap(int[] arr, int first, int second) {\n int temp = arr[first];\n arr[first] = arr[second];\n arr[second] = temp;\n }\n }\n", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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 uses only constant extra space.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1523 ms (Top 9.74%) | Memory: 34 MB (Top 8.51%)\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n\n dictx = {}\n\n for each in nums:\n if each not in dictx:\n dictx[each] = 1\n else:\n return each\n", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0 . You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i ​​​​​​ and i + 1 for all ( 0 <= i < n) . Return the highest altitude of a point.", + "description_images": [], + "constraints": [ + "n == gain.length", + "1 <= n <= 100", + "-100 <= gain[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:gain = [-5,1,5,0,-7]\nOutput:1\nExplanation:The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.", + "image": null + }, + { + "text": "Example 2: Input:gain = [-4,-3,-2,-1,4,3,2]\nOutput:0\nExplanation:The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.7 MB (Top 97.89%)\nclass Solution {\n public int largestAltitude(int[] gain) {\n int max_alt=0;\n int curr_alt=0;\n for(int i=0;i int:\n return max(accumulate([0]+gain))", + "title": "1732. Find the Highest Altitude", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: Given integers num and k , return the k-beauty of num . Note: A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "It has a length of k .", + "It is a divisor of num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 240, k = 2\nOutput:2\nExplanation:The following are the substrings of num of length k:\n- \"24\" from \"240\": 24 is a divisor of 240.\n- \"40\" from \"240\": 40 is a divisor of 240.\nTherefore, the k-beauty is 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 430043, k = 2\nOutput:2\nExplanation:The following are the substrings of num of length k:\n- \"43\" from \"430043\": 43 is a divisor of 430043.\n- \"30\" from \"430043\": 30 is not a divisor of 430043.\n- \"00\" from \"430043\": 0 is not a divisor of 430043.\n- \"04\" from \"430043\": 4 is not a divisor of 430043.\n- \"43\" from \"430043\": 43 is a divisor of 430043.\nTherefore, the k-beauty is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divisorSubstrings(int num, int k) {\n String str=String.valueOf(num); // to covert integer to String\n int count=0; // count of ans..\n for(int i=0;i int:\n # since integer has no length function, we convert our num into a str.\n # Then we run a loop that goes until i+k-1 < len(numStr) and take\n # n = int(numStr[i: i+k]); and if n!=0 and num%n==0 meaning \n\t\t# num is divisible by n so we add 1 to k_beauty and return it in the end.\n\t\t\n numStr = str(num)\n i, k_beauty = 0, 0\n \n while i+k-1 < len(numStr):\n n = int(numStr[i: i+k])\n if n!=0 and num%n==0:\n k_beauty += 1\n \n i += 1\n \n return k_beauty\n", + "title": "2269. Find the K-Beauty of a Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings nums and an integer k . Each string in nums represents an integer without leading zeros. Return the string that represents the k th largest integer in nums . Note : Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"] , \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^4", + "1 <= nums[i].length <= 100", + "nums[i] consists of only digits.", + "nums[i] will not have any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\nOutput:\"3\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4thlargest integer in nums is \"3\".", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\nOutput:\"2\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rdlargest integer in nums is \"2\".", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"0\",\"0\"], k = 2\nOutput:\"0\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2ndlargest integer in nums is \"0\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 27.4%) | Memory: 53.91 MB (Top 31.3%)\n\nclass Solution {\n public String kthLargestNumber(String[] nums, int k) {\n \n int n=nums.length;\n \n Arrays.sort(nums,(a,b)->{\n if(a.length()>b.length()) return 1;\n else if(b.length()>a.length()) return -1;\n else{\n return isgreater(a,b); \n }\n });\n return nums[n-k]; \n }\n \n public static int isgreater(String a,String b){\n \n int n=a.length();\n \n for(int i=0;ib1) return 1;\n if(b1>a1) return -1;\n }\n return 0;\n }\n}", + "title": "1985. Find the Kth Largest Integer in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings nums and an integer k . Each string in nums represents an integer without leading zeros. Return the string that represents the k th largest integer in nums . Note : Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"] , \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^4", + "1 <= nums[i].length <= 100", + "nums[i] consists of only digits.", + "nums[i] will not have any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\nOutput:\"3\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4thlargest integer in nums is \"3\".", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\nOutput:\"2\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rdlargest integer in nums is \"2\".", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"0\",\"0\"], k = 2\nOutput:\"0\"\nExplanation:The numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2ndlargest integer in nums is \"0\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])\n", + "title": "1985. Find the Kth Largest Integer in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k . You are allowed to choose exactly one element from each row to form an array. Return the k th smallest array sum among all possible arrays .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat.length[i]", + "1 <= m, n <= 40", + "1 <= mat[i][j] <= 5000", + "1 <= k <= min(200, n m )", + "mat[i] is a non-decreasing array." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,3,11],[2,4,6]], k = 5\nOutput:7\nExplanation:Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,3,11],[2,4,6]], k = 9\nOutput:17", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput:9\nExplanation:Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kthSmallest(int[][] mat, int k) {\n int[] row = mat[0];\n \n for(int i=1; i list = new ArrayList<>();\n PriorityQueue minHeap = new PriorityQueue<>((a,b) -> (a[0]+a[1]) - (b[0]+b[1]));\n \n for(int i=0; ii).toArray();\n }\n}\n", + "title": "1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k . You are allowed to choose exactly one element from each row to form an array. Return the k th smallest array sum among all possible arrays .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat.length[i]", + "1 <= m, n <= 40", + "1 <= mat[i][j] <= 5000", + "1 <= k <= min(200, n m )", + "mat[i] is a non-decreasing array." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,3,11],[2,4,6]], k = 5\nOutput:7\nExplanation:Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,3,11],[2,4,6]], k = 9\nOutput:17", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput:9\nExplanation:Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n h = [(nums1[0]+nums2[0],0,0)]\n visited = set()\n res = []\n while h and k > 0:\n e, i, j = heappop(h)\n if (i,j) in visited: continue\n res.append(e)\n visited.add((i,j))\n if j+1 < len(nums2):\n heappush(h,(nums1[i]+nums2[j+1],i,j+1))\n if i+1 < len(nums1):\n heappush(h,(nums1[i+1]+nums2[j],i+1,j))\n k -= 1\n return res\n res = mat[0]\n for i in range(1, len(mat)):\n res = kSmallestPairs(res, mat[i], k)\n return res[-1]", + "title": "1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the string s , return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 x 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"eleetminicoworoep\"\nOutput:13\nExplanation:The longest substring is \"leetminicowor\" which contains two each of the vowels:e,iandoand zero of the vowels:aandu.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcodeisgreat\"\nOutput:5\nExplanation:The longest substring is \"leetc\" which contains two e's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bcbcbc\"\nOutput:6\nExplanation:In this case, the given string \"bcbcbc\" is the longest because all vowels:a,e,i,oanduappear zero times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.39%) | Memory: 45.40 MB (Top 86.55%)\n\nclass Solution {\n\n // taken help as for my code TLE T.C = (n^2);\n\n/* static boolean check(String s){\n int n = s.length();\n\n int arr[] = new int[26];\n\n for(int i=0; i int:\n integrals = [(False, False, False, False, False)] # integrals[10][mapping[\"a\"]] == False means we have seen \"a\" appears even times before index 10\n mapping = {\n \"a\": 0,\n \"i\": 1,\n \"u\": 2,\n \"e\": 3,\n \"o\": 4\n }\n\n for v in s:\n vector = list(integrals[-1])\n if v in mapping: # if v is a vowel\n vector[mapping[v]] = not vector[mapping[v]] # toggle that dimension, because if v had appeared even times before, it becomes odd times now\n integrals.append(tuple(vector))\n\n seen = {}\n res = 0\n\n for i, v in enumerate(integrals):\n if v in seen: # we have seen this vector before\n res = max(res, i - seen[v]) # compare its substring length\n else:\n seen[v] = i # just record the first time each vector appears\n\n return res\n", + "title": "1371. Find the Longest Substring Containing Vowels in Even Counts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n , where obstacles[i] describes the height of the i th obstacle. For every index i between 0 and n - 1 ( inclusive ), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n , where ans[i] is the length of the longest obstacle course for index i as described above .", + "description_images": [], + "constraints": [ + "You choose any number of obstacles between 0 and i inclusive .", + "You must include the i th obstacle in the course.", + "You must put the chosen obstacles in the same order as they appear in obstacles .", + "Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [1,2,3,2]\nOutput:[1,2,3,3]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.", + "image": null + }, + { + "text": "Example 2: Input:obstacles = [2,2,1]\nOutput:[1,2,1]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.", + "image": null + }, + { + "text": "Example 3: Input:obstacles = [3,1,5,6,4,2]\nOutput:[1,1,2,3,2,2]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {\n int i = -1, cur = 0, lisSize = -1;\n int[] lis = new int[obstacles.length];\n int[] ans = new int[obstacles.length];\n \n for (int curHeight: obstacles) {\n if (i == -1 || lis[i] <= curHeight) {\n lis[++i] = curHeight;\n lisSize = i;\n } else {\n lisSize = search(lis, 0, i, curHeight);\n lis[lisSize] = curHeight;\n }\n \n ans[cur++] = lisSize + 1;\n }\n \n return ans; \n }\n \n private int search(int[] nums, int start, int end, int target) {\n int left = start, right = end;\n int boundary = 0;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] > target) {\n boundary = mid;\n right = mid - 1;\n } else left = mid + 1;\n }\n return boundary;\n }\n}\n", + "title": "1964. Find the Longest Valid Obstacle Course at Each Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n , where obstacles[i] describes the height of the i th obstacle. For every index i between 0 and n - 1 ( inclusive ), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n , where ans[i] is the length of the longest obstacle course for index i as described above .", + "description_images": [], + "constraints": [ + "You choose any number of obstacles between 0 and i inclusive .", + "You must include the i th obstacle in the course.", + "You must put the chosen obstacles in the same order as they appear in obstacles .", + "Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [1,2,3,2]\nOutput:[1,2,3,3]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.", + "image": null + }, + { + "text": "Example 2: Input:obstacles = [2,2,1]\nOutput:[1,2,1]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.", + "image": null + }, + { + "text": "Example 3: Input:obstacles = [3,1,5,6,4,2]\nOutput:[1,1,2,3,2,2]\nExplanation:The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_right\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n longest, res = [], []\n for i in range(len(obstacles)):\n idx = bisect_right(longest, obstacles[i])\n if idx == len(longest):\n longest.append(obstacles[i])\n else:\n longest[idx] = obstacles[i]\n res.append(idx+1)\n return res\n", + "title": "1964. Find the Longest Valid Obstacle Course at Each Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1] . If middleIndex == 0 , the left side sum is considered to be 0 . Similarly, if middleIndex == nums.length - 1 , the right side sum is considered to be 0 . Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-1,8,4]\nOutput:3\nExplanation:The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-1,4]\nOutput:2\nExplanation:The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,5]\nOutput:-1\nExplanation:There is no valid middleIndex.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 16.64%) | Memory: 42.4 MB (Top 52.37%)\n\nclass Solution {\n public int findMiddleIndex(int[] nums) {\n\n for(int i=0;i int:\n A = [0] + list(accumulate(nums)) + [0]\n total, n = sum(nums), len(nums)\n for i in range(n):\n if A[i] == total - A[i] - nums[i]:\n return i\n return -1 \n", + "title": "1991. Find the Middle Index in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A critical point in a linked list is defined as either a local maxima or a local minima . A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head , return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1] .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [2, 10^5 ] .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,1]\nOutput:[-1,-1]\nExplanation:There are no critical points in [3,1].", + "image": "https://assets.leetcode.com/uploads/2021/10/13/a1.png" + }, + { + "text": "Example 2: Input:head = [5,3,1,2,5,1,2]\nOutput:[1,3]\nExplanation:There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.", + "image": "https://assets.leetcode.com/uploads/2021/10/13/a2.png" + }, + { + "text": "Example 3: Input:head = [1,3,2,2,3,2,2,2,7]\nOutput:[3,3]\nExplanation:There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node.", + "image": "https://assets.leetcode.com/uploads/2021/10/14/a5.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 51.50%) | Memory: 100.7 MB (Top 69.00%)\n\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int res[]=new int[]{-1,-1};\n if(head==null||head.next==null||head.next.next==null) return res;\n int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1;\n ListNode prev=head,ptr=head.next;\n int idx=1,minD=Integer.MAX_VALUE;\n while(ptr!=null&&ptr.next!=null){\n if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val List[int]:\n idx, i = [], 1\n prev, cur = head, head.next\n while cur and cur.next:\n if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n idx.append(i)\n prev = cur\n cur = cur.next\n i += 1\n\n if len(idx) < 2:\n return [-1, -1]\n \n minDist = min(j - i for i, j in pairwise(idx))\n maxDist = idx[-1] - idx[0]\n\n return [minDist, maxDist]\n", + "title": "2058. Find the Minimum and Maximum Number of Nodes Between Critical Points", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer k , return the minimum number of Fibonacci numbers whose sum is equal to k . The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as:", + "description_images": [], + "constraints": [ + "F 1 = 1", + "F 2 = 1", + "F n = F n-1 + F n-2 for n > 2." + ], + "examples": [ + { + "text": "Example 1: Input:k = 7\nOutput:2\nExplanation:The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.", + "image": null + }, + { + "text": "Example 2: Input:k = 10\nOutput:2\nExplanation:For k = 10 we can use 2 + 8 = 10.", + "image": null + }, + { + "text": "Example 3: Input:k = 19\nOutput:3\nExplanation:For k = 19 we can use 1 + 5 + 13 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMinFibonacciNumbers(int k) {\n int ans = 0;\n\n while (k > 0) {\n\t\t\t// Run until solution is reached\n int fib2prev = 1;\n int fib1prev = 1;\n while (fib1prev <= k) {\n\t\t\t\t// Generate Fib values, stop when fib1prev is > k, we have the fib number we want stored in fib2prev\n int temp = fib2prev + fib1prev;\n fib2prev = fib1prev;\n fib1prev = temp;\n }\n k -= fib2prev;\n ans += 1;\n }\n return ans;\n }\n}\n", + "title": "1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer k , return the minimum number of Fibonacci numbers whose sum is equal to k . The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as:", + "description_images": [], + "constraints": [ + "F 1 = 1", + "F 2 = 1", + "F n = F n-1 + F n-2 for n > 2." + ], + "examples": [ + { + "text": "Example 1: Input:k = 7\nOutput:2\nExplanation:The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.", + "image": null + }, + { + "text": "Example 2: Input:k = 10\nOutput:2\nExplanation:For k = 10 we can use 2 + 8 = 10.", + "image": null + }, + { + "text": "Example 3: Input:k = 19\nOutput:3\nExplanation:For k = 19 we can use 1 + 5 + 13 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinFibonacciNumbers(self, k: int) -> int:\n fib_sq = [1, 1]\n while fib_sq[-1] + fib_sq[-2] <= k:\n fib_sq.append(fib_sq[-1]+fib_sq[-2])\n counter = 0\n for i in range(len(fib_sq)-1, -1, -1):\n if fib_sq[i] <= k:\n counter += 1\n k -= fib_sq[i]\n return counter\n", + "title": "1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and a positive integer k , return the most competitive subsequence of nums of size k . An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b . For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,2,6], k = 2\nOutput:[2,6]\nExplanation:Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,3,5,4,9,6], k = 4\nOutput:[2,3,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 96.43%) | Memory: 61.60 MB (Top 10.06%)\n\nclass Solution {\n public int[] mostCompetitive(int[] nums, int k) {\n int[] stack = new int[k];\n for(int i=0,j=0;i0 && stack[j-1]>nums[i] && j+nums.length-i>k) {\n j--;\n }\n if(j List[int]:\n\t\tend = len(nums) - k\n\t\tans = []\n\t\tfor num in nums:\n\t\t\twhile end and ans and num < ans[-1] :\n\t\t\t\tans.pop()\n\t\t\t\tend -= 1\n\t\t\tans.append(num)\n\t\t\n\t\treturn ans[:k]", + "title": "1673. Find the Most Competitive Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words , return the smallest string that contains each string in words as a substring . If there are multiple valid strings of the smallest length, return any of them . You may assume that no string in words is a substring of another string in words .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 12", + "1 <= words[i].length <= 20", + "words[i] consists of lowercase English letters.", + "All the strings of words are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"alex\",\"loves\",\"leetcode\"]\nOutput:\"alexlovesleetcode\"\nExplanation:All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\nOutput:\"gctaagttcatgcatc\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 66 ms (Top 42.04%) | Memory: 50.5 MB (Top 75.16%)\nclass Solution {\n public String shortestSuperstring(String[] words) {\n int n = words.length;\n int[][] discount = new int[n][n];\n for (int i = 0; i < n; i++){\n for (int j = 0; j < n; j++){\n for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->j and j->i\n if (words[j].startsWith(words[i].substring(k))){\n discount[i][j]=words[i].length()-k;\n break;\n }\n }\n }\n }\n int[][] dp = new int[1<0; k++){\n if ((i&1<=dp[i|1<dp[(1<dp[(1<0){\n ans[--idx]=words[end].substring((m&(m-1))==0?0:discount[path[m][end]][end]);\n m^=1< str:\n n = len(words)\n graph = [[0]*n for _ in range(n)] # graph as adjacency matrix \n \n for i in range(n):\n for j in range(n): \n if i != j: \n for k in range(len(words[j])): \n if words[i].endswith(words[j][:k]): \n graph[i][j] = len(words[j]) - k \n \n @cache\n def fn(prev, mask): \n \"\"\"Return length of shortest superstring & current choice of word.\"\"\"\n if mask == 0: return 0, None\n vv, kk = inf, None\n for k in range(n): \n if mask & 1< r) r = x;\n\n while (l < r) {\n int m = l + (r-l)/2;\n if (valid(a, m, h)) r = m;\n else l = m + 1;\n }\n\n return l;\n }\n\n private boolean valid(int[] a, int m, int h) {\n for (int x : a)\n if ((h -= (x + m-1)/m) < 0) return false;\n return true;\n }\n}", + "title": "1283. Find the Smallest Divisor Given a Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums and an integer threshold , we will choose a positive integer divisor , divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold . Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5 ). The test cases are generated so that there will be an answer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 10^6", + "nums.length <= threshold <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,9], threshold = 6\nOutput:5\nExplanation:We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [44,22,33,11,1], threshold = 5\nOutput:44", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def helper(self,nums,m):\n Sum = 0\n for n in nums:\n Sum += math.ceil(n/m)\n return Sum\n \n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n l,r = 1, max(nums)\n while l < r:\n mid = (l+r)//2\n Sum = self.helper(nums,mid)\n if Sum > threshold:\n l = mid + 1\n else:\n r = mid \n return r\n", + "title": "1283. Find the Smallest Divisor Given a Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n students in a class numbered from 0 to n - 1 . The teacher will give each student a problem starting with the student number 0 , then the student number 1 , and so on until the teacher reaches the student number n - 1 . After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k . There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i] , then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk .", + "description_images": [], + "constraints": [ + "chalk.length == n", + "1 <= n <= 10^5", + "1 <= chalk[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:chalk = [5,1,5], k = 22\nOutput:0\nExplanation:The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "image": null + }, + { + "text": "Example 2: Input:chalk = [3,4,1,2], k = 25\nOutput:1\nExplanation:The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for (int c : chalk) {\n sum += c;\n }\n long left = k % sum; \n for (int i = 0; i < chalk.length; i++){\n if(left >= chalk[i]){ \n left -= chalk[i];\n } else { \n return i;\n }\n }\n return -1; //just for return statement, put whatever you want here\n}\n}", + "title": "1894. Find the Student that Will Replace the Chalk", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n students in a class numbered from 0 to n - 1 . The teacher will give each student a problem starting with the student number 0 , then the student number 1 , and so on until the teacher reaches the student number n - 1 . After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k . There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i] , then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk .", + "description_images": [], + "constraints": [ + "chalk.length == n", + "1 <= n <= 10^5", + "1 <= chalk[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:chalk = [5,1,5], k = 22\nOutput:0\nExplanation:The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "image": null + }, + { + "text": "Example 2: Input:chalk = [3,4,1,2], k = 25\nOutput:1\nExplanation:The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x int:\n Trusted = [0] * (N+1)\n for (a, b) in trust:\n Trusted[a] -= 1\n Trusted[b] += 1\n \n for i in range(1, len(Trusted)):\n if Trusted[i] == N-1:\n return i\n return -1\n", + "title": "997. Find the Town Judge", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr of distinct integers and an integer k . A game will be played between the first two elements of the array (i.e. arr[0] and arr[1] ). In each round of the game, we compare arr[0] with arr[1] , the larger integer wins and remains at position 0 , and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game . It is guaranteed that there will be a winner of the game.", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "arr contains distinct integers.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,5,4,6,7], k = 2\nOutput:5\nExplanation:Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,2,1], k = 10\nOutput:3\nExplanation:3 will win the first 10 rounds consecutively.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getWinner(int[] arr, int k) {\n \n int winner =arr[0];\n int count=0;\n for(int i=1;iarr[i])\n count++;\n else\n {\n winner=arr[i];\n count=1;\n }\n if(count==k)\n return winner;\n }\n return winner;\n }\n}\n", + "title": "1535. Find the Winner of an Array Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr of distinct integers and an integer k . A game will be played between the first two elements of the array (i.e. arr[0] and arr[1] ). In each round of the game, we compare arr[0] with arr[1] , the larger integer wins and remains at position 0 , and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game . It is guaranteed that there will be a winner of the game.", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "arr contains distinct integers.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,5,4,6,7], k = 2\nOutput:5\nExplanation:Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,2,1], k = 10\nOutput:3\nExplanation:3 will win the first 10 rounds consecutively.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 506 ms (Top 96.6%) | Memory: 30.16 MB (Top 47.7%)\n\nclass Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n winner = arr[0]\n wins = 0\n for i in range(1,len(arr),1):\n if(winner > arr[i]): wins+=1 # increment wins count \n else:\n wins = 1 # new winner\n winner = arr[i]\n if(wins == k): break # if wins count is k, then return winner\n \n return winner", + "title": "1535. Find the Winner of an Array Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order . More formally, moving clockwise from the i th friend brings you to the (i+1) th friend for 1 <= i < n , and moving clockwise from the n th friend brings you to the 1 st friend. The rules of the game are as follows: Given the number of friends, n , and an integer k , return the winner of the game .", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, k = 2\nOutput:3\nExplanation:Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" + }, + { + "text": "Example 2: Input:n = 6, k = 5\nOutput:1\nExplanation:The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 26.7%) | Memory: 43.29 MB (Top 18.2%)\n\nclass Solution {\n public int findTheWinner(int n, int k) {\n\t // Initialisation of the LinkedList\n LinkedList participants = new LinkedList<>();\n for (int i = 1; i <= n; i++) {\n\t\t participants.add(i);\n\t\t}\n\t\t\n\t\tint lastKilled = 0;\n\t\t// Run the game\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < k-1; j++) {\n\t\t\t participants.add(participants.poll());\n\t\t\t}\n lastKilled = participants.poll();\n }\n // Return the last one killed\n return lastKilled;\n }\n}", + "title": "1823. Find the Winner of the Circular Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order . More formally, moving clockwise from the i th friend brings you to the (i+1) th friend for 1 <= i < n , and moving clockwise from the n th friend brings you to the 1 st friend. The rules of the game are as follows: Given the number of friends, n , and an integer k , return the winner of the game .", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, k = 2\nOutput:3\nExplanation:Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" + }, + { + "text": "Example 2: Input:n = 6, k = 5\nOutput:1\nExplanation:The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef findTheWinner(self, n: int, k: int) -> int:\n ls=list(range(1,n+1))\n while len(ls)>1:\n i=(k-1)%len(ls)\n ls.pop(i)\n ls=ls[i:]+ls[:i]\n \n return ls[0]\n", + "title": "1823. Find the Winner of the Circular Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return three consecutive integers (as a sorted array) that sum to num . If num cannot be expressed as the sum of three consecutive integers, return an empty array.", + "description_images": [], + "constraints": [ + "0 <= num <= 10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 33\nOutput:[10,11,12]\nExplanation:33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].", + "image": null + }, + { + "text": "Example 2: Input:num = 4\nOutput:[]\nExplanation:There is no way to express 4 as the sum of 3 consecutive integers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 76.35%) | Memory: 17.40 MB (Top 18.24%)\n\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n temp=(num-3)/3\n if floor(temp)==ceil(temp):\n return [int(temp),int(temp)+1,int(temp)+2]\n else:\n return []\n", + "title": "2177. Find Three Consecutive Integers That Sum to a Given Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums , where nums[i] is a digit between 0 and 9 ( inclusive ). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]\nOutput:8\nExplanation:The above diagram depicts the process from which we obtain the triangular sum of the array.", + "image": "https://assets.leetcode.com/uploads/2022/02/22/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5]\nOutput:5\nExplanation:Since there is only one element in nums, the triangular sum is the value of that element itself.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int triangularSum(int[] nums) {\n return find(nums,nums.length);\n }\n \n public int find(int[] a, int n){\n if(n == 1)\n return a[0];\n \n for(int i=0;i 1:\n arr = []\n for i in range(len(nums)-1):\n arr.append((nums[i] + nums[i+1]) % 10)\n nums = arr\n return nums[0]\n", + "title": "2221. Find Triangular Sum of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers arr and an integer target . You have to find two non-overlapping sub-arrays of arr each with a sum equal target . There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum . Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 1000", + "1 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,2,4,3], target = 3\nOutput:2\nExplanation:Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,3,4,7], target = 7\nOutput:2\nExplanation:Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,3,2,6,2,3,4], target = 6\nOutput:-1\nExplanation:We have only one sub-array of sum = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSumOfLengths(int[] arr, int target) { //this fits the case when there's negative number, kind like 560\n if (arr == null || arr.length == 0) return 0;\n Map map = new HashMap<>(); //sum - index\n map.put(0, -1);\n int sum = 0;\n for (int i = 0; i < arr.length; i++) { //record preSum and index\n sum += arr[i];\n map.put(sum, i);\n }\n sum = 0;\n int size = arr.length + 1, res = arr.length + 1;//note if we set size as MAX_VALUE the line 16 may overflow\n for (int i = 0; i < arr.length; i++) {\n sum += arr[i];\n if (map.containsKey(sum - target)) size = Math.min(size, i - map.get(sum - target)); //find the subarray from the previous index to current one\n if (map.containsKey(sum + target)) res = Math.min(res, size + map.get(sum + target) - i); //from the current index to next one, this avoid overlap\n }\n return res == arr.length + 1 ? -1 : res;\n }\n}\n", + "title": "1477. Find Two Non-overlapping Sub-arrays Each With Target Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of integers arr and an integer target . You have to find two non-overlapping sub-arrays of arr each with a sum equal target . There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum . Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 1000", + "1 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,2,4,3], target = 3\nOutput:2\nExplanation:Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,3,4,7], target = 7\nOutput:2\nExplanation:Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,3,2,6,2,3,4], target = 6\nOutput:-1\nExplanation:We have only one sub-array of sum = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float('inf')\n min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer and index of num in arr\n windowSum += num\n while windowSum > target: \n\t\t\t# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target\n windowSum -= arr[l]\n l += 1\n\t\t\t# the case when we found a new target sub-array, i.e. current window\n if windowSum == target:\n\t\t\t # length of current window\n curLen = r - l + 1\n\t\t\t\t# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window: \n\t\t\t\t# avoid overlap with cur window\n\t\t\t\t# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping\n\t\t\t\t# , if < res, update res.\n res = min(res, curLen + min_till[l - 1])\n\t\t\t\t# Everytime we found a target window, update the min_till of current right end of the window, \n\t\t\t\t# for future use when sum up to new length of sum_of_two_subarray and update the res.\n min_till[r] = min(curLen, min_till[r - 1])\n else:\n\t\t\t# If windowSum < target: window with current arr[r] as right end does not have any target subarry, \n\t\t\t# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1. \n min_till[r] = min_till[r - 1]\n return res if res < float('inf') else -1\n\t\nTime = O(n): when sliding the window, left and right pointers traverse the array once.\nSpace = O(n): we use one additional list min_till[] to record min length of target subarray till index i.", + "title": "1477. Find Two Non-overlapping Sub-arrays Each With Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings nums containing n unique binary strings each of length n , return a binary string of length n that does not appear in nums . If there are multiple answers, you may return any of them .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 16", + "nums[i].length == n", + "nums[i] is either '0' or '1' .", + "All the strings of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"01\",\"10\"]\nOutput:\"11\"\nExplanation:\"11\" does not appear in nums. \"00\" would also be correct.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"00\",\"01\"]\nOutput:\"11\"\nExplanation:\"11\" does not appear in nums. \"10\" would also be correct.", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"111\",\"011\",\"001\"]\nOutput:\"101\"\nExplanation:\"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder ans= new StringBuilder(); \n for(int i=0; i List[List[int]]:\n matrix = []\n for row in range(len(rowSum)):\n data, array = rowSum[row], []\n for col in range(len(colSum)):\n if data == 0 or colSum[col] == 0:\n array.append(0)\n elif data > colSum[col]:\n data -= colSum[col]\n array.append(colSum[col])\n colSum[col] = 0\n else:\n array.append(data)\n colSum[col] -= data\n data = 0\n matrix.append(array)\n\n return matrix\n \n \n\n\n\n\n\n\n\n", + "title": "1605. Find Valid Matrix Given Row and Column Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Given a 2D integer array moves where moves[i] = [row i , col i ] indicates that the i th move will be played on grid[row i ][col i ] . return the winner of the game if it exists ( A or B ). In case the game ends in a draw return \"Draw\" . If there are still movements to play return \"Pending\" . You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe ), the grid is initially empty, and A will play first.", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player A always places 'X' characters, while the second player B always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never on filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput:\"A\"\nExplanation:A wins, they always play first.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo1-grid.jpg" + }, + { + "text": "Example 2: Input:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput:\"B\"\nExplanation:B wins.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo2-grid.jpg" + }, + { + "text": "Example 3: Input:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput:\"Draw\"\nExplanation:The game ends in a draw since there are no moves to make.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo3-grid.jpg" + } + ], + "follow_up": null, + "solution": "/**\nHere is my solution : \n\nTime Complexity O(M) \nSpace Complaexity O(1)\n*/\n\nclass Solution {\n public String tictactoe(int[][] moves) {\n \n int [][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals\n \n for(int turn =0 ; turn < moves.length ; turn++){\n \n\t\t\tint AorB =-1;\n if(turn%2==0){AorB=1;}\n \n rcd[0][moves[turn][0]]+= AorB; \n rcd[1][moves[turn][1]]+= AorB; \n \n if(moves[turn][0]== moves[turn][1]){rcd[2][0]+=AorB;} // first diagonal\n if(moves[turn][0]+moves[turn][1]-2 == 0){rcd[2][1]+=AorB;} //2nd diagonal \n \n if( Math.abs(rcd[0][moves[turn][0]]) == 3 || Math.abs(rcd[1][moves[turn][1]]) == 3 \n ||Math.abs(rcd[2][0]) ==3 || Math.abs(rcd[2][1]) ==3 ){\n \n\t\t\t return AorB == 1 ? \"A\" : \"B\"; }\n } \n \n return moves.length == 9 ? \"Draw\" : \"Pending\";\n \n }\n}\n\n", + "title": "1275. Find Winner on a Tic Tac Toe Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Given a 2D integer array moves where moves[i] = [row i , col i ] indicates that the i th move will be played on grid[row i ][col i ] . return the winner of the game if it exists ( A or B ). In case the game ends in a draw return \"Draw\" . If there are still movements to play return \"Pending\" . You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe ), the grid is initially empty, and A will play first.", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player A always places 'X' characters, while the second player B always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never on filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput:\"A\"\nExplanation:A wins, they always play first.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo1-grid.jpg" + }, + { + "text": "Example 2: Input:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput:\"B\"\nExplanation:B wins.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo2-grid.jpg" + }, + { + "text": "Example 3: Input:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput:\"Draw\"\nExplanation:The game ends in a draw since there are no moves to make.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n wins = [\n [(0, 0), (0, 1), (0, 2)],\n [(1, 0), (1, 1), (1, 2)],\n [(2, 0), (2, 1), (2, 2)],\n [(0, 0), (1, 0), (2, 0)],\n [(0, 1), (1, 1), (2, 1)],\n [(0, 2), (1, 2), (2, 2)],\n [(0, 0), (1, 1), (2, 2)],\n [(0, 2), (1, 1), (2, 0)],\n ]\n \n def checkWin(S):\n for win in wins:\n flag = True\n for pos in win:\n if pos not in S:\n flag = False\n break\n if flag:\n return True\n return False\n \n A, B = set(), set()\n for i, (x, y) in enumerate(moves):\n if i % 2 == 0:\n A.add((x, y))\n else:\n B.add((x, y))\n \n if checkWin(A):\n return 'A'\n elif checkWin(B):\n return 'B'\n \n return \"Draw\" if len(moves) == 9 else \"Pending\"\n", + "title": "1275. Find Winner on a Tic Tac Toe Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings words and a string chars . A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, chars.length <= 100", + "words[i] and chars consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput:6\nExplanation:The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput:10\nExplanation:The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 90.62%) | Memory: 53.5 MB (Top 72.75%)\nclass Solution {\n public int countCharacters(String[] words, String chars) {\n int[] freq = new int[26];\n for (int i = 0; i < chars.length(); i++) {\n // char - char is a kind of clever way to get the position of\n // the character in the alphabet. 'a' - 'a' would give you 0.\n // 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.\n freq[chars.charAt(i) - 'a'] ++;\n }\n\n int result = 0;\n for (String word : words) {\n int[] copy = Arrays.copyOf(freq, freq.length);\n boolean pass = true;\n for (int j = 0; j < word.length(); j++) {\n // decrement the frequency of this char in array for using\n // if there are less than 1 chance for using this character, invalid,\n // move to next word in words\n if (-- copy[word.charAt(j) - 'a'] < 0) {\n pass = false;\n break;\n }\n }\n if (pass) {\n result += word.length();\n }\n }\n return result;\n }\n}", + "title": "1160. Find Words That Can Be Formed by Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words and a string chars . A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, chars.length <= 100", + "words[i] and chars consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput:6\nExplanation:The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput:10\nExplanation:The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countCharacters(self, words, chars):\n \"\"\"\n :type words: List[str]\n :type chars: str\n :rtype: int\n \"\"\"\n b = set(chars)\n anwser = 0\n for i in words:\n a = set(i)\n if a.issubset(b):\n test = [o for o in a if chars.count(o) < i.count(o)]\n if len(test) == 0: \n anwser += len(i)\n return anwser\n", + "title": "1160. Find Words That Can Be Formed by Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND ) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length . Return the XOR sum of the aforementioned list .", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4 , and the XOR sum of [3] is equal to 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3], arr2 = [6,5]\nOutput:0\nExplanation:The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [12], arr2 = [4]\nOutput:4\nExplanation:The list = [12 AND 4] = [4]. The XOR sum = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 19.55%) | Memory: 56.30 MB (Top 85.71%)\n\nclass Solution {\n public int getXORSum(int[] arr1, int[] arr2) {\n \n int xor1 = 0, xor2 = 0;\n \n for (int arr : arr1) {\n xor1 ^= arr;\n }\n \n for (int arr : arr2) {\n xor2 ^= arr;\n }\n \n return xor1 & xor2;\n }\n}\n", + "title": "1835. Find XOR Sum of All Pairs Bitwise AND", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND ) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length . Return the XOR sum of the aforementioned list .", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4 , and the XOR sum of [3] is equal to 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3], arr2 = [6,5]\nOutput:0\nExplanation:The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [12], arr2 = [4]\nOutput:4\nExplanation:The list = [12 AND 4] = [4]. The XOR sum = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2209 ms (Top 51.91%) | Memory: 30.3 MB (Top 21.37%)\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)\n return xor_lis(arr1) & xor_lis(arr2)", + "title": "1835. Find XOR Sum of All Pairs Bitwise AND", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array digits , where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3] , integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.", + "description_images": [], + "constraints": [ + "The integer consists of the concatenation of three elements from digits in any arbitrary order.", + "The integer does not have leading zeros .", + "The integer is even ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [2,1,3,0]\nOutput:[102,120,130,132,210,230,302,310,312,320]\nExplanation:All the possible integers that follow the requirements are in the output array. \nNotice that there are nooddintegers or integers withleading zeros.", + "image": null + }, + { + "text": "Example 2: Input:digits = [2,2,8,8,2]\nOutput:[222,228,282,288,822,828,882]\nExplanation:The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882.", + "image": null + }, + { + "text": "Example 3: Input:digits = [3,7,5]\nOutput:[]\nExplanation:Noevenintegers can be formed using the given digits.", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n\nAs we know that we want unique numbers of 3 digits only that too only even. so first we \ngather the frequency of all the digits we have, then we iterate from 100 to 999 ( all possible 3 digits numbers, 100,102,104...\nall possible even 3 digit numbers). for ex we are iterating and we are\nat 104 so we will see that if we have digits\n1,0,4 in our database if yes then we can make this number from our\navailable digits given to us.\n\n\nTime complexity : O(digits.length) // due to making of frequency map\nSpace Complexity : O(1) //fixed map array space for digits 0 to 9\n*/\n\nclass Solution {\n public int[] findEvenNumbers(int[] digits) {\n int [] map = new int[10]; // for freq of 0 to 9 (digits are fixed)\n \n for(int i = 0;i arr = new ArrayList<>();\n \n for(int i = 100;i<=999;i = i + 2){ //will always runs from 100 to 999 \n int num = i;\n int [] freq = new int[10];\n while(num > 0){ // will always run 3 times\n int rem = num % 10;\n freq[rem]++;\n num = num/10;\n }\n \n boolean res = findans(freq,map);\n if(res) arr.add(i);\n }\n \n int [] ans = new int[arr.size()]; //logic for arraylist to array conversion\n for(int i = 0;i database[i]) return false;\n }\n return true;\n }\n}\n", + "title": "2094. Finding 3-Digit Even Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array digits , where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3] , integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.", + "description_images": [], + "constraints": [ + "The integer consists of the concatenation of three elements from digits in any arbitrary order.", + "The integer does not have leading zeros .", + "The integer is even ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [2,1,3,0]\nOutput:[102,120,130,132,210,230,302,310,312,320]\nExplanation:All the possible integers that follow the requirements are in the output array. \nNotice that there are nooddintegers or integers withleading zeros.", + "image": null + }, + { + "text": "Example 2: Input:digits = [2,2,8,8,2]\nOutput:[222,228,282,288,822,828,882]\nExplanation:The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882.", + "image": null + }, + { + "text": "Example 3: Input:digits = [3,7,5]\nOutput:[]\nExplanation:Noevenintegers can be formed using the given digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n hmap, res = defaultdict(int), []\n for num in digits:\n hmap[num] += 1 #counting frequency of digits of digits array\n \n for num in range(100, 999, 2): #step 2 because we need even numbers\n checker = defaultdict(int)\n for digit in str(num):\n checker[int(digit)] += 1 #counting frequency of digits of num\n \n\t\t\t#check if every digit in num is in digits array and its frequency is less than or equal to its frequency in digits array\n if all(map(lambda x: x in hmap and checker[x] <= hmap[x], checker)):\n res.append(num)\n \n return res\n", + "title": "2094. Finding 3-Digit Even Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers, m and k , and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:", + "description_images": [], + "constraints": [ + "MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k .", + "void addElement(int num) Inserts a new element num into the stream.", + "int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]Output[null, null, null, -1, null, 3, null, null, null, 5]ExplanationMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be[3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be[5].\n // The average of [5] equals 5/1 = 5, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "class MKAverage {\n class Node implements Comparable {\n int val;\n int time;\n \n Node(int val, int time) {\n this.val = val;\n this.time = time;\n }\n \n @Override\n public int compareTo(Node other) {\n return (this.val != other.val ? this.val - other.val \n : this.time - other.time);\n }\n }\n \n private TreeSet set = new TreeSet<>(); // natural order\n private Deque queue = new LinkedList<>();\n private Node kLeft;\n private Node kRight;\n \n private int m, k;\n \n private int time = 0;\n private int sum = 0;\n\n public MKAverage(int m, int k) {\n this.m = m;\n this.k = k;\n }\n \n public void addElement(int num) {\n Node node = new Node(num, time++);\n\n addNode(node);\n removeNode();\n \n if (time == m) init();\n }\n \n private void init() {\n int i = 0;\n for (Node node : set) {\n if (i < k-1);\n else if (i == k-1) kLeft = node;\n else if (i < m-k) sum += node.val;\n else if (i == m-k) {\n kRight = node;\n return;\n }\n \n i++;\n }\n return;\n }\n \n private void addNode(Node node) {\n queue.offerLast(node);\n set.add(node);\n \n if (queue.size() <= m) return;\n \n if (node.compareTo(kLeft) < 0) {\n sum += kLeft.val;\n kLeft = set.lower(kLeft);\n } else if (node.compareTo(kRight) > 0) {\n sum += kRight.val;\n kRight = set.higher(kRight);\n } else {\n sum += node.val;\n } \n }\n \n private void removeNode() {\n if (queue.size() <= m) return;\n \n Node node = queue.pollFirst();\n \n if (node.compareTo(kLeft) <= 0) {\n kLeft = set.higher(kLeft);\n sum -= kLeft.val;\n } else if (node.compareTo(kRight) >= 0) {\n kRight = set.lower(kRight);\n sum -= kRight.val;\n } else {\n sum -= node.val;\n }\n \n set.remove(node);\n }\n \n public int calculateMKAverage() {\n return (queue.size() < m ? -1 : sum / (m - 2 * k));\n }\n}\n", + "title": "1825. Finding MK Average", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two integers, m and k , and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:", + "description_images": [], + "constraints": [ + "MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k .", + "void addElement(int num) Inserts a new element num into the stream.", + "int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]Output[null, null, null, -1, null, 3, null, null, null, 5]ExplanationMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be[3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be[5].\n // The average of [5] equals 5/1 = 5, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\n\nclass MKAverage:\n\n MAX_NUM = 10 ** 5\n def __init__(self, m: int, k: int):\n \n self.m = m\n self.k = k\n \n # sorted list\n self.sl = SortedList([0] * m)\n\t\t# sum of k smallest elements\n self.sum_k = 0\n\t\t# sum of m - k smallest elements\n self.sum_m_k = 0\n \n # queue for the last M elements if the stream\n self.q = deque([0] * m)\n \n def addElement(self, num: int) -> None:\n # Time: O(logm)\n\t\t\n m, k, q, sl = self.m, self.k, self.q, self.sl \n \n # update q\n q.append(num)\n old = q.popleft()\n \n # remove the old num\n r = sl.bisect_right(old)\n\t\t# maintain sum_k\n if r <= k:\n self.sum_k -= old\n self.sum_k += sl[k]\n\t\t# maintain sum_m_k\n if r <= m - k:\n self.sum_m_k -= old\n self.sum_m_k += sl[m-k]\n # remove the old num\n sl.remove(old)\n \n # add the new num\n r = sl.bisect_right(num)\n if r < k:\n self.sum_k -= sl[k-1]\n self.sum_k += num\n if r < m - k:\n self.sum_m_k -= sl[m - k - 1]\n self.sum_m_k += num\n \n sl.add(num)\n \n return\n\n def calculateMKAverage(self) -> int:\n\t\t# Time: O(1)\n if self.sl[0] == 0:\n return -1\n return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)\n", + "title": "1825. Finding MK Average", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 . You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:", + "description_images": [], + "constraints": [ + "FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2 .", + "void add(int index, int val) Adds val to nums2[index] , i.e., apply nums2[index] += val .", + "int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot ." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]Output[null, 8, null, 2, 1, null, null, 11]ExplanationFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "class FindSumPairs {\n\n private int [] nums1;\n private int [] nums2;\n Map map = new HashMap<>();\n public FindSumPairs(int[] nums1, int[] nums2) {\n this.nums1 = nums1;\n this.nums2 = nums2;\n for (int number : nums2) {\n map.put(number, map.getOrDefault(number, 0) + 1);\n } \n \n }\n \n public void add(int index, int val) {\n map.put(nums2[index], map.get(nums2[index]) - 1);\n nums2[index] += val;\n map.put(nums2[index], map.getOrDefault(nums2[index], 0) + 1);\n }\n \n public int count(int tot) {\n int result = 0;\n for (int number : nums1) {\n if (map.containsKey(tot - number)) {\n result += map.get(tot - number);\n }\n }\n return result;\n }\n}\n\n/**\n * Your FindSumPairs object will be instantiated and called as such:\n * FindSumPairs obj = new FindSumPairs(nums1, nums2);\n * obj.add(index,val);\n * int param_2 = obj.count(tot);\n */\n", + "title": "1865. Finding Pairs With a Certain Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 . You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:", + "description_images": [], + "constraints": [ + "FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2 .", + "void add(int index, int val) Adds val to nums2[index] , i.e., apply nums2[index] += val .", + "int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot ." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]Output[null, 8, null, 2, 1, null, null, 11]ExplanationFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1039 ms (Top 5.41%) | Memory: 80.00 MB (Top 22.7%)\n\nclass FindSumPairs:\n\n def __init__(self, nums1: List[int], nums2: List[int]):\n self.nums1 = sorted(nums1)\n self.nums2 = nums2\n self.hash2 = defaultdict(int)\n for n in nums2:\n self.hash2[n] += 1\n\n def add(self, index: int, val: int) -> None:\n self.hash2[self.nums2[index]] -= 1\n self.nums2[index] += val\n self.hash2[self.nums2[index]] += 1\n\n def count(self, tot: int) -> int:\n result = 0\n for n in self.nums1:\n if n >= tot:\n break\n result += self.hash2[tot - n]\n return result\n", + "title": "1865. Finding Pairs With a Certain Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the logs for users' actions on LeetCode, and an integer k . The logs are represented by a 2D integer array logs where each logs[i] = [ID i , time i ] indicates that the user with ID i performed an action at the minute time i . Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j ( 1 <= j <= k ), answer[j] is the number of users whose UAM equals j . Return the array answer as described above .", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 10^4", + "0 <= ID i <= 10^9", + "1 <= time i <= 10^5", + "k is in the range [The maximum UAM for a user, 10^5 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput:[0,2,0,0,0]\nExplanation:The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1,1],[2,2],[2,3]], k = 4\nOutput:[1,1,0,0]\nExplanation:The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 74.46%) | Memory: 56.30 MB (Top 38.32%)\n\nclass Solution {\n public int[] findingUsersActiveMinutes(int[][] logs, int k) {\n // create a hashmap to record the ids of users \n // and a set to store the minutes in which they were active\n Map> map = new HashMap<>();\n for (int[] l : logs) {\n // l[0] -> id, l[1] -> active minute\n map.putIfAbsent(l[0], new HashSet<>()); // if new id\n map.get(l[0]).add(l[1]); // add the minute of activeness to the set\n }\n\n // create answer array\n int[] ans = new int[k]; \n for (int id : map.keySet()) {\n // the set contains all the minutes in which the id was active\n // so the set size will be the number of active minutes\n // or the 'User Active Minutes' (UAM)\n int uam = map.get(id).size();\n // each index in ans array is a UAM, \n // and we need to put the number of users having that UAM\n // whenever we enocunter a UAM, we increment the value in array\n // which means we have found one more user with the same UAM\n ans[uam-1]++; // since array is 1 based indexing, we substract 1\n }\n\n return ans; // return ans array\n }\n}\n", + "title": "1817. Finding the Users Active Minutes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the logs for users' actions on LeetCode, and an integer k . The logs are represented by a 2D integer array logs where each logs[i] = [ID i , time i ] indicates that the user with ID i performed an action at the minute time i . Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j ( 1 <= j <= k ), answer[j] is the number of users whose UAM equals j . Return the array answer as described above .", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 10^4", + "0 <= ID i <= 10^9", + "1 <= time i <= 10^5", + "k is in the range [The maximum UAM for a user, 10^5 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput:[0,2,0,0,0]\nExplanation:The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1,1],[2,2],[2,3]], k = 4\nOutput:[1,1,0,0]\nExplanation:The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n ret = [0] * k # UAM store\n user_acts = {} # User minutes store\n \n # Adding user minutes to hash table\n\t\tfor log in logs:\n if user_acts.get(log[0], 0):\n user_acts[log[0]].append(log[1])\n else:\n user_acts[log[0]] = [log[1]]\n \n # Calculating UAM\n\t\tfor k, v in user_acts.items():\n l = len(set(v))\n ret[l-1] += 1\n \n return ret\n", + "title": "1817. Finding the Users Active Minutes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4\nOutput:4\nExplanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/* The isBadVersion API is defined in the parent class VersionControl.\n boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n public int firstBadVersion(int n) {\n int s = 0; int e = n;\n \n while(s < e) {\n int mid = s +(e-s)/2;\n \n if(isBadVersion(mid)){\n e = mid ;\n } else {\n s = mid +1;\n }\n }\n return e ;\n }\n}\n", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4\nOutput:4\nExplanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n fast, slow = int(n/2), n\n diff = abs(fast-slow)\n while isBadVersion(fast) == isBadVersion(slow) or diff > 1:\n fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast\n diff = abs(fast-slow)\n return fast if isBadVersion(fast) else slow\n", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms you need to visit, labeled from 0 to n - 1 . Each day is labeled, starting from 0 . You will go in and visit one room a day. Initially on day 0 , you visit room 0 . The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n : Return the label of the first day where you have been in all the rooms . It can be shown that such a day exists. Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Assuming that on a day, you visit room i ,", + "if you have been in room i an odd number of times ( including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i ;", + "if you have been in room i an even number of times ( including the current visit), on the next day you will visit room (i + 1) mod n ." + ], + "examples": [ + { + "text": "Example 1: Input:nextVisit = [0,0]\nOutput:2\nExplanation:- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n  On the next day you will visit room nextVisit[0] = 0\n- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n  On the next day you will visit room (0 + 1) mod 2 = 1\n- On day 2, you visit room 1. This is the first day where you have been in all the rooms.", + "image": null + }, + { + "text": "Example 2: Input:nextVisit = [0,0,2]\nOutput:6\nExplanation:Your room visiting order for each day is: [0,0,1,0,0,1,2,...].\nDay 6 is the first day where you have been in all the rooms.", + "image": null + }, + { + "text": "Example 3: Input:nextVisit = [0,1,2,0]\nOutput:6\nExplanation:Your room visiting order for each day is: [0,0,1,1,2,2,3,...].\nDay 6 is the first day where you have been in all the rooms.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstDayBeenInAllRooms(int[] nextVisit) {\n int rooms = nextVisit.length;\n long dp[] = new long[rooms];\n int mod = (int)(1e9)+7;\n for (int i=1 ; i int:\n\t n:int = len(nextVisit)\n days:List[int] = n*[0] # days[i] is the number of days it takes to first reach room i\n MOD = pow(10, 9) + 7\n for i in range(0,n-1):\n # First we are already at room i. days[i] days has passed\n days[i+1] = days[i]\n # lets go from room i to room i+1. \n # When we first visit room i, we need to visit room i again (so room i is visited twice, which is an even number), then we can visit room i+1\n # after we fist visit room i, the next day we will visit room (nextVisit[i]). \n days[i+1] = (days[i+1] + 1) % MOD\n # Then the problem becomes \"how to go from room (nextVisit[i]) back to room i\". The step is (days[i] - days[nextVisit[i]])\n days[i+1] = (days[i+1] + days[i] - days[nextVisit[i]]) % MOD\n # Then, in the next day we go from room i to i+1\n days[i+1] = (days[i+1] + 1) % MOD\n \n return days[n-1]\n", + "title": "1997. First Day Where You Have Been in All the Rooms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of lowercase English letters, return the first letter to appear twice . Note :", + "description_images": [], + "constraints": [ + "A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b .", + "s will contain at least one letter that appears twice." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccbaacz\"\nOutput:\"c\"\nExplanation:The letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdd\"\nOutput:\"d\"\nExplanation:The only letter that appears twice is 'd' so we return 'd'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 23.65%)\n\nclass Solution {\n public char repeatedCharacter(String s) {\n HashSet set = new HashSet<>();//Create a set of characters\n for(int i = 0 ; i < s.length() ; i++){\n if(set.contains(s.charAt(i))) return s.charAt(i);//If the set already contains the current character, then it is the required ans\n set.add(s.charAt(i));\n }\n return 'a';//As it is given in the question that there is at least one letter that appears twice, therefore it is certain that the ans will be found before we reach this statement. So, just adding any random return statement so that there is no error in the code.\n }\n}\n", + "title": "2351. First Letter to Appear Twice", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s consisting of lowercase English letters, return the first letter to appear twice . Note :", + "description_images": [], + "constraints": [ + "A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b .", + "s will contain at least one letter that appears twice." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccbaacz\"\nOutput:\"c\"\nExplanation:The letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdd\"\nOutput:\"d\"\nExplanation:The only letter that appears twice is 'd' so we return 'd'.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def repeatedCharacter(self, s: str) -> str:\n occurences = defaultdict(int)\n for char in s:\n occurences[char] += 1\n if occurences[char] == 2:\n return char\n", + "title": "2351. First Letter to Appear Twice", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an unsorted integer array nums , return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0]\nOutput:3\nExplanation:The numbers in the range [1,2] are all in the array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,-1,1]\nOutput:2\nExplanation:1 is in the array but 2 is missing.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,8,9,11,12]\nOutput:1\nExplanation:The smallest positive integer 1 is missing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 91.14%) | Memory: 57.8 MB (Top 74.85%)\nclass Solution {\n public int firstMissingPositive(int[] nums) {\n //cyclic sort\n int i = 0;\n while (i0 && nums[i]<=nums.length && nums[i]!=nums[correct]){\n swap(nums,i,correct);\n }else{\n i++;\n }\n }\n //linear search to find the missing number\n for(int index=0;index int:\n mn = float('inf')\n mx = 0\n numsSet = set()\n\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] > 0:\n if nums[i] < mn:\n mn = nums[i]\n if nums[i] > mx:\n mx = nums[i]\n numsSet.add(nums[i])\n del nums[i]\n\n if mn >= 2:\n return 1\n if len(numsSet) == mx:\n return mx + 1\n for i in range(2, len(numsSet) + 1):\n if i not in numsSet:\n return i", + "title": "41. First Missing Positive", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the first non-repeating character in it and return its index . If it does not exist, return -1 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"\nOutput:0", + "image": null + }, + { + "text": "Example 2: Input:s = \"loveleetcode\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabb\"\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstUniqChar(String s) {\n HashMaphmap=new HashMap<>();\n for(int i=0;i int:\n ls=[]\n for i in range(len(s)):\n x=s.count(s[i])\n if x==1:\n return i\n return -1\n", + "title": "387. First Unique Character in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a string array answer ( 1-indexed ) where :", + "description_images": [], + "constraints": [ + "answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5 .", + "answer[i] == \"Fizz\" if i is divisible by 3 .", + "answer[i] == \"Buzz\" if i is divisible by 5 .", + "answer[i] == i (as a string) if none of the above conditions are true." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[\"1\",\"2\",\"Fizz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 15\nOutput:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.61%) | Memory: 45.20 MB (Top 33.59%)\n\nclass Solution {\n public List fizzBuzz(int n) {\n List ans = new ArrayList<>();\n for (int i = 1; i <= n; i++) {\n if (i % 15 == 0) {\n ans.add(\"FizzBuzz\");\n } else if (i % 3 == 0) {\n ans.add(\"Fizz\");\n } else if (i % 5 == 0) {\n ans.add(\"Buzz\");\n } else {\n ans.add(String.valueOf(i));\n }\n }\n \n return ans; \n }\n}\n\n// TC: O(n), SC: O(n)\n", + "title": "412. Fizz Buzz", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return a string array answer ( 1-indexed ) where :", + "description_images": [], + "constraints": [ + "answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5 .", + "answer[i] == \"Fizz\" if i is divisible by 3 .", + "answer[i] == \"Buzz\" if i is divisible by 5 .", + "answer[i] == i (as a string) if none of the above conditions are true." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[\"1\",\"2\",\"Fizz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 15\nOutput:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n result = []\n for i in range(1, n+1):\n if i % 3 == 0 and i % 5 == 0:\n result.append('FizzBuzz')\n elif i % 3 == 0:\n result.append('Fizz')\n elif i % 5 == 0:\n result.append('Buzz')\n else:\n result.append(str(i))\n return result\n", + "title": "412. Fizz Buzz", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer . This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null .", + "description_images": [], + "constraints": [ + "The number of Nodes will not exceed 1000 .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput:[1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,null,3]\nOutput:[1,3,2]\nExplanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]\nExplanation:There could be empty list in the input.", + "image": null + }, + { + "text": "Example 1 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]", + "image": null + }, + { + "text": "[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.2 MB (Top 95.78%)\nclass Solution {\n public Node flatten(Node head) {\n Node curr = head ; // for traversal\n Node tail = head; // for keeping the track of previous node\n Stack stack = new Stack<>(); // for storing the reference of next node when child node encounters\n while(curr != null){\n if(curr.child != null){ // if there is a child\n Node child = curr.child; // creating a node for child\n if(curr.next != null){ // if there is list after we find child a child\n stack.push(curr.next); // pushing the list to the stack\n curr.next.prev = null; // pointing its previous to null\n }\n curr.next = child; // pointing the current's reference to child\n child.prev = curr; // pointing child's previous reference to current.\n curr.child = null; // pointing the current's child pointer to null\n }\n tail = curr ; // for keeping track of previous nodes\n curr= curr.next; // traversing\n }\n while(!stack.isEmpty()){ // checking if the stack has still nodes in it.\n curr = stack.pop(); // getting the last node of the list pushed into the stack\n tail.next = curr; // pointing the previos node to the last node\n curr.prev = tail; // pointing previos pointer of the last node to the previos node.\n while( curr != null){ // traversing the last node's popped out of stack\n tail = curr;\n curr = curr.next ;\n }\n }\n return head;\n }\n}", + "title": "430. Flatten a Multilevel Doubly Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer . This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null .", + "description_images": [], + "constraints": [ + "The number of Nodes will not exceed 1000 .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput:[1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,null,3]\nOutput:[1,3,2]\nExplanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]\nExplanation:There could be empty list in the input.", + "image": null + }, + { + "text": "Example 1 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]", + "image": null + }, + { + "text": "[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': \n node = head\n while node:\n if node.child: # If there is a child travel to last node of the child\n child = node.child\n while child.next:\n child = child.next\n child.next = node.next # Update the next of child to the the next of the current node\n if node.next: # update the prev of the next node to chile to make it valid doubly linked list\n node.next.prev = child\n node.next = node.child # Update the child to become the next of the current\n node.next.prev = node # update the prev of the next node to chile to make it valid doubly linked list\n node.child = None # Make the child of the current node None to fulfill the requirements\n node = node.next\n return head\n\n# time and space complexity\n# time: O(n)\n# space: O(1)\n", + "title": "430. Flatten a Multilevel Doubly Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\":", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]\nOutput:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void flatten(TreeNode root) {\n TreeNode curr=root;\n while(curr!=null)\n {\n if(curr.left!=null)\n {\n TreeNode prev=curr.left;\n while(prev.right!=null)\n prev=prev.right;\n prev.right=curr.right;\n curr.right=curr.left; \n curr.left=null; \n }\n curr=curr.right;\n }\n }\n}\n", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\":", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]\nOutput:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 52.37%) | Memory: 15.1 MB (Top 89.03%)\n#Call the right of the tree node till the node root left and right is not None\n#After reaching the bottom of the tree make the root.right = prev and\n#root.left = None and then prev = None\n#Initially prev will point to None but this is used to point the previously visited root node\n#Prev pointer helps us to change the values from left to right\nclass Solution:\n def flatten(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n prev = None #You can also define that variable inside the init function using self keyword\n def dfs(root):\n nonlocal prev\n\n if not root:\n return\n\n dfs(root.right)\n dfs(root.left)\n\n root.right = prev\n root.left = None\n prev = root\n\n dfs(root)\n# If the above solution is hard to understand than one can do level order traversal\n#Using Stack DS but this will increase the space complexity to O(N).", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a nested list of integers nestedList . Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: Your code will be tested with the following pseudocode: If res matches the expected flattened list, then your code will be judged as correct.", + "description_images": [], + "constraints": [ + "NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList .", + "int next() Returns the next integer in the nested list.", + "boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input:nestedList = [[1,1],2,[1,1]]\nOutput:[1,1,2,1,1]\nExplanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nestedList = [1,[4,[6]]]\nOutput:[1,4,6]\nExplanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].", + "image": null + }, + { + "text": "initialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 77.47%) | Memory: 46.1 MB (Top 81.31%)\npublic class NestedIterator implements Iterator {\n List list=new ArrayList();\n void flatten(List nestedList){\n for(NestedInteger nested:nestedList){\n if(nested.isInteger())\n list.add(nested.getInteger());\n else\n flatten(nested.getList());\n }\n }\n public NestedIterator(List nestedList) {\n flatten(nestedList);\n }\n int index=0;\n @Override\n public Integer next() {\n return list.get(index++);\n }\n\n @Override\n public boolean hasNext() {\n return index nestedList) Initializes the iterator with the nested list nestedList .", + "int next() Returns the next integer in the nested list.", + "boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input:nestedList = [[1,1],2,[1,1]]\nOutput:[1,1,2,1,1]\nExplanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nestedList = [1,[4,[6]]]\nOutput:[1,4,6]\nExplanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].", + "image": null + }, + { + "text": "initialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res", + "image": null + } + ], + "follow_up": null, + "solution": "class NestedIterator:\n def __init__(self, nestedList: [NestedInteger]):\n self.flattened_lst = self.flattenList(nestedList)\n self.idx = 0\n \n def next(self) -> int:\n if self.idx >= len(self.flattened_lst):\n raise Exception(\"Index out of bound\")\n self.idx += 1\n return self.flattened_lst[self.idx-1]\n \n def hasNext(self) -> bool:\n return self.idx < len(self.flattened_lst)\n \n def flattenList(self, lst):\n flattened_lst = []\n for ele in lst:\n if ele.isInteger():\n flattened_lst.append(ele.getInteger())\n else:\n flattened_lst.extend(self.flattenList(ele.getList()))\n return flattened_lst", + "title": "341. Flatten Nested List Iterator", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n . You are also given a sequence of n values voyage , which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage . Return a list of the values of all flipped nodes. You may return the answer in any order . If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage , return the list [-1] .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "n == voyage.length", + "1 <= n <= 100", + "1 <= Node.val, voyage[i] <= n", + "All the values in the tree are unique .", + "All the values in voyage are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2], voyage = [2,1]\nOutput:[-1]\nExplanation:It is impossible to flip the nodes such that the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], voyage = [1,3,2]\nOutput:[1]\nExplanation:Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3], voyage = [1,2,3]\nOutput:[]\nExplanation:The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.10 MB (Top 56.52%)\n\nclass Solution {\n int vix = 0;\n List ans = new ArrayList<>();\n private void dfs(TreeNode node, int[] V) {\n if (node == null || (ans.size() != 0 && ans.get(0) == -1)) return;\n if (node.val != V[vix++])\n ans = new ArrayList(Arrays.asList(-1));\n else if (node.left != null && node.left.val != V[vix]) {\n ans.add(node.val);\n dfs(node.right, V);\n dfs(node.left, V);\n } else {\n dfs(node.left, V);\n dfs(node.right, V);\n }\n }\n public List flipMatchVoyage(TreeNode root, int[] V) {\n dfs(root, V);\n return ans;\n }\n}\n", + "title": "971. Flip Binary Tree To Match Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n . You are also given a sequence of n values voyage , which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage . Return a list of the values of all flipped nodes. You may return the answer in any order . If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage , return the list [-1] .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "n == voyage.length", + "1 <= n <= 100", + "1 <= Node.val, voyage[i] <= n", + "All the values in the tree are unique .", + "All the values in voyage are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2], voyage = [2,1]\nOutput:[-1]\nExplanation:It is impossible to flip the nodes such that the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], voyage = [1,3,2]\nOutput:[1]\nExplanation:Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3], voyage = [1,2,3]\nOutput:[]\nExplanation:The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 21.2%) | Memory: 16.23 MB (Top 89.3%)\n\nclass Solution:\n def flipMatchVoyage(self, root, voyage):\n \n # ------------------------------\n \n def dfs(root):\n \n if not root:\n # base case aka stop condition\n\t\t\t\t# empty node or empty tree\n return True\n \n \n ## general cases\n if root.val != voyage[dfs.idx]:\n \n # current node mismatch, no chance to make correction by flip\n return False\n \n # voyage index moves forward\n dfs.idx += 1\n \n if root.left and (root.left.val != voyage[dfs.idx]):\n \n # left child mismatch, flip with right child if right child exists\n root.right and result.append( root.val )\n \n # check subtree in preorder DFS with child node flip\n return dfs(root.right) and dfs(root.left)\n \n else:\n \n # left child match, check subtree in preorder DFS\n return dfs(root.left) and dfs(root.right)\n \n \n # --------------------------\n \n # flip sequence\n result = []\n \n # voyage index during dfs\n dfs.idx = 0\n \n # start checking from root node\n good = dfs(root)\n \n return result if good else [-1]", + "title": "971. Flip Binary Tree To Match Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary matrix matrix . You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1],[1,1]]\nOutput:1\nExplanation:After flipping no values, 1 row has all values equal.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[0,1],[1,0]]\nOutput:2\nExplanation:After flipping values in the first column, both rows have equal values.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[0,0,0],[0,0,1],[1,1,0]]\nOutput:2\nExplanation:After flipping values in the first two columns, the last two rows have equal values.", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List\nfrom collections import Counter\n\n\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n counter = Counter()\n max_val = 2 ** len(matrix[0]) - 1\n for row in matrix:\n v = self.calculate_binary(row)\n counter[v] += 1\n counter[max_val - v] += 1\n # print(f'counter: {counter}')\n\n return counter.most_common(1)[0][1]\n\n def calculate_binary(self, row: List[int]) -> int:\n val = 0\n for r in row:\n val = val * 2 + r\n return val\n", + "title": "1072. Flip Columns For Maximum Number of Equal Rows", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For a binary tree T , we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees root1 and root2 , return true if the two trees are flip equivalent or false otherwise.", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 100] .", + "Each tree will have unique node values in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput:true\nExplanation:We flipped at nodes with values 1, 3, and 5.", + "image": "https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png" + }, + { + "text": "Example 2: Input:root1 = [], root2 = []\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:root1 = [], root2 = [1]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean flipEquiv(TreeNode root1, TreeNode root2) {\n return helper(root1, root2);\n }\n \n private boolean helper(TreeNode x, TreeNode y)\n {\n if(x == null && y == null) return true;\n if(x == null || y == null || x.val != y.val) return false;\n boolean similarity = helper(x.left, y.left) && helper(x.right, y.right); // check if 2 subtrees are similar\n boolean swap = helper(x.left, y.right) && helper(x.right, y.left); // check if the 2 subtrees can be similar after swapping the left & right subtrees with each other\n \n return similarity || swap; // if either true, means we can flip to match both trees\n }\n}\n", + "title": "951. Flip Equivalent Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "For a binary tree T , we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees root1 and root2 , return true if the two trees are flip equivalent or false otherwise.", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 100] .", + "Each tree will have unique node values in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput:true\nExplanation:We flipped at nodes with values 1, 3, and 5.", + "image": "https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png" + }, + { + "text": "Example 2: Input:root1 = [], root2 = []\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:root1 = [], root2 = [1]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 89.57%) | Memory: 16.70 MB (Top 53.69%)\n\nclass Solution:\n def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n queue = deque([(root1, root2)])\n while queue:\n node1, node2 = queue.pop()\n if (not node1) and (not node2):\n continue\n elif (not node1) or (not node2) or (node1.val != node2.val):\n return False\n L1, R1, L2, R2 = node1.left, node1.right, node2.left, node2.right\n if (L1 and L2 and L1.val == L2.val) or (R1 and R2 and R1.val == R2.val):\n queue.append((L1, L2))\n queue.append((R1, R2))\n else:\n queue.append((L1, R2))\n queue.append((L2, R1))\n return True\n", + "title": "951. Flip Equivalent Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A binary string is monotone increasing if it consists of some number of 0 's (possibly none), followed by some number of 1 's (also possibly none). You are given a binary string s . You can flip s[i] changing it from 0 to 1 or from 1 to 0 . Return the minimum number of flips to make s monotone increasing .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110\"\nOutput:1\nExplanation:We flip the last digit to get 00111.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010110\"\nOutput:2\nExplanation:We flip to get 011111, or alternatively 000111.", + "image": null + }, + { + "text": "Example 3: Input:s = \"00011000\"\nOutput:2\nExplanation:We flip to get 00000000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlipsMonoIncr(String s) {\n int n = s.length();\n int zeroToOne =0;\n int countOfOnes=0;\n for(int i=0;i int:\n n = len(s)\n min_flip = n\n one_left = 0\n # zero_right = 0\n # for c in s:\n # if c == \"0\":\n # zero_right += 1\n \n zero_right = s.count(\"0\") # since we will start with 11...11 then every zero in s will be on the right side of the border\n \n # for each i imagine that we have the borderline at i index any index >= i will be 1 and index < i will be 0.\n # i = 0, n = 5 -> 11111\n # i = 1, n = 5 -> 01111\n # i = 5 -> 00000\n for i in range(n + 1):\n # the number of flip will be equal number of 1 on the left side of the border + number of zero on the right side of the border\n # from example 00110\n # v \n # comparing with 00111 : i = 2, one_left = 0, zero_right = 1, then we have to do 0 + 1 flip in this i\n min_flip = min(min_flip,one_left+zero_right)\n \n # edge case for i = n or all zero (00...00)\n if i == len(s):\n continue\n # reduce count of zero_right when 0 is moving to the 0-zone or left side of border\n if s[i] == \"0\":\n zero_right -= 1\n else:\n one_left += 1 # increase one on the left side when we move 1 into the left side\n \n return min_flip\n \n \n", + "title": "926. Flip String to Monotone Increasing", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an n x n binary matrix image , flip the image horizontally , then invert it, and return the resulting image . To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1 , and each 1 is replaced by 0 .", + "description_images": [], + "constraints": [ + "For example, flipping [1,1,0] horizontally results in [0,1,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput:[[1,0,0],[0,1,0],[1,1,1]]\nExplanation:First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation:First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.21%) | Memory: 44.9 MB (Top 51.92%)\nclass Solution {\n public int[][] flipAndInvertImage(int[][] image) {\n for (int i = 0; i < image.length; ++i) {\n flip(image[i]);\n }\n for (int i = 0; i < image.length; ++i) {\n for (int j = 0; j < image[i].length; ++j) {\n image[i][j] = image[i][j] == 1 ? 0:1;\n }\n }\n return image;\n }\n public static void flip(int[] row) {\n int i = 0;\n int j = row.length - 1;\n while (i < j) {\n int temp = row[i];\n row[i] = row[j];\n row[j] = temp;\n ++i;\n --j;\n }\n }\n}", + "title": "832. Flipping an Image", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n x n binary matrix image , flip the image horizontally , then invert it, and return the resulting image . To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1 , and each 1 is replaced by 0 .", + "description_images": [], + "constraints": [ + "For example, flipping [1,1,0] horizontally results in [0,1,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput:[[1,0,0],[0,1,0],[1,1,1]]\nExplanation:First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation:First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n return [[(1 - i) for i in row[::-1]] for row in image]\n", + "title": "832. Flipping an Image", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr , sc , and color . You should perform a flood fill on the image starting from the pixel image[sr][sc] . To perform a flood fill , consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color . Return the modified image after performing the flood fill .", + "description_images": [], + "constraints": [ + "m == image.length", + "n == image[i].length", + "1 <= m, n <= 50", + "0 <= image[i][j], color < 2 16", + "0 <= sr < m", + "0 <= sc < n" + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\nOutput:[[2,2,2],[2,2,0],[2,0,1]]\nExplanation:From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg" + }, + { + "text": "Example 2: Input:image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\nOutput:[[0,0,0],[0,0,0]]\nExplanation:The starting pixel is already colored 0, so no changes are made to the image.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.13%) | Memory: 48.4 MB (Top 21.53%)\nclass Solution {\n void colorFill(int[][]image,int sr,int sc,int sourceColor,int targetColor){\n int m = image.length, n = image[0].length;\n\n if(sr>=0 && sr=0 && sc List[List[int]]:\n queue = deque()\n rows = len(image)\n cols = len(image[0])\n \n targetColor = image[sr][sc]\n \n if color == targetColor:\n\t\t # in this case, we don't need to do anything\n return image\n\n rDirs = [1, 0, -1, 0]\n cDirs = [0, 1, 0, -1]\n \n queue.append((sr, sc))\n \n while len(queue) > 0:\n r, c = queue.pop()\n \n image[r][c] = color\n for rd, cd in zip(rDirs, cDirs):\n newRow = r + rd\n newCol = c + cd\n \n isValidCoordinate = newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols\n \n if isValidCoordinate and image[newRow][newCol] == targetColor:\n queue.append((newRow, newCol))\n \n return image\n \n \n", + "title": "733. Flood Fill", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n gardens, labeled from 1 to n , and an array paths where paths[i] = [x i , y i ] describes a bidirectional path between garden x i to garden y i . In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer , where answer[i] is the type of flower planted in the (i+1) th garden. The flower types are denoted 1 , 2 , 3 , or 4 . It is guaranteed an answer exists.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= paths.length <= 2 * 10^4", + "paths[i].length == 2", + "1 <= x i , y i <= n", + "x i != y i", + "Every garden has at most 3 paths coming into or leaving it." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, paths = [[1,2],[2,3],[3,1]]\nOutput:[1,2,3]\nExplanation:Gardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].", + "image": null + }, + { + "text": "Example 2: Input:n = 4, paths = [[1,2],[3,4]]\nOutput:[1,2,1,2]", + "image": null + }, + { + "text": "Example 3: Input:n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\nOutput:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] gardenNoAdj(int n, int[][] paths) {\n boolean[][] graph = new boolean[n][n];\n for(int i = 0;i List[int]:\n\t\tg = defaultdict(list)\n\t\tfor u,v in paths:\n\t\t\tg[u-1].append(v-1) \n\t\t\tg[v-1].append(u-1) \n\t\tans = [0]*n\n\t\tfor i in range(n):\n\t\t\tc = [1,2,3,4]\n\t\t\tfor j in g[i]:\n\t\t\t\tif ans[j] in c: c.remove(ans[j])\n\t\t\tans[i] = c.pop()\n\t\treturn ans", + "title": "1042. Flower Planting With No Adjacent", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array groups of length n . You are also given an integer array nums . You are asked if you can choose n disjoint subarrays from the array nums such that the i th subarray is equal to groups[i] ( 0-indexed ), and if i > 0 , the (i-1) th subarray appears before the i th subarray in nums (i.e. the subarrays must be in the same order as groups ). Return true if you can do this task, and false otherwise . Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.", + "description_images": [], + "constraints": [ + "groups.length == n", + "1 <= n <= 10^3", + "1 <= groups[i].length, sum(groups[i].length) <= 10^3", + "1 <= nums.length <= 10^3", + "-10^7 <= groups[i][j], nums[k] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput:true\nExplanation:You can choose the 0thsubarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1stone as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.", + "image": null + }, + { + "text": "Example 2: Input:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput:false\nExplanation:Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "image": null + }, + { + "text": "Example 3: Input:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput:false\nExplanation:Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int search(int[] group, int[] nums, int start, int end )\n {\n int i=start, j=0;\n while(i 0 , the (i-1) th subarray appears before the i th subarray in nums (i.e. the subarrays must be in the same order as groups ). Return true if you can do this task, and false otherwise . Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.", + "description_images": [], + "constraints": [ + "groups.length == n", + "1 <= n <= 10^3", + "1 <= groups[i].length, sum(groups[i].length) <= 10^3", + "1 <= nums.length <= 10^3", + "-10^7 <= groups[i][j], nums[k] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput:true\nExplanation:You can choose the 0thsubarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1stone as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.", + "image": null + }, + { + "text": "Example 2: Input:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput:false\nExplanation:Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "image": null + }, + { + "text": "Example 3: Input:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput:false\nExplanation:Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n groups = ['-'.join(str(s) for s in group) for group in groups]\n nums = '-'.join(str(s) for s in nums)\n j = k = 0\n while k < len(groups):\n group = groups[k]\n i = nums.find(group, j)\n if i == -1: return False\n if i == 0 or i > 0 and nums[i-1] == '-':\n j = i + len(group)\n k += 1\n else: j += 1\n return True \n", + "title": "1764. Form Array by Concatenating Subarrays of Another Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers cost and an integer target , return the maximum integer you can paint under the following rules : Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\" .", + "description_images": [], + "constraints": [ + "The cost of painting a digit (i + 1) is given by cost[i] ( 0-indexed ).", + "The total cost used must be equal to target .", + "The integer does not have 0 digits." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput:\"7772\"\nExplanation:The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.Digit cost1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5", + "image": null + }, + { + "text": "Example 2: Input:cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput:\"85\"\nExplanation:The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.", + "image": null + }, + { + "text": "Example 3: Input:cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput:\"0\"\nExplanation:It is impossible to paint any integer with total cost equal to target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Space Complexity = O(N*M) (N == length of cost array and M == target )\n// Time Complexity = O(N*M)\n\nclass Solution {\n Map map = new HashMap<>();\n String[][] memo;\n public String largestNumber(int[] cost, int target) {\n memo = new String[cost.length+1][target+1];\n \n for( int i = 0;i<=cost.length;i++ ){\n for(int j = 0;j<=target;j++) memo[i][j] = \"0\";\n }\n \n String res = helper(cost,cost.length-1,target);\n \n return res == \"-1\" ? \"0\" : res; \n \n }\n \n public String helper( int[] cost , int index , int target){\n if(target == 0) {\n return \"\";\n }\n \n if(target < 0) return \"-1\";\n \n if(index < 0) return \"-1\";\n \n if( memo[index][target] != \"0\") return memo[index][target];\n \n String str1 = (index+1) + helper(cost,cost.length-1,target-cost[index]) ;\n String str2 = helper(cost,index-1,target);\n \n String res = getBigger(str1,str2);\n \n memo[index][target] = res;\n \n return res;\n }\n \n public String getBigger(String num1 , String num2){\n if( num1.contains(\"-1\") ) return num2;\n if( num2.contains(\"-1\") ) return num1;\n if( num1.length() > num2.length() ) return num1;\n if( num2.length() > num1.length() ) return num2;\n return Double.parseDouble( num1 ) < Double.parseDouble( num2 ) ? num2 : num1;\n }\n}\n", + "title": "1449. Form Largest Integer With Digits That Add up to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers cost and an integer target , return the maximum integer you can paint under the following rules : Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\" .", + "description_images": [], + "constraints": [ + "The cost of painting a digit (i + 1) is given by cost[i] ( 0-indexed ).", + "The total cost used must be equal to target .", + "The integer does not have 0 digits." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput:\"7772\"\nExplanation:The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.Digit cost1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5", + "image": null + }, + { + "text": "Example 2: Input:cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput:\"85\"\nExplanation:The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.", + "image": null + }, + { + "text": "Example 3: Input:cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput:\"0\"\nExplanation:It is impossible to paint any integer with total cost equal to target.", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n @lru_cache(None)\n def dfs(t):\n if t == 0: return 0\n res = float('-inf')\n for digit in range(1,10):\n if t - cost[digit-1] >= 0:\n res = max(res, dfs(t - cost[digit-1])*10+digit)\n return res\n res = dfs(target)\n return \"0\" if res == float('-inf') else str(res)", + "title": "1449. Form Largest Integer With Digits That Add up to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the sum of divisors of the integers in that array that have exactly four divisors . If there is no such integer in the array, return 0 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [21,4,7]\nOutput:32\n\nExplanation:21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.", + "image": null + }, + { + "text": "Example 2: Input:nums = [21,21]\nOutput:64", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumFourDivisors(int[] nums) {\n int res = 0;\n for(int val : nums){\n int sum = 0;\n int count = 0;\n for(int i=1;i*i <= val;i++){\n if(val % i == 0){\n sum += i;\n count++;\n if(i != val/i){\n sum += val/i;\n count++;\n }\n }\n }\n if(count == 4){\n res += sum;\n }\n }\n return res;\n }\n}\n", + "title": "1390. Four Divisors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the sum of divisors of the integers in that array that have exactly four divisors . If there is no such integer in the array, return 0 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [21,4,7]\nOutput:32\nExplanation:21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.", + "image": null + }, + { + "text": "Example 2: Input:nums = [21,21]\nOutput:64", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "import math \nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n s=0\n for i in nums:\n r=i+1\n c=2\n for j in range(2, int(math.sqrt(i))+1):\n if i%j==0:\n if (i / j == j) :\n c+=1\n r+=j\n else :\n c+=2\n r+=j+int(i/j)\n print(c, r)\n if c==4:\n s+=r\n return s\n", + "title": "1390. Four Divisors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 .", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"\nOutput:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"\nOutput:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"\nOutput:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 16.51%) | Memory: 44.40 MB (Top 27.52%)\n\nclass Solution {\n private int gcd(int x, int y){\n return x!=0?gcd(y%x, x):Math.abs(y);\n }\n\n public String fractionAddition(String exp) {\n Scanner sc = new Scanner(exp).useDelimiter(\"/|(?=[-+])\");\n\n int A=0, B=1;\n while(sc.hasNext()){\n int a = sc.nextInt(), b=sc.nextInt();\n A = A * b + B * a;\n B *= b;\n\n int gcdX = gcd(A, B);\n A/=gcdX;\n B/=gcdX;\n }\n return A+\"/\"+B;\n }\n}\n", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 .", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"\nOutput:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"\nOutput:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"\nOutput:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n //Great Common Divisor \n private int gcd(int a,int b) {\n int r=b%a;\n if (r==0) return a;\n return gcd(r,a);\n }\n private int[] add(int[] a,int[] b){\n if(a[0]==0) return b;\n if(b[0]==0) return a;\n int[] ret=new int[]{a[0]*b[1]+b[0]*a[1],a[1]*b[1]};\n if(ret[0]==0){\n ret[1]=1;\n return ret; \n }\n int sign=ret[0]<0?-1:1;\n ret[0]*=sign;\n int g=gcd(Math.min(ret[0],ret[1]),Math.max(ret[0],ret[1]));\n if(g>1) {\n ret[0]/=g;\n ret[1]/=g; \n }\n ret[0]*=sign;\n return ret;\n }\n public String fractionAddition(String expression) {\n return Stream.of(\n expression.replaceAll(\"\\\\-\",\"+-\").split(\"\\\\+\")).filter(s->s.length()>0).map(\n s->s.split(\"/\")).map(\n a->new int[]{Integer.parseInt(a[0]),Integer.parseInt(a[1])}).reduce((a,b)->add(a,b)).map(p->p[0]+\"/\"+p[1]).get();\n \n }\n}\n", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 .", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"\nOutput:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"\nOutput:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"\nOutput:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 35 ms (Top 88.02%) | Memory: 14.1 MB (Top 5.79%)\n\"\"\"\napproach:\nfirst replace - with +- in the string so that implementation gets\na little easy\n\"\"\"\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n expression = expression.replace('-', '+-')\n parts = [item for item in expression.split('+') if item != '']\n numes, denoms, denom_set, lcm = [], [], set(), 1\n def get_lcm(a, b):\n if a == 1:\n return b\n if b == 1:\n return a\n if a < b:\n if b % a == 0:\n return a * get_lcm(1, b/a)\n else:\n return a * get_lcm(1, b)\n else:\n if a % b == 0:\n return b * get_lcm(a/b, 1)\n else:\n return b * get_lcm(a, 1)\n\n for part in parts:\n num, den = part.split('/')\n numes.append(int(num))\n denoms.append(int(den))\n lcm = get_lcm(lcm, int(den))\n\n result = 0\n for num, den in zip(numes, denoms):\n result +=num * int(lcm/den)\n\n def get_gcd(a, b):\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n elif a < b:\n return get_gcd(a, b-a)\n else:\n return get_gcd(a-b, b)\n\n gcd = get_gcd(abs(result), lcm)\n return str(int(result/gcd)) + '/' + str(int(lcm/gcd))", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format . If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them . It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.", + "description_images": [], + "constraints": [ + "-2 31 <= numerator, denominator <= 2 31 - 1", + "denominator != 0" + ], + "examples": [ + { + "text": "Example 1: Input:numerator = 1, denominator = 2\nOutput:\"0.5\"", + "image": null + }, + { + "text": "Example 2: Input:numerator = 2, denominator = 1\nOutput:\"2\"", + "image": null + }, + { + "text": "Example 3: Input:numerator = 4, denominator = 333\nOutput:\"0.(012)\"", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public String fractionToDecimal(int numerator, int denominator) {\n if(numerator == 0){\n return \"0\";\n }\n \n StringBuilder sb = new StringBuilder(\"\");\n if(numerator<0 && denominator>0 || numerator>0 && denominator<0){\n sb.append(\"-\");\n }\n \n long divisor = Math.abs((long)numerator);\n long dividend = Math.abs((long)denominator);\n long remainder = divisor % dividend;\n sb.append(divisor / dividend);\n \n if(remainder == 0){\n return sb.toString();\n }\n sb.append(\".\");\n HashMap map = new HashMap();\n while(remainder!=0){\n if(map.containsKey(remainder)){\n sb.insert(map.get(remainder), \"(\");\n sb.append(\")\");\n break;\n }\n map.put(remainder, sb.length());\n remainder*= 10;\n sb.append(remainder/dividend);\n remainder%= dividend;\n }\n return sb.toString();\n }\n}\n\n", + "title": "166. Fraction to Recurring Decimal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format . If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them . It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.", + "description_images": [], + "constraints": [ + "-2 31 <= numerator, denominator <= 2 31 - 1", + "denominator != 0" + ], + "examples": [ + { + "text": "Example 1: Input:numerator = 1, denominator = 2\nOutput:\"0.5\"", + "image": null + }, + { + "text": "Example 2: Input:numerator = 2, denominator = 1\nOutput:\"2\"", + "image": null + }, + { + "text": "Example 3: Input:numerator = 4, denominator = 333\nOutput:\"0.(012)\"", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n sign = \"\" if numerator*denominator >= 0 else \"-\"\n numerator, denominator = abs(numerator), abs(denominator)\n a = numerator//denominator\n numerator %= denominator\n if not numerator: return sign+str(a)\n fractions = []\n index = defaultdict(int)\n while 10*numerator not in index:\n numerator *= 10\n index[numerator] = len(fractions)\n fractions.append(str(numerator//denominator))\n numerator %= denominator\n i = index[10*numerator]\n return sign+str(a)+\".\"+\"\".join(fractions[:i])+\"(\"+\"\".join(fractions[i:])+\")\" if numerator else sign+str(a)+\".\"+\"\".join(fractions[:i])", + "title": "166. Fraction to Recurring Decimal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\" and use the dial to spell a specific keyword to open the door. Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword . Initially, the first character of the ring is aligned at the \"12:00\" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the \"12:00\" direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i] :", + "description_images": [], + "constraints": [ + "1 <= ring.length, key.length <= 100", + "ring and key consist of only lower case English letters.", + "It is guaranteed that key could always be spelled by rotating ring ." + ], + "examples": [ + { + "text": "Example 1: Input:ring = \"godding\", key = \"gd\"\nOutput:4\nExplanation:For the first key character 'g', since it is already in place, we just need 1 step to spell this character. \nFor the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\nAlso, we need 1 more step for spelling.\nSo the final output is 4.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/ring.jpg" + }, + { + "text": "Example 2: Input:ring = \"godding\", key = \"godding\"\nOutput:13", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 46.01%) | Memory: 46.5 MB (Top 66.67%)\nclass Solution {\n public int findRotateSteps(String ring, String key) {\n Map> locMap = new HashMap<>();\n for (int i = 0; i < ring.length(); i++){\n locMap.computeIfAbsent(ring.charAt(i), o->new TreeSet<>()).add(i);\n }\n return dfs(0, 0, locMap, key, new int[key.length()][ring.length()]);\n }\n\n private int dfs(int cur, int where, Map> locMap, String key, int[][] memo){\n if (cur==key.length()){ // the end\n return 0;\n }\n if (memo[cur][where]>0){ // have computed [cur, end) already.\n return memo[cur][where];\n }\n TreeSet idx = locMap.get(key.charAt(cur));\n if (idx.contains(where)){ // greedily take this if it is already matched\n return memo[cur][where]=dfs(cur+1, where, locMap, key, memo)+1;\n }\n Integer hi = idx.higher(where); // otherwise, we can take the higher key\n Integer lo = idx.lower(where); // or, the lower key\n if (hi == null){ // if no higher key, it becomes the lowest key.\n hi = idx.first();\n }\n if (lo == null){ // if no lower key, it becomes the highest key.\n lo = idx.last();\n }\n int hcost = dfs(cur+1, hi, locMap, key, memo) + (hi>where? hi-where:memo[0].length-where+hi);\n int lcost = dfs(cur+1, lo, locMap, key, memo) + (lo int:\n locs = {}\n for i, ch in enumerate(ring): locs.setdefault(ch, []).append(i)\n \n @cache \n def fn(i, j): \n \"\"\"Return turns to finish key[j:] startin from ith position on ring.\"\"\"\n if j == len(key): return 0 \n loc = locs[key[j]]\n k = bisect_left(loc, i) % len(loc)\n ans = min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1)\n k = (k-1) % len(loc)\n ans = min(ans, min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1))\n return ans \n \n return fn(0, 0) + len(key)\n", + "title": "514. Freedom Trail", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k . In one operation, you can choose an index of nums and increment the element at that index by 1 . Return the maximum possible frequency of an element after performing at most k operations .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4], k = 5\nOutput:3\nExplanation:Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,8,13], k = 5\nOutput:2\nExplanation:There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,9,6], k = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 33.83%) | Memory: 95.9 MB (Top 65.95%)\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n //Step-1: Sorting->\n Arrays.sort(nums);\n //Step-2: Two-Pointers->\n int L=0,R=0;\n long totalSum=0;\n int res=1;\n //Iterating over the array:\n while(R=\" \"windowSize*nums[R]\"\n //then only the window is possible else decrease the \"totalSum\"\n //till the value \"totalSum+k\" is \">=\" \"windowSize*nums[R]\"\n while(! ((totalSum+k) >= ((R-L+1)*nums[R])) )\n {\n totalSum-=nums[L];\n L++;\n }\n res=Math.max(res,(R-L+1));\n R++;\n }\n return res;\n }\n}", + "title": "1838. Frequency of the Most Frequent Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k . In one operation, you can choose an index of nums and increment the element at that index by 1 . Return the maximum possible frequency of an element after performing at most k operations .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4], k = 5\nOutput:3\nExplanation:Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,8,13], k = 5\nOutput:2\nExplanation:There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,9,6], k = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n sums, i, ans = 0, 0, 0\n for j in range(len(nums)):\n sums += nums[j]\n while nums[j]*(j-i+1) > sums+k:\n sums -= nums[i]\n i = i+1\n ans = max(ans, j-i+1)\n return ans", + "title": "1838. Frequency of the Most Frequent Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i th person. A Person x will not send a friend request to a person y ( x != y ) if any of the following conditions is true: Otherwise, x will send a friend request to y . Note that if x sends a request to y , y will not necessarily send a request to x . Also, a person will not send a friend request to themself. Return the total number of friend requests made .", + "description_images": [], + "constraints": [ + "age[y] <= 0.5 * age[x] + 7", + "age[y] > age[x]", + "age[y] > 100 && age[x] < 100" + ], + "examples": [ + { + "text": "Example 1: Input:ages = [16,16]\nOutput:2\nExplanation:2 people friend request each other.", + "image": null + }, + { + "text": "Example 2: Input:ages = [16,17,18]\nOutput:2\nExplanation:Friend requests are made 17 -> 16, 18 -> 17.", + "image": null + }, + { + "text": "Example 3: Input:ages = [20,30,100,110,120]\nOutput:3\nExplanation:Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static int upperBound(int arr[], int target) {\n int l = 0, h = arr.length - 1;\n for (; l <= h;) {\n int mid = (l + h) >> 1;\n if (arr[mid] <= target)\n l = mid + 1;\n else\n h = mid - 1;\n }\n return l;\n }\n public int numFriendRequests(int[] ages) {\n long ans = 0;\n Arrays.sort(ages);\n\t\t// traversing order doesn't matter as we are doing binary-search in whole array\n\t\t// you can traverse from left side also\n for(int i = ages.length - 1;i >= 0;--i){\n int k = upperBound(ages,ages[i] / 2 + 7);\n int t = upperBound(ages,ages[i]);\n ans += Math.max(0,t - k - 1);\n }\n return (int)ans;\n }\n}\n", + "title": "825. Friends Of Appropriate Ages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i th person. A Person x will not send a friend request to a person y ( x != y ) if any of the following conditions is true: Otherwise, x will send a friend request to y . Note that if x sends a request to y , y will not necessarily send a request to x . Also, a person will not send a friend request to themself. Return the total number of friend requests made .", + "description_images": [], + "constraints": [ + "age[y] <= 0.5 * age[x] + 7", + "age[y] > age[x]", + "age[y] > 100 && age[x] < 100" + ], + "examples": [ + { + "text": "Example 1: Input:ages = [16,16]\nOutput:2\nExplanation:2 people friend request each other.", + "image": null + }, + { + "text": "Example 2: Input:ages = [16,17,18]\nOutput:2\nExplanation:Friend requests are made 17 -> 16, 18 -> 17.", + "image": null + }, + { + "text": "Example 3: Input:ages = [20,30,100,110,120]\nOutput:3\nExplanation:Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 936 ms (Top 28.73%) | Memory: 14.9 MB (Top 52.36%)\nclass Solution:\n \"\"\"\n approach:\n we can try solving this problem by finding the valid age group for each age\n sort the array in descending order\n iterate from right to left\n for current age, find the valid agegroup to which the current age person will send a request\n we can use binary search for that\n if current age is x, then valid age group to send a request is:\n x*0.5 + 7 < age(y) <= x\n we can find the left limit using binary search\n \"\"\"\n def binary_search(self, arr, low, high, value):\n if low > high:\n return high\n mid = (low + high) // 2\n if arr[mid] > value:\n return self.binary_search(arr, low, mid-1, value)\n else:\n return self.binary_search(arr, mid+1, high, value)\n\n def numFriendRequests(self, ages: List[int]) -> int:\n ages = sorted(ages)\n total_count = 0\n for i in range(len(ages)-1, -1, -1):\n if i+1 < len(ages) and ages[i] == ages[i+1]:\n total_count+= prev_count\n continue\n\n prev_count = 0\n lower_limit = 0.5 * ages[i] + 7\n index = self.binary_search(ages, 0, i-1, lower_limit)\n prev_count = i - (index+1)\n total_count+=prev_count\n return total_count", + "title": "825. Friends Of Appropriate Ages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones ' positions (in units) in sorted ascending order , determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1 , k , or k + 1 units. The frog can only jump in the forward direction.", + "description_images": [], + "constraints": [ + "2 <= stones.length <= 2000", + "0 <= stones[i] <= 2 31 - 1", + "stones[0] == 0", + "stones is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [0,1,3,5,6,8,12,17]\nOutput:true\nExplanation:The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [0,1,2,3,4,8,9,11]\nOutput:false\nExplanation:There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static boolean flag = false; // If flag is true no more operations in recursion, directly return statement\n public boolean canCross(int[] stones) {\n int i = 0; // starting stone\n int k = 1; // starting jump\n flag = false; \n return canBeCrossed(stones, k, i);\n }\n \n public boolean canBeCrossed(int[] stones, int k, int i){\n if(!flag){ // If flag is false \n if(stones[i] + k == stones[stones.length - 1]){ // If frog do 'k' jump from current stone lands on last stones, no more recusive calls and return true\n flag = true;\n return true;\n }\n\t\t// If frog do 'k' jump from current stone crosses last stone or not able to reach next stone\n\t\t//return false\n if((stones[i] + k > stones[stones.length - 1]) || (stones[i]+k stones[temp]) temp++;\n\t\t//If loop exited 2 condition possible\n\t\t//jump from current stone is reached next possible stone\n\t\t//or not\n\t\t\n\t\t//If next possible stone reached\n\t\t//then do all possible jumps from this stone \n\t\t//the current stone is 'temp'\n\t\t//possible jumps are 'k-1', k, 'k+1'\n if(stones[i]+k == stones[temp]) return (canBeCrossed(stones, k+1, temp) || canBeCrossed(stones, k, temp) || canBeCrossed(stones,k-1,temp));\n\t\t\n\t\t//If next possible stone not reached means jump from the current stone can't reach any stone\n\t\t//hence return false\n else return false;\n }\n else return true;\n }\n}", + "title": "403. Frog Jump", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones ' positions (in units) in sorted ascending order , determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1 , k , or k + 1 units. The frog can only jump in the forward direction.", + "description_images": [], + "constraints": [ + "2 <= stones.length <= 2000", + "0 <= stones[i] <= 2 31 - 1", + "stones[0] == 0", + "stones is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [0,1,3,5,6,8,12,17]\nOutput:true\nExplanation:The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [0,1,2,3,4,8,9,11]\nOutput:false\nExplanation:There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 231 ms (Top 72.60%) | Memory: 19.2 MB (Top 61.18%)\nclass Solution:\n def possible(self, i, n, stones, pos, allowedJumps):\n if i == n - 1:\n return True\n key = tuple([i] + allowedJumps)\n if key in self.cache:\n return self.cache[key]\n for jump in allowedJumps:\n if jump > 0 and stones[i] + jump in pos:\n if self.possible(pos[stones[i] + jump], n, stones, pos, [jump - 1, jump, jump + 1]):\n self.cache[key] = True\n return True\n self.cache[key] = False\n return False\n\n def canCross(self, stones: List[int]) -> bool:\n n = len(stones)\n pos = {}\n for i, stone in enumerate(stones):\n pos[stone] = i\n self.cache = {}\n return self.possible(0, n, stones, pos, [1])", + "title": "403. Frog Jump", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n . A frog starts jumping from vertex 1 . In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Return the probability that after t seconds the frog is on the vertex target . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= a i , b i <= n", + "1 <= t <= 50", + "1 <= target <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput:0.16666666666666666\nExplanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 aftersecond 1and then jumping with 1/2 probability to vertex 4 aftersecond 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/frog1.jpg" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput:0.3333333333333333\nExplanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 aftersecond 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double frogPosition(int n, int[][] edges, int t, int target) {\n \n List> graph=new ArrayList<>();\n for(int i=0;i<=n;i++) graph.add(new ArrayList<>());\n \n for(int i=0;i> graph,int ver,int t,int tar,boolean[] vis){\n \n int count=0;\n for(Integer child:graph.get(ver)){\n if(!vis[child]) count++;\n }\n \n \n vis[ver]=true;\n if(t<0) return 0;\n \n if(ver==tar){\n if(count==0 || t==0) return 1.0;\n }\n \n if(graph.get(ver).size()==0) return 0;\n \n double ans=0.0;\n \n \n for(Integer child:graph.get(ver)){\n\n // System.out.println(child);\n if(!vis[child])\n ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis);\n }\n // System.out.println(ans);\n vis[ver]=false;\n return ans;\n }\n}\n\n\n", + "title": "1377. Frog Position After T Seconds", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n . A frog starts jumping from vertex 1 . In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Return the probability that after t seconds the frog is on the vertex target . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= a i , b i <= n", + "1 <= t <= 50", + "1 <= target <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput:0.16666666666666666\nExplanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 aftersecond 1and then jumping with 1/2 probability to vertex 4 aftersecond 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/frog1.jpg" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput:0.3333333333333333\nExplanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 aftersecond 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 25.36%) | Memory: 17.90 MB (Top 5.07%)\n\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n nei = collections.defaultdict(set)\n for a, b in edges:\n nei[a].add(b)\n nei[b].add(a)\n \n visited, res = set(), 0.\n def dfs(leaf_id, p, time):\n nonlocal res\n if time >= t:\n if leaf_id == target: res = p\n return\n visited.add(leaf_id)\n neighbors = nei[leaf_id] - visited\n for n in neighbors or [leaf_id]:\n dfs(n, p / (len(neighbors) or 1), time + 1)\n dfs(1, 1, 0)\n return res\n", + "title": "1377. Frog Position After T Seconds", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i th tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: Given the integer array fruits , return the maximum number of fruits you can pick .", + "description_images": [], + "constraints": [ + "You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.", + "Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.", + "Once you reach a tree with fruit that cannot fit in your baskets, you must stop." + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [1,2,1]\nOutput:3\nExplanation:We can pick from all 3 trees.", + "image": null + }, + { + "text": "Example 2: Input:fruits = [0,1,2,2]\nOutput:3\nExplanation:We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].", + "image": null + }, + { + "text": "Example 3: Input:fruits = [1,2,3,2,2]\nOutput:4\nExplanation:We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 61 ms (Top 63.76%) | Memory: 95 MB (Top 59.07%)\nclass Solution {\n public int totalFruit(int[] fruits) {\n if (fruits == null || fruits.length == 0) {\n return 0;\n }\n int start = 0, end = 0, res = 0;\n HashMap map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit\n\n while (end < fruits.length) {\n if (map.size() <= 2) {\n map.put(fruits[end], end);\n end++;\n }\n\n if (map.size() > 2) {\n int leftMost = fruits.length;\n for (int num : map.values()) {\n leftMost = Math.min(leftMost, num);\n }\n map.remove(fruits[leftMost]);\n start = leftMost + 1;\n }\n\n res = Math.max(res, end - start);\n }\n return res;\n }\n}", + "title": "904. Fruit Into Baskets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i th tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: Given the integer array fruits , return the maximum number of fruits you can pick .", + "description_images": [], + "constraints": [ + "You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.", + "Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.", + "Once you reach a tree with fruit that cannot fit in your baskets, you must stop." + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [1,2,1]\nOutput:3\nExplanation:We can pick from all 3 trees.", + "image": null + }, + { + "text": "Example 2: Input:fruits = [0,1,2,2]\nOutput:3\nExplanation:We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].", + "image": null + }, + { + "text": "Example 3: Input:fruits = [1,2,3,2,2]\nOutput:4\nExplanation:We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n ans=0\n fruitdict=defaultdict()\n stack=[]\n i,j=0,0\n\n while jfruitdict[stack[1]] :\n i = fruitdict[stack[1]]+1\n del fruitdict[stack[1]]\n stack.pop()\n else:\n i = fruitdict[stack[0]]+1\n del fruitdict[stack[0]] \n stack.pop(0) \n \n ans=max(ans,j-i)\n return ans", + "title": "904. Fruit Into Baskets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array heights representing the heights of buildings, some bricks , and some ladders . You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 ( 0-indexed ), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.", + "description_images": [], + "constraints": [ + "If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.", + "If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\nOutput:4\nExplanation:Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.", + "image": "https://assets.leetcode.com/uploads/2020/10/27/q4.gif" + }, + { + "text": "Example 2: Input:heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\nOutput:7", + "image": null + }, + { + "text": "Example 3: Input:heights = [14,3,19,3], bricks = 17, ladders = 0\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def furthestBuilding(self, H: List[int], B: int, L: int) -> int:\n heap = []\n for i in range(len(H) - 1):\n diff = H[i+1] - H[i]\n if diff > 0:\n if L > 0:\n heappush(heap, diff)\n L -= 1\n elif heap and diff > heap[0]:\n heappush(heap, diff)\n B -= heappop(heap)\n else: B -= diff\n if B < 0: return i\n return len(H) - 1\n", + "title": "1642. Furthest Building You Can Reach", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board , return the next state .", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]\nOutput:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.1 MB (Top 73.63%)\nclass Solution {\n public void gameOfLife(int[][] board) {\n int m = board.length, n = board[0].length;\n int[][] next = new int[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n next[i][j] = nextState(board, i, j, m, n);\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n board[i][j] = next[i][j];\n }\n }\n }\n\n public int nextState(int[][] board, int i, int j, int m, int n) {\n int ones = 0;\n for (int x = -1; x <=1; x++) {\n for (int y = -1; y <= 1; y++) {\n if (x == 0 && y == 0) {\n continue;\n }\n int a = i + x, b = j + y;\n if (a >= 0 && a < m) {\n if (b >= 0 && b < n) {\n ones += board[a][b];\n }\n }\n }\n }\n if (board[i][j] == 0) {\n return ones == 3 ? 1 : 0;\n } else {\n if (ones == 2 || ones == 3) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n}", + "title": "289. Game of Life", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board , return the next state .", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]\nOutput:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "#pattern\nactual update ref \n0 0 0\n1 1 1\n0 1 -1\n1 0 -2\n\nclass Solution:\n\tdef gameOfLife(self, board: List[List[int]]) -> None:\n\t\tr = len(board)\n\t\tc = len(board[0])\n\t\tans = [[0]*c for _ in range(r)]\n\t\tneighs = [[1,0],[-1,0],[0,1],[0,-1],[-1,-1],[-1,1],[1,1],[1,-1]]\n\n\t\tfor i in range(r):\n\t\t\tfor j in range(c):\n\t\t\t\tlivecnt,deadcnt = 0,0\n\t\t\t\tfor di,dj in neighs:\n\t\t\t\t\tif 0<=(i+di) < r and 0<=(j+dj) int:\n deltas = [x-y for x, y in zip(gas, cost)]\n n = len(deltas)\n deltas = deltas + deltas\n cursum, curi = 0, 0\n maxsum, maxi = 0, 0\n for i, delta in enumerate(deltas):\n cursum = max(0, cursum + delta)\n if cursum == 0:\n curi = i+1\n if cursum > maxsum:\n maxi = curi\n maxsum = cursum\n cursum = 0\n for i in range(n):\n cursum += deltas[(maxi+i)%n]\n if cursum < 0: return -1\n return maxi", + "title": "134. Gas Station", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums , and you can perform the following operation any number of times on nums : Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.", + "description_images": [], + "constraints": [ + "Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,21,3]\nOutput:true\nExplanation:We can sort [7,21,3] by performing the following operations:\n- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]\n- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,6,2]\nOutput:false\nExplanation:It is impossible to sort the array because 5 cannot be swapped with any other element.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,5,9,3,15]\nOutput:true\nWe can sort [10,5,9,3,15] by performing the following operations:\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]\n- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 94.62%) | Memory: 71.9 MB (Top 80.64%)\nclass Solution {\n private static final int[] primes;\n // precompute prime numbers\n static {\n primes = new int[5133];\n final int max = 100000 / 2;\n boolean[] notprime = new boolean[max];\n for (int index = 0, i = 2; i < max; i++) {\n if (notprime[i]) continue;\n primes[index++] = i;\n for (int j = (max - 1) / i; j >= 2; j--) notprime[i * j] = true;\n }\n }\n\n public boolean gcdSort(int[] nums) {\n final var sorted = nums.clone();\n Arrays.sort(sorted);\n final int len = nums.length, max = sorted[len - 1];\n final int[] map = new int[max + 1]; // grouping tree child->parent\n for (int i = 0; i < len; i++) map[nums[i]] = nums[i];\n\n for (final var p : primes) {\n if (p > max / 2) break;\n int group = p;\n map[p] = p;\n for (int num = p + p; num <= max; num += p) {\n var existing = map[num];\n if (existing == 0) continue; // value doens't exist in array\n if (existing == num) map[num] = group; // 1st hit, set group, otherwise, group merging\n else if ((existing = root(map, existing)) < group) {\n map[group] = existing;\n group = existing;\n } else map[existing] = group;\n }\n }\n\n for (int i = 0; i < len; i++) if (root(map, nums[i]) != root(map, (sorted[i]))) return false;\n return true;\n }\n\n private static int root(int[] map, int num) {\n int group;\n while (num != (group = map[num])) num = group;\n return group;\n }\n}", + "title": "1998. GCD Sort of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a string with n characters such that each character in such string occurs an odd number of times . The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.", + "description_images": [], + "constraints": [ + "1 <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:\"pppz\"\nExplanation:\"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:\"xy\"\nExplanation:\"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".", + "image": null + }, + { + "text": "Example 3: Input:n = 7\nOutput:\"holasss\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 6.68%) | Memory: 45.2 MB (Top 20.03%)\nclass Solution {\n public String generateTheString(int n) {\n String s = \"\";\n String string =\"a\";\n for (int i = 0; i < n-1; i++)\n s += string;\n if(n%2==0)\n return s+\"b\";\n return s+\"a\";\n }\n}", + "title": "1374. Generate a String With Characters That Have Odd Counts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a string with n characters such that each character in such string occurs an odd number of times . The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.", + "description_images": [], + "constraints": [ + "1 <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:\"pppz\"\nExplanation:\"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:\"xy\"\nExplanation:\"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".", + "image": null + }, + { + "text": "Example 3: Input:n = 7\nOutput:\"holasss\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generateTheString(self, n: int) -> str:\n alpha = \"abcdefghijklmnopqrstuvwxyz\"\n res=\"\"\n while n>0:\n curr, alpha = alpha[0], alpha[1:]\n if n%2:\n res += curr*n\n n-=n\n else: \n res += curr*(n-1)\n n-=n-1\n return res", + "title": "1374. Generate a String With Characters That Have Odd Counts", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n List s = new ArrayList<>();\n public void get(int n, int x, String p)\n {\n if(n==0 && x==0)\n {\n s.add(p);\n return;\n }\n if(n==0)\n {\n get(n,x-1,p+\")\");\n }\n else if(x==0)\n {\n get(n-1,x+1,p+\"(\");\n }\n else\n {\n get(n,x-1,p+\")\");\n get(n-1,x+1,p+\"(\");\n }\n }\n public List generateParenthesis(int n) \n {\n s.clear();\n get(n,0,\"\");\n return s;\n }\n}\n", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n\n # Initialize the result\n res = []\n\n # Recursively go through all possible combinations\n def add(open, close, partialRes):\n\n nonlocal res\n\n # If we have added opening and closing parentheses n times, we reaches a solution\n if open == close == n:\n res.append(\"\".join(partialRes))\n return\n\n # Add a closing parenthesis to the partial result if we have at least 1 opening parenthesis\n if close < open:\n add(open, close + 1, partialRes + [\")\"])\n\n # Add an opening parenthesis to the partial result if we haven't added n parenthesis yet\n if open < n:\n add(open + 1, close, partialRes + [\"(\"])\n\n add(0, 0, [])\n\n return res\n", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center) .", + "randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]Output[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]ExplanationSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n double radius;\n double x_center;\n double y_center;\n Random r=new Random();\n public Solution(double radius, double x_center, double y_center) {\n this.radius=radius;\n this.x_center=x_center;\n this.y_center=y_center;\n }\n \n public double[] randPoint() {\n double angle=r.nextDouble(Math.PI*2);\n\t\t//For probability is inversely proportional to radius, we use sqrt of random number.\n double rad=Math.sqrt(r.nextDouble())*radius;\n double[] ret=new double[2];\n ret[0]=rad*Math.cos(angle)+x_center;\n ret[1]=rad*Math.sin(angle)+y_center;\n return ret;\n }\n}\n\n", + "title": "478. Generate Random Point in a Circle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center) .", + "randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]Output[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]ExplanationSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def __init__(self, radius: float, x_center: float, y_center: float):\n self.rad = radius\n self.xc = x_center\n self.yc = y_center\n\n def randPoint(self) -> List[float]:\n while True:\n xg=self.xc+random.uniform(-1, 1)*self.rad*2\n yg=self.yc+random.uniform(-1, 1)*self.rad*2\n if (xg-self.xc)**2 + (yg-self.yc)**2 <= self.rad**2:\n return [xg, yg]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(radius, x_center, y_center)\n# param_1 = obj.randPoint()\n", + "title": "478. Generate Random Point in a Circle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix grid ​​​. A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid ​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum : Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return the biggest three distinct rhombus sums in the grid in descending order . If there are less than three distinct values, return all of them .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput:[228,216,211]\nExplanation:The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211", + "image": "https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex1.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[20,9,8]\nExplanation:The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)", + "image": "https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex2.png" + }, + { + "text": "Example 3: Input:grid = [[7,7,7]]\nOutput:[7]\nExplanation:All three possible rhombus sums are the same, so return [7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 89.47%) | Memory: 52.7 MB (Top 72.81%)\nclass Solution {\n public int[] getBiggestThree(int[][] grid) {\n int end = Math.min(grid.length, grid[0].length);\n int maxThree[] = {0,0,0};\n for(int length=0; length= length){\n addToMaxThree(maxThree, getSum(grid, start, start1, length));\n }\n }\n }\n }\n\n /*\n get sum of edges of rhombus abcd\n a\n / \\\n d b\n \\ /\n c\n\n */\n int getSum(int[][] grid, int i, int j, int length){\n if(length == 0){\n return grid[i][j];\n }\n\n int sum = 0;\n // edge ab\n for(int it=0; it<=length; it++){\n sum = sum + grid[i+it][j+it];\n }\n\n // edge ad\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+it][j-it];\n }\n\n // edge dc\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+length+it][j-length+it];\n }\n\n // edge bc\n for(int it=1; it List[int]:\n \n def calc(l,r,u,d):\n sc=0\n c1=c2=(l+r)//2\n expand=True\n for row in range(u,d+1):\n if c1==c2:\n sc+=grid[row][c1]\n else:\n sc+=grid[row][c1]+grid[row][c2]\n \n if c1==l:\n expand=False\n \n if expand:\n c1-=1\n c2+=1\n else:\n c1+=1\n c2-=1\n return sc\n \n \n m=len(grid)\n n=len(grid[0])\n heap=[]\n for i in range(m):\n for j in range(n):\n l=r=j\n d=i\n while l>=0 and r<=n-1 and d<=m-1:\n sc=calc(l,r,i,d)\n l-=1\n r+=1\n d+=2\n if len(heap)<3:\n if sc not in heap:\n heapq.heappush(heap,sc)\n else:\n if sc not in heap and sc>heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap,sc)\n \n heap.sort(reverse=True)\n return heap\n", + "title": "1878. Get Biggest Three Rhombus Sums in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and t of the same length and an integer maxCost . You want to change s to t . Changing the i th character of s to i th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost . If there is no substring from s that can be changed to its corresponding substring from t , return 0 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "t.length == s.length", + "0 <= maxCost <= 10^6", + "s and t consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"bcdf\", maxCost = 3\nOutput:3\nExplanation:\"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", t = \"cdef\", maxCost = 3\nOutput:1\nExplanation:Each character in s costs 2 to change to character in t, so the maximum length is 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcd\", t = \"acde\", maxCost = 0\nOutput:1\nExplanation:You cannot make any change, so the maximum length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 46.31%) | Memory: 43.1 MB (Top 83.52%)\nclass Solution {\n public int equalSubstring(String s, String t, int maxCost) {\n int ans =0;\n int tempcost =0;\n int l =0 ;\n int r= 0 ;\n for(;r!=s.length();r++){\n tempcost += Math.abs(s.charAt(r)-t.charAt(r));\n while(tempcost>maxCost){\n tempcost -= Math.abs(s.charAt(l)-t.charAt(l));\n l++;\n }\n ans =Math.max(ans,r+1-l);\n }\n return ans;\n }\n}", + "title": "1208. Get Equal Substrings Within Budget", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and t of the same length and an integer maxCost . You want to change s to t . Changing the i th character of s to i th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost . If there is no substring from s that can be changed to its corresponding substring from t , return 0 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "t.length == s.length", + "0 <= maxCost <= 10^6", + "s and t consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"bcdf\", maxCost = 3\nOutput:3\nExplanation:\"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", t = \"cdef\", maxCost = 3\nOutput:1\nExplanation:Each character in s costs 2 to change to character in t, so the maximum length is 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcd\", t = \"acde\", maxCost = 0\nOutput:1\nExplanation:You cannot make any change, so the maximum length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def equalSubstring(self, s, t, maxCost):\n \"\"\"\n :type s: str\n :type t: str\n :type maxCost: int\n :rtype: int\n \"\"\"\n \n \n \n \n best = 0\n \n windowCost = 0\n l = 0\n for r in range(len(s)):\n \n windowCost += abs(ord(s[r]) - ord(t[r]))\n \n while windowCost > maxCost:\n \n windowCost -= abs(ord(s[l]) - ord(t[l]))\n l+=1\n \n best = max(best,r-l+1)\n \n return best\n \n \n \n\n", + "title": "1208. Get Equal Substrings Within Budget", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums ​​​.", + "description_images": [], + "constraints": [ + "nums[0] = 0", + "nums[1] = 1", + "nums[2 * i] = nums[i] when 2 <= 2 * i <= n", + "nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:3\nExplanation:According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:1\nExplanation:According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3\nOutput:2\nExplanation:According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 71.82%) | Memory: 41.2 MB (Top 34.16%)\nclass Solution {\n public int getMaximumGenerated(int n) {\n if(n==0 || n==1) return n;\n\n int nums[]=new int [n+1];\n\n nums[0]=0;\n nums[1]=1;\n int max=Integer.MIN_VALUE;\n\n for(int i=2;i<=n;i++){\n if(i%2==0){\n nums[i]=nums[i/2];\n }\n else{\n nums[i]=nums[i/2]+nums[i/2 + 1];\n }\n max=Math.max(max,nums[i]);\n }\n return max;\n }\n}", + "title": "1646. Get Maximum in Generated Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums ​​​.", + "description_images": [], + "constraints": [ + "nums[0] = 0", + "nums[1] = 1", + "nums[2 * i] = nums[i] when 2 <= 2 * i <= n", + "nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7\nOutput:3\nExplanation:According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:1\nExplanation:According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3\nOutput:2\nExplanation:According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 84.4%) | Memory: 17.50 MB (Top 12.64%)\n\nfrom queue import deque\n\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n \n def arrgen(n):\n yield 0\n q = deque([1])\n while True:\n yield q[0]\n q.append(q[0])\n q.append(q[0]+q[1])\n q.popleft()\n \n g = arrgen(n)\n return max(next(g) for _ in range(n+1))", + "title": "1646. Get Maximum in Generated Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Choose array nums1 or nums2 to traverse (from index-0).", + "Traverse the current array from left to right.", + "If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path)." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput:30\nExplanation:Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green[2,4,6,8,10].", + "image": "https://assets.leetcode.com/uploads/2020/07/16/sample_1_1893.png" + }, + { + "text": "Example 2: Input:nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput:109\nExplanation:Maximum sum is obtained with the path[1,3,5,100].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput:40\nExplanation:There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long currSum = 0, sum1 = 0, sum2 = 0;\n int i = 0;\n int j = 0;\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] == nums2[j]) {\n currSum += Math.max(sum1, sum2) + nums2[j];\n sum1 = 0;\n sum2 = 0;\n i++;\n j++;\n }\n else if(nums1[i] < nums2[j]){\n sum1 += nums1[i++];\n } else {\n sum2 += nums2[j++];\n }\n }\n \n while(i < nums1.length){\n sum1 += nums1[i++];\n }\n while(j < nums2.length){\n sum2 += nums2[j++];\n }\n return (int)((currSum + Math.max(sum1, sum2)) % 1000000007);\n }\n}\n", + "title": "1537. Get the Maximum Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Choose array nums1 or nums2 to traverse (from index-0).", + "Traverse the current array from left to right.", + "If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path)." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput:30\nExplanation:Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green[2,4,6,8,10].", + "image": "https://assets.leetcode.com/uploads/2020/07/16/sample_1_1893.png" + }, + { + "text": "Example 2: Input:nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput:109\nExplanation:Maximum sum is obtained with the path[1,3,5,100].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput:40\nExplanation:There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n acc1 = list(accumulate(nums1, initial = 0))\n acc2 = list(accumulate(nums2, initial = 0))\n i, j = len(nums1)-1, len(nums2)-1\n previ, prevj = len(nums1), len(nums2)\n prev_maxscore = 0\n while i >= 0 and j >= 0:\n while i >= 0 and j >= 0 and nums1[i] < nums2[j]:\n j -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n while i >= 0 and j >= 0 and nums2[j] < nums1[i]:\n i -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n prev_maxscore += max(acc1[previ]-acc1[0], acc2[prevj]-acc2[0])\n return prev_maxscore % (10**9 + 7)\n", + "title": "1537. Get the Maximum Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people, each person has a unique id between 0 and n-1 . Given the arrays watchedVideos and friends , where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i . Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png", + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png" + ], + "constraints": [ + "n == watchedVideos.length == friends.length", + "2 <= n <= 100", + "1 <= watchedVideos[i].length <= 100", + "1 <= watchedVideos[i][j].length <= 8", + "0 <= friends[i].length < n", + "0 <= friends[i][j] < n", + "0 <= id < n", + "1 <= level < n", + "if friends[i] contains j , then friends[j] contains i" + ], + "examples": [ + { + "text": "Example 1: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput:[\"B\",\"C\"]\nExplanation:You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2", + "image": null + }, + { + "text": "Example 2: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput:[\"D\"]\nExplanation:You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List watchedVideosByFriends(List> watchedVideos, int[][] friends, int id, int level) {\n int n = friends.length;\n boolean[] visited = new boolean[n];\n List> graph = new ArrayList<>();\n for(int i=0;i());\n for(int i=0;i queue = new ArrayDeque<>();\n queue.offer(id);\n visited[id] = true;\n Map answer = new HashMap<>();\n while(!queue.isEmpty() && level>0){\n int size = queue.size();\n for(int i=0;i sortedQueue = new PriorityQueue<>((a,b)->{\n if(a[1].equals(b[1])) return a[0].compareTo(b[0]);\n return Integer.parseInt(a[1])-Integer.parseInt(b[1]);\n });\n for(String key: answer.keySet()){\n sortedQueue.offer(new String[]{key,Integer.toString(answer.get(key))});\n }\n List finalAnswer = new ArrayList<>();\n while(!sortedQueue.isEmpty()) finalAnswer.add(sortedQueue.remove()[0]);\n return finalAnswer;\n }\n}\n", + "title": "1311. Get Watched Videos by Your Friends", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people, each person has a unique id between 0 and n-1 . Given the arrays watchedVideos and friends , where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i . Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png", + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png" + ], + "constraints": [ + "n == watchedVideos.length == friends.length", + "2 <= n <= 100", + "1 <= watchedVideos[i].length <= 100", + "1 <= watchedVideos[i][j].length <= 8", + "0 <= friends[i].length < n", + "0 <= friends[i][j] < n", + "0 <= id < n", + "1 <= level < n", + "if friends[i] contains j , then friends[j] contains i" + ], + "examples": [ + { + "text": "Example 1: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput:[\"B\",\"C\"]\nExplanation:You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2", + "image": null + }, + { + "text": "Example 2: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput:[\"D\"]\nExplanation:You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n\t\tq=[id]\n\t\tvis=set([id])\n\t\tl=0\n\t\twhile l nums[j]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,2]\nOutput:true\nExplanation:There is 1 global inversion and 1 local inversion.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,0]\nOutput:false\nExplanation:There are 2 global inversions and 1 local inversion.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 34.63%) | Memory: 77.1 MB (Top 70.64%)\nclass Solution {\n public boolean isIdealPermutation(int[] nums) {\n\n for(int i=0;i1) return false;\n }\n\n return true;\n }\n}", + "title": "775. Global and Local Inversions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1] . The number of global inversions is the number of the different pairs (i, j) where: The number of local inversions is the number of indices i where: Return true if the number of global inversions is equal to the number of local inversions .", + "description_images": [], + "constraints": [ + "0 <= i < j < n", + "nums[i] > nums[j]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,2]\nOutput:true\nExplanation:There is 1 global inversion and 1 local inversion.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,0]\nOutput:false\nExplanation:There are 2 global inversions and 1 local inversion.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 620 ms (Top 99.42%) | Memory: 31.10 MB (Top 5.81%)\n\nclass Solution:\n def isIdealPermutation(self, A: List[int]) -> bool:\n for i in range(len(A)):\n if i - A[i] > 1 or i - A[i] < -1: return False\n return True\n", + "title": "775. Global and Local Inversions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You own a Goal Parser that can interpret a string command . The command consists of an alphabet of \"G\" , \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\" , \"()\" as the string \"o\" , and \"(al)\" as the string \"al\" . The interpreted strings are then concatenated in the original order. Given the string command , return the Goal Parser 's interpretation of command .", + "description_images": [], + "constraints": [ + "1 <= command.length <= 100", + "command consists of \"G\" , \"()\" , and/or \"(al)\" in some order." + ], + "examples": [ + { + "text": "Example 1: Input:command = \"G()(al)\"\nOutput:\"Goal\"\nExplanation:The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".", + "image": null + }, + { + "text": "Example 2: Input:command = \"G()()()()(al)\"\nOutput:\"Gooooal\"", + "image": null + }, + { + "text": "Example 3: Input:command = \"(al)G(al)()()G\"\nOutput:\"alGalooG\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.40 MB (Top 29.82%)\n\nclass Solution {\n public String interpret(String c) {\n StringBuilder st = new StringBuilder();\n for(int i =0; i G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".", + "image": null + }, + { + "text": "Example 2: Input:command = \"G()()()()(al)\"\nOutput:\"Gooooal\"", + "image": null + }, + { + "text": "Example 3: Input:command = \"(al)G(al)()()G\"\nOutput:\"alGalooG\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def interpret(self, command: str) -> str:\n return command.replace('()','o').replace('(al)','al')\n", + "title": "1678. Goal Parser Interpretation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: Return the final sentence representing the conversion from sentence to Goat Latin .", + "description_images": [], + "constraints": [ + "If a word begins with a vowel ( 'a' , 'e' , 'i' , 'o' , or 'u' ), append \"ma\" to the end of the word. For example, the word \"apple\" becomes \"applema\" .", + "For example, the word \"apple\" becomes \"applema\" .", + "If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\" . For example, the word \"goat\" becomes \"oatgma\" .", + "For example, the word \"goat\" becomes \"oatgma\" .", + "Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1 . For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.", + "For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"I speak Goat Latin\"\nOutput:\"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput:\"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 83.72%) | Memory: 42.5 MB (Top 62.02%)\nclass Solution {\n public String toGoatLatin(String sentence) {\n StringBuffer sb = new StringBuffer();\n StringBuffer temp = new StringBuffer(\"a\"); // temporary stringbuffer\n\n for(String str : sentence.split(\" \")) {\n if(beginsWithConsonant(str)) {\n sb.append(str.substring(1)); // removing the first letter\n sb.append(str.charAt(0)); // appending it to the end\n } else {\n sb.append(str);\n }\n\n sb.append(\"ma\"); // appending \"ma\" to the end of the word (common operation)\n sb.append(temp); // adding one letter 'a' to the end of each word\n\n // the first word gets \"a\" added to the end,\n // the second word gets \"aa\" added to the end,\n // and so on.\n temp.append(\"a\"); // increasing the a's for every word\n sb.append(\" \"); // to put space between words\n }\n\n return sb.toString().trim(); // using trim() to remove the one extra space from the end of string.\n }\n\n public boolean beginsWithConsonant(String str) {\n return \"aeiou\".indexOf(str.toLowerCase().charAt(0)) == -1;\n }\n}", + "title": "824. Goat Latin", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: Return the final sentence representing the conversion from sentence to Goat Latin .", + "description_images": [], + "constraints": [ + "If a word begins with a vowel ( 'a' , 'e' , 'i' , 'o' , or 'u' ), append \"ma\" to the end of the word. For example, the word \"apple\" becomes \"applema\" .", + "For example, the word \"apple\" becomes \"applema\" .", + "If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\" . For example, the word \"goat\" becomes \"oatgma\" .", + "For example, the word \"goat\" becomes \"oatgma\" .", + "Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1 . For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.", + "For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"I speak Goat Latin\"\nOutput:\"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput:\"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n wordList, result, index = sentence.split(' '), \"\", 1\n for word in wordList:\n if index > 1:\n result += \" \"\n firstLetter = word[0]\n if firstLetter in 'aeiouAEIOU':\n result += word + \"ma\"\n else:\n result += word[1:] + firstLetter + \"ma\"\n for i in range(index):\n result += 'a'\n index += 1\n return result\n", + "title": "824. Goat Latin", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We have n cities labeled from 1 to n . Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold . More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: Given the two integers, n and threshold , and an array of queries , you must determine for each queries[i] = [a i , b i ] if cities a i and b i are connected directly or indirectly. (i.e. there is some path between them). Return an array answer , where answer.length == queries.length and answer[i] is true if for the i th query, there is a path between a i and b i , or answer[i] is false if there is no path.", + "description_images": [], + "constraints": [ + "x % z == 0 ,", + "y % z == 0 , and", + "z > threshold ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\nOutput:[false,false,true]\nExplanation:The divisors for each number:\n1: 1\n2: 1, 2\n3: 1,34: 1, 2,45: 1,56: 1, 2,3,6Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6", + "image": "https://assets.leetcode.com/uploads/2020/10/09/ex1.jpg" + }, + { + "text": "Example 2: Input:n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\nOutput:[true,true,true,true,true]\nExplanation:The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.", + "image": "https://assets.leetcode.com/uploads/2020/10/10/tmp.jpg" + }, + { + "text": "Example 3: Input:n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\nOutput:[false,false,false,false,false]\nExplanation:Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].", + "image": "https://assets.leetcode.com/uploads/2020/10/17/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 59.15%) | Memory: 91.1 MB (Top 32.39%)\n//Solving the problem using Disjoint Set Union Find approach\n\nclass Solution {\n\n public int find(int x){\n\n if(parent[x] == x)\n return x;\n\n //Optimising by placing the same parent for all the elements to reduce reduntant calls\n return parent[x] = find(parent[x]);\n }\n\n public void union(int a, int b){\n\n a = find(a);\n b = find(b);\n\n //Using Rank optimisation\n if(rank[a] > rank[b]){\n parent[b] = a;\n rank[a] += rank[b];\n }\n\n else{\n parent[a] = b;\n rank[b] += rank[a];\n }\n\n //parent[b] = a;\n }\n\n int parent[];\n int rank[];\n public List areConnected(int n, int threshold, int[][] queries) {\n\n List ans = new ArrayList();\n parent = new int[n+1];\n rank = new int[n+1];\n\n for(int i=1; i<=n; i++){\n //Each element is its own parent\n parent[i] = i;\n //At beginning each element has rank 1\n rank[i] = 1;\n }\n\n // Finding the possible divisors with pairs above given threshold\n for(int th = threshold+1; th<=n; th++){\n\n int mul = 1;\n while(mul * th <= n){\n //If possible pair then making a union of those paired element\n union(th, mul*th);\n mul++;\n }\n }\n\n //Generating ans for all possible queries\n for(int[] query : queries){\n ans.add((find(query[0]) == find(query[1])));\n }\n return ans;\n }\n}", + "title": "1627. Graph Connectivity With Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We have n cities labeled from 1 to n . Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold . More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: Given the two integers, n and threshold , and an array of queries , you must determine for each queries[i] = [a i , b i ] if cities a i and b i are connected directly or indirectly. (i.e. there is some path between them). Return an array answer , where answer.length == queries.length and answer[i] is true if for the i th query, there is a path between a i and b i , or answer[i] is false if there is no path.", + "description_images": [], + "constraints": [ + "x % z == 0 ,", + "y % z == 0 , and", + "z > threshold ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\nOutput:[false,false,true]\nExplanation:The divisors for each number:\n1: 1\n2: 1, 2\n3: 1,34: 1, 2,45: 1,56: 1, 2,3,6Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6", + "image": "https://assets.leetcode.com/uploads/2020/10/09/ex1.jpg" + }, + { + "text": "Example 2: Input:n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\nOutput:[true,true,true,true,true]\nExplanation:The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.", + "image": "https://assets.leetcode.com/uploads/2020/10/10/tmp.jpg" + }, + { + "text": "Example 3: Input:n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\nOutput:[false,false,false,false,false]\nExplanation:Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].", + "image": "https://assets.leetcode.com/uploads/2020/10/17/ex3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 881 ms (Top 97.89%) | Memory: 49.3 MB (Top 35.92%)\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n parent = list(range(n+1))\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n parent[find(i)] = find(j)\n if not threshold: return [True]*len(queries)\n for i in range(1, n+1):\n for j in range(2*i, n+1, i):\n if i > threshold: union(i,j)\n return [find(i) == find(j) for i,j in queries]", + "title": "1627. Graph Connectivity With Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An n-bit gray code sequence is a sequence of 2 n integers where: Given an integer n , return any valid n-bit gray code sequence .", + "description_images": [], + "constraints": [ + "Every integer is in the inclusive range [0, 2 n - 1] ,", + "The first integer is 0 ,", + "An integer appears no more than once in the sequence,", + "The binary representation of every pair of adjacent integers differs by exactly one bit , and", + "The binary representation of the first and last integers differs by exactly one bit ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[0,1,3,2]\nExplanation:The binary representation of [0,1,3,2] is [00,01,11,10].\n- 00and 01differ by one bit\n-01 and11 differ by one bit\n- 11and 10differ by one bit\n-10 and00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n-00 and10 differ by one bit\n- 10and 11differ by one bit\n-11 and01 differ by one bit\n- 01and 00differ by one bit", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:[0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List grayCode(int n) {\n ArrayList list=new ArrayList();\n for(int i=0;i<(1<>1));\n }\n return list;\n }\n}\n", + "title": "89. Gray Code", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An n-bit gray code sequence is a sequence of 2 n integers where: Given an integer n , return any valid n-bit gray code sequence .", + "description_images": [], + "constraints": [ + "Every integer is in the inclusive range [0, 2 n - 1] ,", + "The first integer is 0 ,", + "An integer appears no more than once in the sequence,", + "The binary representation of every pair of adjacent integers differs by exactly one bit , and", + "The binary representation of the first and last integers differs by exactly one bit ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[0,1,3,2]\nExplanation:The binary representation of [0,1,3,2] is [00,01,11,10].\n- 00and 01differ by one bit\n-01 and11 differ by one bit\n- 11and 10differ by one bit\n-10 and00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n-00 and10 differ by one bit\n- 10and 11differ by one bit\n-11 and01 differ by one bit\n- 01and 00differ by one bit", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:[0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "import math\nclass Solution(object):\n def grayCode(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)]\n grayCodes = [0]\n for diff in allowedDiffs:\n grayCodes += [code + diff for code in reversed(grayCodes)]\n return grayCodes\n", + "title": "89. Gray Code", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 .", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"\nOutput:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String gcdOfStrings(String str1, String str2) {\n \n int length1 = str1.length();\n int length2 = str2.length();\n String temp;\n \n for(int i=gcd(length1,length2); i>0 && length1 % i == 0 && length2 % i == 0; i--) {\n if(str1.substring(0,i).equals(str2.substring(0,i))) {\n if(doesRepeat(str1.substring(0,i),str1,str2))\n return str1.substring(0,i);\n }\n }\n return \"\";\n \n }\n public int gcd(int a, int b) {\n if(b==0)\n return a;\n return gcd(b,a % b);\n }\n public boolean doesRepeat(String s, String str1, String str2) {\n int sLength = s.length();\n boolean bool1 = true, bool2 = true;\n String temp = str1,temp2;\n \n while(sLength < temp.length()) {\n temp2 = temp.substring(sLength,sLength*2);\n \n if(s.equals(temp2));\n else\n bool1 = false;\n temp = temp.substring(sLength,temp.length());\n }\n temp = str2;\n while(sLength < temp.length()) {\n temp2 = temp.substring(sLength,sLength*2);\n if(s.equals(temp2));\n else\n bool2 = false;\n temp = temp.substring(sLength,temp.length());\n }\n return bool1 && bool2;\n }\n \n}\n", + "title": "1071. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 .", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"\nOutput:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 85 ms (Top 15.89%) | Memory: 14 MB (Top 5.19%)\nclass Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n\n if len(str2) > len(str1):\n str1, str2 = str2, str1\n\n curr_str2 = str2\n while True:\n\n rep = len(str1)//len(curr_str2)\n\n if curr_str2*rep == str1:\n return curr_str2\n\n found = False\n for i in range(len(curr_str2)-1, 1, -1):\n try_str2 = curr_str2[:i]\n rep2 = len(str2)//len(try_str2)\n\n if try_str2*rep2 == str2:\n curr_str2 = try_str2\n found = True\n break\n\n if not found:\n break\n return \"\"", + "title": "1071. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string of English letters s , return the greatest English letter which occurs as both a lowercase and uppercase letter in s . The returned letter should be in uppercase . If no such letter exists, return an empty string . An English letter b is greater than another letter a if b appears after a in the English alphabet.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase and uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lEeTcOdE\"\nOutput:\"E\"\nExplanation:The letter 'E' is the only letter to appear in both lower and upper case.", + "image": null + }, + { + "text": "Example 2: Input:s = \"arRAzFif\"\nOutput:\"R\"\nExplanation:The letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"AbCdEfGhIjK\"\nOutput:\"\"\nExplanation:There is no letter that appears in both lower and upper case.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 53.1%) | Memory: 41.50 MB (Top 23.1%)\n\nclass Solution\n{\n public String greatestLetter(String s)\n {\n Set set = new HashSet<>();\n for(char ch : s.toCharArray())\n set.add(ch);\n \n for(char ch = 'Z'; ch >= 'A'; ch--)\n if(set.contains(ch) && set.contains((char)('a'+(ch-'A'))))\n return \"\"+ch;\n return \"\";\n }\n}", + "title": "2309. Greatest English Letter in Upper and Lower Case", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string of English letters s , return the greatest English letter which occurs as both a lowercase and uppercase letter in s . The returned letter should be in uppercase . If no such letter exists, return an empty string . An English letter b is greater than another letter a if b appears after a in the English alphabet.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase and uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lEeTcOdE\"\nOutput:\"E\"\nExplanation:The letter 'E' is the only letter to appear in both lower and upper case.", + "image": null + }, + { + "text": "Example 2: Input:s = \"arRAzFif\"\nOutput:\"R\"\nExplanation:The letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"AbCdEfGhIjK\"\nOutput:\"\"\nExplanation:There is no letter that appears in both lower and upper case.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 34 ms (Top 92.91%) | Memory: 13.8 MB (Top 66.80%)\n\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n cnt = Counter(s)\n return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), \"\")", + "title": "2309. Greatest English Letter in Upper and Lower Case", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the maximum possible sum of elements of the array such that it is divisible by three .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 4 * 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,5,1,8]\nOutput:18\nExplanation:Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [4]\nOutput:0\nExplanation:Since 4 is not divisible by 3, do not pick any number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4]\nOutput:12\nExplanation:Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 68.46%) | Memory: 54.3 MB (Top 56.38%)\n\nclass Solution {\n\n public int maxSumDivThree(int[] nums) {\n int r0 = 0;\n int r1 = 0;\n int r2 = 0;\n for (int i = 0; i < nums.length; i++) {\n int nr0 = r0;\n int nr1 = r1;\n int nr2 = r2;\n int a = r0 + nums[i];\n int b = r1 + nums[i];\n int c = r2 + nums[i];\n if (a % 3 == 0) {\n nr0 = Math.max(nr0, a);\n } else if (a % 3 == 1) {\n nr1 = Math.max(nr1, a);\n } else if (a % 3 == 2) {\n nr2 = Math.max(nr2, a);\n }\n\n if (b % 3 == 0) {\n nr0 = Math.max(nr0, b);\n } else if (b % 3 == 1) {\n nr1 = Math.max(nr1, b);\n } else if (b % 3 == 2) {\n nr2 = Math.max(nr2, b);\n }\n\n if (c % 3 == 0) {\n nr0 = Math.max(nr0, c);\n } else if (c % 3 == 1) {\n nr1 = Math.max(nr1, c);\n } else if (c % 3 == 2) {\n nr2 = Math.max(nr2, c);\n }\n r0=nr0;\n r1=nr1;\n r2=nr2;\n }\n\n return r0;\n }\n}", + "title": "1262. Greatest Sum Divisible by Three", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the maximum possible sum of elements of the array such that it is divisible by three .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 4 * 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,5,1,8]\nOutput:18\nExplanation:Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [4]\nOutput:0\nExplanation:Since 4 is not divisible by 3, do not pick any number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4]\nOutput:12\nExplanation:Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 190 ms (Top 92.53%) | Memory: 22.10 MB (Top 78.57%)\n\nfrom math import inf\n\n\nclass Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n res = 0\n r1_min1 = inf\n r1_min2 = inf\n r2_min1 = inf\n r2_min2 = inf\n\n for v in nums:\n res += v\n if v % 3 == 1:\n if v < r1_min1:\n r1_min2 = r1_min1\n r1_min1 = v\n elif v < r1_min2:\n r1_min2 = v\n elif v % 3 == 2:\n if v < r2_min1:\n r2_min2 = r2_min1\n r2_min1 = v\n elif v < r2_min2:\n r2_min2 = v\n\n if res % 3 == 1:\n res -= min(r1_min1, r2_min1 + r2_min2)\n elif res % 3 == 2:\n res -= min(r2_min1, r1_min1 + r1_min2)\n\n return res\n", + "title": "1262. Greatest Sum Divisible by Three", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 2D array grid of size 2 x n , where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1) . Each robot may only move to the right ( (r, c) to (r, c + 1) ) or down ( (r, c) to (r + 1, c) ). At the start of the game, the first robot moves from (0, 0) to (1, n-1) , collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0 . Then, the second robot moves from (0, 0) to (1, n-1) , collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally , return the number of points collected by the second robot.", + "description_images": [], + "constraints": [ + "grid.length == 2", + "n == grid[r].length", + "1 <= n <= 5 * 10^4", + "1 <= grid[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,5,4],[1,5,1]]\nOutput:4\nExplanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a1.png" + }, + { + "text": "Example 2: Input:grid = [[3,3,1],[8,5,2]]\nOutput:4\nExplanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a2.png" + }, + { + "text": "Example 3: Input:grid = [[1,3,1,15],[1,3,3,1]]\nOutput:7\nExplanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 40.95%) | Memory: 94.7 MB (Top 51.18%)\n\nclass Solution {\n public long gridGame(int[][] grid) {\n int n = grid[0].length;\n long preRow1[] = new long[n];\n long preRow2[] = new long[n];\n\n preRow1[0] = grid[0][0];\n preRow2[0] = grid[1][0];\n\n for(int i = 1;i int:\n top, bottom, res = sum(g[0]), 0, math.inf\n for g0, g1 in zip(g[0], g[1]):\n top -= g0\n res = min(res, max(top, bottom))\n bottom += g1\n return res", + "title": "2017. Grid Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off . You are given a 2D array of lamp positions lamps , where lamps[i] = [row i , col i ] indicates that the lamp at grid[row i ][col i ] is turned on . Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal . You are also given another 2D array queries , where queries[j] = [row j , col j ] . For the j th query, determine whether grid[row j ][col j ] is illuminated or not. After answering the j th query, turn off the lamp at grid[row j ][col j ] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[row j ][col j ] . Return an array of integers ans , where ans[j] should be 1 if the cell in the j th query was illuminated, or 0 if the lamp was not.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "0 <= lamps.length <= 20000", + "0 <= queries.length <= 20000", + "lamps[i].length == 2", + "0 <= row i , col i < n", + "queries[j].length == 2", + "0 <= row j , col j < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput:[1,0]\nExplanation:We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0thquery asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.The 1stquery asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.", + "image": "https://assets.leetcode.com/uploads/2020/08/19/illu_1.jpg" + }, + { + "text": "Example 2: Input:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput:[1,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {\n //we take 5 hashmap\n //1st hashmap for row\n HashMap row = new HashMap<>();\n //2nd hashmap for column\n HashMap col = new HashMap<>();\n //3rd hashmap for lower diagonal\n HashMap d1 = new HashMap<>();\n //4th diagonal for upper diagonal\n HashMap d2 = new HashMap<>();\n //5th diagonal for cell no meaning lamp is present at this spot\n HashMap cellno = new HashMap<>();\n \n for(int i = 0;i List[int]:\n rows = collections.Counter()\n cols = collections.Counter()\n diags1 = collections.Counter()\n diags2 = collections.Counter()\n lamps = {tuple(lamp) for lamp in lamps}\n \n for i, j in lamps:\n rows[i] += 1\n cols[j] += 1\n diags1[i + j] += 1\n diags2[i - j] += 1\n \n ans = []\n directions = ((-1, -1), (-1, 0), (-1, 1),\n (0, -1), (0, 0), (0, 1),\n (1, -1), (1, 0), (1, 1))\n \n for i, j in queries:\n if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:\n ans.append(1)\n else:\n ans.append(0)\n \n for di, dj in directions:\n newI, newJ = i + di, j + dj\n if (newI, newJ) not in lamps:\n continue\n lamps.remove((newI, newJ))\n rows[newI] -= 1\n cols[newJ] -= 1\n diags1[newI + newJ] -= 1\n diags2[newI - newJ] -= 1\n \n return ans", + "title": "1001. Grid Illumination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings strs , group the anagrams together. You can return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 10^4", + "0 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nOutput:[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"\"]\nOutput:[[\"\"]]", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"a\"]\nOutput:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 40.82%) | Memory: 46.2 MB (Top 88.53%)\nclass Solution {\n public List> groupAnagrams(String[] strs) {\n HashMap> hm=new HashMap<>();\n for(String s : strs)\n {\n char ch[]=s.toCharArray();\n Arrays.sort(ch);\n StringBuilder sb=new StringBuilder(\"\");\n for(char c: ch)\n {\n sb.append(c);\n }\n String str=sb.toString();\n if(hm.containsKey(str))\n {\n ArrayList temp=hm.get(str);\n temp.add(s);\n hm.put(str,temp);\n }\n else\n {\n ArrayList temp=new ArrayList<>();\n temp.add(s);\n hm.put(str,temp);\n }\n }\n System.out.println(hm);\n List> res=new ArrayList<>();\n for(ArrayList arr : hm.values())\n {\n res.add(arr);\n }\n return res;\n }\n}", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings strs , group the anagrams together. You can return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 10^4", + "0 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nOutput:[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"\"]\nOutput:[[\"\"]]", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"a\"]\nOutput:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n strs_table = {}\n\n for string in strs:\n sorted_string = ''.join(sorted(string))\n\n if sorted_string not in strs_table:\n strs_table[sorted_string] = []\n\n strs_table[sorted_string].append(string)\n\n return list(strs_table.values())\n", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1 . You are given an integer array groupSizes , where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3 , then person 1 must be in a group of size 3 . Return a list of groups such that each person i is in a group of size groupSizes[i] . Each person should appear in exactly one group , and every person must be in a group. If there are multiple answers, return any of them . It is guaranteed that there will be at least one valid solution for the given input.", + "description_images": [], + "constraints": [ + "groupSizes.length == n", + "1 <= n <= 500", + "1 <= groupSizes[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:groupSizes = [3,3,3,3,3,1,3]\nOutput:[[5],[0,1,2],[3,4,6]]\nExplanation:The first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "image": null + }, + { + "text": "Example 2: Input:groupSizes = [2,1,3,3,3,2]\nOutput:[[1],[0,5],[2,3,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 5.31%) | Memory: 53.9 MB (Top 61.36%)\nclass Solution {\n public List> groupThePeople(int[] groupSizes) {\n\n List> temp = new ArrayList>();\n List> result = new ArrayList>();\n for(int i = 0; itemp.get(j).get(1)){\n result.get(j).add(i);\n temp.get(j).set(1,temp.get(j).get(1)+1);\n flag=false;\n break;\n }\n }\n if(flag){\n // comment 1\n // We create a list with index and put it to result\n List res = new ArrayList();\n res.add(i);\n result.add(res);\n // comment 2\n // we create a new list recording max value can stored and currently filled\n List tempRes = new ArrayList();\n tempRes.add(k);\n tempRes.add(1);\n temp.add(tempRes);\n }\n }\n return result;\n }\n}", + "title": "1282. Group the People Given the Group Size They Belong To", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1 . You are given an integer array groupSizes , where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3 , then person 1 must be in a group of size 3 . Return a list of groups such that each person i is in a group of size groupSizes[i] . Each person should appear in exactly one group , and every person must be in a group. If there are multiple answers, return any of them . It is guaranteed that there will be at least one valid solution for the given input.", + "description_images": [], + "constraints": [ + "groupSizes.length == n", + "1 <= n <= 500", + "1 <= groupSizes[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:groupSizes = [3,3,3,3,3,1,3]\nOutput:[[5],[0,1,2],[3,4,6]]\nExplanation:The first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "image": null + }, + { + "text": "Example 2: Input:groupSizes = [2,1,3,3,3,2]\nOutput:[[1],[0,5],[2,3,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 97.76%) | Memory: 14 MB (Top 88.55%)\nclass Solution(object):\n def groupThePeople(self, groupSizes):\n \"\"\"\n :type groupSizes: List[int]\n :rtype: List[List[int]]\n \"\"\"\n dict_group={}\n for i in range(len(groupSizes)):\n if groupSizes[i] not in dict_group:\n dict_group[groupSizes[i]]=[i]\n else:\n dict_group[groupSizes[i]].append(i)\n return_list=[]\n for i in dict_group:\n num_list=dict_group[i]\n for j in range(0,len(num_list),i):\n return_list.append(num_list[j:j+i])\n return return_list", + "title": "1282. Group the People Given the Group Size They Belong To", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings of the same length words . In one move , you can swap any two even indexed characters or any two odd indexed characters of a string words[i] . Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j] . A group of special-equivalent strings from words is a non-empty subset of words such that: Return the number of groups of special-equivalent strings from words .", + "description_images": [], + "constraints": [ + "For example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\nOutput:3\nExplanation:One group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 698 ms (Top 5.47%) | Memory: 145 MB (Top 5.47%)\n\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n if(words.length == 0 || words.length == 1) return words.length;\n\n // To store group sizes\n HashMap hashmap = new HashMap<>();\n\n // To mark the strings already part of some groups\n boolean[] isGrouped = new boolean[words.length];\n\n for(int index = 0; index < words.length; index++) {\n if(isGrouped[index]) continue; // Already grouped\n String word = words[index];\n for(int j = index + 1; j < words.length; j++) {\n if(isGrouped[j]) continue; // Already grouped\n String string = words[j];\n\n // The idea is to store count of characters on even and odd indices\n // It is done by incrementing counts of characters in both even and odd maps respectively\n // Then compare the two strings by reducing the same count in both even and odd maps\n // If both the maps are empty at last, the two strings for a group\n HashMap evens = new HashMap<>();\n HashMap odds = new HashMap<>();\n boolean isSpecialEquivalent = true;\n\n for(int i = 0; i < word.length(); i++) {\n if(i % 2 == 0) {\n evens.put(word.charAt(i), evens.getOrDefault(word.charAt(i), 0) + 1);\n } else {\n odds.put(word.charAt(i), odds.getOrDefault(word.charAt(i), 0) + 1);\n }\n }\n\n for(int i = 0; i < string.length(); i++) {\n char character = string.charAt(i);\n if(i % 2 == 0) {\n if(!evens.containsKey(character)) {\n isSpecialEquivalent = false;\n break;\n }\n\n evens.put(character, evens.get(character) - 1);\n if(evens.get(character) == 0) evens.remove(character);\n } else {\n if(!odds.containsKey(character)) {\n isSpecialEquivalent = false;\n break;\n }\n\n odds.put(character, odds.get(character) - 1);\n if(odds.get(character) == 0) odds.remove(character);\n }\n }\n\n if(isSpecialEquivalent) {\n hashmap.put(word, hashmap.getOrDefault(word, 0) + 1);\n isGrouped[j] = true;\n }\n }\n\n // If no group is formed, the word alone forms a group of size 1\n if(!hashmap.containsKey(word)) hashmap.put(word, 1);\n }\n\n return hashmap.size();\n }\n}", + "title": "893. Groups of Special-Equivalent Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings of the same length words . In one move , you can swap any two even indexed characters or any two odd indexed characters of a string words[i] . Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j] . A group of special-equivalent strings from words is a non-empty subset of words such that: Return the number of groups of special-equivalent strings from words .", + "description_images": [], + "constraints": [ + "For example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\nOutput:3\nExplanation:One group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSpecialEquivGroups(self, words) -> int:\n return len(set([(''.join(sorted(i[::2])),''.join(sorted(i[1::2]))) for i in words]))", + "title": "893. Groups of Special-Equivalent Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array of strings words . Each string consists of lowercase English letters only. No letter occurs more than once in any string of words . Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups . A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where:", + "description_images": [], + "constraints": [ + "Adding exactly one letter to the set of the letters of s1 .", + "Deleting exactly one letter from the set of the letters of s1 .", + "Replacing exactly one letter from the set of the letters of s1 with any letter, including itself." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ab\",\"cde\"]\nOutput:[2,3]\nExplanation:- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n- words[3] is not connected to any string in words.\nThus, words can be divided into 2 groups [\"a\",\"b\",\"ab\"] and [\"cde\"]. The size of the largest group is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\"]\nOutput:[1,3]\nExplanation:- words[0] is connected to words[1].\n- words[1] is connected to words[0] and words[2].\n- words[2] is connected to words[1].\nSince all strings are connected to each other, they should be grouped together.\nThus, the size of the largest group is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] groupStrings(String[] words) {\n int n = words.length;\n Arrays.sort(words, Comparator.comparingInt(String::length));\n int[] parents = new int[n];\n int[] ranks = new int[n];\n for (int i = 0; i < n; i++) parents[i] = i;\n Arrays.fill(ranks, 1);\n\n int[] masks = new int[n];\n for (int i = 0; i < n; i++) {\n int val = 0;\n for (int j = 0; j < words[i].length(); j++) {\n val += (1 << (words[i].charAt(j) - 'a'));\n }\n masks[i] = val;\n }\n Set seen = new HashSet<>();\n for (int i = 0; i < n; i++) {\n if (seen.contains(masks[i])) continue;\n for (int j = i + 1; j < n; j++) {\n if (words[i].length() + 1 < words[j].length()) break;\n int p1 = find(parents, i), p2 = find(parents, j);\n if (p1 == p2) continue;\n int a = masks[i], b = masks[j];\n if (a == b) merge(parents, ranks, p1, p2);\n int xor = a ^ b;\n int and = a & b;\n int xor1 = a ^ and, xor2 = b ^ and;\n if ((xor & (xor - 1)) == 0 || ((xor1 & (xor1 - 1)) == 0 && (xor2 & (xor2 - 1)) == 0)) {\n merge(parents, ranks, p1, p2);\n }\n }\n seen.add(masks[i]);\n }\n\n Map map = new HashMap<>();\n int max = 1;\n for (int i = 0; i < n; i++) {\n int f = find(parents, i);\n int cnt = map.getOrDefault(f, 0) + 1;\n map.put(f, cnt);\n max = Math.max(max, cnt);\n }\n\n return new int[]{map.size(), max};\n }\n\n private int find(int[] parents, int i) {\n return parents[i] = parents[i] == i ? i: find(parents, parents[i]);\n }\n\n private void merge(int[] parents, int[] ranks, int i, int j) {\n int p1 = find(parents, i), p2 = find(parents, j);\n if (p1 == p2) return;\n if (ranks[p1] > ranks[p2]) {\n parents[p1] = p2;\n parents[i] = p2;\n ranks[p2]++;\n return;\n }\n parents[p2] = p1;\n parents[j] = p1;\n ranks[p1]++;\n }\n}\n", + "title": "2157. Groups of Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array of strings words . Each string consists of lowercase English letters only. No letter occurs more than once in any string of words . Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups . A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where:", + "description_images": [], + "constraints": [ + "Adding exactly one letter to the set of the letters of s1 .", + "Deleting exactly one letter from the set of the letters of s1 .", + "Replacing exactly one letter from the set of the letters of s1 with any letter, including itself." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ab\",\"cde\"]\nOutput:[2,3]\nExplanation:- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n- words[3] is not connected to any string in words.\nThus, words can be divided into 2 groups [\"a\",\"b\",\"ab\"] and [\"cde\"]. The size of the largest group is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\"]\nOutput:[1,3]\nExplanation:- words[0] is connected to words[1].\n- words[1] is connected to words[0] and words[2].\n- words[2] is connected to words[1].\nSince all strings are connected to each other, they should be grouped together.\nThus, the size of the largest group is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class DSU:\n def __init__(self, n):\n self.root = list(range(n))\n def find(self, x):\n if self.root[x] != x:\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n self.root[self.find(x)] = self.find(y)\n\nclass Solution:\n def groupStrings(self, A: List[str]) -> List[int]: \n c = collections.defaultdict(int)\n for a in A: \n\t\t\tc[\"\".join(sorted(a))] += 1\n \n A = list(set([\"\".join(sorted(a)) for a in A]))\n n = len(A)\n \n idx = collections.defaultdict(int) # (binary representation -> index)\n\t\tdsu = DSU(n) # dsu \n\n def add(base):\n for i in range(26):\n if not base & 1 << i:\n yield base ^ 1 << i\n def dele(base):\n for i in range(26):\n if base & 1 << i:\n if base - (1 << i) != 0:\n yield base - (1 << i) \n def rep(base):\n pre, new = [], []\n for i in range(26):\n if base & 1 << i: pre.append(i)\n else: new.append(i)\n for p in pre:\n for n in new:\n yield base - (1 << p) + (1 << n) \n \n for i, a in enumerate(A):\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord('a')\n idx[base] = i\n\n for base in idx.keys():\n for new in add(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in dele(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in rep(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n \n group = collections.defaultdict(int)\n for a in A:\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord('a')\n cnum = c[a]\n group[dsu.find(idx[base])] += cnum\n \n return [len(group), max(group.values())]\n \n", + "title": "2157. Groups of Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day .", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput:16\nExplanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n int start = -1;\n int count = 0;\n \n int max = 0;\n int curr = 0;\n \n for (int i = 0; i < customers.length; i++) {\n if (grumpy[i] == 0) {\n count += customers[i];\n } else {\n curr += customers[i];\n }\n \n if (i-start > minutes) {\n start++;\n if (grumpy[start] == 1) {\n curr -= customers[start];\n }\n }\n max = Math.max(max, curr);\n }\n \n return count + max;\n }\n}\n", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day .", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput:16\nExplanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def recursion(self,index,used):\n # base case\n if index == self.n: return 0\n \n #check in dp\n if (index,used) in self.dp: return self.dp[(index,used)]\n #choice1 is using the secret technique\n choice1 = -float('inf')\n \n # we can only use secret technique once and consecutively\n if used == True :\n # use the secret technique\n end = index + self.minutes if index + self.minutes < self.n else self.n\n to_substract = self.prefix_sum[index - 1] if index != 0 else 0\n val = self.prefix_sum[end - 1] - to_substract\n choice1 = self.recursion(end,False) + val\n \n # Do not use the secret tehcnique and play simple \n choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)\n ans = choice1 if choice1 > choice2 else choice2\n \n # Memoization is done here\n self.dp[(index,used)] = ans\n return ans\n \n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n self.n = len(customers)\n self.customers = customers\n self.grumpy = grumpy\n self.minutes = minutes\n self.dp = {}\n self.prefix_sum = [x for x in customers]\n for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]\n return self.recursion(0,True)\n \n", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked .", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/** \n * Forward declaration of guess API.\n * @param num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n public int guessNumber(int n) {\n int left = 1;\n int right = n;\n \n while(left < right){\n int mid = ((right - left) / 2) + left;\n if(guess(mid) == 0)\n return mid;\n else if(guess(mid) < 0)\n right = mid - 1;\n else\n left = mid + 1;\n }\n \n return left;\n }\n}\n", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked .", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def guessNumber(self, n: int) -> int:\n l=1\n h=n\n while l<=h:\n mid=(l+h)//2\n x =guess(mid)\n if(x==0):\n return mid\n elif(x==1):\n l = mid+1\n else:\n h = mid-1\n", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We are playing the Guessing Game. The game will work as follows: Given a particular n , return the minimum amount of money you need to guarantee a win regardless of what number I pick .", + "description_images": [], + "constraints": [ + "1 <= n <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:16\nExplanation:The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n  - If this is my number, your total is $0. Otherwise, you pay $7.\n  - If my number is higher, the range is [8,10]. Guess 9.\n  - If this is my number, your total is $7. Otherwise, you pay $9.\n  - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n  - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n  - If my number is lower, the range is [1,6]. Guess 3.\n  - If this is my number, your total is $7. Otherwise, you pay $3.\n  - If my number is higher, the range is [4,6]. Guess 5.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n  - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, the range is [1,2]. Guess 1.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/graph.png" + }, + { + "text": "Example 2: Input:n = 1\nOutput:0\nExplanation:There is only one possible number, so you can guess 1 and not have to pay anything.", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:1\nExplanation:There are two possible numbers, 1 and 2.\n- Guess 1.\n  - If this is my number, your total is $0. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMoneyAmount(int n) {\n int dp[][]=new int[n+1][n+1];\n for(int a[]:dp){\n Arrays.fill(a,-1);\n }\n return solve(1,n,dp);\n }\n static int solve(int start,int end,int[][] dp){\n if(start>=end) return 0;\n if(dp[start][end]!=-1) return dp[start][end];\n int min=Integer.MAX_VALUE;\n for(int i=start;i<=end;i++){\n min=Math.min(min,i+Math.max(solve(start,i-1,dp),solve(i+1,end,dp)));\n }\n dp[start][end]=min;\n return min;\n }\n}", + "title": "375. Guess Number Higher or Lower II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are playing the Guessing Game. The game will work as follows: Given a particular n , return the minimum amount of money you need to guarantee a win regardless of what number I pick .", + "description_images": [], + "constraints": [ + "1 <= n <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:16\nExplanation:The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n  - If this is my number, your total is $0. Otherwise, you pay $7.\n  - If my number is higher, the range is [8,10]. Guess 9.\n  - If this is my number, your total is $7. Otherwise, you pay $9.\n  - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n  - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n  - If my number is lower, the range is [1,6]. Guess 3.\n  - If this is my number, your total is $7. Otherwise, you pay $3.\n  - If my number is higher, the range is [4,6]. Guess 5.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n  - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, the range is [1,2]. Guess 1.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/graph.png" + }, + { + "text": "Example 2: Input:n = 1\nOutput:0\nExplanation:There is only one possible number, so you can guess 1 and not have to pay anything.", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:1\nExplanation:There are two possible numbers, 1 and 2.\n- Guess 1.\n  - If this is my number, your total is $0. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMoneyAmount(self, n):\n # For an interval [l,r], we choose a num, which if incorrect still\n # allows us to know whether the secret# is in either [l,num-1] or\n # [num+1,r]. So, the worst-case (w-c) cost is\n #\n # num + max(w-c cost in [l,num-1], w-c cost in [num+1,r])\n # \n # We do this by recursion and binary search, starting with [1,n].\n\n @lru_cache(None) # <-- we cache function results to avoid recomputing them\n def dp(l = 1, r = n)-> int:\n if r-l < 1: return 0 # <-- base case for the recursion; one number in [l,r] \n ans = 1000 # <-- the answer for n = 200 is 952\n \n for choice in range((l+r)//2,r):\n ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r)))\n\n return ans\n\n return dp()", + "title": "375. Guess Number Higher or Lower II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master . You may call Master.guess(word) where word is a six-letter-long string, and it must be from words . Master.guess(word) returns: There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word) . For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).", + "description_images": [], + "constraints": [ + "-1 if word is not from words , or", + "an integer representing the number of exact matches (value and position) of your guess to the secret word." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"acckzz\", words = [\"acckzz\",\"ccbazz\",\"eiowzz\",\"abcczz\"], allowedGuesses = 10\nOutput:You guessed the secret word correctly.\nExplanation:master.guess(\"aaaaaa\") returns -1, because \"aaaaaa\" is not in wordlist.\nmaster.guess(\"acckzz\") returns 6, because \"acckzz\" is secret and has all 6 matches.\nmaster.guess(\"ccbazz\") returns 3, because \"ccbazz\" has 3 matches.\nmaster.guess(\"eiowzz\") returns 2, because \"eiowzz\" has 2 matches.\nmaster.guess(\"abcczz\") returns 4, because \"abcczz\" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case.", + "image": null + }, + { + "text": "Example 2: Input:secret = \"hamada\", words = [\"hamada\",\"khaled\"], allowedGuesses = 10\nOutput:You guessed the secret word correctly.\nExplanation:Since there are two words, you can guess both.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findSecretWord(self, words: List[str], master: 'Master') -> None: \n k = 1 # for tracing the number of loops\n matches = 0\n blacklists = [[] for i in range(6)]\n \n while matches != 6:\n n = len(words)\n r = random.randint(0, n - 1)\n matches = master.guess(words[r])\n key = words[r]\n # print(k, n, r, matches, key)\n \n words.pop(r)\n \n if matches == 0:\n for i in range(6):\n blacklists[i].append(key[i])\n # print(blacklists)\n \n elif matches > 0 and matches < 6:\n candidates = []\n for i in range(n - 1):\n count = 0\n for j in range(6):\n if words[i][j] not in blacklists[j] and words[i][j] == key[j]:\n count += 1\n if count >= matches:\n candidates.append(words[i])\n \n words = candidates.copy()\n # print(words)\n \n k += 1\n", + "title": "843. Guess the Word", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index .", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]\nOutput:3\nExplanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) {\n int n = citations.length;\n Arrays.sort(citations);\n for(int i = 0; i < n; i++) {\n int hlen = (n-1) - i + 1;\n if(citations[i] >= hlen) {\n return hlen;\n }\n }\n return 0;\n }\n}\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index .", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]\nOutput:3\nExplanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n num = sorted(citations)\n h = 0\n j = len(num)-1\n for i in range(len(num)):\n if i+1 <=num[i] and j-i+1>=num[i]:\n h =max(num[i],h)\n elif i+1 <= num[i] and j-i+1 num[i] and j-i+1 >=num[i]:\n h = max(h, num[i])\n \n return h\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper and citations is sorted in an ascending order , return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . You must write an algorithm that runs in logarithmic time.", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 10^5", + "0 <= citations[i] <= 1000", + "citations is sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:citations = [0,1,3,5,6]\nOutput:3\nExplanation:[0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,2,100]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) {\n int n=citations.length;\n int res=0;\n for(int i=0;i=n-i)\n {\n return n-i;\n }\n }\n return res;\n }\n}\n", + "title": "275. H-Index II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper and citations is sorted in an ascending order , return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . You must write an algorithm that runs in logarithmic time.", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 10^5", + "0 <= citations[i] <= 1000", + "citations is sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:citations = [0,1,3,5,6]\nOutput:3\nExplanation:[0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,2,100]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n n = len(citations)\n for h in range(n, -1, -1):\n if h <= n - bisect.bisect_left(citations, h):\n return h\n", + "title": "275. H-Index II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y , return the Hamming distance between them .", + "description_images": [], + "constraints": [ + "0 <= x, y <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 1, y = 4\nOutput:2\nExplanation:1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hammingDistance(int x, int y) {\n int ans=x^y;\n int count=0;\n while(ans>0){\n count+=ans&1;\n ans>>=1;\n }\n \n return count;\n }\n}", + "title": "461. Hamming Distance", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y , return the Hamming distance between them .", + "description_images": [], + "constraints": [ + "0 <= x, y <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 1, y = 4\nOutput:2\nExplanation:1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n\t\t# First, using XOR Bitwise Operator, we take all distinct set bits.\n z = x ^ y\n\t\t# We inicialize our answer with zero.\n ans = 0\n\t\t# Iterate while our z is not zero.\n while z:\n\t\t\t# Every iteration we add one to our answer.\n ans += 1\n\t\t\t# Using the expression z & (z - 1), we erase the lowest set bit in z.\n z &= z - 1\n return ans\n", + "title": "461. Hamming Distance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput:true\nExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4\nOutput:false\nExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 96 ms (Top 31.30%) | Memory: 61.2 MB (Top 7.04%)\nclass Solution {\n public boolean isNStraightHand(int[] hand, int groupSize) {\n if(hand.length % groupSize != 0)\n return false;\n\n Map map = new HashMap<>();\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for(int card : hand){\n if(map.containsKey(card))\n map.put(card, map.get(card) + 1);\n else {\n map.put(card, 1);\n minHeap.add(card);\n }\n }\n\n while(!minHeap.isEmpty()){\n int min = minHeap.peek();\n for(int i=min; i < min + groupSize; i++){\n if(!map.containsKey(i) || map.get(i) == 0)\n return false;\n map.put(i, map.get(i) - 1);\n if(map.get(i) == 0){\n if(minHeap.peek() != i)\n return false;\n minHeap.poll();\n }\n }\n }\n return true;\n }\n}", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput:true\nExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4\nOutput:false\nExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 304 ms (Top 61.38%) | Memory: 15.7 MB (Top 75.38%)\n\n#####################################################################################################################\n# Problem: Hand of Straights\n# Solution : Hash Table, Min Heap\n# Time Complexity : O(n logn)\n# Space Complexity : O(n)\n#####################################################################################################################\n\nclass Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n if len(hand) % groupSize:\n return False\n\n freq = collections.defaultdict(int)\n\n for num in hand:\n freq[num] += 1\n\n min_heap = list(freq.keys())\n heapq.heapify(min_heap)\n\n while min_heap:\n smallest = min_heap[0]\n for num in range(smallest, smallest + groupSize):\n if num not in freq:\n return False\n freq[num] -= 1\n\n if freq[num] == 0:\n if num != min_heap[0]:\n return False\n heapq.heappop(min_heap)\n return True", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19\nOutput:true\nExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 47.06%) | Memory: 41.5 MB (Top 32.65%)\nclass Solution {\n public boolean isHappy(int n) {\n // Create a hash set...\n Set hset = new HashSet();\n // If the number is not in the HashSet, we should add it...\n while (hset.add(n)) {\n // Initialize the total...\n int total = 0;\n // Create a while loop...\n while (n > 0) {\n // Process to get happy number...\n // We use division and modulus operators to repeatedly take digits off the number until none remain...\n // Then squaring each removed digit and adding them together...\n total += (n % 10) * (n % 10);\n n /= 10;\n // Each new converted number must not had occurred before...\n }\n // If total is equal to 1 return true.\n if (total == 1)\n return true;\n // Insert the current number into the set s...\n // Replace the current number with total of the square of its digits.\n else\n n = total;\n }\n // If current number is already in the HashSet, that means we're in a cycle and we should return false..\n return false;\n }\n}", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19\nOutput:true\nExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isHappy(self, n):\n hset = set()\n while n != 1:\n if n in hset: return False\n hset.add(n)\n n = sum([int(i) ** 2 for i in str(n)])\n else:\n return True\n", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same.", + "description_images": [], + "constraints": [ + "1 <= houses.length, heaters.length <= 3 * 10^4", + "1 <= houses[i], heaters[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,2,3], heaters = [2]\nOutput:1\nExplanation:The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 2: Input:houses = [1,2,3,4], heaters = [1,4]\nOutput:1\nExplanation:The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 3: Input:houses = [1,5], heaters = [2]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 66.0%) | Memory: 46.54 MB (Top 44.7%)\n\nclass Solution {\n public boolean can(int r, int[] houses, int[] heaters) {\n int prevHouseIdx = -1;\n for(int i = 0; i < heaters.length; i++) {\n int from = heaters[i]-r;\n int to = heaters[i]+r;\n for(int j = prevHouseIdx+1; j < houses.length; j++){\n if(houses[j]<=to && houses[j]>=from){\n prevHouseIdx++;\n }\n else break;\n }\n if(prevHouseIdx >= houses.length-1)return true;\n }\n return prevHouseIdx>= houses.length-1;\n }\n public int findRadius(int[] houses, int[] heaters) {\n Arrays.sort(houses);\n Arrays.sort(heaters);\n int lo = 0, hi = 1000000004;\n int mid, ans = hi;\n while(lo <= hi) {\n mid = (lo+hi)/2;\n if(can(mid, houses, heaters)){\n ans = mid;\n hi = mid - 1;\n } else lo = mid + 1;\n }\n return ans;\n }\n}", + "title": "475. Heaters", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same.", + "description_images": [], + "constraints": [ + "1 <= houses.length, heaters.length <= 3 * 10^4", + "1 <= houses[i], heaters[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,2,3], heaters = [2]\nOutput:1\nExplanation:The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 2: Input:houses = [1,2,3,4], heaters = [1,4]\nOutput:1\nExplanation:The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 3: Input:houses = [1,5], heaters = [2]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 766 ms (Top 22.98%) | Memory: 17.7 MB (Top 39.36%)\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n \"\"\"\n\n \"\"\"\n\n houses.sort()\n heaters.sort()\n\n max_radius = -inf\n\n for house in houses:\n i = bisect_left(heaters, house)\n\n if i == len(heaters):\n max_radius = max(max_radius, house - heaters[-1])\n elif i == 0:\n max_radius = max(max_radius, heaters[i] - house)\n else:\n curr = heaters[i]\n prev = heaters[i-1]\n max_radius = max(max_radius,min(abs(house - curr), abs(house-prev)))\n\n return max_radius\n\n # O(NLOGN)", + "title": "475. Heaters", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i th student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i th student in line ( 0-indexed ). Return the number of indices where heights[i] != expected[i] .", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 100", + "1 <= heights[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [1,1,4,2,1,3]\nOutput:3\nExplanation:heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,4]\nOutput:5\nExplanation:heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.", + "image": null + }, + { + "text": "Example 3: Input:heights = [1,2,3,4,5]\nOutput:0\nExplanation:heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.11%) | Memory: 42.1 MB (Top 31.42%)\nclass Solution {\n public int heightChecker(int[] heights) {\n\n int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length);\n\n Arrays.sort(dupheights);\n int count = 0;\n\n for(int i=0 ; i< heights.length ; i++){\n\n if(heights[i] != dupheights[i]){\n count++;\n }\n\n }\n\n return count;\n\n }\n}\n", + "title": "1051. Height Checker", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i th student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i th student in line ( 0-indexed ). Return the number of indices where heights[i] != expected[i] .", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 100", + "1 <= heights[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [1,1,4,2,1,3]\nOutput:3\nExplanation:heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,4]\nOutput:5\nExplanation:heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.", + "image": null + }, + { + "text": "Example 3: Input:heights = [1,2,3,4,5]\nOutput:0\nExplanation:heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n heightssort = sorted(heights)\n import numpy as np\n diff = list(np.array(heightssort) - np.array(heights))\n return (len(diff) - diff.count(0))\n", + "title": "1051. Height Checker", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:4\nExplanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]\nOutput:12\nExplanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 31.47%)\nclass Solution {\n public int rob(int[] nums) {\n int[] t = new int[nums.length] ;\n for(int i=0; i=nums.length){\n return 0;\n }\n if(i==nums.length-1){\n return nums[i];\n }\n if(t[i] != -1){\n return t[i];\n }\n\n int pick = nums[i] + helper(nums,i+2,t);\n int unpicked = helper(nums,i+1,t);\n t[i] = Math.max(pick,unpicked);\n return t[i];\n\n }\n}", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:4\nExplanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]\nOutput:12\nExplanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rob(self, nums: List[int]) -> int:\n # [rob1,rob2,n,n+1]\n # 1 | 2 | 3 | 1 \n #index 0 1 2 3\n # so upto last index it depends on previous 2 values :\n # here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2\n # and upto 1st index max rob is 2 ; not choosing any adjacent elements\n # so at 3rd index it depend on prev rob value and 1st index rob value+last value\n # i.e max(2+(val at last index),4)\n rob1=0;rob2=0;\n for i in nums:\n temp=max(rob1+i,rob2);\n rob1=rob2;\n rob2=temp;\n return rob2;\n\n", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2]\nOutput:3\nExplanation:You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,1]\nOutput:4\nExplanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.4 MB (Top 99.44%)\nclass Solution {\n public int rob(int[] nums) {\n if(nums.length==1){\n return nums[0];\n }\n int[] t = new int[nums.length];\n for(int i = 0 ; i < t.length;i++){\n t[i] = -1;\n }\n int[] k = new int[nums.length];\n for(int i = 0 ; i < k.length;i++){\n k[i] = -1;\n }\n return Math.max(helper(nums,0,0,t),helper(nums,1,1,k));\n }\n static int helper(int[] nums, int i,int start , int[] t){\n if(start==0 && i==nums.length-2){\n return nums[i];\n }\n if(start==1 && i==nums.length-1){\n return nums[i];\n }\n if(start==0 && i>=nums.length-1){\n return 0;\n }\n if(start==1 && i>=nums.length){\n return 0;\n }\n if(t[i] != -1){\n return t[i];\n }\n int pick = nums[i]+helper(nums,i+2,start,t);\n int notpick = helper(nums,i+1,start,t);\n t[i] = Math.max(pick,notpick);\n return t[i];\n }\n}", + "title": "213. House Robber II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2]\nOutput:3\nExplanation:You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,1]\nOutput:4\nExplanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n def helper(nums):\n one, two = 0, 0\n for i in nums:\n temp = max(i + one, two)\n one = two\n two = temp\n return two\n \n return max(helper(nums[:-1]), helper(nums[1:]))\n", + "title": "213. House Robber II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root . Besides the root , each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night . Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,2,3,null,3,null,1]\nOutput:7\nExplanation:Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,3,null,1]\nOutput:9\nExplanation:Maximum amount of money the thief can rob = 4 + 5 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.60 MB (Top 27.04%)\n\nclass Solution {\n public int rob(TreeNode root) {\n int ans[] = robHouse(root);\n return Math.max(ans[0],ans[1]);\n }\n \n public int[] robHouse(TreeNode root){\n if(root==null){\n return new int[2];\n }\n \n int left[] = robHouse(root.left);\n int right[] = robHouse(root.right);\n \n int ans[] = new int[2];\n \n ans[0] = Math.max(left[0],left[1])+Math.max(right[0],right[1]);\n ans[1] = root.val+left[0]+right[0];\n \n return ans;\n }\n}\n", + "title": "337. House Robber III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root . Besides the root , each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night . Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,2,3,null,3,null,1]\nOutput:7\nExplanation:Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,3,null,1]\nOutput:9\nExplanation:Maximum amount of money the thief can rob = 4 + 5 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def rob(self, root: Optional[TreeNode]) -> int:\n hashMap = {}\n \n def helper(root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n if root in hashMap:\n return hashMap[root]\n ansOption1 = root.val\n if root.left is not None:\n ansOption1 += (helper(root.left.left) + helper(root.left.right))\n if root.right is not None:\n ansOption1 += (helper(root.right.left) + helper(root.right.right))\n ansOption2 = helper(root.left) + helper(root.right)\n ansFinal = max(ansOption1, ansOption2)\n hashMap[root] = ansFinal\n return ansFinal\n \n return helper(root)\n \n", + "title": "337. House Robber III", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array nums , for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i] . Return the answer in an array.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,1,2,2,3]\nOutput:[4,0,1,1,3]\nExplanation:For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,8]\nOutput:[2,1,0,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7]\nOutput:[0,0,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 76.25%) | Memory: 44.5 MB (Top 55.91%)\nclass Solution {\n public int[] smallerNumbersThanCurrent(int[] nums) {\n int[] sorted = nums.clone();\n int[] res = new int[nums.length];//result array\n Arrays.sort(sorted);\n for (int i = 0; i < nums.length; ++i) {\n //binary search it, if there is no duplicates the idx will be how many smaller are there\n int idx = binarySearch(sorted, nums[i]);\n //if there are duplicates, then we need to find the first one presented in the array\n if (idx-1>=0 && sorted[idx-1] == nums[i]) {\n while (idx >= 0 && sorted[idx] == nums[i]) {\n --idx;\n }\n ++idx;\n }\n //As I said before, array of indices(indexes) will be the answer\n res[i] = idx;\n }\n return res;\n }\n //Just simple iterative binary search\n public static int binarySearch(int[] arr, int target) {\n int s = 0;\n int e = arr.length-1;\n int m = (s+e)/2;\n\n while (s<=e) {\n if (arr[m] == target) {\n return m;\n } else if (arr[m] > target) {\n e = m-1;\n } else {\n s = m+1;\n }\n m = (s+e)/2;\n }\n return -1;\n }\n}", + "title": "1365. How Many Numbers Are Smaller Than the Current Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the array nums , for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i] . Return the answer in an array.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,1,2,2,3]\nOutput:[4,0,1,1,3]\nExplanation:For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,8]\nOutput:[2,1,0,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7]\nOutput:[0,0,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallerNumbersThanCurrent(self, nums):\n sortify = sorted(nums)\n return (bisect_left(sortify, i) for i in nums)\n", + "title": "1365. How Many Numbers Are Smaller Than the Current Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters .", + "description_images": [], + "constraints": [ + "Quotation Mark: the entity is " and symbol character is \" .", + "Single Quote Mark: the entity is ' and symbol character is ' .", + "Ampersand: the entity is & and symbol character is & .", + "Greater Than Sign: the entity is > and symbol character is > .", + "Less Than Sign: the entity is < and symbol character is < .", + "Slash: the entity is ⁄ and symbol character is / ." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"& is an HTML entity but &ambassador; is not.\"\nOutput:\"& is an HTML entity but &ambassador; is not.\"\nExplanation:The parser will replace the & entity by &", + "image": null + }, + { + "text": "Example 2: Input:text = \"and I quote: "..."\"\nOutput:\"and I quote: \\\"...\\\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 70.19%) | Memory: 56.3 MB (Top 73.08%)\nclass Solution {\n public String entityParser(String text) {\n return text.replace(\""\",\"\\\"\").replace(\"'\",\"'\").replace(\">\",\">\").replace(\"<\",\"<\").replace(\"⁄\",\"/\").replace(\"&\",\"&\");\n }\n}", + "title": "1410. HTML Entity Parser", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters .", + "description_images": [], + "constraints": [ + "Quotation Mark: the entity is " and symbol character is \" .", + "Single Quote Mark: the entity is ' and symbol character is ' .", + "Ampersand: the entity is & and symbol character is & .", + "Greater Than Sign: the entity is > and symbol character is > .", + "Less Than Sign: the entity is < and symbol character is < .", + "Slash: the entity is ⁄ and symbol character is / ." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"& is an HTML entity but &ambassador; is not.\"\nOutput:\"& is an HTML entity but &ambassador; is not.\"\nExplanation:The parser will replace the & entity by &", + "image": null + }, + { + "text": "Example 2: Input:text = \"and I quote: "..."\"\nOutput:\"and I quote: \\\"...\\\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def entityParser(self, text: str) -> str:\n d = {\""\" : '\"' , \"'\":\"'\" , \"&\" : \"&\" , \">\" : \">\" , \"<\":\"<\" , \"⁄\" : \"/\"}\n \n \n \n ans = \"\"\n i = 0\n while i < len(text):\n bag = \"\"\n \n #condition if find & and next char is not & also and handdling index out of range for i + 1\n if i+1 < len(text) and text[i] == \"&\" and text[i+1] != \"&\":\n \n #create subtring for speacial char till \";\"\n for j in range(i , len(text)):\n if text[j] == \";\":\n bag += text[j]\n break\n else:\n bag += text[j]\n \n #if that not present in dict we added same as it is\n if bag not in d:\n ans += bag\n else:\n ans += d[bag]\n \n #increment by length of bag \n i += len(bag)\n \n #otherwise increment by 1\n else:\n ans += text[i]\n i += 1\n return ans\n \n", + "title": "1410. HTML Entity Parser", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two images, img1 and img2 , represented as binary, square matrices of size n x n . A binary matrix has only 0 s and 1 s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap .", + "description_images": [], + "constraints": [ + "n == img1.length == img1[i].length", + "n == img2.length == img2[i].length", + "1 <= n <= 30", + "img1[i][j] is either 0 or 1 .", + "img2[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\nOutput:3\nExplanation:We translate img1 to right by 1 unit and down by 1 unit.The number of positions that have a 1 in both images is 3 (shown in red).", + "image": "https://assets.leetcode.com/uploads/2020/09/09/overlap1.jpg" + }, + { + "text": "Example 2: Input:img1 = [[1]], img2 = [[1]]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:img1 = [[0]], img2 = [[0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 593 ms (Top 76.00%) | Memory: 14.7 MB (Top 44.00%)\nclass Solution:\n def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:\n n = len(img1)\n list1, list2 = [], []\n res = 0\n for r in range(n):\n for c in range(n):\n if img1[r][c]:\n list1.append((r, c))\n if img2[r][c]:\n list2.append((r, c))\n\n shiftDict = defaultdict(int)\n for x1, y1 in list1:\n for x2, y2 in list2:\n dx, dy = x2 - x1, y2 - y1\n shiftDict[(dx, dy)] += 1\n\n return max(shiftDict.values()) if shiftDict else 0", + "title": "835. Image Overlap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it .", + "description_images": [], + "constraints": [ + "m == img.length", + "n == img[i].length", + "1 <= m, n <= 200", + "0 <= img[i][j] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:img = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[0,0,0],[0,0,0],[0,0,0]]\nExplanation:For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg" + }, + { + "text": "Example 2: Input:img = [[100,200,100],[200,50,200],[100,200,100]]\nOutput:[[137,141,137],[141,138,141],[137,141,137]]\nExplanation:For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Constant Space Solution. Using input array to store the average\n * This solution can be modified to work if numbers are upto 2^16 - 1 (65,535).\n *\n * Time Complexity: O(8*M*N + M*N) = O(M*N)\n *\n * Space Complexity: O(1)\n *\n * M = Number of rows. N = Number of columns.\n * \n * Note: Similar to \"289. Game of Life\"\n */\nclass Solution {\n private static final int[][] DIRS = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } };\n\n public int[][] imageSmoother(int[][] img) {\n if (img == null) {\n throw new IllegalArgumentException(\"Input image is null\");\n }\n if (img.length == 0 || img[0].length == 0) {\n return img;\n }\n\n int rows = img.length;\n int cols = img[0].length;\n if (rows == 1 && cols == 1) {\n return img;\n }\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n int sum = img[i][j];\n int count = 1;\n for (int[] d : DIRS) {\n int x = i + d[0];\n int y = j + d[1];\n if (x >= 0 && x < rows && y >= 0 && y < cols) {\n sum += img[x][y] & 0xFF;\n count++;\n }\n }\n img[i][j] |= (sum / count) << 8;\n }\n }\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n img[i][j] >>>= 8;\n }\n }\n\n return img;\n }\n}\n", + "title": "661. Image Smoother", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it .", + "description_images": [], + "constraints": [ + "m == img.length", + "n == img[i].length", + "1 <= m, n <= 200", + "0 <= img[i][j] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:img = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[0,0,0],[0,0,0],[0,0,0]]\nExplanation:For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg" + }, + { + "text": "Example 2: Input:img = [[100,200,100],[200,50,200],[100,200,100]]\nOutput:[[137,141,137],[141,138,141],[137,141,137]]\nExplanation:For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1147 ms (Top 25.09%) | Memory: 14.8 MB (Top 29.59%)\nclass Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n m, n = len(img), len(img[0])\n\n def avg(i, j):\n s = squares = 0\n top, bottom = max(0, i - 1), min(m, i + 2)\n left, right = max(0, j - 1), min(n, j + 2)\n\n for x in range(top, bottom):\n for y in range(left, right):\n s += img[x][y]\n squares += 1\n\n return s // squares\n\n return [[avg(i, j) for j in range(n)] for i in range(m)]", + "title": "661. Image Smoother", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class:", + "description_images": [], + "constraints": [ + "MagicDictionary() Initializes the object.", + "void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary .", + "bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]Output[null, null, false, true, false, false]ExplanationMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class MagicDictionary {\n private String[] dictionary;\n \n public MagicDictionary() {}\n \n public void buildDict(String[] dictionary) {\n this.dictionary = dictionary;\n }\n \n public boolean search(String searchWord) {\n for (String dictWord: this.dictionary) {\n if (this.match(searchWord, dictWord, 1))\n return true;\n }\n \n return false;\n }\n \n private boolean match(String s, String t, int expectedDiff) {\n if (s.length() != t.length())\n return false;\n \n int diff = 0;\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) != t.charAt(i))\n diff++;\n if (diff > expectedDiff)\n return false;\n }\n \n return diff == expectedDiff;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n", + "title": "676. Implement Magic Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class:", + "description_images": [], + "constraints": [ + "MagicDictionary() Initializes the object.", + "void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary .", + "bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]Output[null, null, false, true, false, false]ExplanationMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class MagicDictionary:\n\n\tdef __init__(self):\n\t\tTrieNode = lambda : defaultdict(TrieNode)\n\t\tself.root = TrieNode()\n\n\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\tfor s in dictionary:\n\t\t\tcur = self.root\n\t\t\tfor c in s: cur = cur[ord(c)-ord('a')]\n\t\t\tcur['$']=True\n\n\tdef search(self, searchWord: str) -> bool:\n\t\tdef find(i,cur,mis):\n\t\t\tif i==len(searchWord) and mis==0: return('$' in cur)\n\t\t\tif mis < 0: return False\n\t\t\tif i==len(searchWord) and mis!=0: return False\n\t\t\tind = ord(searchWord[i])-ord('a')\n\t\t\tans = False\n\t\t\tfor j in range(26):\n\t\t\t\tif j in cur:\n\t\t\t\t\tif(j!=ind):\n\t\t\t\t\t\tans |= find(i+1,cur[j],mis-1)\n\t\t\t\t\telse: ans |= find(i+1,cur[j],mis)\n\t\t\treturn ans\n\t\t\t\n\t\treturn find(0,self.root,1)\n", + "title": "676. Implement Magic Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 1 ms (Top 70.23%) | Memory: 41.5 MB (Top 77.34%)\nclass MyQueue {\n\n private final Deque stack = new ArrayDeque<>();\n private final Deque temp = new ArrayDeque<>();\n\n /**\n * Initialize your data structure here.\n */\n public MyQueue() {}\n\n /**\n * Pushes element x to the back of the queue.\n */\n public void push(int x) {\n stack.push(x);\n }\n\n /**\n * @return the element at the front of the queue and remove it.\n */\n public int pop() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.pop();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return the element at the front of the queue.\n */\n public int peek() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.peek();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return true if the queue is empty, false otherwise.\n */\n public boolean empty() {\n return stack.isEmpty();\n }\n}", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 53 ms (Top 33.00%) | Memory: 13.9 MB (Top 98.49%)\nclass MyStack:\n def __init__(self):\n self.stack = []\n\n def push(self, x):\n self.stack.append(x)\n\n def top(self):\n return self.stack[-1]\n\n def pop(self):\n return self.stack.pop()\n\n def size(self):\n return len(self.stack)\n\n def isEmpty(self):\n return len(self.stack) == 0\n\nclass MyQueue:\n\n def __init__(self):\n self.stack1 = MyStack()\n self.stack2 = MyStack()\n\n def push(self, x: int) -> None:\n self.stack1.push(x)\n\n def pop(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.pop()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def peek(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.top()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def empty(self) -> bool:\n return self.stack1.isEmpty()\n\n# Your MyQueue object will be instantiated and called as such:\n# obj = MyQueue()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.peek()\n# param_4 = obj.empty()", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the API rand7() that generates a uniform random integer in the range [1, 7] , write a function rand10() that generates a uniform random integer in the range [1, 10] . You can only call the API rand7() , and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n , the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10() .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:[2]", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:[2,8]", + "image": null + }, + { + "text": "Example 3: Input:n = 3\nOutput:[3,8,10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rand10(self):\n \"\"\"\n :rtype: int\n \"\"\"\n x = rand7()\n y = rand7()\n pos = (x - 1) * 7 + y\n if pos > 40:\n return self.rand10()\n return (pos % 10) + 1\n\t\t```", + "title": "470. Implement Rand10() Using Rand7()", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 44 ms (Top 15.83%) | Memory: 16.50 MB (Top 18.94%)\n\nclass MyStack:\n\n def __init__(self):\n self.q1 = deque()\n self.q2 = deque()\n\n def push(self, x: int) -> None:\n self.q1.append(x)\n\n def pop(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n popped_element = self.q1.popleft()\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return popped_element\n\n def top(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n top_element = self.q1[0]\n \n self.q2.append(self.q1.popleft())\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return top_element\n\n def empty(self) -> bool:\n return len(self.q1) == 0\n", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 1 ms (Top 34.13%) | Memory: 42.2 MB (Top 19.29%)\nclass MyStack {\n\n Queue queue = null;\n\n public MyStack() {\n queue = new LinkedList<>();\n }\n\n public void push(int x) {\n\n Queue tempQueue = new LinkedList<>();\n tempQueue.add(x);\n\n while(!queue.isEmpty()){\n tempQueue.add(queue.remove());\n }\n\n queue = tempQueue;\n\n }\n\n public int pop() {\n return queue.remove();\n }\n\n public int top() {\n return queue.peek();\n }\n\n public boolean empty() {\n return queue.isEmpty();\n }\n}", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class MyStack(object):\n\n def __init__(self):\n self.stack=[]\n\n def push(self, x):\n self.stack.append(x)\n return None\n \n def pop(self):\n return self.stack.pop(-1)\n \n\n def top(self):\n return self.stack[-1]\n\n def empty(self):\n if self.stack==[]:\n return True\n return False\n\n\n# Your MyStack object will be instantiated and called as such:\n# obj = MyStack()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.top()\n# param_4 = obj.empty()\n", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement strStr() . Given two strings needle and haystack , return the index of the first occurrence of needle in haystack , or -1 if needle is not part of haystack . Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf() .", + "description_images": [], + "constraints": [ + "1 <= haystack.length, needle.length <= 10^4", + "haystack and needle consist of only lowercase English characters." + ], + "examples": [ + { + "text": "Example 1: Input:haystack = \"hello\", needle = \"ll\"\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:haystack = \"aaaaa\", needle = \"bba\"\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int strStr(String haystack, String needle) {\n \n if(needle.length()>haystack.length()) {\n return -1;\n } \n if(needle.length()==haystack.length()) {\n if(haystack.equals(needle)) {\n return 0;\n }\n return -1;\n }\n \n \n int i=0;\n int j=0;\n while(i map;\n public Trie() {\n root = new Node('\\0');\n map = new HashMap<>();\n }\n\n public void insert(String word) {\n Node temp = root;\n for(char c : word.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n temp.sub[index] = new Node(c);\n\n temp = temp.sub[index];\n }\n map.put(word, true);\n }\n\n public boolean search(String word) {\n return map.containsKey(word);\n }\n\n public boolean startsWith(String prefix) {\n Node temp = root;\n for(char c : prefix.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n return false;\n temp = temp.sub[index];\n }\n return true;\n }\n}", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]Output[null, null, true, false, true, null, true]ExplanationTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\"); // return True\ntrie.search(\"app\"); // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class Node : \n def __init__(self ):\n self.child = {} # to hold the nodes.\n self.end = False # to mark a node if it is the end node or not.\n\nclass Trie:\n \n def __init__(self):\n self.root = Node()\n\n def insert(self, word:str) -> None:\n # time compl len(word)\n \n sz = len(word) \n temp = self.root # to hold the root node.\n \n for ind , i in enumerate( word ) :\n if i in temp.child.keys() : # if this curr char in the current node.\n temp = temp.child[i] #another node.\n \n else:\n temp.child[i] = Node()\n temp = temp.child[i]\n\n \n if ind == sz - 1 :\n temp.end = True \n \n \n\n def search(self, word: str) -> bool:\n \n temp = self.root \n for i in word : \n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n \n return temp.end == True \n \n def startsWith(self, prefix: str) -> bool:\n temp = self.root \n for i in prefix :\n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n return 1 \n\n\n", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . Reorder the string using the following algorithm: In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaaabbbbcccc\"\nOutput:\"abccbaabccba\"\nExplanation:After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\"\nOutput:\"art\"\nExplanation:The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String sortString(String s) {\n \n StringBuilder result = new StringBuilder();\n int[] freq = new int[26];\n for(char c: s.toCharArray()){\n freq[c-'a']++;\n }\n int remaining = s.length();\n while(remaining!=0){\n for(int i=0;i<26&&remaining!=0;i++){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n for(int i=25;i>=0&&remaining!=0;i--){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n }\n return result.toString();\n }\n}\n", + "title": "1370. Increasing Decreasing String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s . Reorder the string using the following algorithm: In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaaabbbbcccc\"\nOutput:\"abccbaabccba\"\nExplanation:After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\"\nOutput:\"art\"\nExplanation:The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 48.8%) | Memory: 17.70 MB (Top 9.21%)\n\nclass Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n result = ''\n while s:\n for letter in sorted(set(s)):\n s.remove(letter)\n result += letter\n for letter in sorted(set(s), reverse=True):\n s.remove(letter)\n result += letter\n return result\n", + "title": "1370. Increasing Decreasing String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree will be in the range [1, 100] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,7]\nOutput:[1,null,5,null,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.5 MB (Top 73.31%)\nclass Solution {\n TreeNode inRoot = new TreeNode();\n TreeNode temp = inRoot;\n public TreeNode increasingBST(TreeNode root) {\n inorder(root);\n return inRoot.right;\n }\n public void inorder(TreeNode root) {\n if(root==null)\n return;\n inorder(root.left);\n temp.right = new TreeNode(root.val);\n temp = temp.right;\n inorder(root.right);\n }\n}", + "title": "897. Increasing Order Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree will be in the range [1, 100] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,7]\nOutput:[1,null,5,null,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 21.66%) | Memory: 17.30 MB (Top 23.65%)\n\nclass Solution:\n def increasingBST(self, node: TreeNode) -> TreeNode:\n dummy = tail = TreeNode()\n while node is not None:\n if node.left is not None:\n predecessor = node.left\n while predecessor.right is not None:\n predecessor = predecessor.right\n \n predecessor.right = node\n left, node.left = node.left, None\n node = left\n else:\n tail.right = tail = node\n node = node.right\n \n return dummy.right\n", + "title": "897. Increasing Order Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return all the different possible increasing subsequences of the given array with at least two elements . You may return the answer in any order . The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 15", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,7,7]\nOutput:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,3,2,1]\nOutput:[[4,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 13.29%) | Memory: 68.6 MB (Top 66.07%)\nclass Solution {\n HashSet> set;\n public List> findSubsequences(int[] nums) {\n set=new HashSet<>();\n\n dfs(nums,0,new ArrayList<>());\n\n List> ans=new ArrayList<>();\n if(set.size()>0){\n ans.addAll(set);\n }\n return ans;\n }\n\n private void dfs(int nums[], int start, List temp){\n if(start==nums.length) return;\n\n for(int i=start;i=2) set.add(new ArrayList<>(temp));\n\n dfs(nums,i+1,temp);\n temp.remove(temp.size()-1);\n }\n }\n }\n}", + "title": "491. Increasing Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return all the different possible increasing subsequences of the given array with at least two elements . You may return the answer in any order . The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 15", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,7,7]\nOutput:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,3,2,1]\nOutput:[[4,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 750 ms (Top 10.08%) | Memory: 22.4 MB (Top 30.72%)\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n def backtracking(nums,path):\n # to ensure that the base array has at least 2 elements\n if len(path)>=2:\n res.add(tuple(path))\n for i in range(len(nums)):\n # to ensure that every element to be added is equal or larger than the former\n if not path or path[-1] <= nums[i]:\n backtracking(nums[i+1:],path+[nums[i]])\n\n res=set()\n backtracking(nums,[])\n return res", + "title": "491. Increasing Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]\nOutput:true\nExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]\nOutput:false\nExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]\nOutput:true\nExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n if(nums.length < 3)\n return false;\n \n int x = Integer.MAX_VALUE;\n int y = Integer.MAX_VALUE;\n \n for (int i : nums){\n if(i <= x){\n x = i;\n }else if (i <= y)\n y = i;\n else \n return true;\n }\n \n return false;\n }\n}\n", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]\nOutput:true\nExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]\nOutput:false\nExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]\nOutput:true\nExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n first = second = float('inf')\n for n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\n return False\n", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the i th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes . Return an array containing [crashTime, memory1 crash , memory2 crash ] , where crashTime is the time (in seconds) when the program crashed and memory1 crash and memory2 crash are the available bits of memory in the first and second sticks respectively .", + "description_images": [], + "constraints": [ + "0 <= memory1, memory2 <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:memory1 = 2, memory2 = 2\nOutput:[3,1,0]\nExplanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rdsecond, the program crashes. The sticks have 1 and 0 bits available respectively.", + "image": null + }, + { + "text": "Example 2: Input:memory1 = 8, memory2 = 11\nOutput:[6,0,4]\nExplanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rdsecond, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4thsecond, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5thsecond, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6thsecond, the program crashes. The sticks have 0 and 4 bits available respectively.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.96%) | Memory: 41.8 MB (Top 45.37%)\nclass Solution {\n public int[] memLeak(int memory1, int memory2) {\n int i = 1;\n while(Math.max(memory1, memory2) >= i){\n if(memory1 >= memory2)\n memory1 -= i;\n else\n memory2 -= i;\n i++;\n }\n return new int[]{i, memory1, memory2};\n }\n}", + "title": "1860. Incremental Memory Leak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the i th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes . Return an array containing [crashTime, memory1 crash , memory2 crash ] , where crashTime is the time (in seconds) when the program crashed and memory1 crash and memory2 crash are the available bits of memory in the first and second sticks respectively .", + "description_images": [], + "constraints": [ + "0 <= memory1, memory2 <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:memory1 = 2, memory2 = 2\nOutput:[3,1,0]\nExplanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rdsecond, the program crashes. The sticks have 1 and 0 bits available respectively.", + "image": null + }, + { + "text": "Example 2: Input:memory1 = 8, memory2 = 11\nOutput:[6,0,4]\nExplanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rdsecond, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4thsecond, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5thsecond, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6thsecond, the program crashes. The sticks have 0 and 4 bits available respectively.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n \n inverted = False \n if memory2>memory1:\n memory2, memory1 = memory1, memory2\n inverted = True \n\n\t\t#Compute the number of steps in first stage - 1\n i_start = solve_quadratic(1,2*(memory1-memory2))\n \n\t\t#Memory1 after the end of first stage is computed using the sum of arithmetic sequence\n memory1-= i_start*(i_start+1)//2\n\t\t\n\t\tif memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion)\n inverted = False \n \n #Compute number of steps in stage - 2\n n_end = solve_quadratic((i_start+1), memory2)\n \n\t\t#Compute sums of respective arithmetic sequences\n i_end_1 = i_start - 1 + 2*n_end\n i_end_2 = i_start + 2*n_end\n \n sum1 = n_end * (i_start+1 + i_end_1)//2\n sum2 = n_end * (i_start+2 + i_end_2)//2\n \n\t\t#Compute updated memories \n memory1-=sum1\n memory2-=sum2\n \n full_cnt=2*n_end+i_start\n \n if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it.\n memory1-=(i_end_2+1)\n full_cnt+=1\n \n return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2]\n \n\t\t ```", + "title": "1860. Incremental Memory Leak", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity.", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedSet {\n HashMap map;\n ArrayList list;\n Random rand;\n public RandomizedSet() {\n map = new HashMap<>();\n list = new ArrayList<>();\n rand = new Random();\n }\n \n public boolean insert(int val) {\n if (!map.containsKey(val)){\n map.put(val, list.size());\n list.add(val);\n return true;\n }\n return false;\n }\n \n public boolean remove(int val) {\n if (map.containsKey(val)){\n int index = map.get(val);\n int last = list.get(list.size() - 1);\n if (index != list.size() - 1){\n list.set(index, last);\n map.put(last, index);\n }\n list.remove(list.size() - 1); \n map.remove(val);\n return true;\n }\n return false;\n }\n \n public int getRandom() {\n int r = rand.nextInt(list.size()); \n return list.get(r);\n }\n}\n", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity.", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedSet:\n\n def __init__(self):\n self.data = set() \n\n def insert(self, val: int) -> bool:\n if val not in self.data:\n self.data.add(val)\n return True \n return False \n \n def remove(self, val: int) -> bool:\n if val in self.data:\n self.data.remove(val)\n return True \n return False \n\n def getRandom(self) -> int:\n return random.choice(list(self.data))\n", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection .", + "description_images": [], + "constraints": [ + "RandomizedCollection() Initializes the empty RandomizedCollection object.", + "bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.", + "bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.", + "int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"]\n[[], [1], [1], [2], [], [1], []]Output[null, true, false, true, 2, true, 1]ExplanationRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\nrandomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\nrandomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedCollection {\n List multiSet;\n HashMap> map;\n Random random;\n public RandomizedCollection() {\n map = new HashMap<>();\n multiSet = new ArrayList<>();\n random = new Random();\n }\n \n public boolean insert(int val) {\n boolean contains = map.containsKey(val);\n multiSet.add(val);\n PriorityQueue pq;\n if(!contains){\n pq = new PriorityQueue<>(Collections.reverseOrder());\n map.put(val, pq);\n }else\n pq = map.get(val);\n \n pq.add(multiSet.size()-1);\n return !contains;\n }\n \n public boolean remove(int val) {\n if(!map.containsKey(val))\n return false;\n \n PriorityQueue pq = map.get(val);\n int indexToRemove = pq.poll();\n if(pq.size() == 0) map.remove(val);\n \n int lastIndex = multiSet.size()-1;\n if(indexToRemove != lastIndex){\n int valLast = multiSet.get(lastIndex);\n PriorityQueue temp = map.get(valLast);\n temp.poll();\n temp.add(indexToRemove);\n multiSet.set(indexToRemove, valLast);\n }\n multiSet.remove(lastIndex);\n return true;\n }\n \n public int getRandom() {\n int index = random.nextInt(multiSet.size());\n return multiSet.get(index);\n }\n}\n", + "title": "381. Insert Delete GetRandom O(1) - Duplicates allowed", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection .", + "description_images": [], + "constraints": [ + "RandomizedCollection() Initializes the empty RandomizedCollection object.", + "bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.", + "bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.", + "int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"]\n[[], [1], [1], [2], [], [1], []]Output[null, true, false, true, 2, true, 1]ExplanationRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\nrandomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\nrandomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedCollection:\n\n def __init__(self):\n self.items = []\n\n def insert(self, val: int) -> bool:\n self.items.append(val)\n if self.items.count(val) > 1:\n return False\n else:\n return True\n\n def remove(self, val: int) -> bool:\n if val in self.items:\n flag = True\n self.items.remove(val)\n else:\n flag = False\n \n return flag\n\n def getRandom(self) -> int:\n return choice(self.items)\n \n", + "title": "381. Insert Delete GetRandom O(1) - Duplicates allowed", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput:[[1,2],[3,10],[12,16]]\nExplanation:Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n if (newInterval == null || newInterval.length == 0) return intervals;\n \n List merged = new LinkedList<>();\n int i = 0;\n // add not overlapping\n while (i < intervals.length && intervals[i][1] < newInterval[0]) {\n merged.add(intervals[i]);\n i++;\n }\n // add overlapping\n while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(intervals[i][0], newInterval[0]);\n newInterval[1] = Math.max(intervals[i][1], newInterval[1]);\n i++;\n }\n merged.add(newInterval);\n // add rest\n while (i < intervals.length) {\n merged.add(intervals[i]);\n i++;\n }\n return merged.toArray(new int[merged.size()][]);\n }\n}\n", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput:[[1,2],[3,10],[12,16]]\nExplanation:Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 202 ms (Top 7.96%) | Memory: 17.3 MB (Top 91.79%)\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n\n intervals.append(newInterval)\n intervals.sort(key=lambda x: x[0])\n\n result = []\n for interval in intervals:\n if not result or result[-1][1] < interval[0]:\n result.append(interval)\n else:\n result[-1][1] = max(result[-1][1],interval[1])\n\n return result", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion . It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-10^8 <= Node.val <= 10^8", + "All the values Node.val are unique .", + "-10^8 <= val <= 10^8", + "It's guaranteed that val does not exist in the original BST." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 5\nOutput:[4,2,7,1,3,5]\nExplanation:Another accepted tree is:", + "image": "https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg" + }, + { + "text": "Example 2: Input:root = [40,20,60,10,30,50,70], val = 25\nOutput:[40,20,60,10,30,50,70,null,null,25]", + "image": null + }, + { + "text": "Example 3: Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput:[4,2,7,1,3,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode insertIntoBST(TreeNode root, int val) {\n if(root == null) return new TreeNode(val);\n \n if(root.val > val) root.left = insertIntoBST(root.left, val);\n \n else root.right = insertIntoBST(root.right, val);\n \n return root;\n }\n}\n", + "title": "701. Insert into a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion . It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-10^8 <= Node.val <= 10^8", + "All the values Node.val are unique .", + "-10^8 <= val <= 10^8", + "It's guaranteed that val does not exist in the original BST." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 5\nOutput:[4,2,7,1,3,5]\nExplanation:Another accepted tree is:", + "image": "https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg" + }, + { + "text": "Example 2: Input:root = [40,20,60,10,30,50,70], val = 25\nOutput:[40,20,60,10,30,50,70,null,null,25]", + "image": null + }, + { + "text": "Example 3: Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput:[4,2,7,1,3,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def insertIntoBST(self, root, val):\n if not root:\n return TreeNode(val)\n \n if val= cur.val)\n prev = temp;\n while(prev.next != null && prev.next.val < cur.val)\n prev = prev.next;\n cur.next = prev.next;\n prev.next = cur;\n cur = nxt;\n }\n return temp.next;\n }\n}\n", + "title": "147. Insertion Sort List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a singly linked list, sort the list using insertion sort , and return the sorted list's head . The steps of the insertion sort algorithm: The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]\nOutput:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]\nOutput:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction insertionSortList(head: ListNode | null): ListNode | null {\n if (!head) return null\n if (!head.next) return head\n\n let output = head\n let curr = head.next\n\n head.next = null\n\n while (curr) {\n const next = curr.next\n const insertion = curr\n\n output = insert(output, insertion)\n curr = next as ListNode\n }\n\n return output\n}\n\nfunction insert(head: ListNode, other: ListNode) {\n let curr = head\n const val = other.val\n\n if (val <= head.val) {\n other.next = head\n return other\n }\n\n while (curr) {\n if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) {\n other.next = curr.next\n curr.next = other\n\n return head\n }\n\n curr = curr.next as ListNode\n }\n\n return head\n}\n", + "title": "147. Insertion Sort List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and an integer limit , delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree . A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "-10^5 <= Node.val <= 10^5", + "-10^9 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\nOutput:[1,2,3,4,null,null,7,8,9,null,14]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-11.png" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\nOutput:[5,4,8,11,null,17,4,7,null,null,null,5]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-3.png" + }, + { + "text": "Example 3: Input:root = [1,2,-3,-5,null,4,null], limit = -1\nOutput:[1,null,-3,4]", + "image": "https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83301-pm.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 45.20 MB (Top 7.32%)\n\nclass Solution { \n public TreeNode helper(TreeNode root,int limit, int sumTillNow)\n {\n if(root == null) return null;\n \n if(root.left == null && root.right == null)\n return root.val + sumTillNow < limit ? null : root;\n \n root.left = helper(root.left,limit,sumTillNow + root.val);\n root.right = helper(root.right,limit,sumTillNow + root.val);\n \n return root.left == null && root.right == null ? null : root;\n }\n \n \n public TreeNode sufficientSubset(TreeNode root, int limit){\n return helper(root,limit,0);\n }\n}\n", + "title": "1080. Insufficient Nodes in Root to Leaf Paths", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree and an integer limit , delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree . A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "-10^5 <= Node.val <= 10^5", + "-10^9 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\nOutput:[1,2,3,4,null,null,7,8,9,null,14]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-11.png" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\nOutput:[5,4,8,11,null,17,4,7,null,null,null,5]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-3.png" + }, + { + "text": "Example 3: Input:root = [1,2,-3,-5,null,4,null], limit = -1\nOutput:[1,null,-3,4]", + "image": "https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83301-pm.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n we can try to solve this problem using depth first traversal\n \"\"\"\n def dfs(self, root, sum_so_far, limit):\n if root is None:\n return None, 0\n \n x, left = self.dfs(root.left, sum_so_far + root.val, limit)\n y, right = self.dfs(root.right, sum_so_far + root.val, limit)\n # print('for node= {}, sum_so_far= {}, left= {}, right= {}'.format(root.val, sum_so_far, left, right))\n if root.left is None and root.right is None:\n # it is leaf, left and right should be 0\n if sum_so_far + root.val < limit:\n # node is insufficient\n return None, root.val\n else:\n # node is sufficient\n return root, root.val\n elif root.left is not None and root.right is None:\n root.left = x\n if sum_so_far + root.val + left < limit:\n # node is insufficient\n return None, root.val + left\n else:\n return root, root.val + left\n \n elif root.left is None and root.right is not None:\n root.right = y\n if sum_so_far + root.val + right < limit:\n return None, root.val + right\n else:\n return root, root.val + right\n \n elif root.left is not None and root.right is not None:\n root.left = x\n root.right = y\n if sum_so_far + root.val + left < limit and sum_so_far + root.val + right < limit:\n return None, max(root.val + left, root.val + right)\n elif sum_so_far + root.val + left < limit and sum_so_far + root.val + right > limit:\n return root, root.val + right\n elif sum_so_far + root.val + left > limit and sum_so_far + root.val + right < limit:\n return root, root.val + left\n else:\n return root, max(root.val + left, root.val + right)\n \n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n root, _ = self.dfs(root, 0, limit)\n return root\n", + "title": "1080. Insufficient Nodes in Root to Leaf Paths", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , break it into the sum of k positive integers , where k >= 2 , and maximize the product of those integers. Return the maximum product you can get .", + "description_images": [], + "constraints": [ + "2 <= n <= 58" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:2 = 1 + 1, 1 × 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:36\nExplanation:10 = 3 + 3 + 4, 3 × 3 × 4 = 36.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.80 MB (Top 7.7%)\n\nclass Solution {\n public int integerBreak(int n) {\n if (n <= 1) {\n return 0;\n }\n int[] memo = new int[n + 1];\n return maxProduct(n, memo);\n }\n \n private int maxProduct(int n, int[] memo) {\n if (n == 2) {\n return 1;\n }\n if (memo[n] != 0) {\n return memo[n];\n }\n int max = 0;\n for (int i = 1; i < n; i++) {\n max = Math.max(max, Math.max(i * (n - i), i * maxProduct(n - i, memo)));\n }\n memo[n] = max;\n return max;\n }\n}\n", + "title": "343. Integer Break", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , break it into the sum of k positive integers , where k >= 2 , and maximize the product of those integers. Return the maximum product you can get .", + "description_images": [], + "constraints": [ + "2 <= n <= 58" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:2 = 1 + 1, 1 × 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 10\nOutput:36\nExplanation:10 = 3 + 3 + 4, 3 × 3 × 4 = 36.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def integerBreak(self, n: int) -> int:\n dp = [0 for _ in range(n+1)]\n dp[1] = 1\n for i in range(2, n+1):\n for j in range(1, i//2+1):\n dp[i] = max(j * (i-j), j * dp[i-j], dp[i])\n return dp[-1]\n", + "title": "343. Integer Break", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , you can apply one of the following operations: Return the minimum number of operations needed for n to become 1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 8\nOutput:3\nExplanation:8 -> 4 -> 2 -> 1", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:4\nExplanation:7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int integerReplacement(int n) {\n return (int)calc(n,0);\n }\n public long calc(long n,int i){\n if(n==1) \n return i;\n if(n<1) \n return 0;\n \n long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE;\n \n if(n%2==0) \n a=calc(n/2,i+1);\n else{\n b=calc(n-1,i+1);\n c=calc(n+1,i+1);\n }\n long d=Math.min(a,Math.min(b,c));\n return d;\n }\n}\n", + "title": "397. Integer Replacement", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , you can apply one of the following operations: Return the minimum number of operations needed for n to become 1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 8\nOutput:3\nExplanation:8 -> 4 -> 2 -> 1", + "image": null + }, + { + "text": "Example 2: Input:n = 7\nOutput:4\nExplanation:7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 77.23%) | Memory: 14 MB (Top 29.19%)\n\nclass Solution:\n def integerReplacement(self, n: int) -> int:\n dp = {}\n def dfs(num):\n if num == 1:\n return 0\n\n if num in dp:\n return dp[num]\n\n # if num is even, we have only one option -> n / 2\n even = odd = 0\n if num % 2 == 0:\n even = 1 + dfs(num // 2)\n else:\n # if num is odd, we have two option, either we increment the num or decrement the num\n odd1 = 1 + dfs(num - 1)\n odd2 = 1 + dfs(num + 1)\n # take the min of both operation\n odd = min(odd1, odd2)\n\n dp[num] = even + odd\n return dp[num]\n\n return dfs(n)", + "title": "397. Integer Replacement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Convert a non-negative integer num to its English words representation.", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 123\nOutput:\"One Hundred Twenty Three\"", + "image": null + }, + { + "text": "Example 2: Input:num = 12345\nOutput:\"Twelve Thousand Three Hundred Forty Five\"", + "image": null + }, + { + "text": "Example 3: Input:num = 1234567\nOutput:\"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[] INT_NUMBERS = {\n 1_000_000_000, 1_000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};\n private static final String[] STRING_NUMBERS = {\n \"Billion\", \"Million\", \"Thousand\", \"Hundred\", \"Ninety\", \"Eighty\", \"Seventy\", \"Sixty\", \"Fifty\", \"Forty\", \"Thirty\", \"Twenty\",\n \"Nineteen\", \"Eighteen\", \"Seventeen\", \"Sixteen\", \"Fifteen\", \"Fourteen\", \"Thirteen\", \"Twelve\", \"Eleven\", \"Ten\",\n \"Nine\", \"Eight\", \"Seven\", \"Six\", \"Five\", \"Four\", \"Three\", \"Two\", \"One\"};\n\n public String numberToWords(int num) {\n if (num == 0) return \"Zero\";\n return numberToWordsHelper(num).toString();\n }\n\n private StringBuilder numberToWordsHelper(int num) {\n StringBuilder sb = new StringBuilder();\n if (num == 0) return sb;\n for (int i = 0; i < INT_NUMBERS.length; i++) {\n if (num >= INT_NUMBERS[i]) {\n if (num >= 100) {\n sb.append(numberToWordsHelper(num / INT_NUMBERS[i]).append(\" \"));\n }\n\n sb.append(STRING_NUMBERS[i]).append(\" \").append(numberToWordsHelper(num % INT_NUMBERS[i]));\n break;\n }\n }\n return sb.charAt(sb.length() - 1) == ' ' ? sb.deleteCharAt(sb.length() - 1) : sb; // trim\n }\n \n}\n\n", + "title": "273. Integer to English Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Convert a non-negative integer num to its English words representation.", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 123\nOutput:\"One Hundred Twenty Three\"", + "image": null + }, + { + "text": "Example 2: Input:num = 12345\nOutput:\"Twelve Thousand Three Hundred Forty Five\"", + "image": null + }, + { + "text": "Example 3: Input:num = 1234567\nOutput:\"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberToWords(self, num: int) -> str:\n \n if num == 0:\n return \"Zero\"\n \n dic1 = {1000000000: \"Billion\", 1000000: \"Million\", 1000: \"Thousand\", 1: \"\"}\n dic2 = {90: \"Ninety\", 80: \"Eighty\", 70: \"Seventy\", 60: \"Sixty\", 50: \"Fifty\", 40: \"Forty\", 30: \"Thirty\", 20: \"Twenty\", 19: 'Nineteen', 18: \"Eighteen\", 17: \"Seventeen\", 16: \"Sixteen\", 15: \"Fifteen\", 14: \"Fourteen\", 13: \"Thirteen\", 12: \"Twelve\", 11: \"Eleven\", 10: \"Ten\", 9: \"Nine\", 8: \"Eight\", 7: \"Seven\", 6: \"Six\", 5: \"Five\", 4: \"Four\", 3: \"Three\", 2: \"Two\", 1: \"One\"}\n \n def construct_num(num):\n ans = ''\n d, num = divmod(num, 100)\n if d > 0:\n ans += dic2[d] + \" \" + \"Hundred\"\n for k, v in dic2.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + v\n return ans.lstrip() \n \n ans = \"\"\n for k, v in dic1.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + construct_num(d) + \" \" + v\n \n return ans.strip()\n", + "title": "273. Integer to English Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given an integer, convert it to a roman numeral.", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:num = 3\nOutput:\"III\"\nExplanation:3 is represented as 3 ones.", + "image": null + }, + { + "text": "Example 2: Input:num = 58\nOutput:\"LVIII\"\nExplanation:L = 50, V = 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:num = 1994\nOutput:\"MCMXCIV\"\nExplanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 27.77%) | Memory: 44.00 MB (Top 31.59%)\n\nclass Solution {\n final static int[] val = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n final static String[] rom = {\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"};\n\n public String intToRoman(int N) {\n StringBuilder ans = new StringBuilder();\n for (int i = 0; N > 0; i++)\n while (N >= val[i]) {\n ans.append(rom[i]);\n N -= val[i];\n }\n return ans.toString();\n }\n}\n", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given an integer, convert it to a roman numeral.", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:num = 3\nOutput:\"III\"\nExplanation:3 is represented as 3 ones.", + "image": null + }, + { + "text": "Example 2: Input:num = 58\nOutput:\"LVIII\"\nExplanation:L = 50, V = 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:num = 1994\nOutput:\"MCMXCIV\"\nExplanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 86.4%) | Memory: 16.42 MB (Top 14.9%)\n\nclass Solution:\n def intToRoman(self, num: int) -> str:\n # Creating Dictionary for Lookup\n num_map = {\n 1: \"I\",\n 5: \"V\", 4: \"IV\",\n 10: \"X\", 9: \"IX\",\n 50: \"L\", 40: \"XL\",\n 100: \"C\", 90: \"XC\",\n 500: \"D\", 400: \"CD\",\n 1000: \"M\", 900: \"CM\",\n }\n \n # Result Variable\n r = ''\n \n \n for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:\n # If n in list then add the roman value to result variable\n while n <= num:\n r += num_map[n]\n num-=n\n return r", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 non-empty substrings respectively, such that: Note: a + b is the concatenation of strings a and b .", + "description_images": [], + "constraints": [ + "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 + ..." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"\nOutput:true\nExplanation:One way to obtain s3 is:\nSplit s1 into s1 = \"aa\" + \"bc\" + \"c\", and s2 into s2 = \"dbbc\" + \"a\".\nInterleaving the two splits, we get \"aa\" + \"dbbc\" + \"bc\" + \"a\" + \"c\" = \"aadbbcbcac\".\nSince s3 can be obtained by interleaving s1 and s2, we return true.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg" + }, + { + "text": "Example 2: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"\nOutput:false\nExplanation:Notice how it is impossible to interleave s2 with any other string to obtain s3.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"\", s2 = \"\", s3 = \"\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3) :\n return False\n dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n \n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]\n", + "title": "97. Interleaving String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= sum(nums[i].length) <= 1000", + "1 <= nums[i][j] <= 1000", + "All the values of nums[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\nOutput:[3,4]\nExplanation:The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[4,5,6]]\nOutput:[]\nExplanation:There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.41%) | Memory: 46.4 MB (Top 56.41%)\n\nclass Solution {\n public List intersection(int[][] nums) {\n\n List ans = new ArrayList<>();\n\n int[] count = new int[1001];\n\n for(int[] arr : nums){\n for(int i : arr){\n count[i]++;\n }\n }\n\n for(int i=0;i List[int]:\n return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])\n\t\t\n", + "title": "2248. Intersection of Multiple Arrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must be unique and you may return the result in any order .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]\nOutput:[2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput:[9,4]\nExplanation:[4,9] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.90%) | Memory: 44.3 MB (Top 29.92%)\nclass Solution {\n public int[] intersection(int[] nums1, int[] nums2) {\n int[] dp = new int[1000];\n for(int i:nums1){\n dp[i]++;\n }\n int[] ans = new int[1000];\n\n //declaring ptr to track ans array index\n int ptr = 0;\n for(int i:nums2){\n if(dp[i] != 0){\n dp[i] = 0;\n ans[ptr] = i;\n ptr++;\n }\n }\n return Arrays.copyOfRange(ans, 0, ptr);\n }\n}", + "title": "349. Intersection of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must be unique and you may return the result in any order .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]\nOutput:[2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput:[9,4]\nExplanation:[4,9] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 73.60%) | Memory: 14 MB (Top 91.27%)\nclass Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n nums1.sort()\n nums2.sort()\n ans = []\n i, j = 0, 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n if len(ans) == 0 or nums1[i] != ans[-1]:\n ans.append(nums1[i])\n i += 1\n j += 1\n return ans", + "title": "349. Intersection of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]\nOutput:[2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput:[4,9]\nExplanation:[9,4] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] intersect(int[] nums1, int[] nums2) {\n int[] dp = new int[1000+1];\n for(int i: nums1){\n dp[i]++;\n }\n int ptr =0;\n int ans[] = new int[1000+1];\n for(int i:nums2){\n if(dp[i]!= 0){\n ans[ptr]= i;\n ptr++;\n dp[i]--;\n }\n \n }\n return Arrays.copyOfRange(ans,0,ptr);\n }\n}\n", + "title": "350. Intersection of Two Arrays II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]\nOutput:[2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput:[4,9]\nExplanation:[9,4] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n nums1.sort()\n nums2.sort()\n ans = []\n i, j = 0, 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n ans.append(nums1[i])\n i += 1\n j += 1\n return ans\n", + "title": "350. Intersection of Two Arrays II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput:Intersected at '8'\nExplanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput:Intersected at '2'\nExplanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput:No intersection\nExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\n\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.75%) | Memory: 55.6 MB (Top 36.20%)\npublic class Solution {\n public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n ListNode tempA = headA, tempB = headB;\n int lenA = 0, lenB = 0;\n while (tempA != null) {\n lenA++;\n tempA = tempA.next;\n }\n while (tempB != null) {\n lenB++;\n tempB = tempB.next;\n }\n tempA = headA; tempB = headB;\n if (lenB > lenA) {\n for (int i = 0; i < lenB - lenA; i++) {\n tempB = tempB.next;\n }\n } else if (lenA > lenB) {\n for (int i = 0; i < lenA - lenB; i++) {\n tempA = tempA.next;\n }\n }\n while (tempA != null && tempA != tempB) {\n tempA = tempA.next;\n tempB = tempB.next;\n }\n return tempA;\n }\n}", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput:Intersected at '8'\nExplanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput:Intersected at '2'\nExplanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput:No intersection\nExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\n\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n m = 0\n n = 0\n temp = headA\n while temp != None:\n m+=1\n temp = temp.next\n temp = headB\n while temp != None:\n n+=1\n temp = temp.next\n diff = 0\n if m>=n : \n diff = m-n\n else:\n diff = n-m\n p1 = headA\n p2 = headB\n if max(m,n) == m:\n while diff > 0:\n p1 = p1.next\n diff-=1\n else:\n while diff > 0:\n p2 = p2.next\n diff-=1\n while p1 != None and p2!=None:\n if p1 == p2:\n return p1\n p1 = p1.next\n p2 = p2.next\n return None\n", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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] .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]", + "image": "https://assets.leetcode.com/uploads/2019/01/30/interval1.png" + }, + { + "text": "Example 2: Input:firstList = [[1,3],[5,9]], secondList = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 9.49%) | Memory: 45.30 MB (Top 8.74%)\n\nclass Solution {\n public int[][] intervalIntersection(int[][] A, int[][] B) {\n List ans = new ArrayList<>();\n int i = 0, j = 0;\n while(i < A.length && j< B.length){\n int start = Math.max(A[i][0], B[j][0]);\n int end = Math.min(A[i][1], B[j][1]);\n if(start <= end) ans.add(new int[]{start, end});\n if(A[i][1]>B[j][1]) j++;\n else i++;\n }\n \n int[][] res = new int[ans.size()][2];\n i = 0;\n for(int[] pair: ans){\n res[i++] = pair;\n }\n \n return res;\n }\n}\n", + "title": "986. Interval List Intersections", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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] .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]", + "image": "https://assets.leetcode.com/uploads/2019/01/30/interval1.png" + }, + { + "text": "Example 2: Input:firstList = [[1,3],[5,9]], secondList = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 325 ms (Top 13.56%) | Memory: 15.2 MB (Top 15.52%)\nfrom collections import deque\n\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\n answer = []\n\n if len(firstList) == 0 or len(secondList) == 0:\n return answer\n\n first_queue= deque(firstList)\n second_queue = deque(secondList )\n\n first = first_queue.popleft()\n second = second_queue.popleft()\n\n while first_queue or second_queue:\n\n if first[1] < second[0]:\n if len(first_queue):\n first = first_queue.popleft()\n continue\n break\n if second[1] < first[0]:\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n answer.append([second[0], first[1]])\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n else:\n answer.append(second)\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n if second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n answer.append([first[0], second[1]])\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n else:\n answer.append(first)\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n\n if len(answer) > 0:\n\n if answer[-1] != [second[0], first[1]]:\n answer.append([second[0], first[1]])\n elif not answer:\n answer.append([second[0], first[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != second:\n answer.append(second)\n elif not answer:\n answer.append(second)\n elif second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n if len(answer) > 0:\n if answer[-1] != [first[0], second[1]]:\n answer.append([first[0], second[1]])\n elif not answer:\n answer.append([first[0], second[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != first:\n answer.append(first)\n elif not answer:\n\n answer.append(first)\n\n return answer", + "title": "986. Interval List Intersections", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array of n integers arr . The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j| . Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i] . Note: |x| is the absolute value of x .", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10^5", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,1,2,3,3]\nOutput:[4,2,7,2,4,4,5]\nExplanation:- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5", + "image": null + }, + { + "text": "Example 2: Input:arr = [10,5,10,10]\nOutput:[5,0,3,4]\nExplanation:- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 544 ms (Top 6.59%) | Memory: 244.1 MB (Top 25.15%)\nclass Solution {\n public long[] getDistances(int[] arr) {\n long[] output = new long[arr.length];\n Map sumMap = new HashMap<>();\n Map countMap = new HashMap<>();\n for (int i = 0; i < arr.length; ++ i) {\n if (!sumMap.containsKey(arr[i])) {\n sumMap.put(arr[i], 0l);\n countMap.put(arr[i], 0);\n }\n\n output[i] += i * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n sumMap.put(arr[i], sumMap.get(arr[i]) + i);\n countMap.put(arr[i], countMap.get(arr[i]) + 1);\n }\n\n sumMap = new HashMap<>();\n countMap = new HashMap<>();\n int len = arr.length;\n for (int i = len - 1; i >= 0; -- i) {\n if (!sumMap.containsKey(arr[i])) {\n sumMap.put(arr[i], 0l);\n countMap.put(arr[i], 0);\n }\n\n output[i] += (len - i - 1) * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n sumMap.put(arr[i], sumMap.get(arr[i]) + (len - i - 1));\n countMap.put(arr[i], countMap.get(arr[i]) + 1);\n }\n\n return output;\n }\n}", + "title": "2121. Intervals Between Identical Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of n integers arr . The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j| . Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i] . Note: |x| is the absolute value of x .", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10^5", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,1,2,3,3]\nOutput:[4,2,7,2,4,4,5]\nExplanation:- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5", + "image": null + }, + { + "text": "Example 2: Input:arr = [10,5,10,10]\nOutput:[5,0,3,4]\nExplanation:- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4", + "image": null + } + ], + "follow_up": null, + "solution": "\n# helper data structure Scout\nclass Scout:\n \n def __init__(self, prev_idx=-1, count_of_equal=0):\n \n # record of index of last identical element\n self.prev_idx = prev_idx\n \n # count of identical elements so far\n self.count_of_equal = count_of_equal\n \n def __iter__(self):\n\t\t# ouput previous index, and count of equal in order\n return iter( (self.prev_idx, self.count_of_equal) )\n \n \n \nclass Solution:\n def getDistances(self, arr: List[int]) -> List[int]:\n \n size = len(arr)\n \n pre_scout = defaultdict( Scout )\n pre_dist_sum = [0 for _ in range(size)]\n \n post_scout = defaultdict( Scout )\n post_dist_sum = [0 for _ in range(size)]\n \n \n ## Step_1:\n # update for pre_dist_sum table, direction is from left to right\n for i, element in enumerate(arr):\n \n prev_equal_idx, prev_count_of_equal = pre_scout[element]\n \n # update pre_dist_sum table if we have identical elements before index i\n if prev_count_of_equal:\n pre_dist_sum[i] += pre_dist_sum[ prev_equal_idx ] + (i - prev_equal_idx) * prev_count_of_equal\n \n # update Scout information for current element\n pre_scout[element] = i, prev_count_of_equal+1\n \n # --------------------------------------------------------------\n \n ## Step_2:\n # update for pos_dist_sum table, direction is from right to left\n for i, element in reversed( [*enumerate(arr)] ):\n \n post_equal_idx, post_count_of_equal = post_scout[element]\n\n # update post_dist_sum table if we have identical elements after index i\n if post_count_of_equal:\n post_dist_sum[i] += post_dist_sum[ post_equal_idx ] + (post_equal_idx - i) * post_count_of_equal\n \n # update Scout information for current element\n post_scout[element] = i, post_count_of_equal+1\n \n \n ## Step_3:\n # Generate final output by definition\n return [ pre_dist_sum[i] + post_dist_sum[i] for i in range(size) ]\n \n \n", + "title": "2121. Intervals Between Identical Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A transaction is possibly invalid if: You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "the amount exceeds $1000 , or;", + "if it occurs within (and including) 60 minutes of another transaction with the same name in a different city ." + ], + "examples": [ + { + "text": "Example 1: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nOutput:[\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nExplanation:The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.", + "image": null + }, + { + "text": "Example 2: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\nOutput:[\"alice,50,1200,mtv\"]", + "image": null + }, + { + "text": "Example 3: Input:transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\nOutput:[\"bob,50,1200,mtv\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 63.84%) | Memory: 50.7 MB (Top 74.53%)\nclass Solution {\n public List invalidTransactions(String[] transactions) {\n Map> nameToTransaction = new HashMap<>();\n for (int i = 0; i < transactions.length; i++) {\n Transaction t = new Transaction(transactions[i], i);\n nameToTransaction.putIfAbsent(t.name, new ArrayList<>());\n nameToTransaction.get(t.name).add(t);\n }\n List invalid = new ArrayList<>();\n for (List list : nameToTransaction.values()) {\n for (Transaction t : list) {\n if (t.isInvalidAmount()) invalid.add(transactions[t.id]);\n else {\n for (Transaction otherT : list) {\n if (t.isInvalidCity(otherT)) {\n invalid.add(transactions[t.id]);\n break;\n }\n }\n }\n }\n }\n return invalid;\n }\n}\n\nclass Transaction {\n String name, city;\n int time, amount, id;\n\n Transaction(String s, int id) {\n this.id = id;\n String[] split = s.split(\",\");\n name = split[0];\n time = Integer.parseInt(split[1]);\n amount = Integer.parseInt(split[2]);\n city = split[3];\n }\n\n boolean isInvalidAmount() {\n return this.amount > 1000;\n }\n\n boolean isInvalidCity(Transaction t) {\n return !city.equals(t.city) && Math.abs(t.time - time) <= 60;\n }\n}", + "title": "1169. Invalid Transactions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A transaction is possibly invalid if: You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "the amount exceeds $1000 , or;", + "if it occurs within (and including) 60 minutes of another transaction with the same name in a different city ." + ], + "examples": [ + { + "text": "Example 1: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nOutput:[\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nExplanation:The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.", + "image": null + }, + { + "text": "Example 2: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\nOutput:[\"alice,50,1200,mtv\"]", + "image": null + }, + { + "text": "Example 3: Input:transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\nOutput:[\"bob,50,1200,mtv\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 99.79%) | Memory: 18.10 MB (Top 5.19%)\n\nclass Transaction:\n def __init__(self, name, time, amount, city):\n self.name = name\n self.time = int(time)\n self.amount = int(amount)\n self.city = city\n\nfrom collections import defaultdict\nclass Solution:\n def invalidTransactions(self, transactions):\n transactions = [Transaction(*transaction.split(',')) for transaction in transactions]\n transactions.sort(key=lambda t: t.time) # O(nlogn) time\n\n trans_indexes = defaultdict(list)\n for i, t in enumerate(transactions): # O(n) time\n trans_indexes[t.name].append(i)\n\n res = []\n for name, indexes in trans_indexes.items(): # O(n) time\n left = right = 0\n for i, t_index in enumerate(indexes):\n t = transactions[t_index]\n if (t.amount > 1000):\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n continue\n while left <= len(indexes)-2 and transactions[indexes[left]].time < t.time - 60: # O(60) time\n left += 1\n while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time\n right += 1\n for i in range(left,right+1): # O(120) time\n if transactions[indexes[i]].city != t.city:\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n break\n\n return res\n", + "title": "1169. Invalid Transactions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, invert the tree, and return its root .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]\nOutput:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]\nOutput:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 66.34%)\nclass Solution {\n public TreeNode invertTree(TreeNode root) {\n\n swap(root);\n return root;\n }\n\n private static void swap(TreeNode current) {\n if (current == null) {\n return;\n }\n\n swap(current.left);\n swap(current.right);\n\n TreeNode temp = current.left;\n current.left = current.right;\n current.right = temp;\n }\n}", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, invert the tree, and return its root .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]\nOutput:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]\nOutput:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7 ms (Top 98.3%) | Memory: 13.26 MB (Top 67.3%)\n\nclass Solution(object):\n def invertTree(self, root):\n # Base case...\n if root == None:\n return root\n # swapping process...\n root.left, root.right = root.right, root.left\n # Call the function recursively for the left subtree...\n self.invertTree(root.left)\n # Call the function recursively for the right subtree...\n self.invertTree(root.right)\n return root # Return the root...", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput:4\nExplanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tstatic int[][] dp;\n\n\tpublic int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n\t\tdp = new int[k + 1][profits.length + 1];\n\t\tfor (int[] row : dp) {\n\t\t\tArrays.fill(row, -1);\n\t\t}\n\t\treturn w + help(k, w, 0, profits, capital);\n\t}\n\n\tpublic int help(int k, int w, int i, int[] profits, int[] capital) {\n\t\tif (k == 0 || i >= profits.length)\n\t\t\treturn 0;\n\t\tif (dp[k][i] != -1)\n\t\t\treturn dp[k][i];\n\t\tint res = Integer.MIN_VALUE;\n\t\tif (capital[i] <= w) {\n\t\t\tres = Math.max(res, Math.max(profits[i] + help(k - 1, w + profits[i], i + 1, profits, capital),\n\t\t\t\t\thelp(k, w, i + 1, profits, capital)));\n\t\t} else {\n\t\t\tres = Math.max(res, help(k, w, i + 1, profits, capital));\n\t\t}\n\t\treturn dp[k][i] = res;\n\t}\n}\n", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput:4\nExplanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heappush, heappop, nlargest\nclass Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n if w >= max(capital):\n return w + sum(nlargest(k, profits))\n \n projects = [[capital[i],profits[i]] for i in range(len(profits))]\n projects.sort(key=lambda x: x[0])\n \n heap = []\n \n for i in range(k):\n while projects and projects[0][0] <= w:\n heappush(heap, -1*projects.pop(0)[1])\n \n if not heap:\n break\n p = -heappop(heap)\n w += p\n return w\n", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not).", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n public boolean isSubsequence(String s, String t) \n {\n int i,x,p=-1;\n if(s.length()>t.length())\n return false;\n for(i=0;ip)\n p=x;\n else\n return false;\n }\n return true;\n }\n}\n", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not).", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n if len(s) > len(t):return False\n if len(s) == 0:return True\n subsequence=0\n for i in range(0,len(t)):\n if subsequence <= len(s) -1:\n print(s[subsequence])\n if s[subsequence]==t[i]:\n\n subsequence+=1\n return subsequence == len(s) \n", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 100", + "grid[i][j] is 0 or 1 .", + "There is exactly one island in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\nOutput:16\nExplanation:The perimeter is the 16 yellow stripes in the image above.", + "image": "https://assets.leetcode.com/uploads/2018/10/12/island.png" + }, + { + "text": "Example 2: Input:grid = [[1]]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 73.55%) | Memory: 62.3 MB (Top 52.61%)\nclass Solution {\n public int islandPerimeter(int[][] grid) {\n if(grid == null || grid.length == 0) return 0;\n\n int row=grid.length,col=grid[0].length;\n int perimeter=0;\n\n for(int i=0;i0 && grid[i-1][j]==1){\n perimeter-=2;\n }\n\n if(j>0 && grid[i][j-1]==1){\n perimeter-=2;\n }\n }\n\n }\n }\n return perimeter;\n }\n}", + "title": "463. Island Perimeter", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 100", + "grid[i][j] is 0 or 1 .", + "There is exactly one island in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\nOutput:16\nExplanation:The perimeter is the 16 yellow stripes in the image above.", + "image": "https://assets.leetcode.com/uploads/2018/10/12/island.png" + }, + { + "text": "Example 2: Input:grid = [[1]]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 382 ms (Top 98.7%) | Memory: 16.57 MB (Top 93.9%)\n\nclass Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n perimeter = 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n perimeter += 4\n if i != 0 and grid[i-1][j] == 1:\n perimeter -= 2\n if j != 0 and grid[i][j-1] == 1:\n perimeter -= 2 \n \n return perimeter\n", + "title": "463. Island Perimeter", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , determine if they are isomorphic . Two strings s and t are isomorphic if the characters in s can be replaced to get t . All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "t.length == s.length", + "s and t consist of any valid ascii character." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"egg\", t = \"add\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"foo\", t = \"bar\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:s = \"paper\", t = \"title\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isIsomorphic(String s, String t) {\n \n ArrayListlist1 = new ArrayList<>();\n ArrayListlist2 = new ArrayList<>();\n for(int i=0;i bool:\n dict1={}\n m=\"\"\n\t\t#creating a dictionary by mapping each element from string S to string T\n for i,j in zip(s,t):\n\t\t# this for the cases like \"badc\" and \"baba\" so we dont want two keys mapping to same value hence we can reject directly\n if j in dict1.values() and i not in dict1.keys():\n return False\n dict1[i]=j \n \n\t\t#now take each letter from string s and using dictionary values replace it with that specific character\n for k in s:\n m=m+dict1[k]\n\t\t\t\n\t\t#now if newly formed string m == T is same then the strings are Isomorphic\n if(m==t):\n return True\n else:\n return False\n", + "title": "205. Isomorphic Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design the CombinationIterator class:", + "description_images": [], + "constraints": [ + "CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.", + "next() Returns the next combination of length combinationLength in lexicographical order .", + "hasNext() Returns true if and only if there exists a next combination." + ], + "examples": [ + { + "text": "Example 1: Input[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]Output[null, \"ab\", true, \"ac\", true, \"bc\", false]ExplanationCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next(); // return \"ab\"\nitr.hasNext(); // return True\nitr.next(); // return \"ac\"\nitr.hasNext(); // return True\nitr.next(); // return \"bc\"\nitr.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class CombinationIterator {\n\n private Queue allCombinations;\n public CombinationIterator(String characters, int combinationLength) {\n this.allCombinations = new LinkedList<>();\n generateAllCombinations(characters,0,combinationLength,new StringBuilder());\n }\n \n private void generateAllCombinations(String characters,int index,int combinationLength,StringBuilder currentString){\n \n if(currentString.length() == combinationLength){\n this.allCombinations.offer(currentString.toString());\n return;\n }\n \n for(int i = index ; i < characters.length() ; i++){\n currentString.append(characters.charAt(i));\n generateAllCombinations(characters,i+1,combinationLength,currentString);\n currentString.deleteCharAt(currentString.length()-1);\n }\n \n }\n \n public String next() {\n return this.allCombinations.poll();\n }\n \n public boolean hasNext() {\n return !this.allCombinations.isEmpty();\n }\n}\n", + "title": "1286. Iterator for Combination", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design the CombinationIterator class:", + "description_images": [], + "constraints": [ + "CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.", + "next() Returns the next combination of length combinationLength in lexicographical order .", + "hasNext() Returns true if and only if there exists a next combination." + ], + "examples": [ + { + "text": "Example 1: Input[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]Output[null, \"ab\", true, \"ac\", true, \"bc\", false]ExplanationCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next(); // return \"ab\"\nitr.hasNext(); // return True\nitr.next(); // return \"ac\"\nitr.hasNext(); // return True\nitr.next(); // return \"bc\"\nitr.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 68.38%) | Memory: 20.00 MB (Top 5.53%)\n\nclass CombinationIterator:\n\n def __init__(self, characters: str, combinationLength: int):\n self.characters = characters\n self.n = len(characters)\n self.combinations = gen_combinations(self.n, combinationLength)\n self.ind = len(self.combinations) - 1\n\n def next(self) -> str:\n s = \"\"\n for i in range(self.n):\n if self.combinations[self.ind][i] != \"0\":\n s += self.characters[i]\n self.ind -= 1\n return s\n\n def hasNext(self) -> bool:\n return self.ind > -1 \n \ndef gen_combinations(l, n):\n end = int(\"1\" * l, 2)\n ans = []\n for i in range(end + 1):\n b = bin(i)[2:]\n if b.count('1') == n:\n ans.append(b.zfill(l))\n return ans\n", + "title": "1286. Iterator for Combination", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\" .", + "description_images": [], + "constraints": [ + "1 <= jewels.length, stones.length <= 50", + "jewels and stones consist of only English letters.", + "All the characters of jewels are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:jewels = \"aA\", stones = \"aAAbbbb\"\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:jewels = \"z\", stones = \"ZZ\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 31.57%) | Memory: 42.7 MB (Top 19.07%)\nclass Solution {\n public int numJewelsInStones(String jewels, String stones) {\n HashSet hs=new HashSet<>();\n int count=0;\n for(int i=0;i int:\n\t\t# 1 : One line solution, My best runtime 38 with 13.9 MB\n return sum(1 for k in stones if k in jewels)\n\t\t\n\t\t# 2 : Traditional solution\n\t\tx=0\n\t\tfor k in stones:\n\t\t\tif k in jewels:\n\t\t\t\tx+=1\n\t\treturn x\n", + "title": "771. Jewels and Stones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]\nOutput:true\nExplanation:Jump 1 step from index 0 to 1, then 3 steps to the last index.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,0,4]\nOutput:false\nExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 67.02%) | Memory: 67.1 MB (Top 78.50%)\nclass Solution {\n public boolean canJump(int[] nums)\n {\n int maxjump = 0;\n for(int i=0;i bool:\n \"\"\"\n # Memoization + DFS Solution\n # TLE as we have as much as n decisions depending on nums[i] which could be\n # 10^5 as an uppercase according to problem constraints\n # better off with a greedy approach\n\n cache = {} # i : bool\n\n def dfs(i):\n if i == len(nums) -1:\n return True\n if nums[i] == 0:\n return False\n if i in cache:\n return cache[i]\n for j in range(1, nums[i] + 1):\n res = dfs(i + j)\n if res:\n cache[i] = True\n return cache[i]\n cache[i] = False\n return cache[i]\n\n return dfs(0)\n \"\"\"\n # Greedy Solution\n # Key with greedy is to find a local and gobal optimum\n # here we find the furthest distance we can travel with each index\n\n # futhest index reachable\n reachable = 0\n\n # iterate through all indexes and if the current index is futher than what we can travel return fasle\n for i in range(len(nums)):\n if i > reachable:\n return False\n\n reachable = max(reachable, nums[i] + i)\n # if the futherest distance we can jump to is greater or equal than the last index break\n if reachable >= len(nums) - 1:\n break\n\n return True", + "title": "55. Jump Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of non-negative integers nums , you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 82.01%) | Memory: 50 MB (Top 21.41%)\nclass Solution {\n\n public int jump(int[] nums) {\n\n int result = 0;\n\n int L = 0;\n int R = 0;\n\n while (R < nums.length - 1) {\n\n int localMaxRight = 0;\n\n for (int i=L; i<=R; i++) {\n\n localMaxRight = Math.max(i + nums[i], localMaxRight);\n }\n\n L = R + 1;\n R = localMaxRight;\n result++;\n }\n\n return result;\n }\n}", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of non-negative integers nums , you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 305 ms (Top 40.77%) | Memory: 15 MB (Top 90.04%)\nclass Solution(object):\n def jump(self, nums):\n ans = l = r = 0\n\n while r < len(nums) - 1:\n farthestJump = 0\n\n for i in range(l, r + 1):\n farthestJump = max(farthestJump, i + nums[i])\n\n l = r + 1\n r = farthestJump\n ans += 1\n\n return ans", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of non-negative integers arr , you are initially positioned at start index of the array. When you are at index i , you can jump to i + arr[i] or i - arr[i] , check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 5 * 10^4", + "0 <= arr[i] < arr.length", + "0 <= start < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,3,0,3,1,2], start = 5\nOutput:true\nExplanation:All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,2,3,0,3,1,2], start = 0\nOutput:true\nExplanation:One possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,0,2,1,2], start = 2\nOutput:false\nExplanation:There is no way to reach at index 1 with value 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReach(int[] arr, int start) {\n int n = arr.length;\n boolean[] vis = new boolean[n];\n Queue q = new LinkedList<>();\n q.add(start);\n while(!q.isEmpty()){\n int size = q.size();\n while(size-- > 0){\n int curr = q.poll();\n if(vis[curr])\n continue;\n if(arr[curr] == 0)\n return true;\n if(curr+arr[curr] < n)\n q.add(curr+arr[curr]);\n if(curr-arr[curr] >= 0)\n q.add(curr-arr[curr]);\n vis[curr] = true;\n }\n }\n return false;\n }\n}\n", + "title": "1306. Jump Game III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of non-negative integers arr , you are initially positioned at start index of the array. When you are at index i , you can jump to i + arr[i] or i - arr[i] , check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 5 * 10^4", + "0 <= arr[i] < arr.length", + "0 <= start < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,3,0,3,1,2], start = 5\nOutput:true\nExplanation:All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,2,3,0,3,1,2], start = 0\nOutput:true\nExplanation:One possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,0,2,1,2], start = 2\nOutput:false\nExplanation:There is no way to reach at index 1 with value 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n vis = [0]*len(arr)\n q = deque() \n q.append(start) \n while q:\n cur = q.popleft() \n print(cur)\n vis[cur] = 1\n if arr[cur] == 0:\n return True\n if cur+arr[cur]=0 and vis[cur-arr[cur]] == 0: \n q.append(cur-arr[cur]) \n return False\n\n ", + "title": "1306. Jump Game III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , you are initially positioned at the first index of the array. In one step you can jump from index i to index: Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "i + 1 where: i + 1 < arr.length .", + "i - 1 where: i - 1 >= 0 .", + "j where: arr[i] == arr[j] and i != j ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput:3\nExplanation:You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7]\nOutput:0\nExplanation:Start index is the last index. You do not need to jump.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,9,6,9,6,9,7]\nOutput:1\nExplanation:You can jump directly from index 0 to index 7 which is last index of the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 147 ms (Top 48.60%) | Memory: 103.8 MB (Top 70.82%)\n/*\nHere we are using map and queue\nmap for storing the array elements and where are the other indices of the same element\nand queue for BFS\n\nInitially we start with 0 index\nSo we offer it to the queue\nNow until the queue is empty we have to do few things for a given position\ni> check the next index (i+1)\nii> check the previous index(i-1)\niii> check all the indices of the list whih are present in the map\nonce these three things have been done we will\nremove the element that is arr[i]\nbecause if we did not remove it we are going to do the same repeated task over and over again\nand this will result in stack overflow\nso it is important to remove the indices which have been visited once\nevery time we check the queue we incease the answer because viewing a queue means that\nwe are not at the last index\n\nI hope the idea was clear :) you'll understand better when you see the code\n*/\nclass Solution {\n public int minJumps(int[] arr) {\n int n = arr.length;\n\n if(n <= 1) return 0;\n Map> mp = new HashMap<>();\n for(int i = 0;i < arr.length ; i++) {\n if(!mp.containsKey(arr[i])) {\n mp.put(arr[i],new ArrayList<>());\n }\n List ls = mp.get(arr[i]);\n ls.add(i);\n }\n //System.out.print(mp);\n Queue q = new LinkedList<>();\n q.offer(0);\n int ans = 0;\n while(!q.isEmpty()) {\n ans++;\n int size = q.size();\n for(int i = 0;i < size;i++)\n {\n int j = q.poll();\n //adding j+1\n if(j+1 < n && mp.containsKey(arr[j+1])) {\n if(j+1 == n-1) return ans;\n q.offer(j+1);\n }\n //adding j-1\n if(j-1 > 0 && mp.containsKey(arr[j-1])) {\n q.offer(j-1);\n }\n\n //adding list indices\n if(mp.containsKey(arr[j])) {\n for(int k : mp.get(arr[j])) {\n //if(k == n-1) return ans;\n if(k != j) {\n if(k == n-1) return ans;\n q.offer(k);\n }\n }\n mp.remove(arr[j]);\n }\n }\n }\n return ans;\n }\n}", + "title": "1345. Jump Game IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , you are initially positioned at the first index of the array. In one step you can jump from index i to index: Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "i + 1 where: i + 1 < arr.length .", + "i - 1 where: i - 1 >= 0 .", + "j where: arr[i] == arr[j] and i != j ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput:3\nExplanation:You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7]\nOutput:0\nExplanation:Start index is the last index. You do not need to jump.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,9,6,9,6,9,7]\nOutput:1\nExplanation:You can jump directly from index 0 to index 7 which is last index of the array.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import deque\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n minSteps = 0\n queue = deque()\n queue.append(0)\n n = len(arr)\n visited = set()\n visited.add(0)\n \n\t\td = {i:[] for i in arr}\n \n for i, val in enumerate(arr):\n d[val].append(i)\n \n while queue:\n for _ in range(len(queue)):\n idx = queue.popleft()\n if idx == n - 1:\n return minSteps\n \n for i in [*d[arr[idx]], idx - 1, idx + 1]:\n if i not in visited and 0 <= i < n:\n visited.add(i)\n queue.append(i)\n d[arr[idx]].clear()\n minSteps += 1\n", + "title": "1345. Jump Game IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr and an integer d . In one step you can jump from index i to index: In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j) ). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "i + x where: i + x < arr.length and 0 < x <= d .", + "i - x where: i - x >= 0 and 0 < x <= d ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput:4\nExplanation:You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.", + "image": "https://assets.leetcode.com/uploads/2020/01/23/meta-chart.jpeg" + }, + { + "text": "Example 2: Input:arr = [3,3,3,3,3], d = 3\nOutput:1\nExplanation:You can start at any index. You always cannot jump to any index.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,5,4,3,2,1], d = 1\nOutput:7\nExplanation:Start at index 0. You can visit all the indicies.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 24.5%) | Memory: 43.52 MB (Top 29.6%)\n\nclass Solution {\n public int maxJumps(int[] arr, int d) {\n List jumpsFrom[] = new List[arr.length]; //find all possible jumps from each spot\n findJumps (arr,d,true,jumpsFrom); // add left jumps (itareting left to right)\n findJumps (arr,d,false,jumpsFrom); // add right jumps\n int jumpChain[] = new int[arr.length] , max = 1; // 0 - unvisited\n for (int i = 0 ; i < arr.length; i++) {\n if (jumpChain[i] == 0) {\n jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n max = Math.max(max, jumpChain[i]);\n }\n }\n return max;\n }\n\n private void findJumps(int[] arr, int d, boolean left , List jumpsFrom[]){\n Stack s = new Stack();\n int i = (left) ? 0 : arr.length - 1;\n while (i >=0 && i < arr.length){\n if (left) jumpsFrom[i] = new ArrayList();\n while (!s.isEmpty() && arr[i] > arr[s.peek()]){ // pop stack until higher step found from left/right, adding all left/right lower jumps from i\n int lowerIndex = s.pop(); \n if (Math.abs(i - lowerIndex) <= d) jumpsFrom[i].add(lowerIndex); \n else s = new Stack(); // past d steps\n }\n s.push(i);\n i += (left) ? 1 : -1;\n }\n }\n\n private int dfs(int[] arr , int jumpChain[], List jumpsFrom[], int start){\n int max = 1;\n for (int i: jumpsFrom[start]) {\n if (jumpChain[i] == 0) jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n max = Math.max (max , 1 + jumpChain[i]);\n }\n return max;\n }\n\n}", + "title": "1340. Jump Game V", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr and an integer d . In one step you can jump from index i to index: In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j) ). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.", + "description_images": [], + "constraints": [ + "i + x where: i + x < arr.length and 0 < x <= d .", + "i - x where: i - x >= 0 and 0 < x <= d ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput:4\nExplanation:You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.", + "image": "https://assets.leetcode.com/uploads/2020/01/23/meta-chart.jpeg" + }, + { + "text": "Example 2: Input:arr = [3,3,3,3,3], d = 3\nOutput:1\nExplanation:You can start at any index. You always cannot jump to any index.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,5,4,3,2,1], d = 1\nOutput:7\nExplanation:Start at index 0. You can visit all the indicies.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n n = len(arr)\n sorted_arr = []\n for i in range(n):\n sorted_arr.append((arr[i], i))\n sorted_arr.sort(reverse = True)\n depth = [1 for i in range(n)]\n while(sorted_arr):\n val, i = sorted_arr.pop()\n for j in range(i-1, max(-1, i-d-1), -1):\n if(arr[j] >= arr[i]):\n break\n depth[i] = max(depth[j] + 1, depth[i])\n for j in range(i+1, min(n, i+d+1)):\n if(arr[j] >= arr[i]):\n break\n depth[i] = max(depth[j] + 1, depth[i])\n return max(depth)\n", + "title": "1340. Jump Game V", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums and an integer k . You are initially standing at index 0 . In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive . You want to reach the last index of the array (index n - 1 ). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get .", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,-2,4,-7,3], k = 2\nOutput:7\nExplanation:You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,-5,-2,4,0,3], k = 3\nOutput:17\nExplanation:You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 93.03%) | Memory: 78 MB (Top 81.86%)\nclass Solution {\n public int maxResult(int[] nums, int k) {\n int n = nums.length, a = 0, b = 0;\n int[] deq = new int[n];\n deq[0] = n - 1;\n for (int i = n - 2; i >= 0; i--) {\n if (deq[a] - i > k) a++;\n nums[i] += nums[deq[a]];\n while (b >= a && nums[deq[b]] <= nums[i]) b--;\n deq[++b] = i;\n }\n return nums[0];\n }\n}", + "title": "1696. Jump Game VI", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and an integer k . You are initially standing at index 0 . In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive . You want to reach the last index of the array (index n - 1 ). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get .", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,-2,4,-7,3], k = 2\nOutput:7\nExplanation:You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,-5,-2,4,0,3], k = 3\nOutput:17\nExplanation:You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 791 ms (Top 67.87%) | Memory: 30.60 MB (Top 42.3%)\n\nclass Solution:\n def maxResult(self, nums, k):\n deq, n = deque([0]), len(nums)\n\n for i in range(1, n):\n while deq and deq[0] < i - k: deq.popleft()\n nums[i] += nums[deq[0]] \n while deq and nums[i] >= nums[deq[-1]]: deq.pop()\n deq.append(i)\n \n return nums[-1]\n", + "title": "1696. Jump Game VI", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Return true if you can reach index s.length - 1 in s , or false otherwise.", + "description_images": [], + "constraints": [ + "i + minJump <= j <= min(i + maxJump, s.length - 1) , and", + "s[j] == '0' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011010\", minJump = 2, maxJump = 3\nOutput:true\nExplanation:In the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \"01101110\", minJump = 2, maxJump = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReach(String s, int minJump, int maxJump) {\n if(s.charAt(s.length() - 1) != '0')\n return false;\n \n Queue queue = new LinkedList<>();\n queue.add(0);\n \n // This variable tells us till which index we have processed\n int maxReach = 0;\n \n while(!queue.isEmpty()){\n int idx = queue.remove();\n // If we reached the last index\n if(idx == s.length() - 1)\n return true;\n \n // start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)]\n for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){\n if(s.charAt(j) == '0')\n queue.add(j);\n }\n \n // since we have processed till idx + maxJump so update maxReach to next index\n maxReach = Math.min(idx + maxJump + 1, s.length() - 1);\n }\n \n return false;\n }\n}\n", + "title": "1871. Jump Game VII", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Return true if you can reach index s.length - 1 in s , or false otherwise.", + "description_images": [], + "constraints": [ + "i + minJump <= j <= min(i + maxJump, s.length - 1) , and", + "s[j] == '0' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011010\", minJump = 2, maxJump = 3\nOutput:true\nExplanation:In the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \"01101110\", minJump = 2, maxJump = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n\t\t# dp[i] represents whether i is reachable\n dp = [False for _ in s]\n dp[0] = True\n\n for i in range(1, len(s)):\n if s[i] == \"1\":\n continue\n\n\t\t\t# iterate through the solutions in range [i - maxJump, i - minJump]\n\t\t\t# and if any previous spot in range is reachable, then i is also reachable\n window_start = max(0, i - maxJump)\n window_end = i - minJump\n for j in range(window_start, window_end + 1):\n if dp[j]:\n dp[i] = True\n break\n \n return dp[-1] \n\n", + "title": "1871. Jump Game VII", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 < x i , y i < 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1\nOutput:[[-2,2]]\nExplanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput:[[3,3],[-2,4]]\nExplanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static class Distance {\n int i;\n int j;\n double dist;\n\n public Distance(int i, int j, double dist) {\n this.i = i;\n this.j = j;\n this.dist = dist;\n }\n }\n\n public int[][] kClosest(int[][] points, int k) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Double.compare(x.dist, y.dist));\n for(int[] point : points) {\n double dist = calcDistance(point[0], point[1]);\n pq.offer(new Distance(point[0], point[1], dist));\n }\n int cnt = 0;\n ArrayList l = new ArrayList<>();\n while(cnt < k) {\n Distance d = pq.poll();\n l.add(new int[]{d.i, d.j});\n cnt++;\n }\n int[][] res = l.toArray(new int[l.size()][]);\n return res;\n }\n\n private double calcDistance(int i, int j) {\n double dist = Math.sqrt(Math.pow(i,2) + Math.pow(j,2));\n return dist;\n }\n}", + "title": "973. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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).", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 < x i , y i < 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1\nOutput:[[-2,2]]\nExplanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput:[[3,3],[-2,4]]\nExplanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2003 ms (Top 6.82%) | Memory: 20.5 MB (Top 21.33%)\n\ndef cal(ele):\n return ele[0]**2 +ele[1]**2\n\ndef partition(arr,start,end):\n # We must take a pivot element randomly to make Quick select work faster\n rdIdx = randint(start,end)\n arr[rdIdx],arr[end] = arr[end],arr[rdIdx]\n pivot = arr[end]\n i = start-1\n pivot_dis = cal(pivot)\n for j in range(start,end):\n if cal(arr[j]) <= pivot_dis:\n i+=1\n arr[j],arr[i] = arr[i],arr[j]\n\n arr[i+1],arr[end] = arr[end],arr[i+1]\n return i+1\ndef qSelect(arr,kth,start,end):\n if start < end:\n pv= partition(arr,start,end)\n # _______________________\n # | Left |ele| Right|\n # ------------------------\n # pv\n # after partition function call, pv is the index that sacrify:\n # all elements in Left will smaller than ele\n # all elements in Right side will greater than ele\n if pv == kth:#\n return\n if kth < pv:\n return qSelect(arr,kth,start,pv-1)\n else:\n return qSelect(arr,kth,pv+1,end)\n# Space O (logn) because of using recursion\n# Time: Average case: O(N)\n# Worst case: O(N**2)\nclass Solution:\n def kClosest(self, points, k):\n # print(points)\n qSelect(points,k-1,0,len(points)-1)# kth smallest number will be at (k-1) index in sorted array\n return points[:k]", + "title": "973. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and two integers k and p , return the number of distinct subarrays which have at most k elements divisible by p . Two arrays nums1 and nums2 are said to be distinct if: A subarray is defined as a non-empty contiguous sequence of elements in an array.", + "description_images": [], + "constraints": [ + "They are of different lengths, or", + "There exists at least one index i where nums1[i] != nums2[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2,2], k = 2, p = 2\nOutput:11\nExplanation:The elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 4, p = 1\nOutput:10\nExplanation:All element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 84.38%) | Memory: 67.2 MB (Top 74.81%)\nclass Solution {\n public int countDistinct(int[] nums, int k, int p) {\n int n = nums.length;\n // we are storing hashcode for all the substrings so that we can compare them faster.\n // main goal is to avoid entire sub array comparision using hashcode.\n Set ways = new HashSet<>();\n for(int i = 0; i < n; i++) {\n int cnt = 0;\n long hc = 1; // this is the running hashcode for sub array [i...j]\n for(int j = i; j < n; j++) {\n hc = 199L * hc + nums[j]; // updating running hashcode, since we nums are <=200, we shall consider a prime near 200 to avoid collision\n if(nums[j] % p == 0)\n cnt++;\n if(cnt <= k) { // if current subarray [i...j] is valid, add its hashcode in our storage.\n ways.add(hc);\n }\n }\n }\n return ways.size();\n }\n}", + "title": "2261. K Divisible Elements Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and two integers k and p , return the number of distinct subarrays which have at most k elements divisible by p . Two arrays nums1 and nums2 are said to be distinct if: A subarray is defined as a non-empty contiguous sequence of elements in an array.", + "description_images": [], + "constraints": [ + "They are of different lengths, or", + "There exists at least one index i where nums1[i] != nums2[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2,2], k = 2, p = 2\nOutput:11\nExplanation:The elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 4, p = 1\nOutput:10\nExplanation:All element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n n = len(nums) \n sub_arrays = set()\n \n\t\t# generate all combinations of subarray\n for start in range(n):\n cnt = 0\n temp = ''\n for i in range(start, n):\n if nums[i]%p == 0:\n cnt+=1 \n temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format \n if cnt>k: # check for termination \n break\n sub_arrays.add(temp) \n \n return len(sub_arrays)\n", + "title": "2261. K Divisible Elements Subarrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] ( inclusive ). You are further given an integer k . You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest) . If there are fewer than k reachable items within the price range, return all of them .", + "description_images": [], + "constraints": [ + "0 represents a wall that you cannot pass through.", + "1 represents an empty cell that you can freely move to and from.", + "All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\nOutput:[[0,1],[1,1],[2,1]]\nExplanation:You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\nOutput:[[2,1],[1,2]]\nExplanation:You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\nOutput:[[2,1],[2,0]]\nExplanation:You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/example3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 88.06%) | Memory: 75.50 MB (Top 67.16%)\n\nclass Solution {\n public List> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n int low = pricing[0];\n int high = pricing[1];\n int n = grid.length;\n int m = grid[0].length;\n Queue q = new LinkedList<>();\n boolean[][] visited = new boolean[n][m];\n ArrayList list = new ArrayList<>();\n int dis = 0;\n q.add(new Pair(start[0], start[1], grid[start[0]][start[1]], 0));\n visited[start[0]][start[1]] = true;\n\t\t// normal bfs starts here.\n while (!q.isEmpty()) {\n int size = q.size();\n dis++;\n while (size-- > 0) {\n Pair p = q.remove();\n int x = p.x;\n int y = p.y;\n int val = p.val;\n\t\t\t\t// if nearby cells in range add that element to queue and mark the cell as visited.\n if (isInRange(x + 1, y, n, m, grid, visited, low, high)) {\n q.add(new Pair(x + 1, y, grid[x + 1][y], dis));\n visited[x + 1][y] = true;\n }\n if (isInRange(x - 1, y, n, m, grid, visited, low, high)) {\n q.add(new Pair(x - 1, y, grid[x - 1][y], dis));\n visited[x - 1][y] = true;\n }\n if (isInRange(x, y + 1, n, m, grid, visited, low, high)) {\n q.add(new Pair(x, y + 1, grid[x][y + 1], dis));\n visited[x][y + 1] = true;\n }\n if (isInRange(x, y - 1, n, m, grid, visited, low, high)) {\n q.add(new Pair(x, y - 1, grid[x][y - 1], dis));\n visited[x][y - 1] = true;\n }\n\t\t\t\t// add every element of queue to list.\n list.add(new Pair(p.x, p.y, p.val, p.dis));\n }\n }\n ArrayList list2 = new ArrayList<>();\n for(Pair p: list) {\n\t\t // remove the values from list if they are not in pricing range and add that to list2.\n if (p.val != 1 && p.val >= low && p.val <= high) {\n list2.add(new Pair(p.x, p.y, p.val, p.dis));\n }\n }\n\t\t// Most important part. Sorting the list2 on basis of the conditions given in question. Higher rank cells must be added first(before) in the list.\n Collections.sort(list2, new Comparator() {\n @Override\n public int compare(Pair p1, Pair p2) {\n\t\t\t // first check on basis of distance (high value, then add it before the second pair).\n if (p1.dis > p2.dis) {\n return 1;\n } else if (p1.dis < p2.dis) {\n return -1;\n } else {\n\t\t\t\t // if distances are equal, then second check on basis of value (high value, then add it before the second pair).\n if (p1.val > p2.val) {\n return 1;\n } else if (p1.val < p2.val) {\n return -1;\n } else {\n\t\t\t\t\t // if distances and values are equal, then third check on basis of x-coordinate (high value, then add it before the second pair).\n if (p1.x > p2.x) {\n return 1;\n } else if (p1.x < p2.x) {\n return -1;\n } else {\n\t\t\t\t\t\t // if distances, values and x-coordinate are equal, then fourth check on basis of y-coordinate (high value, then add it before the second pair).).\n if (p1.y > p2.y) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n }\n }\n });\n List> ans = new ArrayList<>();\n\t\t// selecting only first k values from list2, and adding there x,y - coordinates in ans arraylist.\n for(Pair p: list2) {\n if (k == 0) {\n break;\n } \n k--;\n List temp = new ArrayList<>();\n temp.add(p.x);\n temp.add(p.y);\n ans.add(new ArrayList<>(temp));\n }\n return ans;\n }\n \n\t// check whether i, j is in range or not (ignore visited cells and cells with zero value)\n private boolean isInRange(int i, int j, int n, int m, int[][] grid, boolean[][] visited, int low, int high) {\n if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0 || visited[i][j]) {\n return false;\n }\n return true;\n }\n}\n\n// Pair class for x-coordinate, y-coordinate, grid value, distance from start point\nclass Pair {\n int x; int y; int val; int dis;\n \n public Pair(int x, int y, int val, int dis) {\n this.x = x;\n this.y = y;\n this.val = val;\n this.dis = dis;\n }\n}\n", + "title": "2146. K Highest Ranked Items Within a Price Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] ( inclusive ). You are further given an integer k . You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest) . If there are fewer than k reachable items within the price range, return all of them .", + "description_images": [], + "constraints": [ + "0 represents a wall that you cannot pass through.", + "1 represents an empty cell that you can freely move to and from.", + "All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\nOutput:[[0,1],[1,1],[2,1]]\nExplanation:You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\nOutput:[[2,1],[1,2]]\nExplanation:You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\nOutput:[[2,1],[2,0]]\nExplanation:You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/example3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3258 ms (Top 98.66%) | Memory: 66 MB (Top 18.12%)\nclass Solution:\n def highestRankedKItems(self, G, pricing, start, k):\n m, n = len(G), len(G[0])\n row, col = start\n node = (0, G[row][col], row, col)\n visited = set()\n visited.add((row, col))\n d = deque([node])\n ans = []\n\n while d:\n dist, cost, row, col = d.popleft()\n if pricing[0] <= cost <= pricing[1]:\n ans += [(dist, cost, row, col)]\n\n for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):\n if 0 <= x <= m-1 and 0 <= y <= n-1 and (x, y) not in visited and G[x][y] != 0:\n d.append((dist + 1, G[x][y], x, y))\n visited.add((x, y))\n\n ans = sorted(ans)\n\n return [[x, y] for _, _, x, y in ans[:k]]", + "title": "2146. K Highest Ranked Items Within a Price Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "For an integer array nums , an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j] . Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs . Since the answer can be huge, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 0\nOutput:1\nExplanation:Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 1\nOutput:2\nExplanation:The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 65.12%) | Memory: 47.8 MB (Top 52.38%)\nclass Solution {\n public int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[][] opt = new int[k + 1][n];\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0) {\n opt[i][j] = 1;\n } else if (j > 0) {\n opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD;\n if (i >= j + 1) {\n opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD;\n }\n }\n }\n }\n\n return opt[k][n - 1];\n }\n}", + "title": "629. K Inverse Pairs Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For an integer array nums , an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j] . Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs . Since the answer can be huge, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 0\nOutput:1\nExplanation:Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 1\nOutput:2\nExplanation:The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 185 ms (Top 92.81%) | Memory: 17.30 MB (Top 67.63%)\n\nclass Solution:\n # A very good description of the dp solution is at\n # https://leetcode.com/problems/k-inverse-pairs-array/solution/ \n # The code below uses two 1D arrays--dp and tmp--instead if a \n # 2D array. tmp replaces dp after each i-iteration.\n def kInversePairs(self, n: int, k: int) -> int:\n dp, mod = [1]+[0] * k, 1000000007\n \n for i in range(n):\n tmp, sm = [], 0\n for j in range(k + 1):\n sm+= dp[j]\n if j-i >= 1: sm-= dp[j-i-1]\n sm%= mod\n tmp.append(sm)\n dp = tmp\n #print(dp) # <-- uncomment this line to get a sense of dp from the print output\n\t\t\t # try n = 6, k = 4; your answer should be 49.\n return dp[k]", + "title": "629. K Inverse Pairs Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array nums of n integers, and an integer k . The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k ( inclusive ). If there are less than k elements before or after the index i , then the k-radius average is -1 . Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i . The average of x elements is the sum of the x elements divided by x , using integer division . The integer division truncates toward zero, which means losing its fractional part.", + "description_images": [], + "constraints": [ + "For example, the average of four elements 2 , 3 , 1 , and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75 , which truncates to 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput:[-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:- avg[0], avg[1], and avg[2] are -1 because there are less than k elementsbeforeeach index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Usinginteger division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elementsaftereach index.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/eg1.png" + }, + { + "text": "Example 2: Input:nums = [100000], k = 0\nOutput:[100000]\nExplanation:- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.", + "image": null + }, + { + "text": "Example 3: Input:nums = [8], k = 100000\nOutput:[-1]\nExplanation:- avg[0] is -1 because there are less than k elements before and after index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 10.87%) | Memory: 165.8 MB (Top 61.96%)\nclass Solution\n{\n public int[] getAverages(int[] nums, int k)\n {\n if(k == 0)\n return nums;\n\n int N = nums.length;\n long[] sum = new long[N];\n sum[0] = nums[0];\n\n for(int i = 1; i < N; i++)\n sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i]\n\n int[] ret = new int[N];\n Arrays.fill(ret,-1);\n\n for(int i = k; i < N-k; i++) // Beyond this range, there are less than k elements so -1\n {\n long temp = (sum[i+k]-sum[i-k]+nums[i-k])/(k*2+1);\n ret[i] = (int)temp;\n }\n return ret;\n }\n}", + "title": "2090. K Radius Subarray Averages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array nums of n integers, and an integer k . The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k ( inclusive ). If there are less than k elements before or after the index i , then the k-radius average is -1 . Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i . The average of x elements is the sum of the x elements divided by x , using integer division . The integer division truncates toward zero, which means losing its fractional part.", + "description_images": [], + "constraints": [ + "For example, the average of four elements 2 , 3 , 1 , and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75 , which truncates to 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput:[-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:- avg[0], avg[1], and avg[2] are -1 because there are less than k elementsbeforeeach index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Usinginteger division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elementsaftereach index.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/eg1.png" + }, + { + "text": "Example 2: Input:nums = [100000], k = 0\nOutput:[100000]\nExplanation:- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.", + "image": null + }, + { + "text": "Example 3: Input:nums = [8], k = 100000\nOutput:[-1]\nExplanation:- avg[0] is -1 because there are less than k elements before and after index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1318 ms (Top 77.1%) | Memory: 35.26 MB (Top 20.0%)\n\nclass Solution:\n def getAverages(self, nums: list[int], k: int) -> list[int]:\n\n n, diam = len(nums), 2*k+1\n if n < diam: return [-1]*n\n\n ans = [-1]*k\n\n arr = list(accumulate(nums, initial = 0))\n\n for i in range(n-diam+1):\n ans.append((arr[i+diam]-arr[i])//diam)\n\n return ans + [-1]*k", + "title": "2090. K Radius Subarray Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod = 1000000007;\n \n public int kadane(int[] a ){\n int curr = 0;\n int max = Integer.MIN_VALUE;\n for(int i: a )\n {\n curr+=i;\n if(curr<0 )\n curr =0;\n max = Math.max(max,curr );\n \n }\n \n return max%mod ;\n }\n public int kConcatenationMaxSum(int[] arr, int k) {\n \n int n = arr.length;\n if(k==1 ) \n return kadane(arr);\n int[] temp = new int[2*n]; \n for(int i=0;i=0 )\n return (int)( (kadane(temp)%mod)+ ((sum%mod) * (k-2)%mod) %mod);\n else\n return (kadane(temp)%mod );\n }\n}\n", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n \n dp = [0] * len(arr) # sum of the best subarry ends at i\n dp[0] = arr[0]\n total = arr[0] # total sum \n right = arr[0] # sum of the best subarray starts at 0\n \n p = 1 \n while p < len(arr):\n dp[p] = max(arr[p], dp[p-1] + arr[p])\n total += arr[p] \n right = max(right, total)\n \n p += 1\n \n isolated = max(dp + [0]) # max sum\n left = dp[-1] # sum of the best subarray ends at n-1\n \n if k == 1:\n \n return isolated % (10**9 + 7)\n \n return max(left + right + max(0,(k-2) * total), isolated) % (10**9 + 7)\n", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kConcatenationMaxSum(self, nums: List[int], k: int) -> int:\n def maxSum(k):\n res = cur = 0\n for _ in range(k):\n for num in nums:\n cur = max(cur + num, num)\n res = max(res, cur)\n \n return res\n \n return (max(0, k - 2) * max(0, sum(nums)) + maxSum(min(2, k))) % (10 ** 9 + 7)", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val .", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2\nOutput:2\nExplanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1\nOutput:4\nExplanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0\nOutput:1\nExplanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": " // O(n) Time Solution\n\n class Solution {\n \t\tpublic int findPairs(int[] nums, int k) {\n \t\t\tMap map = new HashMap();\n \t\t\tfor (int num : nums)\n \t\t\t\tmap.put(num, map.getOrDefault(num, 0) + 1);\n\n \t\t\tint result = 0;\n \t\t\tfor (int i : map.keySet())\n \t\t\t\tif (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)\n \t\t\t\t\tresult++;\n \t\t\treturn result;\n \t\t}\n \t}\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val .", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2\nOutput:2\nExplanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1\nOutput:4\nExplanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0\nOutput:1\nExplanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n nums.sort()\n dict1={}\n s=0\n res=[]\n for n in nums:\n if dict1.get(n,None) is not None:\n res.append(n)\n dict1[n+k]=n\n res=list(set(res))\n return len(res)\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val .", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2\nOutput:2\nExplanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1\nOutput:4\nExplanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0\nOutput:1\nExplanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n if k < 0:\n return 0\n \n # initialize hash table\n freq = {}\n for num in nums:\n freq[num] = freq.get(num, 0) + 1\n \n # iterate through array and find pairs\n count = 0\n for num in freq:\n if k == 0:\n if freq[num] > 1:\n count += 1\n else:\n if num + k in freq:\n count += 1\n \n # return count of unique pairs\n return count\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Strings s1 and s2 are k -similar (for some non-negative integer k ) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2 . Given two anagrams s1 and s2 , return the smallest k for which s1 and s2 are k -similar .", + "description_images": [], + "constraints": [ + "1 <= s1.length <= 20", + "s2.length == s1.length", + "s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'} .", + "s2 is an anagram of s1 ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"ba\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abc\", s2 = \"bca\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kSimilarity(String s1, String s2) {\n HashSet vis = new HashSet<>();\n \n ArrayDeque queue = new ArrayDeque<>();\n int level = 0;\n queue.add(s1);\n \n while(queue.size() > 0){\n int size = queue.size();\n for(int i=0;i getNeighbors(String rem,String s2){\n ArrayList res = new ArrayList<>();\n \n int idx = -1;\n for(int i=0;i int:\n n = len(s1)\n \n def helper(i, curr, dp):\n if curr == s2:\n return 0\n \n if curr not in dp[i]:\n if curr[i] == s2[i]:\n dp[i][curr] = helper(i+1, curr, dp)\n else:\n temp = sys.maxsize\n for j in range(i+1, n):\n if curr[j] == s2[i]:\n temp = min(temp, 1+helper(i+1, curr[:i]+curr[j]+curr[i+1:j]+curr[i]+curr[j+1:], dp))\n\n dp[i][curr] = temp\n return dp[i][curr]\n \n dp = [{} for _ in range(n)]\n return helper(0, s1, dp)\n", + "title": "854. K-Similar Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers n and k , return the k th lexicographically smallest integer in the range [1, n] .", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13, k = 2\nOutput:10\nExplanation:The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n \n def prefix(op,n):\n if op==n: return 1\n if int(op)>int(n): return 0\n for i in range(len(op)):\n if int(op[i])>int(n[i]): \n rem = len(n)-1-len(op)\n if not rem: return 1\n return 1+int(10*((1-10**rem)/-9))\n elif int(op[i])1:\n pref = prefix(str(ans),str(n)) \n if pref >= k:\n ans*=10; k-=1\n else: \n ans += 1; k-= pref\n \n return ans\n \n \n", + "title": "440. K-th Smallest in Lexicographical Order", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k . For every i and j where 0 <= i < j < arr.length , we consider the fraction arr[i] / arr[j] . Return the k th smallest fraction considered . Return your answer as an array of integers of size 2 , where answer[0] == arr[i] and answer[1] == arr[j] .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 1000", + "1 <= arr[i] <= 3 * 10^4", + "arr[0] == 1", + "arr[i] is a prime number for i > 0 .", + "All the numbers of arr are unique and sorted in strictly increasing order.", + "1 <= k <= arr.length * (arr.length - 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,5], k = 3\nOutput:[2,5]\nExplanation:The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,7], k = 1\nOutput:[1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n vector kthSmallestPrimeFraction(vector& arr, int k) {\n priority_queue>, vector>>, greater>>> myHeap;\n for (int i=0; i mid + 1) {\n return invert(kthGrammar(n - 1, k - mid));\n } else {\n return 1;\n }\n }\n static int invert(int x) {\n if (x == 0) {\n return 1;\n }\n return 0;\n }\n}\n", + "title": "779. K-th Symbol in Grammar", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We build a table of n rows ( 1-indexed ). We start by writing 0 in the 1 st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01 , and each occurrence of 1 with 10 . Given two integer n and k , return the k th ( 1-indexed ) symbol in the n th row of a table of n rows.", + "description_images": [], + "constraints": [ + "For example, for n = 3 , the 1 st row is 0 , the 2 nd row is 01 , and the 3 rd row is 0110 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 1\nOutput:0\nExplanation:row 1:0", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 1\nOutput:0\nExplanation:row 1: 0\nrow 2:01", + "image": null + }, + { + "text": "Example 3: Input:n = 2, k = 2\nOutput:1\nExplanation:row 1: 0\nrow 2: 01", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solve(self,n,k):\n if n==1 and k==1:\n return 0 \n mid = pow(2,n-1)//2 \n if k<=mid:\n return self.solve(n-1,k) \n \n return not self.solve(n-1,k-mid)\n \n \n def kthGrammar(self,n,k):\n if self.solve(n,k):\n return 1 \n else:\n return 0 \n \n \n \n \n \n \n \n \n \n \n", + "title": "779. K-th Symbol in Grammar", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums . You are also given an integer original which is the first number that needs to be searched for in nums . You then do the following steps: Return the final value of original .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i], original <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,6,1,12], original = 3\nOutput:24\nExplanation:- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9], original = 4\nOutput:4\nExplanation:- 4 is not found in nums. Thus, 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int findFinalValue(int[] nums, int original)\n {\n HashSet set = new HashSet<>();\n for(int i : nums)\n if(i >= original)\n set.add(i);\n while(true)\n if(set.contains(original))\n original *= 2;\n else\n break;\n return original;\n }\n}\n", + "title": "2154. Keep Multiplying Found Values by Two", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of integers nums . You are also given an integer original which is the first number that needs to be searched for in nums . You then do the following steps: Return the final value of original .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i], original <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,6,1,12], original = 3\nOutput:24\nExplanation:- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9], original = 4\nOutput:4\nExplanation:- 4 is not found in nums. Thus, 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findFinalValue(self, nums: List[int], original: int) -> int:\n while original in nums:\n original *= 2\n return original", + "title": "2154. Keep Multiplying Found Values by Two", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words , return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below . In the American keyboard :", + "description_images": [], + "constraints": [ + "the first row consists of the characters \"qwertyuiop\" ,", + "the second row consists of the characters \"asdfghjkl\" , and", + "the third row consists of the characters \"zxcvbnm\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"Hello\",\"Alaska\",\"Dad\",\"Peace\"]\nOutput:[\"Alaska\",\"Dad\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"omk\"]\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:words = [\"adsdf\",\"sfd\"]\nOutput:[\"adsdf\",\"sfd\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.50 MB (Top 13.89%)\n\nclass Solution {\n public String[] findWords(String[] words) {\n String s1 = \"qwertyuiopQWERTYUIOP\";\n String s2 = \"asdfghjklASDFGHJKL\";\n String s3 = \"zxcvbnmZXCVBNM\"; \n ArrayList list = new ArrayList<>();\n for(int i=0;i List[str]:\n #\n set1 = {'q','w','e','r','t','y','u','i','o','p'}\n set2 = {'a','s','d','f','g','h','j','k','l'}\n set3 = {'z','x','c','v','b','n','m'}\n \n res = []\n for i in words:\n wordset = set(i.lower())\n if (wordset&set1 == wordset) or (wordset&set2 == wordset) or (wordset&set3 == wordset):\n res.append(i)\n return res\n", + "title": "500. Keyboard Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise .", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]\nOutput:true\nExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]\nOutput:false\nExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canVisitAllRooms(List> rooms) {\n \t\t boolean[] visited = new boolean[rooms.size()];\n \t\t visited[0]= true;\n \t\t for(int a:rooms.get(0))\n \t\t {\n \t\t\t if(!visited[a])\n \t\t\t {\n \t\t\t\t bfs(a, visited, rooms.size()-1, rooms);\n \t\t\t\t \n \t\t\t }\n \t\t }\n \t\t //System.out.println(\"arr -->>\"+Arrays.toString(visited));\n \t\tfor(boolean a:visited)\n \t\t{\n \t\t\tif(!a)\n \t\t\t\treturn false;\n \t\t}\n \t return true;\n \t \n \t }\n \t public void bfs(int key, boolean[] vivsted, int target,List> rooms)\n \t {\n \t\t\n \t\t\n \t\t vivsted[key] = true;\n \t\t for(int a:rooms.get(key))\n \t\t {\n \t\t\t if(!vivsted[a])\n \t\t\t {\n \t\t\t\t bfs(a, vivsted, target, rooms);\n \t\t\t }\n \t\t }\n \t\t \n \t\t \n \t\t\n \t }\n \n}", + "title": "841. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise .", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]\nOutput:true\nExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]\nOutput:false\nExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n # Create a set of for rooms visited\n visited_rooms = set()\n \n # Create a queue to do a breadth first search visiting rooms\n # Append the first room, 0, to the queue to begin the search\n queue = collections.deque()\n queue.append(0)\n \n # Perform the breadth first search with the queue\n while queue:\n for _ in range(0, len(queue)):\n # Search the room\n room_number = queue.popleft()\n \n # If we haven't visited the room, get the keys from the room\n if room_number not in visited_rooms:\n \n # Collect the keys from the room\n found_keys = rooms[room_number]\n \n # Add the keys to the queue so they can be tested\n for key in found_keys:\n queue.append(key)\n \n # Add the current room to the visited set\n visited_rooms.add(room_number)\n \n # If we visited all of the rooms, then the number of visited rooms should be\n # equal to the number of total rooms\n if len(visited_rooms) == len(rooms):\n return True\n \n return False\n", + "title": "841. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies.", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3\nOutput:[true,true,true,false,true]\nExplanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1\nOutput:[true,false,false,false,false]\nExplanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10\nOutput:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.09%) | Memory: 42.9 MB (Top 55.32%)\nclass Solution {\n public List kidsWithCandies(int[] candies, int extraCandies) {\n Listresult = new ArrayList<>(candies.length); // better practice since the length is known\n int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1\n for (int i = 1; i= theHighest) or (candies[i] >= theHighest-extraCandies)\n int mathLogic = theHighest - extraCandies;\n for (int i = 0; i=10 or 6 >=10-5\n if (candies[i] >= mathLogic) {\n result.add(true);\n } else {\n result.add(false);\n }\n }\n return result;\n }\n}", + "title": "1431. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies.", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3\nOutput:[true,true,true,false,true]\nExplanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1\nOutput:[true,false,false,false,false]\nExplanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10\nOutput:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kidsWithCandies(self, candy, extra):\n #create an array(res) with all values as True and it's lenght is same as candies\n res = [True]*len(candy)\n #iterate over the elements in the array candy\n for i in range(len(candy)):\n #if the no. of canides at curr position + extra is greater than or equal to the maximum of candies then continue \n if (candy[i] + extra) >= max(candy):\n continue\n #if not \n else:\n #change the value of that position in res as false\n res[i] = False\n #return the res list\n return res ", + "title": "1431. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The chess knight has a unique movement , it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L ). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n , return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n . All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:10\nExplanation:We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:20\nExplanation:All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]", + "image": null + }, + { + "text": "Example 3: Input:n = 3131\nOutput:136006598\nExplanation:Please take care of the mod.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int knightDialer(int n) {\n var dp = new long[10];\n var tmp = new long[10];\n Arrays.fill(dp, 1);\n for (int i = 1; i < n; i++) {\n tmp[1] = dp[6]+dp[8];\n tmp[2] = dp[7]+dp[9];\n tmp[3] = dp[4]+dp[8];\n tmp[4] = dp[0]+dp[3]+dp[9];\n tmp[5] = 0;\n tmp[6] = dp[0]+dp[1]+dp[7];\n tmp[7] = dp[2]+dp[6];\n tmp[8] = dp[1]+dp[3];\n tmp[9] = dp[2]+dp[4];\n tmp[0] = dp[4]+dp[6];\n for (int j = 0; j < 10; j++) tmp[j] = tmp[j] % 1000000007;\n var arr = dp;\n dp = tmp;\n tmp = arr;\n }\n long res = 0;\n for (int i = 0; i < 10; i++) {\n res = (res+dp[i]) % 1000000007;\n }\n return (int)res;\n }\n}\n", + "title": "935. Knight Dialer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The chess knight has a unique movement , it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L ). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n , return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n . All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:10\nExplanation:We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:20\nExplanation:All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]", + "image": null + }, + { + "text": "Example 3: Input:n = 3131\nOutput:136006598\nExplanation:Please take care of the mod.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 226 ms (Top 89.51%) | Memory: 16.80 MB (Top 56.81%)\n\nclass Solution:\n MOD = 10**9 + 7\n\n def knightDialer(self, n: int) -> int:\n # Initialize an array to store the possible positions of the knight on the phone pad\n cur_pos = [1] * 10\n\n # Loop through the number of jumps required\n for jump in range(2, n + 1):\n # Create a new list to store the updated positions after each jump\n new_pos = [0] * 10\n\n # Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % self.MOD\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % self.MOD\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % self.MOD\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % self.MOD\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % self.MOD\n new_pos[5] = 0 # Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % self.MOD\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % self.MOD\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % self.MOD\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % self.MOD\n\n # Update the current positions list for the next iteration\n cur_pos = new_pos\n\n # Calculate the total count of distinct phone numbers\n total_count = sum(cur_pos) % self.MOD\n\n return total_count\n", + "title": "935. Knight Dialer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed , so the top-left cell is (0, 0) , and the bottom-right cell is (n - 1, n - 1) . A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving .", + "description_images": [], + "constraints": [ + "1 <= n <= 25", + "0 <= k <= 100", + "0 <= row, column <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2, row = 0, column = 0\nOutput:0.06250\nExplanation:There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 0, row = 0, column = 0\nOutput:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double knightProbability(int n, int k, int row, int column) {\n double [][]curr=new double[n][n];\n double [][]next=new double[n][n];\n \n curr[row][column]=1;\n \n int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};\n for(int p=1;p<=k;p++){\n for(int i=0;i=n || nj>=n){\n continue;\n }\n \n next[ni][nj]+=curr[i][j]/8.0;\n }\n }\n }\n }\n \n curr=next;\n next=new double[n][n];\n }\n \n double sum=0.0;\n \n for(int i=0;i float:\n \n x_dir = [2, 1, -1, -2, -2, -1, 1, 2]\n y_dir = [1, 2, 2, 1, -1, -2, -2, -1]\n \n cache = {}\n \n def kMoves(i, j, moves):\n if i >= n or j >= n or i < 0 or j < 0:\n return 0\n \n if moves == k:\n return 1\n \n if (i, j, moves) in cache:\n return cache[(i, j, moves)]\n \n totMoves = 0\n for ind in range(8):\n totMoves += kMoves(i+x_dir[ind], j+y_dir[ind], moves+1)*(1/8)\n \n cache[(i, j, moves)] = totMoves\n return totMoves\n \n return kMoves(row, column, 0)\n", + "title": "688. Knight Probability in Chessboard", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5\nOutput:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minEatingSpeed(int[] piles, int h) {\n int max=0;\n int ans=0;\n for(int i=0;ipiles[i]/mid)\n time+=num+1;\n else\n time+=num;\n }\n if(time<=h)\n {\n ans=mid;\n right=mid-1;\n }\n else\n left=mid+1;\n }\n return ans;\n }\n}\n", + "title": "875. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5\nOutput:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 308 ms (Top 92.4%) | Memory: 17.82 MB (Top 76.3%)\n\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n def check(x):\n return sum(ceil(ele/x) for ele in piles) <= h\n\n l = 1\n r = max(piles)\n while l < r:\n mid = (l+r) >> 1\n if not check(mid):\n l=mid+1\n else:\n r=mid\n return l", + "title": "875. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of i th node. The root of the tree is node 0 . Find the k th ancestor of a given node. The k th ancestor of a tree node is the k th node in the path from that node to the root node. Implement the TreeAncestor class:", + "description_images": [], + "constraints": [ + "TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.", + "int getKthAncestor(int node, int k) return the k th ancestor of the given node node . If there is no such ancestor, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]Output[null, 1, 0, -1]ExplanationTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor", + "image": "https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 96 ms (Top 79.04%) | Memory: 112.4 MB (Top 41.18%)\nclass TreeAncestor {\n int n;\n int[] parent;\n List[] nodeInPath;\n int[] nodeIdxInPath;\n\n public TreeAncestor(int n, int[] parent) {\n this.n = n;\n this.parent = parent;\n nodeInPath = new ArrayList[n];\n nodeIdxInPath = new int[n];\n fill();\n }\n\n private void fill() {\n boolean[] inner = new boolean[n];\n for (int i = 1; i < n; i++) {\n inner[parent[i]] = true;\n }\n\n for (int i = 1; i < n; i++) {\n if (inner[i] || nodeInPath[i] != null) {\n continue;\n }\n List path = new ArrayList<>();\n int k = i;\n while (k != -1) {\n path.add(k);\n k = parent[k];\n }\n int m = path.size();\n for (int j = 0; j < m; j++) {\n int node = path.get(j);\n if (nodeInPath[node] != null) break;\n nodeInPath[node] = path;\n nodeIdxInPath[node] = j;\n }\n }\n }\n\n public int getKthAncestor(int node, int k) {\n List path = nodeInPath[node];\n int idx = nodeIdxInPath[node] + k;\n return idx >= path.size() ? -1 : path.get(idx);\n }\n}", + "title": "1483. Kth Ancestor of a Tree Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of i th node. The root of the tree is node 0 . Find the k th ancestor of a given node. The k th ancestor of a tree node is the k th node in the path from that node to the root node. Implement the TreeAncestor class:", + "description_images": [], + "constraints": [ + "TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.", + "int getKthAncestor(int node, int k) return the k th ancestor of the given node node . If there is no such ancestor, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]Output[null, 1, 0, -1]ExplanationTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor", + "image": "https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2359 ms (Top 39.76%) | Memory: 44.3 MB (Top 93.27%)\nfrom math import ceil, log2\nfrom typing import List\n\nNO_PARENT = -1\n\nclass TreeAncestor:\n def __init__(self, n: int, parent: List[int]):\n self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]\n self.__initialize(parent)\n\n def __initialize(self, parent: List[int]):\n self.parent[0], prev = parent, parent\n\n for jump_pow in range(1, len(self.parent)):\n cur = self.parent[jump_pow]\n\n for i, p in enumerate(prev):\n if p != NO_PARENT:\n cur[i] = prev[p]\n\n prev = cur\n\n def getKthAncestor(self, node: int, k: int) -> int:\n jump_pow = self.jump_pow\n\n while k > 0 and node != NO_PARENT:\n jumps = 1 << jump_pow\n\n if k >= jumps:\n node = self.parent[jump_pow][node]\n k -= jumps\n else:\n jump_pow -= 1\n\n return node\n\n @property\n def jump_pow(self) -> int:\n return len(self.parent) - 1", + "title": "1483. Kth Ancestor of a Tree Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr , and an integer k , return the k th distinct string present in arr . If there are fewer than k distinct strings, return an empty string \"\" . Note that the strings are considered in the order in which they appear in the array.", + "description_images": [], + "constraints": [ + "1 <= k <= arr.length <= 1000", + "1 <= arr[i].length <= 5", + "arr[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\nOutput:\"a\"\nExplanation:The only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1stdistinct string.\n\"a\" appears 2nd, so it is the 2nddistinct string.\nSince k == 2, \"a\" is returned.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"aaa\",\"aa\",\"a\"], k = 1\nOutput:\"aaa\"\nExplanation:All strings in arr are distinct, so the 1ststring \"aaa\" is returned.", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"a\",\"b\",\"a\"], k = 3\nOutput:\"\"\nExplanation:The only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 99.0%) | Memory: 43.48 MB (Top 20.1%)\n\nclass Solution {\n public String kthDistinct(String[] arr, int k) {\n Map map=new HashMap<>();\n \n for(String s:arr){\n \n if(map.containsKey(s)) map.put(s,map.get(s)+1);\n else map.put(s,1);\n }\n\t\tint i=0;\n for(String s:arr){\n if(map.get(s)==1 && ++i==k){\n \n return s;\n } \n \n }\n return \"\";\n \n }\n}", + "title": "2053. Kth Distinct String in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr , and an integer k , return the k th distinct string present in arr . If there are fewer than k distinct strings, return an empty string \"\" . Note that the strings are considered in the order in which they appear in the array.", + "description_images": [], + "constraints": [ + "1 <= k <= arr.length <= 1000", + "1 <= arr[i].length <= 5", + "arr[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\nOutput:\"a\"\nExplanation:The only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1stdistinct string.\n\"a\" appears 2nd, so it is the 2nddistinct string.\nSince k == 2, \"a\" is returned.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"aaa\",\"aa\",\"a\"], k = 1\nOutput:\"aaa\"\nExplanation:All strings in arr are distinct, so the 1ststring \"aaa\" is returned.", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"a\",\"b\",\"a\"], k = 3\nOutput:\"\"\nExplanation:The only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n hash_map = {}\n for string in arr:\n hash_map[string] = hash_map.get(string, 0) + 1\n for string in arr:\n if hash_map[string] == 1:\n k -= 1\n if k == 0:\n return string\n return \"\"\n", + "title": "2053. Kth Distinct String in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a class to find the k th largest element in a stream. Note that it is the k th largest element in the sorted order, not the k th distinct element. Implement KthLargest class:", + "description_images": [], + "constraints": [ + "KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums .", + "int add(int val) Appends the integer val to the stream and returns the element representing the k th largest element in the stream." + ], + "examples": [ + { + "text": "Example 1: Input[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]Output[null, 4, 5, 5, 8, 8]ExplanationKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3); // return 4\nkthLargest.add(5); // return 5\nkthLargest.add(10); // return 5\nkthLargest.add(9); // return 8\nkthLargest.add(4); // return 8", + "image": null + } + ], + "follow_up": null, + "solution": "class KthLargest {\n PriorityQueue queue=new PriorityQueue();\n int k=0;\n public KthLargest(int k, int[] nums) {\n this.k=k;\n for(int i:nums)\n add(i);\n }\n \n public int add(int val) {\n if(k>queue.size())\n queue.add(val);\n else\n if(val>queue.peek())\n {\n queue.poll();\n queue.add(val);\n }\n return queue.peek();\n }\n}\n", + "title": "703. Kth Largest Element in a Stream", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a class to find the k th largest element in a stream. Note that it is the k th largest element in the sorted order, not the k th distinct element. Implement KthLargest class:", + "description_images": [], + "constraints": [ + "KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums .", + "int add(int val) Appends the integer val to the stream and returns the element representing the k th largest element in the stream." + ], + "examples": [ + { + "text": "Example 1: Input[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]Output[null, 4, 5, 5, 8, 8]ExplanationKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3); // return 4\nkthLargest.add(5); // return 5\nkthLargest.add(10); // return 5\nkthLargest.add(9); // return 8\nkthLargest.add(4); // return 8", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 143 ms (Top 61.21%) | Memory: 18.3 MB (Top 46.75%)\nclass KthLargest:\n def __init__(self, k: int, nums: List[int]):\n self.k = k\n self.hp = []\n for x in nums:\n self.add(x)\n\n return None\n\n def add(self, val: int) -> int:\n heapq.heappush(self.hp, (val))\n if len(self.hp) > self.k:\n heapq.heappop(self.hp)\n\n return self.get_kth_largest()\n\n def get_kth_largest(self):\n return self.hp[0]", + "title": "703. Kth Largest Element in a Stream", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. You must solve it in O(n) time complexity.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,5,6,4], k = 2\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,3,1,2,4,5,5,6], k = 4\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n nums.sort(reverse = True)\n return nums[k-1]", + "title": "215. Kth Largest Element in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of positive integers sorted in a strictly increasing order , and an integer k . Return the k th positive integer that is missing from this array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000", + "1 <= k <= 1000", + "arr[i] < arr[j] for 1 <= i < j <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,3,4,7,11], k = 5\nOutput:9\nExplanation:The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5thmissing positive integer is 9.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4], k = 2\nOutput:6\nExplanation:The missing positive integers are [5,6,7,...]. The 2ndmissing positive integer is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthPositive(int[] arr, int k) {\n if(arr[0] > k) {\n return k;\n }\n \n for(int i=0; i int:\n arr = set(arr)\n i = 0\n missed = 0\n while missed != k:\n i += 1\n if i not in arr:\n missed += 1\n return i", + "title": "1539. Kth Missing Positive Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.10 MB (Top 76.35%)\n\nclass Solution {\n private int count = 0;\n private int result = 0;\n\n public int kthSmallest(TreeNode root, int k) {\n inorderTraversal(root, k);\n return result;\n }\n\n private void inorderTraversal(TreeNode node, int k) {\n if (node == null || count >= k) {\n return;\n }\n\n inorderTraversal(node.left, k);\n\n count++;\n if (count == k) {\n result = node.val;\n return;\n }\n\n inorderTraversal(node.right, k);\n }\n}\n", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 42.71%) | Memory: 18.1 MB (Top 15.27%)\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n n=0\n stack=[] # to store the elements\n cur=root # pointer to iterate\n while cur or stack:\n while cur: # used to find the left most element\n stack.append(cur)\n cur=cur.left\n cur=stack.pop() # pop the most recent element which will be the least value at that moment\n n+=1\n if n==k:\n return cur.val\n cur=cur.right", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the k th smallest element in the matrix . Note that it is the k th smallest element in the sorted order , not the k th distinct element. You must find a solution with a memory complexity better than O(n 2 ) .", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 300", + "-10^9 <= matrix[i][j] <= 10^9", + "All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order .", + "1 <= k <= n 2" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\nOutput:13\nExplanation:The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8thsmallest number is 13", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[-5]], k = 1\nOutput:-5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Using PriorityQueue\n *\n * Time Complexity:\n * O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.\n * If we were adding all elements in one go, then the complexity would be O(min(N,K))\n * Refer: https://stackoverflow.com/a/34697891\n * O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.\n * Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))\n *\n * Space Complexity: O(min(N, K))\n *\n * N = Length of one side of the matrix. K = input value k.\n */\nclass Solution {\n public int kthSmallest(int[][] matrix, int k) {\n if (matrix == null || k <= 0) {\n throw new IllegalArgumentException(\"Input is invalid\");\n }\n\n int n = matrix.length;\n if (k > n * n) {\n throw new NoSuchElementException(\"k is greater than number of elements in matrix\");\n }\n if (k == 1) {\n return matrix[0][0];\n }\n if (k == n * n) {\n return matrix[n - 1][n - 1];\n }\n\n PriorityQueue queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));\n\n for (int i = 0; i < Math.min(n, k); i++) {\n queue.offer(new int[] { i, 0 });\n }\n while (k > 1) {\n int[] cur = queue.poll();\n if (cur[1] < n - 1) {\n cur[1]++;\n queue.offer(cur);\n }\n k--;\n }\n\n return matrix[queue.peek()[0]][queue.peek()[1]];\n }\n}\n", + "title": "378. Kth Smallest Element in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the k th smallest element in the matrix . Note that it is the k th smallest element in the sorted order , not the k th distinct element. You must find a solution with a memory complexity better than O(n 2 ) .", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 300", + "-10^9 <= matrix[i][j] <= 10^9", + "All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order .", + "1 <= k <= n 2" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\nOutput:13\nExplanation:The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8thsmallest number is 13", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[-5]], k = 1\nOutput:-5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 281 ms (Top 5.06%) | Memory: 22.00 MB (Top 9.58%)\n\nclass Solution:\n def kthSmallest(self, matrix, k):\n n, beg, end = len(matrix), matrix[0][0], matrix[-1][-1]\n \n def check(m):\n i, j, cnt = 0, n-1, 0\n for i in range(n):\n while j >= 0 and matrix[i][j] > m: j -= 1\n cnt += (j + 1)\n return cnt\n \n while beg < end:\n mid = (beg + end)//2\n if check(mid) < k:\n beg = mid + 1\n else:\n end = mid\n \n return beg\n", + "title": "378. Kth Smallest Element in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Bob is standing at cell (0, 0) , and he wants to reach destination : (row, column) . He can only travel right and down . You are going to help Bob by providing instructions for him to reach destination . The instructions are represented as a string, where each character is either: Multiple instructions will lead Bob to destination . For example, if destination is (2, 3) , both \"HHHVV\" and \"HVHVH\" are valid instructions . However, Bob is very picky. Bob has a lucky number k , and he wants the k th lexicographically smallest instructions that will lead him to destination . k is 1-indexed . Given an integer array destination and an integer k , return the k th lexicographically smallest instructions that will take Bob to destination .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/12/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/12/ex2.png", + "https://assets.leetcode.com/uploads/2020/10/12/ex3.png" + ], + "constraints": [ + "'H' , meaning move horizontally (go right ), or", + "'V' , meaning move vertically (go down )." + ], + "examples": [ + { + "text": "Example 1: Input:destination = [2,3], k = 1\nOutput:\"HHHVV\"\nExplanation:All the instructions that reach (2, 3) in lexicographic order are as follows:\n[\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].", + "image": null + }, + { + "text": "Example 2: Input:destination = [2,3], k = 2\nOutput:\"HHVHV\"", + "image": null + }, + { + "text": "Example 3: Input:destination = [2,3], k = 3\nOutput:\"HHVVH\"", + "image": null + } + ], + "follow_up": null, + "solution": "from math import comb\nclass Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n i,j = destination\n \n @lru_cache(None)\n def helper(i,j,k):\n if k == 1:\n return \"H\"*j+\"V\"*i\n else:\n horizontal = comb(i+j-1,j-1)\n if k <= horizontal:\n return \"H\" + helper(i,j-1,k)\n else:\n return \"V\" + helper(i-1,j,k-horizontal)\n \n return helper(i,j,k)\n", + "title": "1643. Kth Smallest Instructions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Nearly everyone has used the Multiplication Table . The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j ( 1-indexed ). Given three integers m , n , and k , return the k th smallest element in the m x n multiplication table .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 3 * 10^4", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, k = 5\nOutput:3\nExplanation:The 5thsmallest number is 3.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg" + }, + { + "text": "Example 2: Input:m = 2, n = 3, k = 6\nOutput:6\nExplanation:The 6thsmallest number is 6.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthNumber(int m, int n, int k) {\n int lo = 1;\n int hi = m * n;\n \n while(lo < hi){\n int mid = lo + (hi - lo) / 2;\n \n if(count(mid, m, n) < k){\n lo = mid + 1;\n } else if(count(mid, m, n) >= k){\n hi = mid;\n }\n }\n return lo;\n }\n private int count(int mid, int m, int n){\n int ans = 0;\n for(int i = 1; i <= m; i++){\n int res = Math.min(mid / i, n);\n ans += res;\n }\n return ans;\n }\n}\n", + "title": "668. Kth Smallest Number in Multiplication Table", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Nearly everyone has used the Multiplication Table . The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j ( 1-indexed ). Given three integers m , n , and k , return the k th smallest element in the m x n multiplication table .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 3 * 10^4", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, k = 5\nOutput:3\nExplanation:The 5thsmallest number is 3.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg" + }, + { + "text": "Example 2: Input:m = 2, n = 3, k = 6\nOutput:6\nExplanation:The 6thsmallest number is 6.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 593 ms (Top 63.06%) | Memory: 17.30 MB (Top 29.73%)\n\nclass Solution:\n def findKthNumber(self, m, n, k):\n def count(x):\n return sum(min(x//i, n) for i in range(1,m+1))\n\t\t\t\n L, R, mid, ans = 0, m*n, 0, 0\n while L <= R:\n mid = (L + R) >> 1\n if count(mid) < k:\n L = mid + 1\n else:\n R, ans = mid - 1, mid\n return ans\n", + "title": "668. Kth Smallest Number in Multiplication Table", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 5 * 10^4", + "-10^5 <= nums1[i], nums2[j] <= 10^5", + "1 <= k <= nums1.length * nums2.length", + "nums1 and nums2 are sorted." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,5], nums2 = [3,4], k = 2\nOutput:8\nExplanation:The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2ndsmallest product is 8.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\nOutput:0\nExplanation:The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6thsmallest product is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\nOutput:-6\nExplanation:The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rdsmallest product is -6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 740 ms (Top 67.46%) | Memory: 89.4 MB (Top 63.10%)\nclass Solution {\n static long INF = (long) 1e10;\n public long kthSmallestProduct(int[] nums1, int[] nums2, long k) {\n int m = nums1.length, n = nums2.length;\n long lo = -INF - 1, hi = INF + 1;\n while (lo < hi) {\n long mid = lo + ((hi - lo) >> 1), cnt = 0;\n for (int i : nums1) {\n if (0 <= i) {\n int l = 0, r = n - 1, p = 0;\n while (l <= r) {\n int c = l + ((r - l) >> 1);\n long mul = i * (long) nums2[c];\n if (mul <= mid) {\n p = c + 1;\n l = c + 1;\n } else r = c - 1;\n }\n cnt += p;\n } else {\n int l = 0, r = n - 1, p = 0;\n while (l <= r) {\n int c = l + ((r - l) >> 1);\n long mul = i * (long) nums2[c];\n if (mul <= mid) {\n p = n - c;\n r = c - 1;\n } else l = c + 1;\n }\n cnt += p;\n }\n }\n if (cnt >= k) {\n hi = mid;\n } else lo = mid + 1L;\n }\n return lo;\n }\n}", + "title": "2040. Kth Smallest Product of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 5 * 10^4", + "-10^5 <= nums1[i], nums2[j] <= 10^5", + "1 <= k <= nums1.length * nums2.length", + "nums1 and nums2 are sorted." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,5], nums2 = [3,4], k = 2\nOutput:8\nExplanation:The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2ndsmallest product is 8.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\nOutput:0\nExplanation:The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6thsmallest product is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\nOutput:-6\nExplanation:The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rdsmallest product is -6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n result = []\n for i in range(len(nums1)):\n for j in range(len(nums2)):\n temp = nums1[i]*nums2[j]\n result.append(temp)\n result.sort()\n return result[k-1]\n", + "title": "2040. Kth Smallest Product of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D grid of 0 s and 1 s, return the number of elements in the largest square subgrid that has all 1 s on its border , or 0 if such a subgrid doesn't exist in the grid .", + "description_images": [], + "constraints": [ + "1 <= grid.length <= 100", + "1 <= grid[0].length <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1,0,0]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largest1BorderedSquare(int[][] grid) {\n int m=grid.length;\n int n=grid[0].length;\n\t\t// rows[r][c] is the length of the line ended at [r,c] on row r\n int[][] rows=new int[m][n]; \n\t\t// the length of the line ended at [r,c] on colume c\n int[][] cols=new int[m][n];\n int res=0;\n for(int r=0;r=rows[r][c]||res>=cols[r][c]){\n continue;\n }\n res=Math.max(res,getD(rows,cols,r,c));\n }\n }\n }\n return res*res;\n }\n \n\t// get the dimension of the largest square which bottom-right point is [row,col]\n private int getD(int[][] rows,int[][] cols,int row,int col){\n int len=Math.min(rows[row][col],cols[row][col]);\n for(int i=len-1;i>=0;i--){\n if(rows[row-i][col]>i && cols[row][col-i]>i){\n return i+1;\n }\n }\n return 1;\n }\n}\n", + "title": "1139. Largest 1-Bordered Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid of 0 s and 1 s, return the number of elements in the largest square subgrid that has all 1 s on its border , or 0 if such a subgrid doesn't exist in the grid .", + "description_images": [], + "constraints": [ + "1 <= grid.length <= 100", + "1 <= grid[0].length <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1,0,0]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1382 ms (Top 13.45%) | Memory: 15.1 MB (Top 9.94%)\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)]\n for i in range(m):\n for j in range(n):\n if i > 0:\n if grid[i][j] == 1:\n dp[i][j][1] = dp[i - 1][j][1] + 1\n if j > 0:\n if grid[i][j] == 1:\n dp[i][j][0] = dp[i][j - 1][0] + 1\n for i in range(m - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n if i < m - 1:\n if grid[i][j] == 1:\n dp[i][j][2] = dp[i + 1][j][2] + 1\n if j < n - 1:\n if grid[i][j] == 1:\n dp[i][j][3] = dp[i][j + 1][3] + 1\n mside = min(m, n)\n for l in range(mside - 1, -1, -1):\n for i in range(m - l):\n for j in range(n - l):\n if min(dp[i][j][2], dp[i][j][3], dp[i + l][j + l][0], dp[i + l][j + l][1]) >= l + 1:\n return (l + 1) * (l + 1)\n return 0", + "title": "1139. Largest 1-Bordered Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num representing a large integer. An integer is good if it meets the following conditions: Return the maximum good integer as a string or an empty string \"\" if no such integer exists . Note:", + "description_images": [], + "constraints": [ + "It is a substring of num with length 3 .", + "It consists of only one unique digit." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"6777133339\"\nOutput:\"777\"\nExplanation:There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".", + "image": null + }, + { + "text": "Example 2: Input:num = \"2300019\"\nOutput:\"000\"\nExplanation:\"000\" is the only good integer.", + "image": null + }, + { + "text": "Example 3: Input:num = \"42352338\"\nOutput:\"\"\nExplanation:No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public String largestGoodInteger(String num)\n {\n String ans = \"\";\n for(int i = 2; i < num.length(); i++)\n if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2))\n if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is larger\n ans = num.substring(i-2,i+1);\n return ans;\n }\n}\n", + "title": "2264. Largest 3-Same-Digit Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num representing a large integer. An integer is good if it meets the following conditions: Return the maximum good integer as a string or an empty string \"\" if no such integer exists . Note:", + "description_images": [], + "constraints": [ + "It is a substring of num with length 3 .", + "It consists of only one unique digit." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"6777133339\"\nOutput:\"777\"\nExplanation:There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".", + "image": null + }, + { + "text": "Example 2: Input:num = \"2300019\"\nOutput:\"000\"\nExplanation:\"000\" is the only good integer.", + "image": null + }, + { + "text": "Example 3: Input:num = \"42352338\"\nOutput:\"\"\nExplanation:No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestGoodInteger(self, n: str) -> str:\n return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else \"\" for i in range(2, len(n)))\n", + "title": "2264. Largest 3-Same-Digit Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1 . You are given a string colors where colors[i] is a lowercase English letter representing the color of the i th node in this graph ( 0-indexed ). You are also given a 2D array edges where edges[j] = [a j , b j ] indicates that there is a directed edge from node a j to node b j . A valid path in the graph is a sequence of nodes x 1 -> x 2 -> x 3 -> ... -> x k such that there is a directed edge from x i to x i+1 for every 1 <= i < k . The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/21/leet1.png", + "https://assets.leetcode.com/uploads/2021/04/21/leet2.png" + ], + "constraints": [ + "n == colors.length", + "m == edges.length", + "1 <= n <= 10^5", + "0 <= m <= 10^5", + "colors consists of lowercase English letters.", + "0 <= a j , b j < n" + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\nOutput:3\nExplanation:The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored\"a\" (red in the above image).", + "image": null + }, + { + "text": "Example 2: Input:colors = \"a\", edges = [[0,0]]\nOutput:-1\nExplanation:There is a cycle from 0 to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int max;\n private Map> memo;\n private boolean hasCycle;\n \n public int largestPathValue(String colors, int[][] edges) { \n Map> map = new HashMap<>();\n \n for(int edge[] : edges) {\n List list = map.getOrDefault(edge[0], new ArrayList<>());\n list.add(edge[1]);\n map.put(edge[0], list);\n }\n \n max = -1;\n memo = new HashMap<>();\n \n boolean visited[] = new boolean[colors.length()];\n hasCycle = false;\n \n for(int i = 0; i < colors.length(); i++) {\n dfs(i, map, colors, visited);\n \n if(hasCycle) {\n return -1;\n }\n }\n \n return max;\n }\n \n private Map dfs(int curr, Map> map, String colors, boolean visited[]) {\n if(visited[curr]) {\n hasCycle = true;\n return new HashMap<>();\n }\n \n if(memo.get(curr) != null) {\n return memo.get(curr);\n }\n \n visited[curr] = true;\n List list = map.get(curr);\n Map currMap = new HashMap<>();\n \n if(list != null && !list.isEmpty()) {\n for(int i : list) {\n Map resMap = dfs(i, map, colors, visited);\n \n if(hasCycle) {\n return currMap;\n }\n \n for(char c : resMap.keySet()) {\n int val = resMap.get(c);\n int currVal = currMap.getOrDefault(c, 0);\n currVal = Math.max(currVal, val);\n currMap.put(c, currVal);\n max = Math.max(currVal, max);\n }\n }\n }\n \n int currentNodeColorCount = currMap.getOrDefault(colors.charAt(curr), 0);\n currMap.put(colors.charAt(curr), currentNodeColorCount + 1);\n \n max = Math.max(currentNodeColorCount + 1, max);\n \n visited[curr] = false;\n memo.put(curr, currMap);\n return currMap;\n }\n}", + "title": "1857. Largest Color Value in a Directed Graph", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1 . You are given a string colors where colors[i] is a lowercase English letter representing the color of the i th node in this graph ( 0-indexed ). You are also given a 2D array edges where edges[j] = [a j , b j ] indicates that there is a directed edge from node a j to node b j . A valid path in the graph is a sequence of nodes x 1 -> x 2 -> x 3 -> ... -> x k such that there is a directed edge from x i to x i+1 for every 1 <= i < k . The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/21/leet1.png", + "https://assets.leetcode.com/uploads/2021/04/21/leet2.png" + ], + "constraints": [ + "n == colors.length", + "m == edges.length", + "1 <= n <= 10^5", + "0 <= m <= 10^5", + "colors consists of lowercase English letters.", + "0 <= a j , b j < n" + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\nOutput:3\nExplanation:The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored\"a\" (red in the above image).", + "image": null + }, + { + "text": "Example 2: Input:colors = \"a\", edges = [[0,0]]\nOutput:-1\nExplanation:There is a cycle from 0 to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Graph:\n \n def __init__(self, colors):\n self.V = len(colors)\n self.adj = [[] for _ in range(self.V)]\n self.reset()\n \n def reset(self):\n self.visited = [False] * self.V\n self.recursion = [False] * self.V\n self.stack = []\n \n def addEdges(self, edges: List[List[int]]):\n for u,v in edges:\n self.addEdge(u, v)\n \n def addEdge(self, u, v):\n self.adj[u].append(v) \n \n def DFS(self, u):\n if self.recursion[u]:\n raise ValueError(\"Cycled Detected\")\n\n if self.visited[u]:\n return\n\n self.visited[u] = True\n self.recursion[u] = True\n\n for v in self.adj[u]:\n self.DFS(v)\n \n self.stack.append(u)\n \n self.recursion[u] = False\n \n def getTopologicalSortOrder(self): \n self.reset()\n \n for u in range(self.V):\n self.DFS(u)\n \n return self.stack[::-1]\n \n def isConnected(self, u, v):\n return self.adj[u].index(v) >= 0\n \n def getAdjs(self, u):\n return self.adj[u]\n \n \n\nclass Solution:\n def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:\n \n g = Graph(colors)\n g.addEdges(edges)\n \n try:\n order = g.getTopologicalSortOrder()\n\n result, dp = 0, [[0]*26 for _ in range(len(order)+1)]\n for i in range(len(order)-1, -1, -1): \n u = order[i]\n # we are storing the max colours possible for all paths from this node \n for v in g.getAdjs(u):\n for k in range(26):\n dp[u][k] = max(dp[u][k], dp[v][k])\n\n c = ord(colors[u])-97\n dp[u][c] += 1\n\n result = max(result, max(dp[u]))\n\n return result \n except:\n return -1\n \n", + "title": "1857. Largest Color Value in a Directed Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The bitwise AND of an array nums is the bitwise AND of all integers in nums . You are given an array of positive integers candidates . Evaluate the bitwise AND of every combination of numbers of candidates . Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0 .", + "description_images": [], + "constraints": [ + "For example, for nums = [1, 5, 3] , the bitwise AND is equal to 1 & 5 & 3 = 1 .", + "Also, for nums = [7] , the bitwise AND is 7 ." + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [16,17,71,62,12,24,14]\nOutput:4\nExplanation:The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [8,8]\nOutput:2\nExplanation:The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 19.3%) | Memory: 56.45 MB (Top 7.1%)\n\nclass Solution {\n public static int largestCombination(int[] candidates) {\n\t\tint arr[] = new int[32];\n\t\tfor (int i = 0; i < candidates.length; i++) {\n\t\t\tString temp = Integer.toBinaryString(candidates[i]);\n\t\t\tint n = temp.length();\n\t\t\tint index = 0;\n\t\t\twhile (n-- > 0) {\n\t\t\t\tarr[index++] += temp.charAt(n) - '0';\n\t\t\t}\n\t\t}\n\t\tint res = Integer.MIN_VALUE;\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tres = Math.max(res, arr[i]);\n\t\t}\n\t\treturn res;\n\t}\n}", + "title": "2275. Largest Combination With Bitwise AND Greater Than Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The bitwise AND of an array nums is the bitwise AND of all integers in nums . You are given an array of positive integers candidates . Evaluate the bitwise AND of every combination of numbers of candidates . Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0 .", + "description_images": [], + "constraints": [ + "For example, for nums = [1, 5, 3] , the bitwise AND is equal to 1 & 5 & 3 = 1 .", + "Also, for nums = [7] , the bitwise AND is 7 ." + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [16,17,71,62,12,24,14]\nOutput:4\nExplanation:The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [8,8]\nOutput:2\nExplanation:The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2282 ms (Top 70.42%) | Memory: 24.8 MB (Top 77.26%)\nclass Solution:\n def largestCombination(self, candidates: List[int]) -> int:\n return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))", + "title": "2275. Largest Combination With Bitwise AND Greater Than Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array of unique positive integers nums . Consider the following graph: Return the size of the largest connected component in the graph .", + "description_images": [], + "constraints": [ + "There are nums.length nodes, labeled nums[0] to nums[nums.length - 1] ,", + "There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,15,35]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex1.png" + }, + { + "text": "Example 2: Input:nums = [20,50,9,63]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex2.png" + }, + { + "text": "Example 3: Input:nums = [2,3,6,7,4,12,21,39]\nOutput:8", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 117 ms (Top 99.00%) | Memory: 50 MB (Top 86.57%)\nclass Solution {\n public int largestComponentSize(int[] nums) {\n int maxNum = getMaxNum(nums);\n Map numToFirstPrimeFactor = new HashMap<>();\n DisjointSet ds = new DisjointSet(maxNum + 1);\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n List primeFactors = getPrimeFactors(num);\n int firstPrimeFactor = primeFactors.get(0);\n numToFirstPrimeFactor.put(num, firstPrimeFactor);\n\n for (int i = 1; i < primeFactors.size(); i++) {\n ds.union(primeFactors.get(i-1), primeFactors.get(i));\n }\n }\n\n Map componentToSize = new HashMap<>();\n int maxSize = 0;\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n int firstPrimeFactor = numToFirstPrimeFactor.get(num);\n int component = ds.find(firstPrimeFactor);\n int size = componentToSize.getOrDefault(component, 0);\n componentToSize.put(component, ++size);\n maxSize = Math.max(maxSize, size);\n }\n return maxSize;\n }\n\n public int getMaxNum(int[] nums) {\n int maxNum = 0;\n for (int num : nums) {\n maxNum = Math.max(maxNum, num);\n }\n return maxNum;\n }\n\n public List getPrimeFactors(int num) {\n List primeFactors = new ArrayList<>();\n\n // even prime factor i.e. 2\n if((num & 1) == 0){\n primeFactors.add(2);\n\n do{\n num >>= 1;\n }while((num & 1) == 0);\n }\n\n // odd prime factors\n int primeFactor = 3;\n while(num != 1 && primeFactor*primeFactor <= num){\n if(num % primeFactor == 0){\n primeFactors.add(primeFactor);\n\n do{\n num /= primeFactor;\n }while(num % primeFactor == 0);\n }\n primeFactor += 2;\n }\n\n // num is prime\n if(num != 1){\n primeFactors.add(num);\n }\n return primeFactors;\n }\n}\n\nclass DisjointSet {\n int[] root;\n int[] rank;\n\n public DisjointSet(int size) {\n root = new int[size];\n rank = new int[size];\n for (int i = 0; i < size; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n public int find(int x) {\n while (x != root[x]) {\n root[x] = root[root[x]];\n x = root[x];\n }\n return x;\n }\n\n public void union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n\n if (rootX == rootY) {\n return;\n }\n\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = rootX;\n } else if (rank[rootX] < rank[rootY]) {\n root[rootX] = rootY;\n } else {\n root[rootY] = rootX;\n rank[rootX]++;\n }\n }\n}", + "title": "952. Largest Component Size by Common Factor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array of unique positive integers nums . Consider the following graph: Return the size of the largest connected component in the graph .", + "description_images": [], + "constraints": [ + "There are nums.length nodes, labeled nums[0] to nums[nums.length - 1] ,", + "There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,15,35]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex1.png" + }, + { + "text": "Example 2: Input:nums = [20,50,9,63]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex2.png" + }, + { + "text": "Example 3: Input:nums = [2,3,6,7,4,12,21,39]\nOutput:8", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 818 ms (Top 91.97%) | Memory: 26.40 MB (Top 28.47%)\n\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def union(self, p, q): \n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = qrt\n self.rank[qrt] += self.rank[prt]\n return True \n\n\nclass Solution:\n def largestComponentSize(self, A: List[int]) -> int:\n m = max(A)\n uf = UnionFind(m+1)\n seen = set(A)\n \n # modified sieve of eratosthenes \n sieve = [1]*(m+1)\n sieve[0] = sieve[1] = 0 \n for k in range(m//2+1): \n if sieve[k]: \n prev = k if k in seen else 0\n for x in range(2*k, m+1, k): \n sieve[x] = 0\n if x in seen: \n if prev: uf.union(prev, x)\n else: prev = x\n return max(uf.rank)\n", + "title": "952. Largest Component Size by Common Factor", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a set of distinct positive integers nums , return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are multiple solutions, return any of them.", + "description_images": [], + "constraints": [ + "answer[i] % answer[j] == 0 , or", + "answer[j] % answer[i] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[1,2]\nExplanation:[1,3] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,8]\nOutput:[1,2,4,8]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 44.53%) | Memory: 44.1 MB (Top 26.48%)\nclass Solution {\n public List largestDivisibleSubset(int[] nums) {\n Arrays.sort(nums);\n int N = nums.length;\n List ans =new ArrayList();\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int []hash =new int[N];\n for(int i=0;idp[i]){\n dp[i] = dp[j]+1;\n hash[i] = j;\n }\n if(dp[i] > maxi){\n maxi = dp[i];\n lastindex = i;\n }\n }\n }//for ends\n ans.add(nums[lastindex]);\n while(hash[lastindex] != lastindex){\n lastindex = hash[lastindex];\n ans.add(nums[lastindex]);\n }\n return ans;\n }\n\n}", + "title": "368. Largest Divisible Subset", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a set of distinct positive integers nums , return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are multiple solutions, return any of them.", + "description_images": [], + "constraints": [ + "answer[i] % answer[j] == 0 , or", + "answer[j] % answer[i] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[1,2]\nExplanation:[1,3] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,8]\nOutput:[1,2,4,8]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n nums.sort()\n n = len(nums)\n dp = [1 for i in range(n)]\n hashh = [i for i in range(n)]\n ans_ind = 0\n \n for i in range(1, n):\n for j in range(0,i):\n if nums[i]%nums[j] == 0 and dp[j]+1 > dp[i]: \n dp[i] = dp[j]+1\n hashh[i] = j\n \n # print(dp)\n # print(hashh)\n out = []\n maxi = dp[0]\n \n for i in range(len(nums)):\n if dp[i] > maxi:\n ans_ind = i\n maxi = dp[i]\n \n while(hashh[ans_ind]!=ans_ind):\n out.append(nums[ans_ind])\n ans_ind = hashh[ans_ind]\n out.append(nums[ans_ind])\n return(out)\n \n \n \n", + "title": "368. Largest Divisible Subset", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal . The integers in the magic square do not have to be distinct . Every 1 x 1 grid is trivially a magic square . Given an m x n integer grid , return the size (i.e., the side length k ) of the largest magic square that can be found within this grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput:3\nExplanation:The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 71.23%) | Memory: 45.5 MB (Top 49.32%)\nclass Solution {\n public int largestMagicSquare(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n // every row prefix sum\n int[][] rowPrefix = new int[m][n];\n for (int i = 0; i < m; i++) {\n rowPrefix[i][0] = grid[i][0];\n for (int j = 1; j < n; j++) {\n rowPrefix[i][j] = rowPrefix[i][j - 1] + grid[i][j];\n }\n }\n\n // every column prefix sum\n int[][] columnPrefix = new int[m][n];\n for (int i = 0; i < n; i++) {\n columnPrefix[0][i] = grid[0][i];\n for (int j = 1; j < m; j++) {\n columnPrefix[j][i] = columnPrefix[j - 1][i] + grid[j][i];\n }\n }\n\n int result = 1;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // length of square\n int l = Math.min(m - i, n - j);\n // only check square's length is better than previous result\n for (int k = l; k > result; k--) {\n if (magic(i, j, k, grid, rowPrefix, columnPrefix)) {\n result = k;\n break;\n }\n }\n }\n }\n return result;\n }\n\n private boolean magic(\n int i, int j, int l, int[][] grid, int[][] rowPrefix, int[][] columnPrefix) {\n // check every row\n int target = rowPrefix[i][j + l - 1] - rowPrefix[i][j] + grid[i][j];\n for (int k = 0; k < l; k++) {\n if (rowPrefix[i + k][j + l - 1] - rowPrefix[i + k][j] + grid[i + k][j] != target) {\n return false;\n }\n }\n\n // check every column\n for (int k = 0; k < l; k++) {\n if (columnPrefix[i + l - 1][j + k] - columnPrefix[i][j + k] + grid[i][j + k] != target) {\n return false;\n }\n }\n\n // check both diagonal\n int diagonal = 0;\n // \\\n // \\\n for (int k = 0; k < l; k++) {\n diagonal += grid[i + k][j + k];\n }\n\n if (diagonal != target) {\n return false;\n }\n\n // /\n // /\n for (int k = 0; k < l; k++) {\n diagonal -= grid[i + l - 1 - k][j + k];\n }\n\n return diagonal == 0;\n }\n}", + "title": "1895. Largest Magic Square", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal . The integers in the magic square do not have to be distinct . Every 1 x 1 grid is trivially a magic square . Given an m x n integer grid , return the size (i.e., the side length k ) of the largest magic square that can be found within this grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput:3\nExplanation:The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1987 ms (Top 15.7%) | Memory: 16.60 MB (Top 82.4%)\n\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n for j in range(n): \n rows[i][j+1] = grid[i][j] + rows[i][j]\n cols[i+1][j] = grid[i][j] + cols[i][j]\n \n ans = 1\n for i in range(m): \n for j in range(n): \n diag = grid[i][j]\n for k in range(min(i, j)): \n ii, jj = i-k-1, j-k-1\n diag += grid[ii][jj]\n ss = {diag}\n for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])\n for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])\n ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal\n if len(ss) == 1: ans = max(ans, k+2)\n return ans ", + "title": "1895. Largest Magic Square", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings word1 and word2 . You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: Return the lexicographically largest merge you can construct . A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b . For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c .", + "description_images": [], + "constraints": [ + "If word1 is non-empty, append the first character in word1 to merge and delete it from word1 . For example, if word1 = \"abc\" and merge = \"dv\" , then after choosing this operation, word1 = \"bc\" and merge = \"dva\" .", + "For example, if word1 = \"abc\" and merge = \"dv\" , then after choosing this operation, word1 = \"bc\" and merge = \"dva\" .", + "If word2 is non-empty, append the first character in word2 to merge and delete it from word2 . For example, if word2 = \"abc\" and merge = \"\" , then after choosing this operation, word2 = \"bc\" and merge = \"a\" .", + "For example, if word2 = \"abc\" and merge = \"\" , then after choosing this operation, word2 = \"bc\" and merge = \"a\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cabaa\", word2 = \"bcaaa\"\nOutput:\"cbcabaaaaa\"\nExplanation:One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcabc\", word2 = \"abdcaba\"\nOutput:\"abdcabcabcaba\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 92.79%) | Memory: 44.70 MB (Top 66.67%)\n\nclass Solution {\n public String largestMerge(String word1, String word2) {\n StringBuilder sb = new StringBuilder();\n int i=0;\n int j=0;\n char[] w1 = word1.toCharArray();\n char[] w2 = word2.toCharArray();\n \n int n1=w1.length;\n int n2=w2.length;\n \n // we loop until we exhaust any one of the 2 words completely\n while(iw2[j]){\n sb.append(w1[i++]);\n }else{\n sb.append(w2[j++]);\n }\n }\n \n // at the end of the loop we append any remaining word\n sb.append(word1.substring(i));\n sb.append(word2.substring(j));\n\t\t\n return sb.toString();\n }\n \n private boolean check(char[] w1, int i, char[] w2, int j){\n // will return true if we need to extract from word1 and false if we need to extract from word2\n \n while(iw2[j]){\n return true;\n }else{\n return false;\n }\n }\n \n // if we are unable to find any exhaustable character till the end of the loop we use the one having larger length\n if(i str:\n res = ''\n p1 = 0\n p2 = 0\n while p1 < len(word1) and p2 < len(word2):\n if word1[p1:] > word2[p2:]:\n res += word1[p1]\n p1 += 1\n else:\n res += word2[p2]\n p2 += 1\n \n res += word1[p1:] + word2[p2:]\n\n \n return res\n", + "title": "1754. Largest Merge Of Two Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digits digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order . If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 10^4", + "0 <= digits[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [8,1,9]\nOutput:\"981\"", + "image": null + }, + { + "text": "Example 2: Input:digits = [8,6,7,1,0]\nOutput:\"8760\"", + "image": null + }, + { + "text": "Example 3: Input:digits = [1]\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String largestMultipleOfThree(int[] digits) {\n int n=digits.length;\n Arrays.sort(digits);\n \n if(digits[digits.length-1]==0){\n return \"0\";\n }\n \n int sum=0;\n \n for(int i=0;i=0;i--){\n sb.append(digits[i]);\n }\n \n return sb.toString();\n }else if(sum%3==1){\n int modOne=-1;\n \n for(int i=0;i=0;i--){\n if(digits[i]!=-1){\n sb.append(digits[i]);\n }\n \n }\n \n if(sb.length()>0 && sb.toString().charAt(0)=='0'){\n return \"0\";\n }\n return sb.toString();\n }\n}\n", + "title": "1363. Largest Multiple of Three", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of digits digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order . If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 10^4", + "0 <= digits[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [8,1,9]\nOutput:\"981\"", + "image": null + }, + { + "text": "Example 2: Input:digits = [8,6,7,1,0]\nOutput:\"8760\"", + "image": null + }, + { + "text": "Example 3: Input:digits = [1]\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef largestMultipleOfThree(self, digits: List[int]) -> str:\n\t\tA = digits\n\t\tA.sort()\n\t\tA.reverse()\n\n\t\t@cache\n\t\tdef DP(i, r): # max number whose remainder is r using subarray [0:i] (inclusive) \n\t\t\tif i == 0:\n\t\t\t\tif A[0] % 3 == r:\n\t\t\t\t\treturn A[0]\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\n\t\t\tRa = DP(i-1, r)\n\t\t\tRb = [ x for j in range(3) \\\n\t\t\t\t for x in ( DP(i-1,j) * 10 + A[i] ,)\n\t\t\t\t if x % 3 == r ]\n\n\t\t\treturn max([Ra, *Rb])\n\n\t\tans = DP(len(A) - 1, 0)\n\n\t\tif ans == 0 and 0 not in A:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn str(ans)\n", + "title": "1363. Largest Multiple of Three", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a list of non-negative integers nums , arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2]\nOutput:\"210\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,30,34,5,9]\nOutput:\"9534330\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 69.93%) | Memory: 44.3 MB (Top 32.60%)\n\nclass Solution {\n public String largestNumber(int[] nums) {\n String[] arr=new String[nums.length];\n for(int i=0;i(b+a).compareTo(a+b));\n if(arr[0].equals(\"0\")) return \"0\";\n StringBuilder builder=new StringBuilder();\n for(String item:arr){\n builder.append(item);\n }\n return builder.toString();\n }\n}", + "title": "179. Largest Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a list of non-negative integers nums , arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2]\nOutput:\"210\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,30,34,5,9]\nOutput:\"9534330\"", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cmp_to_key\nclass Solution:\n def largestNumber(self, nums: List[int]) -> str:\n nums = list(map(str, nums))\n nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0))))\n res = \"\".join(nums)\n return res if int(res) else \"0\"", + "title": "179. Largest Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer num . You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 1234\nOutput:3412\nExplanation:Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.", + "image": null + }, + { + "text": "Example 2: Input:num = 65875\nOutput:87655\nExplanation:Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 55.01%) | Memory: 41.3 MB (Top 44.82%)\nclass Solution {\n public int largestInteger(int num) {\n PriorityQueue opq = new PriorityQueue<>();\n PriorityQueue epq = new PriorityQueue<>();\n int bnum = num;\n while(num>0){\n int cur = num%10;\n if(cur%2==1){\n opq.add(cur);\n }else{\n epq.add(cur);\n }\n num /= 10;\n }\n StringBuilder sb = new StringBuilder();\n num = bnum;\n while(num>0){\n int cur = num%10;\n if(cur%2==1)\n sb.insert(0, opq.poll());\n else\n sb.insert(0, epq.poll());\n num /= 10;\n }\n return Integer.parseInt(sb.toString());\n }\n}", + "title": "2231. Largest Number After Digit Swaps by Parity", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer num . You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 1234\nOutput:3412\nExplanation:Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.", + "image": null + }, + { + "text": "Example 2: Input:num = 65875\nOutput:87655\nExplanation:Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res\n", + "title": "2231. Largest Number After Digit Swaps by Parity", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string num , which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d] . You may choose to mutate a single substring of num . To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]] ). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num . A substring is a contiguous sequence of characters within the string.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num consists of only digits 0-9 .", + "change.length == 10", + "0 <= change[d] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\nOutput:\"832\"\nExplanation:Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.", + "image": null + }, + { + "text": "Example 2: Input:num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\nOutput:\"934\"\nExplanation:Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.", + "image": null + }, + { + "text": "Example 3: Input:num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\nOutput:\"5\"\nExplanation:\"5\" is already the largest number that can be created, so return it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maximumNumber(String num, int[] change) {\n int i=0, n=num.length(), startIndex=-1, substringLength=0;\n \n // traverse through each digit in the input string\n while(i digit) {\n startIndex = i;\n // keep on replacing subsequent characters with with the change if they also have greater change\n while(i=startIndex && j str:\n flag=0\n ls=list(num)\n for i in range(len(ls)):\n k=int(ls[i])\n if change[k]>k:\n ls[i]=str(change[k])\n flag=1\n elif flag==1 and change[k] max){\n secondMax = max;\n max = nums[i];\n index = i;\n } else if(nums[i] != max && nums[i] > secondMax){\n secondMax = nums[i];\n }\n }\n if(secondMax * 2 <= max){\n return index;\n }\n return -1;\n }\n}\n", + "title": "747. Largest Number At Least Twice of Others", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums where the largest integer is unique . Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 50", + "0 <= nums[i] <= 100", + "The largest element in nums is unique." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,0]\nOutput:1\nExplanation:6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:-1\nExplanation:4 is less than twice the value of 3, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 86.73%) | Memory: 13.8 MB (Top 57.55%)\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n if len(nums) is 1:\n return 0\n dom = max(nums)\n i = nums.index(dom)\n nums.remove(dom)\n if max(nums) * 2 <= dom:\n return i\n return -1", + "title": "747. Largest Number At Least Twice of Others", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string num , representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num , or an empty string \"\" if no odd integer exists . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num only consists of digits and does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"52\"\nOutput:\"5\"\nExplanation:The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.", + "image": null + }, + { + "text": "Example 2: Input:num = \"4206\"\nOutput:\"\"\nExplanation:There are no odd numbers in \"4206\".", + "image": null + }, + { + "text": "Example 3: Input:num = \"35427\"\nOutput:\"35427\"\nExplanation:\"35427\" is already an odd number.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 63.81%) | Memory: 54.8 MB (Top 11.36%)\nclass Solution {\n public String largestOddNumber(String num) {\n for (int i = num.length() - 1; i > -1; i--) {\n if (num.charAt(i) % 2 == 1) return num.substring(0,i+1);\n }\n return \"\";\n }\n}", + "title": "1903. Largest Odd Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num , representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num , or an empty string \"\" if no odd integer exists . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num only consists of digits and does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"52\"\nOutput:\"5\"\nExplanation:The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.", + "image": null + }, + { + "text": "Example 2: Input:num = \"4206\"\nOutput:\"\"\nExplanation:There are no odd numbers in \"4206\".", + "image": null + }, + { + "text": "Example 3: Input:num = \"35427\"\nOutput:\"35427\"\nExplanation:\"35427\" is already an odd number.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestOddNumber(self, num: str) -> str:\n indx = -1\n n = len(num)\n for i in range(n):\n if int(num[i])%2 == 1:\n indx = i\n \n if indx == -1:\n return \"\"\n return num[:indx+1]\n", + "title": "1903. Largest Odd Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n -digits integers . Since the answer can be very large, return it modulo 1337 .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:987\n\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestPalindrome(int n) {\n if(n == 1 ){\n return 9;\n }\n if(n == 2){\n return 987;\n }\n if(n == 3){\n return 123;\n }\n if(n == 4){\n return 597;\n }\n if(n == 5){\n return 677;\n }\n if(n == 6){\n return 1218;\n }\n if(n == 7){\n return 877;\n }\n return 475;\n \n }\n}\n\n", + "title": "479. Largest Palindrome Product", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n -digits integers . Since the answer can be very large, return it modulo 1337 .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:987\n\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n]\n\n \n def isPalindrome(x):\n return str(x) == str(x)[::-1]\n\n def solve(n):\n best = 0\n for i in range(10**n-1, 0, -1):\n for j in range(max(i, (best-1)//i+1), 10**n):\n if isPalindrome(i*j):\n #print(i, j, i*j)\n best = i*j\n return best\n", + "title": "479. Largest Palindrome Product", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums , return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths . If it is impossible to form any triangle of a non-zero area, return 0 .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,2]\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 44.30%) | Memory: 54.1 MB (Top 55.23%)\nclass Solution {\n public int largestPerimeter(int[] nums) {\n Arrays.sort(nums);\n\n for(int i = nums.length - 3; i >= 0; i--) {\n if(nums[i] + nums[i + 1] > nums[i + 2])\n return nums[i] + nums[i + 1] + nums[i + 2];\n }\n return 0;\n }\n}", + "title": "976. Largest Perimeter Triangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths . If it is impossible to form any triangle of a non-zero area, return 0 .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,2]\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestPerimeter(self, nums: List[int]) -> int:\n nums=sorted(nums,reverse=True)\n l=len(nums)\n for i in range(l-2):\n if nums[i]= 0 && arr[i - 1][j] == 1) {\n dpTop[i][j] = 1 + dpTop[i - 1][j];\n }\n\n if(j - 1 >= 0 && arr[i][j - 1] == 1) {\n dpLeft[i][j] = 1 + dpLeft[i][j - 1];\n }\n }\n }\n\n // Prefix count of 1 cells on bottom and right directions\n for(int i = arr.length - 1; i >= 0; i--) {\n for(int j = arr.length - 1; j >= 0; j--) {\n if(i + 1 < arr.length && arr[i + 1][j] == 1) {\n dpBottom[i][j] = 1 + dpBottom[i + 1][j];\n }\n\n if(j + 1 < arr.length && arr[i][j + 1] == 1) {\n dpRight[i][j] = 1 + dpRight[i][j + 1];\n }\n }\n }\n\n int maxPlusSignLength = 0;\n for(int i = 0; i < arr.length; i++) {\n for(int j = 0; j < arr.length; j++) {\n if(arr[i][j] == 0) continue;\n\n // Minimum adjacent 1 cell count from all four directions to ensure symmetry\n int minAdjacentOnes = Math.min(Math.min(dpTop[i][j], dpBottom[i][j]), Math.min(dpLeft[i][j], dpRight[i][j]));\n maxPlusSignLength = Math.max(maxPlusSignLength, minAdjacentOnes + 1);\n }\n }\n\n return maxPlusSignLength;\n }\n}", + "title": "764. Largest Plus Sign", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n . You have an n x n binary grid grid with all values initially 1 's except for some indices given in the array mines . The i th element of the array mines is defined as mines[i] = [x i , y i ] where grid[x i ][y i ] == 0 . Return the order of the largest axis-aligned plus sign of 1 's contained in grid . If there is none, return 0 . An axis-aligned plus sign of 1 's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1 's. Note that there could be 0 's or 1 's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1 's.", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "1 <= mines.length <= 5000", + "0 <= x i , y i < n", + "All the pairs (x i , y i ) are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, mines = [[4,2]]\nOutput:2\nExplanation:In the above grid, the largest plus sign can only be of order 2. One of them is shown.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/plus1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 1, mines = [[0,0]]\nOutput:0\nExplanation:There is no plus sign, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/plus2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:\n matrix = [1] * n\n aux = {}\n hasOne = False\n for i in range(0,n):\n matrix[i] = [1] * n\n for mine in mines:\n matrix[mine[0]][mine[1]] = 0\n for i in range(0,n):\n for j in range(0,n):\n if(matrix[i][j] == 1):\n hasOne = True\n if((i,j) not in aux):\n aux[(i,j)] = {\"t\":0,\"l\":0,\"r\":0,\"b\":0}\n if(j>0 and matrix[i][j] == 1 and matrix[i][j-1] == 1):\n aux[(i,j)][\"l\"] = aux[(i,j-1)][\"l\"] + 1 \n if(i>0 and matrix[i][j] == 1 and matrix[i-1][j] == 1):\n aux[(i,j)][\"t\"] = aux[(i-1,j)][\"t\"] + 1\n \n maxOrder = 0 \n for i in range(n-1,-1,-1):\n if(i stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.length;\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n \n for(int i=0; i= heights[i])\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n \n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights[stack2.peek()] >= heights[i])\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n \n for(int i=0; i int:\n maxArea = 0\n stack = [] # (index, height)\n \n for i, h in enumerate(heights):\n startIndex = i\n while stack and stack[-1][1] > h:\n index, height = stack.pop()\n maxArea = max(maxArea, height * (i - index))\n startIndex = index\n stack.append((startIndex, h))\n \n \n \n for index, height in stack:\n maxArea = max(maxArea, height * (len(heights) - index))\n \n \n return maxArea", + "title": "84. Largest Rectangle in Histogram", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a binary matrix matrix of size m x n , and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m * n <= 10^5", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput:4\nExplanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" + }, + { + "text": "Example 2: Input:matrix = [[1,0,1,0,1]]\nOutput:3\nExplanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" + }, + { + "text": "Example 3: Input:matrix = [[1,1,0],[1,0,1]]\nOutput:2\nExplanation:Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 97.37%) | Memory: 73.60 MB (Top 19.35%)\n\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length;\n for (int i = 1; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (matrix[i][j] == 1) {\n matrix[i][j] = matrix[i - 1][j] + 1;\n }\n }\n }\n int ans = 0;\n for (var row : matrix) {\n Arrays.sort(row);\n for (int j = n - 1, k = 1; j >= 0 && row[j] > 0; --j, ++k) {\n int s = row[j] * k;\n ans = Math.max(ans, s);\n }\n }\n return ans;\n }\n}\n", + "title": "1727. Largest Submatrix With Rearrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary matrix matrix of size m x n , and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m * n <= 10^5", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput:4\nExplanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" + }, + { + "text": "Example 2: Input:matrix = [[1,0,1,0,1]]\nOutput:3\nExplanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" + }, + { + "text": "Example 3: Input:matrix = [[1,1,0],[1,0,1]]\nOutput:2\nExplanation:Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3821 ms (Top 7.64%) | Memory: 37.3 MB (Top 95.14%)\nfrom collections import Counter\n\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n M = len(matrix)\n N = len(matrix[0])\n\n colcons = [] # preprocess columns\n for c in range(N):\n cons = []\n s = 0\n for r in range(M):\n if not matrix[r][c]:\n s = 0\n else:\n s += 1\n cons.append(s)\n colcons.append(cons)\n # colcons[c][r] is how much 1's we'll get if we start from column c at row r and go up\n\n best = 0\n for r in range(M):\n # try r as the lowest row\n C = Counter(colcons[c][r] for c in range(N))\n vs = sorted(C.keys(), reverse=True)\n cs = accumulate(C[v] for v in vs)\n for v,c in zip(vs,cs):\n best = max(best,v*c)\n return best", + "title": "1727. Largest Submatrix With Rearrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1 . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 300", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\"\nOutput:0\nExplanation:The optimal substring here is an empty substring between the two'a's.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"\nOutput:2\nExplanation:The optimal substring here is \"bc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"cbzxy\"\nOutput:-1\nExplanation:There are no characters that appear twice in s.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 92.59%) | Memory: 41.10 MB (Top 80.55%)\n\nclass Solution {\n public int maxLengthBetweenEqualCharacters(String s) {\n int[] v1 = new int[26];\n int[] v2 = new int[26];\n Arrays.fill(v1, -1);\n Arrays.fill(v2, -1);\n int ans = -1;\n\n for (int i = 0; i < s.length(); ++i) {\n int temp = s.charAt(i) - 'a';\n\n if (v1[temp] == -1) {\n v1[temp] = i;\n } else {\n v2[temp] = i;\n ans = Math.max(ans, v2[temp] - v1[temp] - 1);\n }\n }\n\n return ans;\n }\n}\n\n\n", + "title": "1624. Largest Substring Between Two Equal Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1 . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 300", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\"\nOutput:0\nExplanation:The optimal substring here is an empty substring between the two'a's.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"\nOutput:2\nExplanation:The optimal substring here is \"bc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"cbzxy\"\nOutput:-1\nExplanation:There are no characters that appear twice in s.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans \n", + "title": "1624. Largest Substring Between Two Equal Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums and an integer k . You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums , and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions . Answers within 10 -6 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,1,2,3,9], k = 3\nOutput:20.00000\nExplanation:The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6,7], k = 4\nOutput:20.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Double dp[][][];\n int n;\n int k1;\n public double check(int b, int c,long sum,int n1,int ar[]){\n System.out.println(b+\" \"+c);\n if(dp[b][c][n1]!=null)\n return dp[b][c][n1];\n if(b==n){\n if(sum!=0)\n return (double)sum/(double)n1;\n else\n return 0.0;}\n if(c0)\n dp[b][c][n1]=Math.max((double)sum/(double)n1+check(b,c+1,0,0,ar),check(b+1,c,sum+(long)ar[b],n1+1,ar));\n else\n dp[b][c][n1]=check(b+1,c,sum+(long)ar[b],n1+1,ar);\n\n return dp[b][c][n1];\n }\n public double largestSumOfAverages(int[] nums, int k) {\n n=nums.length;\n k1=k-1;\n dp= new Double[n+1][k][n+1];\n return check(0,0,0l,0,nums);\n }\n}\n", + "title": "813. Largest Sum of Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer k . You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums , and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions . Answers within 10 -6 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,1,2,3,9], k = 3\nOutput:20.00000\nExplanation:The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6,7], k = 4\nOutput:20.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestSumOfAverages(self, A, k):\n n = len(A)\n dp = [0] * n\n sum = 0\n for i in range(n-1,-1,-1):\n sum += A[i]\n dp[i] = sum / (n-i)\n for l in range(1,k):\n for i in range(n-l):\n sum = 0\n for j in range(i,n-l):\n sum += A[j]\n dp[i] = max(dp[i],dp[j+1] + sum / (j-i+1))\n return dp[0]\n", + "title": "813. Largest Sum of Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . Return the latest 24-hour time in \"HH:MM\" format . If no valid time can be made, return an empty string.", + "description_images": [], + "constraints": [ + "arr.length == 4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4]\nOutput:\"23:41\"\nExplanation:The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,5,5,5]\nOutput:\"\"\nExplanation:There are no valid 24-hour times as \"55:55\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String largestTimeFromDigits(int[] arr) {\n int[] count = new int[10];\n for (int num: arr) {\n count[num]++;\n }\n StringBuilder sb = backTrack(count, new StringBuilder());\n if (sb.length() == 4) sb.insert(2, ':');\n return sb.toString();\n \n }\n private StringBuilder backTrack(int[] count, StringBuilder sb) {\n int size = sb.length();\n int start = 0;\n if (size == 0) {\n start = 2;\n }\n if (size == 1) {\n start = sb.charAt(0) == '2' ? 3 : 9;\n }\n if (size == 2) {\n start = 5;\n }\n if (size == 3) {\n start = 9;\n }\n for (int i = start; i >= 0; i--) {\n if (count[i] == 0) continue;\n count[i]--;\n sb.append(i);\n backTrack(count, sb);\n if (sb.length() == 4) {\n return sb;\n }\n else {\n count[Character.getNumericValue(sb.charAt(sb.length() - 1))]++;\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n return sb;\n }\n}\n", + "title": "949. Largest Time for Given Digits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . Return the latest 24-hour time in \"HH:MM\" format . If no valid time can be made, return an empty string.", + "description_images": [], + "constraints": [ + "arr.length == 4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4]\nOutput:\"23:41\"\nExplanation:The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,5,5,5]\nOutput:\"\"\nExplanation:There are no valid 24-hour times as \"55:55\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n res = \"\"\n digit_freq = collections.Counter(arr)\n # first digit\n \n \n if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2:\n res += \"2\"\n arr.remove(2)\n else:\n for digit in [1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # can't make 24-hour time\n if len(res) == 0:\n return \"\"\n \n # second digit 0-3\n if res == \"2\":\n for digit in [3,2,1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # no 0-3 left in arr\n if len(res) == 1:\n return \"\"\n # second digit 0-9\n else:\n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n res += \":\"\n \n for digit in range(5, -1, -1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n if len(res) == 3:\n return \"\"\n \n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n return res\n \n", + "title": "949. Largest Time for Given Digits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of points on the X-Y plane points where points[i] = [x i , y i ] , return the area of the largest triangle that can be formed by any three different points . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "3 <= points.length <= 50", + "-50 <= x i , y i <= 50", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput:2.00000\nExplanation:The five points are shown in the above figure. The red triangle is the largest.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png" + }, + { + "text": "Example 2: Input:points = [[1,0],[0,0],[0,1]]\nOutput:0.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double largestTriangleArea(int[][] points) {\n double ans = 0;\n int n = points.length;\n for(int i=0;i float:\n maxA = 0\n for p1, p2, p3 in combinations(points, 3):\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y1 - y2))\n if A > maxA: maxA = A\n return maxA\n", + "title": "812. Largest Triangle Area", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the i th element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit . Choose a subset s of the n elements such that: The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s .", + "description_images": [], + "constraints": [ + "The size of the subset s is less than or equal to numWanted .", + "There are at most useLimit items with the same label in s ." + ], + "examples": [ + { + "text": "Example 1: Input:values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput:9\nExplanation:The subset chosen is the first, third, and fifth items.", + "image": null + }, + { + "text": "Example 2: Input:values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput:12\nExplanation:The subset chosen is the first, second, and third items.", + "image": null + }, + { + "text": "Example 3: Input:values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput:16\nExplanation:The subset chosen is the first and fourth items.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {\n PriorityQueue> maxHeap = \n new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey()));\n for(int i=0;i(values[i], labels[i]));\n }\n Map labelLimitMap = new HashMap<>();\n int sum = 0;\n while(numWanted != 0) {\n int label = maxHeap.peek().getValue();\n if(labelLimitMap.containsKey(label)) {\n if(labelLimitMap.get(label) == useLimit) {\n maxHeap.poll();\n } else {\n labelLimitMap.put(label, labelLimitMap.get(label) + 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n } else {\n labelLimitMap.put(label, 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n // This Holds since at most numWanted is mentioned.\n if(maxHeap.isEmpty()) {\n return sum;\n }\n }\n return sum;\n }\n}\n", + "title": "1090. Largest Values From Labels", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the i th element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit . Choose a subset s of the n elements such that: The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s .", + "description_images": [], + "constraints": [ + "The size of the subset s is less than or equal to numWanted .", + "There are at most useLimit items with the same label in s ." + ], + "examples": [ + { + "text": "Example 1: Input:values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput:9\nExplanation:The subset chosen is the first, third, and fifth items.", + "image": null + }, + { + "text": "Example 2: Input:values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput:12\nExplanation:The subset chosen is the first, second, and third items.", + "image": null + }, + { + "text": "Example 3: Input:values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput:16\nExplanation:The subset chosen is the first and fourth items.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def largestValsFromLabels(\n self, values: list[int], labels: list[int], numWanted: int, useLimit: int\n ) -> int:\n\n # Add labels and values into the heap\n heap = [(-value, label) for value, label in zip(values, labels)]\n heapq.heapify(heap)\n\n # Initialize the hashmap\n used = defaultdict(int)\n\n # Initialize the result\n res = 0\n\n # Iterate until we have used a certain number or the heap is empty\n while numWanted > 0 and heap:\n\n # Pop a label and its value from the heap\n value, label = heapq.heappop(heap)\n\n # If we can use such label\n if used[label] < useLimit:\n\n # Add its value to the result\n res += -value\n\n # Increment its count in the hashmap\n used[label] += 1\n\n # Decrement the number of numbers we still want\n numWanted -= 1\n\n return res\n", + "title": "1090. Largest Values From Labels", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0 , the entire matrix is land . However, each day a new cell becomes flooded with water . You are given a 1-based 2D array cells , where cells[i] = [r i , c i ] represents that on the i th day, the cell on the r i th row and c i th column ( 1-based coordinates) will be covered with water (i.e., changed to 1 ). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells .", + "description_images": [], + "constraints": [ + "2 <= row, col <= 2 * 10^4", + "4 <= row * col <= 2 * 10^4", + "cells.length == row * col", + "1 <= r i <= row", + "1 <= c i <= col", + "All the values of cells are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]\nOutput:2\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/1.png" + }, + { + "text": "Example 2: Input:row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]\nOutput:1\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/2.png" + }, + { + "text": "Example 3: Input:row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]\nOutput:3\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 49.61%) | Memory: 121.4 MB (Top 10.85%)\nclass Solution {\n int[][] dir = new int[][]{{0, -1}, {-1, 0}, {1, 0}, {0, 1}};\n public int latestDayToCross(int row, int col, int[][] cells) {\n int grid[][] = new int[row][col];\n int low = 0, high = cells.length - 1;\n int ans = 0;\n\n while(low <= high){\n int mid = low + (high - low) / 2;\n\n for(int i = 0; i <= mid; i++)\n grid[cells[i][0] -1][cells[i][1] - 1] = 1;\n\n if(helper(grid, new boolean[row][col])){\n ans = mid;\n low = mid + 1;\n }\n\n else high = mid - 1;\n\n for(int i = 0; i < grid.length; i++)\n for(int j = 0; j < grid[i].length; j++)\n grid[i][j] = 0;\n }\n\n return ans + 1;\n }\n\n public boolean helper(int[][] grid, boolean[][] visited){\n for(int i = 0; i < grid[0].length; i++)\n if(grid[0][i] == 0 && !visited[0][i] &&safe(0, i, grid, visited)) return true;\n return false;\n }\n\n public boolean safe(int i, int j, int[][] cells, boolean[][] visited){\n if(i < 0 || j < 0 || i >= visited.length || j >= visited[i].length || visited[i][j] || cells[i][j] == 1) return false;\n if(i == cells.length - 1 && j < cells[i].length && cells[i][j] == 0) return true;\n\n visited[i][j] = true;\n for(int k = 0; k < dir.length; k++)\n if(safe(i + dir[k][0], j + dir[k][1], cells, visited)) return true;\n return false;\n }\n}", + "title": "1970. Last Day Where You Can Still Cross", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0 , the entire matrix is land . However, each day a new cell becomes flooded with water . You are given a 1-based 2D array cells , where cells[i] = [r i , c i ] represents that on the i th day, the cell on the r i th row and c i th column ( 1-based coordinates) will be covered with water (i.e., changed to 1 ). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells .", + "description_images": [], + "constraints": [ + "2 <= row, col <= 2 * 10^4", + "4 <= row * col <= 2 * 10^4", + "cells.length == row * col", + "1 <= r i <= row", + "1 <= c i <= col", + "All the values of cells are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]\nOutput:2\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/1.png" + }, + { + "text": "Example 2: Input:row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]\nOutput:1\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/2.png" + }, + { + "text": "Example 3: Input:row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]\nOutput:3\nExplanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/3.png" + } + ], + "follow_up": null, + "solution": "class UF:\n def __init__(self, m, n):\n self.n, self.loc_id, c_id = n, dict(), 0\n self.col_set = [set() for _ in range(m*n)]\n for i in range(m): # Assign id for each location (i ,j)\n for j in range(n):\n self.loc_id[(i, j)] = c_id\n self.col_set[c_id].add(j)\n c_id += 1\n self.p = [i for i in range(m*n)] # Initialize parents array `p`\n \n def find(self, i):\n if self.p[i] != i:\n self.p[i] = self.find(self.p[i])\n return self.p[i] \n \n def union(self, i, j):\n pi, pj = self.find(i), self.find(j)\n if pi != pj:\n self.p[pj] = pi # Update `pi`\n self.col_set[pi] = self.col_set[pi] | self.col_set[pj] # Take union of two sets (union all occupied columns)\n return len(self.col_set[pi]) == self.n # if length of col_set[pi] == self.n, meaning this piece occupied all columns from 1 to `col` inclusive, meaning we are blocked\n \nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n uf, visited = UF(row, col), set()\n for i, (x, y) in enumerate(cells):\n x, y = x-1, y-1\n visited.add((x, y))\n for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, 1), (0, -1)]:\n _x, _y = x+dx, y+dy # Check if neighbor is flooded\n if 0 <= _x < row and 0 <= _y < col and (_x, _y) in visited:\n id1, id2 = uf.loc_id[(_x, _y)], uf.loc_id[(x, y)]\n if uf.union(id1, id2): return i # Union two flooded piece and return index if union return True\n return -1\n", + "title": "1970. Last Day Where You Can Still Cross", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have a wooden plank of the length n units . Some ants are walking on the plank, each ant moves with a speed of 1 unit per second . Some of the ants move to the left , the other move to the right . When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t , it falls out of the plank immediately. Given an integer n and two integer arrays left and right , the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= left.length <= n + 1", + "0 <= left[i] <= n", + "0 <= right.length <= n + 1", + "0 <= right[i] <= n", + "1 <= left.length + right.length <= n + 1", + "All values of left and right are unique, and each value can appear only in one of the two arrays." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, left = [4,3], right = [0,1]\nOutput:4\nExplanation:In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants.jpg" + }, + { + "text": "Example 2: Input:n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput:7\nExplanation:All ants are going to the right, the ant at index 0 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants2.jpg" + }, + { + "text": "Example 3: Input:n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput:7\nExplanation:All ants are going to the left, the ant at index 7 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getLastMoment(int n, int[] left, int[] right) {\n int max = 0;\n for (int i = 0; i < left.length; i++) {\n if (left[i] > max)\n max = left[i];\n }\n for (int i = 0; i < right.length; i++) {\n if (n - right[i] > max)\n max = n - right[i];\n }\n return max;\n }\n}\n", + "title": "1503. Last Moment Before All Ants Fall Out of a Plank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have a wooden plank of the length n units . Some ants are walking on the plank, each ant moves with a speed of 1 unit per second . Some of the ants move to the left , the other move to the right . When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t , it falls out of the plank immediately. Given an integer n and two integer arrays left and right , the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= left.length <= n + 1", + "0 <= left[i] <= n", + "0 <= right.length <= n + 1", + "0 <= right[i] <= n", + "1 <= left.length + right.length <= n + 1", + "All values of left and right are unique, and each value can appear only in one of the two arrays." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, left = [4,3], right = [0,1]\nOutput:4\nExplanation:In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants.jpg" + }, + { + "text": "Example 2: Input:n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput:7\nExplanation:All ants are going to the right, the ant at index 0 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants2.jpg" + }, + { + "text": "Example 3: Input:n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput:7\nExplanation:All ants are going to the left, the ant at index 7 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 316 ms (Top 23.17%) | Memory: 15 MB (Top 18.90%)\nclass Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n # make sure left and right are not empty without changing the answer\n left.append(0)\n right.append(n)\n\n return max(max(left), n - min(right))", + "title": "1503. Last Moment Before All Ants Fall Out of a Plank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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 .", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]\nOutput:1\nExplanation:We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 42.30%) | Memory: 40.7 MB (Top 84.83%)\nclass Solution {\n public int lastStoneWeight(int[] stones) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x));\n for (int i = 0; i < stones.length; i++) {\n pq.add(stones[i]);\n }\n while (pq.size() > 1) {\n int r1 = pq.poll();\n int r2 = pq.poll();\n if (r1 != r2) pq.add(r1 - r2);\n }\n return (pq.isEmpty()) ? 0 : pq.poll();\n }\n}", + "title": "1046. Last Stone Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: 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 .", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]\nOutput:1\nExplanation:We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 27.86%) | Memory: 13.9 MB (Top 62.57%)\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n stones = [-x for x in stones]\n heapq.heapify(stones)\n\n while len(stones) > 1:\n mx1 = -heapq.heappop(stones)\n mx2 = -heapq.heappop(stones)\n if mx1 - mx2:\n heapq.heappush(stones, -(mx1 - mx2))\n\n if len(stones):\n return -heapq.heappop(stones)\n return 0\n", + "title": "1046. Last Stone Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 any two stones and smash them together. Suppose the stones have weights x and y with x <= y . The result of this smash is: At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone . If there are no stones left, return 0 .", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]\nOutput:1\nExplanation:We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\nwe can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\nwe can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\nwe can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.", + "image": null + }, + { + "text": "Example 2: Input:stones = [31,26,33,21,40]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n if len(stones) == 1: return stones[0]\n total = sum(stones)\n half, leng = total// 2, len(stones)\n dp = [[0] * (half + 1) for _ in range(leng + 1)]\n \n for i in range(1, leng+1):\n for j in range(1, half+1):\n if j - stones[i-1] >= 0:\n dp[i][j] = max(dp[i-1][j], dp[i-1][j - stones[i-1]] + stones[i-1])\n else:\n dp[i][j] = dp[i-1][j]\n return total - 2 * dp[leng][half]\n", + "title": "1049. Last Stone Weight II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , return the last substring of s in lexicographical order .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 4 * 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"\nOutput:\"bab\"\nExplanation:The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"tcode\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 54.24%) | Memory: 57.7 MB (Top 33.05%)\nclass Solution {\n\npublic String lastSubstring(String s) {\nint maxIndex = s.length() - 1;\n\nfor(int currIndex = s.length() - 1 ; currIndex >= 0 ; currIndex--){\n if(s.charAt(currIndex) > s.charAt(maxIndex))\n maxIndex = currIndex;\n\n else if(s.charAt(currIndex) == s.charAt(maxIndex)){\n int i = currIndex + 1;\n int j = maxIndex + 1;\n\n while(i < maxIndex && j < s.length() && s.charAt(i) == s.charAt(j)){\n i++;\n j++;\n }\n\n if(i == maxIndex || j == s.length() || s.charAt(i) > s.charAt(j))\n maxIndex = currIndex;\n }\n}\n\nreturn s.substring(maxIndex);\n}\n}", + "title": "1163. Last Substring in Lexicographical Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the last substring of s in lexicographical order .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 4 * 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"\nOutput:\"bab\"\nExplanation:The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"tcode\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 273 ms (Top 82.1%) | Memory: 20.15 MB (Top 100.0%)\n\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n i = 0\n j = 1\n k = 0\n n = len(s)\n while j + k < n:\n if s[i + k] == s[j + k]:\n k += 1\n elif s[i + k] > s[j + k]:\n j += k + 1\n k = 0\n elif s[i + k] < s[j + k]:\n i = max(i + k + 1, j)\n j = i + 1\n k = 0\n return s[i:]", + "title": "1163. Last Substring in Lexicographical Order", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string time in the form of hh:mm , where some of the digits in the string are hidden (represented by ? ). The valid times are those inclusively between 00:00 and 23:59 . Return the latest valid time you can get from time by replacing the hidden digits .", + "description_images": [], + "constraints": [ + "time is in the format hh:mm .", + "It is guaranteed that you can produce a valid time from the given string." + ], + "examples": [ + { + "text": "Example 1: Input:time = \"2?:?0\"\nOutput:\"23:50\"\nExplanation:The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.", + "image": null + }, + { + "text": "Example 2: Input:time = \"0?:3?\"\nOutput:\"09:39\"", + "image": null + }, + { + "text": "Example 3: Input:time = \"1?:22\"\nOutput:\"19:22\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maximumTime(String time) {\n char[] times = time.toCharArray();\n //for times[0]\n //if both characters of hour is ?, then hour is 23 then times[0] should be '2'(\"??:3?)\".\n //if 2nd character of hour is <= 3, then hour can be in 20s then times[0] should be '2'.\n //if 2nd character of hour is >3, then hour can only be in 10s then times[0] should be '1'.\n if(times[0]=='?')\n times[0]= (times[1]<='3' || times[1]=='?') ? '2' : '1';\n //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then times[1] should be '9'.\n //if 1st character of hour is 2, then hour can be 23 then times[1] should be '3'.\n if(times[1]=='?')\n times[1]= times[0]=='2' ? '3' : '9';\n //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so times[3] is always '5'.\n if(times[3]=='?')\n times[3]='5';\n //if 2nd character of minute is ?, then times[4] is '9'.\n if(times[4]=='?')\n times[4]='9';\n return new String(times);\n }\n}\n", + "title": "1736. Latest Time by Replacing Hidden Digits", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string time in the form of hh:mm , where some of the digits in the string are hidden (represented by ? ). The valid times are those inclusively between 00:00 and 23:59 . Return the latest valid time you can get from time by replacing the hidden digits .", + "description_images": [], + "constraints": [ + "time is in the format hh:mm .", + "It is guaranteed that you can produce a valid time from the given string." + ], + "examples": [ + { + "text": "Example 1: Input:time = \"2?:?0\"\nOutput:\"23:50\"\nExplanation:The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.", + "image": null + }, + { + "text": "Example 2: Input:time = \"0?:3?\"\nOutput:\"09:39\"", + "image": null + }, + { + "text": "Example 3: Input:time = \"1?:22\"\nOutput:\"19:22\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef maximumTime(self, time: str) -> str:\n memo = {\"0\":\"9\",\n \"1\":\"9\",\n \"?\":\"3\", \n \"2\":\"3\"}\n \n answer = \"\"\n for idx, val in enumerate(time):\n if val == \"?\":\n if idx == 0:\n if time[idx+1] == \"?\":\n answer += \"2\"\n \n else:\n if int(time[idx+1]) >= 4:\n answer += \"1\"\n \n else: answer += \"2\"\n \n if idx == 1:\n answer += memo[time[idx-1]]\n \n if idx == 3:\n answer += \"5\" \n \n if idx == 4:\n answer += \"9\"\n \n else:\n answer += val\n \n return answer\n", + "title": "1736. Latest Time by Replacing Hidden Digits", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.37%) | Memory: 42.6 MB (Top 13.06%)\nclass Solution {\n public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n List list1 = new ArrayList<>();\n checkLeaf(root1, list1);\n List list2 = new ArrayList<>();\n checkLeaf(root2, list2);\n\n if(list1.size() != list2.size()) return false;\n\n int i = 0;\n while(i < list1.size()){\n if(list1.get(i) != list2.get(i)){\n return false;\n }\n i++;\n }\n return true;\n }\n\n private void checkLeaf(TreeNode node, List arr){\n if(node.left == null && node.right == null) arr.add(node.val);\n if(node.left != null) checkLeaf(node.left, arr);\n if(node.right != null) checkLeaf(node.right, arr);\n }\n}", + "title": "872. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n tree=[]\n def inorder(root):\n nonlocal tree\n if root is None:\n return\n if root.left is None and root.right is None:\n tree.append(root.val)\n \n inorder(root.left)\n inorder(root.right)\n \n inorder(root1)\n inorder(root2)\n tree1=tree[:len(tree)//2]\n tree2=tree[len(tree)//2:]\n if tree1==tree2:\n return True\n else:\n return False", + "title": "872. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr and an integer k . Find the least number of unique integers after removing exactly k elements .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^9", + "0 <= k <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,5,4], k = 1\nOutput:1\nExplanation: Remove the single 4, only 5 is left.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,3,1,1,3,3,2], k = 3\nOutput:2\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findLeastNumOfUniqueInts(int[] arr, int k) {\n Map freqMap = new HashMap<>();\n for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1);\n PriorityQueue pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2)));\n pq.addAll(freqMap.keySet());\n while(k>0 && !pq.isEmpty()){\n int element = pq.poll();\n int toBeDeleted = Math.min(k,freqMap.get(element));\n k-=toBeDeleted;\n if(toBeDeleted int:\n\n counter = collections.Counter(arr)\n\n min_heap = [(count, num) for num, count in counter.items()]\n\n\n\n heapify(min_heap)\n\n\n\n while k > 0:\n\n count, num = min_heap[0]\n\n\n\n if count > k:\n\n break\n\n\n\n heappop(min_heap)\n\n k -= count\n\n\n\n return len(min_heap)", + "title": "1481. Least Number of Unique Integers after K Removals", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a single positive integer x , we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1 , op2 , etc. is either addition, subtraction, multiplication, or division ( + , - , * , or /) . For example, with x = 3 , we might write 3 * 3 / 3 + 3 - 3 which is a value of 3 . When writing such an expression, we adhere to the following conventions: We would like to write an expression with the least number of operators such that the expression equals the given target . Return the least number of operators used.", + "description_images": [], + "constraints": [ + "The division operator ( / ) returns rational numbers.", + "There are no parentheses placed anywhere.", + "We use the usual order of operations: multiplication and division happen before addition and subtraction.", + "It is not allowed to use the unary negation operator ( - ). For example, \" x - x \" is a valid expression as it only uses subtraction, but \" -x + x \" is not because it uses negation." + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, target = 19\nOutput:5\nExplanation:3 * 3 + 3 * 3 + 3 / 3.\nThe expression contains 5 operations.", + "image": null + }, + { + "text": "Example 2: Input:x = 5, target = 501\nOutput:8\nExplanation:5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\nThe expression contains 8 operations.", + "image": null + }, + { + "text": "Example 3: Input:x = 100, target = 100000000\nOutput:3\nExplanation:100 * 100 * 100 * 100.\nThe expression contains 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3027 ms (Top 7.32%) | Memory: 13.9 MB (Top 97.56%)\nclass Solution(object):\n def leastOpsExpressTarget(self, x, target):\n return self.cost(x, target)\n\n def cost(self, x, val):\n if val == x:\n return 0\n elif val < x:\n # two possible states\n # either val > x / 2: we substract 1s\n state_1 = 2 * (x - val)\n # or val < x / 2: we divide once to 1 and we add enough 1s\n state_2 = 2*val - 1\n return min(state_1, state_2)\n else:\n # there is a maximum power of x that we can add\n p = int(log(val) // log(x))\n # and either x^p or x^(p+1) is the closest\n a = x**p\n b = a*x\n if b < 2*val:\n # x**(p+1) - val < val - x**p\n return min(p + self.cost(x, val - a), p + 1 + self.cost(x, b - val))\n else:\n return p + self.cost(x, val - a)", + "title": "964. Least Operators to Express Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "At a lemonade stand, each lemonade costs $5 . Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5 , $10 , or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5 . Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the i th customer pays, return true if you can provide every customer with the correct change, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= bills.length <= 10^5", + "bills[i] is either 5 , 10 , or 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:bills = [5,5,5,10,20]\nOutput:true\nExplanation:From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.", + "image": null + }, + { + "text": "Example 2: Input:bills = [5,5,10,10,20]\nOutput:false\nExplanation:From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean lemonadeChange(int[] bills) {\n int count5 = 0, count10 = 0;\n for(int p : bills){\n if(p == 5){\n count5++;\n }\n else if(p == 10){\n if(count5 > 0){\n count5--;\n count10++;\n }\n else{\n return false;\n }\n }\n else if(p == 20){\n if(count5 > 0 && count10 > 0){\n count5--;\n count10--;\n }\n else if(count5 == 0){\n return false;\n }\n else if(count5<3){\n return false;\n }\n else{\n count5 -= 3;\n }\n }\n }\n return true;\n }\n}\n", + "title": "860. Lemonade Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "At a lemonade stand, each lemonade costs $5 . Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5 , $10 , or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5 . Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the i th customer pays, return true if you can provide every customer with the correct change, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= bills.length <= 10^5", + "bills[i] is either 5 , 10 , or 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:bills = [5,5,5,10,20]\nOutput:true\nExplanation:From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.", + "image": null + }, + { + "text": "Example 2: Input:bills = [5,5,10,10,20]\nOutput:false\nExplanation:From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 670 ms (Top 99.03%) | Memory: 22.00 MB (Top 10.8%)\n\nclass Solution:\n def lemonadeChange(self, bills):\n five = ten = 0\n for num in bills:\n if num == 5:\n five += 1\n elif num == 10 and five:\n ten += 1\n five -= 1\n elif num == 20 and five and ten:\n five -= 1\n ten -= 1\n elif num == 20 and five >= 3:\n five -= 3\n else:\n return False\n return True\n", + "title": "860. Lemonade Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"\nOutput:5\nExplanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"\nOutput:4\nExplanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"\nOutput:6\nExplanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 78.55%)\nclass Solution {\n public int lengthOfLastWord(String s) {\n int j=s.length()-1,len=0; boolean flag=true;\n while(j>=0 && (flag || (!flag && s.charAt(j)!=' ')))\n if(s.charAt(j--)!=' '){\n flag=false;\n len++;\n }\n return len;\n }\n}", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"\nOutput:5\nExplanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"\nOutput:4\nExplanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"\nOutput:6\nExplanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n return len(s.strip().split()[-1])\n", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sequence x 1 , x 2 , ..., x n is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr . If one does not exist, return 0 . A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr , without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8] .", + "description_images": [], + "constraints": [ + "n >= 3", + "x i + x i+1 == x i+2 for all i + 2 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,6,7,8]\nOutput:5\nExplanation:The longest subsequence that is fibonacci-like: [1,2,3,5,8].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,7,11,12,14,18]\nOutput:3\nExplanation:The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 97.6%) | Memory: 54.76 MB (Top 33.3%)\n\nclass Solution {\n /*\n * dp[i][j] is the max length of fibbonacci series whose last two elements\n * are A[i] & A[j]\n * for any integer A[k] we need to find two number A[i] & A[j] such that\n * i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time\n * complexity.\n * if there exist i,j,k such that i < j < k and A[i] + A[j] == A[k] then\n * dp[k][j] = dp[i][j] + 1 (A[k], A[j] are last two elements of fibbonacc series)\n */\n public int lenLongestFibSubseq(int[] A) {\n int n = A.length;\n int[][] dp = new int[n][n];\n int result = 0;\n for (int k = 2; k < n; k++) {\n int i = 0, j = k-1;\n while(i < j) {\n int sum = A[i] + A[j] - A[k];\n if (sum < 0) {\n i++;\n } else if (sum > 0) {\n j--;\n } else {\n // ith, jth kth element are fibbonaci sequence\n dp[j][k] = dp[i][j] + 1; // since numbers are unique\n result = Math.max(result, dp[j][k]);\n i++;\n j--;\n }\n }\n }\n return result + 2 >= 3? result + 2: 0;\n }\n}", + "title": "873. Length of Longest Fibonacci Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sequence x 1 , x 2 , ..., x n is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr . If one does not exist, return 0 . A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr , without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8] .", + "description_images": [], + "constraints": [ + "n >= 3", + "x i + x i+1 == x i+2 for all i + 2 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,6,7,8]\nOutput:5\nExplanation:The longest subsequence that is fibonacci-like: [1,2,3,5,8].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,7,11,12,14,18]\nOutput:3\nExplanation:The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object): #DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A)\n def lenLongestFibSubseq(self, A):\n index = {Ai: i for i, Ai in enumerate(A)}\n dp = collections.defaultdict(lambda: 2)\n ans = 0\n for k, Ak in enumerate(A): #Following IJK idiom here\n for j in range(k-1,0,-1): \n i = index.get(Ak - A[j], None)\n if Ak - A[j] >= A[j]: break #Pruning for illegal Ai\n if i is not None and i < j:\n cur_len = dp[j, k] = dp[i, j] + 1\n ans = max(ans, cur_len)\n \n return ans # ans is either 0 or >=3 for SURE\n\n", + "title": "873. Length of Longest Fibonacci Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , you can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create . Return the output in any order .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 12", + "s consists of lowercase English letters, uppercase English letters, and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a1b2\"\nOutput:[\"a1b2\",\"a1B2\",\"A1b2\",\"A1B2\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"3z4\"\nOutput:[\"3z4\",\"3Z4\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def letterCasePermutation(self, s):\n \n if s==\"\":\n return [\"\"]\n t=s[0].lower()\n li=[]\n res=self.letterCasePermutation(s[1:])\n for i in res:\n li.append(t+i)\n if t not in \"1234567890\":\n for i in res:\n li.append(t.upper()+i)\n return li\n \n \n \n", + "title": "784. Letter Case Permutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"\nOutput:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"\nOutput:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n String[] num = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n public List letterCombinations(String digits) {\n List ll = new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n if (digits.length() != 0) {\n combination(digits.toCharArray(), ll, sb, 0);\n }\n return ll;\n }\n public void combination(char[] digits, List ll, StringBuilder sb, int idx) {\n \n if (sb.length() == digits.length) {\n ll.add(sb.toString());\n return;\n }\n \n String grp = num[digits[idx] - 48];\n for (int i = 0; i < grp.length(); i++) {\n sb.append(grp.charAt(i));\n combination(digits, ll, sb, idx + 1);\n sb.deleteCharAt(sb.length() - 1);\n }\n \n }\n}\n", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"\nOutput:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"\nOutput:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n \n mapping = {\"2\": \"abc\",\n \"3\": \"def\",\n \"4\": \"ghi\",\n \"5\": \"jkl\",\n \"6\": \"mno\",\n \"7\": \"pqrs\",\n \"8\": \"tuv\",\n \"9\": \"wxyz\"}\n \n ans = []\n first = True\n for i in range(len(digits)):\n \n # mult: times we should print each digit\n mult = 1 \n for j in range(i+1, len(digits)):\n mult *= len(mapping[digits[j]])\n \n # cycles: times we should run same filling cycle\n if not first:\n cycles = len(ans) // mult\n else:\n cycles = 1\n if times > 1:\n cycles //= len(mapping[digits[i]])\n \n # cyclically adding each digits to answer\n answer_ind = 0 \n for _ in range(cycles):\n for char in mapping[digits[i]]:\n for __ in range(mult):\n if first:\n ans.append(char)\n else:\n ans[answer_ind] += char\n answer_ind += 1\n if first:\n first = False\n \n return ans\n", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 7", + "tiles consists of uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = \"AAB\"\nOutput:8\nExplanation:The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".", + "image": null + }, + { + "text": "Example 2: Input:tiles = \"AAABBC\"\nOutput:188", + "image": null + }, + { + "text": "Example 3: Input:tiles = \"V\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int result=0;\n public int numTilePossibilities(String tiles) {\n Map map = new HashMap<>();\n for(char c:tiles.toCharArray()){\n map.put(c,map.getOrDefault(c,0)+1);\n }\n find(map);\n return result-1;\n }\n public void find(Map map){\n result++;\n for(Map.Entry m:map.entrySet()){\n char c=m.getKey();\n int val =m.getValue();\n if(val>0){\n map.put(c,val-1);\n find(map);\n map.put(c,val);\n }\n }\n }\n}\n", + "title": "1079. Letter Tile Possibilities", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 7", + "tiles consists of uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = \"AAB\"\nOutput:8\nExplanation:The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".", + "image": null + }, + { + "text": "Example 2: Input:tiles = \"AAABBC\"\nOutput:188", + "image": null + }, + { + "text": "Example 3: Input:tiles = \"V\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n n= len(tiles)\n tiles=list(tiles)\n s1=set()\n for i in range(1,n+1):\n s1.update(permutations(tiles,i))\n return len(s1)", + "title": "1079. Letter Tile Possibilities", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space.", + "description_images": [], + "constraints": [ + "1 <= n <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 94 ms (Top 5.29%) | Memory: 74.9 MB (Top 5.05%)\nclass Solution {\n\n private final TrieNode trie = new TrieNode(' ');\n\n class TrieNode{\n\n private Character digit;\n private String value;\n private boolean isWord;\n private Map children;\n\n TrieNode(Character c){\n this.digit = c;\n this.isWord = false;\n this.children = new HashMap<>();\n }\n\n void insert(String s){\n TrieNode current = this;\n for(Character c : s.toCharArray()){\n current = current.children.computeIfAbsent(c, k -> new TrieNode(c));\n }\n current.value = s;\n current.isWord = true;\n }\n\n List getWordsPreOrder(){\n return getWordsPreOrder(this);\n }\n\n private List getWordsPreOrder(TrieNode root){\n List result = new ArrayList<>();\n if(root == null){\n return result;\n }\n\n if(root.isWord){\n result.add(Integer.parseInt(root.value));\n }\n for(TrieNode node : root.children.values()){\n result.addAll(getWordsPreOrder(node));\n }\n return result;\n }\n }\n\n public List lexicalOrder(int n) {\n for(int i = 1 ; i<=n;i++){\n trie.insert(String.valueOf(i));\n }\n return trie.getWordsPreOrder();\n }\n}", + "title": "386. Lexicographical Numbers", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space.", + "description_images": [], + "constraints": [ + "1 <= n <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lexicalOrder(self, n: int) -> List[int]:\n result = []\n orderDic = {}\n for i in range(1, n + 1):\n strI = str(i)\n level = orderDic\n for char in strI:\n if char not in level:\n level[char] = {}\n level = level[char]\n self.traverse(orderDic, \"\", result)\n return result\n \n def traverse(self, dic, temp, result):\n for key in dic:\n result.append(int(temp + key))\n self.traverse(dic[key], temp + key, result)\n", + "title": "386. Lexicographical Numbers", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of even length consisting of digits from 0 to 9 , and two integers a and b . You can apply either of the following two operations any number of times and in any order on s : Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9' .", + "description_images": [], + "constraints": [ + "Add a to all odd indices of s (0-indexed) . Digits post 9 are cycled back to 0 . For example, if s = \"3456\" and a = 5 , s becomes \"3951\" .", + "Rotate s to the right by b positions. For example, if s = \"3456\" and b = 1 , s becomes \"6345\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5525\", a = 9, b = 2\nOutput:\"2050\"\nExplanation:We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\n​​​​​​​Add: \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"74\", a = 5, b = 1\nOutput:\"24\"\nExplanation:We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"0011\", a = 4, b = 2\nOutput:\"0011\"\nExplanation:There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private String result;\n public String findLexSmallestString(String s, int a, int b) {\n result = \"z\";\n HashSet set = new HashSet<>();\n dfs(s, a, b, set);\n return result;\n }\n private void dfs(String s, int a, int b, HashSet set) {\n if(set.contains(s))\n return;\n set.add(s);\n String s1, s2;\n s1 = addA(s, a);\n s2 = rotateB(s, b);\n dfs(s1, a , b, set);\n dfs(s2, a , b, set);\n }\n private String addA(String s, int a) {\n char c[] = s.toCharArray();\n int i, temp;\n for(i=1;i 0)\n result = s;\n return s;\n }\n private String rotateB(String s, int b) {\n if(b < 0)\n b += s.length();\n b = b % s.length();\n b = s.length() - b;\n s = s.substring(b) + s.substring(0, b);\n if(result.compareTo(s) > 0)\n result = s;\n return s;\n }\n}\n", + "title": "1625. Lexicographically Smallest String After Applying Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s of even length consisting of digits from 0 to 9 , and two integers a and b . You can apply either of the following two operations any number of times and in any order on s : Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9' .", + "description_images": [], + "constraints": [ + "Add a to all odd indices of s (0-indexed) . Digits post 9 are cycled back to 0 . For example, if s = \"3456\" and a = 5 , s becomes \"3951\" .", + "Rotate s to the right by b positions. For example, if s = \"3456\" and b = 1 , s becomes \"6345\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5525\", a = 9, b = 2\nOutput:\"2050\"\nExplanation:We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\n​​​​​​​Add: \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"74\", a = 5, b = 1\nOutput:\"24\"\nExplanation:We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"0011\", a = 4, b = 2\nOutput:\"0011\"\nExplanation:There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nw: BFS\nh: for each possible number (node), we have two possible operations (add, rotate)\n it seems to be a 2^100 possible number, however, note:\n 1) add a to number of odd index, we will get to the same number after 10 rounds of add\n 2) s has even length, if b is odd, we can get the same number after n round\n 3) for each shift, we would get different number at even index in 10 rounds\n \n so we would have 10 * n * 10 number at most, then we can use BFS + memo\n'''\nimport collections\n\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n seen = set()\n deque = collections.deque([s])\n\n while deque:\n #print(deque)\n curr = deque.popleft()\n seen.add(curr)\n \n #1.add\n ad = self.add_(curr, a)\n if ad not in seen:\n deque.append(ad)\n seen.add(ad)\n\n \n #2. rotate:\n ro = self.rotate_(curr, b)\n if ro not in seen:\n deque.append(ro)\n seen.add(ro)\n\n return min(seen)\n \n \n def add_(self,s,a):\n res = ''\n for idx, i in enumerate(s):\n if idx % 2 == 1:\n num = (int(i) + a) % 10\n res += str(num)\n else:\n res += i\n \n return res\n \n \n def rotate_(self, s, b):\n idx = len(s)-b\n res = s[idx:] + s[0:idx]\n return res\n", + "title": "1625. Lexicographically Smallest String After Applying Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 78.13%) | Memory: 133.90 MB (Top 10.6%)\n\nclass LFUCache {\n\n final int capacity;\n int curSize;\n int minFrequency;\n Map cache;\n Map frequencyMap;\n\n /*.*/\n /*\n * @param capacity: total capacity of LFU Cache\n * @param curSize: current size of LFU cache\n * @param minFrequency: frequency of the last linked list (the minimum frequency of entire LFU cache)\n * @param cache: a hash map that has key to Node mapping, which used for storing all nodes by their keys\n * @param frequencyMap: a hash map that has key to linked list mapping, which used for storing all\n * double linked list by their frequencies\n * */\n public LFUCache(int capacity) {\n this.capacity = capacity;\n this.curSize = 0;\n this.minFrequency = 0;\n\n this.cache = new HashMap<>();\n this.frequencyMap = new HashMap<>();\n }\n\n /** get node value by key, and then update node frequency as well as relocate that node **/\n public int get(int key) {\n DLLNode curNode = cache.get(key);\n if (curNode == null) {\n return -1;\n }\n updateNode(curNode);\n return curNode.val;\n }\n\n /**\n * add new node into LFU cache, as well as double linked list\n * condition 1: if LFU cache has input key, update node value and node position in list\n * condition 2: if LFU cache does NOT have input key\n * - sub condition 1: if LFU cache does NOT have enough space, remove the Least Recent Used node\n * in minimum frequency list, then add new node\n * - sub condition 2: if LFU cache has enough space, add new node directly\n * **/\n public void put(int key, int value) {\n // corner case: check cache capacity initialization\n if (capacity == 0) {\n return;\n }\n\n if (cache.containsKey(key)) {\n DLLNode curNode = cache.get(key);\n curNode.val = value;\n updateNode(curNode);\n }\n else {\n curSize++;\n if (curSize > capacity) {\n // get minimum frequency list\n DoubleLinkedList minFreqList = frequencyMap.get(minFrequency);\n cache.remove(minFreqList.tail.prev.key);\n minFreqList.removeNode(minFreqList.tail.prev);\n curSize--;\n }\n // reset min frequency to 1 because of adding new node\n minFrequency = 1;\n DLLNode newNode = new DLLNode(key, value);\n\n // get the list with frequency 1, and then add new node into the list, as well as into LFU cache\n DoubleLinkedList curList = frequencyMap.getOrDefault(1, new DoubleLinkedList());\n curList.addNode(newNode);\n frequencyMap.put(1, curList);\n cache.put(key, newNode);\n }\n }\n\n public void updateNode(DLLNode curNode) {\n int curFreq = curNode.frequency;\n DoubleLinkedList curList = frequencyMap.get(curFreq);\n curList.removeNode(curNode);\n\n // if current list the the last list which has lowest frequency and current node is the only node in that list\n // we need to remove the entire list and then increase min frequency value by 1\n if (curFreq == minFrequency && curList.listSize == 0) {\n minFrequency++;\n }\n\n curNode.frequency++;\n // add current node to another list has current frequency + 1,\n // if we do not have the list with this frequency, initialize it\n DoubleLinkedList newList = frequencyMap.getOrDefault(curNode.frequency, new DoubleLinkedList());\n newList.addNode(curNode);\n frequencyMap.put(curNode.frequency, newList);\n }\n\n /*\n * @param key: node key\n * @param val: node value\n * @param frequency: frequency count of current node\n * (all nodes connected in same double linked list has same frequency)\n * @param prev: previous pointer of current node\n * @param next: next pointer of current node\n * */\n class DLLNode {\n int key;\n int val;\n int frequency;\n DLLNode prev;\n DLLNode next;\n\n public DLLNode(int key, int val) {\n this.key = key;\n this.val = val;\n this.frequency = 1;\n }\n }\n\n /*\n * @param listSize: current size of double linked list\n * @param head: head node of double linked list\n * @param tail: tail node of double linked list\n * */\n class DoubleLinkedList {\n int listSize;\n DLLNode head;\n DLLNode tail;\n public DoubleLinkedList() {\n this.listSize = 0;\n this.head = new DLLNode(0, 0);\n this.tail = new DLLNode(0, 0);\n head.next = tail;\n tail.prev = head;\n }\n\n /** add new node into head of list and increase list size by 1 **/\n public void addNode(DLLNode curNode) {\n DLLNode nextNode = head.next;\n curNode.next = nextNode;\n curNode.prev = head;\n head.next = curNode;\n nextNode.prev = curNode;\n listSize++;\n }\n\n /** remove input node and decrease list size by 1**/\n public void removeNode(DLLNode curNode) {\n DLLNode prevNode = curNode.prev;\n DLLNode nextNode = curNode.next;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n listSize--;\n }\n\n }\n}\n\n/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */\n", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n \n def __init__(self, key, val, cnt=1, nxxt=None, prev=None):\n self.key = key\n self.val = val\n self.cnt = cnt\n self.nxxt = nxxt\n self.prev = prev\n \n \nclass NodeList(Node):\n \n def __init__(self):\n self.head = Node(0,0)\n self.tail = Node(0,0)\n self.head.nxxt = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n \n def addFront(self, node):\n temp = self.head.nxxt\n self.head.nxxt = node\n node.prev = self.head\n node.nxxt = temp\n temp.prev = node\n \n self.size += 1\n \n \n def removeNode(self, node):\n delprev = node.prev\n delnxxt = node.nxxt\n delprev.nxxt = delnxxt\n delnxxt.prev = delprev\n \n self.size -= 1\n \n\nclass LFUCache(NodeList):\n\n def __init__(self, capacity: int):\n self.keyNode = {}\n self.freqNodeList = {}\n self.maxSizeCache = capacity\n self.currSize = 0\n self.minFreq = 0\n \n \n def updateFreqNodeList(self, node):\n del self.keyNode[node.key]\n nodelist = self.freqNodeList[node.cnt]\n nodelist.removeNode(node)\n \n if node.cnt == self.minFreq and self.freqNodeList[node.cnt].size == 0:\n self.minFreq += 1\n \n if (node.cnt+1) in self.freqNodeList:\n nextHigherFreqNodeList = self.freqNodeList[node.cnt+1]\n else:\n nextHigherFreqNodeList = NodeList()\n \n node.cnt += 1\n nextHigherFreqNodeList.addFront(node)\n \n self.freqNodeList[node.cnt] = nextHigherFreqNodeList\n self.keyNode[node.key] = node\n \n\n def get(self, key: int) -> int:\n if key in self.keyNode:\n node = self.keyNode[key]\n ans = node.val\n self.updateFreqNodeList(node)\n \n return ans\n \n else:\n return -1\n \n\n def put(self, key: int, value: int) -> None:\n if self.maxSizeCache == 0:\n return\n \n if key in self.keyNode:\n node = self.keyNode[key]\n node.val = value\n self.updateFreqNodeList(node)\n return\n \n else:\n if self.currSize == self.maxSizeCache:\n nodelist = self.freqNodeList[self.minFreq]\n del self.keyNode[nodelist.tail.prev.key]\n nodelist.removeNode(nodelist.tail.prev)\n self.currSize -= 1\n \n self.currSize += 1\n self.minFreq = 1\n \n if self.minFreq in self.freqNodeList:\n nodelist = self.freqNodeList[self.minFreq]\n else:\n nodelist = NodeList()\n \n node = Node(key, value)\n nodelist.addFront(node)\n \n self.keyNode[key] = node\n self.freqNodeList[self.minFreq] = nodelist\n \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k . We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of English letters, digits, and dashes '-' .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5F3Z-2e-9-w\", k = 4\nOutput:\"5F3Z-2E9W\"\nExplanation:The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.", + "image": null + }, + { + "text": "Example 2: Input:s = \"2-5g-3-J\", k = 2\nOutput:\"2-5G-3J\"\nExplanation:The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 55.76%) | Memory: 45.6 MB (Top 53.19%)\nclass Solution {\n public String licenseKeyFormatting(String s, int k) {\n StringBuilder answer = new StringBuilder();\n int length = 0;\n // Iterate Backwards to fullfill first group condition\n for(int i=s.length()-1;i>=0;i--) {\n if(s.charAt(i) == '-') {\n continue;\n }\n if(length > 0 && length % k == 0) {\n answer.append('-');\n }\n answer.append(Character.toUpperCase(s.charAt(i)));\n length++;\n }\n return answer.reverse().toString();\n }\n}", + "title": "482. License Key Formatting", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k . We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of English letters, digits, and dashes '-' .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5F3Z-2e-9-w\", k = 4\nOutput:\"5F3Z-2E9W\"\nExplanation:The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.", + "image": null + }, + { + "text": "Example 2: Input:s = \"2-5g-3-J\", k = 2\nOutput:\"2-5G-3J\"\nExplanation:The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 55.38%) | Memory: 14.3 MB (Top 86.51%)\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n new_str = s.replace(\"-\", \"\")\n res = \"\"\n j = len(new_str)-1\n i = 0\n while j >= 0:\n res += new_str[j].upper()\n i += 1\n if i == k and j != 0:\n res += \"-\"\n i = 0\n j -= 1\n return res[::-1]", + "title": "482. License Key Formatting", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list .", + "description_images": [], + "constraints": [ + "The number of nodes in the linked list is n .", + "1 <= n <= 10^4", + "0 <= Node.val < n", + "All the values Node.val are unique .", + "1 <= nums.length <= n", + "0 <= nums[i] < n", + "All the values of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,1,2,3], nums = [0,1,3]\nOutput:2\nExplanation:0 and 1 are connected, so [0, 1] and [3] are the two connected components.", + "image": "https://assets.leetcode.com/uploads/2021/07/22/lc-linkedlistcom1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2,3,4], nums = [0,3,1,4]\nOutput:2\nExplanation:0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.", + "image": "https://assets.leetcode.com/uploads/2021/07/22/lc-linkedlistcom2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numComponents(ListNode head, int[] nums) {\n int count=0;\n HashSet set=new HashSet();\n for(int i=0;i int:\n d,count={},0\n for num in nums:\n d[num] = 0\n\n while head:\n if head.val in d:\n head = head.next\n while head and head.val in d:\n head = head.next\n count += 1\n else:\n head = head.next\n return count", + "title": "817. Linked List Components", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:false\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "public class Solution {\n public boolean hasCycle(ListNode head) {\n ListNode fast = head;\n ListNode slow = head;\n boolean result = false;\n while(fast!=null && fast.next!=null){\n fast = fast.next.next;\n slow = slow.next;\n if(fast == slow){\n result = true;\n break;\n }\n }\n return result;\n }\n}\n", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:false\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n for i in range(0, 10001):\n if head == None: return False\n head = head.next\n \n return True\n", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:tail connects to node index 1\nExplanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:tail connects to node index 0\nExplanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:no cycle\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "public class Solution {\n public ListNode detectCycle(ListNode head) {\n if (head == null) return null;\n ListNode tortoise = head;\n ListNode hare = new ListNode();\n hare.next = head.next;\n while (hare != null && hare.next != null && hare != tortoise) {\n tortoise = tortoise.next;\n hare = hare.next.next;\n }\n if (hare == null || hare.next == null) return null;\n tortoise = head;\n while (tortoise != hare) {\n tortoise = tortoise.next;\n hare = hare.next;\n }\n return hare;\n }\n}\n", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:tail connects to node index 1\nExplanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:tail connects to node index 0\nExplanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:no cycle\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return None\n slow = fast = entry = head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if slow == fast:\n while slow != entry:\n slow = slow.next\n entry = entry.next\n return entry\n return None\n", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png", + "https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png" + ], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 2500] .", + "The number of nodes in the list will be in the range [1, 100] .", + "1 <= Node.val <= 100 for each node in the linked list and binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:true\nExplanation:Nodes in blue form a subpath in the binary Tree.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:false\nExplanation:There is no path in the binary tree that contains all the elements of the linked list fromhead.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 72.52%) | Memory: 49.5 MB (Top 46.71%)\nclass Solution {\n public boolean isSubPath(ListNode head, TreeNode root) {\n if(root == null) return false;\n if(issame(head, root)) return true;\n return isSubPath(head, root.left) || isSubPath(head, root.right);\n }\n private boolean issame(ListNode head, TreeNode root) {\n if(head == null) return true;\n if(root == null) return false;\n if(head.val != root.val) return false;\n return issame(head.next, root.left) || issame(head.next, root.right);\n }\n}", + "title": "1367. Linked List in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png", + "https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png" + ], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 2500] .", + "The number of nodes in the list will be in the range [1, 100] .", + "1 <= Node.val <= 100 for each node in the linked list and binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:true\nExplanation:Nodes in blue form a subpath in the binary Tree.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput:false\nExplanation:There is no path in the binary tree that contains all the elements of the linked list fromhead.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 139 ms (Top 73.10%) | Memory: 16.3 MB (Top 54.16%)\n\nclass Solution(object):\n def isSubPath(self, head, root):\n if not root:\n return False\n if self.issame(head, root):\n return True\n return self.isSubPath(head, root.left) or self.isSubPath(head, root.right)\n def issame(self, head, root):\n if not head:\n return True\n if not root:\n return False\n if head.val != root.val:\n return False\n return self.issame(head.next, root.left) or self.issame(head.next, root.right)", + "title": "1367. Linked List in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(ListNode head) Initializes the object with the head of the singly-linked list head .", + "int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 3, 2, 2, 3]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.", + "image": "https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 57.7%) | Memory: 44.32 MB (Top 46.5%)\n\nclass Solution {\n int N = 0;\n ListNode head = null;\n public Solution(ListNode head) {\n this.head = head;\n }\n \n public int getRandom() {\n ListNode p = this.head;\n int i = 1, ans = 0;\n while (p != null) {\n if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i\n p = p.next;\n i ++;\n }\n return ans;\n }\n}", + "title": "382. Linked List Random Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(ListNode head) Initializes the object with the head of the singly-linked list head .", + "int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 3, 2, 2, 3]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.", + "image": "https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 95.6%) | Memory: 20.10 MB (Top 30.35%)\n\nclass Solution:\n def __init__(self, head: Optional[ListNode]):\n self.ll=[]\n while head:\n self.ll.append(head.val)\n head=head.next\n def getRandom(self) -> int:\n return self.ll[randint(0, len(self.ll)-1)]\n", + "title": "382. Linked List Random Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c , the key might get long pressed , and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.", + "description_images": [], + "constraints": [ + "1 <= name.length, typed.length <= 1000", + "name and typed consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:name = \"alex\", typed = \"aaleex\"\nOutput:true\nExplanation:'a' and 'e' in 'alex' were long pressed.", + "image": null + }, + { + "text": "Example 2: Input:name = \"saeed\", typed = \"ssaaedd\"\nOutput:false\nExplanation:'e' must have been pressed twice, but it was not in the typed output.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.52%) | Memory: 42.1 MB (Top 54.01%)\nclass Solution {\n public boolean isLongPressedName(String name, String typed) {\n int i = 0;\n int j = 0;\n int m = name.length();\n int n = typed.length();\n\n while(j < n)\n {\n if(i < m && name.charAt(i) == typed.charAt(j))\n {\n i++;\n j++;\n }\n else if(j > 0 && typed.charAt(j) == typed.charAt(j-1))\n {\n j++;\n }\n else\n {\n return false;\n }\n }\n\n return i == m;\n }\n}", + "title": "925. Long Pressed Name", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c , the key might get long pressed , and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.", + "description_images": [], + "constraints": [ + "1 <= name.length, typed.length <= 1000", + "name and typed consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:name = \"alex\", typed = \"aaleex\"\nOutput:true\nExplanation:'a' and 'e' in 'alex' were long pressed.", + "image": null + }, + { + "text": "Example 2: Input:name = \"saeed\", typed = \"ssaaedd\"\nOutput:false\nExplanation:'e' must have been pressed twice, but it was not in the typed output.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n #dic for memoization\n\t\tdic = {}\n def dfs(i, j):\n if (i, j) in dic:\n return dic[(i, j)]\n \n\t\t\t#see if there is any case where both i and j reach to the end, cuz that will be the true condition\n\t\t\t#I only need one True \n if i >= len(name):\n return j == len(typed)\n\t\t\t#we iterated through the end of typed, and not yet for name \n if j >= len(typed):\n return False\n \n\t\t\t#if the characters don't match, return False\n if name[i] != typed[j]:\n dic[(i, j)] = False\n return False\n \n\t\t\t#if the two characters match\n\t\t\t#two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1))\n\t\t\t#return if any of them is True, which means that i, j reach to the end as aforementioned\n dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1)\n return dic[(i, j)]\n \n\t\t#start from index 0, 0\n return dfs(0, 0)\n", + "title": "925. Long Pressed Name", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s , return true if the longest contiguous segment of 1 ' s is strictly longer than the longest contiguous segment of 0 ' s in s , or return false otherwise . Note that if there are no 0 's, then the longest continuous segment of 0 's is considered to have a length 0 . The same applies if there is no 1 's.", + "description_images": [], + "constraints": [ + "For example, in s = \" 11 01 000 10\" the longest continuous segment of 1 s has length 2 , and the longest continuous segment of 0 s has length 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"\nOutput:true\nExplanation:The longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"111000\"\nOutput:false\nExplanation:The longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"110100010\"\nOutput:false\nExplanation:The longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 92.84%) | Memory: 41.5 MB (Top 80.00%)\n\nclass Solution {\n public boolean checkZeroOnes(String s) {\n int length1 = 0;\n int length0 = 0;\n\n int i = 0;\n while(i < s.length()){\n int temp = 0;\n while(i < s.length() && s.charAt(i) == '1'){ //counting 1s\n temp++;\n i++;\n }\n length1 = Math.max(temp,length1);\n temp = 0;\n while(i < s.length() && s.charAt(i) == '0'){ // counting 0s\n temp++;\n i++;\n }\n length0 = Math.max(temp,length0);\n }\n return length1 > length0;\n }\n}", + "title": "1869. Longer Contiguous Segments of Ones than Zeros", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a binary string s , return true if the longest contiguous segment of 1 ' s is strictly longer than the longest contiguous segment of 0 ' s in s , or return false otherwise . Note that if there are no 0 's, then the longest continuous segment of 0 's is considered to have a length 0 . The same applies if there is no 1 's.", + "description_images": [], + "constraints": [ + "For example, in s = \" 11 01 000 10\" the longest continuous segment of 1 s has length 2 , and the longest continuous segment of 0 s has length 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"\nOutput:true\nExplanation:The longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"111000\"\nOutput:false\nExplanation:The longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"110100010\"\nOutput:false\nExplanation:The longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 65.12%) | Memory: 13.9 MB (Top 66.60%)\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n s1 = s.split('0')\n s0 = s.split('1')\n r1 = max([len(i) for i in s1])\n r0 = max([len(i) for i in s0])\n return r1>r0", + "title": "1869. Longer Contiguous Segments of Ones than Zeros", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2 . subdir1 contains a file file1.ext and subdirectory subsubdir1 . subdir2 contains a subdirectory subsubdir2 , which contains a file file2.ext . In text form, it looks like this (with ⟶ representing the tab character): If we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\" . Note that the '\\n' and '\\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s . Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\" . Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension , where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system . If there is no file in the system, return 0 . Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg" + ], + "constraints": [ + "1 <= input.length <= 10^4", + "input may contain lowercase or uppercase English letters, a new line character '\\n' , a tab character '\\t' , a dot '.' , a space ' ' , and digits.", + "All file and directory names have positive length." + ], + "examples": [ + { + "text": "Example 1: Input:input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\nOutput:20\nExplanation:We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg" + }, + { + "text": "Example 2: Input:input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\nOutput:32\nExplanation:We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg" + }, + { + "text": "Example 3: Input:input = \"a\"\nOutput:0\nExplanation:We do not have any files, just a single directory named \"a\".", + "image": null + }, + { + "text": "dir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.1%) | Memory: 40.51 MB (Top 47.9%)\n\nclass Solution {\n public int lengthLongestPath(String input) {\n var stack = new ArrayDeque();\n int max = 0;\n String[] lines = input.split(\"\\n\");\n for(var line: lines) {\n int tabs = countTabs(line);\n while(tabs < stack.size()) {\n stack.pop();\n }\n int current = stack.isEmpty() ? 0: stack.peek();\n int nameLength = line.length() - tabs;\n if(isFilename(line)) {\n max = Math.max(max, current + nameLength);\n } else {\n stack.push(current + nameLength + 1);\n }\n }\n return max;\n }\n \n private int countTabs(String s) {\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) != '\\t') return i;\n }\n return 0;\n }\n \n private boolean isFilename(String s) {\n return s.lastIndexOf(\".\") != -1;\n }\n \n}\n", + "title": "388. Longest Absolute File Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2 . subdir1 contains a file file1.ext and subdirectory subsubdir1 . subdir2 contains a subdirectory subsubdir2 , which contains a file file2.ext . In text form, it looks like this (with ⟶ representing the tab character): If we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\" . Note that the '\\n' and '\\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s . Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\" . Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension , where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system . If there is no file in the system, return 0 . Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg" + ], + "constraints": [ + "1 <= input.length <= 10^4", + "input may contain lowercase or uppercase English letters, a new line character '\\n' , a tab character '\\t' , a dot '.' , a space ' ' , and digits.", + "All file and directory names have positive length." + ], + "examples": [ + { + "text": "Example 1: Input:input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\nOutput:20\nExplanation:We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg" + }, + { + "text": "Example 2: Input:input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\nOutput:32\nExplanation:We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg" + }, + { + "text": "Example 3: Input:input = \"a\"\nOutput:0\nExplanation:We do not have any files, just a single directory named \"a\".", + "image": null + }, + { + "text": "dir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef lengthLongestPath(self, input: str) -> int:\n\t\tif \".\" not in input:\n\t\t\treturn 0\n\n\t\ta=input.split(\"\\n\")\n\t\tfiles=[]\n\t\tfor i in a:\n\t\t\tif \".\" in i:\n\t\t\t\tfiles.append(i)\n\n\t\tfinal=[]\n\t\tfor i in range(len(files)):\n\t\t\tfile=files[i]\n\t\t\tlvl=file.count(\"\\t\")\n\t\t\tidx=a.index(file)-1\n\t\t\tsave=[files[i].replace(\"\\t\",\"\")]\n\t\t\tfor j in range(lvl):\n\t\t\t\twhile a[idx].count(\"\\t\")!=lvl-1:\n\t\t\t\t\tidx-=1\n\t\t\t\tlvl=a[idx].count(\"\\t\")\n\t\t\t\tsave.append(a[idx].replace(\"\\t\",\"\"))\n\t\t\t\tidx-=1\n\t\t\tfinal.append(save)\n\n\t\tfinal=list(map(\"/\".join,final))\n\t\treturn len(max(final,key=len))", + "title": "388. Longest Absolute File Path", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums . Recall that a subsequence of an array nums is a list nums[i 1 ], nums[i 2 ], ..., nums[i k ] with 0 <= i 1 < i 2 < ... < i k <= nums.length - 1 , and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1 ).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "0 <= nums[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,12]\nOutput:4\nExplanation:The whole array is an arithmetic sequence with steps of length = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,7,2,10]\nOutput:3\nExplanation:The longest arithmetic subsequence is [4,7,10].", + "image": null + }, + { + "text": "Example 3: Input:nums = [20,1,15,3,10,5,8]\nOutput:4\nExplanation:The longest arithmetic subsequence is [20,15,10,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 440 ms (Top 73.2%) | Memory: 70.79 MB (Top 29.5%)\n\nclass Solution \n{\n public int longestArithSeqLength(int[] nums) \n {\n int n = nums.length;\n int longest = 0;\n Map[] dp = new HashMap[n];\n \n for (int i = 0; i < n; i++) \n {\n dp[i] = new HashMap<>();\n \n for (int j = 0; j < i; j++) \n {\n int diff = nums[i] - nums[j];\n dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1);\n longest = Math.max(longest, dp[i].get(diff));\n }\n }\n \n return longest;\n }\n}", + "title": "1027. Longest Arithmetic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums . Recall that a subsequence of an array nums is a list nums[i 1 ], nums[i 2 ], ..., nums[i k ] with 0 <= i 1 < i 2 < ... < i k <= nums.length - 1 , and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1 ).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "0 <= nums[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,12]\nOutput:4\nExplanation:The whole array is an arithmetic sequence with steps of length = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,7,2,10]\nOutput:3\nExplanation:The longest arithmetic subsequence is [4,7,10].", + "image": null + }, + { + "text": "Example 3: Input:nums = [20,1,15,3,10,5,8]\nOutput:4\nExplanation:The longest arithmetic subsequence is [20,15,10,5].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7591 ms (Top 12.82%) | Memory: 21.8 MB (Top 96.69%)\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = [[1]*1001 for i in range(len(nums))]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n d = nums[j] - nums[i] + 500\n dp[j][d] = max(dp[i][d]+1,dp[j][d])\n return max([max(i) for i in dp])", + "title": "1027. Longest Arithmetic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr and an integer difference , return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference . A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i], difference <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4], difference = 1\nOutput:4\nExplanation:The longest arithmetic subsequence is [1,2,3,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,5,7], difference = 1\nOutput:1\nExplanation:The longest arithmetic subsequence is any single element.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput:4\nExplanation:The longest arithmetic subsequence is [7,5,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 77.18%) | Memory: 57.40 MB (Top 33.18%)\n\nclass Solution\n{\npublic\n int longestSubsequence(int[] arr, int difference)\n {\n // Storing the final answer as 1\n int length = arr.length, max_length = 1;\n HashMap Terms_till_now = new HashMap<>();\n for (int i = 0; i < length; i++)\n {\n /*\n Find the number of terms, till curr_element - difference , say terms\n Mapping 1 + n to the current term of the sequence, i.e. curr_element\n */\n int terms = ((Terms_till_now.get(arr[i] - difference) == null) ? 0 : Terms_till_now.get(arr[i] - difference));\n Terms_till_now.put(arr[i], 1 + terms);\n max_length = Math.max(max_length, 1 + terms);\n }\n return max_length;\n }\n}\n", + "title": "1218. Longest Arithmetic Subsequence of Given Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr and an integer difference , return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference . A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i], difference <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4], difference = 1\nOutput:4\nExplanation:The longest arithmetic subsequence is [1,2,3,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,5,7], difference = 1\nOutput:1\nExplanation:The longest arithmetic subsequence is any single element.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput:4\nExplanation:The longest arithmetic subsequence is [7,5,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 548 ms (Top 98.07%) | Memory: 27.7 MB (Top 73.31%)\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n d = defaultdict(int)\n for num in arr:\n if num - difference in d:\n d[num] = d[num - difference] + 1\n else:\n d[num] = 1\n return max((d[x] for x in d))\n", + "title": "1218. Longest Arithmetic Subsequence of Given Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary string s and a positive integer k . Return the length of the longest subsequence of s that makes up a binary number less than or equal to k . Note:", + "description_images": [], + "constraints": [ + "The subsequence can contain leading zeroes .", + "The empty string is considered to be equal to 0 .", + "A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001010\", k = 5\nOutput:5\nExplanation:The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00101001\", k = 1\nOutput:6\nExplanation:\"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.60 MB (Top 67.53%)\n\nclass Solution {\n public int longestSubsequence(String s, int k) {\n int z=0;\n //count zero\n for(int i=0;ik\n for(int i=s.length()-1;i>=0;i--){\n \n if(num+base>k)break;\n if(s.charAt(i)=='1'){\n num+=base;\n }\n else {\n\t\t\t//remove already taken zeros from zeros count\n z--;\n }\n base*=2;\n len++;\n }\n \n return len+z;\n }\n}\n", + "title": "2311. Longest Binary Subsequence Less Than or Equal to K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary string s and a positive integer k . Return the length of the longest subsequence of s that makes up a binary number less than or equal to k . Note:", + "description_images": [], + "constraints": [ + "The subsequence can contain leading zeroes .", + "The empty string is considered to be equal to 0 .", + "A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001010\", k = 5\nOutput:5\nExplanation:The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00101001\", k = 1\nOutput:6\nExplanation:\"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 62.5%) | Memory: 16.50 MB (Top 18.75%)\n\nclass Solution:\n def longestSubsequence(self, s: str, k: int) -> int:\n \n end, n = len(s)-1, s.count(\"0\") \n while end >=0 and int(s[end:], 2)<= k:\n end-=1\n return n+ s[end+1:].count(\"1\")\n \n", + "title": "2311. Longest Binary Subsequence Less Than or Equal to K", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string text . You should split it to k substrings (subtext 1 , subtext 2 , ..., subtext k ) such that: Return the largest possible value of k .", + "description_images": [], + "constraints": [ + "subtext i is a non-empty string.", + "The concatenation of all the substrings is equal to text (i.e., subtext 1 + subtext 2 + ... + subtext k == text ).", + "subtext i == subtext k - i + 1 for all valid values of i (i.e., 1 <= i <= k )." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput:7\nExplanation:We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"merchant\"\nOutput:1\nExplanation:We can split the string on \"(merchant)\".", + "image": null + }, + { + "text": "Example 3: Input:text = \"antaprezatepzapreanta\"\nOutput:11\nExplanation:We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int longestDecomposition(String text) {\n int n = text.length(); \n for (int i = 0; i < n/2; i++) \n if (text.substring(0, i + 1).equals(text.substring(n-1-i, n))) \n return 2+longestDecomposition(text.substring(i+1, n-1-i));\n return (n==0)?0:1;\n}\n}", + "title": "1147. Longest Chunked Palindrome Decomposition", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string text . You should split it to k substrings (subtext 1 , subtext 2 , ..., subtext k ) such that: Return the largest possible value of k .", + "description_images": [], + "constraints": [ + "subtext i is a non-empty string.", + "The concatenation of all the substrings is equal to text (i.e., subtext 1 + subtext 2 + ... + subtext k == text ).", + "subtext i == subtext k - i + 1 for all valid values of i (i.e., 1 <= i <= k )." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput:7\nExplanation:We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"merchant\"\nOutput:1\nExplanation:We can split the string on \"(merchant)\".", + "image": null + }, + { + "text": "Example 3: Input:text = \"antaprezatepzapreanta\"\nOutput:11\nExplanation:We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 82 ms (Top 23.89%) | Memory: 13.9 MB (Top 78.76%)\n\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n left, right = 0, len(text) - 1\n sol, last_left = 0, 0\n a, b = deque(), deque()\n while right > left:\n a.append(text[left])\n b.appendleft(text[right])\n if a == b:\n sol += 2\n last_left = left\n a, b = deque(), deque()\n right -= 1\n left += 1\n if left == right or left > last_left + 1:\n sol += 1\n return max(sol, 1)\n", + "title": "1147. Longest Chunked Palindrome Decomposition", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\" .", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 200", + "0 <= strs[i].length <= 200", + "strs[i] consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"flower\",\"flow\",\"flight\"]\nOutput:\"fl\"", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"dog\",\"racecar\",\"car\"]\nOutput:\"\"\nExplanation:There is no common prefix among the input strings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 21.11%) | Memory: 42.4 MB (Top 35.11%)\nclass TrieNode{\n TrieNode[] childs;\n int frequency;\n TrieNode(){\n childs = new TrieNode[26];\n this.frequency = 1;\n }\n}\n\nclass Solution {\n\n TrieNode root = new TrieNode();\n\n public String longestCommonPrefix(String[] strs) {\n if(strs.length == 0) return \"\";\n if(strs.length == 1) return strs[0];\n for(String str : strs){\n insertIntoTrie(str.toLowerCase());\n }\n return findCommonPrefix(strs[0], strs.length);\n }\n\n private void insertIntoTrie(String str) {\n TrieNode ptr = root;\n for(int i=0; i str:\n cmp=strs[0]\n for i in range(1,len(strs)):\n l=0\n if (len(cmp)>len(strs[i])):\n l+=len(strs[i])\n else:\n l+=len(cmp)\n ans=\"\"\n for j in range(l):\n if (cmp[j]!=strs[i][j]):\n if (j==0):\n return \"\"\n else:\n break\n else:\n ans+=strs[i][j]\n cmp=ans\n return cmp\n\t\t\nUpvote If you Like!!!", + "title": "14. Longest Common Prefix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a country of n cities numbered from 0 to n - 1 . In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once , but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the i th friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all . A subpath of a path is a contiguous sequence of cities within that path.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "m == paths.length", + "2 <= m <= 10^5", + "sum(paths[i].length) <= 10^5", + "0 <= paths[i][j] < n", + "The same city is not listed multiple times consecutively in paths[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]\nOutput:2\nExplanation:The longest common subpath is [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, paths = [[0],[1],[2]]\nOutput:0\nExplanation:There is no common subpath shared by the three paths.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]\nOutput:1\nExplanation:The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 460 ms (Top 16.0%) | Memory: 73.80 MB (Top 56.0%)\n\nclass Solution {\n \n //mod \n long mod = (long)(Math.pow(10,11) + 3);\n \n long p = 100003;\n \n long p_i[];\n \n public int longestCommonSubpath(int n, int[][] paths) {\n \n //min length will be 1 \n int min = 1;\n \n //max length will be the (path of min length) \n \n int max = Integer.MAX_VALUE;\n \n for(int path[] : paths){\n max = Math.min(max,path.length);\n }\n \n //now we will pre calculate the the powers of base\n //and upto max only bcoz that's the longest subarray \n //we are going to deal with\n p_i = new long[max + 1];\n \n p_i[0] = 1;\n \n for(int i=1;i<=max;i++){\n //mod multiplication\n p_i[i] = mulmod(p_i[i-1],p,mod);\n }\n \n int ans = 0;\n \n while(min <= max){\n \n int mid = (min + max) / 2;\n \n if(solve(mid,paths)){\n //if this length satisfies \n //we are moving to right \n //checking length greater than this\n ans = mid;\n min = mid + 1;\n }else{\n //else smaller\n max = mid - 1;\n }\n \n }\n \n return ans;\n \n }\n \n public boolean solve(int len,int paths[][]){\n \n Map map = new HashMap<>();\n \n // now for each path we are going to calculate the \n // hash value for each subpath of length -> len\n // and store the frequency of hash in map\n // and if for a hash value the frequency equals \n // paths.length it means it exists in all path array\n // so return true\n \n for(int path[] : paths){\n \n long hash = 0l;\n \n // we are using a set for storing hash value of particular len for \n // each path beacuse there is a possibility \n // that a subpath repeats multiple times \n // in a path so it directly updating in map\n // will lead to wrong count\n Set set = new HashSet<>();\n \n // hash is calculated as\n // let's say len is 3\n // (p^3 * (path[0]+1)) + (p^2 * (path[1]+1)) + (p^1 * (path[2] + 1))\n \n // now when we are moving forward \n // and we need to update the hash value \n // we can do it like \n // delete (p^3 * (path[index-len]+1)) from prev_hash\n // so now the hash will become -> \n // (p^2 * (path[1]+1)) + (p^1 * (path[2] + 1))\n // and then multiply prev_hash by p\n // (p^3 * (path[1]+1)) + (p^2 * (path[2] + 1))\n // now add (p^1 * (path[3]+1))\n // so hash becomes->\n //(p^3 * (path[1]+1)) + (p^2 * (path[2] + 1)) + (p^1 * (path[3]+1))\n \n //using this way we avoid calculating invmod\n //so easier to implement\n \n for(int i=0;i 0){\n if((b&1) == 1){\n ans = mulmod(ans,val,mod);\n }\n val = mulmod(val,val,mod);\n b = b >> 1;\n }\n \n return ans % mod;\n }\n \n long mulmod(long a, long b,long mod)\n {\n return ((a%mod) * (b%mod)) % mod;\n }\n \n \n \n}\n", + "title": "1923. Longest Common Subpath", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a country of n cities numbered from 0 to n - 1 . In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once , but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the i th friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all . A subpath of a path is a contiguous sequence of cities within that path.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "m == paths.length", + "2 <= m <= 10^5", + "sum(paths[i].length) <= 10^5", + "0 <= paths[i][j] < n", + "The same city is not listed multiple times consecutively in paths[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]\nOutput:2\nExplanation:The longest common subpath is [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, paths = [[0],[1],[2]]\nOutput:0\nExplanation:There is no common subpath shared by the three paths.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]\nOutput:1\nExplanation:The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4090 ms (Top 34.15%) | Memory: 51.70 MB (Top 78.05%)\n\nclass Solution:\n def longestCommonSubpath(self, n, paths) -> int:\n def get_common_subpath_hashes(k):\n \"\"\"Return hash values of common subpaths of length k, or empty set if none exists\"\"\"\n def get_subpath_hashes(path):\n hash, coeff = 0, pow(n, k-1, mod)\n for i in range(len(path)+1):\n if i < k:\n hash = (hash*n + path[i]) % mod\n else:\n yield hash\n if i < len(path):\n hash = ((hash-coeff*path[i-k])*n + path[i]) % mod \n return reduce(set.intersection, (set(get_subpath_hashes(p)) for p in paths))\n \n\t # can be replaced with a pre-computed large prime\n mod = self._generate_large_prime(int(1e18), int(9e18))\n low, high = 1, min(len(p) for p in paths)+1\n while low < high:\n mid = (low+high) // 2\n if get_common_subpath_hashes(mid):\n low = mid + 1\n else:\n high = mid\n return high - 1\n \n def _generate_large_prime(self, lower, upper):\n \"\"\"Generate a prime between [lower, upper)\"\"\"\n def is_prime(n, trials=50):\n def witness(a, n):\n x0 = pow(a, u, n)\n for _ in range(t):\n x = x0**2 % n\n if x == 1 and x0 != 1 and x0 != n-1:\n return True\n x0 = x\n return True if x0 != 1 else False\n\n t, u = 0, n-1\n while u%2 == 0:\n t, u = t+1, u>>1\n return not any(witness(randrange(1, n), n) for _ in range(trials))\n return next(r for r in iter(lambda: randrange(lower, upper), None) if is_prime(r))\n", + "title": "1923. Longest Common Subpath", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"\nOutput:3\nExplanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"\nOutput:3\nExplanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"\nOutput:0\nExplanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 78.9%) | Memory: 48.13 MB (Top 74.6%)\n\nclass Solution {\n public int longestCommonSubsequence(String text1, String text2) {\n int m = text1.length();\n int n = text2.length();\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n dp[i][j] = 1 + dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n return dp[m][n];\n }\n}\n", + "title": "1143. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"\nOutput:3\nExplanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"\nOutput:3\nExplanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"\nOutput:0\nExplanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n def lcs(ind1,ind2):\n prev=[0 for i in range(ind2+1)]\n curr=[0 for i in range(ind2+1)]\n \n for i in range(1,ind1+1):\n for j in range(1,ind2+1):\n if text1[i-1]==text2[j-1]:\n curr[j]=1+prev[j-1]\n \n else:\n curr[j]=max(prev[j],curr[j-1])\n prev=list(curr) # remember to use a new list for prev\n\n return prev[-1]\n \n \n ans=lcs(len(text1),len(text2))\n return ans\n", + "title": "1143. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]\nOutput:4\nExplanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestConsecutive(int[] nums) {\n Set storage = new HashSet();\n \n for(int i = 0; i < nums.length; i++){\n storage.add(nums[i]);\n }\n \n int maxL = 0;\n \n for(int i = 0; i < nums.length; i++){\n \n //check if nums[i] id present in set or not\n //since after checking in set we remove the element from \n //set, there is no double calculation for same sequence \n if(storage.contains(nums[i])){\n storage.remove(nums[i]);\n \n int dec = nums[i]-1;\n int inc = nums[i]+1;\n int tempL = 1;\n \n //check both ways from nums[i] and calculate \n //tempL. since we are removing elements from \n //set we only calculate once for every sequence.\n \n while(storage.contains(dec)){\n storage.remove(dec);\n dec--;\n tempL++;\n }\n \n while(storage.contains(inc)){\n storage.remove(inc);\n inc++;\n tempL++;\n }\n \n \n maxL = Math.max(maxL, tempL);\n \n }\n }\n \n return maxL;\n }\n}\n", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]\nOutput:4\nExplanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def longestConsecutive(self, nums):\n ans=0\n nums=set(nums)\n count=0\n for i in nums:\n if i-1 not in nums:\n j=i\n count=0\n while j in nums:\n count+=1\n j+=1\n ans=max(ans,count) \n return ans\n", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an unsorted array of integers nums , return the length of the longest continuous increasing subsequence (i.e. subarray) . The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r ( l < r ) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r , nums[i] < nums[i + 1] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]\nOutput:3\nExplanation:The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]\nOutput:1\nExplanation:The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 45.4 MB (Top 76.62%)\nclass Solution {\n public int findLengthOfLCIS(int[] nums) {\n int count = 1;\n int maxCount = 1;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] > nums[i - 1]) {\n count++;\n } else {\n maxCount = Math.max(count, maxCount);\n count = 1;\n }\n }\n maxCount = Math.max(count, maxCount);\n return maxCount;\n }\n}", + "title": "674. Longest Continuous Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an unsorted array of integers nums , return the length of the longest continuous increasing subsequence (i.e. subarray) . The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r ( l < r ) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r , nums[i] < nums[i + 1] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]\nOutput:3\nExplanation:The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]\nOutput:1\nExplanation:The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 416 ms (Top 5.00%) | Memory: 15.4 MB (Top 49.36%)\n\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n count=0\n for i in range(len(nums)):\n a=nums[i]\n c=1\n for j in range(i+1, len(nums)):\n if nums[j]>a:\n a=nums[j]\n c+=1\n else:\n break\n count=max(count, c)\n return count", + "title": "674. Longest Continuous Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4\nOutput:2\nExplanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5\nOutput:4\nExplanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n \n public int longestSubarray(int[] nums, int limit) {\n \n Deque increasing = new LinkedList(); // To keep track of Max_value index\n Deque decreasing = new LinkedList(); // To keep track of Min_value index\n \n int i = 0 ;\n int j = 0 ;\n int max_length = 0 ;\n \n while(j < nums.length){\n \n while(!increasing.isEmpty() && nums[increasing.peekLast()] >= nums[j]){\n increasing.pollLast() ;\n }\n \n increasing.add(j);\n \n while(!decreasing.isEmpty() && nums[decreasing.peekLast()] <= nums[j]){\n decreasing.pollLast() ;\n }\n \n decreasing.add(j);\n \n int max_val = nums[decreasing.peekFirst()] ;\n int min_val = nums[increasing.peekFirst()] ;\n \n if(max_val-min_val <= limit){\n max_length = Math.max(max_length , j-i+1);\n }else{\n \n // If maximum absolute diff > limit , then remove from dequeue and increase i\n while(i<=j && nums[decreasing.peekFirst()] - nums[increasing.peekFirst()] > limit ){\n \n if(!increasing.isEmpty() && increasing.peekFirst() == i){\n increasing.pollFirst() ;\n }\n \n if(!decreasing.isEmpty() && decreasing.peekFirst() == i){\n decreasing.pollFirst() ;\n }\n \n i++ ; \n } \n \n }\n \n \n j++ ;\n }\n \n return max_length ;\n }\n}\n\n", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4\nOutput:2\nExplanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5\nOutput:4\nExplanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# max absolte diff within a subarray is subarray max substracted by subarray min\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n q = collections.deque() # monotonic decreasing deque to compute subarray max, index of\n q2 = collections.deque() # monotonic increasing deque to compute subarray min, index of\n \n # sliding window\n res = left = 0\n for right in range(len(nums)):\n # pop monotocity-violating numbers from right end\n while q and nums[q[-1]] <= nums[right]:\n q.pop()\n q.append(right)\n \n # pop monotocity-violating numbers from right end\n while q2 and nums[q2[-1]] >= nums[right]:\n q2.pop()\n q2.append(right)\n \n # sliding window\n while left < right and q and q2 and nums[q[0]] - nums[q2[0]] > limit:\n # compress window from left pointer\n if q and q[0] == left:\n q.popleft()\n \n # compress left pointer\n if q2 and q2[0] == left:\n q2.popleft()\n \n left += 1\n \n if nums[q[0]] - nums[q2[0]] <= limit:\n res = max(res, right - left + 1)\n \n return res\n", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from node i , then edges[i] == -1 . Return the length of the longest cycle in the graph . If no cycle exists, return -1 . A cycle is a path that starts and ends at the same node.", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [3,3,4,2,3]\nOutput:3\nExplanation:The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" + }, + { + "text": "Example 2: Input:edges = [2,-1,3,1]\nOutput:-1\nExplanation:There are no cycles in this graph.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 81.42%) | Memory: 99.3 MB (Top 65.13%)\nclass Solution {\n public int longestCycle(int[] edges) {\n int[] map = new int[edges.length];\n int result = -1;\n\n for (int i = 0; i < edges.length; i++)\n result = Math.max(result, helper(i, 1, edges, map));\n\n return result;\n }\n\n int helper(int index, int total, int[] edges, int[] map) {\n if (index == -1 || map[index] == -1)\n return -1;\n\n if (map[index] != 0)\n return total - map[index];\n\n map[index] = total;\n int result = helper(edges[index], total + 1, edges, map);\n map[index] = -1;\n\n return result;\n }\n}", + "title": "2360. Longest Cycle in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from node i , then edges[i] == -1 . Return the length of the longest cycle in the graph . If no cycle exists, return -1 . A cycle is a path that starts and ends at the same node.", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [3,3,4,2,3]\nOutput:3\nExplanation:The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" + }, + { + "text": "Example 2: Input:edges = [2,-1,3,1]\nOutput:-1\nExplanation:There are no cycles in this graph.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestCycle(self, edges: List[int]) -> int:\n preorder = [-1 for _ in range(len(edges))]\n self.ans = -1\n self.pre = 0\n \n def dfs(self, i: int, st: int) -> None:\n preorder[i] = self.pre\n self.pre += 1\n \n if edges[i] == -1:\n return\n elif preorder[edges[i]] == -1:\n dfs(self, edges[i], st)\n return\n elif preorder[edges[i]] >= st:\n self.ans = max(self.ans, preorder[i] - preorder[edges[i]] + 1)\n return\n \n for i in range(len(edges)):\n if preorder[i] == -1 and edges[i] != -1:\n dfs(self, i, self.pre)\n \n return self.ans\n", + "title": "2360. Longest Cycle in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , consider all duplicated substrings : (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\" .", + "description_images": [], + "constraints": [ + "2 <= s.length <= 3 * 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"banana\"\nOutput:\"ana\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestDupSubstring(String s) {\n long[] e = new long[s.length()+1];\n long h = 1;\n int p = 991919;\n long M = 957689076713L;\n for (int i = 0; i < e.length; i++){\n e[i]=h;\n h=h*p%M;\n }\n int lo = 0, hi = s.length(), st = 0, end = 0;\n while(lo < hi){\n int mid = (lo+hi+1)>>1;\n Set seen = new HashSet<>();\n long hash = 0;\n boolean ok=false;\n for (int i = 0; i < s.length() && !ok; i++){\n hash = (hash*p+s.charAt(i))%M;\n if (i >= mid){\n hash = (hash - e[mid]*(s.charAt(i-mid))%M+M)%M;\n }\n if (i >= mid-1 && !seen.add(hash)){\n end = i;\n st = i-mid+1;\n ok=true;\n }\n }\n if (ok){\n lo=mid;\n }else{\n hi=mid-1;\n }\n }\n return lo == 0? \"\": s.substring(st, end+1);\n }\n}\n", + "title": "1044. Longest Duplicate Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , consider all duplicated substrings : (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\" .", + "description_images": [], + "constraints": [ + "2 <= s.length <= 3 * 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"banana\"\nOutput:\"ana\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2799 ms (Top 43.0%) | Memory: 16.80 MB (Top 93.0%)\n\nclass Solution:\n def longestDupSubstring(self, s: str) -> str:\n left = 0\n right = 1\n res = \"\"\n n = len(s)\n while right len(res):\n res = s[left:right]\n right+=1\n continue\n left+=1\n if left == right:\n right+=1\n return res", + "title": "1044. Longest Duplicate Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s , return the longest happy prefix of s . Return an empty string \"\" if no such prefix exists.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"level\"\nOutput:\"l\"\nExplanation:s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababab\"\nOutput:\"abab\"\nExplanation:\"abab\" is the largest prefix which is also suffix. They can overlap in the original string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 89.72%) | Memory: 43.2 MB (Top 90.81%)\nclass Solution {\n public String longestPrefix(String s) {\n int n=s.length();\n char arr[] = s.toCharArray();\n int lps[]=new int[n];\n for(int i=1; i0 && arr[j]!=arr[i]){\n j=lps[j-1]; // DEACREASING TILL WE FIND ITS PREFIX WHICH IS EQUAL TO ITS SUFFIX\n }\n if(arr[j]==arr[i]){// IF ITS PREV IS SAME AS CURRENT THEN INCREAMENT IT\n j++;\n }\n lps[i]=j; // SAVE WHATEVER THE VALUE IS\n }\n int j=lps[n-1];\n StringBuilder sb = new StringBuilder();\n for(int i=0;i0){ // ELSE DEACREASE TILL WE ARE NOT FINDING IT\n j=lps[j-1];\n i--;\n }\n }\n return s.substring(0,j);\n\n */", + "title": "1392. Longest Happy Prefix", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s , return the longest happy prefix of s . Return an empty string \"\" if no such prefix exists.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"level\"\nOutput:\"l\"\nExplanation:s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababab\"\nOutput:\"abab\"\nExplanation:\"abab\" is the largest prefix which is also suffix. They can overlap in the original string.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 186 ms (Top 90.2%) | Memory: 21.02 MB (Top 32.3%)\n\nclass Solution:\n def longestPrefix(self, s: str) -> str:\n n=len(s)\n lps=[0]*n\n j=0\n for i in range(1,n):\n while s[i]!=s[j] and j>0:\n j=lps[j-1]\n\n if s[i]==s[j]:\n lps[i]=j+1\n j+=1\n\n return s[:lps[-1]]", + "title": "1392. Longest Happy Prefix", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is called happy if it satisfies the following conditions: Given three integers a , b , and c , return the longest possible happy string . If there are multiple longest happy strings, return any of them . If there is no such string, return the empty string \"\" . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "s only contains the letters 'a' , 'b' , and 'c' .", + "s does not contain any of \"aaa\" , \"bbb\" , or \"ccc\" as a substring.", + "s contains at most a occurrences of the letter 'a' .", + "s contains at most b occurrences of the letter 'b' .", + "s contains at most c occurrences of the letter 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 1, c = 7\nOutput:\"ccaccbcc\"\nExplanation:\"ccbccacc\" would also be a correct answer.", + "image": null + }, + { + "text": "Example 2: Input:a = 7, b = 1, c = 0\nOutput:\"aabaa\"\nExplanation:It is the only correct answer in this case.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.66 MB (Top 66.7%)\n\n/*\nThe idea behid this problem\n1. Here we start by taking the size as the sum of a, b, c.\n2. Then we use 3 variables A, B, C to count the occurance of a, b, c.\n3. Now we iterate until the size, and \n -> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.\n \n4. Finally return the string.\n*/\nclass Solution {\n public String longestDiverseString(int a, int b, int c) {\n int totalSize = a + b + c;\n int A = 0;\n int B = 0;\n int C = 0;\n StringBuilder sb = new StringBuilder();\n for (int i=0; i=b && a>=c && A<2) || (B==2 && a>0) || (C==2 && a>0)) {\n sb.append(\"a\");\n a -= 1;\n A += 1;\n B = 0;\n C = 0;\n }\n // check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be added\n else if ((b>=a && b>=c && B<2) || (A==2 && b>0) || (C==2 && b>0)) {\n sb.append(\"b\");\n b -= 1;\n B += 1;\n A = 0;\n C = 0;\n }\n // checks c is largest and its count still < 2 or B and A = 2 and there are still c that can be added\n else if ((c>=a && c>=b && C<2) || (A==2 && c>0) || (B==2 && c>0)) {\n sb.append(\"c\");\n c -= 1;\n C += 1;\n A = 0;\n B = 0;\n }\n }\n return sb.toString();\n }\n}", + "title": "1405. Longest Happy String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string s is called happy if it satisfies the following conditions: Given three integers a , b , and c , return the longest possible happy string . If there are multiple longest happy strings, return any of them . If there is no such string, return the empty string \"\" . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "s only contains the letters 'a' , 'b' , and 'c' .", + "s does not contain any of \"aaa\" , \"bbb\" , or \"ccc\" as a substring.", + "s contains at most a occurrences of the letter 'a' .", + "s contains at most b occurrences of the letter 'b' .", + "s contains at most c occurrences of the letter 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 1, c = 7\nOutput:\"ccaccbcc\"\nExplanation:\"ccbccacc\" would also be a correct answer.", + "image": null + }, + { + "text": "Example 2: Input:a = 7, b = 1, c = 0\nOutput:\"aabaa\"\nExplanation:It is the only correct answer in this case.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef longestDiverseString(self, a: int, b: int, c: int) -> str:\n\t\tpq = []\n\t\tif a > 0: heapq.heappush(pq,(-a,'a')) \n\t\tif b > 0: heapq.heappush(pq,(-b,'b')) \n\t\tif c > 0: heapq.heappush(pq,(-c,'c'))\n\n\t\tans = ''\n\t\twhile pq:\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif len(ans)>1 and ans[-1] == ans[-2] == ch:\n\t\t\t\tif not pq: break\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\n\t\treturn ans\n", + "title": "1405. Longest Happy String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1 . Given an integer array nums , return the length of its longest harmonious subsequence among all its possible subsequences . A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,2,5,2,3,7]\nOutput:5\nExplanation:The longest harmonious subsequence is [3,2,2,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 74.55%) | Memory: 54.5 MB (Top 74.21%)\nclass Solution {\n public static int firstOccurence(int[] arr,int target)\n {\n int res=-1;\n int start=0;\n int end=arr.length-1;\n while(start<=end)\n {\n int mid=start + (end-start)/2;\n if(arr[mid]==target)\n {\n res=mid;\n end=mid-1;\n }\n else if(arr[mid]maxLen)\n maxLen=b-a+1;\n }\n }\n return maxLen;\n }\n}", + "title": "594. Longest Harmonious Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1 . Given an integer array nums , return the length of its longest harmonious subsequence among all its possible subsequences . A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,2,5,2,3,7]\nOutput:5\nExplanation:The longest harmonious subsequence is [3,2,2,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\nfrom collections import Counter\nclass Solution:\n\tdef findLHS(self, nums: List[int]) -> int:\n\t\tcounter=Counter(nums)\n\t\t# values=set(nums)\n\t\tres=0\n\t\t# if len(values)==1:return 0\n\t\tfor num in nums:\n\t\t\tif num+1 in counter or num-1 in counter:\n\t\t\t\tres=max(res,counter[num]+counter.get(num+1,0))\n\t\t\t\tres=max(res,counter[num]+counter.get(num-1,0))\n\n\t\treturn res\n\"\"", + "title": "594. Longest Harmonious Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of lowercase letters and an integer k . We call a string t ideal if the following conditions are satisfied: Return the length of the longest ideal string . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25 , not 1 .", + "description_images": [], + "constraints": [ + "t is a subsequence of the string s .", + "The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"acfgbd\", k = 2\nOutput:4\nExplanation:The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", k = 3\nOutput:4\nExplanation:The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 49.30%) | Memory: 48.5 MB (Top 48.18%)\nclass Solution {\n public int longestIdealString(String s, int k) {\n int DP[] = new int[26], ans = 1;\n\n for (int ch = 0, n = s.length(); ch < n; ch++) {\n int i = s.charAt(ch) - 'a';\n DP[i] = DP[i] + 1;\n\n for (int j = Math.max(0, i - k); j <= Math.min(25, i + k); j++)\n if (j != i)\n DP[i] = Math.max(DP[i], DP[j] + 1);\n\n ans = Math.max(ans, DP[i]);\n }\n\n return ans;\n }\n}", + "title": "2370. Longest Ideal Subsequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s consisting of lowercase letters and an integer k . We call a string t ideal if the following conditions are satisfied: Return the length of the longest ideal string . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25 , not 1 .", + "description_images": [], + "constraints": [ + "t is a subsequence of the string s .", + "The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"acfgbd\", k = 2\nOutput:4\nExplanation:The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", k = 3\nOutput:4\nExplanation:The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 381 ms (Top 86.75%) | Memory: 17.40 MB (Top 70.48%)\n\nclass Solution:\n def longestIdealString(self, s: str, k: int) -> int:\n dp = [0] * 26\n for ch in s:\n i = ord(ch) - ord(\"a\")\n dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)])\n return max(dp)\n", + "title": "2370. Longest Ideal Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 200", + "0 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput:4\nExplanation:The longest increasing path is[1, 2, 6, 9].", + "image": "https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput:4\nExplanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.", + "image": "https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 22.67%) | Memory: 61.2 MB (Top 10.43%)\nclass Solution {\n public int longestIncreasingPath(int[][] matrix) {\n int[][] memo = new int[matrix.length][matrix[0].length];\n int longestPath = 0;\n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n dfs(matrix, i, j, memo);\n longestPath = Math.max(longestPath, memo[i][j]);\n }\n }\n return longestPath;\n }\n\n private void dfs(int[][] matrix, int i, int j, int[][] memo) {\n if (memo[i][j] != 0)\n return;\n int[][] dirs = {{-1,0}, {0,1}, {1,0}, {0,-1}};\n int max = 0;\n for (int k = 0; k < dirs.length; k++) {\n int x = dirs[k][0] + i;\n int y = dirs[k][1] + j;\n if (isValid(matrix, x, y) && matrix[x][y] > matrix[i][j]) {\n // Get/compute the largest path for that index\n if (memo[x][y] == 0) { // If longest path doesn't exist for that path then compute it\n dfs(matrix, x, y, memo);\n }\n max = Math.max(max, memo[x][y]);\n }\n }\n memo[i][j] = 1 + max;\n }\n\n private boolean isValid(int[][] matrix, int i, int j) {\n if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)\n return false;\n return true;\n }\n}", + "title": "329. Longest Increasing Path in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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).", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 200", + "0 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput:4\nExplanation:The longest increasing path is[1, 2, 6, 9].", + "image": "https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput:4\nExplanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.", + "image": "https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n ROWS, COLS = len(matrix), len(matrix[0])\n dp = {}\n \n def dfs(r, c, prevVal):\n if (r < 0 or r == ROWS or\n c < 0 or c == COLS or\n matrix[r][c] <= prevVal):\n return 0\n if (r, c) in dp:\n return dp[(r, c)]\n res = 1\n res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))\n res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))\n dp[(r, c)] = res\n return res\n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, -1)\n return max(dp.values())\n", + "title": "329. Longest Increasing Path in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2500", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,9,2,5,3,7,101,18]\nOutput:4\nExplanation:The longest increasing subsequence is [2,3,7,101], therefore the length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,3,2,3]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7,7,7,7]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 68.33%) | Memory: 43.7 MB (Top 85.25%)\nclass Solution {\n public int lengthOfLIS(int[] nums) {\n\n ArrayList lis = new ArrayList<>();\n\n for(int num:nums){\n\n int size = lis.size();\n\n if(size==0 ||size>0 && num>lis.get(size-1)){\n lis.add(num);\n }else{\n int insertIndex = bs(lis,num);\n lis.set(insertIndex,num);\n }\n }\n\n return lis.size();\n }\n\n int bs(List list, int target){\n int lo = 0;\n int hi = list.size()-1;\n\n while(lo int:\n\n # Initialize the result\n res = []\n\n # Binary search to find the index of the smallest number in result that is greater than or equal to the target\n def binarySearch(l, r, target):\n\n nonlocal res\n\n # If the left and right pointers meet, we have found the smallest number that is greater than the target\n if l == r:\n return l\n\n # Find the mid pointer\n m = (r - l) // 2 + l\n\n # If the number at the mid pointer is equal to the target, we have found a number that is equal to the target\n if res[m] == target:\n return m\n\n # Else if the number at the mid poitner is less than the target, we search the right side\n elif res[m] < target:\n return binarySearch(m + 1, r, target)\n\n # Else, we search the left side including the number at mid pointer because it is one of the possible solution since it is greater than the target\n else:\n return binarySearch(l, m, target)\n\n # Iterate through all numbers\n for n in nums:\n\n # If the last number in the result is less than the current number\n if not res or res[-1] < n:\n\n # Append the current number to the result\n res.append(n)\n\n continue\n\n # Else, find the index of the smallest number in the result that is greater than or equal to the current number\n i = binarySearch(0, len(res) - 1, n)\n\n # Replace the current number at such index\n res[i] = n\n\n return len(res)\n", + "title": "300. Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array arr , return the length of the longest subarray, which is a mountain . Return 0 if there is no mountain subarray.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,4,7,3,2,5]\nOutput:5\nExplanation:The largest mountain is [1,4,7,3,2] which has length 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,2,2]\nOutput:0\nExplanation:There is no mountain.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 81.75%) | Memory: 52.8 MB (Top 24.19%)\nclass Solution {\n public int longestMountain(int[] arr) {\n if (arr.length < 3)\n return 0;\n int max = 0;\n for (int i = 0; i < arr.length; i++) {\n if (isPeak(arr, i)) {\n int leftLength = left(arr, i);\n int rightLength = right(arr, i);\n max = Math.max(max, leftLength + rightLength + 1);\n }\n }\n return max;\n }\n\n public int left(int[] arr, int i) {\n int j = i - 1;\n while (j >= 0 && arr[j] < arr[j + 1])\n j--;\n return i - (j + 1);\n }\n\n public int right(int[] arr, int i) {\n int j = i + 1;\n while (j < arr.length && arr[j - 1] > arr[j])\n j++;\n return j - (i + 1);\n }\n\n public boolean isPeak(int[] arr, int i) {\n return i - 1 >= 0 && i + 1 < arr.length && arr[i - 1] < arr[i] && arr[i + 1] < arr[i];\n }\n}", + "title": "845. Longest Mountain in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array arr , return the length of the longest subarray, which is a mountain . Return 0 if there is no mountain subarray.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,4,7,3,2,5]\nOutput:5\nExplanation:The largest mountain is [1,4,7,3,2] which has length 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,2,2]\nOutput:0\nExplanation:There is no mountain.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestMountain(self, arr: List[int]) -> int:\n if len(arr) < 3:\n return 0\n \n max_up, max_down = [1 for _ in arr], [1 for _ in arr]\n \n for i, x in enumerate(arr):\n if i == 0:\n continue\n if x > arr[i - 1]:\n max_up[i] = max_up[i - 1] + 1\n \n for j, y in reversed(list(enumerate(arr))):\n if j == len(arr) - 1:\n continue\n if y > arr[j + 1]:\n max_down[j] = max_down[j + 1] + 1\n \n return max(\n x + y - 1 if x > 1 and y > 1 else 0 \n for x, y in zip(max_up, max_down)\n )\n", + "title": "845. Longest Mountain in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s , return the longest substring of s that is nice . If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"YazaAay\"\nOutput:\"aAa\"\nExplanation:\"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Bb\"\nOutput:\"Bb\"\nExplanation:\"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"c\"\nOutput:\"\"\nExplanation:There are no nice substrings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestNiceSubstring(String s) {\n String result = \"\";\n // take first index, go from 0 to length-1 of the string\n\t\tfor (int i = 0;i 1 && result.length() < temp.length() && checkNice(temp)) result = temp;\n } \n }\n return result;\n }\n \n\t//validate Nice String check\n public boolean checkNice(String temp){\n //add substring to the set\n\t\tSet s = new HashSet<>();\n for (char ch : temp.toCharArray()) s.add(ch);\n \n\t\t// return false If you do not find both lower case and upper case in the sub string\n\t\t//for e.g 'aAa' substring added to set will have both a and A in the substring which is valid\n\t\t// 'azaA' substring will fail for 'z'\n\t\t// 'aaaaaaaa' will return \"\" as result\n\t\t//make sure that the substring contains both lower and upper case\n for (char ch : s)\n if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch))) return false; \n return true;\n }\n}\n", + "title": "1763. Longest Nice Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s , return the longest substring of s that is nice . If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"YazaAay\"\nOutput:\"aAa\"\nExplanation:\"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Bb\"\nOutput:\"Bb\"\nExplanation:\"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"c\"\nOutput:\"\"\nExplanation:There are no nice substrings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def divcon(s):\n\t\t # string with length 1 or less arent considered nice\n if len(s) < 2:\n return \"\"\n \n pivot = []\n # get every character that is not nice\n for i, ch in enumerate(s):\n if ch.isupper() and ch.lower() not in s:\n pivot.append(i)\n if ch.islower() and ch.upper() not in s:\n pivot.append(i)\n\t\t\t# if no such character return the string\n if not pivot:\n return s\n\t\t\t# divide the string in half excluding the char that makes the string not nice\n else:\n mid = (len(pivot)) // 2\n return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)\n \n return divcon(s)\n", + "title": "1763. Longest Nice Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome here.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"\nOutput:7\nExplanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:1\nExplanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 56.47%) | Memory: 40.7 MB (Top 92.38%)\nclass Solution {\n public int longestPalindrome(String s) {\n HashMap map = new HashMap<>();\n\n int evenNo = 0;\n int oddNo = 0;\n\n for ( int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (map.containsKey(c)) {\n map.put(c, map.get(c) + 1);\n } else {\n map.put(c, 1);\n }\n\n }\n for (Map.Entry e : map.entrySet()) {\n int n = (int) e.getValue();\n if (n % 2 != 0) {\n oddNo += n;\n }\n evenNo += (n / 2) * 2;\n }\n\n if (oddNo > 0) {\n evenNo += 1;\n }\n return evenNo;\n }\n}", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome here.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"\nOutput:7\nExplanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:1\nExplanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n letters = {} \n for letter in s: #count each letter and update letters dict\n if letter in letters:\n letters[letter] += 1\n else:\n letters[letter] = 1\n \n \n plus1 = 0 # if there is a letter with count of odd ans must +=1 \n ans = 0\n for n in letters.values():\n if n == 1: #1 can only appear in the middle of our word\n plus1 = 1\n elif n%2 == 0:\n ans += n\n else:\n ans += n - 1\n plus1 = 1\n \n return ans + plus1\n\n\n", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of strings words . Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order . Each element can be selected at most once . Return the length of the longest palindrome that you can create . If it is impossible to create any palindrome, return 0 . A palindrome is a string that reads the same forward and backward.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^5", + "words[i].length == 2", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"lc\",\"cl\",\"gg\"]\nOutput:6\nExplanation:One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput:8\nExplanation:One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"cc\",\"ll\",\"xx\"]\nOutput:2\nExplanation:One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 99.82%) | Memory: 57.9 MB (Top 94.96%)\nclass Solution {\n public int longestPalindrome(String[] words) {\n int[][] freq = new int[26][26];//array for all alphabet combinations\n for (String word : words)\n freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word\n int left = 0;//to store freq counts\n boolean odd = false;\n for (int i = 0; i != 26; i++) {//iterate over our array\n odd |= (freq[i][i] & 1) == 1;//means odd number of freq for similar words are there\n left += freq[i][i] / 2;\n for (int j = i + 1; j != 26; j++)//nested iteration to find non similar pairs\n left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present\n }\n int res = left * 2 * 2;//res from total freq found!!\n if (odd){\n res+=2;// if odd then adding 2\n }\n return res;\n }\n}", + "title": "2131. Longest Palindrome by Concatenating Two Letter Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words . Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order . Each element can be selected at most once . Return the length of the longest palindrome that you can create . If it is impossible to create any palindrome, return 0 . A palindrome is a string that reads the same forward and backward.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^5", + "words[i].length == 2", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"lc\",\"cl\",\"gg\"]\nOutput:6\nExplanation:One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput:8\nExplanation:One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"cc\",\"ll\",\"xx\"]\nOutput:2\nExplanation:One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def longestPalindrome(self, words):\n wc = collections.Counter(words)\n aa = 0 # count how many words contain only two identical letters like 'aa'\n center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively\n\n for w, c in wc.items():\n if w[0] == w[1]: # like 'aa', 'bb', ...\n aa += c // 2 * 2 # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively\n # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n if c % 2 == 1: center = 2\n else:\n abba += min(wc[w], wc[w[::-1]]) * 0.5 # will definitely double counting\n return aa * 2 + int(abba) * 4 + center\n", + "title": "2131. Longest Palindrome by Concatenating Two Letter Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , find the longest palindromic subsequence 's length in s . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bbbab\"\nOutput:4\nExplanation:One possible longest palindromic subsequence is \"bbbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"\nOutput:2\nExplanation:One possible longest palindromic subsequence is \"bb\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestPalindromeSubseq(String s) {\n \tStringBuilder sb = new StringBuilder(s);\n \t sb.reverse();\n \t String s2 = sb.toString();\n return longestCommonSubsequence(s,s2);\n }\n public int longestCommonSubsequence(String text1, String text2) {\n int [][]dp = new int[text1.length()+1][text2.length()+1]; \n for(int i= text1.length()-1;i>=0;i--){\n for(int j = text2.length()-1;j>=0;j--){\n char ch1 = text1.charAt(i);\n char ch2 = text2.charAt(j);\n if(ch1==ch2) // diagnal\n dp[i][j]= 1+dp[i+1][j+1];\n else// right,down considering not matchning char from s1 and skipping s2 \n //considering not matchning char from s2 and skipping s1\n dp[i][j] = Math.max(dp[i][j+1],dp[i+1][j]);\n \n }\n }\n return dp[0][0];\n }\n}\n", + "title": "516. Longest Palindromic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , find the longest palindromic subsequence 's length in s . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bbbab\"\nOutput:4\nExplanation:One possible longest palindromic subsequence is \"bbbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"\nOutput:2\nExplanation:One possible longest palindromic subsequence is \"bb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1248 ms (Top 52.16%) | Memory: 34.60 MB (Top 50.8%)\n\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n dp = [[0 for _ in range(len(s))] for _ in range(len(s))]\n for k in range(1, len(s) + 1):\n for i in range(len(s) - k + 1):\n j = k + i - 1\n if i == j:\n dp[i][j] = 1\n elif i + 1 == j and s[i] == s[j]:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i+1][j-1] + 2\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return dp[0][-1]\n", + "title": "516. Longest Palindromic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the longest palindromic substring in s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"\nOutput:\"bab\"\nExplanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"\nOutput:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n String max = \"\";\n \n private void checkPalindrome(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {\n if (r - l >= max.length()) {\n max = s.substring(l, r + 1);\n } \n\n l--;\n r++;\n }\n }\n \n public String longestPalindrome(String s) {\n for (int i = 0; i < s.length(); i++) {\n checkPalindrome(s, i, i);\n checkPalindrome(s, i, i + 1); \n }\n \n return max;\n }\n}\n", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the longest palindromic substring in s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"\nOutput:\"bab\"\nExplanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"\nOutput:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 643 ms (Top 86.54%) | Memory: 14 MB (Top 58.84%)\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n res = \"\"\n for i in range(len(s)):\n left, right = i - 1, i + 1\n\n while (right < len(s) and s[right] == s[i]):\n right += 1\n\n while (0 <= left < right < len(s) and s[left] == s[right]):\n left, right = left - 1, right + 1\n\n res = s[left+1:right] if right - left-1 > len(res) else res\n return res", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1 . The tree is represented by a 0-indexed array parent of size n , where parent[i] is the parent of node i . Since node 0 is the root, parent[0] == -1 . You are also given a string s of length n , where s[i] is the character assigned to node i . Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.", + "description_images": [], + "constraints": [ + "n == parent.length == s.length", + "1 <= n <= 10^5", + "0 <= parent[i] <= n - 1 for all i >= 1", + "parent[0] == -1", + "parent represents a valid tree.", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:parent = [-1,0,0,1,1,2], s = \"abacbe\"\nOutput:3\nExplanation:The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/testingdrawio.png" + }, + { + "text": "Example 2: Input:parent = [-1,0,0,0], s = \"aabc\"\nOutput:3\nExplanation:The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/graph2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 151 ms (Top 22.99%) | Memory: 94.00 MB (Top 86.21%)\n\nclass Solution {\n int longestPathValue = 1; // variable to store the length of the longest path\n\n public int longestPath(int[] parent, String s) {\n // create an adjacency list representation of the tree\n Map> adj = new HashMap<>();\n for(int i = 1; i < parent.length; i++){\n int j = parent[i];\n adj.putIfAbsent(j, new LinkedList<>());\n adj.get(j).add(i);\n }\n // call dfs on the root of the tree\n dfs(0, adj, s);\n return longestPathValue;\n }\n\n public int dfs(int node, Map> adj, String s){\n // if the node is a leaf node, return 1\n if(!adj.containsKey(node)) return 1;\n int max = 0, secondMax = 0;\n // for each neighbor of the node\n for(int nbrNode : adj.get(node)){\n int longestPathFromNbrNode = dfs(nbrNode , adj, s);\n // if the characters at the current node and its neighbor are the same, ignore the neighbor\n if(s.charAt(node) == s.charAt(nbrNode)) continue;\n // update max and secondMax with the longest path from the neighbor node\n if(longestPathFromNbrNode > max){\n secondMax = max;\n max = longestPathFromNbrNode;\n }else if(longestPathFromNbrNode > secondMax){\n secondMax = longestPathFromNbrNode;\n }\n }\n // update longestPathValue with the longest path that includes the current node\n longestPathValue = Math.max(longestPathValue, max+secondMax+1);\n return max+1;\n }\n}\n\n", + "title": "2246. Longest Path With Different Adjacent Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1 . The tree is represented by a 0-indexed array parent of size n , where parent[i] is the parent of node i . Since node 0 is the root, parent[0] == -1 . You are also given a string s of length n , where s[i] is the character assigned to node i . Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.", + "description_images": [], + "constraints": [ + "n == parent.length == s.length", + "1 <= n <= 10^5", + "0 <= parent[i] <= n - 1 for all i >= 1", + "parent[0] == -1", + "parent represents a valid tree.", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:parent = [-1,0,0,1,1,2], s = \"abacbe\"\nOutput:3\nExplanation:The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/testingdrawio.png" + }, + { + "text": "Example 2: Input:parent = [-1,0,0,0], s = \"aabc\"\nOutput:3\nExplanation:The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/graph2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestPath(self, parent: list[int], s: str) -> int:\n def l_path_and_chain(tree: dict[int, list[int]], s: str, root: int) -> tuple[int, int]:\n lp = lc1 = lc2 = 0\n for child, path, chain in ((c, *l_path_and_chain(tree, s, c)) for c in tree[root]):\n lp = max(lp, path)\n if s[child] != s[root]: *_, lc2, lc1 = sorted((chain, lc2, lc1))\n\n return max(lp, lc1 + lc2 + 1), lc1 + 1\n\n t = defaultdict(list)\n for c, p in enumerate(parent): t[p].append(c)\n return l_path_and_chain(t, s, 0)[0]\n", + "title": "2246. Longest Path With Different Adjacent Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only uppercase English letters.", + "0 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABAB\", k = 2\nOutput:4\nExplanation:Replace the two 'A's with two 'B's or vice versa.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AABABBA\", k = 1\nOutput:4\nExplanation:Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 85.13%) | Memory: 42.60 MB (Top 48.1%)\n\n/**\n * Time O(n)\n * Space O(26)\n */\nclass Solution {\n public int characterReplacement(String s, int k) {\n // Space O(26)\n int[] dic = new int[26];\n int start = 0;\n int maxLen = 0;\n // Time O(n)\n for (int end = 0; end < s.length(); end++) {\n maxLen = Math.max(maxLen, ++dic[s.charAt(end) - 'A']);\n if (end - start + 1 > maxLen + k) {\n dic[s.charAt(start) - 'A']--;\n start++;\n }\n }\n return s.length() - start;\n }\n}\n", + "title": "424. Longest Repeating Character Replacement", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only uppercase English letters.", + "0 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABAB\", k = 2\nOutput:4\nExplanation:Replace the two 'A's with two 'B's or vice versa.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AABABBA\", k = 1\nOutput:4\nExplanation:Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n # Initialize variables\n window_start = 0\n max_length = 0\n max_count = 0\n char_count = {}\n\n # Traverse the string s\n for window_end in range(len(s)):\n # Increment the count of the current character\n char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1\n # Update the maximum count seen so far\n max_count = max(max_count, char_count[s[window_end]])\n \n # Shrink the window if required\n if window_end - window_start + 1 > max_count + k:\n char_count[s[window_start]] -= 1\n window_start += 1\n \n # Update the maximum length of the substring with repeating characters seen so far\n max_length = max(max_length, window_end - window_start + 1)\n \n return max_length\n", + "title": "424. Longest Repeating Character Replacement", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of words where each word consists of lowercase English letters. word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A without changing the order of the other characters to make it equal to word B . A word chain is a sequence of words [word 1 , word 2 , ..., word k ] with k >= 1 , where word 1 is a predecessor of word 2 , word 2 is a predecessor of word 3 , and so on. A single word is trivially a word chain with k == 1 . Return the length of the longest possible word chain with words chosen from the given list of words .", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a predecessor of \"ab a c\" , while \"cba\" is not a predecessor of \"bcad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput:4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput:5\nExplanation:All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].", + "image": null + }, + { + "text": "Example 3: Input:words = [\"abcd\",\"dbqca\"]\nOutput:1\nExplanation:The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n Boolean compareForIncreaseByOne(String str1,String str2){\n //str 1 will be long than str2\n int first=0;\n int second=0;\n if(str1.length() != (str2.length() + 1)){\n return false;\n }\n while(first < str1.length()){\n if(second < str2.length() && str1.charAt(first) == str2.charAt(second)){\n first++;\n second++;\n }else{\n first++;\n }\n }\n if(first == str1.length() && second == str2.length()){\n return true;\n }\n return false;\n }\n \n public int longestStrChain(String[] words) {\n int N = words.length;\n Arrays.sort(words,(a,b) -> a.length()-b.length()); //as Sequence/Subset are not ordered\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j] + 1;\n maxi = Math.max(maxi,dp[i]);\n }\n }\n }//for neds\n return maxi;\n }\n}\n", + "title": "1048. Longest String Chain", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of words where each word consists of lowercase English letters. word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A without changing the order of the other characters to make it equal to word B . A word chain is a sequence of words [word 1 , word 2 , ..., word k ] with k >= 1 , where word 1 is a predecessor of word 2 , word 2 is a predecessor of word 3 , and so on. A single word is trivially a word chain with k == 1 . Return the length of the longest possible word chain with words chosen from the given list of words .", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a predecessor of \"ab a c\" , while \"cba\" is not a predecessor of \"bcad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput:4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput:5\nExplanation:All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].", + "image": null + }, + { + "text": "Example 3: Input:words = [\"abcd\",\"dbqca\"]\nOutput:1\nExplanation:The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 123 ms (Top 85.4%) | Memory: 16.81 MB (Top 58.4%)\n\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \n words.sort(key=len)\n dic = {}\n \n for i in words:\n dic[ i ] = 1\n \n for j in range(len(i)):\n \n # creating words by deleting a letter\n successor = i[:j] + i[j+1:]\n if successor in dic:\n dic[ i ] = max (dic[i], 1 + dic[successor])\n \n res = max(dic.values())\n return res", + "title": "1048. Longest String Chain", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]\nOutput:3\nExplanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]\nOutput:5\nExplanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]\nOutput:2\nExplanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums) {\n List groups = new ArrayList<>();\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0)\n groups.add(nums[i]);\n if (nums[i] == 1) {\n int count = 0;\n while (i < nums.length && nums[i] == 1) {\n count++;\n i++;\n }\n groups.add(count);\n if (i < nums.length && nums[i] == 0)\n groups.add(0);\n }\n }\n int max = 0;\n if (groups.size() == 1) {\n return groups.get(0) - 1;\n }\n for (int i = 0; i < groups.size(); i++) {\n if (i < groups.size() - 2) {\n max = Math.max(max, groups.get(i) + groups.get(i+2));\n } else {\n max = Math.max(max, groups.get(i));\n }\n }\n \n return max;\n }\n}\n", + "title": "1493. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]\nOutput:3\nExplanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]\nOutput:5\nExplanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]\nOutput:2\nExplanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n pre, suf = [1]*n, [1]*n\n if nums[0] == 0:pre[0] = 0\n if nums[-1] == 0:suf[-1] = 0\n \n for i in range(1, n):\n if nums[i] == 1 and nums[i-1] == 1:\n pre[i] = pre[i-1] + 1\n elif nums[i] == 0:\n pre[i] = 0\n \n for i in range(n-2, -1, -1):\n if nums[i] == 1 and nums[i+1] == 1:\n suf[i] = suf[i+1] + 1\n elif nums[i] == 0:\n suf[i] = 0\n \n ans = 0\n for i in range(n):\n if i == 0:\n ans = max(ans, suf[i+1])\n elif i == n-1:\n ans = max(ans, pre[i-1])\n else:\n ans = max(ans, pre[i-1] + suf[i+1])\n \n return ans", + "title": "1493. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of length n , and an integer k . You are tasked to find the longest subsequence repeated k times in string s . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s , where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s . If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string .", + "description_images": [], + "constraints": [ + "For example, \"bba\" is repeated 2 times in the string \"bababcba\" , because the string \"bbabba\" , constructed by concatenating \"bba\" 2 times, is a subsequence of the string \" b a bab c ba \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"letsleetcode\", k = 2\nOutput:\"let\"\nExplanation:There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.", + "image": "https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png" + }, + { + "text": "Example 2: Input:s = \"bb\", k = 2\nOutput:\"b\"\nExplanation:The longest subsequence repeated 2 times is \"b\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\", k = 2\nOutput:\"\"\nExplanation:There is no subsequence repeated 2 times. Empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 56.76%) | Memory: 43.2 MB (Top 86.49%)\nclass Solution {\n char[] A;\n public String longestSubsequenceRepeatedK(String s, int k) {\n A = s.toCharArray();\n Queue queue = new ArrayDeque<>();\n queue.offer(\"\");\n String ans = \"\";\n int[] count = new int[26];\n BitSet bit = new BitSet();\n for (char ch : A) if (++count[ch-'a'] >= k){\n bit.set(ch-'a');\n }\n while(!queue.isEmpty()){\n String sb = queue.poll();\n for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i+1)){\n String res = sb+(char)(i+'a');\n if (check(k, res)){\n ans = res;\n queue.offer(res);\n }\n }\n }\n return ans;\n }\n\n private boolean check(int k, String s){\n int cnt = 0;\n for (char ch : A){\n if (s.charAt(cnt%s.length()) == ch && ++cnt >= k * s.length()){\n return true;\n }\n }\n return false;\n }\n}", + "title": "2014. Longest Subsequence Repeated k Times", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of length n , and an integer k . You are tasked to find the longest subsequence repeated k times in string s . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s , where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s . If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string .", + "description_images": [], + "constraints": [ + "For example, \"bba\" is repeated 2 times in the string \"bababcba\" , because the string \"bbabba\" , constructed by concatenating \"bba\" 2 times, is a subsequence of the string \" b a bab c ba \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"letsleetcode\", k = 2\nOutput:\"let\"\nExplanation:There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.", + "image": "https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png" + }, + { + "text": "Example 2: Input:s = \"bb\", k = 2\nOutput:\"b\"\nExplanation:The longest subsequence repeated 2 times is \"b\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\", k = 2\nOutput:\"\"\nExplanation:There is no subsequence repeated 2 times. Empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n n = len(s)\n max_chunk_sz = n // k\n \n d = collections.Counter(s)\n chars = sorted([c for c in d if d[c] >= k], reverse=True)\n if not chars:\n return ''\n \n old_cand = chars\n for m in range(2, max_chunk_sz+1):\n new_cand = []\n for t in self.get_next_level(old_cand, chars):\n if self.find(s, t*k):\n new_cand.append(t)\n \n if len(new_cand) == 0:\n break\n old_cand = new_cand\n return old_cand[0]\n \n def get_next_level(self, cand, chars):\n for s in cand:\n for ch in chars:\n yield s + ch\n \n def find(self, s, t):\n # find subsequence t in s\n j = 0\n for i in range(len(s)):\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n return True\n return False\n", + "title": "2014. Longest Subsequence Repeated k Times", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is considered beautiful if it satisfies the following conditions: For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful , but \"uaeio\" , \"aeoiu\" , and \"aaaeeeooo\" are not beautiful . Given a string word consisting of English vowels, return the length of the longest beautiful substring of word . If no such substring exists, return 0 . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "Each of the 5 English vowels ( 'a' , 'e' , 'i' , 'o' , 'u' ) must appear at least once in it.", + "The letters must be sorted in alphabetical order (i.e. all 'a' s before 'e' s, all 'e' s before 'i' s, etc.)." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput:13\nExplanation:The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.", + "image": null + }, + { + "text": "Example 2: Input:word = \"aeeeiiiioooauuuaeiou\"\nOutput:5\nExplanation:The longest beautiful substring in word is \"aeiou\" of length 5.", + "image": null + }, + { + "text": "Example 3: Input:word = \"a\"\nOutput:0\nExplanation:There is no beautiful substring, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 192 ms (Top 11.20%) | Memory: 65.5 MB (Top 18.15%)\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n for(int i = 1;i verify = new HashSet<>();\n verify.add(word.charAt(i-1));\n while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){\n temp++;\n verify.add(word.charAt(i));\n i++;\n }\n max = verify.size() == 5 ? Math.max(max,temp) : max ;\n }\n\n return max;\n }\n}", + "title": "1839. Longest Substring Of All Vowels in Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string is considered beautiful if it satisfies the following conditions: For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful , but \"uaeio\" , \"aeoiu\" , and \"aaaeeeooo\" are not beautiful . Given a string word consisting of English vowels, return the length of the longest beautiful substring of word . If no such substring exists, return 0 . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "Each of the 5 English vowels ( 'a' , 'e' , 'i' , 'o' , 'u' ) must appear at least once in it.", + "The letters must be sorted in alphabetical order (i.e. all 'a' s before 'e' s, all 'e' s before 'i' s, etc.)." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput:13\nExplanation:The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.", + "image": null + }, + { + "text": "Example 2: Input:word = \"aeeeiiiioooauuuaeiou\"\nOutput:5\nExplanation:The longest beautiful substring in word is \"aeiou\" of length 5.", + "image": null + }, + { + "text": "Example 3: Input:word = \"a\"\nOutput:0\nExplanation:There is no beautiful substring, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n g = ''\n count = m = 0\n for x in word:\n if g and x < g[-1]:\n count = 0\n g = ''\n if not g or x > g[-1]:\n g += x\n count += 1\n if g == 'aeiou':\n m = max(m, count)\n return m\n", + "title": "1839. Longest Substring Of All Vowels in Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string s . You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k , both of which are used to describe k queries. The i th query updates the character in s at index queryIndices[i] to the character queryCharacters[i] . Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the i th query is performed.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "k == queryCharacters.length == queryIndices.length", + "1 <= k <= 10^5", + "queryCharacters consists of lowercase English letters.", + "0 <= queryIndices[i] < s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babacc\", queryCharacters = \"bcb\", queryIndices = [1,3,3]\nOutput:[3,3,4]\nExplanation:- 1stquery updates s = \"bbbacc\". The longest substring consisting of one repeating character is \"bbb\" with length 3.\n- 2ndquery updates s = \"bbbccc\". \n The longest substring consisting of one repeating character can be \"bbb\" or \"ccc\" with length 3.\n- 3rdquery updates s = \"bbbbcc\". The longest substring consisting of one repeating character is \"bbbb\" with length 4.\nThus, we return [3,3,4].", + "image": null + }, + { + "text": "Example 2: Input:s = \"abyzz\", queryCharacters = \"aa\", queryIndices = [2,1]\nOutput:[2,3]\nExplanation:- 1stquery updates s = \"abazz\". The longest substring consisting of one repeating character is \"zz\" with length 2.\n- 2ndquery updates s = \"aaazz\". The longest substring consisting of one repeating character is \"aaa\" with length 3.\nThus, we return [2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 87 ms (Top 83.33%) | Memory: 76.70 MB (Top 22.22%)\n\nclass Solution {\n class TreeNode {\n //range\n int start;\n int end;\n \n //conti left char\n char leftChar;\n int leftCharLen;\n \n //conti right char\n char rightChar;\n int rightCharLen;\n \n int max;\n \n TreeNode left;\n TreeNode right;\n \n TreeNode(int start, int end) {\n this.start = start;\n this.end = end;\n left = null;\n right = null;\n }\n }\n\n public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) {\n char[] sChar = s.toCharArray();\n char[] qChar = queryCharacters.toCharArray();\n \n TreeNode root = buildTree(sChar, 0, sChar.length - 1);\n \n int[] result = new int[qChar.length];\n \n for (int i = 0; i < qChar.length; i++) {\n updateTree(root, queryIndices[i], qChar[i]);\n result[i] = root.max;\n }\n return result;\n }\n \n private TreeNode buildTree(char[] s, int from, int to) {\n if (from > to) return null;\n TreeNode root = new TreeNode(from, to);\n if (from == to) {\n root.max = 1;\n root.rightChar = root.leftChar = s[from];\n root.leftCharLen = root.rightCharLen = 1;\n return root;\n }\n \n int middle = from + (to - from) / 2;\n \n root.left = buildTree(s, from, middle);\n root.right = buildTree(s, middle + 1, to);\n \n updateNode(root);\n return root;\n \n }\n \n private void updateTree(TreeNode root, int index, char c) {\n if (root == null || root.start > index || root.end < index) {\n return;\n }\n if (root.start == index && root.end == index) {\n root.leftChar = root.rightChar = c;\n return;\n }\n updateTree(root.left, index, c);\n updateTree(root.right, index, c);\n \n updateNode(root);\n \n }\n \n private void updateNode(TreeNode root) {\n if (root == null) return;\n root.leftChar = root.left.leftChar;\n root.leftCharLen = root.left.leftCharLen;\n root.rightChar = root.right.rightChar;\n root.rightCharLen = root.right.rightCharLen;\n root.max = Math.max(root.left.max, root.right.max);\n if (root.left.rightChar == root.right.leftChar) {\n int len = root.left.rightCharLen + root.right.leftCharLen;\n if (root.left.leftChar == root.left.rightChar && root.left.leftCharLen == root.left.end - root.left.start + 1) {\n root.leftCharLen = len;\n }\n if (root.right.leftChar == root.right.rightChar && root.right.leftCharLen == root.right.end - root.right.start + 1) {\n root.rightCharLen = len;\n }\n root.max = Math.max(root.max, len);\n }\n }\n}\n", + "title": "2213. Longest Substring of One Repeating Character", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed string s . You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k , both of which are used to describe k queries. The i th query updates the character in s at index queryIndices[i] to the character queryCharacters[i] . Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the i th query is performed.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "k == queryCharacters.length == queryIndices.length", + "1 <= k <= 10^5", + "queryCharacters consists of lowercase English letters.", + "0 <= queryIndices[i] < s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babacc\", queryCharacters = \"bcb\", queryIndices = [1,3,3]\nOutput:[3,3,4]\nExplanation:- 1stquery updates s = \"bbbacc\". The longest substring consisting of one repeating character is \"bbb\" with length 3.\n- 2ndquery updates s = \"bbbccc\". \n The longest substring consisting of one repeating character can be \"bbb\" or \"ccc\" with length 3.\n- 3rdquery updates s = \"bbbbcc\". The longest substring consisting of one repeating character is \"bbbb\" with length 4.\nThus, we return [3,3,4].", + "image": null + }, + { + "text": "Example 2: Input:s = \"abyzz\", queryCharacters = \"aa\", queryIndices = [2,1]\nOutput:[2,3]\nExplanation:- 1stquery updates s = \"abazz\". The longest substring consisting of one repeating character is \"zz\" with length 2.\n- 2ndquery updates s = \"aaazz\". The longest substring consisting of one repeating character is \"aaa\" with length 3.\nThus, we return [2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3460 ms (Top 87.5%) | Memory: 38.10 MB (Top 67.5%)\n\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n sl = SortedList()\n length = SortedList()\n curr = 0\n for char, it in itertools.groupby(s):\n c = sum(1 for _ in it)\n length.add(c)\n sl.add((curr, curr + c, char))\n curr += c\n ans = []\n for char, i in zip(queryCharacters, queryIndices):\n t = (i, math.inf, 'a')\n index = sl.bisect_right(t) - 1\n to_remove = [sl[index]]\n to_add = []\n left, right, original_char = to_remove[0]\n if original_char != char:\n length.remove(right - left)\n if right - left > 1:\n if i == left:\n left += 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n elif i == right - 1:\n right -= 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n else:\n to_add.append((left, i, original_char))\n length.add(i - left)\n to_add.append((i + 1, right, original_char))\n length.add(right - (i + 1))\n \n l, r = i, i + 1\n if index - 1 >= 0 and sl[index - 1][1:3] == (i, char):\n l, old_r, _ = sl[index - 1]\n to_remove.append(sl[index - 1])\n length.remove(old_r - l)\n if index + 1 < len(sl) and sl[index + 1][0] == i + 1 and sl[index + 1][2] == char:\n old_l, r, old_length = sl[index + 1]\n to_remove.append(sl[index + 1])\n length.remove(r - old_l)\n length.add(r - l)\n sl.add((l, r, char))\n for t in to_remove:\n sl.remove(t)\n sl.update(to_add)\n # print(sl)\n # print(length)\n ans.append(length[-1])\n\n return ans\n", + "title": "2213. Longest Substring of One Repeating Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabb\", k = 3\nOutput:3\nExplanation:The longest substring is \"aaa\", as 'a' is repeated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababbc\", k = 2\nOutput:5\nExplanation:The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1034 ms (Top 5.0%) | Memory: 40.34 MB (Top 79.2%)\n\n// Solution 1: O(n^2) brute force\n// time O(n^2)\n// space O(1)\nclass Solution {\n public int longestSubstring(String s, int k) {\n if (s == null || s.isEmpty() || k > s.length()) {\n return 0;\n }\n \n int[] map = new int[26]; // letter -> freq\n int n = s.length();\n int max = 0; // length of longest substring T so far\n for (int i = 0; i < n; i++) {\n Arrays.fill(map, 0);\n for (int j = i; j < n; j++) {\n map[s.charAt(j) - 'a']++; \n if (isValid(s, i, j, k, map)) {\n max = Math.max(max, j - i + 1);\n }\n }\n }\n \n return max;\n }\n \n // return true if each distinct character in the substring s[left..right] appear >= k times\n private boolean isValid(String s, int left, int right, int k, int[] map) {\n int numLetters = 0; // number of distinct letters\n int numLettersAtLeastK = 0;\n for (int num : map) {\n if (num > 0) {\n numLetters++;\n }\n \n if (num >= k) {\n numLettersAtLeastK++;\n }\n }\n \n return numLettersAtLeastK == numLetters;\n }\n}", + "title": "395. Longest Substring with At Least K Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s and an integer k , return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabb\", k = 3\nOutput:3\nExplanation:The longest substring is \"aaa\", as 'a' is repeated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababbc\", k = 2\nOutput:5\nExplanation:The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 57 ms (Top 73.85%) | Memory: 14.4 MB (Top 21.39%)\nfrom collections import Counter\n\nclass Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n return get_longest_substring(s, k)\n\ndef get_longest_substring(s, k):\n if len(s) == 0: return 0\n c = Counter(s)\n low_freq_char = set([char for char, freq in c.items() if freq < k])\n # base case\n if len(low_freq_char) == 0:\n return len(s)\n # recursively split str into substr\n division_points = [i for i in range(len(s)) if s[i] in low_freq_char]\n substr_lst = []\n # start\n substr_lst.append(s[:division_points[0]])\n # middle\n for i in range(len(division_points) - 1):\n substr_lst.append(s[division_points[i] + 1: division_points[i + 1]])\n # end\n substr_lst.append(s[division_points[-1] + 1:])\n return max([get_longest_substring(substr, k) for substr in substr_lst])", + "title": "395. Longest Substring with At Least K Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the length of the longest substring without repeating characters.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"\nOutput:3\nExplanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"\nOutput:1\nExplanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"\nOutput:3\nExplanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 310 ms (Top 7.97%) | Memory: 117.9 MB (Top 6.60%)\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Map hash = new HashMap<>();\n int count = 0;\n int ans = 0;\n for(int i=0; i < s.length(); i++){\n if(hash.containsKey(s.charAt(i))){\n i = hash.get(s.charAt(i)) + 1;\n hash.clear();\n count = 0;\n }\n if(!hash.containsKey(s.charAt(i))){\n hash.put(s.charAt(i), i);\n count++;\n ans = Math.max(ans, count);\n }\n }\n return ans;\n }\n}", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , find the length of the longest substring without repeating characters.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"\nOutput:3\nExplanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"\nOutput:1\nExplanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"\nOutput:3\nExplanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \n longest_s = ''\n curr_s = ''\n for i in s:\n if i not in curr_s:\n curr_s += i\n if len(curr_s) >= len(longest_s):\n longest_s = curr_s\n else:\n curr_s = curr_s[curr_s.index(i)+1:]+i\n \n return len(longest_s)\n", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "For i <= k < j : arr[k] > arr[k + 1] when k is odd, and arr[k] < arr[k + 1] when k is even.", + "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.", + "arr[k] > arr[k + 1] when k is even, and", + "arr[k] < arr[k + 1] when k is odd." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,4,2,10,7,8,8,1,9]\nOutput:5\nExplanation:arr[1] > arr[2] < arr[3] > arr[4] < arr[5]", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,12,16]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [100]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxTurbulenceSize(int[] arr) {\n if(arr.length == 1) {\n return 1;\n } \n int l = 0, r = 1;\n int diff = arr[l] - arr[r];\n int max;\n if(diff == 0) {\n l = 1;\n r = 1;\n max = 1;\n } else {\n l = 0;\n r = 1;\n max = 2;\n }\n for(int i = 1; r < arr.length-1; i++) {\n int nextdiff = arr[i] - arr[i+1];\n if(diff < 0) {\n if(nextdiff > 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n } else {\n if(nextdiff < 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n }\n diff = nextdiff;\n max = Math.max(max, r-l+1);\n }\n return max;\n }\n}\n", + "title": "978. Longest Turbulent Subarray", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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:", + "description_images": [], + "constraints": [ + "For i <= k < j : arr[k] > arr[k + 1] when k is odd, and arr[k] < arr[k + 1] when k is even.", + "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.", + "arr[k] > arr[k + 1] when k is even, and", + "arr[k] < arr[k + 1] when k is odd." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,4,2,10,7,8,8,1,9]\nOutput:5\nExplanation:arr[1] > arr[2] < arr[3] > arr[4] < arr[5]", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,12,16]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [100]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1152 ms (Top 13.10%) | Memory: 18.7 MB (Top 31.75%)\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n def cmp(a,b):\n if a == b: return 0\n if a > b : return 1\n return -1\n\n n = len(arr)\n ans = 1\n prev = 0\n for i in range(1,n):\n c = cmp(arr[i-1],arr[i])\n if c == 0:\n # we shift prev to i\n prev = i\n elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1:\n ans = ans if ans > i - prev + 1 else i - prev + 1\n prev = i\n return ans", + "title": "978. Longest Turbulent Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings a and b , return the length of the longest uncommon subsequence between a and b . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between two strings is a string that is a subsequence of one but not the other . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s .", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"cdc\"\nOutput:3\nExplanation:One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.", + "image": null + }, + { + "text": "Example 2: Input:a = \"aaa\", b = \"bbb\"\nOutput:3\nExplanation:The longest uncommon subsequences are \"aaa\" and \"bbb\".", + "image": null + }, + { + "text": "Example 3: Input:a = \"aaa\", b = \"aaa\"\nOutput:-1\nExplanation:Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.7 MB (Top 58.87%)\nclass Solution {\n public int findLUSlength(String a, String b) {\n if(a.equals(b)) return -1;\n return Math.max(a.length(),b.length());\n }\n}", + "title": "521. Longest Uncommon Subsequence I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings a and b , return the length of the longest uncommon subsequence between a and b . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between two strings is a string that is a subsequence of one but not the other . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s .", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"cdc\"\nOutput:3\nExplanation:One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.", + "image": null + }, + { + "text": "Example 2: Input:a = \"aaa\", b = \"bbb\"\nOutput:3\nExplanation:The longest uncommon subsequences are \"aaa\" and \"bbb\".", + "image": null + }, + { + "text": "Example 3: Input:a = \"aaa\", b = \"aaa\"\nOutput:-1\nExplanation:Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 54.94%) | Memory: 13.9 MB (Top 58.35%)\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a == b:\n return -1\n\n else:\n return max(len(a), len(b))", + "title": "521. Longest Uncommon Subsequence I", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of strings strs , return the length of the longest uncommon subsequence between them . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s .", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"aba\",\"cdc\",\"eae\"]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"aaa\",\"aaa\",\"aa\"]\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 84.32%) | Memory: 39.8 MB (Top 90.27%)\nclass Solution {\n public int findLUSlength(String[] strs) {\n Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length\n // store the frequency of all strings in array\n Map map = new HashMap<>();\n for(String s : strs) map.put(s,map.getOrDefault(s,0)+1);\n\n for(int i=0;i int:\n def isSubseq(a, b):\n j = 0\n for i in range(len(b)):\n if a[j] == b[i]:\n j += 1\n if j == len(a):\n return True\n return False\n c = Counter(strs)\n s = sorted(c.keys(), key=len, reverse=True)\n for i in range(len(s)):\n if c[s[i]] > 1:\n continue\n if i == 0 or not any(isSubseq(s[i], s[j]) for j in range(i)): \n return len(s[i])\n return -1 \n", + "title": "522. Longest Uncommon Subsequence II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value . This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000", + "The depth of the tree will not exceed 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,5,1,1,null,5]\nOutput:2\nExplanation:The shown image shows that the longest path of the same value (i.e. 5).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [1,4,5,4,4,null,5]\nOutput:2\nExplanation:The shown image shows that the longest path of the same value (i.e. 4).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxLen = 0;\n public int longestUnivaluePath(TreeNode root) {\n lup(root);\n return maxLen;\n }\n public int lup(TreeNode root) {\n if (root == null) {\n return 0;\n }\n int left = lup(root.left);\n int right = lup(root.right);\n int leftMax = 0;\n int rightMax = 0;\n if (root.left != null && root.val == root.left.val) {\n leftMax = left + 1;\n }\n if (root.right != null && root.val == root.right.val) {\n rightMax = right + 1;\n }\n maxLen = Math.max(maxLen, leftMax + rightMax);\n return Math.max(leftMax, rightMax);\n }\n}\n", + "title": "687. Longest Univalue Path", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value . This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000", + "The depth of the tree will not exceed 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,5,1,1,null,5]\nOutput:2\nExplanation:The shown image shows that the longest path of the same value (i.e. 5).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [1,4,5,4,4,null,5]\nOutput:2\nExplanation:The shown image shows that the longest path of the same value (i.e. 4).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tmax_path=0\n\tdef longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n\t\tself.dfs(root);\n\t\treturn self.max_path\n\n\tdef dfs(self,root):\n\t\tif root is None:return 0\n\t\tleft=self.dfs(root.left)\n\t\tright=self.dfs(root.right)\n\n\t\tif root.left and root.left.val == root.val:\n\t\t\tleftPath=left+1\n\t\telse:\n\t\t\tleftPath=0\n\n\t\tif root.right and root.right.val == root.val:\n\t\t\trightPath=right+1\n\t\telse:\n\t\t\trightPath=0\n\n\t\tself.max_path = max(self.max_path, leftPath + rightPath)\n\t\treturn max(leftPath, rightPath)\n", + "title": "687. Longest Univalue Path", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string containing just the characters '(' and ')' , find the length of the longest valid (well-formed) parentheses substring.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"\nOutput:2\nExplanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"\nOutput:4\nExplanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1644 ms (Top 5.15%) | Memory: 43.1 MB (Top 65.80%)\nclass Solution {\n public int longestValidParentheses(String s) {\n int i=0;\n int len=0;\n while(iopen) break;\n if(open==closed) len=Math.max(len,j-i+1);\n\n j++;\n }\n i++;\n }\n return len;\n }\n}", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string containing just the characters '(' and ')' , find the length of the longest valid (well-formed) parentheses substring.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"\nOutput:2\nExplanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"\nOutput:4\nExplanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 48.14%) | Memory: 14.8 MB (Top 24.60%)\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n\n maxi = 0\n stack = [-1]\n\n for i in range(len(s)) :\n if s[i] == \"(\" : stack.append(i)\n else :\n stack.pop()\n if len(stack) == 0 : stack.append(i)\n else : maxi = max(maxi, i - stack[-1])\n\n return maxi", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given hours , a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8 . A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval.", + "description_images": [], + "constraints": [ + "1 <= hours.length <= 10^4", + "0 <= hours[i] <= 16" + ], + "examples": [ + { + "text": "Example 1: Input:hours = [9,9,6,0,6,6,9]\nOutput:3\nExplanation:The longest well-performing interval is [9,9,6].", + "image": null + }, + { + "text": "Example 2: Input:hours = [6,6,6]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)\n// For Longest Well Performing Interval/Window\n// T.C. = O(n^2) , S.C. = O(n)\nclass Solution {\n \n public int longestWPI(int[] hours) {\n int n = hours.length;\n \n int[] prefixSumTiringDaysMinusNonTiringDaysArr = new int[n + 1];\n prefixSumTiringDaysMinusNonTiringDaysArr[0] = 0;\n \n int prefixSumTiringDaysCount = 0;\n int prefixSumNonTiringDaysCount = 0;\n \n for (int i = 0 ; i < n ; i++) {\n int noOfHoursWorkedToday = hours[i];\n \n if (noOfHoursWorkedToday > 8) {\n prefixSumTiringDaysCount++;\n }\n else {\n prefixSumNonTiringDaysCount++;\n }\n \n prefixSumTiringDaysMinusNonTiringDaysArr[i + 1] = prefixSumTiringDaysCount - prefixSumNonTiringDaysCount;\n // System.out.print(prefixSumTiringDaysMinusNonTiringDaysArr[i] + \" \");\n }\n // System.out.println(prefixSumTiringDaysMinusNonTiringDaysArr[n]);\n \n int longestLengthOfContinuousPositiveSequence = 0;\n \n for (int currentSlidingWindowLength = 1 ; currentSlidingWindowLength <= n ; currentSlidingWindowLength++) {\n // System.out.print(currentSlidingWindowLength + \" - \");\n for (int i = 0 ; i <= n - currentSlidingWindowLength ; i++) {\n int j = i + currentSlidingWindowLength - 1;\n // System.out.print(i + \",\" + j + \" \");\n int currentIntervalNoOfTiringDaysMinusNonTiringDays = prefixSumTiringDaysMinusNonTiringDaysArr[j + 1] - prefixSumTiringDaysMinusNonTiringDaysArr[i];\n if (currentIntervalNoOfTiringDaysMinusNonTiringDays > 0) { // => currentInterval = Well Performing Interval\n longestLengthOfContinuousPositiveSequence = Math.max(currentSlidingWindowLength, longestLengthOfContinuousPositiveSequence);\n }\n }\n // System.out.println();\n }\n // System.out.println();\n \n int lengthOfLongestWellPerformingInterval = longestLengthOfContinuousPositiveSequence;\n \n return lengthOfLongestWellPerformingInterval;\n }\n \n}\n", + "title": "1124. Longest Well-Performing Interval", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given hours , a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8 . A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval.", + "description_images": [], + "constraints": [ + "1 <= hours.length <= 10^4", + "0 <= hours[i] <= 16" + ], + "examples": [ + { + "text": "Example 1: Input:hours = [9,9,6,0,6,6,9]\nOutput:3\nExplanation:The longest well-performing interval is [9,9,6].", + "image": null + }, + { + "text": "Example 2: Input:hours = [6,6,6]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n #accumulative count\n #+1 when > 8, -1 when less than 8. \n #find strictly increasing length.\n \n p = [] #number of tiring days vs not\n c = 0\n for e in hours:\n if e > 8:\n c +=1\n else:\n c-=1\n \n p.append(c)\n \n \n \n #for every moment: we want earliest moment which could be positive overall tiring days.\n a = []\n #a is sorted by tiringnes. At day 8 have -2, want earliest point that could get us to at least 1.\n #so up until that point we have -3, -4, etc, and we want earliest out of it to get longest well performing interval. Which is when prefix comes in.\n \n a1 =[]\n for i in range(len(p)):\n a.append([p[i], i])\n a1.append(p[i])\n \n a1.sort() #bisectable list\n a.sort()\n \n prefix = []\n currearly = float('inf')\n for t, day in a:\n currearly = min(currearly, day)\n prefix.append(currearly)\n \n \n res = 0\n \n # print(p)\n \n for i in range(len(hours)):\n if p[i] > 0:\n res = max(res, i + 1) \n \n else:\n #find earliest \n #value must be less than -1-p[i] \n loc = bisect_right(a1, -1+p[i]) #bisect right means anything before this is less than or equals to\n \n \n \n if loc == 0: #the rightmost place to put it is at the beginning...\n \n continue\n \n \n else:\n earliest = prefix[loc - 1]\n \n if earliest >= i: continue\n \n interval = i - earliest #notice: we're not including the starting index, since its also technically being removed!\n\n # print(\"From day\", earliest, \"to\", i)\n \n res = max(res, interval)\n \n \n \n return res\n \n \n \n \n", + "title": "1124. Longest Well-Performing Interval", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words . If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. Note that the word should be built from left to right with each additional character being added to the end of a previous word.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length <= 30", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput:\"world\"\nExplanation:The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput:\"apple\"\nExplanation:Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private class Node{\n Node[] sub;\n Node(){\n sub = new Node[26];\n }\n }\n Node root;\n StringBuilder ans;\n private void buildTire(String word){\n Node temp = root;\n int n = word.length();\n for(int i = 0; i < n-1; i++){\n int index = word.charAt(i)-'a';\n if(temp.sub[index] == null) return;\n temp = temp.sub[index];\n }\n int index = word.charAt(n-1)-'a';\n temp.sub[index] = new Node();\n \n if(word.length() > ans.length())\n ans = new StringBuilder(word);\n }\n public String longestWord(String[] words) {\n this.ans = new StringBuilder();\n this.root = new Node();\n PriorityQueue pq = new PriorityQueue<>();\n pq.addAll(Arrays.asList(words));\n while(!pq.isEmpty()) buildTire(pq.poll());\n return ans.toString();\n }\n}\n", + "title": "720. Longest Word in Dictionary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words . If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. Note that the word should be built from left to right with each additional character being added to the end of a previous word.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length <= 30", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput:\"world\"\nExplanation:The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput:\"apple\"\nExplanation:Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 240 ms (Top 36.59%) | Memory: 15.2 MB (Top 46.59%)\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n TrieNode = lambda: defaultdict(TrieNode)\n root = TrieNode()\n for i,s in enumerate(words):\n cur = root\n for c in s: cur=cur[c]\n cur['$']=i\n\n ans = ''\n st = list(root.values())\n while st:\n cur = st.pop()\n if '$' in cur:\n w = words[cur['$']]\n if len(ans) dictionary) {\n \n int[] fre=new int[26];\n \n \n String ans=\"\";\n int flag=0;\n int[] fff=new int[26];\n char[] ch = s.toCharArray();\n for(char c : ch)\n fre[c-'a']+=1;\n \n for(String s1 : dictionary)\n { \n fff=fre.clone();\n int[] fre1=new int[26];\n char[] ch1 = s1.toCharArray();\n for(char c : ch1)\n {\n \n fre1[c-'a']+=1;\n }\n \n for(char c : ch1)\n {\n if(fre1[c-'a'] <= fff[c-'a'])\n { flag=0;\n fff[c-'a']-=1; \n fre1[c-'a']-=1;\n }\n else\n {flag=1;\n break;} \n }\n if(flag==0)\n {\n if(ans != \"\")\n {\n if(ans.length() s1.charAt(m))\n {\n f=1;\n break;\n }\n \n }\n if(f==1)\n ans=s1;\n }\n }\n }\n else\n ans =s1;\n }\n else\n {\n flag=0;\n }\n }\n \n return ans;\n \n }\n}\n\n", + "title": "524. Longest Word in Dictionary through Deleting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and a string array dictionary , return the longest string in the dictionary that can be formed by deleting some of the given string characters . If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 1000", + "s and dictionary[i] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]\nOutput:\"apple\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]\nOutput:\"a\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLongestWord(self, s: str, dictionary: list[str]) -> str:\n solution = \"\"\n for word in dictionary:\n j = 0\n for i in range(len(s)):\n if s[i] == word[j]:\n j+=1\n if j == len(word):\n solution = word if len(word) > len(solution) or len(word) == len(solution) and word < solution else solution\n break\n return solution", + "title": "524. Longest Word in Dictionary through Deleting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree .", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\nOutput:3\nExplanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput:4\nExplanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 84.82%) | Memory: 54.1 MB (Top 87.52%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n static class Pair{\n int left=-1;\n int right=-1;\n int maxLen=0;\n }\n public int longestZigZag(TreeNode root) {\n Pair ans=longestZigZag_(root);\n return ans.maxLen;\n }\n\n public Pair longestZigZag_(TreeNode root) {\n if(root==null)\n return new Pair();\n Pair l=longestZigZag_(root.left);\n Pair r=longestZigZag_(root.right);\n\n Pair myAns=new Pair();\n myAns.left=l.right+1;\n myAns.right=r.left+1;\n int max=Math.max(myAns.left,myAns.right);\n myAns.maxLen=Math.max(max,Math.max(l.maxLen,r.maxLen));\n return myAns;\n\n }\n\n}", + "title": "1372. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree .", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\nOutput:3\nExplanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput:4\nExplanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 437 ms (Top 91.25%) | Memory: 59.8 MB (Top 86.06%)\n\nclass Solution:\n def longestZigZag(self, root: Optional[TreeNode]) -> int:\n self.res = 0\n\n def helper(root):\n if root is None:\n return -1, -1\n\n leftRight = helper(root.left)[1] + 1\n rightLeft = helper(root.right)[0] + 1\n self.res = max(self.res, leftRight, rightLeft)\n return leftRight, rightLeft\n\n helper(root)\n return self.res", + "title": "1372. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [a i , b i ] indicates that a i has more money than b i and an integer array quiet where quiet[i] is the quietness of the i th person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y] ) among all people who definitely have equal to or more money than the person x .", + "description_images": [], + "constraints": [ + "n == quiet.length", + "1 <= n <= 500", + "0 <= quiet[i] < n", + "All the values of quiet are unique .", + "0 <= richer.length <= n * (n - 1) / 2", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs of richer are unique .", + "The observations in richer are all logically consistent." + ], + "examples": [ + { + "text": "Example 1: Input:richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput:[5,5,2,5,4,5,6,7]\nExplanation:answer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.", + "image": null + }, + { + "text": "Example 2: Input:richer = [], quiet = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 42.47%) | Memory: 65.2 MB (Top 60.25%)\nclass Solution {\n ArrayList> adj =new ArrayList<>();\n int res[];\n public int[] loudAndRich(int[][] richer, int[] quiet) {\n int n=quiet.length;\n res=new int[n];\n Arrays.fill(res,-1);\n for(int i=0;i());\n for(int i=0;i());\n adj.get(richer[i][1]).add(richer[i][0]);\n }\n for(int i=0;i List[int]:\n length = len(quiet)\n arr = [i for i in range(length)]\n indegree = [0 for _ in range(length)]\n graph = collections.defaultdict(list)\n dq = collections.deque([])\n \n for a, b in richer:\n # Note that the graph is uni-directional\n graph[a].append(b)\n indegree[b] += 1\n\n for i in range(length):\n if not indegree[i]: \n dq.append(i)\n \n while dq:\n node = dq.popleft()\n \n for vertex in graph[node]:\n indegree[vertex] -= 1\n if quiet[arr[node]] < quiet[arr[vertex]]:\n arr[vertex] = arr[node]\n if not indegree[vertex]:\n dq.append(vertex)\n return arr\n", + "title": "851. Loud and Rich", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 ).”", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput:6\nExplanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput:2\nExplanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 35.9%) | Memory: 43.95 MB (Top 54.7%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n if(root == null || root == p || root == q)return root;\n\n TreeNode left = lowestCommonAncestor(root.left, p , q);\n TreeNode right = lowestCommonAncestor(root.right, p ,q);\n\n if(left == null)return right;\n if(right == null)return left;\n else{\n return root;\n }\n }\n}", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 ).”", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput:6\nExplanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput:2\nExplanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \n if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)):\n return root\n elif (root.val > p.val):\n return self.lowestCommonAncestor(root.left, p, q)\n else:\n return self.lowestCommonAncestor(root.right, p , q)\n", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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 ).”", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput:3\nExplanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput:5\nExplanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n List path_to_p= new ArrayList<>();\n List path_to_q= new ArrayList<>();\n getPath(root,p,path_to_p);\n getPath(root,q,path_to_q);\n int n=path_to_q.size()>path_to_p.size()?path_to_p.size():path_to_q.size();\n TreeNode anscesstor=root;\n for(int i=0;i list){\n if(root==null) return false;\n list.add(root);\n if(root==target) return true;\n if(getPath(root.left,target,list) || getPath(root.right,target,list)){\n return true;\n }\n list.remove(list.size()-1);\n return false;\n }\n}\n", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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 ).”", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput:3\nExplanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput:5\nExplanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 197 ms (Top 13.70%) | Memory: 26.4 MB (Top 30.94%)\nclass Solution:\n # @param {TreeNode} root\n # @param {TreeNode} p\n # @param {TreeNode} q\n # @return {TreeNode}\n def lowestCommonAncestor(self, root, p, q):\n # escape condition\n if (not root) or (root == p) or (root == q):\n return root\n # search left and right subtree\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if left and right:\n # both found, root is the LCA\n return root\n return left or right", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves . Recall that:", + "description_images": [], + "constraints": [ + "The node of a binary tree is a leaf if and only if it has no children", + "The depth of the root of the tree is 0 . if the depth of a node is d , the depth of each of its children is d + 1 .", + "The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput:[2,7,4]\nExplanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[1]\nExplanation:The root is the deepest node in the tree, and it's the lca of itself.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]\nOutput:[2]\nExplanation:The deepest leaf node in the tree is 2, the lca of one node is itself.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 8.73%) | Memory: 45 MB (Top 22.93%)\nclass Solution {\n public TreeNode lcaDeepestLeaves(TreeNode root) {\n if (root.left == null && root.right == null) return root;\n int depth = findDepth(root);\n Queue q = new LinkedList<>();\n q.offer(root);\n int count = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n count++;\n if (count == depth) {\n break;\n }\n for (int i = 0; i < size; i++) {\n TreeNode cur = q.poll();\n if (cur.left != null) q.offer(cur.left);\n if (cur.right != null) q.offer(cur.right);\n }\n }\n Set set = new HashSet<>();\n while (!q.isEmpty()) {\n set.add(q.poll().val);\n }\n return find(root, set);\n }\n\n public int findDepth(TreeNode root) {\n if (root == null) return 0;\n int left = findDepth(root.left);\n int right = findDepth(root.right);\n return 1 + Math.max(left, right);\n }\n\n public TreeNode find(TreeNode root, Set set) {\n if (root == null) return root;\n if (set.contains(root.val)) return root;\n TreeNode left = find(root.left, set);\n TreeNode right = find(root.right, set);\n if (left != null && right != null) return root;\n else if (left != null) return left;\n else if (right != null) return right;\n else return null;\n }\n}\n", + "title": "1123. Lowest Common Ancestor of Deepest Leaves", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves . Recall that:", + "description_images": [], + "constraints": [ + "The node of a binary tree is a leaf if and only if it has no children", + "The depth of the root of the tree is 0 . if the depth of a node is d , the depth of each of its children is d + 1 .", + "The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput:[2,7,4]\nExplanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[1]\nExplanation:The root is the deepest node in the tree, and it's the lca of itself.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]\nOutput:[2]\nExplanation:The deepest leaf node in the tree is 2, the lca of one node is itself.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 112 ms (Top 7.97%) | Memory: 14.4 MB (Top 40.85%)\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n\n self.max_lvl = (0,[])\n self.pathes = {}\n def rec(root,parent,lvl):\n if not root:\n return\n if lvl > self.max_lvl[0]:\n self.max_lvl = (lvl,[root])\n elif lvl == self.max_lvl[0]:\n self.max_lvl = (lvl,self.max_lvl[1]+[root])\n self.pathes[root] = parent\n rec(root.left,root,lvl+1)\n rec(root.right,root,lvl+1)\n rec(root,None,0)\n print(self.max_lvl)\n # for key in self.pathes:\n # if key!=None and self.pathes[key]!=None:\n # print(key.val,\"-\",self.pathes[key].val)\n if len(self.max_lvl[1]) < 2:\n return self.max_lvl[1][0]\n parent = self.max_lvl[1]\n while len(parent) > 1:\n temp = set()\n for p in parent:\n temp.add(self.pathes.get(p,None))\n parent = temp\n return parent.pop()\n", + "title": "1123. Lowest Common Ancestor of Deepest Leaves", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n // Declare Node class for Doubly Linked List \n class Node{\n int key,value;// to store key and value \n Node next,prev; // Next and Previous Pointers\n Node(int k, int v){\n key=k;\n value=v;\n }\n }\n Node head=new Node(-1,-1); // Default values \n Node tail=new Node(-1,-1);\n Mapmp; // to store key and Node\n int cap;\n public LRUCache(int capacity) {\n // initializing in constructor\n cap=capacity;\n head.next=tail;\n tail.prev=head;\n mp=new HashMap();\n }\n \n public int get(int key) {\n // if map contains the specific key \n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n del(existing);\n ins(existing);// reinserting to keep key after the head pointer and to update LRU list\n return existing.value;\n }\n //otherwise\n return -1;\n }\n \n public void put(int key, int value) {\n // if map contains the key\n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n // remove from the map and delete from the LRU list\n mp.remove(key);\n del(existing);\n }\n // if map size is equal to spcified capacity of the LRU list\n if(mp.size()==cap){\n // remove from the map and delete from the LRU list\n mp.remove(tail.prev.key);\n del(tail.prev);\n }\n Node newNode = new Node(key,value);\n ins(newNode); \n mp.put(key,head.next); \n }\n public void ins(Node newNode){\n //Insert always after the head of the linkedList\n Node temp=head.next;\n head.next=newNode;\n newNode.prev=head;\n newNode.next=temp;\n temp.prev=newNode;\n }\n public void del(Node newNode){\n //Remove the specified node using previous and next pointers\n Node pr=newNode.prev;\n Node nx=newNode.next;\n pr.next=nx;\n nx.prev=pr;\n \n }\n}\n\n", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n int N;\n list pages;\n unordered_map::iterator>> cache;\npublic:\n LRUCache(int capacity) : N(capacity) {\n \n }\n \n int get(int key) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n pages.push_front(key);\n cache[key].second = pages.begin();\n return cache[key].first;\n }\n \n return -1;\n }\n \n void put(int key, int value) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n } else {\n if (pages.size() == N) {\n int lru = pages.back();\n cache.erase(lru);\n pages.pop_back();\n }\n }\n \n pages.push_front(key);\n cache[key] = {value, pages.begin()};\n }\n};\n", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order . A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= n, m <= 50", + "1 <= matrix[i][j] <= 10^5 .", + "All elements in the matrix are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput:[15]\nExplanation:15 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput:[12]\nExplanation:12 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[7,8],[1,2]]\nOutput:[7]\nExplanation:7 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List luckyNumbers (int[][] matrix) {\n List luckyNums = new ArrayList();\n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int[] row : matrix){\n int min = row[0];\n int index = 0;\n boolean lucky = true;\n for(int col = 0; col < m; col++){\n if(min > row[col]){\n min = row[col];\n index = col;\n }\n }\n \n for(int r = 0; r < n; r++){\n if(min < matrix[r][index]){\n lucky = false;\n break;\n }\n }\n if(lucky){\n luckyNums.add(min);\n }\n \n }\n \n return luckyNums;\n \n }\n}\n", + "title": "1380. Lucky Numbers in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order . A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= n, m <= 50", + "1 <= matrix[i][j] <= 10^5 .", + "All elements in the matrix are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput:[15]\nExplanation:15 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput:[12]\nExplanation:12 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[7,8],[1,2]]\nOutput:[7]\nExplanation:7 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n min_, max_ = 0, 0\n min_temp = []\n max_temp = []\n m = len(matrix)\n n = len(matrix[0])\n for i in matrix:\n min_temp.append(min(i))\n print(min_temp)\n if n >= m:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))\n elif n == 1:\n for i in range(m):\n max_check = []\n for j in range(n):\n max_check.append(matrix[i][j])\n max_temp.append(max(max_check))\n return [max(max_temp)]\n else:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))\n", + "title": "1380. Lucky Numbers in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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?  (Each subgrid is contiguous).", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 10", + "0 <= grid[i][j] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput:1\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/09/11/magic_main.jpg" + }, + { + "text": "Example 2: Input:grid = [[8]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int numMagicSquaresInside(int[][] grid) {\n\t\tint n=grid.length,m=grid[0].length,count=0;\n\t\tfor(int i=0;i9 ||count[grid[x+i][y+j]]!=0)\n\t\t\t\t\treturn false;\n\t\t\t\tcount[grid[x+i][y+j]]=1;\n\n\t\t\t}\n\t\t\tif(sum1!=sum || sum!=sum2 || sum1!=sum2)\n\t\t\t\treturn false;\n\t\t}\n\t\tsum1=grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2];\n\t\tsum2=grid[x][y+2]+grid[x+1][y+1]+grid[x+2][y];\n\t\tif(sum1!=sum2 || sum1!=sum)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n", + "title": "840. Magic Squares In Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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?  (Each subgrid is contiguous).", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 10", + "0 <= grid[i][j] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput:1\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/09/11/magic_main.jpg" + }, + { + "text": "Example 2: Input:grid = [[8]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n @classmethod\n def magic_3_3(cls, square: List[List[int]]) -> bool:\n if set(sum(square, [])) != Solution.digits:\n return False\n sum_row0 = sum(square[0])\n for r in range(1, 3):\n if sum(square[r]) != sum_row0:\n return False\n if any(sum(col) != sum_row0 for col in zip(*square)):\n return False\n sum_main_diagonal = sum_second_diagonal = 0\n for i in range(3):\n sum_main_diagonal += square[i][i]\n sum_second_diagonal += square[i][2 - i]\n return sum_main_diagonal == sum_second_diagonal == sum_row0\n\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n count = 0\n rows, cols = len(grid), len(grid[0])\n for r in range(rows - 2):\n for c in range(cols - 2):\n if Solution.magic_3_3([grid[row_idx][c: c + 3]\n for row_idx in range(r, r + 3)]):\n count += 1\n return count\n", + "title": "840. Magic Squares In Grid", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A magical string s consists of only '1' and '2' and obeys the following rules: The first few elements of s is s = \"1221121221221121122……\" . If we group the consecutive 1 's and 2 's in s , it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1 's or 2 's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\" . You can see that the occurrence sequence is s itself. Given an integer n , return the number of 1 's in the first n number in the magical string s .", + "description_images": [], + "constraints": [ + "The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6\nOutput:3\nExplanation:The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 32.48%) | Memory: 43.8 MB (Top 21.66%)\nclass Solution {\n public int magicalString(int n) {\n if(n <= 3)\n return 1;\n Magical m = new Magical();\n int ans = 1;\n for(int i = 3; i < n; ++i)\n if(m.next() == 1)\n ++ans;\n return ans;\n }\n}\n\nclass Magical{\n\n private Deque nums;\n private int n;\n\n public Magical(){\n nums = new ArrayDeque<>();\n nums.offerLast(1);\n nums.offerLast(1);\n n = 1;\n }\n\n public int next(){\n if(n-- < 0){\n int c = nums.pollFirst();\n n = c - 2;\n int curr = 3 - nums.peekLast();\n for(; c > 0; --c)\n nums.offerLast(curr);\n return curr;\n }\n return nums.peekLast();\n }\n}", + "title": "481. Magical String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A magical string s consists of only '1' and '2' and obeys the following rules: The first few elements of s is s = \"1221121221221121122……\" . If we group the consecutive 1 's and 2 's in s , it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1 's or 2 's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\" . You can see that the occurrence sequence is s itself. Given an integer n , return the number of 1 's in the first n number in the magical string s .", + "description_images": [], + "constraints": [ + "The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6\nOutput:3\nExplanation:The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 489 ms (Top 6.14%) | Memory: 14.1 MB (Top 72.07%)\nclass Solution:\n def magicalString(self, n: int) -> int:\n queue, ans, i = deque([2]), 1, 1\n\n while i <= n - 2:\n m = queue.popleft()\n ans += (m == 1)\n queue.extend([1 + (i % 2 == 0)] * m)\n i += 1\n\n return ans", + "title": "481. Magical String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the i th basket is at position[i] , Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum . Rick stated that magnetic force between two different balls at positions x and y is |x - y| . Given the integer array position and the integer m . Return the required force .", + "description_images": [], + "constraints": [ + "n == position.length", + "2 <= n <= 10^5", + "1 <= position[i] <= 10^9", + "All integers in position are distinct .", + "2 <= m <= position.length" + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3,4,7], m = 3\nOutput:3\nExplanation:Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.", + "image": "https://assets.leetcode.com/uploads/2020/08/11/q3v1.jpg" + }, + { + "text": "Example 2: Input:position = [5,4,3,2,1,1000000000], m = 2\nOutput:999999999\nExplanation:We can use baskets 1 and 1000000000.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 68.1%) | Memory: 57.23 MB (Top 20.3%)\n\nclass Solution {\n public int maxDistance(int[] position, int m) {\n Arrays.sort(position);\n int low=Integer.MAX_VALUE;\n int high=0;\n for(int i=1;i=maxPossibleDist){\n prevballplace=position[i];\n balls++;\n }\n }\n if(balls>=m){\n return true;\n }\n return false;\n }\n}", + "title": "1552. Magnetic Force Between Two Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the i th basket is at position[i] , Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum . Rick stated that magnetic force between two different balls at positions x and y is |x - y| . Given the integer array position and the integer m . Return the required force .", + "description_images": [], + "constraints": [ + "n == position.length", + "2 <= n <= 10^5", + "1 <= position[i] <= 10^9", + "All integers in position are distinct .", + "2 <= m <= position.length" + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3,4,7], m = 3\nOutput:3\nExplanation:Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.", + "image": "https://assets.leetcode.com/uploads/2020/08/11/q3v1.jpg" + }, + { + "text": "Example 2: Input:position = [5,4,3,2,1,1000000000], m = 2\nOutput:999999999\nExplanation:We can use baskets 1 and 1000000000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def possible (self,distance,positions,M):\n ball = 1 \n lastPos = positions[0] \n for pos in positions:\n if pos-lastPos >= distance:\n ball+=1 \n if ball == M: return True \n lastPos=pos \n \n return False \n \n \n \n def maxDistance(self, positions,M):\n positions.sort()\n low = 0 \n high = positions [-1] \n ans = 0\n while low<=high:\n distance = low+(high-low)//2 \n \n if self.possible(distance,positions,M):\n ans = distance\n low=distance+1 \n else:\n high=distance-1 \n return ans \n", + "title": "1552. Magnetic Force Between Two Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]\nOutput:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 14 ms (Top 32.93%) | Memory: 56.8 MB (Top 19.67%)\nclass Solution {\n public int majorityElement(int[] nums) {\n // Base case...\n if (nums.length == 1) {\n return nums[0];\n }\n // Sort nums array...\n Arrays.sort(nums);\n // Since the majority element appears more than n / 2 times...\n // The n/2 -th element in the sorted nums must be the majority element...\n return nums[nums.length / 2];\n }\n}", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]\nOutput:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution(object):\n def majorityElement(self, nums):\n sol = None\n cnt = 0\n for i in nums:\n if cnt == 0:\n sol = i\n cnt += (1 if i == sol else -1)\n return sol\n", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array of size n , find all elements that appear more than ⌊ n/3 ⌋ times.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]\nOutput:[3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List majorityElement(int[] nums) {\n int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;\n for(int i = 1; i < nums.length; i++){\n if(val1 == nums[i]){\n cnt1++;\n } else if(val2 == nums[i]){\n cnt2++;\n } else{\n if(cnt1 == 0){\n val1 = nums[i];\n cnt1++;\n } else if(cnt2 == 0){\n val2 = nums[i];\n cnt2++;\n } else{\n cnt1--;\n cnt2--;\n }\n }\n }\n int check1 = 0, check2 = 0;\n for(int i = 0; i < nums.length; i++){\n if(val1 == nums[i])check1++;\n else if(val2 == nums[i])check2++;\n }\n List ans = new ArrayList<>();\n if(check1 > nums.length / 3) ans.add(val1);\n if(check2 > nums.length / 3) ans.add(val2);\n return ans;\n }\n}\n", + "title": "229. Majority Element II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array of size n , find all elements that appear more than ⌊ n/3 ⌋ times.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]\nOutput:[3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n \n #Boyer Moore Voting Algo (As used in ME1 ques) \n #now we can observe that there cannot be more than two elements occuring more than n//3 times in an array\n #so find two majority elements(me=majority element)\n \n\n n=len(nums)\n req=n//3 #for an element to be ME required number of times present \n\n c1=0 #count 1\n c2=0 #count 2\n me1=None #majority element 1\n me2=None #majority element 2\n\n for i in nums:\n if i == me1:\n c1+=1\n\n elif i == me2:\n c2+=1\n\n elif c1 == 0:\n me1=i\n c1=1\n\n elif c2 == 0:\n me2=i\n c2=1\n\n else:\n c1-=1\n c2-=1\n #here we have found our majority elements now check if the found majority element is ME\n # print(me1,me2)\n\n #check if the found majority element is ME\n c1=0\n c2=0\n for i in nums:\n if i==me1:\n c1+=1\n if i==me2:\n c2+=1\n # print(c1,c2)\n\n if c1 > req and c2 > req:\n\n return [me1,me2]\n\n elif c1> req :\n return [me1]\n\n elif c2> req :\n return [me2]\n\n", + "title": "229. Majority Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays arr1 and arr2 , return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j] . If there is no way to make arr1 strictly increasing, return -1 .", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 2000", + "0 <= arr1[i], arr2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\nOutput:1\nExplanation:Replace5with2, thenarr1 = [1, 2, 3, 6, 7].", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,5,3,6,7], arr2 = [4,3,1]\nOutput:2\nExplanation:Replace5with3and then replace3with4.arr1 = [1, 3, 4, 6, 7].", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\nOutput:-1\nExplanation:You can't makearr1strictly increasing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 329 ms (Top 20.6%) | Memory: 44.12 MB (Top 82.6%)\n\nclass Solution {\n public int makeArrayIncreasing(int[] A, int[] B) { // A = arr1, B = arr2\n TreeSet set = new TreeSet<>(Arrays.stream(B).boxed().toList());\n int[] dp = new int[B.length+1];\n dp[0]=-1;\n int INF = (int)2e9;\n for (int i = 0; i < A.length; i++){\n for (int j = B.length; j >= 0; j--){\n int a = A[i] > dp[j]? A[i] : INF; // option A - don't swap\n Integer b = set.higher(j==0?INF:dp[j-1]); // option B - swap\n dp[j]=Math.min(a, b==null?INF:b); // take the min of A and B\n }\n }\n for (int i = 0; i <= B.length; i++) if (dp[i] != INF){\n return i;\n }\n return -1;\n }\n}", + "title": "1187. Make Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays arr1 and arr2 , return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j] . If there is no way to make arr1 strictly increasing, return -1 .", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 2000", + "0 <= arr1[i], arr2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\nOutput:1\nExplanation:Replace5with2, thenarr1 = [1, 2, 3, 6, 7].", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,5,3,6,7], arr2 = [4,3,1]\nOutput:2\nExplanation:Replace5with3and then replace3with4.arr1 = [1, 3, 4, 6, 7].", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\nOutput:-1\nExplanation:You can't makearr1strictly increasing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n1 , n2, dp = len(arr1) , len(arr2) , {}\n arr2.sort()\n \n def solve(i , j , prev):\n \n if i == n1:return 0\n \n if (i,j,prev) in dp: return dp[(i,j,prev)]\n \n k = bisect.bisect_right(arr2[j:],prev) + j\n \n ans = float('inf') if k == n2 else solve(i+1,k+1,arr2[k]) + 1\n \n if arr1[i] > prev:ans = min(ans,solve(i+1 , j ,arr1[i]))\n \n dp[(i,j,prev)] = ans\n \n return ans\n \n \n ans = solve(0,0,-float('inf'))\n \n return ans if ans != float('inf') else -1", + "title": "1187. Make Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a non-negative integer array nums . In one operation, you must: Return the minimum number of operations to make every element in nums equal to 0 .", + "description_images": [], + "constraints": [ + "Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums .", + "Subtract x from every positive element in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,0,3,5]\nOutput:3\nExplanation:In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:0\nExplanation:Each element in nums is already 0 so no operations are needed.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.28%) | Memory: 40.90 MB (Top 7.16%)\n\nclass Solution {\n public int minimumOperations(int[] nums) {\n Set s = new HashSet<>();\n int result = 0;\n if(nums[0] == 0 && nums.length == 1){\n return 0;\n }\n else{\n for (int num : nums) {\n s.add(num);\n }\n for (int num : nums) {\n s.remove(0);\n }\n result = s.size();;\n }\n return result;\n }\n}\n", + "title": "2357. Make Array Zero by Subtracting Equal Amounts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a non-negative integer array nums . In one operation, you must: Return the minimum number of operations to make every element in nums equal to 0 .", + "description_images": [], + "constraints": [ + "Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums .", + "Subtract x from every positive element in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,0,3,5]\nOutput:3\nExplanation:In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:0\nExplanation:Each element in nums is already 0 so no operations are needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n return len(set(nums) - {0})\n", + "title": "2357. Make Array Zero by Subtracting Equal Amounts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers nums , remove the smallest subarray (possibly empty ) such that the sum of the remaining elements is divisible by p . It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible . A subarray is defined as a contiguous block of elements in the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= p <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,2], p = 6\nOutput:1\nExplanation:The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,5,2], p = 9\nOutput:2\nExplanation:We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], p = 3\nOutput:0\nExplanation:Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 457 ms (Top 46.03%) | Memory: 34.70 MB (Top 85.36%)\n\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n n = len(nums)\n target = sum(nums)%p\n if not target:\n return 0\n answer = n\n prefix_sum = 0\n hashmap = {0: -1}\n for i, num in enumerate(nums):\n prefix_sum += num\n key = (prefix_sum%p - target)%p\n if key in hashmap:\n answer = min(answer, i-hashmap[key])\n hashmap[prefix_sum%p] = i\n return answer if answer < n else -1\n", + "title": "1590. Make Sum Divisible by P", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leEeetcode\"\nOutput:\"leetcode\"\nExplanation:In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abBAcC\"\nOutput:\"\"\nExplanation:We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"s\"\nOutput:\"s\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic String makeGood(String s) {\n char[] res = s.toCharArray();\n int i = 0;\n for( char n: s.toCharArray())\n {\n res[i] = n;\n \n if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32)\n {\n i-=2;\n }\n i++;\n }\n return new String(res, 0, i);\n}\n}\n", + "title": "1544. Make The String Great", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leEeetcode\"\nOutput:\"leetcode\"\nExplanation:In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abBAcC\"\nOutput:\"\"\nExplanation:We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"s\"\nOutput:\"s\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 76 ms (Top 13.82%) | Memory: 13.8 MB (Top 62.06%)\nclass Solution:\n def makeGood(self, s: str) -> str:\n while True:\n for i in range(len(s)-1):\n if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()):\n s = s[:i]+s[i+2:]\n break\n else:\n break\n return s", + "title": "1544. Make The String Great", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums ​​​ and an integer k ​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right , inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right] . Return the minimum number of elements to change in the array such that the XOR of all segments of size k ​​​​​​ is equal to zero.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 2000", + "​​​​​​0 <= nums[i] < 2 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0,3,0], k = 1\nOutput:3\nExplanation:Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,5,2,1,7,3,4,7], k = 3\nOutput:3\nExplanation:Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,4,1,2,5,1,2,6], k = 3\nOutput:3\nExplanation:Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 100.0%) | Memory: 43.98 MB (Top 84.6%)\n\nclass Solution {\n public int minChanges(int[] nums, int k) {\n // solution (sequence) is uniquely defined by the first k elements, because a[i] == a[i+k] == a[i+2k] == ... for any offset i\n int v = 1 << 10;\n // best[pattern] is the highest number of relevant (ie. those with offsets between 0 and i) elements in nums\n // that can be left unchanged to achieve a[0] ^ a[1] ^ ... ^ a[i] == pattern\n int[] best = new int[v];\n // iterate over over each offset i of the solution\n for (int i = 0; i < k; i++) {\n // find frequencies of distinct element values present in the subsequence with offset i\n Map n2c = new HashMap();\n for (int p = i; p < nums.length; p += k) {\n n2c.put(nums[p],1+n2c.getOrDefault(nums[p],0));\n }\n // treat initial subsequence (i = 0) correctly\n if (i == 0) {\n for (int vv : n2c.keySet()) {\n best[vv] = n2c.get(vv);\n }\n continue;\n }\n int[] next = new int[v];\n int max = 0;\n for (int j : best) max = Math.max(max, j);\n // elements previously unchanged (ie. from subsequences with offsets 0, 1, 2, .., i-1) can be carried to the current offset i\n // max of all best[] is used\n for (int j = 0; j < v; j++) next[j] = max;\n // for elements present in the subsequnce with offset i next[] can be improved accordingly\n for (int vv : n2c.keySet()) {\n int cnt = n2c.get(vv);\n for (int j = 0; j < v; j++) {\n next[j ^ vv] = Math.max(next[j ^ vv], best[j] + cnt);\n }\n }\n best = next;\n }\n // solution is for pattern == 0, hence best[0]. Report minimum number of elements to change rather than maximum that can be left unchanged.\n return nums.length - best[0];\n }\n}", + "title": "1787. Make the XOR of All Segments Equal to Zero", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two integer arrays of equal length target and arr . In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target or false otherwise .", + "description_images": [], + "constraints": [ + "target.length == arr.length", + "1 <= target.length <= 1000", + "1 <= target[i] <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,4], arr = [2,4,1,3]\nOutput:true\nExplanation:You can follow the next steps to convert arr to target:\n1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.", + "image": null + }, + { + "text": "Example 2: Input:target = [7], arr = [7]\nOutput:true\nExplanation:arr is equal to target without any reverses.", + "image": null + }, + { + "text": "Example 3: Input:target = [3,7,9], arr = [3,7,11]\nOutput:false\nExplanation:arr does not have value 9 and it can never be converted to target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canBeEqual(int[] target, int[] arr) {\n HashMaphm1=new HashMap();\n for(int i: arr){\n if(hm1.containsKey(i))\n hm1.put(i,hm1.get(i)+1);\n else\n hm1.put(i,1);\n }\n for(int i: target){\n if(hm1.containsKey(i)){\n hm1.put(i,hm1.getOrDefault(i,0)-1);\n if(hm1.get(i)==0)\n hm1.remove(i);\n }\n else\n return false;\n \n }\n if(hm1.size()==0)\n return true;\n \n return false;\n }\n}\n", + "title": "1460. Make Two Arrays Equal by Reversing Sub-arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays of equal length target and arr . In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target or false otherwise .", + "description_images": [], + "constraints": [ + "target.length == arr.length", + "1 <= target.length <= 1000", + "1 <= target[i] <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,4], arr = [2,4,1,3]\nOutput:true\nExplanation:You can follow the next steps to convert arr to target:\n1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.", + "image": null + }, + { + "text": "Example 2: Input:target = [7], arr = [7]\nOutput:true\nExplanation:arr is equal to target without any reverses.", + "image": null + }, + { + "text": "Example 3: Input:target = [3,7,9], arr = [3,7,11]\nOutput:false\nExplanation:arr does not have value 9 and it can never be converted to target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n target.sort()\n arr.sort()\n if len(target)==len(arr):\n if target==arr:\n return True\n else:\n return False\n", + "title": "1460. Make Two Arrays Equal by Reversing Sub-arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary matrix grid . You are allowed to change at most one 0 to be 1 . Return the size of the largest island in grid after applying this operation . An island is a 4-directionally connected group of 1 s.", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]\nOutput:3\nExplanation:Change one 0 to 1 and connect two 1s, then we get an island with area = 3.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1],[1,0]]\nOutput:4\nExplanation:Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1],[1,1]]\nOutput:4\nExplanation:Can't change any 0 to 1, only one island with area = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int dir[][] = new int[][]{\n {1, 0},\n {-1,0},\n {0,1},\n {0,-1}\n };\n private int countArea(int grid[][], int i, int j, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)\n return 0;\n \n if(grid[i][j] != 1) return 0;\n \n grid[i][j] = num;\n int count = 0;\n for(int d[] : dir){\n count += countArea(grid, i + d[0], j + d[1], num);\n }\n \n return 1 + count;\n }\n \n private void fillDP(int grid[][], int dp[][], int i, int j, int count, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return ;\n \n if(grid[i][j] != num) return;\n \n if(dp[i][j] != 0) return ;\n dp[i][j] = count;\n for(int d[] : dir){\n fillDP(grid, dp, i + d[0], j + d[1], count, num);\n }\n \n }\n \n \n public int largestIsland(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n int dp[][] = new int[n][m];\n \n int num = 1;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] == 1){\n ++num;\n int count1 = countArea(grid, i, j, num);\n fillDP(grid, dp, i, j, count1, num);\n }\n }\n }\n \n int max = 0;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] != 0) continue;\n int val = 1;\n Set set = new HashSet<>();\n for(int d[] : dir){\n int newRow = i + d[0];\n int newCol = j + d[1];\n \n if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= m) continue;\n if(set.contains(grid[newRow][newCol])) continue;\n \n val += dp[newRow][newCol];\n set.add(grid[newRow][newCol]);\n }\n max = Math.max(max, val);\n }\n }\n \n if(max == 0) return n * m;\n return max;\n \n }\n}\n", + "title": "827. Making A Large Island", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n binary matrix grid . You are allowed to change at most one 0 to be 1 . Return the size of the largest island in grid after applying this operation . An island is a 4-directionally connected group of 1 s.", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]\nOutput:3\nExplanation:Change one 0 to 1 and connect two 1s, then we get an island with area = 3.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1],[1,0]]\nOutput:4\nExplanation:Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1],[1,1]]\nOutput:4\nExplanation:Can't change any 0 to 1, only one island with area = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n # parent array to keey track\n parent = list(range(m*n))\n # rank array used for union by rank and size calculation\n rank = [1 for _ in range(m*n)]\n \n # standard DSU find function\n def find(x):\n while x != parent[x]:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n \n # standard DSU union by rank function\n def union(x,y):\n parX, parY = find(x), find(y)\n if parX == parY: return\n if rank[parX] >= rank[parY]:\n rank[parX] += rank[parY]\n parent[parY] = parX\n else:\n rank[parY] += rank[parX]\n parent[parX] = parY\n \n # Step 1: join the land\n\n # for each island we perform union operation\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # important condition: if we have a water body, we set its rank to 0 (will be used in the next step)\n if not val: \n rank[i*m+j] = 0\n continue\n \n # performing union of land bodies\n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n if grid[x][y]: union(i*m+j, x*m+y)\n \n # Step 2: convert a water body (if present)\n \n # the minimum final ans will always be the size of the largest land present \n ans = max(rank)\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # we dont need to do anything if we encounter a land\n if val: continue\n \n neighbours = set()\n res = 0\n \n # \n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n # checking unique neighbours by adding the parent to the set\n # here we dont care if the neighbour is water as its rank is 0 so it contributes nothing\n idx = x*m+y\n neighbours.add(find(idx))\n \n # Once we have all unique neighbours, just add their ranks\n for idx in neighbours:\n res += rank[idx]\n \n # res + 1 because we convert the current cell (i,j) to land too\n ans = max(ans, res+1)\n \n return ans\n", + "title": "827. Making A Large Island", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings names of size n . You will create n folders in your file system such that , at the i th minute, you will create a folder with the name names[i] . Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k) , where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the i th folder when you create it.", + "description_images": [], + "constraints": [ + "1 <= names.length <= 5 * 10^4", + "1 <= names[i].length <= 20", + "names[i] consists of lowercase English letters, digits, and/or round brackets." + ], + "examples": [ + { + "text": "Example 1: Input:names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput:[\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation:Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"", + "image": null + }, + { + "text": "Example 2: Input:names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput:[\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation:Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"", + "image": null + }, + { + "text": "Example 3: Input:names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput:[\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation:When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Map map = new HashMap<>();\n \n public String[] getFolderNames(String[] names) {\n String[] op = new String[names.length];\n int i = 0;\n \n for(String cur : names){\n if(map.containsKey(cur)) {\n cur = generateCopyName(cur);\n op[i++] = cur;\n // System.out.println(map.toString());\n continue;\n }\n \n op[i++] = cur;\n map.put(cur, 0);\n // System.out.println(map.toString());\n }\n \n return op;\n }\n \n private String generateCopyName(String s) {\n int count = map.get(s) + 1;\n \n String postfix = \"(\" + count + \")\";\n StringBuilder sb = new StringBuilder(s);\n sb.append(postfix);\n \n boolean isChanged = false;\n while(map.containsKey(sb.toString())) {\n sb = new StringBuilder(s);\n sb.append(\"(\" + count + \")\");\n count++;\n isChanged = true;\n }\n String res = sb.toString();\n //System.out.println(res);\n \n \n if(isChanged)\n count = count -1;\n \n map.put(s, count);\n map.put(res, 0);\n \n return res;\n }\n}\n", + "title": "1487. Making File Names Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings names of size n . You will create n folders in your file system such that , at the i th minute, you will create a folder with the name names[i] . Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k) , where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the i th folder when you create it.", + "description_images": [], + "constraints": [ + "1 <= names.length <= 5 * 10^4", + "1 <= names[i].length <= 20", + "names[i] consists of lowercase English letters, digits, and/or round brackets." + ], + "examples": [ + { + "text": "Example 1: Input:names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput:[\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation:Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"", + "image": null + }, + { + "text": "Example 2: Input:names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput:[\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation:Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"", + "image": null + }, + { + "text": "Example 3: Input:names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput:[\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation:When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1004 ms (Top 5.08%) | Memory: 28.1 MB (Top 35.29%)\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # Hashmap will store the name as key and the number of times that name has duplicated so fas as value.\n hashmap = {}\n\n for name in names:\n modified = name\n # Check whether the name has already been used\n if name in hashmap:\n # Get the number of times the {name} has been used\n k = hashmap[name]\n # Calculate the next available suffix.\n while modified in hashmap:\n k += 1\n modified = f'{name}({k})'\n # Update the number of times the original {name} is used. This will help to efficiently check for next available suffix if the {name} again comes in future.\n hashmap[name] = k\n # Store the modified {name} with 0 as it is not duplicated yet.\n hashmap[modified] = 0\n\n # Return the keys of hashmap as that would be the unique file names.\n return hashmap.keys()", + "title": "1487. Making File Names Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]\nOutput:[[1,0],[2,1]]\nExplanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput:[[1,1,0],[0,1,1],[1,2,2]]\nExplanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};\n int rows;\n int cols;\n int[][] isWater;\n\n \n public int[][] highestPeak(int[][] isWater) {\n this.isWater = isWater;\n rows = isWater.length;\n cols = isWater[0].length;\n \n\n int[][] heightCells = new int[rows][cols];\n \n //store the coordinate of water cell\n Queue queue = new LinkedList();\n \n for(int r = 0; r < rows; r++){\n for(int c = 0; c < cols; c++){\n if(isWater[r][c] == 1){\n \n //mark as water\n heightCells[r][c] = 0;\n \n //add water coordinate\n queue.add(new int[]{r, c});\n } else{\n //mark default value for land\n heightCells[r][c] = -1; \n }\n }\n }\n\n \n /*\n * Approach\n * 1. start from every water source, \n update their neighbor height\n * 2. add each neighbours which was not processed earlier\n 3. do it every cell is processed\n */\n bfs(queue, heightCells);\n \n \n return heightCells;\n }\n \n private void bfs(Queue queue, int[][] heightCells){\n \n while(!queue.isEmpty()){\n int[] cell = queue.remove();\n \n //increment height of neighbor cell in all 4 direction \n //e.g, left, right, up, down\n for(int[] dir : DIRECTION){\n \n int newRow = cell[0] + dir[0];\n int newCol = cell[1] + dir[1]; \n \n //check new coordinate of cell inside the grid or not\n if(!isInsideGrid(newRow, newCol)) continue;\n \n //check already handled\n if(heightCells[newRow][newCol] != -1) continue;\n\n //increament, \n heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1;\n \n //to handle the neighbour of this new cell\n queue.add(new int[]{newRow, newCol});\n }\n \n }\n }\n \n private boolean isInsideGrid(int row, int col){\n return row >= 0 && row < rows && col >= 0 && col < cols;\n } \n}\n", + "title": "1765. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]\nOutput:[[1,0],[2,1]]\nExplanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput:[[1,1,0],[0,1,1],[1,2,2]]\nExplanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = collections.deque()\n m, n = len(isWater), len(isWater[0])\n for i in range(m):\n for j in range(n):\n if isWater[i][j] == 1:\n arr.append((0, i, j))\n \n ans = [[-1] * n for _ in range(m)]\n while arr:\n val, x, y = arr.popleft() \n if ans[x][y] != -1: continue\n ans[x][y] = val\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n xx, yy = x+dx, y+dy\n if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1:\n arr.append((val+1, xx, yy))\n return ans\n", + "title": "1765. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a map that allows you to do the following: Implement the MapSum class:", + "description_images": [], + "constraints": [ + "Maps a string key to a given value.", + "Returns the sum of the values that have a key with a prefix equal to a given string." + ], + "examples": [ + { + "text": "Example 1: Input[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]Output[null, null, 3, null, 5]ExplanationMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3); \nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2); \nmapSum.sum(\"ap\"); // return 5 (apple +app = 3 + 2 = 5)", + "image": null + } + ], + "follow_up": null, + "solution": "class MapSum {\n private Map map;\n private Map words;\n\n public MapSum() {\n this.map = new HashMap<>();\n this.words = new HashMap<>();\n }\n \n public void insert(String key, int val) {\n Integer lookup = this.words.getOrDefault(key, null);\n int diff;\n if (lookup == null)\n diff = val;\n else\n diff = val - lookup;\n \n int k = key.length();\n \n StringBuilder sb = new StringBuilder(); \n for (int i = 0; i < k; i++) {\n sb.append(key.charAt(i));\n \n String prefix = sb.toString();\n map.put(prefix, map.getOrDefault(prefix, 0) + diff);\n }\n \n this.words.put(key, val);\n }\n \n public int sum(String prefix) {\n return this.map.getOrDefault(prefix, 0);\n }\n}\n\n/**\n * Your MapSum object will be instantiated and called as such:\n * MapSum obj = new MapSum();\n * obj.insert(key,val);\n * int param_2 = obj.sum(prefix);\n */\n", + "title": "677. Map Sum Pairs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a map that allows you to do the following: Implement the MapSum class:", + "description_images": [], + "constraints": [ + "Maps a string key to a given value.", + "Returns the sum of the values that have a key with a prefix equal to a given string." + ], + "examples": [ + { + "text": "Example 1: Input[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]Output[null, null, 3, null, 5]ExplanationMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3); \nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2); \nmapSum.sum(\"ap\"); // return 5 (apple +app = 3 + 2 = 5)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 97.14%) | Memory: 17.50 MB (Top 9.54%)\n\nclass MapSum:\n\n def __init__(self):\n self.trie = {}\n\n def insert(self, key: str, val: int) -> None:\n node = self.trie\n for ch in key:\n node = node.setdefault(ch, {})\n node['val'] = val\n return\n\n def sum(self, prefix: str) -> int:\n def traverse(node):\n nonlocal res\n if not node:\n return\n if 'val' in node:\n res += node['val']\n for child in node:\n if child == 'val': continue\n traverse(node[child])\n return\n \n node = self.trie\n for ch in prefix:\n node = node.get(ch, {})\n if not node:\n return 0\n res = 0\n traverse(node)\n return res\n", + "title": "677. Map Sum Pairs", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a personal information string s , representing either an email address or a phone number . Return the masked personal information using the below rules . Email address: An email address is: To mask an email: Phone number: A phone number is formatted as follows: To mask a phone number:", + "description_images": [], + "constraints": [ + "A name consisting of uppercase and lowercase English letters, followed by", + "The '@' symbol, followed by", + "The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetCode@LeetCode.com\"\nOutput:\"l*****e@leetcode.com\"\nExplanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AB@qq.com\"\nOutput:\"a*****b@qq.com\"\nExplanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1(234)567-890\"\nOutput:\"***-***-7890\"\nExplanation:s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.55%) | Memory: 42.3 MB (Top 50.00%)\nclass Solution {\n public String maskPII(String s) {\n StringBuilder sb = new StringBuilder();\n //email handeling\n if((s.charAt(0) >= 97 && s.charAt(0) <= 122) || (s.charAt(0) >= 65 && s.charAt(0) <= 90)){\n\n s = s.toLowerCase();\n int indexofAt = s.indexOf('@');\n String firstName = s.substring(0, indexofAt);\n sb.append(firstName.charAt(0)).append(\"*****\").append(firstName.charAt(firstName.length()-1));\n sb.append(s.substring(indexofAt,s.length()));\n }\n //phone number handeling\n else{\n int digits = 0;\n for(int i = 0 ; i < s.length(); i++){\n if(Character.isDigit(s.charAt(i))){\n digits++;\n }\n }\n if(digits > 10){\n sb.append('+');\n }\n while(digits > 10){\n sb.append('*');\n digits--;\n }\n if(sb.toString().isEmpty() == false){\n sb.append('-');\n }\n sb.append(\"***\").append('-').append(\"***-\");\n StringBuilder last4 = new StringBuilder();\n int count = 0;\n for(int i = s.length()-1; i >=0; --i){\n if(count == 4){\n break;\n }\n if(Character.isDigit(s.charAt(i))){\n last4.append(s.charAt(i));\n count++;\n }\n }\n sb.append(last4.reverse());\n }\n\n return sb.toString();\n }\n}", + "title": "831. Masking Personal Information", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a personal information string s , representing either an email address or a phone number . Return the masked personal information using the below rules . Email address: An email address is: To mask an email: Phone number: A phone number is formatted as follows: To mask a phone number:", + "description_images": [], + "constraints": [ + "A name consisting of uppercase and lowercase English letters, followed by", + "The '@' symbol, followed by", + "The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetCode@LeetCode.com\"\nOutput:\"l*****e@leetcode.com\"\nExplanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AB@qq.com\"\nOutput:\"a*****b@qq.com\"\nExplanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1(234)567-890\"\nOutput:\"***-***-7890\"\nExplanation:s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maskPII(self, s: str) -> str:\n res=''\n if '@' in s:\n \n l=s.split('@')\n \n a=l[0]\n b=l[1]\n \n c=b.split('.')\n \n \n res=a[0].lower()+'*'*5+a[-1].lower()+'@'+c[0].lower()+'.'+c[1].lower()\n return res\n else:\n l=0\n res=''\n flag=False\n f=False\n c=0\n for i in range(len(s)-1,-1,-1):\n if s[i]==\"(\" or s[i]==')' or s[i]=='-' or s[i]=='+' or s[i]==' ':\n continue\n \n if f==True:\n c+=1\n continue\n \n if flag==False:\n res=s[i]+res\n else:\n res='*'+res\n \n \n \n if l==3 or l==6:\n if l==3:\n flag=True\n res='-'+res\n l+=1\n \n if len(res)==12:\n f=True\n if c==1:\n res='+*-'+res\n elif c==2:\n res=\"+**-\"+res\n elif c==3:\n res=\"+***-\"+res\n \n \n return res\n \n \n \n \n \n \n", + "title": "831. Masking Personal Information", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and sub . You are also given a 2D character array mappings where mappings[i] = [old i , new i ] indicates that you may perform the following operation any number of times: Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings . Otherwise, return false . A substring is a contiguous non-empty sequence of characters within a string.", + "description_images": [], + "constraints": [ + "Replace a character old i of sub with new i ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]\nOutput:true\nExplanation:Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = \"l3e7\" is a substring of s, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]\nOutput:false\nExplanation:The string \"f00l\" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]\nOutput:true\nExplanation:Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = \"l33tb\" is a substring of s, so we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean matchReplacement(String s, String sub, char[][] mappings) {\n HashMap> m = new HashMap<>();\n for(char[] carr: mappings) {\n if (!m.containsKey(carr[0])){\n m.put(carr[0], new HashSet());\n }\n m.get(carr[0]).add(carr[1]);\n }\n int len_s = s.length();\n int len_sub = sub.length();\n for (int pos = 0; pos < s.length(); pos++ ){\n int i = pos;\n int j = 0;\n boolean cont = false; \n while (j <= sub.length()) {\n if ( j == sub.length()) return true;\n int lenlefts = len_s - i;\n int lenleftsub = len_sub - j;\n if (lenlefts < lenleftsub) {\n break;\n } else if ((s.charAt(i) == sub.charAt(j)) || \n\t\t\t\t (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) {\n i += 1;\n j += 1;\n } else {\n break;\n }\n }\n }\n return false;\n }\n}\n", + "title": "2301. Match Substring After Replacement", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and sub . You are also given a 2D character array mappings where mappings[i] = [old i , new i ] indicates that you may perform the following operation any number of times: Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings . Otherwise, return false . A substring is a contiguous non-empty sequence of characters within a string.", + "description_images": [], + "constraints": [ + "Replace a character old i of sub with new i ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]\nOutput:true\nExplanation:Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = \"l3e7\" is a substring of s, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]\nOutput:false\nExplanation:The string \"f00l\" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]\nOutput:true\nExplanation:Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = \"l33tb\" is a substring of s, so we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nimport re\n\nclass Solution:\n def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n reachable = defaultdict(set)\n for a, b in mappings:\n reachable[a].add(b)\n for c in sub:\n reachable[c].add(c)\n regex = \"\"\n for c in sub:\n if len(reachable[c]) > 1:\n regex += \"(\"\n regex += \"|\".join(reachable[c])\n regex += \")\"\n else:\n regex += c\n return re.compile(regex).search(s)\n", + "title": "2301. Match Substring After Replacement", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the i th matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time . Return true if you can make this square and false otherwise.", + "description_images": [], + "constraints": [ + "1 <= matchsticks.length <= 15", + "1 <= matchsticks[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matchsticks = [1,1,2,2,2]\nOutput:true\nExplanation:You can form a square with length 2, one side of the square came two sticks with length 1.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg" + }, + { + "text": "Example 2: Input:matchsticks = [3,3,3,3,4]\nOutput:false\nExplanation:You cannot find a way to form a square with all the matchsticks.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.50 MB (Top 26.55%)\n\nclass Solution {\n public boolean makesquare(int[] M) {\n Arrays.sort(M);\n int total = 0;\n for (int i = 0; i < M.length; i++)\n total += M[i];\n side = total / 4;\n if ((float)total / 4 > side || M[M.length-1] > side)\n return false;\n return btrack(M.length-1, side, 0, M);\n }\n private int side;\n private boolean btrack(int i, int space, int done, int[] M) {\n if (done == 3)\n return true;\n for (; i >= 0; i--) {\n int num = M[i];\n boolean res;\n if (num > space)\n continue;\n M[i] = side + 1;\n if (num == space)\n res = btrack(M.length-2, side, done+1, M);\n else\n res = btrack(i-1, space-num, done, M);\n if (res)\n return true;\n M[i] = num;\n while (i > 0 && M[i-1] == num)\n i--;\n }\n return false;\n }\n}\n", + "title": "473. Matchsticks to Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the i th matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time . Return true if you can make this square and false otherwise.", + "description_images": [], + "constraints": [ + "1 <= matchsticks.length <= 15", + "1 <= matchsticks[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matchsticks = [1,1,2,2,2]\nOutput:true\nExplanation:You can form a square with length 2, one side of the square came two sticks with length 1.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg" + }, + { + "text": "Example 2: Input:matchsticks = [3,3,3,3,4]\nOutput:false\nExplanation:You cannot find a way to form a square with all the matchsticks.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makesquare(self, matchsticks: List[int]) -> bool:\n target,m=divmod(sum(matchsticks),4)\n if m:return False\n targetLst=[0]*4\n length=len(matchsticks)\n matchsticks.sort(reverse=True)\n def bt(i):\n if i==length:\n return len(set(targetLst))==1\n for j in range(4):\n if matchsticks[i]+targetLst[j]>target:\n continue\n targetLst[j]+=matchsticks[i]\n if bt(i+1):\n return True\n targetLst[j]-=matchsticks[i]\n if not targetLst[j]:break\n return False\n return matchsticks[0]<=target and bt(0)\n", + "title": "473. Matchsticks to Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a m x n matrix mat and an integer k , return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for :", + "description_images": [], + "constraints": [ + "i - k <= r <= i + k,", + "j - k <= c <= j + k , and", + "(r, c) is a valid position in the matrix." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput:[[12,21,16],[27,45,33],[24,39,28]]", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput:[[45,45,45],[45,45,45],[45,45,45]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 88 ms (Top 26.15%) | Memory: 43.2 MB (Top 92.07%)\nclass Solution {\n public int[][] matrixBlockSum(int[][] mat, int k) {\n int m = mat.length,n = mat[0].length;\n int[][] answer = new int[m][n];\n for(int i=0;i List[List[int]]:\n ROWS, COLS = len(matrix), len(matrix[0])\n\n prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)]\n\n for r in range(1, ROWS + 1):\n for c in range(1, COLS + 1):\n prefix_sums[r][c] = prefix_sums[r - 1][c] + prefix_sums[r][c - 1] + \\\n matrix[r - 1][c - 1] - prefix_sums[r - 1][c - 1]\n\n res = [[0] * COLS for _ in range(ROWS)]\n for r in range(ROWS):\n for c in range(COLS):\n res[r][c] = prefix_sums[min(r + k + 1, ROWS)][min(c + k + 1, COLS)] - \\\n prefix_sums[max(r - k, 0)][min(c + k + 1, COLS)] - \\\n prefix_sums[min(r + k + 1, ROWS)][max(c - k, 0)] + \\\n prefix_sums[max(r - k, 0)][max(c - k, 0)]\n\n return res", + "title": "1314. Matrix Block Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given four integers row , cols , rCenter , and cCenter . There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter) . Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance . You may return the answer in any order that satisfies this condition. The distance between two cells (r 1 , c 1 ) and (r 2 , c 2 ) is |r 1 - r 2 | + |c 1 - c 2 | .", + "description_images": [], + "constraints": [ + "1 <= rows, cols <= 100", + "0 <= rCenter < rows", + "0 <= cCenter < cols" + ], + "examples": [ + { + "text": "Example 1: Input:rows = 1, cols = 2, rCenter = 0, cCenter = 0\nOutput:[[0,0],[0,1]]\nExplanation:The distances from (0, 0) to other cells are: [0,1]", + "image": null + }, + { + "text": "Example 2: Input:rows = 2, cols = 2, rCenter = 0, cCenter = 1\nOutput:[[0,1],[0,0],[1,1],[1,0]]\nExplanation:The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.", + "image": null + }, + { + "text": "Example 3: Input:rows = 2, cols = 3, rCenter = 1, cCenter = 2\nOutput:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\nExplanation:The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 88.98%) | Memory: 44.4 MB (Top 93.55%)\n//--------------------Method 1----------------------\n\nclass Solution {\n public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n int [][]res=new int[rows*cols][2];\n\n int idx=0;\n\n for(int i=0;i{\n int d1=Math.abs(a[0]-rCenter)+Math.abs(a[1]-cCenter);\n int d2=Math.abs(b[0]-rCenter)+Math.abs(b[1]-cCenter);\n\n return d1-d2;\n });\n\n return res;\n }\n}\n\n//--------------------Method 2--------------------\n\n// class Solution {\n// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n// boolean [][]vis=new boolean[rows][cols];\n// int [][]ans=new int[rows*cols][2];\n\n// Queue q=new LinkedList<>();\n// q.add(new Pair(rCenter,cCenter));\n// int idx=0;\n// vis[rCenter][cCenter]=true;\n// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};\n\n// while(!q.isEmpty()){\n// Pair curr=q.remove();\n// ans[idx][0]=curr.r;\n// ans[idx][1]=curr.c;\n// idx++;\n\n// for(int []d:dir){\n// int nr=curr.r+d[0];\n// int nc=curr.c+d[1];\n\n// if(nr>=0 && nr=0 && nc List[List[int]]:\n # create a r, c matrix given the rows & cols\n # each element represents a list [r, c] where r is the row & c the col\n # find find the distances of all cells from the center (append to res)\n # sort the result by distance function\n # Time O(M + N) Space O(M + N)\n \n \n def distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n \n matrix = [[i, j] for i in range(rows) for j in range(cols)]\n center = [rCenter, cCenter]\n matrix.sort(key=lambda c: distance(c, center))\n \n return matrix\n", + "title": "1030. Matrix Cells in Distance Order", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a square matrix mat , return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.", + "description_images": [], + "constraints": [ + "n == mat.length == mat[i].length", + "1 <= n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]\nOutput:25\nExplanation:Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" + }, + { + "text": "Example 2: Input:mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]\nOutput:8", + "image": null + }, + { + "text": "Example 3: Input:mat = [[5]]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int diagonalSum(int[][] mat) {\n int sum1 = 0;\n int sum2 = 0;\n int n = mat.length;\n for(int i = 0 ; i < n ; i++)\n {\n sum1 += mat[i][i];\n sum2 += mat[i][n-i-1];\n }\n int res = sum1 + sum2;\n if(n%2 != 0)\n {\n res -= mat[n/2][n/2];\n }\n return res;\n }\n}\n", + "title": "1572. Matrix Diagonal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a square matrix mat , return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.", + "description_images": [], + "constraints": [ + "n == mat.length == mat[i].length", + "1 <= n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]\nOutput:25\nExplanation:Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" + }, + { + "text": "Example 2: Input:mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]\nOutput:8", + "image": null + }, + { + "text": "Example 3: Input:mat = [[5]]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 89.16%) | Memory: 17.60 MB (Top 5.05%)\n\nclass Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n \n n = len(mat)\n \n mid = n // 2\n \n summation = 0\n \n for i in range(n):\n \n # primary diagonal\n summation += mat[i][i]\n \n # secondary diagonal\n summation += mat[n-1-i][i]\n \n \n if n % 2 == 1:\n # remove center element (repeated) on odd side-length case\n summation -= mat[mid][mid]\n \n \n return summation\n", + "title": "1572. Matrix Diagonal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: 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]]\nOutput:6\nExplanation:The answer is not 11, because the island must be connected 4-directionally.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0,0,0,0,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 93 ms (Top 5.05%) | Memory: 72.8 MB (Top 5.08%)\nclass Solution {\n public int maxAreaOfIsland(int[][] grid) {\n\n final int rows=grid.length;\n final int cols=grid[0].length;\n final int[][] dirrections=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};\n Map> adj=new HashMap<>();\n boolean[][] visited=new boolean[rows][cols];\n Queue queue=new LinkedList<>();\n int res=0;\n\n for(int i=0;i list=new ArrayList<>();\n for(int[] dirrection:dirrections)\n {\n int newRow=dirrection[0]+i;\n int newCol=dirrection[1]+j;\n\n boolean isInBoard=newRow>=rows||newRow<0||newCol>=cols||newCol<0;\n if(!isInBoard)\n {\n list.add(new int[]{newRow,newCol,grid[newRow][newCol]});\n }\n }\n\n adj.put(getNodeStringFormat(i,j,grid[i][j]),list);\n }\n }\n\n for(int i=0;i int:\n if not grid:\n return 0\n \n maxArea = 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1: # run dfs only when we find a land\n maxArea = max(maxArea, self.dfs(grid, i, j))\n \n return maxArea\n \n \n def dfs(self, grid, i, j):\n\t\t# conditions for out of bound and when we encounter water\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:\n return 0\n \n maxArea = 1\n grid[i][j] = '#' # this will act as visited set\n maxArea += self.dfs(grid, i+1, j)\n maxArea += self.dfs(grid, i-1, j)\n maxArea += self.dfs(grid, i, j+1)\n maxArea += self.dfs(grid, i, j-1)\n \n return maxArea\n", + "title": "695. Max Area of Island", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1] . We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array .", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10", + "0 <= arr[i] < n", + "All the elements of arr are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,3,2,1,0]\nOutput:1\nExplanation:Splitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,0,2,3,4]\nOutput:4\nExplanation:We can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.9 MB (Top 81.61%)\nclass Solution {\n public int maxChunksToSorted(int[] arr) {\n\n int max=0, count=0;\n for(int i=0; i. 0 1 2 3 4 5 6 7\n\nInput --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70\n <------------> <--> <-------> <------->\nLeft Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75\n\nRight Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max\n\n1. At pos 2 , left_max 30 is smaller than right_min 40 at pos 3\n2. That means , all the elements in the right side of 30 are bigger than all the elements of left side of 30 , including 30\n3. Hence we can break it at pos 2 into a chunk and sort this whole sub-array( 0 - 2 )\n\n*/\n\nclass Solution {\n\n public int maxChunksToSorted(int[] arr) {\n\n // 1. Generate Right min\n\n int[] min_from_right = new int[arr.length+1] ;\n min_from_right[arr.length] = Integer.MAX_VALUE ;\n\n for(int i=arr.length-1 ; i>=0 ; i--){\n min_from_right[i] = Math.min(arr[i] , min_from_right[i+1]);\n }\n\n // 2. Generate Left Max and Count chunks\n int chunk_count = 0 ;\n int max_cur = Integer.MIN_VALUE ;\n\n for(int i=0 ; i int:\n sortedArr = sorted(arr)\n\n posMap = defaultdict(list)\n for i in range(len(sortedArr)):\n posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position\n\n idx = len(arr) - 1\n cnt = 0\n for i in range(len(arr) - 1, -1, -1):\n idx = min(idx, posMap[arr[i]][-1]) # the smallest position need to move arr[i] to correct position\n posMap[arr[i]].pop()\n if i == idx:\n cnt += 1\n idx -= 1\n return cnt", + "title": "768. Max Chunks To Make Sorted II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , return the maximum number of consecutive 1 's in the array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1,1,1]\nOutput:3\nExplanation:The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1,0,1]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 25.35%) | Memory: 56.8 MB (Top 44.29%)\nclass Solution {\n public int findMaxConsecutiveOnes(int[] nums) {\n int max = 0;\n int new_max = 0;\n for(int i=0;inew_max){\n new_max = max;\n }\n max = 0;\n }\n }\n if(max int:\n \n count = maxCount = 0\n \n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n else:\n maxCount = max(count, maxCount)\n count = 0\n \n return max(count, maxCount)\n", + "title": "485. Max Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput:6\nExplanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput:10\nExplanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 43.4 MB (Top 96.24%)\n\nclass Solution {\n public int longestOnes(int[] nums, int k) {\n int ans = 0;\n int j = -1;\n int count = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n count++;\n }\n while (count > k) {\n j++;\n if (nums[j] == 0) {\n count--;\n }\n }\n int len = i - j;\n if (len > ans) ans = len;\n }\n return ans;\n }\n}", + "title": "1004. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput:6\nExplanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput:10\nExplanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 398 ms (Top 99.0%) | Memory: 17.90 MB (Top 17.54%)\n\nclass Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n l=r=0 \n for r in range(len(nums)):\n if nums[r] == 0:\n k-=1\n if k<0:\n if nums[l] == 0:\n k+=1\n l+=1\n return r-l+1\n", + "title": "1004. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer num . You will apply the following steps exactly two times: Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b .", + "description_images": [], + "constraints": [ + "Pick a digit x (0 <= x <= 9) .", + "Pick another digit y (0 <= y <= 9) . The digit y can be equal to x .", + "Replace all the occurrences of x in the decimal representation of num by y .", + "The new integer cannot have any leading zeros, also the new integer cannot be 0." + ], + "examples": [ + { + "text": "Example 1: Input:num = 555\nOutput:888\nExplanation:The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888", + "image": null + }, + { + "text": "Example 2: Input:num = 9\nOutput:8\nExplanation:The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDiff(int num) {\n int[] arr = new int[String.valueOf(num).length()];\n for (int i = arr.length - 1; i >= 0; i--){\n arr[i] = num % 10;\n num /= 10;\n }\n return max(arr.clone()) - min(arr);\n }\n\n private int max(int[] arr){ // find max\n for (int i = 0, t = -1; i < arr.length; i++){\n if (t == -1 && arr[i] != 9){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = 9;\n }\n }\n return parse(arr);\n }\n\n private int min(int[] arr){ // find min\n int re = arr[0] == 1? 0 : 1;\n int t = arr[0] == 1? -1 : arr[0];\n for (int i = 0; i < arr.length; i++){\n if (t == -1 && arr[i] != 0 && arr[i] != arr[0]){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = re;\n }\n }\n return parse(arr);\n }\n\n private int parse(int[] arr){\n int ans = 0;\n for (int i = 0; i < arr.length; i++){\n ans = 10 * ans + arr[i];\n }\n return ans;\n }\n}\n", + "title": "1432. Max Difference You Can Get From Changing an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer num . You will apply the following steps exactly two times: Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b .", + "description_images": [], + "constraints": [ + "Pick a digit x (0 <= x <= 9) .", + "Pick another digit y (0 <= y <= 9) . The digit y can be equal to x .", + "Replace all the occurrences of x in the decimal representation of num by y .", + "The new integer cannot have any leading zeros, also the new integer cannot be 0." + ], + "examples": [ + { + "text": "Example 1: Input:num = 555\nOutput:888\nExplanation:The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888", + "image": null + }, + { + "text": "Example 2: Input:num = 9\nOutput:8\nExplanation:The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 82.14%) | Memory: 16.40 MB (Top 63.78%)\n\nclass Solution:\n def maxDiff(self, num: int) -> int:\n num = str(num)\n \n i = next((i for i in range(len(num)) if num[i] != \"9\"), -1) #first non-9 digit\n hi = int(num.replace(num[i], \"9\"))\n \n if num[0] != \"1\": lo = int(num.replace(num[0], \"1\"))\n else: \n i = next((i for i in range(len(num)) if num[i] not in \"01\"), -1)\n lo = int(num.replace(num[i], \"0\") if i > 0 else num)\n \n return hi - lo\n", + "title": "1432. Max Difference You Can Get From Changing an Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two arrays nums1 and nums2 . Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 500", + "-1000 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput:18\nExplanation:Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,-2], nums2 = [2,-6,7]\nOutput:21\nExplanation:Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-1,-1], nums2 = [1,1]\nOutput:-1\nExplanation:Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDotProduct(int[] nums1, int[] nums2) {\n int N = nums1.length, M = nums2.length;\n int[][] dp = new int[N][M];\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n dp[i][j] = nums1[i] * nums2[j];\n if (i > 0 && j > 0 && dp[i - 1][j - 1] > 0) {\n dp[i][j] += dp[i - 1][j - 1];\n }\n if (i > 0 && dp[i - 1][j] > dp[i][j]) {\n dp[i][j] = dp[i - 1][j];\n }\n if (j > 0 && dp[i][j - 1] > dp[i][j]) {\n dp[i][j] = dp[i][j - 1];\n }\n }\n }\n return dp[N - 1][M - 1];\n }\n}", + "title": "1458. Max Dot Product of Two Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two arrays nums1 and nums2 . Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 500", + "-1000 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput:18\nExplanation:Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,-2], nums2 = [2,-6,7]\nOutput:21\nExplanation:Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-1,-1], nums2 = [1,1]\nOutput:-1\nExplanation:Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 435 ms (Top 93.00%) | Memory: 13.8 MB (Top 100.00%)\nclass Solution:\n def maxDotProduct(self, A, B):\n dp = [float('-inf')] * (len(B)+1)\n for i in range(len(A)):\n prev = float('-inf')\n for j in range(len(B)):\n product = A[i] * B[j]\n prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product)\n return dp[-1]", + "title": "1458. Max Dot Product of Two Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c . A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0 -height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction .", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[r].length", + "2 <= n <= 50", + "0 <= grid[r][c] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\nOutput:35\nExplanation:The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]", + "image": "https://assets.leetcode.com/uploads/2021/06/21/807-ex1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[0,0,0],[0,0,0]]\nOutput:0\nExplanation:Increasing the height of any building will result in the skyline changing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] row = new int[n];\n int[] col = new int[n];\n int ans = 0;\n for(int i=0;i int:\n\t\tmxr = [max(i) for i in grid]\n\t\tmxc = [0 for _ in range(len(grid[0]))]\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[0])):\n\t\t\t\tmxc[j] = max(grid[i][j],mxc[j])\n\t\tans =0 \n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid)):\n\t\t\t\tans+=(min(mxr[i],mxc[j]) - grid[i][j]) \n\t\treturn ans", + "title": "807. Max Increase to Keep City Skyline", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5\nOutput:2\nExplanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6\nOutput:1\nExplanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxOperations(int[] nums, int k) {\n HashMapmap=new HashMap<>();\n int count=0;\n for(int i=0;i0){\n count++;\n map.put(k-nums[i],map.get(k-nums[i])-1);\n }else{\n //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1\n //and if some value is present then it return that value \"similar to map.get(i)\" and I added 1 on it \n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n }\n return count;\n }\n}\n", + "title": "1679. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5\nOutput:2\nExplanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6\nOutput:1\nExplanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n nums.sort()\n left = 0\n right = len(nums) - 1\n ans = 0\n while left < right:\n cur = nums[left] + nums[right]\n if cur == k:\n ans += 1\n left += 1\n right -= 1\n elif cur < k:\n left += 1\n else:\n right -= 1\n \n return ans\n", + "title": "1679. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of points where points[i] = [x i , y i ] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 300", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[3,3]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" + }, + { + "text": "Example 2: Input:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 45.59%) | Memory: 42 MB (Top 92.59%)\nclass Solution {\n public int maxPoints(int[][] points) {\n int n = points.length;\n if(n == 1) return n;\n int result = 0;\n for(int i = 0; i< n; i++){\n for(int j = i+1; j< n; j++){\n result = Math.max(result, getPoints(i, j, points));\n }\n }\n return result;\n }\n private int getPoints(int pt1, int pt2, int[][] points){\n int[] point1 = points[pt1], point2 = points[pt2];\n double slope = (point1[1] - point2[1])/(double)(point1[0] - point2[0]);\n int result = 0;\n for(int i = 0; i int:\n ans = 0\n n = len(points)\n \n for i in range(n):\n d = collections.defaultdict(int)\n for j in range(n):\n if i != j:\n slope = float(\"inf\")\n if (points[j][1] - points[i][1] != 0):\n slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1])\n d[slope] += 1\n if d:\n ans = max(ans, max(d.values())+1)\n else:\n ans = max(ans, 1)\n \n return ans", + "title": "149. Max Points on a Line", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j , such that i != j , and the sum of digits of the number nums[i] is equal to that of nums[j] . Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [18,43,36,13,7]\nOutput:54\nExplanation:The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,12,19,14]\nOutput:-1\nExplanation:There are no two numbers that satisfy the conditions, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 33.41%) | Memory: 82.2 MB (Top 27.68%)\nclass Solution {\n public int maximumSum(int[] nums) {\n HashMap map = new HashMap<>();\n int result = -1;\n\n for (int item : nums) {\n int key = getNumberTotal(item);\n\n if (!map.containsKey(key))\n map.put(key, item);\n else {\n result = Math.max(result, map.get(key) + item);\n map.put(key, Math.max(map.get(key), item));\n }\n }\n\n return result;\n }\n\n int getNumberTotal(int num) {\n int result = 0;\n while (num > 0) {\n result += num % 10;\n num /= 10;\n }\n\n return result;\n }\n}", + "title": "2342. Max Sum of a Pair With Equal Sum of Digits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j , such that i != j , and the sum of digits of the number nums[i] is equal to that of nums[j] . Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [18,43,36,13,7]\nOutput:54\nExplanation:The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,12,19,14]\nOutput:-1\nExplanation:There are no two numbers that satisfy the conditions, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: # The plan here is to:\n # \n # • sort the elements of nums into a dict of maxheaps,\n # according to sum-of-digits.\n #\n # • For each key, determine whether there are at least two \n # elements in that key's values, and if so, compute the\n # product of the greatest two elements.\n #\n # • return the the greatest such product as the answer.\n\n # For example:\n\t\t\t\t\t\n # nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}\n\t\t\t\t\t\n # Only two keys qualify, 3 and 6, for which the greatest two elements\n # are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,\n # so the answer is 39.\n\n def maximumSum(self, nums: List[int]) -> int:\n d, mx = defaultdict(list), -1\n digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function\n \n for n in nums: # <-- construct max-heaps\n heappush(d[digits(n)],-n) # (note \"-n\") \n\n for i in d: # <-- pop the two greatest values off\n if len(d[i]) > 1: # each maxheap (when possible) and\n mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value.\n \n return mx", + "title": "2342. Max Sum of a Pair With Equal Sum of Digits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput:2\nExplanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 388 ms (Top 6.05%) | Memory: 45.20 MB (Top 6.85%)\n\nclass Solution {\n public int maxSumSubmatrix(int[][] matrix, int tar) {\n int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar;\n for(i=0;i0) dp[i][j]+=dp[i][j-1];\n }\n }\n for(i=0;i0) dp[i][j]+=dp[i-1][j];\n }\n }\n for(i=0;i=0 && (j-1)>=0) val += dp[i-1][j-1];\n if((i-1)>=0) val=val-dp[i-1][l];\n if((j-1)>=0) val=val-dp[k][j-1];\n if(val>max && val<=target) max=val;\n }\n }\n }\n }\n return max;\n }\n}\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput:2\nExplanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maxSumSubmatrix(int[][] matrix, int k) {\n final int m = matrix.length;\n if (m < 1) {\n throw new IllegalArgumentException(\"empty matrix - no rows\");\n }\n final int n = matrix[0].length;\n if (n < 1) {\n throw new IllegalArgumentException(\"empty matrix - no columns\");\n }\n // Let's make our bottom-right sum matrix wider and higher by 1 each, so we don't go out of range.\n // All of the values r >= m and c >= n should be 0 (and will default to 0 during array construction).\n final int[][] brsum = new int[m + 1][n + 1];\n // Build up from bottom right, bottom to top and right to left.\n for (int r = (m - 1); r >= 0; --r) {\n for (int c = (n - 1); c >= 0; --c) {\n final int val = matrix[r][c];\n // did we happen to find a 1x1 rectangle at (r, c) which sums to k?\n if (val == k) {\n return val;\n }\n // Extend the sum: value + right + down - rightAndDown (because rightAndDown was added twice)\n brsum[r][c] = matrix[r][c] + brsum[r][c + 1] + brsum[r + 1][c] - brsum[r + 1][c + 1];\n }\n }\n // Now, we search.\n int maxSum = Integer.MIN_VALUE;\n for (int r0 = 0; r0 < m; ++r0) {\n for (int rf = r0; rf < m; ++rf) {\n final int rfp1 = rf + 1; // Let's avoid computing rf + 1 many times.\n for (int c0 = 0; c0 < n; ++c0) {\n for (int cf = c0; cf < n; ++cf) {\n final int cfp1 = cf + 1; // Let's avoid computing cf + 1 multiple times.\n\t\t\t\t\t\t// Compute the sum for this rectangle: complete - right - lower + lower_right.\n final int sum = brsum[r0][c0] + brsum[rfp1][cfp1] - brsum[r0][cfp1] - brsum[rfp1][c0];\n\t\t\t\t\t\t// Did we happen to find a sum adding to k? If not, did we find a larger sum less than k?\n if (sum == k) {\n return sum;\n } else if (sum < k && sum > maxSum) {\n maxSum = sum;\n }\n }\n }\n }\n }\n return maxSum;\n }\n\n}\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput:2\nExplanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n import numpy as np\n \n matrix = np.array(matrix, dtype=np.int32)\n \n M,N = matrix.shape\n \n ret = float(\"-inf\")\n \n CUM = np.zeros((M,N), dtype=np.int32)\n for shift_r in range(M):\n CUM[:M-shift_r] += matrix[shift_r:]\n \n _CUM = np.zeros((M-shift_r,N), dtype=np.int32)\n for shift_c in range(N):\n _CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]\n tmp = _CUM[(_CUM<=k) & (_CUM>ret)]\n if tmp.size:\n ret = tmp.max()\n if ret == k:\n return ret\n \n return ret\n\n'''\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [x i , y i ] such that x i < x j for all 1 <= i < j <= points.length . You are also given an integer k . Return the maximum value of the equation y i + y j + |x i - x j | where |x i - x j | <= k and 1 <= i < j <= points.length . It is guaranteed that there exists at least one pair of points that satisfy the constraint |x i - x j | <= k .", + "description_images": [], + "constraints": [ + "2 <= points.length <= 10^5", + "points[i].length == 2", + "-10^8 <= x i , y i <= 10^8", + "0 <= k <= 2 * 10^8", + "x i < x j for all 1 <= i < j <= points.length", + "x i form a strictly increasing sequence." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\nOutput:4\nExplanation:The first two points satisfy the condition |xi- xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.", + "image": null + }, + { + "text": "Example 2: Input:points = [[0,0],[3,0],[9,2]], k = 3\nOutput:3\nExplanation:Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 80.93%) | Memory: 104.9 MB (Top 83.74%)\nclass Solution {\n public int findMaxValueOfEquation(int[][] points, int k) {\n int ans=Integer.MIN_VALUE;\n int i=0;\n int f=1;\n while(i < points.length) {\n if(f(points[i][0]+k))\n break;\n if((points[i][1]+points[j][1]+points[j][0]-points[i][0])>ans){\n ans=points[i][1]+points[j][1]+points[j][0]-points[i][0];\n f=j-1;\n }\n }\n i++;\n }\n return ans;\n }\n}", + "title": "1499. Max Value of Equation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [x i , y i ] such that x i < x j for all 1 <= i < j <= points.length . You are also given an integer k . Return the maximum value of the equation y i + y j + |x i - x j | where |x i - x j | <= k and 1 <= i < j <= points.length . It is guaranteed that there exists at least one pair of points that satisfy the constraint |x i - x j | <= k .", + "description_images": [], + "constraints": [ + "2 <= points.length <= 10^5", + "points[i].length == 2", + "-10^8 <= x i , y i <= 10^8", + "0 <= k <= 2 * 10^8", + "x i < x j for all 1 <= i < j <= points.length", + "x i form a strictly increasing sequence." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\nOutput:4\nExplanation:The first two points satisfy the condition |xi- xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.", + "image": null + }, + { + "text": "Example 2: Input:points = [[0,0],[3,0],[9,2]], k = 3\nOutput:3\nExplanation:Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n \"\"\"\n Eqn is: yi + yj + |xi - xj|\n Since points is sorted by x values, \n therefore, xj will always be greater than xi\n therefore xi - xj will always be negative\n So the above eqn can be rewritten as,\n (yj+xj) + (yi-xi)\n Now the problem boils down to finding maximum in sliding window of k size.\n (https://leetcode.com/problems/sliding-window-maximum/discuss/1911533/Python-or-Dequeue-or-Sliding-Window-or-Simple-Solution)\n \"\"\"\n queue = deque()\n maxVal = -sys.maxsize\n for x,y in points:\n while queue and abs(queue[0][0] - x) > k:\n queue.popleft()\n \n if queue:\n maxVal = max(maxVal, y+x+queue[0][1])\n \n while queue and queue[-1][1] <= y-x:\n queue.pop()\n \n queue.append((x, y-x))\n \n return maxVal\n", + "title": "1499. Max Value of Equation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput:4\nExplanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput:5\nExplanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput:5\nExplanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 12.52%) | Memory: 44.60 MB (Top 24.53%)\n\nclass Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n int[] degree = new int[n];\n Set roadSet = new HashSet<>();\n \n for (int[] road : roads) {\n degree[road[0]]++;\n degree[road[1]]++;\n roadSet.add(road[0] + \",\" + road[1]);\n roadSet.add(road[1] + \",\" + road[0]);\n }\n\n int maxRank = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n int rank = degree[i] + degree[j];\n if (roadSet.contains(i + \",\" + j)) {\n rank--;\n }\n maxRank = Math.max(maxRank, rank);\n }\n }\n\n return maxRank;\n }\n}\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput:4\nExplanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput:5\nExplanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput:5\nExplanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n \n //number of road connected to city\n int[] numRoadsConnectedCity = new int[100 + 1];\n \n //road exist between two two cities\n boolean[][] raadExist = new boolean[n][n];\n \n for(int[] cities : roads){\n \n //increment the count of numbers of connected city\n numRoadsConnectedCity[cities[0]]++;\n numRoadsConnectedCity[cities[1]]++;\n \n //mark road exist, between two cities\n raadExist[cities[0]][cities[1]] = true;\n raadExist[cities[1]][cities[0]] = true;\n }\n \n \n \n int maxRank = 0;\n for(int city1 = 0; city1 < n - 1; city1++){\n for(int city2 = city1 + 1; city2 < n; city2++){\n \n //count total number of road connected to both city\n int rank = numRoadsConnectedCity[city1] + numRoadsConnectedCity[city2];\n \n //just decrement the rank, if both city connected\n if(raadExist[city1][city2]) rank--;\n \n maxRank = Math.max(maxRank, rank);\n }\n }\n \n \n return maxRank;\n }\n}\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput:4\nExplanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput:5\nExplanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput:5\nExplanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximalNetworkRank(self, n: int, roads) -> int:\n max_rank = 0\n connections = {i: set() for i in range(n)}\n for i, j in roads:\n connections[i].add(j)\n connections[j].add(i)\n for i in range(n - 1):\n for j in range(i + 1, n):\n max_rank = max(max_rank, len(connections[i]) +\n len(connections[j]) - (j in connections[i]))\n return max_rank\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a rows x cols binary matrix filled with 0 's and 1 's, find the largest rectangle containing only 1 's and return its area .", + "description_images": [], + "constraints": [ + "rows == matrix.length", + "cols == matrix[i].length", + "1 <= row, cols <= 200", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput:6\nExplanation:The maximal rectangle is shown in the above picture.", + "image": "https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\"]]\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[\"1\"]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 29.92%) | Memory: 46.6 MB (Top 92.25%)\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n ArrayList list = new ArrayList<>();\n int n = matrix[0].length;\n for(int i=0; i heights) {\n Stack stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.size();\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n\n for(int i=0; i= heights.get(i))\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n\n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights.get(stack2.peek()) >= heights.get(i))\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n\n for(int i=0; i int:\n maxA = 0 #local max variable to return max area of a 1D array\n stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing\n arr.append(-1) # value for stack index -1 and one extra iteration to empty the stack\n for i in range(len(arr)): # traversing for stack from left to right\n arr[i] = int(arr[i]) # we are getting str value from matrix\n while stack and arr[stack[-1]] >= int(arr[i]): #stack is non empty and stack top is greater or equal to current element\n index = stack.pop() #pop greater element from stack and finds its area\n width = i - stack[-1] - 1 if stack else i # for empty stack width is len of 1D arr, and after poping if we have element in stack then it becomes left boundary and current index as right boundary\n maxA = max(maxA, width * arr[index]) # geting max area (L * B)\n stack.append(int(i)) # inserting each element in stack\n return maxA # return the max area\n \"\"\"Below is the code for adding each row one by one and passing it to above function to get the max area for each row\"\"\"\n # r1 - 1 0 1 0 0\n # r2 - 1 0 1 1 1\n # r = 2 0 2 1 1 This is for else condition\n\n # r1 - 1 1 1 0 1\n # r2 - 1 0 1 1 0\n # r = 2 0 2 1 0 This is for if condition\n\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n result = [0] * len(matrix[0])\n maxReact = 0\n maxReact = self.maxArea(result)\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = int(matrix[i][j])\n if matrix[i][j] == 0:\n result[j] = 0\n else:\n result[j] = result[j] + matrix[i][j]\n maxReact = max(maxReact,self.maxArea(result)) #after getting max area for 1D arr we are getting max value from those 1D arr for the 2D arr\n return maxReact\n", + "title": "85. Maximal Rectangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 98.27%) | Memory: 53.6 MB (Top 98.31%)\nclass Solution {\n public int maximalSquare(char[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] dp = new int[m][n];\n\n int max = 0;\n\n for (int i = 0; i < m; i++) {\n dp[i][0] = matrix[i][0] - 48;\n if (matrix[i][0] == '1') max = 1;\n }\n for (int i = 0; i < n; i++) {\n dp[0][i] = matrix[0][i] - 48;\n if (matrix[0][i] == '1') max = 1;\n }\n\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][j] == '1') {\n dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;\n if (dp[i][j] > max) {\n max = dp[i][j];\n }\n }\n }\n }\n\n return max * max;\n }\n}", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 499 ms (Top 97.16%) | Memory: 19.30 MB (Top 88.93%)\n\nclass Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n m, n = len(matrix), len(matrix[0])\n result = 0\n dp = [[0]*n for _ in range(m)] # dp[x][y] is the length of the maximal square at (x, y)\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == '1': # ensure this condition first\n # perform computation, mind border restrictions\n dp[i][j] = min(dp[i-1][j] if i > 0 else 0,\n dp[i][j-1] if j > 0 else 0,\n dp[i-1][j-1] if i > 0 and j > 0 else 0) + 1\n if dp[i][j] > result:\n result = dp[i][j]\n return result*result\n", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the i th seat, and seats[i] = 0 represents that the i th seat is empty (0-indexed) . There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person .", + "description_images": [], + "constraints": [ + "2 <= seats.length <= 2 * 10^4", + "seats[i] is 0 or 1 .", + "At least one seat is empty .", + "At least one seat is occupied ." + ], + "examples": [ + { + "text": "Example 1: Input:seats = [1,0,0,0,1,0,1]\nOutput:2\nExplanation:If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/distance.jpg" + }, + { + "text": "Example 2: Input:seats = [1,0,0,0]\nOutput:3\nExplanation:If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.", + "image": null + }, + { + "text": "Example 3: Input:seats = [0,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 6.92%) | Memory: 49.9 MB (Top 21.03%)\n\nclass Solution {\n public int maxDistToClosest(int[] seats) {\n int size = seats.length;\n int max = 0;\n int start = -1;\n int end = -1;\n\n for(int i = 0; i int:\n # strategy is greedy solution:\n # calculate local maximum for each interval: (b-a)//2\n # then take max of local maximums\n # the solution is O(n)\n # I find this solution clear, but uses 5 passes\n \n # get all the occupied seat nums\n seat_nums = [ix for ix, val in enumerate(seats) if val == 1]\n \n # check the ends\n left_max, right_max = min(seat_nums), len(seats)-max(seat_nums)-1\n \n # calculate max distance for each gap\n dists = [(y-x)//2 for x, y in zip(seat_nums, seat_nums[1:])]\n \n # take max of sitting on either end + each gap\n return max([left_max, right_max, *dists])\n", + "title": "849. Maximize Distance to Closest Person", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given four integers, m , n , introvertsCount , and extrovertsCount . You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness .", + "description_images": [], + "constraints": [ + "Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).", + "Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert)." + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\nOutput:240\nExplanation:Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/grid_happiness.png" + }, + { + "text": "Example 2: Input:m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\nOutput:260\nExplanation:Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.", + "image": null + }, + { + "text": "Example 3: Input:m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\nOutput:240", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) {\n // introvert = -1, extrovert = 1\n return dfs(m, n, 0, introvertsCount, extrovertsCount, 0, 0, new Integer[m+1][introvertsCount+1][extrovertsCount+1][(1 << (n+1))][(1 << (n+1))]);\n }\n public int dfs(int m, int n, int row, int in_count, int ex_count, int prev_in_pos, int prev_ex_pos, Integer[][][][][] dp) {\n if(dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos] != null)\n return dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos];\n if((in_count == 0 && ex_count == 0) || (row == m)) \n return 0;\n List possible_permutations = new ArrayList(); // get all possible ways to fill a row**** with given number of introverts & extroverts\n int[] aux = new int[n];\n getPermutations(in_count, ex_count, aux, 0, possible_permutations, n);\n \n int ans = 0;\n for(int[] possible : possible_permutations) {\n int curr_in_count = in_count, curr_ex_count = ex_count;\n int curr_in_pos = 0, curr_ex_pos = 0;\n for(int i = 0; i < n; i++) {\n if(possible[i] == 0)\n continue;\n if(possible[i] == -1) {\n curr_in_count--;\n curr_in_pos |= (1 << i);\n }\n else {\n curr_ex_count--;\n curr_ex_pos |= (1 << i);\n }\n }\n int curr_row_val = calculate(possible, prev_in_pos, prev_ex_pos, n); \n int rest_rows_val = dfs(m, n, row+1, curr_in_count, curr_ex_count, curr_in_pos, curr_ex_pos, dp);\n ans = Math.max(ans, curr_row_val + rest_rows_val);\n }\n return dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos] = ans;\n }\n // for each row, find happiness (keeping in account : left, right and upper neighors, for people in this row) and\n // (keeping in account : lower neighbors for people in previous row)\n public int calculate(int[] currRow, int prev_in_pos, int prev_ex_pos, int columns) {\n int res = 0;\n // vertical neighbors\n for(int i = 0; i < columns; i++) {\n if(currRow[i] == 0) continue;\n if(currRow[i] == 1) {\n res += 40;\n if( (prev_in_pos & (1 << i)) != 0) res += (20 - 30); // -30 : because previous upper neighbor is introvert\n else if( (prev_ex_pos & (1 << i)) != 0 ) res += (20 + 20);\n }\n else {\n res += 120;\n if( (prev_in_pos & (1 << i)) != 0) res += (-30 - 30);\n else if( (prev_ex_pos & (1 << i)) != 0 ) res += (-30 + 20);\n }\n }\n // horizontal neighbors\n for(int i = 0; i < columns; i++) {\n if(currRow[i] == 0) continue;\n if(currRow[i] == -1) {\n if(i-1 >= 0 && currRow[i-1] != 0) res += (-30);\n if(i+1 < columns && currRow[i+1] != 0) res += (-30);\n }\n else {\n if(i-1 >= 0 && currRow[i-1] != 0) res += (20);\n if(i+1 < columns && currRow[i+1] != 0) res += (20);\n }\n }\n return res;\n }\n public void getPermutations(int in_count, int ex_count, int[] curr, int index, List possible_permutations, int len) {\n if((in_count == 0 && ex_count == 0) || index == len) {\n int[] arr = new int[len];\n for(int i = 0; i < len; i++)\n arr[i] = curr[i];\n possible_permutations.add(arr);\n return;\n }\n if(in_count > 0) {\n curr[index] = -1;\n getPermutations(in_count-1, ex_count, curr, index+1, possible_permutations, len);\n curr[index] = 0;\n }\n if(ex_count > 0) {\n curr[index] = 1;\n getPermutations(in_count, ex_count-1, curr, index+1, possible_permutations, len);\n curr[index] = 0;\n }\n getPermutations(in_count, ex_count, curr, index+1, possible_permutations, len);\n }\n}\n", + "title": "1659. Maximize Grid Happiness", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given four integers, m , n , introvertsCount , and extrovertsCount . You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness .", + "description_images": [], + "constraints": [ + "Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).", + "Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert)." + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\nOutput:240\nExplanation:Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/grid_happiness.png" + }, + { + "text": "Example 2: Input:m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\nOutput:260\nExplanation:Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.", + "image": null + }, + { + "text": "Example 3: Input:m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\nOutput:240", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n \n @cache\n def fn(prev, i, j, intro, extro): \n \"\"\"Return max grid happiness at (i, j).\"\"\"\n if i == m: return 0 # no more position\n if j == n: return fn(prev, i+1, 0, intro, extro)\n if intro == extro == 0: return 0 \n \n prev0 = prev[:j] + (0,) + prev[j+1:]\n ans = fn(prev0, i, j+1, intro, extro)\n if intro: \n val = 120 \n if i and prev[j]: # neighbor from above \n val -= 30 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: # neighbor from left \n val -= 30 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (1,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro-1, extro))\n if extro: \n val = 40 \n if i and prev[j]: \n val += 20 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: \n val += 20 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (2,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro, extro-1))\n return ans \n \n return fn((0,)*n, 0, 0, introvertsCount, extrovertsCount)", + "title": "1659. Maximize Grid Happiness", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer primeFactors . You are asked to construct a positive integer n that satisfies the following conditions: Return the number of nice divisors of n . Since that number can be too large, return it modulo 10^9 + 7 . Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n .", + "description_images": [], + "constraints": [ + "The number of prime factors of n (not necessarily distinct) is at most primeFactors .", + "The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n . For example, if n = 12 , then its prime factors are [2,2,3] , then 6 and 12 are nice divisors, while 3 and 4 are not." + ], + "examples": [ + { + "text": "Example 1: Input:primeFactors = 5\nOutput:6\nExplanation:200 is a valid value of n.\nIt has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\nThere is not other value of n that has at most 5 prime factors and more nice divisors.", + "image": null + }, + { + "text": "Example 2: Input:primeFactors = 8\nOutput:18", + "image": null + } + ], + "follow_up": null, + "solution": "MOD = 10**9 + 7\nclass Solution:\n def maxNiceDivisors(self, n: int) -> int:\n if n <= 2: return n\n i, c = divmod(n, 3)\n if not c: return pow(3, i, MOD)\n return (self.maxNiceDivisors(n-2)*2) % MOD\n", + "title": "1808. Maximize Number of Nice Divisors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2 , both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once . Note that the character can be added even at the beginning or at the end of text . Return the maximum number of times pattern can occur as a subsequence of the modified text . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^5", + "pattern.length == 2", + "text and pattern consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abdcdbc\", pattern = \"ac\"\nOutput:4\nExplanation:If we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aabb\", pattern = \"ab\"\nOutput:6\nExplanation:Some of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 15.87%) | Memory: 54.4 MB (Top 56.08%)\nclass Solution {\n public long maximumSubsequenceCount(String text, String pattern) {\n //when pattern[0] == pattern[1]\n if (pattern.charAt(0) == pattern.charAt(1)) {\n long freq = 1;\n //O(N)\n for (int i = 0; i < text.length(); i++) {\n if (text.charAt(i) == pattern.charAt(0)) {\n freq++;\n }\n }\n //number of subsequences : choose any two characters from freq nC2\n return (freq * (freq - 1)) / 2;\n }\n\n //choice 1\n String text1 = pattern.charAt(0) + text;\n\n int freq = 0;\n long count1 = 0;\n //O(N)\n for (int i = 0; i < text1.length(); i++) {\n if (text1.charAt(i) == pattern.charAt(0)) {\n freq++;\n } else if (text1.charAt(i) == pattern.charAt(1)) {\n count1 += freq;\n }\n }\n\n //choice 2\n String text2 = text + pattern.charAt(1);\n freq = 0;\n long count2 = 0;\n //O(N)\n for (int i = text2.length() - 1; i>= 0; i--) {\n if (text2.charAt(i) == pattern.charAt(1)) {\n freq++;\n } else if (text2.charAt(i) == pattern.charAt(0)) {\n count2 += freq;\n }\n }\n\n return Math.max(count1, count2);\n }\n}", + "title": "2207. Maximize Number of Subsequences in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2 , both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once . Note that the character can be added even at the beginning or at the end of text . Return the maximum number of times pattern can occur as a subsequence of the modified text . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^5", + "pattern.length == 2", + "text and pattern consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abdcdbc\", pattern = \"ac\"\nOutput:4\nExplanation:If we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aabb\", pattern = \"ab\"\nOutput:6\nExplanation:Some of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n total = count_a = count_b = 0\n for c in text:\n if c == pattern[1]:\n total += count_a\n count_b += 1\n if c == pattern[0]:\n count_a += 1\n \n return total + max(count_a, count_b)\n", + "title": "2207. Maximize Number of Subsequences in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings, word1 and word2 . You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0 . A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.", + "description_images": [], + "constraints": [ + "Choose some non-empty subsequence subsequence1 from word1 .", + "Choose some non-empty subsequence subsequence2 from word2 .", + "Concatenate the subsequences: subsequence1 + subsequence2 , to make the string." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cacb\", word2 = \"cbba\"\nOutput:5\nExplanation:Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"ab\"\nOutput:3\nExplanation:Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"aa\", word2 = \"bb\"\nOutput:0\nExplanation:You cannot construct a palindrome from the described method, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 545 ms (Top 8.4%) | Memory: 230.95 MB (Top 8.4%)\n\nclass Solution {\n public int longestPalindrome(String word1, String word2) {\n String lWord = word1 + word2;\n return palindrome(lWord, 0, lWord.length()-1, word1.length(), false, \n new int[lWord.length()][lWord.length()][2]);\n }\n \n private int palindrome(String word, int start, int end, int boundary, boolean isFound, int[][][] dp) {\n if ((!isFound && (start >= boundary || end < boundary)) || (start > end))\n return 0;\n \n if (dp[start][end][isFound?0:1] != 0)\n return dp[start][end][isFound?0:1];\n \n return dp[start][end][isFound?0:1] = word.charAt(start) == word.charAt(end) ? \n ((start == end ? 1: 2) + palindrome(word, start+1, end-1, boundary, true, dp)) : \n Math.max(palindrome(word, start+1, end, boundary, isFound, dp), \n palindrome(word, start, end-1, boundary, isFound, dp));\n }\n}\n", + "title": "1771. Maximize Palindrome Length From Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings, word1 and word2 . You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0 . A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.", + "description_images": [], + "constraints": [ + "Choose some non-empty subsequence subsequence1 from word1 .", + "Choose some non-empty subsequence subsequence2 from word2 .", + "Concatenate the subsequences: subsequence1 + subsequence2 , to make the string." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cacb\", word2 = \"cbba\"\nOutput:5\nExplanation:Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"ab\"\nOutput:3\nExplanation:Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"aa\", word2 = \"bb\"\nOutput:0\nExplanation:You cannot construct a palindrome from the described method, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 932 ms (Top 96.15%) | Memory: 70.20 MB (Top 90.38%)\n\nclass Solution:\n\tdef longestPalindrome(self, word1: str, word2: str) -> int:\n\t\tres=0\n\t\tnew_word=word1+word2\n\t\tn,mid=len(word1)+len(word2),len(word1)\n\t\tdp=[[0]*n for _ in range(n)]\n\t\tfor i in range(n):\n\t\t\tdp[i][i]=1\n\t\tfor l in range(n-2,-1,-1):\n\t\t\tfor r in range(l+1,n,1):\n\t\t\t\tif new_word[l]==new_word[r]:\n\t\t\t\t\tdp[l][r]=(dp[l+1][r-1] if r-1>=l+1 else 0)+2\n\t\t\t\t\tif l=mid:\n\t\t\t\t\t\tres=max(res,dp[l][r])\n\t\t\t\telse:\n\t\t\t\t\tdp[l][r]=max(dp[l+1][r],dp[l][r-1])\n\t\treturn res", + "title": "1771. Maximize Palindrome Length From Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given nums , an array of positive integers of size 2 * n . You must perform n operations on this array. In the i th operation (1-indexed) , you will: Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y .", + "description_images": [], + "constraints": [ + "Choose two elements, x and y .", + "Receive a score of i * gcd(x, y) .", + "Remove x and y from nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2]\nOutput:1\nExplanation:The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,6,8]\nOutput:11\nExplanation:The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6]\nOutput:14\nExplanation:The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxScore(int[] nums) {\n int n = nums.length;\n Map gcdVal = new HashMap<>();\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n gcdVal.put((1 << i) + (1 << j), gcd(nums[i], nums[j]));\n }\n }\n \n int[] dp = new int[1 << n];\n \n for (int i = 0; i < (1 << n); ++i) {\n int bits = Integer.bitCount(i); // how many numbers are used\n if (bits % 2 != 0) // odd numbers, skip it\n continue;\n for (int k : gcdVal.keySet()) {\n if ((k & i) != 0) // overlapping used numbers\n continue;\n dp[i ^ k] = Math.max(dp[i ^ k], dp[i] + gcdVal.get(k) * (bits / 2 + 1));\n }\n }\n \n return dp[(1 << n) - 1];\n }\n \n public int gcd(int a, int b) {\n if (b == 0) \n return a; \n return gcd(b, a % b); \n }\n}\n\n// Time: O(2^n * n^2)\n// Space: O(2 ^ n)\n", + "title": "1799. Maximize Score After N Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given nums , an array of positive integers of size 2 * n . You must perform n operations on this array. In the i th operation (1-indexed) , you will: Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y .", + "description_images": [], + "constraints": [ + "Choose two elements, x and y .", + "Receive a score of i * gcd(x, y) .", + "Remove x and y from nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2]\nOutput:1\nExplanation:The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,6,8]\nOutput:11\nExplanation:The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6]\nOutput:14\nExplanation:The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6454 ms (Top 9.35%) | Memory: 24.7 MB (Top 37.40%)\nfrom functools import lru_cache\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n def gcd(a, b):\n while a:\n a, b = b%a, a\n return b\n halfplus = len(nums)//2 + 1\n @lru_cache(None)\n def dfs(mask, k):\n if k == halfplus:\n return 0\n res = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if not(mask & (1< minHeap = new PriorityQueue<>();\n for(int val : nums) minHeap.add(val);\n\n while(k > 0){\n\n int curr = minHeap.poll();\n minHeap.add(-curr);\n k--;\n }\n\n int sum = 0;\n while(!minHeap.isEmpty()){\n sum += minHeap.poll();\n }\n return sum;\n }\n}", + "title": "1005. Maximize Sum Of Array After K Negations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , modify the array in the following way: You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way .", + "description_images": [], + "constraints": [ + "choose an index i and replace nums[i] with -nums[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3], k = 1\nOutput:5\nExplanation:Choose index 1 and nums becomes [4,-2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,-1,0,2], k = 3\nOutput:6\nExplanation:Choose indices (1, 2, 2) and nums becomes [3,1,0,2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-3,-1,5,-4], k = 2\nOutput:13\nExplanation:Choose indices (1, 4) and nums becomes [2,3,-1,5,4].", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heapreplace\n\nclass Solution:\n def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:\n heapify(nums)\n while k and nums[0] < 0:\n heapreplace(nums, -nums[0])\n k -= 1\n if k % 2:\n heapreplace(nums, -nums[0])\n return sum(nums)", + "title": "1005. Maximize Sum Of Array After K Negations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey , where answerKey[i] is the original answer to the i th question. In addition, you are given an integer k , the maximum number of times you may perform the following operation: Return the maximum number of consecutive 'T' s or 'F' s in the answer key after performing the operation at most k times .", + "description_images": [], + "constraints": [ + "Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F' )." + ], + "examples": [ + { + "text": "Example 1: Input:answerKey = \"TTFF\", k = 2\nOutput:4\nExplanation:We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.", + "image": null + }, + { + "text": "Example 2: Input:answerKey = \"TFFT\", k = 1\nOutput:3\nExplanation:We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.", + "image": null + }, + { + "text": "Example 3: Input:answerKey = \"TTFTTFTT\", k = 1\nOutput:5\nExplanation:We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 6.64%) | Memory: 48.1 MB (Top 51.04%)\n\nclass Solution {\n\n // Binary Search + Sliding Window fixed\n\n public int maxConsecutiveAnswers(String answerKey, int k) {\n\n int start = 1 ;\n int end = answerKey.length();\n int max_length = 0 ;\n\n while(start <= end) {\n int mid = start+(end-start)/2 ;\n if(isMax(answerKey , k , mid)) {\n max_length = mid ;\n start = mid+1 ;\n }else {\n end = mid-1 ;\n }\n }\n\n return max_length ;\n }\n\n public boolean isMax(String answerKey , int k , int max_val) {\n\n int T_count = 0 ;\n int F_count = 0 ;\n\n int i = 0 ;\n int j = 0 ;\n\n while(j < answerKey.length()) {\n\n if(answerKey.charAt(j) == 'T') {\n T_count++ ;\n }else {\n F_count++ ;\n }\n\n if(j-i+1 == max_val) {\n\n if(Math.max(T_count, F_count)+k >= max_val) {\n return true ;\n }\n\n if(answerKey.charAt(i) == 'T') {\n T_count-- ;\n }else {\n F_count-- ;\n }\n\n i++ ;\n }\n\n j++ ;\n }\n\n return false ;\n }\n}\n", + "title": "2024. Maximize the Confusion of an Exam", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey , where answerKey[i] is the original answer to the i th question. In addition, you are given an integer k , the maximum number of times you may perform the following operation: Return the maximum number of consecutive 'T' s or 'F' s in the answer key after performing the operation at most k times .", + "description_images": [], + "constraints": [ + "Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F' )." + ], + "examples": [ + { + "text": "Example 1: Input:answerKey = \"TTFF\", k = 2\nOutput:4\nExplanation:We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.", + "image": null + }, + { + "text": "Example 2: Input:answerKey = \"TFFT\", k = 1\nOutput:3\nExplanation:We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.", + "image": null + }, + { + "text": "Example 3: Input:answerKey = \"TTFTTFTT\", k = 1\nOutput:5\nExplanation:We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 482 ms (Top 77.29%) | Memory: 14.4 MB (Top 36.09%)\nclass Solution:\n def maxConsecutiveAnswers(self, string: str, k: int) -> int:\n result = 0\n j = 0\n count1 = k\n for i in range(len(string)):\n if count1 == 0 and string[i] == \"F\":\n while string[j] != \"F\":\n j+=1\n count1+=1\n j+=1\n\n if string[i] == \"F\":\n if count1 > 0:\n count1-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n j = 0\n count2 = k\n for i in range(len(string)):\n if count2 == 0 and string[i] == \"T\":\n while string[j] != \"T\":\n j+=1\n count2+=1\n j+=1\n\n if string[i] == \"T\":\n if count2 > 0:\n count2-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n return result", + "title": "2024. Maximize the Confusion of an Exam", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed integer array nums representing the contents of a pile , where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: You are also given an integer k , which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves . In case it is not possible to obtain a non-empty pile after k moves, return -1 .", + "description_images": [], + "constraints": [ + "If the pile is not empty, remove the topmost element of the pile.", + "If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,2,4,0,6], k = 4\nOutput:5\nExplanation:One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2], k = 1\nOutput:-1\nExplanation:In the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 85.6 MB (Top 12.35%)\nclass Solution {\n public int maximumTop(int[] nums, int k) {\n int n = nums.length, max = -1;\n\n if(n==1){\n if(k%2==1) return -1;\n else return nums[0];\n }\n\n if(kn) k = n+1;\n\n for (int i = 0; i < k-1; i++) {\n max = Math.max(max, nums[i]);\n }\n return max;\n }\n}", + "title": "2202. Maximize the Topmost Element After K Moves", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums representing the contents of a pile , where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: You are also given an integer k , which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves . In case it is not possible to obtain a non-empty pile after k moves, return -1 .", + "description_images": [], + "constraints": [ + "If the pile is not empty, remove the topmost element of the pile.", + "If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,2,4,0,6], k = 4\nOutput:5\nExplanation:One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2], k = 1\nOutput:-1\nExplanation:In the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 498 ms (Top 63.4%) | Memory: 30.38 MB (Top 40.6%)\n\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n if k%2 != 0:\n return -1\n return nums[0]\n \n if k == 0:\n return nums[0]\n if k == len(nums):\n return max(nums[:-1])\n if k > len(nums):\n return max(nums)\n if k == 1:\n return nums[1]\n m = max(nums[:k-1])\n m = max(m, nums[k])\n return m", + "title": "2202. Maximize the Topmost Element After K Moves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer num consisting only of digits 6 and 9 . Return the maximum number you can get by changing at most one digit ( 6 becomes 9 , and 9 becomes 6 ) .", + "description_images": [], + "constraints": [ + "1 <= num <= 10^4", + "num consists of only 6 and 9 digits." + ], + "examples": [ + { + "text": "Example 1: Input:num = 9669\nOutput:9969\nExplanation:Changing the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.", + "image": null + }, + { + "text": "Example 2: Input:num = 9996\nOutput:9999\nExplanation:Changing the last digit 6 to 9 results in the maximum number.", + "image": null + }, + { + "text": "Example 3: Input:num = 9999\nOutput:9999\nExplanation:It is better not to apply any change.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximum69Number (int num) {\n int i;\n String s=String.valueOf(num);\n int l=s.length();\n int max=num;\n \n for(i=0;i 0)\n currentMinSum = 0;\n }\n return Math.max(maxSum, -minSum);\n }\n}\n", + "title": "1749. Maximum Absolute Sum of Any Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . The absolute sum of a subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is abs(nums l + nums l+1 + ... + nums r-1 + nums r ) . Return the maximum absolute sum of any (possibly empty) subarray of nums . Note that abs(x) is defined as follows:", + "description_images": [], + "constraints": [ + "If x is a negative integer, then abs(x) = -x .", + "If x is a non-negative integer, then abs(x) = x ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-3,2,3,-4]\nOutput:5\nExplanation:The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,-5,1,-4,3,-2]\nOutput:8\nExplanation:The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef maxAbsoluteSum(self, A):\n\n\t\tma,mi,res = 0,0,0\n\t\tfor a in A:\n\t\t\tma = max(0,ma+a)\n\t\t\tmi = min(0,mi+a)\n\t\t\tres = max(res,ma,-mi)\n\t\treturn res\n", + "title": "1749. Maximum Absolute Sum of Any Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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.", + "description_images": [], + "constraints": [ + "For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]\nOutput:7\nExplanation:It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,7,8]\nOutput:8\nExplanation:It is optimal to choose the subsequence [8] with alternating sum 8.", + "image": null + }, + { + "text": "Example 3: Input:nums = [6,2,1,2,4,5]\nOutput:10\nExplanation:It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxAlternatingSum(int[] nums) {\n int n = nums.length;\n long dp[][] = new long[n][2];\n dp[0][0] = nums[0];\n for(int i=1;i int:\n ans = 0\n direction = 'down'\n n = len(nums)\n for i in range(n-1):\n if direction == 'down' and nums[i] >= nums[i+1]:\n ans += nums[i]\n direction = 'up'\n elif direction == 'up' and nums[i] <= nums[i+1]:\n ans -= nums[i]\n direction = 'down'\n if direction == 'up':\n return ans\n return ans + nums[-1]", + "title": "1911. Maximum Alternating Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n . There are numSlots slots numbered from 1 to numSlots . You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.", + "description_images": [], + "constraints": [ + "For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1 ) + (3 AND 1 ) + (4 AND 2 ) + (6 AND 2 ) = 1 + 1 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6], numSlots = 3\nOutput:9\nExplanation:One possible placement is [1, 4] into slot1, [2, 6] into slot2, and [3, 5] into slot3. \nThis gives the maximum AND sum of (1 AND1) + (4 AND1) + (2 AND2) + (6 AND2) + (3 AND3) + (5 AND3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,10,4,7,1], numSlots = 9\nOutput:24\nExplanation:One possible placement is [1, 1] into slot1, [3] into slot3, [4] into slot4, [7] into slot7, and [10] into slot9.\nThis gives the maximum AND sum of (1 AND1) + (1 AND1) + (3 AND3) + (4 AND4) + (7 AND7) + (10 AND9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 93.9%) | Memory: 44.11 MB (Top 57.7%)\n\nclass Solution {\n int[] memo;\n int[] nums;\n int numSlots;\n public int maximumANDSum(int[] nums, int numSlots) {\n this.memo=new int[1<<(2*numSlots)];\n this.nums=nums;\n this.numSlots=numSlots;\n return helper(0,0);\n }\n int helper(int numIndex, int set) {\n // Base case when we used all the numbers \n if(numIndex==nums.length) return 0;\n // Set informs BOTH the slots used and the numIndex. If the later\n // statement surprises you, think it like this: We must place all\n // the numbers in a slot, so how many slots are used in numIndex=10?\n // yes! 9 slots (because we will use the 10th now!), so the set will\n // have 10 ones. No other numIndex will have 9 ones. So having memo\n // with 2 dimentions would be redundant, as you would naver have a\n // combination of numIndex 3 with sets 1, 2, 4, 6.. etc, only\n // numIndex 2 will have those sets.\n if(memo[set]>0) return memo[set]-1; // I use memo-1 so I dont have to fill it with -1\n int max=0;\n for(int i=0;i-1?firstHalfSlot:secondHalfSlot;\n if(slotChosen<0) continue; // both slots are used\n int andSum=0;\n if(slotChosen>=numSlots) andSum=((slotChosen-numSlots)+1)&nums[numIndex];\n else andSum=(slotChosen+1)&nums[numIndex];\n // By adjusting the set in the recursion signature\n // I am backtracking in an elegant way.\n max=Math.max(max, andSum+ helper(numIndex+1,set|1<= n . There are numSlots slots numbered from 1 to numSlots . You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.", + "description_images": [], + "constraints": [ + "For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1 ) + (3 AND 1 ) + (4 AND 2 ) + (6 AND 2 ) = 1 + 1 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6], numSlots = 3\nOutput:9\nExplanation:One possible placement is [1, 4] into slot1, [2, 6] into slot2, and [3, 5] into slot3. \nThis gives the maximum AND sum of (1 AND1) + (4 AND1) + (2 AND2) + (6 AND2) + (3 AND3) + (5 AND3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,10,4,7,1], numSlots = 9\nOutput:24\nExplanation:One possible placement is [1, 1] into slot1, [3] into slot3, [4] into slot4, [7] into slot7, and [10] into slot9.\nThis gives the maximum AND sum of (1 AND1) + (1 AND1) + (3 AND3) + (4 AND4) + (7 AND7) + (10 AND9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1881 ms (Top 9.44%) | Memory: 23.9 MB (Top 80.86%)\nfrom functools import lru_cache, cache\n\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n @cache\n def dp(i=0, m1=0, m2=0): # mask1, mask2\n if i == len(nums):\n return 0\n ans = 0\n for s in range(numSlots):\n if m2 & (1 << s) == 0: # i.e. 0b0?, implying the slot is not full\n if m1 & (1 << s) == 0: # 0b00 + 1 => 0b01\n nm1 = m1 | (1 << s); nm2 = m2\n else: # 0b01 + 1 => 0b10\n nm1 = m1 & ~(1 << s); nm2 = m2 | (1 << s)\n ans = max(ans, dp(i + 1, nm1, nm2) + ((s + 1) & nums[i])) # s + 1 is the actual slot no.\n return ans\n return dp()", + "title": "2172. Maximum AND Sum of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts . Since the answer can be a large number, return this modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "horizontalCuts[i] is the distance from the top of the rectangular cake to the i th horizontal cut and similarly, and", + "verticalCuts[j] is the distance from the left of the rectangular cake to the j th vertical cut." + ], + "examples": [ + { + "text": "Example 1: Input:h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput:4\nExplanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png" + }, + { + "text": "Example 2: Input:h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput:6\nExplanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png" + }, + { + "text": "Example 3: Input:h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.BigInteger;\nclass Solution {\n public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {\n Arrays.sort(horizontalCuts);\n Arrays.sort(verticalCuts);\n int i;\n int hMax=horizontalCuts[0];\n for(i=1;i hMax)\n hMax= h-horizontalCuts[horizontalCuts.length-1];\n int vMax=verticalCuts[0];\n for(i=1;i vMax)\n vMax= w-verticalCuts[verticalCuts.length-1];\n return (int)((long)hMax*vMax%1000000007);\n }\n}\n", + "title": "1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts . Since the answer can be a large number, return this modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "horizontalCuts[i] is the distance from the top of the rectangular cake to the i th horizontal cut and similarly, and", + "verticalCuts[j] is the distance from the left of the rectangular cake to the j th vertical cut." + ], + "examples": [ + { + "text": "Example 1: Input:h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput:4\nExplanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png" + }, + { + "text": "Example 2: Input:h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput:6\nExplanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png" + }, + { + "text": "Example 3: Input:h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n horizontalCuts.sort()\n verticalCuts.sort()\n \n mxHr = 0\n prev = 0\n for i in horizontalCuts:\n mxHr = max(mxHr, i-prev)\n prev = i\n mxHr = max(mxHr, h-horizontalCuts[-1])\n \n mxVr = 0\n prev = 0\n for i in verticalCuts:\n mxVr = max(mxVr, i-prev)\n prev = i\n mxVr = max(mxVr, w-verticalCuts[-1])\n \n return (mxHr * mxVr) % ((10 ** 9) + 7)\n", + "title": "1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers nums , return the maximum possible sum of an ascending subarray in nums . A subarray is defined as a contiguous sequence of numbers in an array. A subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is ascending if for all i where l <= i < r , nums i < nums i+1 . Note that a subarray of size 1 is ascending .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20,30,5,10,50]\nOutput:65\nExplanation:[5,10,50] is the ascending subarray with the maximum sum of 65.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30,40,50]\nOutput:150\nExplanation:[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "image": null + }, + { + "text": "Example 3: Input:nums = [12,17,15,13,10,11,12]\nOutput:33\nExplanation:[10,11,12] is the ascending subarray with the maximum sum of 33.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.10 MB (Top 28.39%)\n\nclass Solution {\n public int maxAscendingSum(int[] nums) {\n int res = nums[0],temp = nums[0];\n for(int i = 1;i nums[i-1])\n temp+=nums[i];\n else\n temp = nums[i];\n res = Math.max(res,temp);\n }\n return res;\n }\n}\n", + "title": "1800. Maximum Ascending Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of positive integers nums , return the maximum possible sum of an ascending subarray in nums . A subarray is defined as a contiguous sequence of numbers in an array. A subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is ascending if for all i where l <= i < r , nums i < nums i+1 . Note that a subarray of size 1 is ascending .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20,30,5,10,50]\nOutput:65\nExplanation:[5,10,50] is the ascending subarray with the maximum sum of 65.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30,40,50]\nOutput:150\nExplanation:[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "image": null + }, + { + "text": "Example 3: Input:nums = [12,17,15,13,10,11,12]\nOutput:33\nExplanation:[10,11,12] is the ascending subarray with the maximum sum of 33.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n count=nums[0]\n final=nums[0]\n for i in range(1,len(nums)):\n if nums[i]>nums[i-1]:\n count+=nums[i]\n else:\n count=nums[i]\n final=max(final,count)\n return final\n", + "title": "1800. Maximum Ascending Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes , where classes[i] = [pass i , total i ] . You know beforehand that in the i th class, there are total i total students, but only pass i number of students will pass the exam. You are also given an integer extraStudents . There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= classes.length <= 10^5", + "classes[i].length == 2", + "1 <= pass i <= total i <= 10^5", + "1 <= extraStudents <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:classes = [[1,2],[3,5],[2,2]],extraStudents= 2\nOutput:0.78333\nExplanation:You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.", + "image": null + }, + { + "text": "Example 2: Input:classes = [[2,4],[3,9],[4,5],[2,10]],extraStudents= 4\nOutput:0.53485", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 575 ms (Top 86.89%) | Memory: 100.8 MB (Top 90.16%)\nclass Solution {\n public double maxAverageRatio(int[][] classes, int extraStudents) {\n PriorityQueue pq = new PriorityQueue<>(new Comparator(){\n public int compare(double[] a, double[] b){\n double adiff = (a[0]+1)/(a[1]+1) - (a[0]/a[1]);\n double bdiff = (b[0]+1)/(b[1]+1) - (b[0]/b[1]);\n if(adiff==bdiff) return 0;\n return adiff>bdiff? -1:1;\n }\n });\n\n for(int[] c:classes) pq.add(new double[]{c[0],c[1]});\n\n for(int i =0;i float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n\n", + "title": "1792. Maximum Average Pass Ratio", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums consisting of n elements, and an integer k . Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value . Any answer with a calculation error less than 10 -5 will be accepted.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= k <= n <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,12,-5,-6,50,3], k = 4\nOutput:12.75000\nExplanation:Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 1\nOutput:5.00000", + "image": null + } + ], + "follow_up": null, + "solution": "//O(N) Time and O(1) Space - SLIDING WINDOW\n\nclass Solution {\npublic:\n double findMaxAverage(vector& nums, int k) {\n \n double ans = INT_MIN;\n \n int i = 0;\n int j = 0;\n int sum = 0;\n \n while(j int:\n v, c, l = [], 0, len(rocks)\n for i in range(l):\n p = capacity[i]-rocks[i]\n if(p>0):\n v.append(p)\n else: c += 1\n v.sort()\n k=0\n while(additionalRocks>0 and k \" 10 010 \"", + "For example, \" 00 010\" -> \" 10 010 \"", + "Operation 2: If the number contains the substring \"10\" , you can replace it with \"01\" . For example, \"000 10 \" -> \"000 01 \"", + "For example, \"000 10 \" -> \"000 01 \"" + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"000110\"\nOutput:\"111011\"\nExplanation:A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"", + "image": null + }, + { + "text": "Example 2: Input:binary = \"01\"\nOutput:\"01\"\nExplanation:\"01\" cannot be transformed any further.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 32.6%) | Memory: 45.01 MB (Top 8.1%)\n\nclass Solution {\n public String maximumBinaryString(String binary) {\n int n = binary.length();\n StringBuffer ans = new StringBuffer(\"\");\n StringBuffer buffer = new StringBuffer(\"\");\n int onesAfter1stZero = 0;\n boolean found1stZero = false;\n for(int i=0;i \" 10 010 \"", + "For example, \" 00 010\" -> \" 10 010 \"", + "Operation 2: If the number contains the substring \"10\" , you can replace it with \"01\" . For example, \"000 10 \" -> \"000 01 \"", + "For example, \"000 10 \" -> \"000 01 \"" + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"000110\"\nOutput:\"111011\"\nExplanation:A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"", + "image": null + }, + { + "text": "Example 2: Input:binary = \"01\"\nOutput:\"01\"\nExplanation:\"01\" cannot be transformed any further.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 128 ms (Top 57.69%) | Memory: 15.4 MB (Top 69.23%)\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n zero = binary.count('0') # count number of '0'\n zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists\n one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's)\n return f\"{binary[:zero_idx]}{'1'*(zero-1)}{'0'*min(zero, 1)}{'1'*one}\"", + "title": "1702. Maximum Binary String After Change", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Return the maximum binary tree built from nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000", + "All integers in nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,6,0,5]\nOutput:[6,3,5,null,2,0,null,null,1]\nExplanation:The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg" + }, + { + "text": "Example 2: Input:nums = [3,2,1]\nOutput:[3,null,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode constructMaximumBinaryTree(int[] nums) {\n TreeNode root = construct(nums,0,nums.length-1);\n return root;\n }\n \n private TreeNode construct(int []nums, int start, int end) {\n if(start > end)\n return null;\n if(start == end)\n return new TreeNode(nums[start]);\n \n int maxIdx = findMax(nums,start,end);\n TreeNode root = new TreeNode(nums[maxIdx]);\n \n root.left = construct(nums,start,maxIdx-1);\n root.right = construct(nums,maxIdx+1,end);\n \n return root;\n }\n \n private int findMax(int []arr, int low, int high) {\n int idx = -1, max = Integer.MIN_VALUE;\n for(int i=low;i<=high;++i) \n if(arr[i]>max) {\n max = arr[i];\n idx = i;\n }\n return idx;\n }\n}\n", + "title": "654. Maximum Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Return the maximum binary tree built from nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000", + "All integers in nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,6,0,5]\nOutput:[6,3,5,null,2,0,null,null,1]\nExplanation:The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg" + }, + { + "text": "Example 2: Input:nums = [3,2,1]\nOutput:[3,null,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n\t\tif not nums:\n\t\t\treturn None\n\t\tm = max(nums)\n\t\tidx = nums.index(m)\n\t\troot = TreeNode(m)\n\t\troot.left = self.constructMaximumBinaryTree(nums[:idx])\n\t\troot.right = self.constructMaximumBinaryTree(nums[idx+1:])\n\t\treturn root", + "title": "654. Maximum Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val . Just as in the previous problem , the given tree was constructed from a list a ( root = Construct(a) ) recursively with the following Construct(a) routine: Note that we were not given a directly, only a root node root = Construct(a) . Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b) .", + "description_images": [], + "constraints": [ + "If a is empty, return null .", + "Otherwise, let a[i] be the largest element of a . Create a root node with the value a[i] .", + "The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]) .", + "The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]) .", + "Return root ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,3,null,null,2], val = 5\nOutput:[5,4,null,1,3,null,null,2]\nExplanation:a = [1,4,2,3], b = [1,4,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG" + }, + { + "text": "Example 2: Input:root = [5,2,4,null,1], val = 3\nOutput:[5,2,4,null,1,null,3]\nExplanation:a = [2,1,5,4], b = [2,1,5,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG" + }, + { + "text": "Example 3: Input:root = [5,2,3,null,1], val = 4\nOutput:[5,2,4,null,1,3]\nExplanation:a = [2,1,5,3], b = [2,1,5,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode insertIntoMaxTree(TreeNode root, int val) {\n if (root==null) return new TreeNode(val);\n if (val > root.val) {\n TreeNode newRoot = new TreeNode(val);\n newRoot.left = root;\n return newRoot;\n }\n root.right = insertIntoMaxTree(root.right, val);\n return root;\n }\n}\n", + "title": "998. Maximum Binary Tree II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val . Just as in the previous problem , the given tree was constructed from a list a ( root = Construct(a) ) recursively with the following Construct(a) routine: Note that we were not given a directly, only a root node root = Construct(a) . Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b) .", + "description_images": [], + "constraints": [ + "If a is empty, return null .", + "Otherwise, let a[i] be the largest element of a . Create a root node with the value a[i] .", + "The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]) .", + "The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]) .", + "Return root ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,3,null,null,2], val = 5\nOutput:[5,4,null,1,3,null,null,2]\nExplanation:a = [1,4,2,3], b = [1,4,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG" + }, + { + "text": "Example 2: Input:root = [5,2,4,null,1], val = 3\nOutput:[5,2,4,null,1,null,3]\nExplanation:a = [2,1,5,4], b = [2,1,5,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG" + }, + { + "text": "Example 3: Input:root = [5,2,3,null,1], val = 4\nOutput:[5,2,4,null,1,3]\nExplanation:a = [2,1,5,3], b = [2,1,5,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n approach:\n given a, we can get the inorder traversal of it, then append val to it and\n then construct the tree back\n \"\"\"\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n inorder_list = []\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n inorder_list.append(root.val)\n inorder(root.right)\n \n inorder(root)\n inorder_list.append(val)\n \n def get_maximum(val_list):\n max_index = -1\n max_val = -1\n for i, val in enumerate(val_list):\n if val > max_val:\n max_val = val\n max_index = i\n return max_index, max_val\n \n def create_tree(val_list):\n if not len(val_list):\n return None\n index, val = get_maximum(val_list)\n node = TreeNode(val)\n node.left = create_tree(val_list[:index])\n node.right = create_tree(val_list[index+1:])\n return node\n \n b = create_tree(inorder_list)\n return b\n", + "title": "998. Maximum Binary Tree II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n . However, there are city restrictions on the heights of the new buildings: Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [id i , maxHeight i ] indicates that building id i must have a height less than or equal to maxHeight i . It is guaranteed that each building will appear at most once in restrictions , and building 1 will not be in restrictions . Return the maximum possible height of the tallest building .", + "description_images": [], + "constraints": [ + "The height of each building must be a non-negative integer.", + "The height of the first building must be 0 .", + "The height difference between any two adjacent buildings cannot exceed 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, restrictions = [[2,1],[4,1]]\nOutput:2\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex1-1.png" + }, + { + "text": "Example 2: Input:n = 6, restrictions = []\nOutput:5\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex2.png" + }, + { + "text": "Example 3: Input:n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput:5\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 143 ms (Top 19.44%) | Memory: 114.3 MB (Top 55.56%)\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n List list=new ArrayList<>();\n list.add(new int[]{1,0});\n for(int[] restriction:restrictions){\n list.add(restriction);\n }\n Collections.sort(list,new IDSorter());\n\n if(list.get(list.size()-1)[0]!=n){\n list.add(new int[]{n,n-1});\n }\n\n for(int i=1;i=0;i--){\n list.get(i)[1]=Math.min(list.get(i)[1],list.get(i+1)[1] + list.get(i+1)[0] - list.get(i)[0]);\n }\n\n int result=0;\n for(int i=1;i{\n @Override\n public int compare(int[] myself,int[] other){\n return myself[0]-other[0];\n }\n }\n}", + "title": "1840. Maximum Building Height", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n . However, there are city restrictions on the heights of the new buildings: Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [id i , maxHeight i ] indicates that building id i must have a height less than or equal to maxHeight i . It is guaranteed that each building will appear at most once in restrictions , and building 1 will not be in restrictions . Return the maximum possible height of the tallest building .", + "description_images": [], + "constraints": [ + "The height of each building must be a non-negative integer.", + "The height of the first building must be 0 .", + "The height difference between any two adjacent buildings cannot exceed 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, restrictions = [[2,1],[4,1]]\nOutput:2\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex1-1.png" + }, + { + "text": "Example 2: Input:n = 6, restrictions = []\nOutput:5\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex2.png" + }, + { + "text": "Example 3: Input:n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput:5\nExplanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1203 ms (Top 88.37%) | Memory: 55.60 MB (Top 9.3%)\n\n#Readability version\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # Set the initial height for the 1st building\n restrictions.append([1, 0])\n restrictions.sort()\n\n # Process restrictions to find the valid ones for reaching previous restrictions\n valid_restrictions_forward = []\n temp_diff = 0\n for id, ht in restrictions:\n current_diff = id - ht\n if current_diff >= temp_diff:\n temp_diff = current_diff\n valid_restrictions_forward.append([id, ht])\n\n # Process valid restrictions backward to find the ones for reaching next restrictions\n valid_restrictions_backward = []\n temp_sum = n + n - 1\n for id, ht in valid_restrictions_forward[::-1]:\n current_sum = id + ht\n if current_sum <= temp_sum:\n temp_sum = current_sum\n valid_restrictions_backward.append([id, ht])\n\n # Reverse the backward valid restrictions to get the correct order\n valid_restrictions_backward.reverse()\n\n # Add maximum height for the last building due to the last restriction\n if valid_restrictions_backward[-1][0] != n:\n valid_restrictions_backward.append([n, valid_restrictions_backward[-1][1] + n - valid_restrictions_backward[-1][0]])\n\n # Calculate the maximum height\n max_height = 0\n for i in range(len(valid_restrictions_backward) - 1):\n x1, y1 = valid_restrictions_backward[i]\n x2, y2 = valid_restrictions_backward[i + 1]\n available_height = (-x1 + y1 + x2 + y2) // 2\n if available_height > max_height:\n max_height = available_height\n\n return max_height\n\n", + "title": "1840. Maximum Building Height", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array candies . Each element in the array denotes a pile of candies of size candies[i] . You can divide each pile into any number of sub piles , but you cannot merge two piles together. You are also given an integer k . You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get.", + "description_images": [], + "constraints": [ + "1 <= candies.length <= 10^5", + "1 <= candies[i] <= 10^7", + "1 <= k <= 10^12" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [5,8,6], k = 3\nOutput:5\nExplanation:We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.", + "image": null + }, + { + "text": "Example 2: Input:candies = [2,5], k = 11\nOutput:0\nExplanation:There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canSplit(int[] candies, long k, long mid) {\n long split = 0;\n for(int i = 0; i < candies.length; ++i) {\n split += candies[i]/mid;\n } \n if(split >= k)\n return true;\n else\n return false;\n }\n \n public int maximumCandies(int[] candies, long k) {\n long sum = 0;\n for(int i = 0; i < candies.length; ++i) {\n sum += candies[i];\n }\n long start = 1, end = sum;\n long ans = 0;\n while(start <= end) {\n long mid = (start + end)/2;\n if(canSplit(candies, k, mid)) {\n ans = mid;\n start = mid + 1;\n } else {\n end = mid-1;\n }\n }\n return (int)ans;\n }\n}\n", + "title": "2226. Maximum Candies Allocated to K Children", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array candies . Each element in the array denotes a pile of candies of size candies[i] . You can divide each pile into any number of sub piles , but you cannot merge two piles together. You are also given an integer k . You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get.", + "description_images": [], + "constraints": [ + "1 <= candies.length <= 10^5", + "1 <= candies[i] <= 10^7", + "1 <= k <= 10^12" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [5,8,6], k = 3\nOutput:5\nExplanation:We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.", + "image": null + }, + { + "text": "Example 2: Input:candies = [2,5], k = 11\nOutput:0\nExplanation:There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3294 ms (Top 14.29%) | Memory: 27.4 MB (Top 62.05%)\ndef canSplit(candies, mid, k):\n split = 0\n for i in candies:\n split += i//mid\n if split >= k:\n return True\n else:\n return False\n\nclass Solution:\n def maximumCandies(self, candies: List[int], k: int) -> int:\n end = sum(candies)//k\n start = 1\n ans = 0\n while start <= end:\n mid = (start + end)//2\n if canSplit(candies, mid, k):\n start = mid + 1\n ans = mid\n else:\n end = mid - 1\n return ans\n", + "title": "2226. Maximum Candies Allocated to K Children", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n boxes labeled from 0 to n - 1 . You are given four arrays: status , candies , keys , and containedBoxes where: You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above .", + "description_images": [], + "constraints": [ + "status[i] is 1 if the i th box is open and 0 if the i th box is closed,", + "candies[i] is the number of candies in the i th box,", + "keys[i] is a list of the labels of the boxes you can open after opening the i th box.", + "containedBoxes[i] is a list of the boxes you found inside the i th box." + ], + "examples": [ + { + "text": "Example 1: Input:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\nOutput:16\nExplanation:You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.", + "image": null + }, + { + "text": "Example 2: Input:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\nOutput:6\nExplanation:You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 61.19%) | Memory: 57.10 MB (Top 59.7%)\n\nclass Solution {\n\t\tpublic int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes)\n\t\t{\n\t\t\tint n=initialBoxes.length;\n\n\t\t\tif(n==0)\n\t\t\t\treturn 0;\n\n\t\t\tQueue q=new LinkedList<>();\n\t\t\tint totalCandies=0;\n\n\t\t\tfor(int i:initialBoxes)\n\t\t\t{\n if(status[i]==0)\n {\n q.add(i);\n }\n else\n {\n totalCandies+=candies[i]; // Add all Candies of intial box;\n for(int j=0;j0 && isValid(q,status))\n\t\t\t{\n\t\t\t\tint b=q.poll();\n\t\t\t\tif(status[b]==1)\n\t\t\t\t{\n\t\t\t\t\ttotalCandies+=candies[b]; // Add all Candies of selected box;\n\n\n\t\t\t\t\tfor(int j=0;j q,int[] status) \n\t\t{\n\t\t\tQueue cq=new LinkedList<>(q);\n\n\t\t\twhile(cq.size()>0)\n\t\t\t{\n\t\t\t\tif(status[cq.poll()]==1)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n", + "title": "1298. Maximum Candies You Can Get from Boxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n boxes labeled from 0 to n - 1 . You are given four arrays: status , candies , keys , and containedBoxes where: You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above .", + "description_images": [], + "constraints": [ + "status[i] is 1 if the i th box is open and 0 if the i th box is closed,", + "candies[i] is the number of candies in the i th box,", + "keys[i] is a list of the labels of the boxes you can open after opening the i th box.", + "containedBoxes[i] is a list of the boxes you found inside the i th box." + ], + "examples": [ + { + "text": "Example 1: Input:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\nOutput:16\nExplanation:You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.", + "image": null + }, + { + "text": "Example 2: Input:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\nOutput:6\nExplanation:You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n count = 0 # Found candy. Class variable to keep found candy\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n boxes = [] # Newly found boxes\n progress = False\n for box in initialBoxes:\n if status[box]: # The box is open\n progress = True\n boxes.extend(containedBoxes[box]) # Add newly found boxes\n self.count += candies[box] # Count found candy\n for key in keys[box]:\n status[key] = 1 # Use found keys to open boxes even if we don't have them.\n else:\n boxes.append(box) # The box is closed. Keep it for the next iteration.\n if not progress: # Nothing happened. return.\n return self.count\n\t\t# Run another iteration with the new 'boxes'\n return self.maxCandies(status, candies, keys, containedBoxes, boxes)\n", + "title": "1298. Maximum Candies You Can Get from Boxes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1 . The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the i th student ( 0-indexed ). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the j th mentor ( 0-indexed ). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores . Given students and mentors , return the maximum compatibility score sum that can be achieved.", + "description_images": [], + "constraints": [ + "For example, if the student's answers were [1, 0 , 1 ] and the mentor's answers were [0, 0 , 1 ] , then their compatibility score is 2 because only the second and the third answers are the same." + ], + "examples": [ + { + "text": "Example 1: Input:students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput:8\nExplanation:We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.", + "image": null + }, + { + "text": "Example 2: Input:students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput:0\nExplanation:The compatibility score of any student-mentor pair is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 29.11%) | Memory: 42.3 MB (Top 38.61%)\nclass Solution {\n int max;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n boolean[] visited = new boolean[students.length];\n helper(visited, students, mentors, 0, 0);\n return max;\n }\n public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos, int score){\n if(pos >= students.length){\n max = Math.max(max, score);\n return;\n }\n for(int i = 0; i < mentors.length; i++)\n if(!visited[i]){\n visited[i] = true;\n helper(visited, students, mentors, pos + 1, score + score(students[pos], mentors[i]));\n visited[i] = false;\n }\n }\n public int score(int[] a, int[] b){\n int count = 0;\n\n for(int i = 0; i < b.length; i++)\n if(a[i] == b[i]) count += 1;\n return count;\n }\n}", + "title": "1947. Maximum Compatibility Score Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1 . The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the i th student ( 0-indexed ). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the j th mentor ( 0-indexed ). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores . Given students and mentors , return the maximum compatibility score sum that can be achieved.", + "description_images": [], + "constraints": [ + "For example, if the student's answers were [1, 0 , 1 ] and the mentor's answers were [0, 0 , 1 ] , then their compatibility score is 2 because only the second and the third answers are the same." + ], + "examples": [ + { + "text": "Example 1: Input:students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput:8\nExplanation:We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.", + "image": null + }, + { + "text": "Example 2: Input:students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput:0\nExplanation:The compatibility score of any student-mentor pair is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 104 ms (Top 82.18%) | Memory: 13.9 MB (Top 66.34%)\nimport heapq\nfrom collections import defaultdict\n\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m, n = len(students), len(students[0])\n def hamming(student, mentor):\n return sum([int(student[i] != mentor[i]) for i in range(n)])\n\n pq = [(0, 0, '0'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)\n optimal = defaultdict(lambda:float('inf'))\n\n while pq: # O(V)\n cost, i, mentor_status = heapq.heappop(pq) # O(logV)\n\n # early stopping with termination condition\n if i == m:\n return m * n - cost\n\n # generate successors. The next student to be assigned is at index i\n for j, mentor in enumerate(mentors): # O(m)\n if mentor_status[j] != '1':\n new_cost = cost + hamming(students[i], mentor)\n new_mentor_status = mentor_status[:j] + '1' + mentor_status[j+1:]\n\n # update optimal cost if a new successor appears with lower cost to the same node\n if new_cost < optimal[(i+1, new_mentor_status)]:\n optimal[(i+1, new_mentor_status)] = new_cost\n heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV)\n\n return 0", + "title": "1947. Maximum Compatibility Score Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors , used for relaxation only. You are given two integers bottom and top , which denote that Alice has rented all the floors from bottom to top ( inclusive ). You are also given the integer array special , where special[i] denotes a special floor that Alice has designated for relaxation. Return the maximum number of consecutive floors without a special floor .", + "description_images": [], + "constraints": [ + "1 <= special.length <= 10^5", + "1 <= bottom <= special[i] <= top <= 10^9", + "All the values of special are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = 2, top = 9, special = [4,6]\nOutput:3\nExplanation:The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.", + "image": null + }, + { + "text": "Example 2: Input:bottom = 6, top = 8, special = [7,6,8]\nOutput:0\nExplanation:Every floor rented is a special floor, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 13.68%) | Memory: 77.1 MB (Top 37.46%)\nclass Solution {\n public int maxConsecutive(int bottom, int top, int[] special) {\n int max = Integer.MIN_VALUE;\n\n Arrays.sort(special);\n\n // from bottom to the first special floor\n max = Math.max(max, special[0] - bottom);\n\n // middle floors\n for(int i = 1; i < special.length; i++) {\n max = Math.max(max, special[i] - special[i - 1] - 1);\n }\n\n // from last special floor to the top\n max = Math.max(max, top - special[special.length - 1]);\n\n return max;\n }\n}", + "title": "2274. Maximum Consecutive Floors Without Special Floors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors , used for relaxation only. You are given two integers bottom and top , which denote that Alice has rented all the floors from bottom to top ( inclusive ). You are also given the integer array special , where special[i] denotes a special floor that Alice has designated for relaxation. Return the maximum number of consecutive floors without a special floor .", + "description_images": [], + "constraints": [ + "1 <= special.length <= 10^5", + "1 <= bottom <= special[i] <= top <= 10^9", + "All the values of special are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = 2, top = 9, special = [4,6]\nOutput:3\nExplanation:The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.", + "image": null + }, + { + "text": "Example 2: Input:bottom = 6, top = 8, special = [7,6,8]\nOutput:0\nExplanation:Every floor rented is a special floor, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n special.sort()\n special.insert(0, bottom - 1)\n special.append(top + 1)\n \n ans = 0\n for i in range(len(special)-1):\n ans = max(ans, special[i+1] - special[i] - 1)\n return ans\n", + "title": "2274. Maximum Consecutive Floors Without Special Floors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(TreeNode root) {\n // Base Condition\n if(root == null) return 0;\n // Hypothesis\n int left = maxDepth(root.left);\n int right = maxDepth(root.right);\n // Induction\n return Math.max(left, right) + 1;\n }\n}\n", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 88.16%) | Memory: 16.3 MB (Top 23.73%)\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n depths = []\n self.handler(root, result, depths)\n return max(depths)\n\n def handler(self, root, result, depths):\n if root:\n result += 1\n self.handler(root.left, result, depths)\n self.handler(root.right, result, depths)\n else:\n depths.append(result)", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:3", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(Node root) {\n if (root == null) return 0;\n int[] max = new int[]{0};\n dfs(root,1,max);\n return max[0];\n }\n public static void dfs(Node root, int depth, int[] max) {\n if (depth>max[0]) max[0] = depth;\n if(root==null){\n return;\n }\n ++depth;\n for(Node n:root.children) dfs(n, depth, max);\n }\n}\n", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:3", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\n#DFS\nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n if root is None:\n return 0\n def dfs(r):\n \n if not r.children:\n return 1\n depth = 0\n for child in r.children:\n depth = max(depth, dfs(child) + 1)\n \n return depth\n\n return dfs(root)\n\t\t\n\t\t\n#BFS \nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n if root is None:\n return 0\n def bfs(r):\n \n q = []\n q.append(root)\n level = 0\n while q != []:\n num_nodes = len(q)\n level += 1\n for _ in range(num_nodes):\n node = q.pop(0)\n\n for child in node.children:\n q.append(child)\n return level\n\n return bfs(root)\n\n", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:3", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDepth(self, root: 'Node') -> int:\n \n if not root : return 0\n \n if root.children :\n return 1 + max([self.maxDepth(x) for x in root.children])\n else :\n return 1 ", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a 0-indexed integer array nums of size n , find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i] ), such that 0 <= i < j < n and nums[i] < nums[j] . Return the maximum difference . If no such i and j exists, return -1 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 1000", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,1,5,4]\nOutput:4\nExplanation:The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,3,2]\nOutput:-1\nExplanation:There is no i and j such that i < j and nums[i] < nums[j].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,2,10]\nOutput:9\nExplanation:The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 99.17%)\nclass Solution {\n public int maximumDifference(int[] nums) {\n if(nums.length < 2)\n return -1;\n int result = Integer.MIN_VALUE;\n int minValue = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > minValue)\n result = Math.max(result, nums[i] - minValue);\n minValue = Math.min(minValue, nums[i]);\n }\n return result == Integer.MIN_VALUE ? -1 : result;\n }\n}", + "title": "2016. Maximum Difference Between Increasing Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 0-indexed integer array nums of size n , find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i] ), such that 0 <= i < j < n and nums[i] < nums[j] . Return the maximum difference . If no such i and j exists, return -1 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 1000", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,1,5,4]\nOutput:4\nExplanation:The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,3,2]\nOutput:-1\nExplanation:There is no i and j such that i < j and nums[i] < nums[j].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,2,10]\nOutput:9\nExplanation:The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curmin = nums[0]\n diff = 0\n for num in nums:\n diff = max(diff, num - curmin)\n curmin = min(curmin, num)\n return diff or -1\n", + "title": "2016. Maximum Difference Between Increasing Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b . A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5000] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput:7\nExplanation:We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2,null,0,3]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 70.91%) | Memory: 41.7 MB (Top 98.42%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxAncestorDiff(TreeNode root) {\n\n if (root == null) return 0;\n\n return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n\n public int find(TreeNode root, int min, int max) {\n if (root == null) return Math.abs(max-min);\n\n min = Math.min(min, root.val);\n max = Math.max(max, root.val);\n\n return Math.max(find(root.left, min, max), find(root.right, min, max));\n }\n\n}", + "title": "1026. Maximum Difference Between Node and Ancestor", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b . A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5000] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput:7\nExplanation:We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2,null,0,3]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n self.max_diff = float('-inf')\n \n def dfs(node,prev_min,prev_max):\n if not node:\n return\n dfs(node.left,min(prev_min,node.val),max(prev_max,node.val))\n dfs(node.right,min(prev_min,node.val),max(prev_max,node.val))\n self.max_diff = max(abs(node.val-prev_min),abs(node.val-prev_max),self.max_diff)\n dfs(root,root.val,root.val)\n return self.max_diff\n", + "title": "1026. Maximum Difference Between Node and Ancestor", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 ​​​​​​ and nums2 ​​​​​​. A pair of indices (i, j) , where 0 <= i < nums1.length and 0 <= j < nums2.length , is valid if both i <= j and nums1[i] <= nums2[j] . The distance of the pair is j - i ​​​​. Return the maximum distance of any valid pair (i, j) . If there are no valid pairs, return 0 . An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[j] <= 10^5", + "Both nums1 and nums2 are non-increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput:2\nExplanation:The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,2,2], nums2 = [10,10,1]\nOutput:1\nExplanation:The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput:2\nExplanation:The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 16.02%) | Memory: 101.7 MB (Top 80.40%)\nclass Solution {\n public int maxDistance(int[] nums1, int[] nums2) {\n int max = 0;\n for (int i = 0; i < nums1.length; i++) {\n int r = nums2.length - 1;\n int l = i;\n int m = i;\n while (l <= r) {\n m = l + (r - l) / 2;\n if (nums1[i] > nums2[m]) {\n r = m - 1;\n } else if (nums1[i] == nums2[m]) {\n l = m + 1;\n } else {\n l = m + 1;\n }\n }\n if (r < 0) {\n continue;\n }\n max = Math.max(max, r - i);\n }\n return max;\n }\n}", + "title": "1855. Maximum Distance Between a Pair of Values", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 ​​​​​​ and nums2 ​​​​​​. A pair of indices (i, j) , where 0 <= i < nums1.length and 0 <= j < nums2.length , is valid if both i <= j and nums1[i] <= nums2[j] . The distance of the pair is j - i ​​​​. Return the maximum distance of any valid pair (i, j) . If there are no valid pairs, return 0 . An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[j] <= 10^5", + "Both nums1 and nums2 are non-increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput:2\nExplanation:The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,2,2], nums2 = [10,10,1]\nOutput:1\nExplanation:The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput:2\nExplanation:The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDistance(self, n1: List[int], n2: List[int]) -> int:\n i = j = res = 0\n while i < len(n1) and j < len(n2):\n if n1[i] > n2[j]:\n i += 1\n else:\n res = max(res, j - i)\n j += 1\n return res\n", + "title": "1855. Maximum Distance Between a Pair of Values", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides , where rides[i] = [start i , end i , tip i ] denotes the i th passenger requesting a ride from point start i to point end i who is willing to give a tip i dollar tip. For each passenger i you pick up, you earn end i - start i + tip i dollars. You may only drive at most one passenger at a time. Given n and rides , return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= rides.length <= 3 * 10^4", + "rides[i].length == 3", + "1 <= start i < end i <= n", + "1 <= tip i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, rides = [[2,5,4],[1,5,1]]\nOutput:7\nExplanation:We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.", + "image": null + }, + { + "text": "Example 2: Input:n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\nOutput:20\nExplanation:We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 72.84%) | Memory: 71.20 MB (Top 35.03%)\n\nclass Solution {\n private static class Job {\n\t\tprivate int start;\n\t\tprivate int end;\n\t\tprivate int profit;\n\n\t\tpublic Job(int start, int end, int profit) {\n\t\t\tthis.start = start;\n\t\t\tthis.end = end;\n\t\t\tthis.profit = profit;\n\t\t}\n\t}\n \n private int binarySearch(Job jobs[], int index) {\n\t\tint low = 0;\n\t\tint high = index - 1;\n\t\tint ans = -1;\n\t\twhile (low <= high) {\n\t\t\tint mid = low + (high - low) / 2;\n\t\t\tif (jobs[mid].end <= jobs[index].start) {\n\t\t\t\tans = mid;\n\t\t\t\tlow = mid + 1;\n\t\t\t} else {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n \n public long maxTaxiEarnings(int n, int[][] rides) {\n\t\tJob jobs[] = new Job[rides.length];\n\t\tfor (int i = 0; i < rides.length; i++) {\n\t\t\tjobs[i] = new Job(rides[i][0], rides[i][1], rides[i][1] - rides[i][0] + rides[i][2]);\n\t\t}\n\t\tArrays.sort(jobs, (j1, j2) -> (j1.end - j2.end));\n\t\tlong[] dp = new long[rides.length];\n\t\tdp[0] = jobs[0].profit;\n\t\tfor (int i = 1; i < jobs.length; i++) {\n\t\t\tlong include = jobs[i].profit;\n\t\t\tint index = binarySearch(jobs, i);\n\t\t\tif (index != -1) {\n\t\t\t\tinclude += dp[index];\n\t\t\t}\n\t\t\tdp[i] = Math.max(include, dp[i - 1]);\n\t\t}\n\t\treturn dp[rides.length - 1];\n }\n}\n", + "title": "2008. Maximum Earnings From Taxi", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides , where rides[i] = [start i , end i , tip i ] denotes the i th passenger requesting a ride from point start i to point end i who is willing to give a tip i dollar tip. For each passenger i you pick up, you earn end i - start i + tip i dollars. You may only drive at most one passenger at a time. Given n and rides , return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= rides.length <= 3 * 10^4", + "rides[i].length == 3", + "1 <= start i < end i <= n", + "1 <= tip i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, rides = [[2,5,4],[1,5,1]]\nOutput:7\nExplanation:We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.", + "image": null + }, + { + "text": "Example 2: Input:n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\nOutput:20\nExplanation:We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: \n rides.sort()\n for job in rides:\n job[2]+=job[1]-job[0]\n \n heap=[]\n cur=ans=0\n for start,e,p in rides:\n \n while heap and heap[0][0]<=start: \n _,val=heappop(heap)\n cur=max(cur,val)\n heappush(heap,(e,cur+p))\n \n ans=max(ans,cur+p)\n \n return ans\n", + "title": "2008. Maximum Earnings From Taxi", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of positive integers arr . Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions .", + "description_images": [], + "constraints": [ + "The value of the first element in arr must be 1 .", + "The absolute difference between any 2 adjacent elements must be less than or equal to 1 . In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length ( 0-indexed ). abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,1,2,1]\nOutput:2\nExplanation:We can satisfy the conditions by rearrangingarrso it becomes[1,2,2,2,1].\nThe largest element inarris 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,1,1000]\nOutput:3\nExplanation:One possible way to satisfy the conditions is by doing the following:\n1. Rearrangearrso it becomes[1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNowarr = [1,2,3], whichsatisfies the conditions.\nThe largest element inarr is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5]\nOutput:5\nExplanation:The array already satisfies the conditions, and the largest element is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n arr[0] = 1;\n for(int i = 1;i 1)\n arr[i] = arr[i-1] + 1; \n }\n return arr[arr.length-1];\n }\n}", + "title": "1846. Maximum Element After Decreasing and Rearranging", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of positive integers arr . Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions .", + "description_images": [], + "constraints": [ + "The value of the first element in arr must be 1 .", + "The absolute difference between any 2 adjacent elements must be less than or equal to 1 . In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length ( 0-indexed ). abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,1,2,1]\nOutput:2\nExplanation:We can satisfy the conditions by rearrangingarrso it becomes[1,2,2,2,1].\nThe largest element inarris 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,1,1000]\nOutput:3\nExplanation:One possible way to satisfy the conditions is by doing the following:\n1. Rearrangearrso it becomes[1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNowarr = [1,2,3], whichsatisfies the conditions.\nThe largest element inarr is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5]\nOutput:5\nExplanation:The array already satisfies the conditions, and the largest element is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\t\tcounter = collections.Counter(arr)\n available = sum(n > len(arr) for n in arr)\n i = ans = len(arr)\n while i > 0:\n # This number is not in arr\n if not counter[i]:\n # Use another number to fill in its place. If we cannot, we have to decrease our max\n if available: available -= 1 \n else: ans -= 1\n # Other occurences can be used for future.\n else:\n available += counter[i] - 1\n i -= 1\n return ans\n", + "title": "1846. Maximum Element After Decreasing and Rearranging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1 . Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite , where favorite[i] denotes the favorite person of the i th employee, return the maximum number of employees that can be invited to the meeting .", + "description_images": [], + "constraints": [ + "n == favorite.length", + "2 <= n <= 10^5", + "0 <= favorite[i] <= n - 1", + "favorite[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:favorite = [2,2,1,2]\nOutput:3\nExplanation:The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex1.png" + }, + { + "text": "Example 2: Input:favorite = [1,2,0]\nOutput:3\nExplanation:Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": null + }, + { + "text": "Example 3: Input:favorite = [3,0,1,4,1]\nOutput:4\nExplanation:The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 43.06%) | Memory: 139.6 MB (Top 38.28%)\nclass Solution {\n public int maximumInvitations(int[] favorite) {\n List> graph = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n graph.add(new ArrayList<>());\n }\n\n int answer = 0;\n\n List> pairs = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n if (i == favorite[favorite[i]]) {\n if (i < favorite[i]) {\n List pair = new ArrayList<>();\n pair.add(i);\n pair.add(favorite[i]);\n pairs.add(pair);\n }\n } else {\n graph.get(favorite[i]).add(i);\n }\n }\n\n boolean[] visited = new boolean[favorite.length];\n for (List pair: pairs) {\n answer += dfs(graph, pair.get(0), visited) + dfs(graph, pair.get(1), visited);\n }\n\n int[] counter = new int[favorite.length];\n int[] round = new int[favorite.length];\n\n int rnd = 1;\n\n int circleMax = 0;\n\n for (int i = 0; i < favorite.length; i++) {\n if (visited[i]) {\n continue;\n }\n if (round[i] != 0) {\n continue;\n }\n\n int cnt = 1;\n int j = i;\n while (counter[j] == 0) {\n counter[j] = cnt;\n round[j] = rnd;\n j = favorite[j];\n cnt++;\n }\n if (round[j] == rnd) {\n circleMax = Math.max(circleMax, cnt - counter[j]);\n }\n rnd++;\n }\n return Math.max(circleMax, answer);\n }\n\n private int dfs(List> graph, int node, boolean[] visited) {\n visited[node] = true;\n int max = 0;\n for (int neighbor: graph.get(node)) {\n max = Math.max(max, dfs(graph, neighbor, visited));\n }\n return max + 1;\n }\n}", + "title": "2127. Maximum Employees to Be Invited to a Meeting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1 . Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite , where favorite[i] denotes the favorite person of the i th employee, return the maximum number of employees that can be invited to the meeting .", + "description_images": [], + "constraints": [ + "n == favorite.length", + "2 <= n <= 10^5", + "0 <= favorite[i] <= n - 1", + "favorite[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:favorite = [2,2,1,2]\nOutput:3\nExplanation:The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex1.png" + }, + { + "text": "Example 2: Input:favorite = [1,2,0]\nOutput:3\nExplanation:Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": null + }, + { + "text": "Example 3: Input:favorite = [3,0,1,4,1]\nOutput:4\nExplanation:The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n visited_time = [0] * n\n inpath = [False] * n\n cur_time = 1\n def get_max_len_cycle(cur) :\n nonlocal cur_time\n inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]\n cur_time += 1\n ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1\n if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))\n inpath[cur] = False\n return ret\n \n ret_cycle = 0\n for i in range(n) :\n if visited_time[i] == 0 :\n ret_cycle = max(ret_cycle, get_max_len_cycle(i))\n \n ret_not_cycle = 0\n back_edge_graph = [[] for _ in range(n)]\n for i in range(n) : back_edge_graph[favorite[i]].append(i)\n def get_max_depth(cur) :\n ret = 0\n for nxt in back_edge_graph[cur] :\n if favorite[cur] != nxt :\n ret = max(ret, get_max_depth(nxt) + 1)\n return ret\n \n for i in range(n) :\n if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1\n \n ret = max(ret_cycle, ret_not_cycle)\n return ret\n", + "title": "2127. Maximum Employees to Be Invited to a Meeting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums , such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1,1,5,3,3,5]\nOutput:7\nExplanation:For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput:13", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.TreeMap;\nimport java.util.NavigableMap;\nclass Solution {\n public int maxEqualFreq(int[] nums) {\n Map F = new HashMap<>(); //Frequencies\n NavigableMap V = new TreeMap<>(); //Values for frequencies\n int max = 0;\n for (int i = 0; i < nums.length; i++) {\n increaseCount(F, nums[i]);\n int frequency = F.get(nums[i]);\n decreaseCount(V, frequency - 1);\n increaseCount(V, frequency);\n if (isPossibleToRemove(V)) max = i;\n }\n return max + 1;\n }\n \n public boolean isPossibleToRemove(NavigableMap frequenciesMap) {\n if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies\n Map.Entry first = frequenciesMap.firstEntry();\n Map.Entry last = frequenciesMap.lastEntry();\n if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d]\n int firstReduced = removeElement(first);\n int lastReduced = removeElement(last);\n if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false;\n return true;\n }\n \n //Try to remove element which contributes to this frequency:\n //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1\n //if there are more than 1 occurences of such frequency, removing 1 element will not change it\n public int removeElement(Map.Entry frequencyValue) {\n if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1;\n return frequencyValue.getKey();\n }\n \n public void decreaseCount(Map map, int element) {\n if (!map.containsKey(element)) return;\n map.put(element, map.get(element) - 1);\n if (map.get(element) == 0) map.remove(element);\n }\n \n public void increaseCount(Map map, int element) {\n if (!map.containsKey(element)) map.put(element, 0);\n map.put(element, map.get(element) + 1);\n }\n}\n", + "title": "1224. Maximum Equal Frequency", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums , such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1,1,5,3,3,5]\nOutput:7\nExplanation:For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput:13", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ans = 0\n n = len(nums)\n countToFreq = defaultdict(int)\n # key = count value = Freq ex 2 occured 3 times in nums so 2 : 3\n freqToCount = defaultdict(int)\n # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3\n \n for i,val in enumerate(nums):\n \n x = countToFreq[val] + 1\n freqToCount[x - 1] -= 1\n if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)\n freqToCount[x] += 1\n countToFreq[val] = x\n \n # if a single item is repeated for i + 1 times like [1,1,1]\n if countToFreq[val] == i + 1 :ans = i + 1\n \n # if all items are having same frequency like [2,2,1,1,3,3]\n elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1\n \n # if all items have same frequency except one having 1 freq like [2,2,3,3,1]\n elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1\n \n # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]\n elif len(freqToCount) == 2:\n keys,values = [],[]\n for j in freqToCount:keys.append(j) , values.append(freqToCount[j])\n if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1\n return ans\n", + "title": "1224. Maximum Equal Frequency", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of positive integers nums and want to erase a subarray containing unique elements . The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a , that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r) .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,4,5,6]\nOutput:17\nExplanation:The optimal subarray here is [2,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,1,2,5,2,1,2,5]\nOutput:8\nExplanation:The optimal subarray here is [5,2,1] or [1,2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 95.0%) | Memory: 59.10 MB (Top 35.8%)\n\nclass Solution {\n public int maximumUniqueSubarray(int[] nums) {\n short[] nmap = new short[10001];\n int total = 0, best = 0;\n for (int left = 0, right = 0; right < nums.length; right++) {\n nmap[nums[right]]++;\n total += nums[right];\n while (nmap[nums[right]] > 1) {\n nmap[nums[left]]--;\n total -= nums[left++];\n }\n best = Math.max(best, total);\n }\n return best;\n }\n}", + "title": "1695. Maximum Erasure Value", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of positive integers nums and want to erase a subarray containing unique elements . The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a , that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r) .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,4,5,6]\nOutput:17\nExplanation:The optimal subarray here is [2,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,1,2,5,2,1,2,5]\nOutput:8\nExplanation:The optimal subarray here is [5,2,1] or [1,2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 796 ms (Top 99.64%) | Memory: 29.60 MB (Top 94.86%)\n\nclass Solution:\n\tdef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\t\tlow = 0\n\t\tvisited = set()\n\t\tresult = 0\n\t\tcurSum = 0\n\t\tfor high in range(len(nums)):\n\t\t\twhile nums[high] in visited:\n\t\t\t\tvisited.remove(nums[low])\n\t\t\t\tcurSum -= nums[low]\n\t\t\t\tlow+=1\n\n\t\t\tvisited.add(nums[high])\n\t\t\tcurSum += nums[high]\n\n\t\t\tif curSum > result:\n\t\t\t\tresult = curSum\n\n\t\treturn result\n", + "title": "1695. Maximum Erasure Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class:", + "description_images": [], + "constraints": [ + "FreqStack() constructs an empty frequency stack.", + "void push(int val) pushes an integer val onto the top of the stack.", + "int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.", + "If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]Output[null, null, null, null, null, null, null, 5, 7, 5, 4]ExplanationFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 83.25%) | Memory: 51.6 MB (Top 94.52%)\nclass Node{\n int data, freq, time;\n Node(int data, int freq, int time){\n this.data=data;\n this.freq=freq;\n this.time=time;\n }\n}\n\nclass CompareNode implements Comparator{\n @Override\n public int compare(Node a, Node b){\n if(a.freq-b.freq==0){\n return b.time-a.time;\n }\n return b.freq-a.freq;\n }\n}\n\nclass FreqStack {\n PriorityQueue pq;\n Map map;\n int c=0;\n public FreqStack(){\n pq=new PriorityQueue<>(new CompareNode());\n map=new HashMap<>();\n }\n\n public void push(int val){\n c++;\n int freq=1;\n if(map.containsKey(val)){\n freq+=map.get(val).freq;\n }\n map.put(val, new Node(val, freq, c));\n pq.add(new Node(val,freq,c++));\n }\n\n public int pop() {\n Node r=pq.remove();\n Node a=map.get(r.data);\n a.freq--;\n return r.data;\n }\n}", + "title": "895. Maximum Frequency Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class:", + "description_images": [], + "constraints": [ + "FreqStack() constructs an empty frequency stack.", + "void push(int val) pushes an integer val onto the top of the stack.", + "int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.", + "If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]Output[null, null, null, null, null, null, null, 5, 7, 5, 4]ExplanationFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 347 ms (Top 94.76%) | Memory: 22.7 MB (Top 60.86%)\nclass FreqStack:\n\n def __init__(self):\n self.cnt = {}\n self.maxcount = 0\n self.stack = {}\n\n def push(self, val: int) -> None:\n count = self.cnt.get(val,0)+1\n self.cnt[val] = count\n if count>self.maxcount:\n self.maxcount = count\n self.stack[count] = []\n self.stack[count].append(val)\n\n def pop(self) -> int:\n res = self.stack[self.maxcount].pop()\n self.cnt[res]-=1\n if not self.stack[self.maxcount]:\n self.maxcount-=1\n return res\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()", + "title": "895. Maximum Frequency Stack", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [position i , amount i ] depicts amount i fruits at the position position i . fruits is already sorted by position i in ascending order , and each position i is unique . You are also given an integer startPos and an integer k . Initially, you are at the position startPos . From any position, you can either walk to the left or right . It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest .", + "description_images": [], + "constraints": [ + "1 <= fruits.length <= 10^5", + "fruits[i].length == 2", + "0 <= startPos, position i <= 2 * 10^5", + "position i-1 < position i for any i > 0 ( 0-indexed )", + "1 <= amount i <= 10^4", + "0 <= k <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput:9\nExplanation:The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/1.png" + }, + { + "text": "Example 2: Input:fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput:14\nExplanation:You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/2.png" + }, + { + "text": "Example 3: Input:fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput:0\nExplanation:You can move at most k = 2 steps and cannot reach any position with fruits.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 54.24%) | Memory: 127.9 MB (Top 64.41%)\nclass Solution {\n public int maxTotalFruits(int[][] fruits, int startPos, int k) {\n int n = fruits.length;\n int posOfLastFruit = fruits[n-1][0];\n int prefixArr[] = new int[posOfLastFruit + 1];\n int start = Math.max(startPos - k, 0);\n int end = Math.min(startPos + k, prefixArr.length-1);\n\n if(startPos > posOfLastFruit) {\n int diff = startPos - posOfLastFruit;\n startPos = posOfLastFruit;\n k = k - diff;\n if(k == 0)\n return fruits[posOfLastFruit][1];\n else if(k < 0)\n return 0;\n }\n\n for(int i = 0 ; i < n ; i++) {\n prefixArr[fruits[i][0]] = fruits[i][1];\n }\n\n int curr = 0;\n for(int i = startPos-1 ; i >= start ; i--) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n curr = 0;\n for(int i = startPos+1 ; i <= end ; i++) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n int minimum = prefixArr[startPos];\n prefixArr[startPos] = 0;\n int ans = 0;\n\n for(int i = start ; i < startPos ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = startPos - i;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i + stepsRemaining;\n\n if(endIndex > startPos && endIndex < prefixArr.length) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex >= prefixArr.length) {\n maxCurrPossible += prefixArr[prefixArr.length-1];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n for(int i = startPos+1 ; i <= end ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = i - startPos;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i - stepsRemaining;\n\n if(endIndex < startPos && endIndex >= 0) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex < 0) {\n maxCurrPossible += prefixArr[0];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n return ans + minimum;\n }\n}", + "title": "2106. Maximum Fruits Harvested After at Most K Steps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [position i , amount i ] depicts amount i fruits at the position position i . fruits is already sorted by position i in ascending order , and each position i is unique . You are also given an integer startPos and an integer k . Initially, you are at the position startPos . From any position, you can either walk to the left or right . It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest .", + "description_images": [], + "constraints": [ + "1 <= fruits.length <= 10^5", + "fruits[i].length == 2", + "0 <= startPos, position i <= 2 * 10^5", + "position i-1 < position i for any i > 0 ( 0-indexed )", + "1 <= amount i <= 10^4", + "0 <= k <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput:9\nExplanation:The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/1.png" + }, + { + "text": "Example 2: Input:fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput:14\nExplanation:You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/2.png" + }, + { + "text": "Example 3: Input:fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput:0\nExplanation:You can move at most k = 2 steps and cannot reach any position with fruits.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 5941 ms (Top 24.26%) | Memory: 59.9 MB (Top 86.39%)\nclass Solution:\n def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n arr = [0 for _ in range(2*k+1)]\n for pos, numOfFruit in fruits:\n if pos < startPos-k or pos > startPos+k:\n continue\n arr[pos-(startPos-k)] += numOfFruit\n\n left, right = sum(arr[:k+1]), sum(arr[k:])\n maxSeen = max(left, right)\n\n turn = 1 # turning point\n for i in range(2, k+1, 2):\n left = left-arr[i-2]-arr[i-1]+arr[k+turn]\n right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn]\n maxSeen = max(maxSeen, left, right)\n turn += 1\n\n return maxSeen", + "title": "2106. Maximum Fruits Harvested After at Most K Steps", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the maximum difference between two successive elements in its sorted form . If the array contains less than two elements, return 0 . You must write an algorithm that runs in linear time and uses linear extra space.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,1]\nOutput:3\nExplanation:The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10]\nOutput:0\nExplanation:The array contains less than 2 elements, therefore return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumGap(int[] nums) {\n Arrays.sort(nums);\n int res=0;\n if(nums.length==0){\n return 0;\n }\n for (int i =0;i int:\n if len(nums)<2: return 0\n \n #radix sort\n #N = length of nums\n #find number of digits in largest number - O(K) where K = length of largest number\n longest = 0\n for i in nums:\n longest = max(longest,len(str(i)))\n \n #normalize so that all numbers have same number of digits by adding 0s at the start of shorter numbers - O(N*K)\n for i in range(len(nums)):\n if len(str(nums[i]))!=longest:\n nums[i] = '0'*(longest-len(str(nums[i]))) + str(nums[i])\n else:\n nums[i] = str(nums[i])\n \n #apply counting sort starting with each digit from the end of the last digits - O(K*N)\n for digit in range(longest-1,-1,-1):\n vals = [[] for k in range(10)]\n for num in nums:\n vals[int(num[digit])] += [num]\n\t\t\t#join list sorted by that digit position together:\n new = []\n for i in vals:\n new += i\n nums = new.copy()\n \n #find the largest difference in the now sorted nums - O(N)\n best_diff = 0\n for i in range(1,len(nums)):\n best_diff = max(best_diff,int(nums[i])-int(nums[i-1]))\n return best_diff\n \n#Overall complexity is O(N*K) but K is at most 10 so O(10*N) = O(N) so linear\n#Please correct me if I am wrong!\n", + "title": "164. Maximum Gap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a rooted tree consisting of n nodes numbered 0 to n - 1 . Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x ). The genetic difference between two genetic values is defined as the bitwise- XOR of their values. You are given the integer array parents , where parents[i] is the parent for node i . If node x is the root of the tree, then parents[x] == -1 . You are also given the array queries where queries[i] = [node i , val i ] . For each query i , find the maximum genetic difference between val i and p i , where p i is the genetic value of any node that is on the path between node i and the root (including node i and the root). More formally, you want to maximize val i XOR p i . Return an array ans where ans[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "2 <= parents.length <= 10^5", + "0 <= parents[i] <= parents.length - 1 for every node i that is not the root.", + "parents[root] == -1", + "1 <= queries.length <= 3 * 10^4", + "0 <= node i <= parents.length - 1", + "0 <= val i <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]\nOutput:[2,3,7]\nExplanation:The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/c1.png" + }, + { + "text": "Example 2: Input:parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]\nOutput:[6,14,7]\nExplanation:The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/c2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 6663 ms (Top 46.4%) | Memory: 339.09 MB (Top 7.1%)\n\nclass Solution:\n def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:\n adj_map = collections.defaultdict(set)\n root = None\n for i, node in enumerate(parents):\n if node == -1:\n root = i\n else:\n adj_map[node].add(i)\n queries_map = collections.defaultdict(set)\n\n for q in queries:\n queries_map[q[0]].add(q[1])\n self.res_map = {}\n def helperDFS(curr_root,prefix_map):\n\n if curr_root in queries_map:\n for val in queries_map[curr_root]:\n bin_rep = format(val, '020b')\n best_bin = \"\"\n print(bin_rep)\n for i in range(20):\n if prefix_map[best_bin+str(1-int(bin_rep[i]))]:\n best_bin += str(1-int(bin_rep[i]))\n else:\n best_bin += bin_rep[i]\n self.res_map[(curr_root,val)] = int(best_bin,2) ^ val \n for child in adj_map[curr_root]:\n bin_rep = format(child, '020b')\n for i in range(1, len(bin_rep)+1):\n prefix_map[bin_rep[0:i]].add(child)\n helperDFS(child, prefix_map)\n for i in range(1, len(bin_rep)+1):\n prefix_map[bin_rep[0:i]].remove(child)\n\n initial_prefixmap = collections.defaultdict(set)\n root_rep = format(root, '020b')\n for i in range(1,21):\n initial_prefixmap[root_rep[0:i]].add(root)\n helperDFS(root, initial_prefixmap)\n res = []\n for q in queries:\n res.append(self.res_map[(q[0],q[1])])\n return res\n \n", + "title": "1938. Maximum Genetic Difference Query", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n . Return the maximum number of people who can be good based on the statements made by the n people .", + "description_images": [], + "constraints": [ + "The good person : The person who always tells the truth.", + "The bad person : The person who might tell the truth and might lie." + ], + "examples": [ + { + "text": "Example 1: Input:statements = [[2,1,2],[1,2,2],[2,0,2]]\nOutput:2\nExplanation:Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n - Based on the statement made by person 2, person 1 is a bad person.\n - Now we know for sure that person 1 is bad and person 2 is good.\n - Based on the statement made by person 1, and since person 1 is bad, they could be:\n - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n - lying. In this case, person 0 is also a bad person and lied in their statement.\n -Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n - Based on the statement made by person 2, and since person 2 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n -Following that person 2 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Since person 1 is a good person, person 0 is also a good person.\n -Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic1.jpg" + }, + { + "text": "Example 2: Input:statements = [[2,0],[0,2]]\nOutput:1\nExplanation:Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n - Based on the statement made by person 0, person 1 is a bad person and was lying.\n -Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n - Based on the statement made by person 0, and since person 0 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad.\n -Following that person 0 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n -Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.48%) | Memory: 42.5 MB (Top 63.64%)\nclass Solution {\n public int maximumGood(int[][] statements) {\n int[] result = { 0 };\n maximumGood(statements, new boolean[statements.length], 0, 0, result);\n return result[0];\n }\n\n /*\n This function uses backtracking to do the DFS. We are basically constructing all possible scenarios and verifying them.\n\n statements (int[][]): This is the input statements.\n goodPeople (boolean[]): This array tells who are good and bad in the group.\n currentPerson (int): This is the current person that we are verifying.\n currentGoodPeople (int): This is the number of the good people identified so far.\n result (int[]): This array holds the result, the total number of good people.\n */\n private void maximumGood(int[][] statements, boolean[] goodPeople, int currentPerson, int currentGoodPeople, int[] result) {\n if (currentPerson == goodPeople.length) {\n result[0] = Math.max(result[0], currentGoodPeople);\n return;\n }\n\n // Now we are going to use backtracking to do DFS.\n\n // Scenario 1: Assume the current person is good and verify it.\n goodPeople[currentPerson] = true;\n // Prune the tree if the sum of unverified people (goodPeople.length - currentPerson) and verifyied good people (currentGoodPeople) is less than the result.\n if (goodPeople.length - currentPerson + currentGoodPeople < result[0]) {\n return;\n }\n if (isValid(statements, goodPeople, currentPerson)) {\n maximumGood(statements, goodPeople, currentPerson + 1, currentGoodPeople + 1, result);\n }\n\n // Scenario 2: Assume the current person is bad and verify it.\n goodPeople[currentPerson] = false;\n // Prune the tree for the same reason mentioned earlier.\n if (goodPeople.length - currentPerson - 1 + currentGoodPeople < result[0]) {\n return;\n }\n if (isValid(statements, goodPeople, currentPerson)) {\n maximumGood(statements, goodPeople, currentPerson + 1, currentGoodPeople, result);\n }\n\n return;\n }\n\n private boolean isValid(int[][] statements, boolean[] goodPeople, int currentPerson) {\n // To verify if the current assumption of good/bad people is correct, we need to do 2 things.\n // 1. We need to verify the statements from all processed good people. What they said about the current person should be correct.\n for (int i = 0; i < currentPerson; ++i) {\n if (goodPeople[i]) {\n if (goodPeople[currentPerson] && statements[i][currentPerson] == 0) {\n return false;\n }\n if (!goodPeople[currentPerson] && statements[i][currentPerson] == 1) {\n return false;\n }\n }\n }\n\n // 2. We need to verify the statement from the current person if he is good. What he said about other people should be correct.\n if (goodPeople[currentPerson]) {\n for (int i = 0; i < currentPerson; ++i) {\n if (goodPeople[i] && statements[currentPerson][i] == 0) return false;\n if (!goodPeople[i] && statements[currentPerson][i] == 1) return false;\n }\n }\n\n return true;\n }\n}", + "title": "2151. Maximum Good People Based on Statements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n . Return the maximum number of people who can be good based on the statements made by the n people .", + "description_images": [], + "constraints": [ + "The good person : The person who always tells the truth.", + "The bad person : The person who might tell the truth and might lie." + ], + "examples": [ + { + "text": "Example 1: Input:statements = [[2,1,2],[1,2,2],[2,0,2]]\nOutput:2\nExplanation:Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n - Based on the statement made by person 2, person 1 is a bad person.\n - Now we know for sure that person 1 is bad and person 2 is good.\n - Based on the statement made by person 1, and since person 1 is bad, they could be:\n - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n - lying. In this case, person 0 is also a bad person and lied in their statement.\n -Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n - Based on the statement made by person 2, and since person 2 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n -Following that person 2 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Since person 1 is a good person, person 0 is also a good person.\n -Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic1.jpg" + }, + { + "text": "Example 2: Input:statements = [[2,0],[0,2]]\nOutput:1\nExplanation:Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n - Based on the statement made by person 0, person 1 is a bad person and was lying.\n -Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n - Based on the statement made by person 0, and since person 0 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad.\n -Following that person 0 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n -Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumGood(self, S):\n n, ans = len(S), 0\n def valid(cur):\n for i in range(n):\n if cur[i]:\n for j in range(n):\n if S[i][j] != 2 and S[i][j] != cur[j]: return False\n return True;\n def dfs(cur, i, cnt):\n nonlocal ans\n if i == n:\n if valid(cur): ans = max(ans, cnt)\n return\n cur.append(0)\n dfs(cur, i+1, cnt)\n cur[-1] = 1\n dfs(cur, i+1, cnt+1)\n cur.pop()\n \n dfs([], 0, 0)\n return ans\n \n", + "title": "2151. Maximum Good People Based on Statements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given n cuboids where the dimensions of the i th cuboid is cuboids[i] = [width i , length i , height i ] ( 0-indexed ). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if width i <= width j and length i <= length j and height i <= height j . You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/21/image.jpg" + ], + "constraints": [ + "n == cuboids.length", + "1 <= n <= 100", + "1 <= width i , length i , height i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cuboids = [[50,45,20],[95,37,53],[45,23,12]]\nOutput:190\nExplanation:Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.", + "image": null + }, + { + "text": "Example 2: Input:cuboids = [[38,25,45],[76,35,3]]\nOutput:76\nExplanation:You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.", + "image": null + }, + { + "text": "Example 3: Input:cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\nOutput:102\nExplanation:After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 37.8%) | Memory: 41.26 MB (Top 83.6%)\n\nclass Solution {\n public int maxHeight(int[][] cuboids) {\n // Sorting all Dimensions\n for(int[] arr : cuboids) Arrays.sort(arr);\n\n // sort all cuboids on basis of height, if same then breadth,\n // if same then length\n Arrays.sort(cuboids, (a, b) -> (b[2] - a[2] == 0 ? (b[1] - a[1] == 0 ? b[0] - a[0] : b[1] - a[1]) : b[2] - a[2]));\n\n // use logic of LIS(Longest Increasing Subsequence)\n return helperTab(cuboids);\n\n }\n public int helperTab(int[][] nums){\n int n = nums.length;\n int[] currRow = new int[n + 1];\n int[] nextRow = new int[n + 1];\n\n for(int curr = n - 1; curr >= 0; curr--){\n for(int prev = curr - 1; prev >= -1; prev--){\n int take = 0;\n if(prev == -1 || check(nums[curr], nums[prev])) take = nums[curr][2] + nextRow[curr + 1];\n int notTake = 0 + nextRow[prev + 1];\n currRow[prev + 1] = Math.max(take, notTake);\n }\n nextRow = currRow;\n }\n return nextRow[0];\n }\n // These function checks whether current cuboid can be placed above \n //the below one or not, on the basis on condition given in question.\n public boolean check(int[] a, int[] b){\n if(a[0] <= b[0] && a[1] <= b[1] && a[2] <= b[2]) return true;\n else return false;\n }\n}", + "title": "1691. Maximum Height by Stacking Cuboids", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given n cuboids where the dimensions of the i th cuboid is cuboids[i] = [width i , length i , height i ] ( 0-indexed ). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if width i <= width j and length i <= length j and height i <= height j . You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/21/image.jpg" + ], + "constraints": [ + "n == cuboids.length", + "1 <= n <= 100", + "1 <= width i , length i , height i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cuboids = [[50,45,20],[95,37,53],[45,23,12]]\nOutput:190\nExplanation:Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.", + "image": null + }, + { + "text": "Example 2: Input:cuboids = [[38,25,45],[76,35,3]]\nOutput:76\nExplanation:You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.", + "image": null + }, + { + "text": "Example 3: Input:cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\nOutput:102\nExplanation:After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 199 ms (Top 36.11%) | Memory: 13.8 MB (Top 87.22%)\n\nclass Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n dp=[0]*len(cuboids)\n max_value=0\n for i in range(len(cuboids)):\n cuboids[i].sort()\n cuboids.sort()\n for i in range(len(cuboids)):\n dp[i]=cuboids[i][2]\n for j in range(i):\n if cuboids[i][0]>=cuboids[j][0] and cuboids[i][1]>=cuboids[j][1] and cuboids[i][2]>=cuboids[j][2]:\n dp[i]=max(dp[i],dp[j]+cuboids[i][2])\n if dp[i]>max_value:\n max_value=dp[i]\n return max_value", + "title": "1691. Maximum Height by Stacking Cuboids", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n , where costs[i] is the price of the i th ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order.", + "description_images": [], + "constraints": [ + "costs.length == n", + "1 <= n <= 10^5", + "1 <= costs[i] <= 10^5", + "1 <= coins <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [1,3,2,4,1], coins = 7\nOutput:4\nExplanation:The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.", + "image": null + }, + { + "text": "Example 2: Input:costs = [10,6,8,7,7,8], coins = 5\nOutput:0\nExplanation:The boy cannot afford any of the ice cream bars.", + "image": null + }, + { + "text": "Example 3: Input:costs = [1,6,3,1,2,5], coins = 20\nOutput:6\nExplanation:The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 62.29%) | Memory: 74.7 MB (Top 66.20%)\nclass Solution {\n public int maxIceCream(int[] costs, int coins) {\n\n //Greedy Approach\n //a. sort cost in increasing order\n\n Arrays.sort(costs);\n\n int count = 0;\n for(int cost : costs){\n\n //b. check remainig coin is greater or equal than cuurent ice - cream cost\n if(coins - cost >= 0) {\n coins -= cost;\n count++;\n }\n }\n\n return count;\n }\n}", + "title": "1833. Maximum Ice Cream Bars", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n , where costs[i] is the price of the i th ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order.", + "description_images": [], + "constraints": [ + "costs.length == n", + "1 <= n <= 10^5", + "1 <= costs[i] <= 10^5", + "1 <= coins <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [1,3,2,4,1], coins = 7\nOutput:4\nExplanation:The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.", + "image": null + }, + { + "text": "Example 2: Input:costs = [10,6,8,7,7,8], coins = 5\nOutput:0\nExplanation:The boy cannot afford any of the ice cream bars.", + "image": null + }, + { + "text": "Example 3: Input:costs = [1,6,3,1,2,5], coins = 20\nOutput:6\nExplanation:The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n costs.sort()\n i= 0\n for price in costs:\n if price<= coins:\n i+= 1\n coins-= price\n else:\n break\n return i", + "title": "1833. Maximum Ice Cream Bars", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings arr . A string s is formed by the concatenation of a subsequence of arr that has unique characters . Return the maximum possible length of s . A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 16", + "1 <= arr[i].length <= 26", + "arr[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"un\",\"iq\",\"ue\"]\nOutput:4\nExplanation:All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"cha\",\"r\",\"act\",\"ers\"]\nOutput:6\nExplanation:Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"abcdefghijklmnopqrstuvwxyz\"]\nOutput:26\nExplanation:The only string in arr has all 26 characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 61.57%) | Memory: 49.1 MB (Top 67.72%)\nclass Solution {\n public int maxLength(List arr) {\n String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);\n int[] dp = new int[1< int:\n ans = 0\n count = [0]*26\n counts = []\n new_arr = []\n\n for string in arr:\n flag = True\n tmp = [0]*26\n for ch in string:\n if tmp[ord(ch) - 97] == True:\n flag = False\n break\n else:\n tmp[ord(ch) - 97] = True\n\n if flag == False:continue\n counts.append(tmp)\n new_arr.append(string)\n\n n = len(new_arr)\n\n def compatible(a,b):\n for i in range(26):\n if a[i] == True and b[i] == True: return False\n return True\n\n def addUp(a,b):\n for i in range(26):\n if b[i] == True: a[i] = True\n\n def solve(index,count):\n if index == n:return 0\n cpy = count.copy()\n ch1 = -inf\n if compatible(count,counts[index]):\n addUp(count,counts[index])\n ch1 = solve(index+1,count) + len(new_arr[index])\n ch2 = solve(index+1 , cpy)\n ans = max(ch1,ch2)\n return ans\n\n return solve(0,count)", + "title": "1239. Maximum Length of a Concatenated String with Unique Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n pairs pairs where pairs[i] = [left i , right i ] and left i < right i . A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c . A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed . You do not need to use up all the given intervals. You can select pairs in any order.", + "description_images": [], + "constraints": [ + "n == pairs.length", + "1 <= n <= 1000", + "-1000 <= left i < right i <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3],[3,4]]\nOutput:2\nExplanation:The longest chain is [1,2] -> [3,4].", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,2],[7,8],[4,5]]\nOutput:3\nExplanation:The longest chain is [1,2] -> [4,5] -> [7,8].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n int findLongestChain(vector>& arr) {\n \n if(arr.size()==1)\n {\n return 1;\n }\n vector>v;\n for(int i=0;idp(v.size(),0);\n int ans=INT_MIN; \n dp[0]=1;\n for(int i=1;i=0;j--)\n {\n if(v[j].second=0;i--){\n for(int j = m-1 ;j>=0;j--){\n if(nums1[i]==nums2[j]){\n dp[i][j] = dp[i+1][j+1]+1;\n if(ans int:\n dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)]\n max_len = 0\n for row in range(len(nums2)):\n for col in range(len(nums1)):\n if nums2[row] == nums1[col]:\n dp[row][col] = 1 + dp[row - 1][col - 1]\n max_len = max(max_len,dp[row][col])\n else:\n dp[row][col] = 0\n return max_len\n \n", + "title": "718. Maximum Length of Repeated Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,-3,4]\nOutput:4\nExplanation:The array nums already has a positive product of 24.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,-2,-3,-4]\nOutput:3\nExplanation:The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3,0,1]\nOutput:2\nExplanation:The longest subarray with positive product is [-1,-2] or [-2,-3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 27.34%) | Memory: 84.2 MB (Top 12.92%)\nclass Solution {\n public int getMaxLen(int[] nums)\n {\n int first_negative=-1;\n int zero_position=-1;\n int count_neg=0;\n int res=0;\n for(int i=0;i int:\n n=len(arr)\n def solve(nums):\n i,j,last_neg,neg,ans=0,0,None,0,0\n while j map = new HashMap<>();\n\n public void go(TreeNode root, int level) {\n if(root == null) return;\n if(map.containsKey(level)) {\n map.put(level, map.get(level) + root.val);\n }\n else {\n map.put(level, root.val);\n }\n\n go(root.left, level+1);\n go(root.right, level+1);\n }\n public int maxLevelSum(TreeNode root) {\n go(root, 0);\n int max = Integer.MIN_VALUE, ind = -1;\n for (var i : map.entrySet()) {\n if(max < i.getValue()) {\n max = i.getValue();\n ind = i.getKey();\n }\n }\n return ind+1;\n }\n}", + "title": "1161. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, the level of its root is 1 , the level of its children is 2 , and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,7,0,7,-8,null,null]\nOutput:2\nExplanation:Level 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" + }, + { + "text": "Example 2: Input:root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n global_max = float('-inf')\n res = -1\n q = deque([root])\n lvl = 1\n while q:\n total = 0\n for _ in range(len(q)):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n total+=node.val\n if total>global_max:\n res = lvl\n global_max = total\n lvl+=1\n return res\n", + "title": "1161. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix . You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border . Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.", + "description_images": [], + "constraints": [ + "Choose any two adjacent elements of matrix and multiply each of them by -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,-1],[-1,1]]\nOutput:4\nExplanation:We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput:16\nExplanation:We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxMatrixSum(int[][] matrix) {\n long ans = 0;\n int neg = 0;\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] < 0) {\n neg++;\n }\n ans += Math.abs(matrix[i][j]);\n if(min > Math.abs(matrix[i][j]))\n \tmin = Math.abs(matrix[i][j]);\n }\n }\n if(neg % 2 == 0)\n \treturn ans;\n else\n \treturn ans - 2*min;\n }\n}\n", + "title": "1975. Maximum Matrix Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n integer matrix . You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border . Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.", + "description_images": [], + "constraints": [ + "Choose any two adjacent elements of matrix and multiply each of them by -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,-1],[-1,1]]\nOutput:4\nExplanation:We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput:16\nExplanation:We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n # count -'s\n count = 0\n for row in matrix:\n for col_num in row:\n if col_num < 0:\n count += 1\n tot_sum = sum([sum([abs(x) for x in row])\n for row in matrix])\n if count % 2 == 0:\n return tot_sum\n else:\n min_val = min([min([abs(x) for x in row])\n for row in matrix])\n return tot_sum - 2 * min_val\n", + "title": "1975. Maximum Matrix Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A string is a valid parentheses string (denoted VPS ) if it meets one of the following: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS 's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS 's. Given a VPS represented as string s , return the nesting depth of s .", + "description_images": [], + "constraints": [ + "It is an empty string \"\" , or a single character not equal to \"(\" or \")\" ,", + "It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or", + "It can be written as (A) , where A is a VPS ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(1+(2*3)+((8)/4))+1\"\nOutput:3\nExplanation:Digit 8 is inside of 3 nested parentheses in the string.", + "image": null + }, + { + "text": "Example 2: Input:s = \"(1)+((2))+(((3)))\"\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(String s) {\n int count = 0; //count current dept of \"()\"\n int max = 0; //count max dept of \"()\"\n\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == '(') {\n count++;\n } else if (s.charAt(i) == ')') {\n count--;\n }\n max = Math.max(count, max);\n }\n return max;\n }\n}\n", + "title": "1614. Maximum Nesting Depth of the Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string is a valid parentheses string (denoted VPS ) if it meets one of the following: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS 's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS 's. Given a VPS represented as string s , return the nesting depth of s .", + "description_images": [], + "constraints": [ + "It is an empty string \"\" , or a single character not equal to \"(\" or \")\" ,", + "It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or", + "It can be written as (A) , where A is a VPS ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(1+(2*3)+((8)/4))+1\"\nOutput:3\nExplanation:Digit 8 is inside of 3 nested parentheses in the string.", + "image": null + }, + { + "text": "Example 2: Input:s = \"(1)+((2))+(((3)))\"\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDepth(self, s: str) -> int:\n ans = cur = 0\n for c in s:\n if c == '(':\n cur += 1\n ans = max(ans, cur)\n elif c == ')':\n cur -= 1\n return ans \n", + "title": "1614. Maximum Nesting Depth of the Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's. Given a VPS seq , split it into two disjoint subsequences A and B , such that A and B are VPS's (and A.length + B.length = seq.length ). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length ) that encodes such a choice of A and B : answer[i] = 0 if seq[i] is part of A , else answer[i] = 1 .  Note that even though multiple answers may exist, you may return any of them.", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB ( A concatenated with B ), where A and B are VPS's, or", + "It can be written as (A) , where A is a VPS." + ], + "examples": [ + { + "text": "Example 1: Input:seq = \"(()())\"\nOutput:[0,1,1,1,1,0]", + "image": null + }, + { + "text": "Example 2: Input:seq = \"()(())()\"\nOutput:[0,0,0,1,1,0,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxDepthAfterSplit(String seq) {\n int[] res = new int[seq.length()];\n for(int i=0; i List[int]:\n ans = []\n last = 1\n for i in seq:\n if i == '(':\n if last == 0: ans.append(1)\n else:ans.append(0)\n else:\n ans.append(last)\n last = (last + 1) % 2\n return ans\n", + "title": "1111. Maximum Nesting Depth of Two Valid Parentheses Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a m x n matrix grid . Initially, you are located at the top-left corner (0, 0) , and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1) , find the path with the maximum non-negative product . The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7 . If the maximum product is negative , return -1 . Notice that the modulo is performed after getting the maximum product.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 15", + "-4 <= grid[i][j] <= 4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput:-1\nExplanation:It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput:8\nExplanation:Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,3],[0,-4]]\nOutput:0\nExplanation:Maximum non-negative product is shown (1 * 0 * -4 = 0).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 41.67%) | Memory: 43.3 MB (Top 29.76%)\nclass Solution {\n public class Pair{\n long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;\n Pair(){\n\n }\n Pair(long min,long max){\n this.min=min;\n this.max=max;\n }\n }\n public int maxProductPath(int[][] grid) {\n Pair[][] dp=new Pair[grid.length][grid[0].length];\n for(int r=grid.length-1;r>=0;r--){\n for(int c=grid[0].length-1;c>=0;c--){\n if(r==grid.length-1 && c==grid[0].length-1){\n dp[r][c]=new Pair(grid[r][c],grid[r][c]);\n }else{\n Pair hor=(c==grid[0].length-1)?new Pair():dp[r][c+1];\n Pair ver=(r==grid.length-1)?new Pair():dp[r+1][c];\n long min,max;\n if(grid[r][c]>=0){\n max=Math.max(hor.max,ver.max);\n min=Math.min(hor.min,ver.min);\n }else{\n min=Math.max(hor.max,ver.max);\n max=Math.min(hor.min,ver.min);\n }\n dp[r][c]=new Pair(min*grid[r][c],max*grid[r][c]);\n }\n }\n }\n int mod=(int)1e9 +7;\n return dp[0][0].max<0?-1:(int)(dp[0][0].max%mod);\n }\n}", + "title": "1594. Maximum Non Negative Product in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a m x n matrix grid . Initially, you are located at the top-left corner (0, 0) , and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1) , find the path with the maximum non-negative product . The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7 . If the maximum product is negative , return -1 . Notice that the modulo is performed after getting the maximum product.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 15", + "-4 <= grid[i][j] <= 4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput:-1\nExplanation:It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput:8\nExplanation:Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,3],[0,-4]]\nOutput:0\nExplanation:Maximum non-negative product is shown (1 * 0 * -4 = 0).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 63 ms (Top 56.0%) | Memory: 16.84 MB (Top 17.4%)\n\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n \"\"\"Return maximum & minimum products ending at (i, j).\"\"\"\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007", + "title": "1594. Maximum Non Negative Product in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We have n buildings numbered from 0 to n - 1 . Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [from i , to i ] represents an employee's request to transfer from building from i to building to i . All buildings are full , so a list of requests is achievable only if for each building, the net change in employee transfers is zero . This means the number of employees leaving is equal to the number of employees moving in . For example if n = 3 and two employees are leaving building 0 , one is leaving building 1 , and one is leaving building 2 , there should be two employees moving to building 0 , one employee moving to building 1 , and one employee moving to building 2 . Return the maximum number of achievable requests .", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= requests.length <= 16", + "requests[i].length == 2", + "0 <= from i , to i < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\nOutput:5Explantion:Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move1.jpg" + }, + { + "text": "Example 2: Input:n = 3, requests = [[0,0],[1,2],[2,1]]\nOutput:3Explantion:Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move2.jpg" + }, + { + "text": "Example 3: Input:n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 65.52%) | Memory: 42.2 MB (Top 56.90%)\nclass Solution {\n int max = 0;\n public int maximumRequests(int n, int[][] requests) {\n helper(requests, 0, new int[n], 0);\n return max;\n }\n\n private void helper(int[][] requests, int index, int[] count, int num) {\n // Traverse all n buildings to see if they are all 0. (means balanced)\n if (index == requests.length) {\n for (int i : count) {\n if (0 != i) {\n return;\n }\n }\n max = Math.max(max, num);\n return;\n }\n // Choose this request\n count[requests[index][0]]++;\n count[requests[index][1]]--;\n helper(requests, index + 1, count, num + 1);\n count[requests[index][0]]--;\n count[requests[index][1]]++;\n\n // Not Choose the request\n helper(requests, index + 1, count, num);\n }\n}", + "title": "1601. Maximum Number of Achievable Transfer Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We have n buildings numbered from 0 to n - 1 . Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [from i , to i ] represents an employee's request to transfer from building from i to building to i . All buildings are full , so a list of requests is achievable only if for each building, the net change in employee transfers is zero . This means the number of employees leaving is equal to the number of employees moving in . For example if n = 3 and two employees are leaving building 0 , one is leaving building 1 , and one is leaving building 2 , there should be two employees moving to building 0 , one employee moving to building 1 , and one employee moving to building 2 . Return the maximum number of achievable requests .", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= requests.length <= 16", + "requests[i].length == 2", + "0 <= from i , to i < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\nOutput:5Explantion:Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move1.jpg" + }, + { + "text": "Example 2: Input:n = 3, requests = [[0,0],[1,2],[2,1]]\nOutput:3Explantion:Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move2.jpg" + }, + { + "text": "Example 3: Input:n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4533 ms (Top 17.14%) | Memory: 13.9 MB (Top 48.57%)\nclass Solution:\n def maximumRequests(self, n: int, r: List[List[int]]) -> int:\n k=len(r)\n deg=[0 for i in range(n)]\n\n def check(i,res,s):\n if i==k:\n #print(deg,s)\n if max(deg)==min(deg)==0:\n res[0]=max(res[0],s)\n return\n\n u,v=r[i]\n deg[u]-=1\n deg[v]+=1\n check(i+1,res,s+1)\n deg[u]+=1\n deg[v]-=1\n check(i+1,res,s)\n res=[0]\n check(0,res,0)\n return res[0]\n", + "title": "1601. Maximum Number of Achievable Transfer Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string text , you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once . Return the maximum number of instances that can be formed.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex1_upd.JPG", + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex2_upd.JPG" + ], + "constraints": [ + "1 <= text.length <= 10^4", + "text consists of lower case English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"nlaebolko\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:text = \"loonbalxballpoon\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:text = \"leetcode\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 74.74%) | Memory: 42.3 MB (Top 69.99%)\nclass Solution {\n\n public int maxNumberOfBalloons(String text) {\n return maxNumberOfWords(text, \"balloon\");\n }\n\n private int maxNumberOfWords(String text, String word) {\n final int[] tFrequencies = new int[26];\n for (int i = 0; i < text.length(); ++i) {\n tFrequencies[text.charAt(i) - 'a']++;\n }\n final int[] wFrequencies = new int[26];\n for (int i = 0; i < word.length(); ++i) {\n wFrequencies[word.charAt(i) - 'a']++;\n }\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < 26; ++i) {\n if (wFrequencies[i] > 0) {\n final int count = (tFrequencies[i] / wFrequencies[i]);\n if (count < min) {\n min = count;\n }\n }\n }\n return min;\n }\n\n}", + "title": "1189. Maximum Number of Balloons", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string text , you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once . Return the maximum number of instances that can be formed.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex1_upd.JPG", + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex2_upd.JPG" + ], + "constraints": [ + "1 <= text.length <= 10^4", + "text consists of lower case English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"nlaebolko\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:text = \"loonbalxballpoon\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:text = \"leetcode\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}\n \n for char in text:\n if not char in freq:\n continue\n \n step = 0.5 if char == 'l' or char == 'o' else 1\n \n freq[char] += step\n \n result = min(freq.values())\n \n return floor(result)", + "title": "1189. Maximum Number of Balloons", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1 ), and an infinite number of boxes numbered from 1 to infinity . Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1 . Given two integers lowLimit and highLimit , return the number of balls in the box with the most balls.", + "description_images": [], + "constraints": [ + "1 <= lowLimit <= highLimit <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:lowLimit = 1, highLimit = 10\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.", + "image": null + }, + { + "text": "Example 2: Input:lowLimit = 5, highLimit = 15\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.", + "image": null + }, + { + "text": "Example 3: Input:lowLimit = 19, highLimit = 28\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 20.04%) | Memory: 49.5 MB (Top 50.90%)\nclass Solution {\n public int countBalls(int lowLimit, int highLimit) {\n Map map = new HashMap<>();\n int count = Integer.MIN_VALUE;\n for(int i = lowLimit;i<=highLimit;i++){\n int value = 0;\n int temp = i;\n while (temp!=0){\n value += temp%10;\n temp/=10;\n }\n map.put(value,map.getOrDefault(value,0)+1);\n count = map.get(value) > count ? map.get(value) : count;\n }\n return count;\n }\n}", + "title": "1742. Maximum Number of Balls in a Box", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1 ), and an infinite number of boxes numbered from 1 to infinity . Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1 . Given two integers lowLimit and highLimit , return the number of balls in the box with the most balls.", + "description_images": [], + "constraints": [ + "1 <= lowLimit <= highLimit <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:lowLimit = 1, highLimit = 10\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.", + "image": null + }, + { + "text": "Example 2: Input:lowLimit = 5, highLimit = 15\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.", + "image": null + }, + { + "text": "Example 3: Input:lowLimit = 19, highLimit = 28\nOutput:2\nExplanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n boxes = [0] * 100\n \n for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number \"i\", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n boxes[sum([int(j) for j in str(i)])] += 1\n \n return max(boxes)", + "title": "1742. Maximum Number of Balls in a Box", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: Given an array of integers piles where piles[i] is the number of coins in the i th pile. Return the maximum number of coins that you can have.", + "description_images": [], + "constraints": [ + "In each step, you will choose any 3 piles of coins (not necessarily consecutive).", + "Of your choice, Alice will pick the pile with the maximum number of coins.", + "You will pick the next pile with the maximum number of coins.", + "Your friend Bob will pick the last pile.", + "Repeat until there are no more piles of coins." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [2,4,1,2,7,8]\nOutput:9\nExplanation:Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with7coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with2coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1,2, 8), (2,4, 7) you only get 2 + 4 = 6 coins which is not optimal.", + "image": null + }, + { + "text": "Example 2: Input:piles = [2,4,5]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:piles = [9,8,7,6,5,1,2,3,4]\nOutput:18", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 37.50%) | Memory: 77.8 MB (Top 8.89%)\nclass Solution {\n public int maxCoins(int[] piles) {\n Arrays.sort(piles);\n int s=0,n=piles.length;\n for(int i=n/3;i int:\n piles.sort()\n n = len(piles)\n k = n // 3\n i, j = 0, 2\n ans = 0\n while i < k:\n ans += piles[n-j]\n j += 2\n i +=1\n return ans", + "title": "1561. Maximum Number of Coins You Can Get", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the i th coin is coins[i] . You can make some value x if you can choose some of your n coins such that their values sum up to x . Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0 . Note that you may have multiple coins of the same value.", + "description_images": [], + "constraints": [ + "coins.length == n", + "1 <= n <= 4 * 10^4", + "1 <= coins[i] <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,3]\nOutput:2\nExplanation:You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 2: Input:coins = [1,1,1,4]\nOutput:8\nExplanation:You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,10,3,1]\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMaximumConsecutive(int[] coins) {\n if(coins.length==0 && coins==null)\n return 0;\n TreeMap map=new TreeMap();\n for(int i:coins)\n map.put(i,map.getOrDefault(i,0)+1);\n int range=0;\n for(int i:map.keySet()){\n if(range==0 && i==1)\n range=i*map.get(i);\n else if(range!=0 && range+1>=i)\n range+=i*map.get(i);\n else \n break;\n }\n return range+1;\n }\n}\n", + "title": "1798. Maximum Number of Consecutive Values You Can Make", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the i th coin is coins[i] . You can make some value x if you can choose some of your n coins such that their values sum up to x . Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0 . Note that you may have multiple coins of the same value.", + "description_images": [], + "constraints": [ + "coins.length == n", + "1 <= n <= 4 * 10^4", + "1 <= coins[i] <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,3]\nOutput:2\nExplanation:You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 2: Input:coins = [1,1,1,4]\nOutput:8\nExplanation:You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,10,3,1]\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 576 ms (Top 97.83%) | Memory: 23.00 MB (Top 5.22%)\n\nclass Solution:\n def getMaximumConsecutive(self, coins: List[int]) -> int:\n cur_max = 0\n coins.sort()\n \n for coin in coins:\n if coin == 1:\n cur_max += 1\n elif coin <= cur_max+1:\n cur_max += coin\n else: #coin > cur_max + 1\n break\n \n return cur_max+1\n", + "title": "1798. Maximum Number of Consecutive Values You Can Make", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [x i , y i ] is the position of the i th dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r , return the maximum number of darts that can lie on the dartboard .", + "description_images": [], + "constraints": [ + "1 <= darts.length <= 100", + "darts[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "1 <= r <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput:4\nExplanation:Circle dartboard with center in (0,0) and radius = 2 contain all points.", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_1_1806.png" + }, + { + "text": "Example 2: Input:darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput:5\nExplanation:Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_2_1806.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 275 ms (Top 78.13%) | Memory: 14.5 MB (Top 9.38%)\nclass Solution:\n def numPoints(self, points: List[List[int]], r: int) -> int:\n\n def getPointsInside(i, r, n):\n # This vector stores alpha and beta and flag\n # is marked true for alpha and false for beta\n angles = []\n\n for j in range(n):\n\n if i != j and distance[i][j] <= 2 * r:\n # acos returns the arc cosine of the complex\n # used for cosine inverse\n B = math.acos(distance[i][j] / (2 * r))\n\n # arg returns the phase angle of the complex\n x1, y1 = points[i]\n x2, y2 = points[j]\n\n A = math.atan2(y1 - y2, x1 - x2)\n\n alpha = A - B\n\n beta = A + B\n\n angles.append((alpha, False))\n\n angles.append((beta, True))\n\n # angles vector is sorted and traversed\n angles.sort()\n # count maintains the number of points inside\n # the circle at certain value of theta\n # res maintains the maximum of all count\n cnt, res = 1, 1\n for angle in angles:\n # entry angle\n if angle[1] == False:\n cnt += 1\n # exit angle\n else:\n cnt -= 1\n\n res = max(cnt, res)\n\n return res\n\n # Returns count of maximum points that can lie\n # in a circle of radius r.\n #a dis array stores the distance between every\n # pair of points\n n = len(points)\n max_pts = n\n distance = [[0 for _ in range(max_pts)] for _ in range(max_pts)]\n for i in range(n - 1):\n for j in range(i + 1, n):\n # abs gives the magnitude of the complex\n # number and hence the distance between\n # i and j\n x1, y1 = points[i]\n x2, y2 = points[j]\n distance[i][j] = distance[j][i] = sqrt((x1 - x2)**2 + (y1 - y2)**2)\n\n # This loop picks a point p\n ans = 0\n # maximum number of points for point arr[i]\n for i in range(n):\n ans = max(ans, getPointsInside(i, r, n))\n\n return ans", + "title": "1453. Maximum Number of Darts Inside of a Circular Dartboard", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a special kind of apple tree that grows apples every day for n days. On the i th day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0 . You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n , return the maximum number of apples you can eat.", + "description_images": [], + "constraints": [ + "n == apples.length == days.length", + "1 <= n <= 2 * 10^4", + "0 <= apples[i], days[i] <= 2 * 10^4", + "days[i] = 0 if and only if apples[i] = 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput:7\nExplanation:You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.", + "image": null + }, + { + "text": "Example 2: Input:apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput:5\nExplanation:You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 95.27%) | Memory: 45.90 MB (Top 56.76%)\n\nclass Solution {\n class Basket{\n int appleCount;\n int day;\n Basket(int appleCount, int day){\n this.appleCount = appleCount;\n this.day = day;\n }\n }\n public int eatenApples(int[] apples, int[] days) {\n int n = apples.length;\n PriorityQueue q = new PriorityQueue<>(n,(b1,b2) -> b1.day-b2.day);\n int i; // counter for day \n\t\tint apple = 0; // count of consumed apple\n \n for(i=0; i 0:\n cnt, apple = heapq.heappop(heap)\n if apple > 0 and cnt > day :\n rtn +=1\n day +=1\n if apple > 1 and cnt > day:\n heapq.heappush(heap, (cnt, apple-1))\n if day < len(days) and apples[day] > 0 :\n heapq.heappush(heap, (day +days[day], apples[day]))\n return rtn ", + "title": "1705. Maximum Number of Eaten Apples", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of events where events[i] = [startDay i , endDay i ] . Every event i starts at startDay i and ends at endDay i . You can attend an event i at any day d where startTime i <= d <= endTime i . You can only attend one event at any time d . Return the maximum number of events you can attend .", + "description_images": [], + "constraints": [ + "1 <= events.length <= 10^5", + "events[i].length == 2", + "1 <= startDay i <= endDay i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2],[2,3],[3,4]]\nOutput:3\nExplanation:You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/05/e1.png" + }, + { + "text": "Example 2: Input:events= [[1,2],[2,3],[3,4],[1,2]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "\n\nclass Solution {\n public int maxEvents(int[][] events) {\n Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]);\n // here sorting the array on ths basis of last day because we want to finish the events which happens first,fist.\n \n TreeSet set =new TreeSet<>();\n for(int i =1;i<=100000;i++){\n set.add(i);\n }\n //initliasing a tree set to check available days ;\n // a day can go maximum to 100000;\n int ans =0;\n for(int i =0;ievents[i][1])\n continue;\n else{\n set.remove(temp);\n ans +=1;\n }\n }\n return ans; \n }\n}\n", + "title": "1353. Maximum Number of Events That Can Be Attended", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of events where events[i] = [startDay i , endDay i ] . Every event i starts at startDay i and ends at endDay i . You can attend an event i at any day d where startTime i <= d <= endTime i . You can only attend one event at any time d . Return the maximum number of events you can attend .", + "description_images": [], + "constraints": [ + "1 <= events.length <= 10^5", + "events[i].length == 2", + "1 <= startDay i <= endDay i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2],[2,3],[3,4]]\nOutput:3\nExplanation:You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/05/e1.png" + }, + { + "text": "Example 2: Input:events= [[1,2],[2,3],[3,4],[1,2]]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1160 ms (Top 93.22%) | Memory: 61.6 MB (Top 51.45%)\nclass Solution(object):\n def maxEvents(self, events):\n \"\"\"\n :type events: List[List[int]]\n :rtype: int\n \"\"\"\n events = sorted(events, key=lambda x: x[0])\n current_day = 0\n min_heap = []\n event_id = 0\n total_number_of_days = max(end for start, end in events)\n total_events_attended = 0\n #total_number_of_days+1 because I want to include the last day\n for day in range(1, total_number_of_days+1):\n\n #Add all the events that can be started on that day\n while event_id < len(events) and events[event_id][0] == day:\n heapq.heappush(min_heap, events[event_id][1])\n event_id+=1\n\n #while there is something in heap and the event should have been completed before the current day\n #remove those evenets and consider them not attended\n while min_heap and min_heap[0] < day :\n heapq.heappop(min_heap)\n\n #if theere is an event present in heap\n #lets mark 1 of those events as complted today and add it to\n #total_events_attended\n\n if min_heap:\n heapq.heappop(min_heap)\n total_events_attended+=1\n return total_events_attended\n", + "title": "1353. Maximum Number of Events That Can Be Attended", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of events where events[i] = [startDay i , endDay i , value i ] . The i th event starts at startDay i and ends at endDay i , and if you attend this event, you will receive a value of value i . You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive : that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png" + ], + "constraints": [ + "1 <= k <= events.length", + "1 <= k * events.length <= 10^6", + "1 <= startDay i <= endDay i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput:7\nExplanation:Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput:10\nExplanation:Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you donothave to attend k events.", + "image": null + }, + { + "text": "Example 3: Input:events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput:9\nExplanation:Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 53.72%) | Memory: 100.9 MB (Top 52.07%)\nclass Solution {\n public int maxValue(int[][] events, int k) {\n Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0]));\n return maxValue(events, 0, k, 0, new int[k+1][events.length]);\n }\n\n private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEndDay, int[][] dp) {\n // Return 0 if no events are left or maximum choice is reached\n if (index >= events.length || remainingEvents == 0)\n return 0;\n\n // An Event cannot be picked if the previous event has not completed before current event\n if (lastEventEndDay >= events[index][0])\n return maxValue(events, index+1, remainingEvents, lastEventEndDay, dp);\n\n // Return the value if the solution is already available\n if (dp[remainingEvents][index] != 0)\n return dp[remainingEvents][index];\n\n // There are 2 choices that we can make,\n // SKIP this meeting or PICK this meeting\n return dp[remainingEvents][index] = Math.max(\n maxValue(events, index+1, remainingEvents, lastEventEndDay, dp), // skip\n maxValue(events, index+1, remainingEvents-1, events[index][1], dp) + events[index][2] // pick\n );\n }\n}", + "title": "1751. Maximum Number of Events That Can Be Attended II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of events where events[i] = [startDay i , endDay i , value i ] . The i th event starts at startDay i and ends at endDay i , and if you attend this event, you will receive a value of value i . You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive : that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png" + ], + "constraints": [ + "1 <= k <= events.length", + "1 <= k * events.length <= 10^6", + "1 <= startDay i <= endDay i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput:7\nExplanation:Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput:10\nExplanation:Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you donothave to attend k events.", + "image": null + }, + { + "text": "Example 3: Input:events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput:9\nExplanation:Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nfrom functools import lru_cache\n\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n if k == 1: # optimization for TLE test case 57/67\n return max([event[2] for event in events])\n \n events.sort()\n event_starts = [event[0] for event in events] # enables binary search\n \n @lru_cache(None)\n def dp(i, j):\n if j == 0: # out of turns\n return 0\n if i >= len(events): # end of events array\n return 0\n max_score = events[i][2]\n \n # get minimum index where start day is greater than current end day\n next_index_minimum = bisect.bisect_left(event_starts, events[i][1] + 1)\n \n # check each possibility from the minimum next index until end of the array\n for k in range(next_index_minimum, len(events)):\n max_score = max(max_score, events[i][2] + dp(k, j - 1))\n \n # check if we can get a better score if we skip this index altogether\n max_score = max(max_score, dp(i + 1, j))\n return max_score\n return dp(0, k)\n", + "title": "1751. Maximum Number of Events That Can Be Attended II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: Return the maximum number of groups that can be formed .", + "description_images": [], + "constraints": [ + "The sum of the grades of students in the i th group is less than the sum of the grades of students in the (i + 1) th group, for all groups (except the last).", + "The total number of students in the i th group is less than the total number of students in the (i + 1) th group, for all groups (except the last)." + ], + "examples": [ + { + "text": "Example 1: Input:grades = [10,6,12,7,3,5]\nOutput:3\nExplanation:The following is a possible way to form 3 groups of students:\n- 1stgroup has the students with grades = [12]. Sum of grades: 12. Student count: 1\n- 2ndgroup has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2\n- 3rdgroup has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3\nIt can be shown that it is not possible to form more than 3 groups.", + "image": null + }, + { + "text": "Example 2: Input:grades = [8,8]\nOutput:1\nExplanation:We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 58.70 MB (Top 6.47%)\n\nclass Solution {\n public int maximumGroups(int[] grades) {\n int len = grades.length;\n int groups = (int)(-1 + Math.sqrt(1 + 8*len))/2;\n return groups;\n }\n}", + "title": "2358. Maximum Number of Groups Entering a Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a donuts shop that bakes donuts in batches of batchSize . They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups , where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.", + "description_images": [], + "constraints": [ + "1 <= batchSize <= 9", + "1 <= groups.length <= 30", + "1 <= groups[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:batchSize = 3, groups = [1,2,3,4,5,6]\nOutput:4\nExplanation:You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6thgroups will be happy.", + "image": null + }, + { + "text": "Example 2: Input:batchSize = 4, groups = [1,3,2,5,2,2,1,6]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 209 ms (Top 60.0%) | Memory: 21.90 MB (Top 65.0%)\n\nclass Solution:\n def maxHappyGroups(self, B, groups):\n ans = sum(g%B == 0 for g in groups)\n groups = [g for g in groups if g%B != 0]\n\n pos = [0]*B\n for g in groups: pos[g%B] += 1\n\n for i in range(1, B):\n t = min(pos[i], pos[B-i]) if 2*i != B else pos[i]//2\n ans += t\n pos[i] -= t\n pos[B-i] -= t\n \n if sum(pos) == 0: return ans\n\n @lru_cache(None)\n def dfs(position, last):\n if sum(position) == 0: return 0\n\n ans = float(\"-inf\")\n for i in range(B):\n if position[i] > 0:\n t = [j for j in position]\n t[i] -= 1\n U = (last - i) % B\n ans = max(ans, dfs(tuple(t), U) + (U == 0))\n \n return ans\n\n return max(dfs(tuple(pos), i) for i in range(1, B)) + ans\n", + "title": "1815. Maximum Number of Groups Getting Fresh Donuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums and an integer target , return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "0 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 2\nOutput:2\nExplanation:There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,3,5,1,4,2,-9], target = 6\nOutput:2\nExplanation:There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxNonOverlapping(int[] nums, int target) {\n Map valToPos = new HashMap<>();\n int sums = 0;\n int count = 0;\n int lastEndPos = 0;\n valToPos.put(0, 0);\n for (int i = 0; i < nums.length; i++) {\n sums += nums[i];\n int pos = valToPos.getOrDefault(sums - target, -1);\n if (pos >= lastEndPos) {\n count += 1;\n lastEndPos = i + 1;\n }\n valToPos.put(sums, i + 1);\n }\n return count;\n }\n}\n", + "title": "1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums and an integer target , return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "0 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 2\nOutput:2\nExplanation:There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,3,5,1,4,2,-9], target = 6\nOutput:2\nExplanation:There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "'''\ngreedy, prefix sum with hashtable\nO(n), O(n)\n'''\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n # hash set to record previously encountered prefix sums\n prefix_sums = {0}\n \n res = prefix_sum = 0\n for num in nums:\n prefix_sum += num\n if prefix_sum - target in prefix_sums:\n res += 1\n # greedily discard prefix sums before num\n # thus not considering subarrays that start at before num \n prefix_sums = {prefix_sum} \n else:\n prefix_sums.add(prefix_sum)\n return res\n", + "title": "1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: Find the maximum number of substrings that meet the above conditions . If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"adefaddaccc\"\nOutput:[\"e\",\"f\",\"ccc\"]\nExplanation:The following are all the possible substrings that meet the conditions:\n[\n  \"adefaddaccc\"\n  \"adefadda\",\n  \"ef\",\n  \"e\",\n \"f\",\n  \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbaccd\"\nOutput:[\"d\",\"bb\",\"cc\"]\nExplanation:Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 132 ms (Top 24.51%) | Memory: 55.2 MB (Top 53.55%)\nclass Solution {\n public List maxNumOfSubstrings(String s) {\n int n = s.length();\n int[] R = new int[26];\n int[] L = new int[26];\n Arrays.fill(R, -1);\n Arrays.fill(L, -1);\n BitSet[] bit = new BitSet[26];\n Arrays.setAll(bit, o -> new BitSet());\n for (int i = 0; i < n; i++){\n R[s.charAt(i)-'a']=i; // last character index position\n }\n for (int i = n-1; i >= 0; i--){\n L[s.charAt(i)-'a']=i; // first character index position\n }\n for (int i = 0; i < 26; i++){ // add all characters between a character range.\n for (int j = L[i]+1; j < R[i] && L[i] >= 0; j++){\n bit[i].set(s.charAt(j)-'a');\n }\n }\n boolean go = true;\n while(go){ // keep merging until there is no more range change.\n go = false;\n for (int i = 0; i < 26; i++){\n for (int j = bit[i].nextSetBit(0); j >= 0; j = bit[i].nextSetBit(j+1)){\n bit[i].or(bit[j]); // add all characters from character j to i.\n int l = Math.min(L[i], L[j]);\n int r = Math.max(R[i], R[j]);\n go |= l != L[i] || r != R[i];\n L[i] = l;\n R[i] = r;\n }\n }\n }\n List ans = new ArrayList<>();\n boolean[] seen = new boolean[n];\n for (int i = 0; i < 26; i++){ // populate the answer\n boolean ok = L[i] >= 0 && !seen[L[i]];\n for (int j = 0; j < 26 && ok; j++){\n if (i != j && L[j] >= 0){ // only take those that has no smaller valid ranges.\n ok &= !(L[i]R[j]);\n }\n }\n if (ok){\n ans.add(s.substring(L[i], R[i]+1));\n seen[L[i]]=true;\n }\n }\n return ans;\n }\n}", + "title": "1520. Maximum Number of Non-Overlapping Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: Find the maximum number of substrings that meet the above conditions . If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"adefaddaccc\"\nOutput:[\"e\",\"f\",\"ccc\"]\nExplanation:The following are all the possible substrings that meet the conditions:\n[\n  \"adefaddaccc\"\n  \"adefadda\",\n  \"ef\",\n  \"e\",\n \"f\",\n  \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbaccd\"\nOutput:[\"d\",\"bb\",\"cc\"]\nExplanation:Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n st = defaultdict(lambda : -1)\n ed = defaultdict(int)\n for i, c in enumerate(s):\n if st[c]==-1:\n st[c] = i\n ed[c] = i\n else:\n ed[c] = i\n ints = []\n for c in set(s):\n b, e = st[c], ed[c]\n i = b\n while i <= e and b == st[c]:\n b = min(b, st[s[i]])\n e = max(e, ed[s[i]])\n i += 1\n if b == st[c]:\n ints.append((b,e))\n ints.sort(key = lambda e: e[1])\n res = []\n prev = -1\n for i in range(len(ints)):\n j,k = ints[i]\n if j > prev:\n res.append(s[j:k+1])\n prev = k\n return res", + "title": "1520. Maximum Number of Non-Overlapping Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the maximum number of ocurrences of any substring under the following rules:", + "description_images": [], + "constraints": [ + "The number of unique characters in the substring must be less than or equal to maxLetters .", + "The substring size must be between minSize and maxSize inclusive." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4\nOutput:2\nExplanation:Substring \"aab\" has 2 ocurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3\nOutput:2\nExplanation:Substring \"aaa\" occur 2 times in the string. It can overlap.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {\n Map count = new HashMap<>();\n int ans = 0;\n int n = s.length();\n \n for(int i=0;i+minSize-1 hs = new HashSet<>();\n for(int j=0;j int:\n #dict to store valid substrings and their respective occurences count\n d = defaultdict(int)\n #find longest substrings that has k unique chars\n #counter dict for char count and make sure unique char count is not exceeded\n counter = defaultdict(int)\n #init left and right pointers of sliding window\n r = l = 0\n #iterate right pointer\n while r < len(s):\n counter[s[r]] += 1\n \n #invalid window found, so make it valid again\n #len of window is greater than minSize\n while (r - l + 1) > minSize:\n counter[s[l]] -= 1\n #remove the key from dict for unique char count if it becomes zero\n if counter[s[l]] == 0:\n del counter[s[l]]\n #increment the left pointer to make it a valid window\n l += 1\n\n #valid window size (minSize) and unique char count is lesser than or equal to maxLetters\n if r - l + 1 == minSize and len(counter) <= maxLetters:\n #increment count of the occurence of the substring\n d[s[l:r+1]] += 1\n \n #make sure to update right pointer only after an iteration\n r += 1\n \n #return the count of substring with max occurence\n #edge case with no substring\n return max(d.values()) if d else 0\n", + "title": "1297. Maximum Number of Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one operation, you may do the following: The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible .", + "description_images": [], + "constraints": [ + "Choose two integers in nums that are equal .", + "Remove both integers from nums , forming a pair ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,1,3,2,2]\nOutput:[3,1]\nExplanation:Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[1,0]\nExplanation:Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0]\nOutput:[0,1]\nExplanation:No pairs can be formed, and there is 1 number leftover in nums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 21.09%) | Memory: 42.4 MB (Top 76.38%)\nclass Solution {\n public int[] numberOfPairs(int[] nums) {\n\n if(nums.length == 1)\n return new int[]{0,1};\n\n HashSet set = new HashSet<>();\n\n int pairs=0;\n for(int i : nums){\n if(!set.contains(i)){\n set.add(i); // No pair present\n }else{\n set.remove(i); // Pair found\n pairs++;\n }\n }\n\n return new int[]{pairs,set.size()};\n }\n}", + "title": "2341. Maximum Number of Pairs in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one operation, you may do the following: The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible .", + "description_images": [], + "constraints": [ + "Choose two integers in nums that are equal .", + "Remove both integers from nums , forming a pair ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,1,3,2,2]\nOutput:[3,1]\nExplanation:Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[1,0]\nExplanation:Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0]\nOutput:[0,1]\nExplanation:No pairs can be formed, and there is 1 number leftover in nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfPairs(self, nums: List[int]) -> List[int]:\n ans = [0] * 2\n c = Counter(nums)\n \n for v in c.values():\n ans[0] += (v // 2)\n ans[1] += (v % 2)\n \n return ans\n", + "title": "2341. Maximum Number of Pairs in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix points ( 0-indexed ). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row . Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1 ), picking cells at coordinates (r, c 1 ) and (r + 1, c 2 ) will subtract abs(c 1 - c 2 ) from your score. Return the maximum number of points you can achieve . abs(x) is defined as:", + "description_images": [], + "constraints": [ + "x for x >= 0 .", + "-x for x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput:9\nExplanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:points = [[1,5],[2,3],[4,2]]\nOutput:11\nExplanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "/* \n -> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get \n\tadded to next values from next row.\n\n -> conditions to update values in frame \n\t\t* we will keep only those values which will contribute maximum in next row addition\n\n\te.g-->\n\t\tpoints --->[[1,2,3]\n\t\t\t\t\t[1,5,1]\n\t\t\t\t\t[3,1,1]]\n\n\t\tfor 1st iteration frame <--- [1,2,3] rest of two loops will not affect frame so in \n\t\t2nd itreration frame <--------[2,7,4] <-------- [1,2,3] + [1,5,1]\n\t\tnow we have to update frame so it can give max values for next row addition\n\t\t 0 1 2 \n\t\t[2,7,4] \n\t\t \\ \n\t\t[2,7,4] check left to right--> just check value at index 0 can contribute more than curr_sum at index 1 but to do so it has to give up (1-0) a penalty,here 7 can contribute more than 2-1=1 in next sum.\n\t\t2 7 4 now check for index 2,where (7-1)>4\n\t\t \\\n\t\t2 7 6\n\t\t\t\t\tnow do in reverse,can 6 contribute more than 7 no ( 7 >(6-1) ) \n\t\t\t\t\tcan 7 contibute more than 2 yes (2<(7-1)),so now frame will be\n\t\t6 7 6 now we can cal optimal-frame for rest of the matrix.\n\t+ 3 1 1\n ------------------- \n\t\t9 8 7 check left to right--> can 9 can contibute 8>(9-1) no; can 8 can contibute for index 2 no simlier for right to left\n*/\n\nclass Solution {\n\tpublic long maxPoints(int[][] points) {\n\t\tlong[] frame = new long[points[0].length];\n\n\t\tfor (int i = 0; i < points.length; i++) {\n\t\t\tfor (int j = 0; j =0;j--) frame[j] = Math.max(frame[j], frame[j + 1] - 1);\n\n\t\t\tfor(long k:frame) System.out.println(k);\n\t\t}\n\n\n\t\tlong ans = 0;\n\t\tfor (int i = 0; i < frame.length; i ++) {\n\t\t\tans = Math.max(ans, frame[i]);\n\t\t}\n\t\treturn ans;\n\t}\n}\n", + "title": "1937. Maximum Number of Points with Cost", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix points ( 0-indexed ). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row . Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1 ), picking cells at coordinates (r, c 1 ) and (r + 1, c 2 ) will subtract abs(c 1 - c 2 ) from your score. Return the maximum number of points you can achieve . abs(x) is defined as:", + "description_images": [], + "constraints": [ + "x for x >= 0 .", + "-x for x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput:9\nExplanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:points = [[1,5],[2,3],[4,2]]\nOutput:11\nExplanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n for i in range(m - 1):\n for j in range(1, n):\n points[i][j] = max(points[i][j], points[i][j - 1] - 1)\n \n for j in range(n - 2, -1, -1):\n points[i][j] = max(points[i][j], points[i][j + 1] - 1)\n \n for j in range(n):\n points[i + 1][j] += points[i][j]\n \n return max(points[m - 1])", + "title": "1937. Maximum Number of Points with Cost", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings s and p where p is a subsequence of s . You are also given a distinct 0-indexed integer array removable containing a subset of indices of s ( s is also 0-indexed ). You want to choose an integer k ( 0 <= k <= removable.length ) such that, after removing k characters from s using the first k indices in removable , p is still a subsequence of s . More formally, you will mark the character at s[removable[i]] for each 0 <= i < k , then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals . 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.", + "description_images": [], + "constraints": [ + "1 <= p.length <= s.length <= 10^5", + "0 <= removable.length < s.length", + "0 <= removable[i] < s.length", + "p is a subsequence of s .", + "s and p both consist of lowercase English letters.", + "The elements in removable are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcacb\", p = \"ab\", removable = [3,1,0]\nOutput:2\nExplanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\nOutput:1\nExplanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\nOutput:0\nExplanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumRemovals(String s, String p, int[] removable) {\n int left = 0, right = removable.length;\n\n while (left < right) {\n int middle = (right + left + 1) / 2;\n String afterRemoval = remove(s, removable, middle);\n if (isSubsequence(p, afterRemoval, p.length(), afterRemoval.length()))\n left = middle;\n else\n right = middle - 1;\n }\n\n return left;\n }\n\n private String remove(String s, int[] removable, int k) {\n char[] symbols = s.toCharArray();\n for (int i = 0; i < k; i++) {\n symbols[removable[i]] = Character.MIN_VALUE;\n }\n return String.valueOf(symbols);\n }\n\n private boolean isSubsequence(String subSequence, String word, int subSequenceChar, int wordChar) {\n if (subSequenceChar == 0) return true;\n if (wordChar == 0) return false;\n\n if (subSequence.charAt(subSequenceChar - 1) == word.charAt(wordChar - 1))\n return isSubsequence(subSequence, word, subSequenceChar - 1, wordChar - 1);\n\n return isSubsequence(subSequence, word, subSequenceChar, wordChar - 1);\n }\n}\n", + "title": "1898. Maximum Number of Removable Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s and p where p is a subsequence of s . You are also given a distinct 0-indexed integer array removable containing a subset of indices of s ( s is also 0-indexed ). You want to choose an integer k ( 0 <= k <= removable.length ) such that, after removing k characters from s using the first k indices in removable , p is still a subsequence of s . More formally, you will mark the character at s[removable[i]] for each 0 <= i < k , then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals . 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.", + "description_images": [], + "constraints": [ + "1 <= p.length <= s.length <= 10^5", + "0 <= removable.length < s.length", + "0 <= removable[i] < s.length", + "p is a subsequence of s .", + "s and p both consist of lowercase English letters.", + "The elements in removable are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcacb\", p = \"ab\", removable = [3,1,0]\nOutput:2\nExplanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\nOutput:1\nExplanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\nOutput:0\nExplanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 957 ms (Top 98.8%) | Memory: 28.80 MB (Top 96.39%)\n\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n\n def isEnough(k):\n s_arr = list(s)\n for i in removable[:k]:\n s_arr[i] = ''\n return isSubsequence(p, s_arr)\n \n def isSubsequence(s, t):\n t = iter(t)\n return all(c in t for c in s)\n\n while l < r:\n m = (l+r+1)//2\n if isEnough(m):\n l = m\n else:\n r = m - 1\n \n return l\n", + "title": "1898. Maximum Number of Removable Characters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks , with the i th task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers , with the j th worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i] ). Additionally, you have pills magical pills that will increase a worker's strength by strength . You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength , return the maximum number of tasks that can be completed.", + "description_images": [], + "constraints": [ + "n == tasks.length", + "m == workers.length", + "1 <= n, m <= 5 * 10^4", + "0 <= pills <= m", + "0 <= tasks[i], workers[j], strength <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1\nOutput:3\nExplanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5\nOutput:1\nExplanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)", + "image": null + }, + { + "text": "Example 3: Input:tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\nOutput:2\nExplanation:We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) { \n Arrays.sort(tasks);\n Arrays.sort(workers);\n \n int st = 0;\n int end = Math.min(tasks.length, workers.length)-1;\n int ans =0;\n while(st<=end){\n int mid = (st+end)/2;\n if(isPossible(tasks, workers, pills, strength, mid)){\n st = mid+1;\n ans = Math.max(ans, mid+1);\n }else{\n end = mid-1;\n }\n }\n return ans;\n }\n \nboolean isPossibleToComplete(int[] tasks, int[] workers, int pills, int strength, int mid) {\n int n = workers.length;\n TreeMap map = new TreeMap<>();\n \n for (int i = n - 1, count = 0; count <= mid && i >= 0; i--, count++) {\n map.merge(workers[i], 1, (a, b) -> a + b);\n }\n int done = n - 1;\n int count = mid;\n for (int i = mid; i >= 0; i--) {\n int val = tasks[i];\n Integer kv = map.ceilingKey(val);\n if (kv != null) {\n updateMap(map, kv);\n } else {\n if(pills>0){\n int newStrg = val-strength;\n Integer newKv = map.ceilingKey(newStrg);\n if(newKv!=null){\n updateMap(map, newKv);\n pills--;\n }else {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }\n void updateMap(TreeMap map, int key){\n int vl = map.get(key);\n map.put(key, vl - 1);\n if (vl - 1 == 0) {\n map.remove(key);\n }\n }\n}\n", + "title": "2071. Maximum Number of Tasks You Can Assign", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks , with the i th task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers , with the j th worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i] ). Additionally, you have pills magical pills that will increase a worker's strength by strength . You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength , return the maximum number of tasks that can be completed.", + "description_images": [], + "constraints": [ + "n == tasks.length", + "m == workers.length", + "1 <= n, m <= 5 * 10^4", + "0 <= pills <= m", + "0 <= tasks[i], workers[j], strength <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1\nOutput:3\nExplanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5\nOutput:1\nExplanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)", + "image": null + }, + { + "text": "Example 3: Input:tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\nOutput:2\nExplanation:We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n from sortedcontainers import SortedList\n \n tasks.sort()\n workers.sort()\n \n def check_valid(ans):\n \n # _tasks = SortedList(tasks[:ans])\n _tasks = deque(tasks[:ans])\n _workers = workers[-ans:]\n remain_pills = pills\n \n for worker in _workers:\n task = _tasks[0]\n if worker >= task:\n # the worker can finish the min task without pill, just move on\n # _tasks.pop(0)\n _tasks.popleft()\n elif worker + strength >= task and remain_pills:\n # the worker cannot finish the min task without pill, but can solve it with pill\n # remove the max task that the strengthened worker can finish instead\n # remove_task_idx = _tasks.bisect_right(worker + strength)\n remove_task_idx = bisect.bisect_right(_tasks, worker + strength)\n # _tasks.pop(remove_task_idx - 1)\n del _tasks[remove_task_idx - 1]\n remain_pills -= 1\n else:\n return False\n return True\n \n lo, hi = 0, min(len(workers), len(tasks))\n while lo < hi:\n mid = (lo + hi + 1) // 2\n if check_valid(mid):\n lo = mid\n else:\n hi = mid - 1\n return lo\n", + "title": "2071. Maximum Number of Tasks You Can Assign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array points , an integer angle , and your location , where location = [pos x , pos y ] and points[i] = [x i , y i ] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate . In other words, pos x and pos y cannot be changed. Your field of view in degrees is represented by angle , determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2] . Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view . There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "location.length == 2", + "0 <= angle < 360", + "0 <= pos x , pos y , x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput:3\nExplanation:The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/89a07e9b-00ab-4967-976a-c723b2aa8656.png" + }, + { + "text": "Example 2: Input:points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput:4\nExplanation:All points can be made visible in your field of view, including the one at your location.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput:1\nExplanation:You can only see one of the two points, as shown above.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/5010bfd3-86e6-465f-ac64-e9df941d2e49.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 251 ms (Top 43.04%) | Memory: 144 MB (Top 24.17%)\nclass Solution {\n public int visiblePoints(List> points, int angle, List location) {\n int overlap = 0;\n List list = new ArrayList<>(points.size());\n for (List p : points) {\n if (p.get(0) == location.get(0) && p.get(1) == location.get(1)) {\n overlap++;\n } else {\n list.add(angle(p.get(1) - location.get(1),\n p.get(0) - location.get(0)));\n }\n }\n Collections.sort(list);\n int max = 0;\n int n = list.size();\n int i2 = 0;\n // list.get(i1) is first angle leg\n // list.get(i2) is second angle leg\n for (int i1 = 0; i1 < n; i1++) {\n // let's grow i1-i2 angle as much as possible\n // edge case example: angle = 30, i1 = 350 degrees, i2 = 10 degrees\n // edge case handling: allow i2 to circle around and calculate second leg as (360 + list.get(i2 % n))\n // then i1 = 350, i2 = 370, delta = 20 degrees < 30 degrees\n while ((i2 < n && list.get(i2) - list.get(i1) <= angle) ||\n (i2 >= n && 360 + list.get(i2 % n) - list.get(i1) <= angle)) {\n i2++;\n }\n // after i2 went as far as possible away from i1 under allowed limit - check if a new maximum found\n max = Math.max(max, i2-i1);\n }\n return max + overlap;\n }\n\n private double angle(int dy, int dx) {\n double a = Math.toDegrees(Math.atan2(dy, dx));\n return (a < 0 ? a + 360 : a);\n }\n}", + "title": "1610. Maximum Number of Visible Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array points , an integer angle , and your location , where location = [pos x , pos y ] and points[i] = [x i , y i ] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate . In other words, pos x and pos y cannot be changed. Your field of view in degrees is represented by angle , determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2] . Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view . There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "location.length == 2", + "0 <= angle < 360", + "0 <= pos x , pos y , x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput:3\nExplanation:The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/89a07e9b-00ab-4967-976a-c723b2aa8656.png" + }, + { + "text": "Example 2: Input:points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput:4\nExplanation:All points can be made visible in your field of view, including the one at your location.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput:1\nExplanation:You can only see one of the two points, as shown above.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/5010bfd3-86e6-465f-ac64-e9df941d2e49.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 5206 ms (Top 8.11%) | Memory: 46.3 MB (Top 98.26%)\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n\n arr, extra = [], 0\n xx, yy = location\n\n for x, y in points:\n if x == xx and y == yy:\n extra += 1\n continue\n arr.append(math.atan2(y - yy, x - xx))\n\n arr.sort()\n arr = arr + [x + 2.0 * math.pi for x in arr]\n angle = math.pi * angle / 180\n\n l = ans = 0\n for r in range(len(arr)):\n while arr[r] - arr[l] > angle:\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans + extra", + "title": "1610. Maximum Number of Visible Points", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3\nOutput:3\nExplanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2\nOutput:2\nExplanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3\nOutput:2\nExplanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 97.98%) | Memory: 45.20 MB (Top 9.52%)\n\nclass Solution {\n public int maxVowels(String s, int k) {\n int n = s.length();\n int maxVowels = 0;\n int count = 0;\n\n int[] vowels = new int[128];\n vowels['a'] = 1;\n vowels['e'] = 1;\n vowels['i'] = 1;\n vowels['o'] = 1;\n vowels['u'] = 1;\n\n for (int i = 0; i < k; i++) {\n count += vowels[s.charAt(i)];\n }\n\n maxVowels = count;\n for (int i = k; i < n; i++) {\n count += vowels[s.charAt(i)] - vowels[s.charAt(i - k)];\n maxVowels = Math.max(maxVowels, count);\n //System.out.println(Arrays.toString(vowels));\n if (maxVowels == k) {\n return maxVowels; \n }\n }\n return maxVowels;\n }\n}\n\n", + "title": "1456. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3\nOutput:3\nExplanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2\nOutput:2\nExplanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3\nOutput:2\nExplanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxVowels(self, s: str, k: int) -> int:\n \n def find_count_vowels(string):\n lst_vowels= ['a', 'e', 'i', 'o', 'u']\n c=0\n for i in string:\n if i in lst_vowels:\n c+=1\n return c\n \n \n lst_vowels= ['a', 'e', 'i', 'o', 'u']\n if k>len(s):\n return find_count_vowels(s)\n dp = [0]*(len(s)-k+1)\n dp[0] = find_count_vowels(s[:k])\n for i in range(1,len(s)-k+1):\n \n \n if s[i-1] in lst_vowels and s[i+k-1] in lst_vowels:\n dp[i] = dp[i-1]\n elif s[i-1] in lst_vowels and s[i+k-1] not in lst_vowels:\n dp[i] = dp[i-1] - 1\n\n elif s[i-1] not in lst_vowels and s[i+k-1] in lst_vowels:\n dp[i] = dp[i-1] + 1\n else:\n dp[i] = dp[i-1]\n return max(dp)\n \n", + "title": "1456. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k . You can choose to change the value of one element of nums to k , or to leave the array unchanged . Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element .", + "description_images": [], + "constraints": [ + "1 <= pivot < n", + "nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,2], k = 3\nOutput:1\nExplanation:One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], k = 1\nOutput:2\nExplanation:The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput:4\nExplanation:One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 532 ms (Top 32.98%) | Memory: 178.2 MB (Top 67.02%)\nclass Solution {\n //time - O(n), space - O(n)\n public int waysToPartition(int[] nums, int k) {\n int n = nums.length;\n\n int[] pref = new int[n];\n pref[0] = nums[0];\n Map count = new HashMap<>(); //contribution of prefixes without changing\n count.put(pref[0], 1);\n\n for (int i = 1; i < n - 1; i++){\n pref[i] += pref[i - 1] + nums[i];\n count.put(pref[i], count.getOrDefault(pref[i], 0) + 1);\n }\n pref[n - 1] += pref[n - 2] + nums[n - 1]; //last step doesn't add into 'count' map, because we're trying to find at least two parts.\n\n int sum = pref[n - 1];\n int max = 0;\n if (sum % 2 == 0)\n max = count.getOrDefault(sum / 2, 0); //max without changing\n\n Map countPrev = new HashMap<>(); //contribution of prefixes before current step\n for (int i = 0; i < n; i++){\n int diff = k - nums[i];\n int changedSum = sum + diff;\n if (changedSum % 2 == 0)\n max = Math.max(max, count.getOrDefault(changedSum / 2 - diff, 0) + countPrev.getOrDefault(changedSum / 2, 0));\n count.put(pref[i], count.getOrDefault(pref[i], 0) - 1);\n countPrev.put(pref[i], countPrev.getOrDefault(pref[i], 0) + 1);\n }\n return max;\n }\n}", + "title": "2025. Maximum Number of Ways to Partition an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k . You can choose to change the value of one element of nums to k , or to leave the array unchanged . Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element .", + "description_images": [], + "constraints": [ + "1 <= pivot < n", + "nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,2], k = 3\nOutput:1\nExplanation:One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], k = 1\nOutput:2\nExplanation:The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput:4\nExplanation:One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3346 ms (Top 89.52%) | Memory: 46.9 MB (Top 30.64%)\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix_sums = list(accumulate(nums))\n total_sum = prefix_sums[-1]\n best = 0\n if total_sum % 2 == 0:\n best = prefix_sums[:-1].count(total_sum // 2) # If no change\n\n after_counts = Counter(total_sum - 2 * prefix_sum\n for prefix_sum in prefix_sums[:-1])\n before_counts = Counter()\n\n best = max(best, after_counts[k - nums[0]]) # If we change first num\n\n for prefix, x in zip(prefix_sums, nums[1:]):\n gap = total_sum - 2 * prefix\n after_counts[gap] -= 1\n before_counts[gap] += 1\n\n best = max(best, after_counts[k - x] + before_counts[x - k])\n\n return best", + "title": "2025. Maximum Number of Ways to Partition an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n projects numbered from 0 to n - 1 . You are given an integer array milestones where each milestones[i] denotes the number of milestones the i th project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working . Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above .", + "description_images": [], + "constraints": [ + "Every week, you will finish exactly one milestone of one project. You must work every week.", + "You cannot work on two milestones from the same project for two consecutive weeks." + ], + "examples": [ + { + "text": "Example 1: Input:milestones = [1,2,3]\nOutput:6\nExplanation:One possible scenario is:\n​​​​- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 2.\n- During the 3rdweek, you will work on a milestone of project 1.\n- During the 4thweek, you will work on a milestone of project 2.\n- During the 5thweek, you will work on a milestone of project 1.\n- During the 6thweek, you will work on a milestone of project 2.\nThe total number of weeks is 6.", + "image": null + }, + { + "text": "Example 2: Input:milestones = [5,2,1]\nOutput:7\nExplanation:One possible scenario is:\n- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 1.\n- During the 3rdweek, you will work on a milestone of project 0.\n- During the 4thweek, you will work on a milestone of project 1.\n- During the 5thweek, you will work on a milestone of project 0.\n- During the 6thweek, you will work on a milestone of project 2.\n- During the 7thweek, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8thweek because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 73.74%) | Memory: 55.50 MB (Top 96.97%)\n\nclass Solution {\n public long numberOfWeeks(int[] milestones) {\n long sum = 0;\n int max = Integer.MIN_VALUE;\n for(int milestone: milestones) {\n sum += milestone;\n max = Math.max(milestone, max);\n }\n if((sum - max) < max)\n return ((sum - max) * 2) + 1;\n else\n return sum;\n }\n}\n", + "title": "1953. Maximum Number of Weeks for Which You Can Work", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n projects numbered from 0 to n - 1 . You are given an integer array milestones where each milestones[i] denotes the number of milestones the i th project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working . Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above .", + "description_images": [], + "constraints": [ + "Every week, you will finish exactly one milestone of one project. You must work every week.", + "You cannot work on two milestones from the same project for two consecutive weeks." + ], + "examples": [ + { + "text": "Example 1: Input:milestones = [1,2,3]\nOutput:6\nExplanation:One possible scenario is:\n​​​​- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 2.\n- During the 3rdweek, you will work on a milestone of project 1.\n- During the 4thweek, you will work on a milestone of project 2.\n- During the 5thweek, you will work on a milestone of project 1.\n- During the 6thweek, you will work on a milestone of project 2.\nThe total number of weeks is 6.", + "image": null + }, + { + "text": "Example 2: Input:milestones = [5,2,1]\nOutput:7\nExplanation:One possible scenario is:\n- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 1.\n- During the 3rdweek, you will work on a milestone of project 0.\n- During the 4thweek, you will work on a milestone of project 1.\n- During the 5thweek, you will work on a milestone of project 0.\n- During the 6thweek, you will work on a milestone of project 2.\n- During the 7thweek, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8thweek because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1032 ms (Top 59.60%) | Memory: 25.7 MB (Top 80.23%)\nclass Solution:\n def numberOfWeeks(self, m: List[int]) -> int:\n return min(sum(m), 2 * (sum(m) - max(m)) + 1)", + "title": "1953. Maximum Number of Weeks for Which You Can Work", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences , where each sentences[i] represents a single sentence . Return the maximum number of words that appear in a single sentence .", + "description_images": [], + "constraints": [ + "1 <= sentences.length <= 100", + "1 <= sentences[i].length <= 100", + "sentences[i] consists only of lowercase English letters and ' ' only.", + "sentences[i] does not have leading or trailing spaces.", + "All the words in sentences[i] are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:sentences = [\"alice and bob love leetcode\", \"i think so too\",\"this is great thanks very much\"]\nOutput:6\nExplanation:- The first sentence, \"alice and bob love leetcode\", has 5 words in total.\n- The second sentence, \"i think so too\", has 4 words in total.\n- The third sentence, \"this is great thanks very much\", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.", + "image": null + }, + { + "text": "Example 2: Input:sentences = [\"please wait\",\"continue to fight\",\"continue to win\"]\nOutput:3\nExplanation:It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 54.44%) | Memory: 45.2 MB (Top 33.72%)\nclass Solution {\n public int mostWordsFound(String[] sentences) {\n int max=0;\n for(int i=0; i int:\n mx=0\n for i in sentences:\n c=i.split()\n if len(c)>mx:\n mx=len(c)\n return mx\n\t\t\n", + "title": "2114. Maximum Number of Words Found in Sentences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard .", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^4", + "0 <= brokenLetters.length <= 26", + "text consists of words separated by a single space without any leading or trailing spaces.", + "Each word only consists of lowercase English letters.", + "brokenLetters consists of distinct lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"hello world\", brokenLetters = \"ad\"\nOutput:1\nExplanation:We cannot type \"world\" because the 'd' key is broken.", + "image": null + }, + { + "text": "Example 2: Input:text = \"leet code\", brokenLetters = \"lt\"\nOutput:1\nExplanation:We cannot type \"leet\" because the 'l' and 't' keys are broken.", + "image": null + }, + { + "text": "Example 3: Input:text = \"leet code\", brokenLetters = \"e\"\nOutput:0\nExplanation:We cannot type either word because the 'e' key is broken.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 25.13%) | Memory: 42.1 MB (Top 88.13%)\nclass Solution {\n public int canBeTypedWords(String text, String brokenLetters) {\n int count = 1;\n boolean isBad = false;\n for (char c : text.toCharArray()) {\n if (c == ' ') {\n isBad = false;\n count++;\n } else {\n if (!isBad && brokenLetters.indexOf(c) != -1) {\n isBad = true;\n count--;\n }\n }\n }\n return count;\n }\n}", + "title": "1935. Maximum Number of Words You Can Type", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard .", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^4", + "0 <= brokenLetters.length <= 26", + "text consists of words separated by a single space without any leading or trailing spaces.", + "Each word only consists of lowercase English letters.", + "brokenLetters consists of distinct lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"hello world\", brokenLetters = \"ad\"\nOutput:1\nExplanation:We cannot type \"world\" because the 'd' key is broken.", + "image": null + }, + { + "text": "Example 2: Input:text = \"leet code\", brokenLetters = \"lt\"\nOutput:1\nExplanation:We cannot type \"leet\" because the 'l' and 't' keys are broken.", + "image": null + }, + { + "text": "Example 3: Input:text = \"leet code\", brokenLetters = \"e\"\nOutput:0\nExplanation:We cannot type either word because the 'e' key is broken.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n text = text.split()\n length = len(text)\n brokenLetters = set(brokenLetters)\n\n for word in text:\n for char in word:\n if char in brokenLetters:\n length -= 1\n break\n\t\t\t\t\t\n return length\n", + "title": "1935. Maximum Number of Words You Can Type", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length .", + "description_images": [], + "constraints": [ + "2 <= arr1.length == arr2.length <= 40000", + "-10^6 <= arr1[i], arr2[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput:13", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 33.52%) | Memory: 58.1 MB (Top 8.52%)\nclass Solution {\n public int maxAbsValExpr(int[] arr1, int[] arr2) {\n\n //1. remove the modulas -\n //i & j are interchangable because they are inside the modulas\n // A[i] - A[j] + B[i] -B[j] + i-j\n // A[i] + B[i] + i - B[j] - A[j] - j\n // (A[i] + B[i] + i) ->X\n // (B[j] - A[j] - j) -> y\n // X - Y;\n //to get max value X should be max & Y should min\n\n // Possible cases (Since both arrays have same number of indexes, we can use single for loop & i as index)\n //A[i] + B[i] + i ->1\n //A[i] - B[i] + i ->2\n //A[i] + B[i] - i ->3\n //A[i] - B[i] - i ->4\n\n // Find out max of all response\n\n int arrayLength =arr1.length;\n int v1[] = new int [arrayLength];\n int v2[] = new int [arrayLength] ;\n int v3[] = new int [arrayLength] ;\n int v4[] = new int [arrayLength] ;\n int res = 0;\n for(int i = 0 ; i< arrayLength; i++)\n {\n v1[i] = i + arr1[i] + arr2[i];\n v2[i] = i + arr1[i] - arr2[i];\n v3[i] = i - arr1[i] + arr2[i];\n v4[i] = i - arr1[i] - arr2[i];\n }\nres = Math.max(res,Arrays.stream(v1).max().getAsInt()-Arrays.stream(v1).min().getAsInt());\n res = Math.max(res,Arrays.stream(v2).max().getAsInt()-Arrays.stream(v2).min().getAsInt());\n res = Math.max(res,Arrays.stream(v3).max().getAsInt()-Arrays.stream(v3).min().getAsInt());\n res = Math.max(res,Arrays.stream(v4).max().getAsInt()-Arrays.stream(v4).min().getAsInt());\n return res;\n }\n}", + "title": "1131. Maximum of Absolute Value Expression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length .", + "description_images": [], + "constraints": [ + "2 <= arr1.length == arr2.length <= 40000", + "-10^6 <= arr1[i], arr2[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput:13", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxAbsValExpr(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf')\n min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),float('inf'),float('inf'),float('inf')\n for i,(a,b) in enumerate(zip(arr1,arr2)):\n ppp=a+b+i\n if ppp>max_ppp:max_ppp=ppp\n if pppmax_ppm:max_ppm=ppm\n if ppmmax_pmp:max_pmp=pmp\n if pmpmax_pmm:max_pmm=pmm\n if pmm 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex1drawio.png" + }, + { + "text": "Example 2: Input:values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\nOutput:25\nExplanation:One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex2drawio.png" + }, + { + "text": "Example 3: Input:values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\nOutput:7\nExplanation:One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex31drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 301 ms (Top 63.32%) | Memory: 101.4 MB (Top 52.55%)\nclass Solution {\n public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {\n int n = values.length;\n List[] adj = new List[n];\n for (int i = 0; i < n; ++i) adj[i] = new LinkedList();\n for (int[] e : edges) {\n int i = e[0], j = e[1], t = e[2];\n adj[i].add(new int[]{j, t});\n adj[j].add(new int[]{i, t});\n }\n int[] res = new int[1];\n int[] seen = new int[n];\n seen[0]++;\n dfs(adj, 0, values, maxTime, seen, res, values[0]);\n return res[0];\n }\n private void dfs(List[] adj, int src, int[] values, int maxTime, int[] seen, int[] res, int sum) {\n if (0 == src) {\n res[0] = Math.max(res[0], sum);\n }\n if (0 > maxTime) return;\n for (int[] data : adj[src]) {\n int dst = data[0], t = data[1];\n if (0 > maxTime - t) continue;\n seen[dst]++;\n dfs(adj, dst, values, maxTime - t, seen, res, sum + (1 == seen[dst] ? values[dst] : 0));\n seen[dst]--;\n }\n }\n}", + "title": "2065. Maximum Path Quality of a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected graph with n nodes numbered from 0 to n - 1 ( inclusive ). You are given a 0-indexed integer array values where values[i] is the value of the i th node. You are also given a 0-indexed 2D integer array edges , where each edges[j] = [u j , v j , time j ] indicates that there is an undirected edge between the nodes u j and v j , and it takes time j seconds to travel between the two nodes. Finally, you are given an integer maxTime . A valid path in the graph is any path that starts at node 0 , ends at node 0 , and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path . Note: There are at most four edges connected to each node.", + "description_images": [], + "constraints": [ + "n == values.length", + "1 <= n <= 1000", + "0 <= values[i] <= 10^8", + "0 <= edges.length <= 2000", + "edges[j].length == 3", + "0 <= u j < v j <= n - 1", + "10 <= time j , maxTime <= 100", + "All the pairs [u j , v j ] are unique .", + "There are at most four edges connected to each node.", + "The graph may not be connected." + ], + "examples": [ + { + "text": "Example 1: Input:values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49\nOutput:75\nExplanation:One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex1drawio.png" + }, + { + "text": "Example 2: Input:values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\nOutput:25\nExplanation:One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex2drawio.png" + }, + { + "text": "Example 3: Input:values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\nOutput:7\nExplanation:One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex31drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n graph = defaultdict(list)\n\t\t# build graph\n for edge in edges:\n graph[edge[0]].append((edge[1], edge[2]))\n graph[edge[1]].append((edge[0], edge[2]))\n \n q = deque()\n q.append((0, 0, values[0], set([0])))\n cache = {}\n maxPoint = 0\n\t\t\n while q:\n currV, currTime, currPoints, currSet = q.popleft()\n if currV in cache:\n\t\t\t\t# if vertex has been visited, and if the previousTime is \n\t\t\t\t# less or equal to current time but current points is lower?\n\t\t\t\t# then this path can't give us better quality so stop proceeding.\n prevTime, prevPoints = cache[currV]\n if prevTime <= currTime and prevPoints > currPoints:\n continue\n cache[currV] = (currTime, currPoints)\n\t\t\t# can't go over the maxTime limit\n if currTime > maxTime:\n continue\n\t\t\t# collect maxPoint only if current vertex is 0\n if currV == 0:\n maxPoint = max(maxPoint, currPoints)\n for neigh, neighTime in graph[currV]:\n newSet = currSet.copy()\n\t\t\t\t# collects quality only if not collected before\n if neigh not in currSet:\n newSet.add(neigh)\n newPoint = currPoints + values[neigh]\n else:\n newPoint = currPoints\n q.append((neigh, currTime + neighTime, newPoint, newSet))\n return maxPoint\n", + "title": "2065. Maximum Path Quality of a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n . There are n engineers numbered from 1 to n . speed[i] and efficiency[i] represent the speed and efficiency of the i th engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance . The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team . Since the answer can be a huge number, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^5", + "speed.length == n", + "efficiency.length == n", + "1 <= speed[i] <= 10^5", + "1 <= efficiency[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput:60\nExplanation:We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput:68\nExplanation:This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "image": null + }, + { + "text": "Example 3: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput:72", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 90 ms (Top 75.46%) | Memory: 69.9 MB (Top 33.86%)\nclass Engineer {\n int speed, efficiency;\n Engineer(int speed, int efficiency) {\n this.speed = speed;\n this.efficiency = efficiency;\n }\n}\n\nclass Solution {\n public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {\n List engineers = new ArrayList<>();\n for(int i=0;i b.efficiency - a.efficiency);\n PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> a.speed - b.speed);\n long maxPerformance = 0l, totalSpeed = 0l;\n for(Engineer engineer: engineers) {\n if(maxHeap.size() == k) {\n totalSpeed -= maxHeap.poll().speed;\n }\n totalSpeed += engineer.speed;\n maxHeap.offer(engineer);\n maxPerformance = Math.max(maxPerformance, totalSpeed * (long)engineer.efficiency);\n }\n return (int)(maxPerformance % 1_000_000_007);\n }\n}", + "title": "1383. Maximum Performance of a Team", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n . There are n engineers numbered from 1 to n . speed[i] and efficiency[i] represent the speed and efficiency of the i th engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance . The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team . Since the answer can be a huge number, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^5", + "speed.length == n", + "efficiency.length == n", + "1 <= speed[i] <= 10^5", + "1 <= efficiency[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput:60\nExplanation:We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput:68\nExplanation:This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "image": null + }, + { + "text": "Example 3: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput:72", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n l = list(zip(efficiency,speed))\n l.sort(reverse=True)\n h = []\n res = 0\n mod = 1000000007\n mx_sum = 0\n print(l)\n for i in range(n):\n res = max(res , (mx_sum+l[i][1])*l[i][0])\n if len(h) 0)\n bob[0] += remainArr;\n if(point > bobPoint) { // Update the max points and result output\n bobPoint = point;\n maxbob = bob.clone();\n }\n return;\n }\n //part 1: assign 1 more arrow than alice\n if(remainArr >= alice[index]+1) {\n bob[index] = alice[index] + 1;\n calculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index);\n bob[index] = 0;\n }\n //part 2: assign no arrow and move to next point\n calculate(alice, bob, index-1, remainArr, point);\n bob[index] = 0;\n }\n }", + "title": "2212. Maximum Points in an Archery Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11 , then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12 , which represents the number of arrows Alice shot on each scoring section from 0 to 11 . Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11 . The sum of the values in bobArrows should equal numArrows . If there are multiple ways for Bob to earn the maximum total points, return any one of them.", + "description_images": [], + "constraints": [ + "For example, if Alice and Bob both shot 2 arrows on the section with score 11 , then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points." + ], + "examples": [ + { + "text": "Example 1: Input:numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\nOutput:[0,0,0,0,1,1,0,0,1,2,3,1]\nExplanation:The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.", + "image": "https://assets.leetcode.com/uploads/2022/02/24/ex1.jpg" + }, + { + "text": "Example 2: Input:numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\nOutput:[0,0,0,0,0,0,0,0,1,1,1,0]\nExplanation:The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.", + "image": "https://assets.leetcode.com/uploads/2022/02/24/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 114 ms (Top 97.78%) | Memory: 16.60 MB (Top 73.33%)\n\nclass Solution:\n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n max_score = [0, None]\n def calc(i, remaining, score, arrows):\n\t\t # Base case. Update max score.\n if remaining == 0 or i == -1:\n if score > max_score[0]:\n max_score[0] = score\n max_score[1] = arrows[:]\n return\n\n\t\t\t# Special handling for the last section. Use up all the arrows.\n if i == 0:\n arrows[i] = remaining\n calc(i - 1, 0, score + i, arrows)\n arrows[i] = 0\n return\n\n\t\t # Try to compete with Alice if there are enough arrows.\n arrowsNeeded = aliceArrows[i] + 1\n if remaining >= arrowsNeeded:\n arrows[i] = arrowsNeeded\n calc(i - 1, remaining - arrowsNeeded, score + i, arrows)\n arrows[i] = 0\n\n # Skip this section and go to the next section.\n calc(i - 1, remaining, score, arrows)\n \n\t\t# Kick off the recursion\n calc(len(aliceArrows) - 1, numArrows, 0, [0 for _ in aliceArrows])\n return max_score[1]\n", + "title": "2212. Maximum Points in an Archery Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are several cards arranged in a row , and each card has an associated number of points. The points are given in the integer array cardPoints . In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k , return the maximum score you can obtain.", + "description_images": [], + "constraints": [ + "1 <= cardPoints.length <= 10^5", + "1 <= cardPoints[i] <= 10^4", + "1 <= k <= cardPoints.length" + ], + "examples": [ + { + "text": "Example 1: Input:cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput:12\nExplanation:After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.", + "image": null + }, + { + "text": "Example 2: Input:cardPoints = [2,2,2], k = 2\nOutput:4\nExplanation:Regardless of which two cards you take, your score will always be 4.", + "image": null + }, + { + "text": "Example 3: Input:cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput:55\nExplanation:You have to take all the cards. Your score is the sum of points of all cards.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 20.60%) | Memory: 66.5 MB (Top 16.04%)\nclass Solution {\n public int maxScore(int[] cardPoints, int k) {\n int n = cardPoints.length;\n int[] totalSum = new int[n];\n int sum = 0;\n for(int i=0;i int:\n n = len(cardPoints)\n total = sum(cardPoints)\n \n remaining_length = n - k\n subarray_sum = sum(cardPoints[:remaining_length])\n \n min_sum = subarray_sum\n for i in range(remaining_length, n):\n # Update the sliding window sum to the subarray ending at index i\n subarray_sum += cardPoints[i]\n subarray_sum -= cardPoints[i - remaining_length]\n # Update min_sum to track the overall minimum sum so far\n min_sum = min(min_sum, subarray_sum)\n return total - min_sum\n", + "title": "1423. Maximum Points You Can Obtain from Cards", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array logs where each logs[i] = [birth i , death i ] indicates the birth and death years of the i th person. The population of some year x is the number of people alive during that year. The i th person is counted in year x 's population if x is in the inclusive range [birth i , death i - 1] . Note that the person is not counted in the year that they die. Return the earliest year with the maximum population .", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 100", + "1950 <= birth i < death i <= 2050" + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[1993,1999],[2000,2010]]\nOutput:1993\nExplanation:The maximum population is 1, and 1993 is the earliest year with this population.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput:1960\nExplanation:The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 78.61%) | Memory: 42.6 MB (Top 29.91%)\nclass Solution {\n public int maximumPopulation(int[][] logs) {\n\n int[] year = new int[2051];\n\n // O(n) -> n is log.length\n\n for(int[] log : logs){\n\n year[log[0]] += 1;\n year[log[1]] -= 1;\n }\n\n int maxNum = year[1950], maxYear = 1950;\n\n // O(100) -> 2050 - 1950 = 100\n\n for(int i = 1951; i < year.length; i++){\n year[i] += year[i - 1]; // Generating Prefix Sum\n\n if(year[i] > maxNum){\n maxNum = year[i];\n maxYear = i;\n }\n }\n\n return maxYear;\n }\n}", + "title": "1854. Maximum Population Year", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array logs where each logs[i] = [birth i , death i ] indicates the birth and death years of the i th person. The population of some year x is the number of people alive during that year. The i th person is counted in year x 's population if x is in the inclusive range [birth i , death i - 1] . Note that the person is not counted in the year that they die. Return the earliest year with the maximum population .", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 100", + "1950 <= birth i < death i <= 2050" + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[1993,1999],[2000,2010]]\nOutput:1993\nExplanation:The maximum population is 1, and 1993 is the earliest year with this population.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput:1960\nExplanation:The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n logs.sort(key=lambda x: x[0])\n print(logs)\n living = 0\n max_living = 0\n year = 0\n\n for ind, (start, stop) in enumerate(logs):\n born = ind+1\n dead = 0\n for i in range(ind):\n if logs[i][1] <= start:\n dead += 1\n \n living = born - dead\n # print(born, dead, living, max_living)\n if living > max_living:\n max_living = living\n year = start\n\n \n \n return year", + "title": "1854. Maximum Population Year", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of non-negative integers nums and an integer k . In one operation, you may choose any element from nums and increment it by 1 . Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7 . Note that you should maximize the product before taking the modulo.", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,4], k = 5\nOutput:20\nExplanation:Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,3,2], k = 2\nOutput:216\nExplanation:Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumProduct(int[] nums, int k) {\n \n Queue pq = new PriorityQueue<>();\n for (int num : nums) pq.add(num);\n \n while (k-->0) {\n int top = pq.poll() + 1 ;\n pq.add(top);\n }\n\n long res = 1;\n while (!pq.isEmpty()) {\n res = (res*pq.poll()) % 1000000007;\n }\n\n return (int)(res);\n }\n}\n", + "title": "2233. Maximum Product After K Increments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of non-negative integers nums and an integer k . In one operation, you may choose any element from nums and increment it by 1 . Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7 . Note that you should maximize the product before taking the modulo.", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,4], k = 5\nOutput:20\nExplanation:Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,3,2], k = 2\nOutput:216\nExplanation:Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 985 ms (Top 85.38%) | Memory: 27.10 MB (Top 71.7%)\n\nclass Solution:\n def maximumProduct(self, nums: List[int], k: int) -> int:\n heap = nums.copy()\n heapify(heap)\n for i in range(k):\n t = heappop(heap)\n heappush(heap, t + 1)\n ans = 1\n mod = 1000000007\n for i in heap:\n ans = (ans*i) % mod\n return ans\n", + "title": "2233. Maximum Product After K Increments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d) . Given an integer array nums , choose four distinct indices w , x , y , and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized . Return the maximum such product difference .", + "description_images": [], + "constraints": [ + "For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,6,2,7,4]\nOutput:34\nExplanation:We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,5,9,7,4,8]\nOutput:64\nExplanation:We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProductDifference(int[] nums) {\n int max1 = Integer.MIN_VALUE;\n int max2 = max1;\n\n int min1 = Integer.MAX_VALUE;\n int min2 = min1;\n for (int i = 0; i < nums.length; i++) {\n if (max1 < nums[i]) {\n max2 = max1;\n max1 = nums[i];\n } else if(nums[i] > max2)\n max2 = nums[i];\n\n if(min1 > nums[i]){\n min2 = min1;\n min1 = nums[i];\n }else if (nums[i] < min2)\n min2 = nums[i];\n }\n \n return (max1 * max2) - (min1 * min2);\n }\n}\n", + "title": "1913. Maximum Product Difference Between Two Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d) . Given an integer array nums , choose four distinct indices w , x , y , and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized . Return the maximum such product difference .", + "description_images": [], + "constraints": [ + "For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,6,2,7,4]\nOutput:34\nExplanation:We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,5,9,7,4,8]\nOutput:64\nExplanation:We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n max_1 = 0\n max_2 = 0\n min_1 = 10001\n min_2 = 10001\n for i in nums:\n if i >= max_1:\n max_2,max_1 = max_1,i\n elif i > max_2:\n max_2 = i\n if i <= min_1:\n min_2,min_1 = min_1,i\n elif i < min_2:\n min_2 = i\n \n return max_1*max_2 - min_1*min_2\n", + "title": "1913. Maximum Product Difference Between Two Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees . Since the answer may be too large, return it modulo 10^9 + 7 . Note that you need to maximize the answer before taking the mod and not after taking it.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5 * 10^4 ] .", + "1 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:110\nExplanation:Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" + }, + { + "text": "Example 2: Input:root = [1,null,2,3,4,null,null,5,6]\nOutput:90\nExplanation:Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 82.12%) | Memory: 70.1 MB (Top 38.32%)\nclass Solution {\n public void findMaxSum(TreeNode node,long sum[]){\n if(node==null) return ;\n\n findMaxSum(node.left,sum);\n findMaxSum(node.right,sum);\n\n sum[0]+=node.val;\n\n }\n\n public long findProd(TreeNode node,long sum[],long []max){\n if(node==null) return 0;\n\n long left=findProd(node.left, sum, max);\n long right=findProd(node.right,sum,max);\n\n long val=left+right+node.val;\n\n max[0]=Math.max(max[0],val*(sum[0]-val));\n\n return val;\n }\n public int maxProduct(TreeNode root) {\n\n long max[]=new long[1];\n long sum[]=new long[1];\n\n findMaxSum(root,sum);\n\n long n= findProd(root,sum,max);\n\n return (int)(max[0]%((int)1e9+7));\n }\n}", + "title": "1339. Maximum Product of Splitted Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees . Since the answer may be too large, return it modulo 10^9 + 7 . Note that you need to maximize the answer before taking the mod and not after taking it.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5 * 10^4 ] .", + "1 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:110\nExplanation:Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" + }, + { + "text": "Example 2: Input:root = [1,null,2,3,4,null,null,5,6]\nOutput:90\nExplanation:Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, root: Optional[TreeNode]) -> int:\n def findTotalSum(node, totalSum):\n if node is None:\n return totalSum\n totalSum = findTotalSum(node.left,totalSum)\n totalSum += node.val\n totalSum = findTotalSum(node.right,totalSum)\n return totalSum\n \n def dfs(node,maxProd,totalSum):\n if node is None:\n return maxProd,0\n if not node.left and not node.right:\n return maxProd,node.val\n maxProd, lSum = dfs(node.left,maxProd,totalSum)\n maxProd, rSum = dfs(node.right,maxProd,totalSum)\n subTreeSum = lSum+rSum+node.val\n maxProd = max(maxProd,(totalSum-lSum)*lSum,(totalSum-rSum)*rSum,(totalSum-subTreeSum)*subTreeSum)\n return maxProd, subTreeSum\n \n totalSum = findTotalSum(root, 0)\n product,_ = dfs(root,1,totalSum)\n return product % (pow(10,9)+7)\n", + "title": "1339. Maximum Product of Splitted Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find two disjoint palindromic subsequences of s such that the product of their lengths is maximized . The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.", + "description_images": [], + "constraints": [ + "2 <= s.length <= 12", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcodecom\"\nOutput:9\nExplanation: An optimal solution is to choose \"ete\" for the 1stsubsequence and \"cdc\" for the 2ndsubsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png" + }, + { + "text": "Example 2: Input:s = \"bb\"\nOutput:1\nExplanation: An optimal solution is to choose \"b\" (the first character) for the 1stsubsequence and \"b\" (the second character) for the 2ndsubsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"accbcaxxcxx\"\nOutput:25\nExplanation: An optimal solution is to choose \"accca\" for the 1stsubsequence and \"xxcxx\" for the 2ndsubsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 952 ms (Top 21.5%) | Memory: 44.16 MB (Top 54.1%)\n\nclass Solution {\n int res = 0;\n \n public int maxProduct(String s) {\n char[] strArr = s.toCharArray();\n dfs(strArr, 0, \"\", \"\");\n return res;\n }\n\n public void dfs(char[] strArr, int i, String s1, String s2){\n if(i >= strArr.length){\n if(isPalindromic(s1) && isPalindromic(s2))\n res = Math.max(res, s1.length()*s2.length());\n return;\n }\n dfs(strArr, i+1, s1 + strArr[i], s2);\n dfs(strArr, i+1, s1, s2 + strArr[i]);\n dfs(strArr, i+1, s1, s2);\n }\n\n public boolean isPalindromic(String str){\n int j = str.length() - 1;\n char[] strArr = str.toCharArray();\n for (int i = 0; i < j; i ++){\n if (strArr[i] != strArr[j])\n return false;\n j--;\n }\n return true;\n }\n}", + "title": "2002. Maximum Product of the Length of Two Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , find two disjoint palindromic subsequences of s such that the product of their lengths is maximized . The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.", + "description_images": [], + "constraints": [ + "2 <= s.length <= 12", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcodecom\"\nOutput:9\nExplanation: An optimal solution is to choose \"ete\" for the 1stsubsequence and \"cdc\" for the 2ndsubsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png" + }, + { + "text": "Example 2: Input:s = \"bb\"\nOutput:1\nExplanation: An optimal solution is to choose \"b\" (the first character) for the 1stsubsequence and \"b\" (the second character) for the 2ndsubsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"accbcaxxcxx\"\nOutput:25\nExplanation: An optimal solution is to choose \"accca\" for the 1stsubsequence and \"xxcxx\" for the 2ndsubsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, s: str) -> int:\n # n <= 12, which means the search space is small\n n = len(s)\n arr = []\n \n for mask in range(1, 1< 0:\n subseq += s[i]\n if subseq == subseq[::-1]:\n arr.append((mask, len(subseq)))\n \n result = 1\n for (mask1, len1), (mask2, len2) in product(arr, arr):\n # disjoint\n if mask1 & mask2 == 0:\n result = max(result, len1 * len2)\n return result\n", + "title": "2002. Maximum Product of the Length of Two Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i , j , k , l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive . Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "2 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababbb\"\nOutput:9\nExplanation:Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zaaaxbbby\"\nOutput:9\nExplanation:Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 65.22%) | Memory: 61.1 MB (Top 39.13%)\n// using manachers algorithm\n\nclass Solution {\n\n public long maxProduct(String s) {\n int n = s.length();\n if (n == 2) return 1;\n int[] len = manachers(s); // get lengths of palindromes at each element\n\n long left[] = new long[n]; // stores the max length of palindrome to left of each index\n\n int max = 1;\n left[0] = max;\n for (int i = 1; i <= n - 1; i++) {\n // does any palindrome end at i with length greater than max\n if (len[(i - max - 1 + i)/2] > max) max += 2;\n left[i] = max;\n }\n max = 1;\n long[] right = new long[n]; // stores the max length of palindrome to right of each index\n right[n - 1] = max;\n\n for (int i = n - 2; i >= 0; i--) {\n // does any palindrome start at i with length greater than max\n if (len[(i + max + 1 + i)/2] > max) max += 2;\n right[i] = max;\n }\n\n long res = 1;\n\n for (int i = 1; i < n; i++) {\n res = Math.max(res, left[i - 1] * right[i]);\n }\n return res;\n }\n\n // credit : https://hackernoon.com/manachers-algorithm-explained-longest-palindromic-substring-22cb27a5e96f\n private int[] manachers(String s) {\n\n int len = s.length();\n int[] P = new int[len];\n int c = 0; //stores the center of the longest palindromic substring until now\n int r = 0; //stores the right boundary of the longest palindromic substring until now\n int maxLen = 0;\n\n for(int i = 0; i < len; i++) {\n //get mirror index of i\n int mirror = (2 * c) - i;\n\n //see if the mirror of i is expanding beyond the left boundary of current longest palindrome at center c\n //if it is, then take r - i as P[i]\n //else take P[mirror] as P[i]\n if(i < r) {\n P[i] = Math.min(r - i, P[mirror]);\n }\n\n //expand at i\n int a = i + (1 + P[i]);\n int b = i - (1 + P[i]);\n while(a < len && b >= 0 && s.charAt(a) == s.charAt(b)) {\n P[i]++;\n a++;\n b--;\n }\n\n //check if the expanded palindrome at i is expanding beyond the right boundary of current longest palindrome at center c\n //if it is, the new center is i\n if(i + P[i] > r) {\n c = i;\n r = i + P[i];\n }\n }\n for (int i = 0; i < len; i++) P[i] = 1 + 2*P[i];\n return P;\n }\n\n}", + "title": "1960. Maximum Product of the Length of Two Palindromic Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i , j , k , l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive . Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "2 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababbb\"\nOutput:9\nExplanation:Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zaaaxbbby\"\nOutput:9\nExplanation:Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, s: str) -> int:\n n = len(s)\n \n # Manacher's algo\n hlen = [0]*n # half-length\n center = right = 0 \n for i in range(n): \n if i < right: hlen[i] = min(right - i, hlen[2*center - i])\n while 0 <= i-1-hlen[i] and i+1+hlen[i] < len(s) and s[i-1-hlen[i]] == s[i+1+hlen[i]]: \n hlen[i] += 1\n if right < i+hlen[i]: center, right = i, i+hlen[i]\n \n prefix = [0]*n\n suffix = [0]*n\n for i in range(n): \n prefix[i+hlen[i]] = max(prefix[i+hlen[i]], 2*hlen[i]+1)\n suffix[i-hlen[i]] = max(suffix[i-hlen[i]], 2*hlen[i]+1)\n \n for i in range(1, n): \n prefix[~i] = max(prefix[~i], prefix[~i+1]-2)\n suffix[i] = max(suffix[i], suffix[i-1]-2)\n \n for i in range(1, n): \n prefix[i] = max(prefix[i-1], prefix[i])\n suffix[~i] = max(suffix[~i], suffix[~i+1])\n \n return max(prefix[i-1]*suffix[i] for i in range(1, n))", + "title": "1960. Maximum Product of the Length of Two Palindromic Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , find three numbers whose product is maximum and return the maximum product .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:24", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3]\nOutput:-6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 99.90%) | Memory: 54.7 MB (Top 23.03%)\nclass Solution {\n public int maximumProduct(int[] nums) {\n int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;\n for (int n: nums) {\n if (n <= min1) {\n min2 = min1;\n min1 = n;\n } else if (n <= min2) { // n lies between min1 and min2\n min2 = n;\n }\n if (n >= max1) { // n is greater than max1, max2 and max3\n max3 = max2;\n max2 = max1;\n max1 = n;\n } else if (n >= max2) { // n lies betweeen max1 and max2\n max3 = max2;\n max2 = n;\n } else if (n >= max3) { // n lies betwen max2 and max3\n max3 = n;\n }\n }\n return Math.max(min1 * min2 * max1, max1 * max2 * max3);\n }\n}", + "title": "628. Maximum Product of Three Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , find three numbers whose product is maximum and return the maximum product .", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:24", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3]\nOutput:-6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n # TC = O(NlogN) because sorting the array \n # SC = O(1); no extra space needed; sorting was done in place.\n \n # sorting the array in descending order\n nums.sort(reverse = True)\n \n # maximum product can only occur for:\n # 1. positive no * positive no * positive no\n # 2. negative no * negative no * positive no\n \n # one negative and two positives and all negatives wont give max product\n # case where all numbers in the array are negative \n # eg : [-4,-3,-2,-1] is covered in all positives \n \n return max(nums[0]*nums[1]*nums[2],nums[-1]*nums[-2]*nums[0])\n", + "title": "628. Maximum Product of Three Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,2]\nOutput:12\nExplanation:If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,4,5]\nOutput:16\nExplanation:Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,7]\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProduct(int[] nums) {\n int max = Integer.MIN_VALUE;\n int maxi = -1;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] > max) {\n max = nums[i];\n maxi = i;\n }\n }\n nums[maxi] = Integer.MIN_VALUE;\n int nextmax = Integer.MIN_VALUE;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] > nextmax) nextmax = nums[i];\n }\n return max*nextmax-max-nextmax+1;\n }\n}\n", + "title": "1464. Maximum Product of Two Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,2]\nOutput:12\nExplanation:If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,4,5]\nOutput:16\nExplanation:Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,7]\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n # mx1 - max element, mx2 - second max element\n mx1 = nums[0] if nums[0] > nums[1] else nums[1]\n mx2 = nums[1] if nums[0] > nums[1] else nums[0]\n for num in nums[2:]:\n if num > mx1:\n mx1, mx2 = num, mx1\n elif num > mx2:\n mx2 = num\n\n return (mx1 - 1) * (mx2 - 1)\n\n", + "title": "1464. Maximum Product of Two Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string array words , return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters . If no such two words exist, return 0 .", + "description_images": [], + "constraints": [ + "2 <= words.length <= 1000", + "1 <= words[i].length <= 1000", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\nOutput:16\nExplanation:The two words can be \"abcw\", \"xtfn\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\nOutput:4\nExplanation:The two words can be \"ab\", \"cd\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput:0\nExplanation:No such pair of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 91.40%) | Memory: 44.6 MB (Top 93.55%)\nclass Solution {\n public int maxProduct(String[] words) {\n int n = words.length;\n int[] masks = new int[n];\n\n for (int i=0; i int:\n n=len(words)\n \n bit_masks = [0] * n\n lengths = [0] * n\n \n for i in range(n): \n for c in words[i]:\n bit_masks[i]|=1<<(ord(c) - ord('a')) # set the character bit \n lengths[i]=len(words[i])\n \n max_val = 0\n for i in range(n):\n for j in range(i+1, n):\n if not (bit_masks[i] & bit_masks[j]):\n max_val=max(max_val, lengths[i] * lengths[j])\n \n return max_val \n", + "title": "318. Maximum Product of Word Lengths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find a contiguous non-empty subarray within the array 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. A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10 <= nums[i] <= 10", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]\nOutput:6\nExplanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]\nOutput:0\nExplanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.73%) | Memory: 44.9 MB (Top 43.86%)\nclass Solution {\n public int maxProduct(int[] nums) {\n int ans = Integer.MIN_VALUE;\n int m = 1;\n for(int i=0; i< nums.length; i++){\n m*=nums[i];\n ans = Math.max(m, ans);\n if(m == 0) m=1;\n }\n int n = 1;\n for(int i=nums.length-1; i>=0; i--){\n n*=nums[i];\n ans = Math.max(n, ans);\n if(n == 0) n=1;\n }\n return ans;\n }\n}", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , find a contiguous non-empty subarray within the array 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. A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10 <= nums[i] <= 10", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]\nOutput:6\nExplanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]\nOutput:0\nExplanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prod=1\n maxprod=-100000000\n for i in range(len(nums)): # traverse from L-R so that we get max \n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n prod=1\n for i in range(len(nums)-1,-1,-1): #if 0 or -ve present at starting then find from back\n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n return maxprod\n", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i] , obtaining a profit of profit[i] . You're given the startTime , endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/10/sample1_1584.png", + "https://assets.leetcode.com/uploads/2019/10/10/sample22_1584.png", + "https://assets.leetcode.com/uploads/2019/10/10/sample3_1584.png" + ], + "constraints": [ + "1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4", + "1 <= startTime[i] < endTime[i] <= 10^9", + "1 <= profit[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\nOutput:120\nExplanation:The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\nOutput:150\nExplanation:The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.", + "image": null + }, + { + "text": "Example 3: Input:startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 990 ms (Top 41.71%) | Memory: 47.5 MB (Top 21.04%)\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n n = len(startTime)\n jobs = list(zip(startTime, endTime, profit))\n jobs.sort()\n startTime.sort()\n @lru_cache(None)\n def recur(i):\n if i == n:\n return 0\n j = bisect_left(startTime, jobs[i][1])\n one = jobs[i][2] + recur(j)\n two = recur(i+1)\n return max(one, two)\n return recur(0)", + "title": "1235. Maximum Profit in Job Scheduling", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are the operator of a Centennial Wheel that has four gondolas , and each gondola has room for up to four people . You have the ability to rotate the gondolas counterclockwise , which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the i th rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive . You cannot make customers wait if there is room in the gondola . Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers . If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation . Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1 .", + "description_images": [], + "constraints": [ + "n == customers.length", + "1 <= n <= 10^5", + "0 <= customers[i] <= 50", + "1 <= boardingCost, runningCost <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:customers = [8,3], boardingCost = 5, runningCost = 6\nOutput:3\nExplanation:The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.", + "image": "https://assets.leetcode.com/uploads/2020/09/09/wheeldiagram12.png" + }, + { + "text": "Example 2: Input:customers = [10,9,6], boardingCost = 6, runningCost = 4\nOutput:7\nExplanation:1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.", + "image": null + }, + { + "text": "Example 3: Input:customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\nOutput:-1\nExplanation:1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 80.7%) | Memory: 55.64 MB (Top 69.2%)\n\nclass Solution {\n public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {\n int rotatn = 0;\n int cust = 0;\n int profit = Integer.MIN_VALUE;\n int prRotn = 0;\n int cSit = 0;\n\n for(int i = 0 ; i < customers.length ; i++){\n cust += customers[i];\n rotatn++;\n\n int prof = 0;\n if(cust >= 4){\n \n cust = cust - 4;\n cSit += 4;\n }else{\n cSit += cust;\n cust = 0;\n }\n prof = cSit*boardingCost - rotatn*runningCost ;\n if(prof > profit){\n profit = prof;\n prRotn = rotatn;\n } \n }\n while(cust > 0){\n rotatn++;\n\n int prof = 0;\n if(cust >= 4){\n cust = cust - 4;\n cSit += 4;\n }else{\n cSit += cust;\n cust = 0;\n }\n prof = cSit*boardingCost - rotatn*runningCost ;\n\n if(prof > profit){\n profit = prof;\n\n prRotn = rotatn;\n } \n }\n if(profit > 0) return prRotn;\n return -1;\n }\n}", + "title": "1599. Maximum Profit of Operating a Centennial Wheel", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are the operator of a Centennial Wheel that has four gondolas , and each gondola has room for up to four people . You have the ability to rotate the gondolas counterclockwise , which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the i th rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive . You cannot make customers wait if there is room in the gondola . Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers . If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation . Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1 .", + "description_images": [], + "constraints": [ + "n == customers.length", + "1 <= n <= 10^5", + "0 <= customers[i] <= 50", + "1 <= boardingCost, runningCost <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:customers = [8,3], boardingCost = 5, runningCost = 6\nOutput:3\nExplanation:The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.", + "image": "https://assets.leetcode.com/uploads/2020/09/09/wheeldiagram12.png" + }, + { + "text": "Example 2: Input:customers = [10,9,6], boardingCost = 6, runningCost = 4\nOutput:7\nExplanation:1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.", + "image": null + }, + { + "text": "Example 3: Input:customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\nOutput:-1\nExplanation:1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "import sys\nMIN_INT = -sys.maxsize-1\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n maxx = MIN_INT\n rotate = total = ans = money = num = i = 0\n for i in range(len(customers)):\n total += customers[i]\n rotate = i+1\n if total >= 4:\n num += 4\n total -= 4\n else: \n num += total\n total = 0\n money = num * boardingCost - rotate * runningCost\n if maxx < money:\n maxx = money\n ans = rotate\n i+=1\n while(total > 0):\n rotate = i+1\n if total >= 4:\n num += 4\n total -= 4\n else: \n num += total\n total = 0\n money = num * boardingCost - rotate * runningCost\n if maxx < money:\n maxx = money\n ans = rotate\n i+=1\n if maxx < 0: return -1\n return ans\n", + "title": "1599. Maximum Profit of Operating a Centennial Wheel", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For a string sequence , a string word is k -repeating if word concatenated k times is a substring of sequence . The word 's maximum k -repeating value is the highest value k where word is k -repeating in sequence . If word is not a substring of sequence , word 's maximum k -repeating value is 0 . Given strings sequence and word , return the maximum k -repeating value of word in sequence .", + "description_images": [], + "constraints": [ + "1 <= sequence.length <= 100", + "1 <= word.length <= 100", + "sequence and word contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sequence = \"ababc\", word = \"ab\"\nOutput:2\nExplanation:\"abab\" is a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 2: Input:sequence = \"ababc\", word = \"ba\"\nOutput:1\nExplanation:\"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 3: Input:sequence = \"ababc\", word = \"ac\"\nOutput:0\nExplanation:\"ac\" is not a substring in \"ababc\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxRepeating(String s, String w) {\n if(w.length()>s.length()) return 0;\n int ans=0;\n StringBuilder sb=new StringBuilder(\"\");\n while(sb.length()<=s.length()){\n sb.append(w);\n if(s.contains(sb)) ans++;\n else break;\n }\n return ans;\n }\n}", + "title": "1668. Maximum Repeating Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For a string sequence , a string word is k -repeating if word concatenated k times is a substring of sequence . The word 's maximum k -repeating value is the highest value k where word is k -repeating in sequence . If word is not a substring of sequence , word 's maximum k -repeating value is 0 . Given strings sequence and word , return the maximum k -repeating value of word in sequence .", + "description_images": [], + "constraints": [ + "1 <= sequence.length <= 100", + "1 <= word.length <= 100", + "sequence and word contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sequence = \"ababc\", word = \"ab\"\nOutput:2\nExplanation:\"abab\" is a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 2: Input:sequence = \"ababc\", word = \"ba\"\nOutput:1\nExplanation:\"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 3: Input:sequence = \"ababc\", word = \"ac\"\nOutput:0\nExplanation:\"ac\" is not a substring in \"ababc\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 15.28%) | Memory: 13.8 MB (Top 62.83%)\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n if word not in sequence:\n return 0\n\n left = 1\n right = len(sequence) // len(word)\n while left <= right:\n mid = (left + right) // 2\n if word * mid in sequence:\n left = mid + 1\n else:\n right = mid - 1\n\n return left - 1", + "title": "1668. Maximum Repeating Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the i th battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times . The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.", + "description_images": [], + "constraints": [ + "1 <= n <= batteries.length <= 10^5", + "1 <= batteries[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, batteries = [3,3,3]\nOutput:4\nExplanation:Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example1-fit.png" + }, + { + "text": "Example 2: Input:n = 2, batteries = [1,1,1,1]\nOutput:2\nExplanation:Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 70.5%) | Memory: 56.31 MB (Top 66.2%)\n\nclass Solution {\n\n private boolean canFit(int n, long k, int[] batteries) {\n long currBatSum = 0;\n long target = n * k;\n\n for (int bat : batteries) {\n if (bat < k) {\n currBatSum += bat;\n } else {\n currBatSum += k;\n }\n\n if (currBatSum >= target) {\n return true;\n }\n }\n\n return currBatSum >= target;\n\n }\n\n public long maxRunTime(int n, int[] batteries) {\n long batSum = 0;\n for (int bat : batteries) {\n batSum += bat;\n }\n \n long lower = 0;\n long upper = batSum / n;\n long res = -1;\n\n\t\t// binary search\n while (lower <= upper) {\n long mid = lower + (upper - lower) / 2;\n\n if (canFit(n, mid, batteries)) {\n res = mid;\n lower = mid + 1;\n } else {\n upper = mid - 1;\n }\n }\n\n return res;\n }\n}", + "title": "2141. Maximum Running Time of N Computers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the i th battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times . The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.", + "description_images": [], + "constraints": [ + "1 <= n <= batteries.length <= 10^5", + "1 <= batteries[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, batteries = [3,3,3]\nOutput:4\nExplanation:Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example1-fit.png" + }, + { + "text": "Example 2: Input:n = 2, batteries = [1,1,1,1]\nOutput:2\nExplanation:Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1321 ms (Top 44.04%) | Memory: 28.7 MB (Top 24.77%)\nclass Solution:\n def maxRunTime(self, n: int, batteries: List[int]) -> int:\n batteries.sort()\n total=sum(batteries)\n while batteries[-1]>total//n:\n n-=1\n total-=batteries.pop()\n return total//n", + "title": "2141. Maximum Running Time of N Computers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.", + "description_images": [], + "constraints": [ + "2 <= s.length <= 500", + "The string s consists of characters '0' and '1' only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011101\"\nOutput:5\nExplanation:All possible ways of splitting s into two non-empty substrings are:\nleft = \"0\" and right = \"11101\", score = 1 + 4 = 5 \nleft = \"01\" and right = \"1101\", score = 1 + 3 = 4 \nleft = \"011\" and right = \"101\", score = 1 + 2 = 3 \nleft = \"0111\" and right = \"01\", score = 1 + 1 = 2 \nleft = \"01110\" and right = \"1\", score = 2 + 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:s = \"00111\"\nOutput:5\nExplanation:When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 14.4%) | Memory: 44.28 MB (Top 5.7%)\n\nclass Solution {\n public int maxScore(String s) {\n int max =0;\n for(int i =0; i int:\n m0=0\n m1=0\n for i in s:\n if i==\"0\":\n m0+=1\n else:\n m1+=1\n if m0==0 or m1==0:\n return max(m0-1,m1-1)\n l=len(s)\n i=0\n max_=0\n c0=0\n c1=m1\n idx=-1\n while i = m . The arrays are 1-indexed . You begin with a score of 0 . You want to perform exactly m operations. On the i th operation (1-indexed) , you will: Return the maximum score after performing m operations.", + "description_images": [], + "constraints": [ + "Choose one integer x from either the start or the end of the array nums .", + "Add multipliers[i] * x to your score.", + "Remove x from the array nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], multipliers = [3,2,1]\nOutput:14\nExplanation:An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\nOutput:102\nExplanation:An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 360 ms (Top 22.12%) | Memory: 168.2 MB (Top 19.45%)\nclass Solution {\n public int maximumScore(int[] nums, int[] multipliers) {\n int n = nums.length, m = multipliers.length;\n return helper(nums, multipliers, 0, 0, n-1, new Integer[m][m]);\n }\n\n public int helper(int[] nums, int[] multipliers, int idx, int left, int right, Integer[][] memo){\n if(idx == multipliers.length) return 0;\n if(memo[idx][left] != null) return memo[idx][left];\n\n int takeLeft = nums[left] * multipliers[idx] +\n helper(nums, multipliers, idx + 1, left + 1, right, memo);\n\n int takeRight = nums[right] * multipliers[idx] +\n helper(nums, multipliers, idx + 1, left, right - 1, memo);\n\n return memo[idx][left] = Math.max(takeLeft, takeRight);\n }\n}", + "title": "1770. Maximum Score from Performing Multiplication Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m . The arrays are 1-indexed . You begin with a score of 0 . You want to perform exactly m operations. On the i th operation (1-indexed) , you will: Return the maximum score after performing m operations.", + "description_images": [], + "constraints": [ + "Choose one integer x from either the start or the end of the array nums .", + "Add multipliers[i] * x to your score.", + "Remove x from the array nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], multipliers = [3,2,1]\nOutput:14\nExplanation:An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\nOutput:102\nExplanation:An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n = len(nums)\n m = len(multipliers)\n \n @lru_cache(None)\n #To Save Computed Result\n \n def X(i, left):\n \n if i==m:\n return 0\n \n return max ( (multipliers[i] * nums[left]) + X(i + 1, left + 1), \n (multipliers[i] * nums[n-1-(i-left)]) + X(i + 1, left) ) \n \n #Start from Zero operations\n return X(0,0)\n", + "title": "1770. Maximum Score from Performing Multiplication Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are playing a solitaire game with three piles of stones of sizes a ​​​​​​, b ,​​​​​​ and c ​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a ​​​​​, b ,​​​​​ and c ​​​​​, return the maximum score you can get.", + "description_images": [], + "constraints": [ + "1 <= a, b, c <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 4, c = 6\nOutput:6\nExplanation:The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 4, c = 6\nOutput:7\nExplanation:The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 8, c = 8\nOutput:8\nExplanation:One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.30 MB (Top 77.67%)\n\nclass Solution {\n public int maximumScore(int a, int b, int c) {\n // Make sure a <= b <= c\n if (a>b) return maximumScore(b,a,c);\n if (b>c) return maximumScore(a,c,b);\n \n // if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c\n if (a+b<=c) return a+b;\n \n // if sum of smallest numbers is greater than c, then we can (a+b)/2 pairs after making c empty\n return c+(a+b-c)/2;\n }\n}\n", + "title": "1753. Maximum Score From Removing Stones", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a solitaire game with three piles of stones of sizes a ​​​​​​, b ,​​​​​​ and c ​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a ​​​​​, b ,​​​​​ and c ​​​​​, return the maximum score you can get.", + "description_images": [], + "constraints": [ + "1 <= a, b, c <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 4, c = 6\nOutput:6\nExplanation:The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 4, c = 6\nOutput:7\nExplanation:The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 8, c = 8\nOutput:8\nExplanation:One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted([a, b, c], reverse=True)\n ans = 0\n while a > 0 and b > 0:\n a -= 1\n b -= 1\n ans += 1\n a, b, c = sorted([a, b, c], reverse=True)\n return ans\n", + "title": "1753. Maximum Score From Removing Stones", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and two integers x and y . You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s .", + "description_images": [], + "constraints": [ + "Remove substring \"ab\" and gain x points. For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "Remove substring \"ba\" and gain y points. For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" .", + "For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput:19\nExplanation:- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumGain(String s, int x, int y) {\n \n int aCount = 0;\n int bCount = 0;\n int lesser = Math.min(x, y);\n int result = 0;\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c > 'b') {\n result += Math.min(aCount, bCount) * lesser;\n aCount = 0;\n bCount = 0;\n } else if (c == 'a') {\n if (x < y && bCount > 0) {\n bCount--;\n result += y;\n } else {\n aCount++;\n }\n } else {\n if (x > y && aCount > 0) {\n aCount--;\n result += x;\n } else {\n bCount++;\n };\n }\n }\n \n result += Math.min(aCount, bCount) * lesser;\n \n return result;\n }\n}\n", + "title": "1717. Maximum Score From Removing Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s and two integers x and y . You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s .", + "description_images": [], + "constraints": [ + "Remove substring \"ab\" and gain x points. For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "Remove substring \"ba\" and gain y points. For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" .", + "For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput:19\nExplanation:- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n a = 'a'\n b = 'b'\n if x < y:\n x, y = y, x\n a, b = b, a\n seen = Counter()\n ans = 0\n for c in s + 'x':\n if c in 'ab':\n if c == b and 0 < seen[a]:\n ans += x\n seen[a] -= 1\n else:\n seen[c] += 1\n else:\n ans += y * min(seen[a], seen[b])\n seen = Counter()\n\n return ans\n", + "title": "1717. Maximum Score From Removing Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers nums (0-indexed) and an integer k . The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1) . A good subarray is a subarray where i <= k <= j . Return the maximum possible score of a good subarray.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 2 * 10^4", + "0 <= k < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,7,4,5], k = 3\nOutput:15\nExplanation:The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,5,4,5,4,1,1,1], k = 0\nOutput:20\nExplanation:The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 75.40%) | Memory: 51.5 MB (Top 97.59%)\nclass Solution {\n public int maximumScore(int[] nums, int k) {\n int n = nums.length;\n int i = k - 1, j = k + 1;\n int min = nums[k];\n int ans = min;\n\n while(i >= 0 || j < n) {\n int v1 = 0, v2 = 0;\n int min1 = min, min2 = min;\n\n if(i >= 0) {\n min1 = Math.min(min, nums[i]);\n v1 = min1 * (j - i);\n }\n\n if(j < n) {\n min2 = Math.min(min, nums[j]);\n v2 = min2 * (j - i);\n }\n\n if(v1 > v2) {\n --i;\n ans = Math.max(v1, ans);\n min = Math.min(min1, min);\n }\n else {\n ++j;\n ans = Math.max(ans, v2);\n min = Math.min(min, min2);\n }\n }\n\n return ans;\n }\n}", + "title": "1793. Maximum Score of a Good Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of integers nums (0-indexed) and an integer k . The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1) . A good subarray is a subarray where i <= k <= j . Return the maximum possible score of a good subarray.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 2 * 10^4", + "0 <= k < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,7,4,5], k = 3\nOutput:15\nExplanation:The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,5,4,5,4,1,1,1], k = 0\nOutput:20\nExplanation:The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextSmallerElement(self, nums):\n nextSmaller = [None] * len(nums)\n stack = [[-sys.maxsize, -1]]\n for i in range(len(nums)-1, -1, -1):\n while nums[i] <= stack[-1][0]:\n stack.pop()\n nextSmaller[i] = stack[-1][1]\n stack.append([nums[i], i])\n return nextSmaller\n \n \n def previousSmallerElement(self, nums):\n previousSmaller = [None] * len(nums)\n stack = [[-sys.maxsize, -1]]\n for i in range(len(nums)):\n while nums[i] <= stack[-1][0]:\n stack.pop()\n previousSmaller[i] = stack[-1][1]\n stack.append([nums[i], i])\n return previousSmaller\n \n def maximumScore(self, nums: List[int], k: int) -> int:\n nextSmaller = self.nextSmallerElement(nums)\n previousSmaller = self.previousSmallerElement(nums)\n\n score = 0\n for idx, num in enumerate(nums):\n\t\t\t# previousSmaller[idx] (let's say i) and nextSmaller[idx] (let's say j) ensures that the element present at idx is the minimum in range (i -> j)\n i = previousSmaller[idx]\n i += 1\n j = nextSmaller[idx]\n if j == -1:\n j = len(nums)\n j -= 1\n if i <= k <= j:\n score = max(score, num * (j-i+1))\n \n return score\n \n", + "title": "1793. Maximum Score of a Good Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i . You are also given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . A node sequence is valid if it meets the following conditions: The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4 . If no such sequence exists, return -1 .", + "description_images": [], + "constraints": [ + "There is an edge connecting every pair of adjacent nodes in the sequence.", + "No node appears more than once in the sequence." + ], + "examples": [ + { + "text": "Example 1: Input:scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput:24\nExplanation:The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.", + "image": "https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" + }, + { + "text": "Example 2: Input:scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]\nOutput:-1\nExplanation:The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.", + "image": "https://assets.leetcode.com/uploads/2022/03/17/ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 99.80%) | Memory: 131.6 MB (Top 18.36%)\nclass Solution {\n public int maximumScore(int[] scores, int[][] edges) {\n int n = scores.length;\n\n int[][] count = new int[n][6];\n for (int[] edge : edges) {\n int s = edge[0];\n int e = edge[1];\n if (count[s][0] == 0) {\n count[s][1] = e;\n count[s][0] = scores[e];\n } else if (count[s][2] == 0) {\n if (scores[e] > count[s][0]) {\n count[s][3] = count[s][1];\n count[s][2] = count[s][0];\n count[s][1] = e;\n count[s][0] = scores[e];\n } else {\n count[s][3] = e;\n count[s][2] = scores[e];\n }\n } else if (scores[e] > count[s][4]) {\n if (scores[e] > count[s][0]) {\n count[s][5] = count[s][3];\n count[s][4] = count[s][2];\n count[s][3] = count[s][1];\n count[s][2] = count[s][0];\n count[s][1] = e;\n count[s][0] = scores[e];\n } else if (scores[e] > count[s][2]) {\n count[s][5] = count[s][3];\n count[s][4] = count[s][2];\n count[s][3] = e;\n count[s][2] = scores[e];\n } else {\n count[s][5] = e;\n count[s][4] = scores[e];\n }\n }\n if (count[e][0] == 0) {\n count[e][1] = s;\n count[e][0] = scores[s];\n } else if (count[e][2] == 0) {\n if (scores[s] > count[e][0]) {\n count[e][3] = count[e][1];\n count[e][2] = count[e][0];\n count[e][1] = s;\n count[e][0] = scores[s];\n } else {\n count[e][3] = s;\n count[e][2] = scores[s];\n }\n } else if (scores[s] > count[e][4]) {\n if (scores[s] > count[e][0]) {\n count[e][5] = count[e][3];\n count[e][4] = count[e][2];\n count[e][3] = count[e][1];\n count[e][2] = count[e][0];\n count[e][1] = s;\n count[e][0] = scores[s];\n } else if (scores[s] > count[e][2]) {\n count[e][5] = count[e][3];\n count[e][4] = count[e][2];\n count[e][3] = s;\n count[e][2] = scores[s];\n } else {\n count[e][5] = s;\n count[e][4] = scores[s];\n }\n }\n }\n int max = -1;\n for (int[] edge : edges) {\n int s = edge[0];\n int e = edge[1];\n int pos = scores[s] + scores[e];\n int p1 = -1;\n int p2 = -1;\n boolean fine = true;\n if (count[s][1] == e) {\n if (count[s][2] == 0)\n fine = false;\n p1 = count[s][3];\n if (count[s][4] > 0)\n p2 = count[s][5];\n } else if (count[s][3] == e) {\n if (count[s][0] == 0)\n fine = false;\n p1 = count[s][1];\n if (count[s][4] > 0)\n p2 = count[s][5];\n } else {\n p1 = count[s][1];\n if (count[s][0] == 0)\n fine = false;\n if (count[s][2] > 0)\n p2 = count[s][3];\n }\n int p3 = -1;\n int p4 = -1;\n if (count[e][1] == s) {\n if (count[e][2] == 0)\n fine = false;\n p3 = count[e][3];\n if (count[e][4] > 0)\n p4 = count[e][5];\n } else if (count[e][3] == s) {\n if (count[e][0] == 0)\n fine = false;\n p3 = count[e][1];\n if (count[e][4] > 0)\n p4 = count[e][5];\n } else {\n p3 = count[e][1];\n if (count[e][0] == 0)\n fine = false;\n if (count[e][2] > 0)\n p4 = count[e][3];\n }\n if (fine) {\n if (p1 == p3) {\n if (p4 > -1)\n max = Math.max(max, pos + scores[p1] + scores[p4]);\n if (p2 > -1)\n max = Math.max(max, pos + scores[p1] + scores[p2]);\n } else {\n max = Math.max(max, pos + scores[p1] + scores[p3]);\n }\n }\n }\n return max;\n }\n}", + "title": "2242. Maximum Score of a Node Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i . You are also given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . A node sequence is valid if it meets the following conditions: The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4 . If no such sequence exists, return -1 .", + "description_images": [], + "constraints": [ + "There is an edge connecting every pair of adjacent nodes in the sequence.", + "No node appears more than once in the sequence." + ], + "examples": [ + { + "text": "Example 1: Input:scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput:24\nExplanation:The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.", + "image": "https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" + }, + { + "text": "Example 2: Input:scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]\nOutput:-1\nExplanation:The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.", + "image": "https://assets.leetcode.com/uploads/2022/03/17/ex2.png" + } + ], + "follow_up": null, + "solution": "# defaultdict is the same as Python's usual dictionary, but if an\n# element doesn't exist, you can give it a default value to initialize with. \nfrom collections import defaultdict\n# nlargest(n, l) - returns the n largest values of collection l.\nfrom heapq import nlargest\n# \"product\" is a function that takes two collections and \n# returns every pair between them.\n# product(\"ab\", \"cd\") = [(a, c), (a, d), (b, c), (b, d)].\nfrom itertools import product\n\nLet V be the number of nodes and E = len(edges).\n# Time complexity: O(V + E) - we iterate through every vertex \n# and every edge a constant number of times.\n# Space complexity: O(V) - we save a constant \n# number of neighbors (3) for every node.\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n # Turn the edge list into an adjacency graph.\n m = defaultdict(list)\n for u, v in edges:\n m[u].append((scores[v], v)) \n m[v].append((scores[u], u))\n \n # Cut down all neighbors of each node to the three\n # that have the highest value.\n for u in m:\n m[u] = nlargest(3, m[u])\n\n ret = -1\n # Consider each edge to potentially be (B, C) for a quadruplet.\n for b, c in edges:\n # For every possible A and D in the neighbors of B and C...\n for (aWeight, a), (dWeight, d) in product(m[b], m[c]):\n # ... If we have no redundant nodes, it's a quadruplet.\n # Since it's the highest value quadruplet we could\n # possibly make with B and C, this solution is always accurate.\n if a not in [b, c] and d not in [b, c] and a != d:\n ret = max(ret, scores[b] + scores[c] + aWeight + dWeight)\n \n return ret\n", + "title": "2242. Maximum Score of a Node Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 , both of length n . You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right] . You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2) , where sum(arr) is the sum of all the elements in the array arr . Return the maximum possible score . A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ).", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2 , nums1 becomes [1, 12,13 ,4,5] and nums2 becomes [11, 2,3 ,14,15] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [60,60,60], nums2 = [10,90,10]\nOutput:210\nExplanation:Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]\nOutput:220\nExplanation:Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,11,13], nums2 = [1,1,1]\nOutput:31\nExplanation:We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maximumsSplicedArray(int[] nums1, int[] nums2) {\n int ans = 0, sum1 = 0, sum2 = 0;\n\n for (int i : nums1) sum1 += i;\n for (int i : nums2) sum2 += i;\n\n ans = Math.max(sum1, sum2);\n\n int first = 0, second = 0, max1 = 0, max2 = 0;\n\n for (int i = 0; i < nums1.length; i++) {\n first += (nums2[i] - nums1[i]);\n second += (nums1[i] - nums2[i]);\n \n max1 = Math.max(max1, first);\n max2 = Math.max(max2, second);\n \n if (first < 0) first = 0;\n if (second < 0) second = 0;\n }\n\n ans = Math.max(ans, sum1 + max1);\n ans = Math.max(ans, sum2 + max2);\n\n return ans;\n }\n}\n", + "title": "2321. Maximum Score Of Spliced Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 , both of length n . You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right] . You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2) , where sum(arr) is the sum of all the elements in the array arr . Return the maximum possible score . A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ).", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2 , nums1 becomes [1, 12,13 ,4,5] and nums2 becomes [11, 2,3 ,14,15] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [60,60,60], nums2 = [10,90,10]\nOutput:210\nExplanation:Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]\nOutput:220\nExplanation:Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,11,13], nums2 = [1,1,1]\nOutput:31\nExplanation:We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n\t\tnums3 = [0]*n\n\t\tnums4 = [0]*n\n\t\tfor i in range(n):\n\t\t\tnums3[i] = nums1[i]-nums2[i]\n\t\t\tnums4[i] = nums2[i]-nums1[i]\n\t\tmaxsubseq1 = maxsubseq2 = 0\n\t\tv1 = v2 = 0 \n\t\t# use kadane algorithm to solve this max subseq problem\n\t\tfor i in range(n):\n\t\t\tmaxsubseq1 = max(maxsubseq1 + nums3[i], nums3[i])\n\t\t\tmaxsubseq2 = max(maxsubseq2 + nums4[i], nums4[i])\n\t\t\tv1 = max(v1, maxsubseq1)\n\t\t\tv2 = max(v2, maxsubseq2)\n\t\t_sum1 = sum(nums1)\n\t\t_sum2 = sum(nums2)\n\t\treturn max(_sum1 + v2, _sum2 + v1)\n", + "title": "2321. Maximum Score Of Spliced Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of words , list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters ( words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a' , 'b' , 'c' , ... , 'z' is given by score[0] , score[1] , ... , score[25] respectively.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 14", + "1 <= words[i].length <= 15", + "1 <= letters.length <= 100", + "letters[i].length == 1", + "score.length == 26", + "0 <= score[i] <= 10", + "words[i] , letters[i] contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput:23\nExplanation:Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput:27\nExplanation:Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput:0\nExplanation:Letter \"e\" can only be used once.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 32.14%) | Memory: 44.3 MB (Top 16.39%)\nclass Solution {\n int[] memo;\n public int maxScoreWords(String[] words, char[] letters, int[] score) {\n memo = new int[words.length];\n Arrays.fill(memo,-1);\n HashMap hm = new HashMap<>();\n for(char c : letters){\n int t = hm.getOrDefault(c,0);\n t++;\n hm.put(c,t);\n }\n //return dp(words,hm,score,0,0);\n int res = dp(words,hm,score,0,0);\n //for(int i : memo) System.out.println(i);\n return res;\n }\n\n public int dp(String[] words, Map hm, int[] score, int index, int cs){//cs-current Score\n if(index==words.length) return cs;\n if(memo[index]!=-1) return memo[index];\n HashMap temp = new HashMap<>(hm);\n int tcs=cs; //tcs = temporory current score\n\n for(char c : words[index].toCharArray()){\n int t = temp.getOrDefault(c,0);\n t--;\n if(t<0){\n return dp(words,hm,score,index+1,cs);\n // memo[index] = dp(words,hm,score,index+1,cs);\n // return memo[index];\n }\n tcs+=score[c-'a'];\n temp.put(c,t);\n }\n return Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // memo[index] = Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // return memo[index];\n }\n}", + "title": "1255. Maximum Score Words Formed by Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a list of words , list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters ( words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a' , 'b' , 'c' , ... , 'z' is given by score[0] , score[1] , ... , score[25] respectively.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 14", + "1 <= words[i].length <= 15", + "1 <= letters.length <= 100", + "letters[i].length == 1", + "score.length == 26", + "0 <= score[i] <= 10", + "words[i] , letters[i] contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput:23\nExplanation:Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput:27\nExplanation:Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput:0\nExplanation:Letter \"e\" can only be used once.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 61 ms (Top 55.33%) | Memory: 17.40 MB (Top 11.89%)\n\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n\n f, ans = lambda x : sum(score[ord(c) - 97] for c in x), 0\n\n def dfs(words,letters, tally):\n nonlocal ans\n \n for i in range(len(words)):\n cWord=Counter(words[i])\n\t\t\t\t\n if all(letters[c] >= cWord[c] for c in cWord):\n dfs(words[i+1:], letters - cWord, tally + f(words[i]))\n\n ans = max(ans,tally)\n return ans\n\n return dfs(words, Counter(letters), 0)\n", + "title": "1255. Maximum Score Words Formed by Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a m x n matrix mat and an integer threshold , return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 300", + "0 <= mat[i][j] <= 10^4", + "0 <= threshold <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput:2\nExplanation:The maximum side length of square with sum less than 4 is 2 as shown.", + "image": "https://assets.leetcode.com/uploads/2019/12/05/e1.png" + }, + { + "text": "Example 2: Input:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSideLength(int[][] mat, int threshold) {\n int rows = mat.length;\n int cols = mat[0].length;\n int[][] preSum = new int[rows+1][cols+1];\n for(int i=1;i<=rows;i++){\n for(int j=1;j<=cols;j++){\n preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + mat[i-1][j-1];\n }\n }\n int lo=1,hi=Math.min(rows,cols);\n while(lo<=hi){\n int m = (lo+hi)>>1;\n if(fun(preSum,threshold,rows,cols,m)) lo=m+1;\n else hi=m-1;\n }\n return lo-1;\n }\n private boolean fun(int[][] preSum, int maxSum,int rows, int cols, int size){\n for(int r=size;r<=rows;r++){\n for(int c=size;c<=cols;c++){\n int sum = preSum[r][c] - preSum[r-size][c] - preSum[r][c-size] + preSum[r-size][c-size];\n if(sum <= maxSum) return true;\n }\n }\n return false;\n }\n}\n", + "title": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a m x n matrix mat and an integer threshold , return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 300", + "0 <= mat[i][j] <= 10^4", + "0 <= threshold <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput:2\nExplanation:The maximum side length of square with sum less than 4 is 2 as shown.", + "image": "https://assets.leetcode.com/uploads/2019/12/05/e1.png" + }, + { + "text": "Example 2: Input:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n # prefix matrix\n dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)]\n \n for i in range(1, len(mat)+1):\n for j in range(1, len(mat[0])+1):\n dp[i][j] = dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1] + mat[i-1][j-1]\n \n #bin search\n max_side = 0\n for i in range(1, len(mat) + 1):\n for j in range(1, len(mat[0]) + 1):\n if min(i, j) < max_side:\n continue\n left = 0\n right = min(i,j)\n while left <= right:\n mid = (left+right)//2\n pref_sum = dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid]\n if pref_sum <= threshold:\n max_side = max(max_side, mid)\n left = mid + 1\n else:\n right = mid - 1\n return max_side\n \n", + "title": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer finalSum . Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers . If no valid split exists for finalSum , return an empty list . You may return the integers in any order.", + "description_images": [], + "constraints": [ + "For example, given finalSum = 12 , the following splits are valid (unique positive even integers summing up to finalSum ): (12) , (2 + 10) , (2 + 4 + 6) , and (4 + 8) . Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique." + ], + "examples": [ + { + "text": "Example 1: Input:finalSum = 12\nOutput:[2,4,6]\nExplanation:The following are valid splits:(12),(2 + 10),(2 + 4 + 6), and(4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.", + "image": null + }, + { + "text": "Example 2: Input:finalSum = 7\nOutput:[]\nExplanation:There are no valid splits for the given finalSum.\nThus, we return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:finalSum = 28\nOutput:[6,8,2,12]\nExplanation:The following are valid splits:(2 + 26),(6 + 8 + 2 + 12), and(4 + 24).(6 + 8 + 2 + 12)has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List maximumEvenSplit(long finalSum) {\n List res = new ArrayList();\n //odd sum cannot be divided into even numbers\n if(finalSum % 2 != 0) {\n return res;\n }\n //Greedy approach, try to build the total sum using minimum unique even nos\n long currNum = 2;\n long remainingSum = finalSum;\n //as long as we can add subtract this number from remaining sum\n while(currNum <= remainingSum) {\n res.add(currNum);\n remainingSum -= currNum;//reducing remaining sum\n currNum += 2;//next even number\n }\n //now, remaining sum cannot be fulfilled by any larger even number\n //so extract the largest even number we added to the last index of res, and make it even larger by adding this current remaining sum\n //add remaining sum to the last element\n long last = res.remove(res.size()-1);\n res.add(last+remainingSum);\n return res;\n }\n}\n", + "title": "2178. Maximum Split of Positive Even Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer finalSum . Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers . If no valid split exists for finalSum , return an empty list . You may return the integers in any order.", + "description_images": [], + "constraints": [ + "For example, given finalSum = 12 , the following splits are valid (unique positive even integers summing up to finalSum ): (12) , (2 + 10) , (2 + 4 + 6) , and (4 + 8) . Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique." + ], + "examples": [ + { + "text": "Example 1: Input:finalSum = 12\nOutput:[2,4,6]\nExplanation:The following are valid splits:(12),(2 + 10),(2 + 4 + 6), and(4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.", + "image": null + }, + { + "text": "Example 2: Input:finalSum = 7\nOutput:[]\nExplanation:There are no valid splits for the given finalSum.\nThus, we return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:finalSum = 28\nOutput:[6,8,2,12]\nExplanation:The following are valid splits:(2 + 26),(6 + 8 + 2 + 12), and(4 + 24).(6 + 8 + 2 + 12)has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1817 ms (Top 5.05%) | Memory: 26.8 MB (Top 41.50%)\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n l=[]\n if finalSum%2!=0:\n return l\n else:\n s=0\n i=2 # even pointer 2, 4, 6, 8, 10, 12...........\n while(s> 1);\n ans = Math.max(ans, cnt + dfs(nxt, i + 1));\n }\n }\n return f[seat][i] = ans;\n }\n}", + "title": "1349. Maximum Students Taking Exam", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition.", + "description_images": [], + "constraints": [ + "seats contains only characters '.' and '#'.", + "m == seats.length", + "n == seats[i].length", + "1 <= m <= 8", + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n  [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n  [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\nOutput:4\nExplanation:Teacher can place 4 students in available seats so they don't cheat on the exam.", + "image": "https://assets.leetcode.com/uploads/2020/01/29/image.png" + }, + { + "text": "Example 2: Input:seats = [[\".\",\"#\"],\n  [\"#\",\"#\"],\n  [\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\".\",\"#\"]]\nOutput:3\nExplanation:Place all students in available seats.", + "image": null + }, + { + "text": "Example 3: Input:seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\".\",\".\",\"#\",\".\",\".\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\"#\",\".\",\".\",\".\",\"#\"]]\nOutput:10\nExplanation:Place students in available seats in column 1, 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n m, n = len(seats), len(seats[0])\n match = [[-1]*n for _ in range(m)]\n def dfs(i, j, visited):\n for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]:\n if 0 <= x < m and 0 <= y < n and seats[x][y] == \".\" and (x, y) not in visited:\n visited.add((x, y))\n if match[x][y] == -1 or dfs(*match[x][y], visited):\n match[x][y] = (i, j)\n match[i][j] = (x, y)\n return True\n return False\n def max_matching():\n cnt = 0\n for i in range(m):\n for j in range(0,n,2):\n if seats[i][j] == '.' and match[i][j] == -1:\n visited = set()\n cnt += dfs(i, j, visited)\n return cnt\n\t\t#returns the number of elements of the maximum independent set in the bipartite set\n return sum(seats[i][j]=='.' for i in range(m) for j in range(n)) - max_matching()", + "title": "1349. Maximum Students Taking Exam", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find the contiguous subarray (containing at least one number) which has the largest sum and return its sum . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput:6\nExplanation:[4,-1,2,1] has the largest sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,4,-1,7,8]\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubArray(int[] nums) {\n int n = nums.length;\n int currmax = 0;\n int gmax = nums[0];\n for(int i=0;i int:\n def kadane(i):\n if F[i] != None:\n return F[i]\n F[i] = max(nums[i],kadane(i-1) + nums[i])\n return F[i]\n n = len(nums)\n F = [None for _ in range(n)]\n F[0] = nums[0]\n kadane(n-1)\n return max(F)", + "title": "53. Maximum Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The min-product of an array is equal to the minimum value in the array multiplied by the array's sum . Given an array of integers nums , return the maximum min-product of any non-empty subarray of nums . Since the answer may be large, return it modulo 10^9 + 7 . Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "For example, the array [3,2,5] (minimum value is 2 ) has a min-product of 2 * (3+2+5) = 2 * 10 = 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,2]\nOutput:14\nExplanation:The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,3,1,2]\nOutput:18\nExplanation:The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,1,5,6,4,2]\nOutput:60\nExplanation:The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSumMinProduct(int[] nums) {\n int mod=(int)Math.pow(10,9)+7;\n int n=nums.length;\n \n //next smaller on left\n int[] left=new int[n];\n Stack st=new Stack<>();\n left[0]=-1;\n st.push(0);\n for(int i=1;i0 && nums[st.peek()]>=nums[i]){\n st.pop();\n }\n \n if(st.size()==0) left[i]=-1;\n else left[i]=st.peek();\n \n st.push(i);\n }\n \n //next smaller on right\n int[] right=new int[n];\n st=new Stack<>();\n right[n-1]=n;\n st.push(n-1);\n for(int i=n-2;i>=0;i--){\n while(st.size()>0 && nums[st.peek()]>=nums[i]) st.pop();\n \n if(st.size()>0) right[i]=st.peek();\n else right[i]=n;\n \n st.push(i);\n }\n \n long[] prefixSum=new long[n];\n prefixSum[0]=nums[0];\n for(int i=1;i= 0; j--){\n leftPrefixSum = Math.max(leftPrefixSum, prefixSum[i-1] -prefixSum[j]);\n }\n \n int rightPrefixSum = 0;\n // find max in i to n\n for(int j = i+1; j <= n; j++){\n rightPrefixSum = Math.max(rightPrefixSum, prefixSum[j] -prefixSum[i]);\n } \n ans = Math.max(ans, leftPrefixSum + rightPrefixSum);\n }\n }\n return Math.max(ans, prefixSum[n]);\n }\n}\n", + "title": "1186. Maximum Subarray Sum with One Deletion", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,-2,0,3]\nOutput:4\nExplanation:Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,-2,3]\nOutput:3\nExplanation:We just choose [3] and it's the maximum sum.", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-1,-1,-1]\nOutput:-1\nExplanation:The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSum(self, arr: List[int]) -> int:\n n = len(arr)\n if n ==1:\n return arr[0]\n dpLeft = [-10**4-1 for _ in range(n)]\n dpLeft[0] = arr[0]\n i = 1 \n while i < n :\n dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])\n i += 1\n dpRight = [-10**4-1 for _ in range(n)]\n dpRight[-1] = arr[-1]\n j = n-2 \n while j >= 0:\n dpRight[j] = max(arr[j],dpRight[j+1]+arr[j])\n j -= 1\n k = 0\n maxi = -10**4-1\n while k < n:\n # if we take it \n curr_maxi_with = dpRight[k] + dpLeft[k] - arr[k]\n \n if k==0:\n curr_maxi_without = dpRight[k+1]\n elif k==n-1:\n curr_maxi_without = dpLeft[k-1]\n else:\n if dpLeft[k-1]>=0 and dpRight[k+1]>=0:\n curr_maxi_without = dpRight[k+1] + dpLeft[k-1]\n else:\n curr_maxi_without = max(dpLeft[k-1],dpRight[k+1])\n \n maxi= max(maxi,curr_maxi_without, curr_maxi_with)\n k += 1\n \n return maxi \n\n", + "title": "1186. Maximum Subarray Sum with One Deletion", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree root , return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST) . Assume a BST is defined as follows:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png", + "https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" + ], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput:20\nExplanation:Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:root = [4,3,null,1,2]\nOutput:2\nExplanation:Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.", + "image": null + }, + { + "text": "Example 3: Input:root = [-4,-2,-5]\nOutput:0\nExplanation:All values are negatives. Return an empty BST.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 57.67%) | Memory: 71 MB (Top 82.51%)\nclass Solution {\n\n int ans = 0;\n public int maxSumBST(TreeNode root) {\n solve(root);\n return ans;\n }\n // int[] = { min, max, sum };\n private int[] solve(TreeNode root) {\n if(root == null)\n return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 };\n\n int[] left = solve(root.left);\n int[] right = solve(root.right);\n\n if(root.val > left[1] && root.val < right[0]) {\n int sum = left[2] + right[2] + root.val;\n ans = Math.max(ans, sum);\n return new int[] { Math.min(left[0], root.val), Math.max(root.val, right[1]), sum };\n }\n\n return new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };\n }\n\n}", + "title": "1373. Maximum Sum BST in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root , return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST) . Assume a BST is defined as follows:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png", + "https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" + ], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput:20\nExplanation:Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:root = [4,3,null,1,2]\nOutput:2\nExplanation:Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.", + "image": null + }, + { + "text": "Example 3: Input:root = [-4,-2,-5]\nOutput:0\nExplanation:All values are negatives. Return an empty BST.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 22.49%) | Memory: 35.50 MB (Top 99.31%)\n\nclass Solution:\n def maxSumBST(self, root: TreeNode) -> int:\n res = 0\n def traverse(root):\n '''return status_of_bst, size_of_bst, left_bound, right_bound'''\n nonlocal res\n if not root: return 1, 0, None, None # this subtree is empty\n \n ls, l, ll, lr = traverse(root.left)\n rs, r, rl, rr = traverse(root.right)\n \n if ((ls == 2 and lr < root.val) or ls == 1) and ((rs == 2 and rl > root.val) or rs == 1):\n\t\t # this subtree is a BST\n size = root.val + l + r\n res = max(res, size)\n return 2, size, (ll if ll is not None else root.val), (rr if rr is not None else root.val)\n return 0, None, None, None # this subtree is not a BST\n \n traverse(root)\n return res\n", + "title": "1373. Maximum Sum BST in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]\nOutput:3\nExplanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]\nOutput:10\nExplanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]\nOutput:-2\nExplanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 96.02%) | Memory: 64.4 MB (Top 41.15%)\nclass Solution {\n public int maxSubarraySumCircular(int[] nums) {\n int ans = kadane(nums);\n int sum = 0;\n for (int i = 0; i < nums.length; i++) {\n sum += nums[i];\n nums[i] = -nums[i];\n }\n int kadane_sum = kadane(nums) + sum;\n if (kadane_sum == 0) {\n return ans;\n }\n return Math.max(ans, kadane_sum);\n }\n public int kadane(int[] nums) {\n int sum = 0;\n int ans = Integer.MIN_VALUE;\n for (int i : nums) {\n sum += i;\n ans = Math.max(ans, sum);\n if (sum < 0) {\n sum = 0;\n }\n }\n return ans;\n }\n}", + "title": "918. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]\nOutput:3\nExplanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]\nOutput:10\nExplanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]\nOutput:-2\nExplanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 729 ms (Top 66.43%) | Memory: 18.9 MB (Top 76.46%)\nclass Solution:\n\n def kadanes(self,nums):\n\n #kadanes algo\n\n max_till_now = nums[0]\n curr_max = nums[0]\n\n for i in range(1,len(nums)):\n curr_max = max(curr_max+nums[i],nums[i])\n max_till_now = max(max_till_now,curr_max)\n\n return max_till_now\n\n def maxSubarraySumCircular(self, nums: List[int]) -> int:\n\n #there will be 2 case\n #case 1 : our max subarray is not wrapping i.e not circular\n #case 2: our max subarray is wrapping i.e circular\n\n # case 1 is easy to find\n # to find case 2 what we can do is if we multiply each nums element by -1 and\n # on that find kadanes then we will get sum of elements which is not part of maxsubarray in case2 (not part because we negate)\n # now subtract this newmax in case 2 from total nums sum, we get wrapping sum\n # max of case1 and case is our ans\n\n total = sum(nums)\n\n nonwrappingsum = self.kadanes(nums)\n\n # edge case when all elements are -ve then return max negative\n if nonwrappingsum<0:\n return nonwrappingsum\n\n #negate\n for i in range(len(nums)):\n nums[i]*=-1\n\n wrappingsum = total-(-self.kadanes(nums)) #-ve because originally it was negated\n\n return max(nonwrappingsum,wrappingsum)\n", + "title": "918. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have an array of integers, nums , and an array of requests where requests[i] = [start i , end i ] . The i th request asks for the sum of nums[start i ] + nums[start i + 1] + ... + nums[end i - 1] + nums[end i ] . Both start i and end i are 0-indexed . Return the maximum total sum of all requests among all permutations of nums . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "0 <= nums[i] <= 10^5", + "1 <= requests.length <= 10^5", + "requests[i].length == 2", + "0 <= start i <= end i < n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput:19\nExplanation:One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput:11\nExplanation:A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput:47\nExplanation:A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 87 ms (Top 13.18%) | Memory: 134 MB (Top 44.96%)\nclass Solution {\n public int maxSumRangeQuery(int[] nums, int[][] requests) {\n int n = nums.length;\n int[] pref = new int[n];\n for(int i=0;i nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput:11\nExplanation:A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput:47\nExplanation:A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1436 ms (Top 61.0%) | Memory: 50.25 MB (Top 70.4%)\n\nclass Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n count = [0] * len(nums)\n for i, j in requests:\n count[i] += 1\n if j + 1 < len(count):\n count[j+1] -= 1\n cur = 0\n for i in range(len(count)):\n count[i] += cur\n cur = count[i]\n return sum(n * c for n, c in zip(sorted(nums, reverse=True), sorted(count, reverse=True))) % (10 ** 9 + 7)", + "title": "1589. Maximum Sum Obtained of Any Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval ( 0-indexed ). If there are multiple answers, return the lexicographically smallest one.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] < 2 16", + "1 <= k <= floor(nums.length / 3)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,6,7,5,1], k = 2\nOutput:[0,3,5]\nExplanation:Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput:[0,2,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSumOfThreeSubarrays(int[] nums, int k) {\n int n = nums.length;\n int[] ans = new int[3];\n int[] pre = new int[n];\n int[] third = new int[n];\n for (int i=0;i=2*k;--i){ // find the best index for the last part\n int cur = pre[i+k-1]-pre[i-1];\n max=Math.max(max, cur);\n third[i]=cur==max?i:third[i+1];\n }\n for (int i=k,first=0,fmax=0,max=0;i+2*k-1 fmax){ // compute the best index for the first part on the fly\n fmax=cur;\n first=i-k;\n }\n int a = fmax; // first\n int b = pre[i+k-1]-pre[i-1]; // middle\n int c = pre[third[i+k]+k-1]-pre[third[i+k]-1]; // last\n if (a+b+c>max){\n max=a+b+c;\n ans[0]=first;\n ans[1]=i;\n ans[2]=third[i+k];\n }\n }\n return ans;\n }\n}\n", + "title": "689. Maximum Sum of 3 Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval ( 0-indexed ). If there are multiple answers, return the lexicographically smallest one.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] < 2 16", + "1 <= k <= floor(nums.length / 3)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,6,7,5,1], k = 2\nOutput:[0,3,5]\nExplanation:Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput:[0,2,4]", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\nfrom functools import lru_cache\n\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n n = len(nums)\n windows = list(accumulate(nums))\n windows = [windows[i+k-1]-(windows[i-1] if i>0 else 0) for i in range(len(windows)-k+1)]\n \n @lru_cache(None)\n def dfs(i, t):\n if t == 0:\n return 0, []\n if i >= len(windows):\n return float('-inf'), []\n cost1, sol1 = dfs(i+k, t-1)\n cost2, sol2 = dfs(i+1, t)\n if windows[i] + cost1 < cost2:\n return cost2, sol2\n return windows[i] + cost1, [i]+sol1\n return dfs(0, 3)[1]", + "title": "689. Maximum Sum of 3 Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and two integers firstLen and secondLen , return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen . The array with length firstLen could occur before or after the array with length secondLen , but they have to be non-overlapping. A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= firstLen, secondLen <= 1000", + "2 <= firstLen + secondLen <= 1000", + "firstLen + secondLen <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput:20\nExplanation:One choice of subarrays is [9] with length 1, and [6,5] with length 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput:29\nExplanation:One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput:31\nExplanation:One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {\n int []dp1=new int[nums.length];\n int []dp2=new int[nums.length];\n \n int sum=0;\n for(int i=0;i=0;i--){\n if(i+secondLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+secondLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n int max=0;\n \n for(int i=firstLen-1;i=0;i--){\n if(i+firstLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+firstLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n max=0;\n \n for(int i=secondLen-1;i int:\n n = len(nums)\n p = [0]\n for el in nums:\n p.append(p[-1] + el)\n msum = 0\n for f, s in [(firstLen, secondLen), (secondLen, firstLen)]:\n for i in range(f - 1, n - s + 1):\n for j in range(i + 1, n - s + 1):\n l = p[i + 1] - p[i - f + 1]\n r = p[j + s] - p[j]\n msum = max(msum, l + r)\n return msum\n", + "title": "1031. Maximum Sum of Two Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer num . You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get .", + "description_images": [], + "constraints": [ + "0 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 2736\nOutput:7236\nExplanation:Swap the number 2 and the number 7.", + "image": null + }, + { + "text": "Example 2: Input:num = 9973\nOutput:9973\nExplanation:No swap.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.26%) | Memory: 41.4 MB (Top 23.64%)\nclass Solution {\n public int maximumSwap(int num) {\n char str[]=String.valueOf(num).toCharArray();\n char arr[]=str.clone();\n Arrays.sort(arr);\n int i=0;\n int j=str.length-1;\n while(i=0 && arr[j]==str[i]){i++;j--;}\n int search=j;\n if(i==str.length) return num;\n j=str.length-1;\n while(arr[search]!=str[j]){j--;}\n\n char c=str[i];\n str[i]=str[j];\n str[j]=c;\n return Integer.parseInt(new String(str));\n }\n}", + "title": "670. Maximum Swap", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer num . You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get .", + "description_images": [], + "constraints": [ + "0 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 2736\nOutput:7236\nExplanation:Swap the number 2 and the number 7.", + "image": null + }, + { + "text": "Example 2: Input:num = 9973\nOutput:9973\nExplanation:No swap.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSwap(self, num: int) -> int:\n digits = [int(x) for x in str(num)]\n n = len(digits)\n \n for i in range(n):\n maxx = digits[i]\n indx = i\n \n for j in range(i+1,n):\n if digits[j]>=maxx and digits[j]!=digits[i]:\n maxx = digits[j]\n indx = j\n \n if indx!=i:\n digits[i],digits[indx] = digits[indx],digits[i]\n \n #only one swap allowed\n return \"\".join([str(x) for x in digits])\n \n #already sorted\n return num\n", + "title": "670. Maximum Swap", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n , where flowers[i] is the number of flowers already planted in the i th garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers , which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target , full , and partial . A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.", + "description_images": [], + "constraints": [ + "The number of complete gardens multiplied by full .", + "The minimum number of flowers in any of the incomplete gardens multiplied by partial . If there are no incomplete gardens, then this value will be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1\nOutput:14\nExplanation:Alice can plant\n- 2 flowers in the 0thgarden\n- 3 flowers in the 1stgarden\n- 1 flower in the 2ndgarden\n- 1 flower in the 3rdgarden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.", + "image": null + }, + { + "text": "Example 2: Input:flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6\nOutput:30\nExplanation:Alice can plant\n- 3 flowers in the 0thgarden\n- 0 flowers in the 1stgarden\n- 0 flowers in the 2ndgarden\n- 2 flowers in the 3rdgarden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) {\n int n = flowers.length;\n long[] prefix = new long[n + 1];\n Arrays.sort(flowers);\n for (int i = 0; i < n; ++i) prefix[i + 1] = prefix[i] + Math.min(flowers[i], target);\n long res = 0;\n for (int c = 0, i = n - 1; c <= n; ++c) {\n long remain = prefix[n] - prefix[n - c] + newFlowers - c * (long) target, min = 0;\n if (0 > remain) break;\n i = Math.min(i, n - c - 1);\n while (0 <= i && (target <= flowers[i] || flowers[i] * (long) (i + 1) - prefix[i + 1] > remain)) i--;\n if (0 <= i) {\n long dif = flowers[i] * (long) (i + 1) - prefix[i + 1];\n min = Math.min(target - 1, flowers[i] + (remain - dif) / (i + 1));\n if (i + 1 < n - c) min = Math.min(min, flowers[i + 1]);\n }\n res = Math.max(res, c * (long) full + min * (long) partial);\n }\n return res;\n }\n}\n", + "title": "2234. Maximum Total Beauty of the Gardens", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n , where flowers[i] is the number of flowers already planted in the i th garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers , which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target , full , and partial . A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.", + "description_images": [], + "constraints": [ + "The number of complete gardens multiplied by full .", + "The minimum number of flowers in any of the incomplete gardens multiplied by partial . If there are no incomplete gardens, then this value will be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1\nOutput:14\nExplanation:Alice can plant\n- 2 flowers in the 0thgarden\n- 3 flowers in the 1stgarden\n- 1 flower in the 2ndgarden\n- 1 flower in the 3rdgarden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.", + "image": null + }, + { + "text": "Example 2: Input:flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6\nOutput:30\nExplanation:Alice can plant\n- 3 flowers in the 0thgarden\n- 0 flowers in the 1stgarden\n- 0 flowers in the 2ndgarden\n- 2 flowers in the 3rdgarden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 865 ms (Top 94.12%) | Memory: 32.60 MB (Top 7.84%)\n\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n \n\t\t# move out already completed garden\n already_complete = 0\n temp = []\n for f in flowers:\n if f >= target:\n already_complete += 1\n else:\n temp.append(f)\n\n max_beauty = 0\n \n flowers = temp\n flowers.sort()\n \n presum = [0] + list(accumulate(flowers))\n N = len(flowers)\n \n dp_arr = []\n \n for i in range(N+1):\n # iterate all index: left part is all partial, right part (>= i) is all complete\n \n # update the dp arr for binary search below\n if i < N:\n dp_arr.append((i+1) * flowers[i] - presum[i+1])\n \n right_sum = presum[-1] - presum[i]\n right_count = N - i\n \n # if can't make the right part all complete, go to next index\n if right_sum + newFlowers < right_count * target:\n continue\n \n # remaining flowers after making right part all complete\n rem_flowers = newFlowers - (right_count * target - right_sum)\n \n # binary search to find the maximum possible min flowers in the left part (named 'min_partial')\n if i == 0:\n min_partial = 0\n else:\n j = min(bisect.bisect_right(dp_arr, rem_flowers) - 1, i-1)\n min_partial = min((rem_flowers + presum[j+1]) // (j+1), target-1)\n \n complete = right_count + already_complete\n max_beauty = max(max_beauty, complete * full + min_partial * partial)\n\n \n return max_beauty\n", + "title": "2234. Maximum Total Beauty of the Gardens", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1 . You are also given a 2D integer array roads where roads[i] = [a i , b i ] denotes that there exists a bidirectional road connecting cities a i and b i . You need to assign each city with an integer value from 1 to n , where each value can only be used once . The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally.", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "1 <= roads.length <= 5 * 10^4", + "roads[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no duplicate roads." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput:43\nExplanation:The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,3],[2,4],[1,3]]\nOutput:20\nExplanation:The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 55.58%) | Memory: 124.3 MB (Top 45.11%)\nclass Solution {\n public long maximumImportance(int n, int[][] roads) {\n long ans = 0, x = 1;\n long degree[] = new long[n];\n for(int road[] : roads){\n degree[road[0]]++;\n degree[road[1]]++;\n }\n Arrays.sort(degree);\n for(long i : degree) ans += i * (x++) ;\n return ans;\n }\n}", + "title": "2285. Maximum Total Importance of Roads", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1 . You are also given a 2D integer array roads where roads[i] = [a i , b i ] denotes that there exists a bidirectional road connecting cities a i and b i . You need to assign each city with an integer value from 1 to n , where each value can only be used once . The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally.", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "1 <= roads.length <= 5 * 10^4", + "roads[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no duplicate roads." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput:43\nExplanation:The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,3],[2,4],[1,3]]\nOutput:20\nExplanation:The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1313 ms (Top 92.99%) | Memory: 41.50 MB (Top 72.32%)\n\nclass Solution:\n def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n Arr = [0] * n # i-th city has Arr[i] roads\n for A,B in roads:\n Arr[A] += 1 # Each road increase the road count\n Arr[B] += 1\n Arr.sort() # Cities with most road should receive the most score\n summ = 0\n for i in range(len(Arr)):\n summ += Arr[i] * (i+1) # Multiply city roads with corresponding score\n \n return summ\n", + "title": "2285. Maximum Total Importance of Roads", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array grid of size m x n , where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid . Note:", + "description_images": [], + "constraints": [ + "Horizontal movement means moving in either the left or right direction.", + "Vertical movement means moving in either the up or down direction." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput:3\nExplanation:The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.", + "image": "https://assets.leetcode.com/uploads/2022/03/23/ex1new2.jpg" + }, + { + "text": "Example 2: Input:grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput:0\nExplanation:The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 84 ms (Top 75.61%) | Memory: 82.50 MB (Top 26.83%)\n\nclass Solution {\n public int maxTrailingZeros(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[][] two = new int[m][n];\n int[][] five = new int[m][n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n two[i][j] = getFactorNum(grid[i][j], 2);\n five[i][j] = getFactorNum(grid[i][j], 5);\n }\n }\n \n int[][] left2 = new int[m][n];\n int[][] left5 = new int[m][n];\n for (int i = 0; i < m; ++i) {\n int sum2 = 0;\n int sum5 = 0;\n for (int j = 0; j < n; ++j) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n left2[i][j] = sum2;\n left5[i][j] = sum5;\n }\n }\n \n int[][] right2 = new int[m][n];\n int[][] right5 = new int[m][n];\n for (int i = 0; i < m; ++i) {\n int sum2 = 0;\n int sum5 = 0;\n for (int j = n - 1; j >= 0; --j) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n right2[i][j] = sum2;\n right5[i][j] = sum5;\n }\n }\n \n int[][] up2 = new int[m][n];\n int[][] up5 = new int[m][n];\n for (int j = 0; j < n; ++j) {\n int sum2 = 0;\n int sum5 = 0;\n for (int i = 0; i < m; ++i) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n up2[i][j] = sum2;\n up5[i][j] = sum5;\n }\n }\n \n int[][] down2 = new int[m][n];\n int[][] down5 = new int[m][n];\n for (int j = 0; j < n; ++j) {\n int sum2 = 0;\n int sum5 = 0;\n for (int i = m - 1; i >= 0; --i) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n down2[i][j] = sum2;\n down5[i][j] = sum5;\n }\n }\n \n int res = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n // left-up\n if (i != 0 || j != 0) {\n int cur = Math.min(left2[i][j] + up2[i][j] - two[i][j], left5[i][j] + up5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // up-right\n if (i != 0 || j != n - 1) {\n int cur = Math.min(right2[i][j] + up2[i][j] - two[i][j], right5[i][j] + up5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // right-down\n if (i != m - 1 || j != n - 1) {\n int cur = Math.min(right2[i][j] + down2[i][j] - two[i][j], right5[i][j] + down5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // down-left\n if (i != m - 1 || j != 0) {\n int cur = Math.min(left2[i][j] + down2[i][j] - two[i][j], left5[i][j] + down5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n }\n }\n return res;\n }\n \n private int getFactorNum(int input, int factor) {\n int res = 0;\n while (input != 0 && input % factor == 0) {\n ++res;\n input /= factor;\n }\n return res;\n }\n}\n", + "title": "2245. Maximum Trailing Zeros in a Cornered Path", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array grid of size m x n , where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid . Note:", + "description_images": [], + "constraints": [ + "Horizontal movement means moving in either the left or right direction.", + "Vertical movement means moving in either the up or down direction." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput:3\nExplanation:The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.", + "image": "https://assets.leetcode.com/uploads/2022/03/23/ex1new2.jpg" + }, + { + "text": "Example 2: Input:grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput:0\nExplanation:The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/ex2.jpg" + } + ], + "follow_up": null, + "solution": "import numpy as np\n\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n A = np.array(grid)\n def cumdivs(d):\n D = sum(A % d**i == 0 for i in range(1, 10))\n return D.cumsum(0) + D.cumsum(1) - D\n return max(np.minimum(cumdivs(2), cumdivs(5)).max()\n for _ in range(4)\n if [A := np.rot90(A)])\n", + "title": "2245. Maximum Trailing Zeros in a Cornered Path", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list .", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]\nOutput:6\nExplanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]\nOutput:7\nExplanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]\nOutput:100001\nExplanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int pairSum(ListNode head) {\n if (head == null) {\n return 0;\n }\n if (head.next == null) {\n return head.val;\n }\n ListNode slow = head;\n ListNode fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n slow = reverse(slow);\n fast = head;\n int sum = Integer.MIN_VALUE;\n while (slow != null) {\n sum = Math.max(slow.val + fast.val, sum);\n slow = slow.next;\n fast = fast.next;\n }\n return sum;\n }\n \n public ListNode reverse(ListNode node) {\n if (node == null) {\n return null;\n }\n ListNode current = node;\n ListNode previous = null;\n while (current != null) {\n ListNode next = current.next;\n current.next = previous;\n previous = current;\n current = next;\n }\n return previous;\n }\n}\n", + "title": "2130. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list .", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]\nOutput:6\nExplanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]\nOutput:7\nExplanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]\nOutput:100001\nExplanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2246 ms (Top 8.54%) | Memory: 54.1 MB (Top 58.68%)\nclass Solution:\n def pairSum(self, head: Optional[ListNode]) -> int:\n nums = []\n curr = head\n while curr:\n nums.append(curr.val)\n curr = curr.next\n\n N = len(nums)\n res = 0\n for i in range(N // 2):\n res = max(res, nums[i] + nums[N - i - 1])\n return res", + "title": "2130. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are assigned to put some amount of boxes onto one truck . You are given a 2D array boxTypes , where boxTypes[i] = [numberOfBoxes i , numberOfUnitsPerBox i ] : You are also given an integer truckSize , which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize . Return the maximum total number of units that can be put on the truck.", + "description_images": [], + "constraints": [ + "numberOfBoxes i is the number of boxes of type i .", + "numberOfUnitsPerBox i is the number of units in each box of the type i ." + ], + "examples": [ + { + "text": "Example 1: Input:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\nOutput:8\nExplanation:There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.", + "image": null + }, + { + "text": "Example 2: Input:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\nOutput:91", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int maximumUnits(int[][] boxTypes, int truckSize) {\n\t\tArrays.sort(boxTypes, Comparator.comparingInt(o -> -o[1]));\n\t\tint ans = 0, i = 0, n = boxTypes.length;\n\t\twhile (i < n && truckSize > 0) {\n\t\t\tint maxi = Math.min(boxTypes[i][0], truckSize);\n\t\t\tans += maxi * boxTypes[i][1];\n\t\t\ti++;\n\t\t\ttruckSize -= maxi;\n\t\t}\n\t\treturn ans;\n\t}\n}", + "title": "1710. Maximum Units on a Truck", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are assigned to put some amount of boxes onto one truck . You are given a 2D array boxTypes , where boxTypes[i] = [numberOfBoxes i , numberOfUnitsPerBox i ] : You are also given an integer truckSize , which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize . Return the maximum total number of units that can be put on the truck.", + "description_images": [], + "constraints": [ + "numberOfBoxes i is the number of boxes of type i .", + "numberOfUnitsPerBox i is the number of units in each box of the type i ." + ], + "examples": [ + { + "text": "Example 1: Input:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\nOutput:8\nExplanation:There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.", + "image": null + }, + { + "text": "Example 2: Input:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\nOutput:91", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumUnits(self, B: List[List[int]], T: int) -> int:\n B.sort(key=lambda x: x[1], reverse=True)\n ans = 0\n for b,n in B:\n boxes = min(b, T)\n ans += boxes * n\n T -= boxes\n if T == 0: return ans\n return ans\n", + "title": "1710. Maximum Units on a Truck", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a very large integer n , represented as a string,​​​​​​ and an integer digit x . The digits in n and the digit x are in the inclusive range [1, 9] , and n may represent a negative number. You want to maximize n 's numerical value by inserting x anywhere in the decimal representation of n ​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n ​​​​​​ after the insertion .", + "description_images": [], + "constraints": [ + "For example, if n = 73 and x = 6 , it would be best to insert it between 7 and 3 , making n = 763 .", + "If n = -55 and x = 2 , it would be best to insert it before the first 5 , making n = -255 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"99\", x = 9\nOutput:\"999\"\nExplanation:The result is the same regardless of where you insert 9.", + "image": null + }, + { + "text": "Example 2: Input:n = \"-13\", x = 2\nOutput:\"-123\"\nExplanation:You can make n one of {-213, -123, -132}, and the largest of those three is -123.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maxValue(String n, int x) {\n StringBuilder res= new StringBuilder();\n int i=0, j=0;\n if(n.charAt(0)=='-'){\n res.append(n.charAt(0));\n for(j=1; j= x){ \n res.append(ch);\n }else{\n res.append(x);\n res.append(ch);\n res.append(n.substring(i+1));\n break;\n }\n }\n if(i==n.length()){\n res.append(x);\n }\n }\n return res.toString();\n }\n}", + "title": "1881. Maximum Value after Insertion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a very large integer n , represented as a string,​​​​​​ and an integer digit x . The digits in n and the digit x are in the inclusive range [1, 9] , and n may represent a negative number. You want to maximize n 's numerical value by inserting x anywhere in the decimal representation of n ​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n ​​​​​​ after the insertion .", + "description_images": [], + "constraints": [ + "For example, if n = 73 and x = 6 , it would be best to insert it between 7 and 3 , making n = 763 .", + "If n = -55 and x = 2 , it would be best to insert it before the first 5 , making n = -255 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"99\", x = 9\nOutput:\"999\"\nExplanation:The result is the same regardless of where you insert 9.", + "image": null + }, + { + "text": "Example 2: Input:n = \"-13\", x = 2\nOutput:\"-123\"\nExplanation:You can make n one of {-213, -123, -132}, and the largest of those three is -123.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValue(self, n: str, x: int) -> str:\n if int(n)>0:\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])>=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n else:\n n = n[1:]\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])<=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n ans = \"-\"+ans\n \n return ans\n \n", + "title": "1881. Maximum Value after Insertion", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given three positive integers: n , index , and maxSum . You want to construct an array nums ( 0-indexed ) that satisfies the following conditions: Return nums[index] of the constructed array . Note that abs(x) equals x if x >= 0 , and -x otherwise.", + "description_images": [], + "constraints": [ + "nums.length == n", + "nums[i] is a positive integer where 0 <= i < n .", + "abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1 .", + "The sum of all the elements of nums does not exceed maxSum .", + "nums[index] is maximized ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, index = 2, maxSum = 6\nOutput:2\nExplanation:nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].", + "image": null + }, + { + "text": "Example 2: Input:n = 6, index = 1, maxSum = 10\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "\n/* Intuition:\nAs the number of elements is 10^9 so we can't actually create the array\nAnd by seeing the limit we can judge that the complexity should be O(logn)\nSo it will become obvious that binary search can only help to solve this prob\n\nWe have to put the maximum possible value in the index position and then all \nthe values to its right and left should decrease by 1 until the value reaches 1\nfor Ex in n = 6, index = 1, maxSum = 10\n\nour index at 1 should be 3 and the array will look like\n2 3 2 1 1\n+ max - - same\n\nmeans you have to make an array which is strictly increasing and it attains its max (which is answer)\nthen strictly decreasing till value becomes 1 and then continues it as 1. Like\n1 ... 1, 2, 3, 4, 5, 6(if answer is 6), 5, 4, 3, 2, 1, .... 1\n\nWhy this solution?\nBecause our objective is to maximize our index position value i.e. ans. So to maximize it\nwe all the other elements other than index position should be as low as possible (so that sum of our array\nis less than maxSum), which will lead to this solution of \"Get the max element on index given and decrease strictly\non both sides of the array till our value is 1, and then continue it to 1\"\n*/\n\nclass Solution {\n public int maxValue(int n, int index, int maxSum) {\n // Setting the initial values is very important, our ans can never be 0 so set low as 1\n int low = 1, mid = 0, high = 1000000000;\n while(low <= high) {\n mid = (low + high) / 2;\n \n // If our ans (which is mid) is making the sum of array more than maxSum means we have to decrease our high\n if(calcAns(mid, index, n) > maxSum) { \n high = mid - 1;\n } \n \n // If our ans (which is mid) is so low that even ans + 1 (i.e. mid + 1) is giving better result that means increase our low\n else if(calcAns(mid + 1, index, n) <= maxSum) {\n low = mid + 1;\n } \n \n // If our ans (== mid) is such that the sum of array is less than maxSum and even increasing 1 to mid will result the total\n // sum to increase from maxSum, that signifies that we have the answer as mid\n else {\n break;\n }\n }\n \n return mid;\n }\n \n public int calcAns(int max, int idx, int n) {\n \n // This method will give you answer of the setup where our peak element is ans at index idx and we have n elements\n // So we have two part of array one is the left part (1, 1... 2, 3 ... max - 1) and then (max, max - 1, max - 2, 1 ... 1)\n // so you can think of it as we have few extraOnes on both left and right parts and then an AP array which goes upto max\n \n // Left part I have taken till max - 1 and right part I have taken from max.\n // calcPart takes (first value of AP, number of elements)\n \n long ret = calcPart(max - 1, idx) + calcPart(max, n - idx);\n if(ret > 1000000000) {\n // Seeing the constraints, if you chose to take high mid value then it might overflow from int. And our answer can never\n // be greater than 10^9 so limit it to that.\n return 1000000001;\n } else {\n \n // This is the sum of the array where max is taken as answer\n return (int)ret;\n }\n }\n \n public long calcPart(int a, int num) {\n \n // For AP we need first element (which is \"a\") and last element (which we calculate in an)\n long an = 0, extraOnes = 0;\n long ans = 0;\n if(num >= a) {\n \n // If total number of elements is more than a which means it will look like\n // a, a - 1, a - 2, ... , 2, 1 ... followed by extraOnes\n an = 1;\n extraOnes = num - a;\n } else if(num < a) {\n \n // If total number of elements is such that we never reach 1 as our last element means\n // a, a - 1, a - 2 ... a - x, then extraOnes will be 0\n extraOnes = 0;\n an = a - num + 1;\n }\n \n // Sum of AP where we know first and last element = ((first + last) * n) / 2\n ans = ((an + a) * (a - an + 1)) / 2;\n \n // Add extra ones\n ans += extraOnes;\n \n return ans;\n }\n}\n", + "title": "1802. Maximum Value at a Given Index in a Bounded Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given three positive integers: n , index , and maxSum . You want to construct an array nums ( 0-indexed ) that satisfies the following conditions: Return nums[index] of the constructed array . Note that abs(x) equals x if x >= 0 , and -x otherwise.", + "description_images": [], + "constraints": [ + "nums.length == n", + "nums[i] is a positive integer where 0 <= i < n .", + "abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1 .", + "The sum of all the elements of nums does not exceed maxSum .", + "nums[index] is maximized ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, index = 2, maxSum = 6\nOutput:2\nExplanation:nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].", + "image": null + }, + { + "text": "Example 2: Input:n = 6, index = 1, maxSum = 10\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n l = 1\n r = int(1e9)\n ans = 0\n\n while l<=r:\n mid = (l+r)//2\n total = 0\n\n # add left numbers\n if mid>=index+1:\n first = mid-index\n size = index+1\n total += first*size + size*(size-1)/2\n else:\n total += mid*(mid+1)/2\n total += index+1-mid\n\n\n # add right numbers\n size = n-index\n if mid >= size:\n last = mid - (n-index-1)\n total += last*size + size*(size-1)/2\n else:\n total += mid*(mid+1)/2\n total += (size-mid) \n\n # deduct mid because it was added twice \n total -= mid\n \n if total <= maxSum:\n ans = max(ans, mid)\n l = mid+1\n else:\n r = mid-1\n\n return ans", + "title": "1802. Maximum Value at a Given Index in a Bounded Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles , where piles[i] is a list of integers denoting the composition of the i th pile from top to bottom , and a positive integer k , return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally .", + "description_images": [], + "constraints": [ + "n == piles.length", + "1 <= n <= 1000", + "1 <= piles[i][j] <= 10^5", + "1 <= k <= sum(piles[i].length) <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [[1,100,3],[7,8,9]], k = 2\nOutput:101\nExplanation:The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.", + "image": "https://assets.leetcode.com/uploads/2019/11/09/e1.png" + }, + { + "text": "Example 2: Input:piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput:706\nExplanation:The maximum total can be obtained if we choose all coins from the last pile.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 223 ms (Top 73.40%) | Memory: 55.8 MB (Top 38.07%)\nclass Solution {\n public int maxValueOfCoins(List> piles, int k) {\n int n = piles.size();\n int[][] ans = new int[n+1][2001];\n Collections.sort(piles, (List a, List b) -> b.size() - a.size());\n for(int i = 1; i <= k; i++) {\n for(int j = 1; j <= n; j++) {\n int sizeOfPile = piles.get(j-1).size();\n List pile = piles.get(j-1);\n int sum = 0;\n ans[j][i] = ans[j-1][i];\n for(int l = 1; l <= Math.min(i, sizeOfPile); l++) {\n // Take K from this pile + remaining from previous piles\n sum += pile.get(l-1);\n int rem = i - l;\n ans[j][i] = Math.max(ans[j][i], sum + ans[j-1][rem]);\n }\n }\n }\n\n return ans[n][k];\n }\n}", + "title": "2218. Maximum Value of K Coins From Piles", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles , where piles[i] is a list of integers denoting the composition of the i th pile from top to bottom , and a positive integer k , return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally .", + "description_images": [], + "constraints": [ + "n == piles.length", + "1 <= n <= 1000", + "1 <= piles[i][j] <= 10^5", + "1 <= k <= sum(piles[i].length) <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [[1,100,3],[7,8,9]], k = 2\nOutput:101\nExplanation:The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.", + "image": "https://assets.leetcode.com/uploads/2019/11/09/e1.png" + }, + { + "text": "Example 2: Input:piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput:706\nExplanation:The maximum total can be obtained if we choose all coins from the last pile.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n n = len(piles)\n prefixSum = []\n for i in range(n):\n temp = [0]\n for j in range(len(piles[i])):\n temp.append(temp[-1] + piles[i][j])\n prefixSum.append(temp)\n \n dp = [[0] * (k + 1) for _ in range(n)]\n for j in range(1, k + 1):\n if j < len(prefixSum[0]):\n dp[0][j] = prefixSum[0][j]\n \n for i in range(1, n):\n for j in range(1, k + 1):\n for l in range(len(prefixSum[i])):\n if l > j:\n break\n dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l])\n return dp[n - 1][k]\n", + "title": "2218. Maximum Value of K Coins From Piles", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array tiles where tiles[i] = [l i , r i ] represents that every tile j in the range l i <= j <= r i is colored white. You are also given an integer carpetLen , the length of a single carpet that can be placed anywhere . Return the maximum number of white tiles that can be covered by the carpet .", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 5 * 10^4", + "tiles[i].length == 2", + "1 <= l i <= r i <= 10^9", + "1 <= carpetLen <= 10^9", + "The tiles are non-overlapping ." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\nOutput:9\nExplanation:Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/example1drawio3.png" + }, + { + "text": "Example 2: Input:tiles = [[10,11],[1,1]], carpetLen = 2\nOutput:2\nExplanation:Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/03/24/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 71.1%) | Memory: 71.05 MB (Top 47.1%)\n\nclass Solution\n{\n public int maximumWhiteTiles(int[][] tiles, int carpetLen)\n {\n Arrays.sort(tiles,(a,b)->{return a[0]-b[0];});\n int x = 0;\n int y = 0;\n long maxCount = 0;\n long count = 0;\n \n while(y < tiles.length && x <= y)\n {\n long start = tiles[x][0];\n long end = tiles[y][1];\n \n if(end-start+1 <= carpetLen) \n {\n count += tiles[y][1] - tiles[y][0]+1;\n maxCount = Math.max(maxCount,count);\n y++;\n }\n else \n {\n long midDist = start+carpetLen-1;\n long s = tiles[y][0];\n long e = tiles[y][1];\n if(midDist <= e && midDist >= s) maxCount = Math.max(maxCount,count+midDist-s+1);\n count -= tiles[x][1] - tiles[x][0] + 1;\n x++;\n }\n }\n return (int)maxCount;\n }\n}", + "title": "2271. Maximum White Tiles Covered by a Carpet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array tiles where tiles[i] = [l i , r i ] represents that every tile j in the range l i <= j <= r i is colored white. You are also given an integer carpetLen , the length of a single carpet that can be placed anywhere . Return the maximum number of white tiles that can be covered by the carpet .", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 5 * 10^4", + "tiles[i].length == 2", + "1 <= l i <= r i <= 10^9", + "1 <= carpetLen <= 10^9", + "The tiles are non-overlapping ." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\nOutput:9\nExplanation:Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/example1drawio3.png" + }, + { + "text": "Example 2: Input:tiles = [[10,11],[1,1]], carpetLen = 2\nOutput:2\nExplanation:Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/03/24/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n tiles.sort()\n\t\t#j: window index\n j = cover = res = 0\n for i in range(len(tiles)):\n\t\t\t#slide the window as far as we can to cover fully the intervals with the carpet\n while j int:\n q = deque([(root, 0)])\n res = 0\n\n while q:\n res = max(res, q[-1][1] - q[0][1] + 1)\n for _ in range(len(q)):\n curr, pos = q.popleft()\n\n if curr.left:\n q.append((curr.left, pos*2))\n if curr.right:\n q.append((curr.right, pos*2 + 1))\n\n return res", + "title": "662. Maximum Width of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j] . The width of such a ramp is j - i . Given an integer array nums , return the maximum width of a ramp in nums . If there is no ramp in nums , return 0 .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,0,8,2,1,5]\nOutput:4\nExplanation:The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,1,0,1,9,4,0,4,1]\nOutput:7\nExplanation:The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxWidthRamp(int[] nums) {\n Stack s = new Stack<>();\n int res = 0;\n for(int i = 0; i< nums.length; i++){\n if(!s.isEmpty() && nums[s.peek()]<=nums[i]) {\n res = Math.max(res, i-s.peek());\n continue;\n }\n s.push(i);\n }\n int i = nums.length-1;\n while(!s.isEmpty() && i>=0){\n if(nums[s.peek()]<=nums[i]){\n res = Math.max(res, i-s.peek());\n s.pop();\n }else{\n i--;\n }\n }\n return res;\n }\n}\n", + "title": "962. Maximum Width Ramp", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j] . The width of such a ramp is j - i . Given an integer array nums , return the maximum width of a ramp in nums . If there is no ramp in nums , return 0 .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,0,8,2,1,5]\nOutput:4\nExplanation:The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,1,0,1,9,4,0,4,1]\nOutput:7\nExplanation:The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 635 ms (Top 30.72%) | Memory: 21.1 MB (Top 46.08%)\nclass Solution:\n def maxWidthRamp(self, nums: List[int]):\n st=[]\n n=len(nums)\n for i in range(n):\n if len(st)==0 or nums[st[-1]]>=nums[i]:\n st.append(i)\n print(st)\n max_idx=-1\n for j in range(n-1,-1,-1):\n while len(st) and nums[st[-1]]<=nums[j]:\n prev=st.pop()\n max_idx=max(max_idx,j-prev)\n\n return max_idx\n", + "title": "962. Maximum Width Ramp", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one operation, select any non-negative integer x and an index i , then update nums[i] to be equal to nums[i] AND (nums[i] XOR x) . Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,4,6]\nOutput:7\nExplanation:Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,9,2]\nOutput:11\nExplanation:Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int i=0; i int:\n res=0\n for i in nums:\n res |= i\n return res\n", + "title": "2317. Maximum XOR After Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a sorted array nums of n non-negative integers and an integer maximumBit . You want to perform the following query n times : Return an array answer , where answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "nums.length == n", + "1 <= n <= 10^5", + "1 <= maximumBit <= 20", + "0 <= nums[i] < 2 maximumBit", + "nums ​​​ is sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,1,3], maximumBit = 2\nOutput:[0,3,2,3]\nExplanation: The queries are answered as follows:\n1stquery: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n2ndquery: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n3rdquery: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n4thquery: nums = [0], k = 3 since 0 XOR 3 = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,4,7], maximumBit = 3\nOutput:[5,2,6,5]\nExplanation: The queries are answered as follows:\n1stquery: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n2ndquery: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n3rdquery: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n4thquery: nums = [2], k = 5 since 2 XOR 5 = 7.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,2,5,7], maximumBit = 3\nOutput:[4,3,6,4,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 736 ms (Top 100.0%) | Memory: 34.71 MB (Top 50.5%)\n\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n ans = [(1 << maximumBit) - 1]\n for n in nums:\n ans.append(ans[-1] ^ n)\n\n return ans[len(ans)-1:0:-1]", + "title": "1829. Maximum XOR for Each Query", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the maximum result of nums[i] XOR nums[j] , where 0 <= i <= j < n .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^5", + "0 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,10,5,25,2,8]\nOutput:28\nExplanation:The maximum result is 5 XOR 25 = 28.", + "image": null + }, + { + "text": "Example 2: Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]\nOutput:127", + "image": null + } + ], + "follow_up": null, + "solution": "class Node {\n Node[] links = new Node[2];\n \n public Node () {\n \n }\n \n boolean containsKey(int ind) {\n return links[ind] != null;\n }\n \n Node get(int ind) {\n return links[ind];\n }\n \n void put(int ind, Node node) {\n links[ind] = node;\n }\n}\n\nclass Trie {\n private static Node root;\n \n public Trie() {\n root = new Node();\n }\n \n public static void insert(int num) {\n Node node = root;\n for (int i = 31; i >= 0; i--) {\n int bit = (num >> i) & 1;\n if (!node.containsKey(bit)) {\n node.put(bit, new Node());\n }\n node = node.get(bit);\n }\n }\n \n public static int getMax(int num) {\n Node node = root;\n int maxNum = 0;\n \n for (int i = 31; i >= 0; i--) {\n int bit = (num >> i) & 1;\n if (node.containsKey(1 - bit)) {\n maxNum = maxNum | (1 << i);\n node = node.get(1 - bit);\n }\n else {\n node = node.get(bit);\n }\n }\n return maxNum;\n }\n}\n\n\nclass Solution {\n public int findMaximumXOR(int[] nums) {\n Trie trie = new Trie();\n \n for (int i = 0; i < nums.length; i++) {\n trie.insert(nums[i]);\n }\n \n int maxi = 0;\n for (int i = 0; i < nums.length; i++) {\n maxi = Math.max(maxi, trie.getMax(nums[i]));\n }\n return maxi;\n }\n}\n", + "title": "421. Maximum XOR of Two Numbers in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the maximum result of nums[i] XOR nums[j] , where 0 <= i <= j < n .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^5", + "0 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,10,5,25,2,8]\nOutput:28\nExplanation:The maximum result is 5 XOR 25 = 28.", + "image": null + }, + { + "text": "Example 2: Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]\nOutput:127", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findMaximumXOR(self, nums: List[int]) -> int:\n\t\tTrieNode = lambda: defaultdict(TrieNode)\n\t\troot = TrieNode()\n\t\tfor n in nums:\n\t\t\tcur = root\n\t\t\tfor i in range(31,-1,-1):\n\t\t\t\tbit = 1 if n&(1< {\n public int compare(int[] a, int[] b) {\n return Integer.compare(a[1], b[1]);\n }\n }\n \n class Node {\n Node zero;\n Node one;\n \n public Node() {\n this.zero = null;\n this.one = null;\n }\n }\n \n public int[] maximizeXor(int[] nums, int[][] queries) {\n Arrays.sort(nums);\n \n int len = queries.length;\n int[][] queryWithIndex = new int[len][3];\n for(int i = 0; i < len; i++) {\n queryWithIndex[i][0] = queries[i][0];\n queryWithIndex[i][1] = queries[i][1];\n queryWithIndex[i][2] = i;\n }\n Arrays.sort(queryWithIndex, new QueryComparator());\n \n int numId = 0;\n int[] ans = new int[len];\n \n Node root = new Node();\n for(int i = 0; i < len; i++) {\n while(numId < nums.length && nums[numId] <= queryWithIndex[i][1]) {\n addNumToTree(nums[numId], root);\n numId++;\n }\n \n ans[queryWithIndex[i][2]] = maxXOR(queryWithIndex[i][0], root);\n }\n \n return ans;\n }\n \n private void addNumToTree(int num, Node node) {\n for(int i = 31; i >= 0; i--) {\n int digit = (num >> i) & 1;\n if (digit == 1) {\n if (node.one == null) {\n node.one = new Node();\n }\n node = node.one;\n } else {\n if (node.zero == null) {\n node.zero = new Node();\n }\n node = node.zero;\n }\n }\n }\n \n private int maxXOR(int num, Node node) {\n if (node.one == null && node.zero == null) {\n return -1;\n }\n\n int ans = 0;\n for(int i = 31; i >= 0 && node != null; i--) {\n int digit = (num >> i) & 1;\n if (digit == 1) {\n if (node.zero != null) {\n ans += (1 << i);\n node = node.zero;\n } else {\n node = node.one;\n }\n } else {\n if (node.one != null) {\n ans += (1 << i);\n node = node.one;\n } else {\n node = node.zero;\n }\n }\n }\n \n return ans;\n }\n}\n", + "title": "1707. Maximum XOR With an Element From Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [x i , m i ] . The answer to the i th query is the maximum bitwise XOR value of x i and any element of nums that does not exceed m i . In other words, the answer is max(nums[j] XOR x i ) for all j such that nums[j] <= m i . If all elements in nums are larger than m i , then the answer is -1 . Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the i th query.", + "description_images": [], + "constraints": [ + "1 <= nums.length, queries.length <= 10^5", + "queries[i].length == 2", + "0 <= nums[j], x i , m i <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\nOutput:[3,3,7]\nExplanation:1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\nOutput:[15,-1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Trie:\n def __init__(self):\n self.root = {}\n \n def insert(self, num):\n p = self.root\n for i in range(31, -1, -1):\n cur = (num >> i) & 1\n if cur not in p:\n p[cur] = {}\n p = p[cur]\n \n def query(self, num):\n if not self.root: \n return -1\n p, ans = self.root, 0\n for i in range(31, -1, -1):\n cur = (num >> i) & 1\n if 1 - cur in p:\n p = p[1 - cur]\n ans |= (1 << i)\n else:\n p = p[cur]\n return ans\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted(enumerate(queries), key=lambda x: x[1][1])\n trie = Trie()\n ans = [-1] * len(queries)\n j = 0\n for i, (x, m) in queries:\n while j < len(nums) and nums[j] <= m:\n trie.insert(nums[j])\n j += 1\n ans[i] = trie.query(x)\n return ans\n", + "title": "1707. Maximum XOR With an Element From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr , return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10 -5 of the actual answer will be considered accepted.", + "description_images": [], + "constraints": [ + "20 <= arr.length <= 1000", + "arr.length is a multiple of 20 .", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput:2.00000\nExplanation:After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput:4.00000", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput:4.77778", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double trimMean(int[] arr) {\n Arrays.sort(arr);\n int length = arr.length;\n int toRemove = length * 5 / 100;\n int total = 0;\n for (int number: arr) {\n total += number;\n }\n for (int i=0; i= length-toRemove; i--)\n total -= arr[i];\n length -= (2 * toRemove);\n return (double) ((double)total / (double)length);\n }\n}\n", + "title": "1619. Mean of Array After Removing Some Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10 -5 of the actual answer will be considered accepted.", + "description_images": [], + "constraints": [ + "20 <= arr.length <= 1000", + "arr.length is a multiple of 20 .", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput:2.00000\nExplanation:After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput:4.00000", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput:4.77778", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 11.43%) | Memory: 14.1 MB (Top 36.03%)\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n\n return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])\n", + "title": "1619. Mean of Array After Removing Some Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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)) .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]\nOutput:2.00000\nExplanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]\nOutput:2.50000\nExplanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 46.02%) | Memory: 50.6 MB (Top 18.35%)\n\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0;\n int i = 0;\n int j = 0;\n int k = 0;\n int nums[] = new int[nums1.length + nums2.length];\n if(nums1.length !=0 && nums2.length != 0){\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] < nums2[j]){\n nums[k] = nums1[i];\n i++;\n k++;\n }else{\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n while(i < nums1.length){\n nums[k] = nums1[i];\n i++;\n k++;\n }\n while(j < nums2.length){\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n if(nums1.length==0){\n for(int h: nums2){\n nums[k] = h;\n k++;\n }\n }\n\n if(nums2.length==0){\n for(int d : nums1){\n nums[k] = d;\n k++;\n }\n }\n\n int mid = (nums.length / 2);\n\n if (nums.length % 2 == 0) {\n return ((double) nums[mid] + (double) nums[mid - 1]) / 2.0;\n } else {\n return nums[mid];\n }\n }\n}", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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)) .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]\nOutput:2.00000\nExplanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]\nOutput:2.50000\nExplanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n lis = nums1 + nums2\n lis.sort()\n hi = len(lis)\n print(5/2)\n if hi%2 == 0:\n if (lis[hi/2] + lis[hi/2-1])%2 == 0:\n return (lis[hi/2] + lis[hi/2-1] )/2\n return (lis[hi/2] + lis[hi/2-1])/2 + 0.5\n else:\n return lis[hi//2]\n", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees ( 0-indexed ). Each BST in trees has at most 3 nodes , and no two roots have the same value. In one operation, you can: Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST . A BST (binary search tree) is a binary tree where each node satisfies the following property: A leaf is a node that has no children.", + "description_images": [], + "constraints": [ + "Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j] .", + "Replace the leaf node in trees[i] with trees[j] .", + "Remove trees[j] from trees ." + ], + "examples": [ + { + "text": "Example 1: Input:trees = [[2,1],[3,2,5],[5,4]]\nOutput:[3,2,5,1,null,4]\nExplanation:In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].The resulting tree, shown above, is a valid BST, so return its root.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d1.png" + }, + { + "text": "Example 2: Input:trees = [[5,3,8],[3,2,6]]\nOutput:[]\nExplanation:Pick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d2.png" + }, + { + "text": "Example 3: Input:trees = [[5,4],[3]]\nOutput:[]\nExplanation:It is impossible to perform any operations.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 179 ms (Top 13.99%) | Memory: 158.1 MB (Top 58.04%)\n\nclass Solution {\n public TreeNode canMerge(List trees) {\n //Map root value to tree\n HashMap map = new HashMap<>();\n for(TreeNode t : trees){\n map.put(t.val, t);\n }\n\n // Merge trees\n for(TreeNode t : trees){\n if(map.containsKey(t.val)){\n merger(t, map);\n }\n }\n\n //After merging we should have only one tree left else return null\n if(map.size() != 1) return null;\n else {\n //Return the one tree left after merging\n for(int c : map.keySet()) {\n //Check if final tree is valid else return null\n if(isValidBST(map.get(c))){\n return map.get(c);\n } else return null;\n }\n }\n\n return null;\n\n }\n\n void merger(TreeNode t, HashMap map){\n map.remove(t.val); // Remove current tree to prevent cyclical merging For. 2->3(Right) and 3->2(Left)\n //Merge on left\n if(t.left != null && map.containsKey(t.left.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.left.val), map);\n t.left = map.get(t.left.val);\n map.remove(t.left.val);\n }\n\n // Merge on right\n if(t.right!=null && map.containsKey(t.right.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.right.val), map);\n t.right = map.get(t.right.val);\n map.remove(t.right.val);\n }\n // Add tree back to map once right and left merge is complete\n map.put(t.val, t);\n }\n\n // Validate BST\n public boolean isValidBST(TreeNode root) {\n return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n\n public boolean helper(TreeNode root, long min, long max){\n if(root == null) return true;\n if(root.val <= min || root.val >= max) return false;\n return helper(root.left, min, root.val) && helper(root.right, root.val, max);\n }\n}", + "title": "1932. Merge BSTs to Create Single BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees ( 0-indexed ). Each BST in trees has at most 3 nodes , and no two roots have the same value. In one operation, you can: Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST . A BST (binary search tree) is a binary tree where each node satisfies the following property: A leaf is a node that has no children.", + "description_images": [], + "constraints": [ + "Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j] .", + "Replace the leaf node in trees[i] with trees[j] .", + "Remove trees[j] from trees ." + ], + "examples": [ + { + "text": "Example 1: Input:trees = [[2,1],[3,2,5],[5,4]]\nOutput:[3,2,5,1,null,4]\nExplanation:In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].The resulting tree, shown above, is a valid BST, so return its root.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d1.png" + }, + { + "text": "Example 2: Input:trees = [[5,3,8],[3,2,6]]\nOutput:[]\nExplanation:Pick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d2.png" + }, + { + "text": "Example 3: Input:trees = [[5,4],[3]]\nOutput:[]\nExplanation:It is impossible to perform any operations.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2457 ms (Top 91.30%) | Memory: 66.7 MB (Top 52.17%)\nclass Solution:\n def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n n = len(trees)\n if n == 1: return trees[0]\n\n value_to_root = {} # Map each integer root value to its node\n appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf\n self.saw_conflict = False # If this is ever true, break out of function and return None\n leaf_value_to_parent_node = {}\n\n def is_leaf_node(curr: TreeNode) -> bool:\n return curr.left is None and curr.right is None\n\n def get_size(curr: TreeNode) -> int: # DFS to count Binary Tree Size\n if curr is None: return 0\n return 1 + get_size(curr.left) + get_size(curr.right)\n\n def is_valid_bst(curr: TreeNode, lo=-math.inf, hi=math.inf) -> bool: # Standard BST validation code\n if curr is None: return True\n return all((lo < curr.val < hi,\n is_valid_bst(curr.left, lo, curr.val),\n is_valid_bst(curr.right, curr.val, hi)))\n\n def process_child(child_node: TreeNode, parent: TreeNode) -> None:\n if child_node is None:\n return None\n elif child_node.val in leaf_value_to_parent_node or child_node.val in appeared_as_middle_child:\n self.saw_conflict = True # Already saw this child node's value in a non-root node\n elif is_leaf_node(child_node):\n leaf_value_to_parent_node[child_node.val] = parent\n elif child_node.val in value_to_root:\n self.saw_conflict = True\n else:\n appeared_as_middle_child.add(child_node.val)\n process_child(child_node.left, child_node)\n process_child(child_node.right, child_node)\n\n def process_root(curr_root: TreeNode) -> None:\n value_to_root[curr_root.val] = curr_root\n\n if curr_root.val in appeared_as_middle_child:\n self.saw_conflict = True\n else:\n process_child(curr_root.left, curr_root)\n process_child(curr_root.right, curr_root)\n\n for root_here in trees:\n process_root(root_here)\n if self.saw_conflict: return None\n\n final_expected_size = len(leaf_value_to_parent_node) + len(appeared_as_middle_child) + 1\n\n final_root = None # The root of our final BST will be stored here\n while value_to_root:\n root_val, root_node_to_move = value_to_root.popitem()\n\n if root_val not in leaf_value_to_parent_node: # Possibly found main root\n if final_root is None:\n final_root = root_node_to_move\n else:\n return None # Found two main roots\n else:\n new_parent = leaf_value_to_parent_node.pop(root_val)\n if new_parent.left is not None and new_parent.left.val == root_val:\n new_parent.left = root_node_to_move\n continue\n elif new_parent.right is not None and new_parent.right.val == root_val:\n new_parent.right = root_node_to_move\n else:\n return None # Didn't find a place to put this node\n\n # Didn't find any candidates for main root, or have a cycle, or didn't use all trees\n if final_root is None or not is_valid_bst(final_root) or get_size(final_root) != final_expected_size:\n return None\n\n return final_root", + "title": "1932. Merge BSTs to Create Single BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head.", + "description_images": [], + "constraints": [ + "3 <= list1.length <= 10^4", + "1 <= a <= b < list1.length - 1", + "1 <= list2.length <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput:[0,1,2,1000000,1000001,1000002,5]\nExplanation:We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png" + }, + { + "text": "Example 2: Input:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput:[0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation:The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n ListNode left = list1;\n for (int i = 1; i < a; i++)\n left = left.next;\n \n ListNode middle = left;\n for (int i = a; i <= b; i++)\n middle = middle.next;\n \n\t\tleft.next = list2;\n while (list2.next != null)\n list2 = list2.next;\n \n list2.next = middle.next;\n return list1;\n }\n}\n", + "title": "1669. Merge In Between Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head.", + "description_images": [], + "constraints": [ + "3 <= list1.length <= 10^4", + "1 <= a <= b < list1.length - 1", + "1 <= list2.length <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput:[0,1,2,1000000,1000001,1000002,5]\nExplanation:We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png" + }, + { + "text": "Example 2: Input:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput:[0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation:The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 44.4%) | Memory: 22.60 MB (Top 86.42%)\n\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n head = list1\n for _ in range(a-1):\n head = head.next\n cur = head.next\n for _ in range(b-a):\n cur = cur.next\n head.next = list2\n while head.next:\n head = head.next\n if cur.next:\n head.next = cur.next\n return list1\n", + "title": "1669. Merge In Between Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput:[[1,6],[8,10],[15,18]]\nExplanation:Since intervals [1,3] and [2,6] overlap, merge them into [1,6].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]\nOutput:[[1,5]]\nExplanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 74.73%) | Memory: 55.4 MB (Top 43.78%)\nclass Solution {\n public int[][] merge(int[][] intervals) {\n // sort\n // unknown size of ans = use ArrayList\n // insert from back\n // case 1 : Merging\n // start of new interval is less that end of old interval\n // new end = Math.max(new intervals end, old intervals end)\n // case 2 : Non-merging\n // seperate interval\n // convert ArrayList to array and return\n\n Arrays.sort(intervals, (a,b) -> a[0]-b[0]);\n ArrayList list = new ArrayList<>();\n for(int i = 0; i < intervals.length; i++) {\n if(i == 0) {\n list.add(intervals[i]);\n } else {\n int[] prev = list.get(list.size()-1);\n int[] curr = intervals[i];\n if(curr[0] <= prev[1]) {\n prev[1] = Math.max(curr[1], prev[1]);\n }else {\n list.add(curr);\n }\n }\n }\n return list.toArray(new int[list.size()][2]);\n }\n}", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput:[[1,6],[8,10],[15,18]]\nExplanation:Since intervals [1,3] and [2,6] overlap, merge them into [1,6].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]\nOutput:[[1,5]]\nExplanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def merge(self, A: List[List[int]]) -> List[List[int]]:\n\t#sort array wrt its 0'th index\n A.sort(key=lambda x:x[0])\n i=0\n while i<(len(A)-1):\n if A[i][1]>=A[i+1][0]:\n A[i][1]=max(A[i+1][1],A[i][1])\n A.pop(i+1)\n else:\n i+=1\n return(A)\n \n", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]\nOutput:[1,1,2,3,4,4,5,6]\nExplanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 392 ms (Top 5.94%) | Memory: 46.8 MB (Top 77.33%)\nclass Solution {\npublic ListNode mergeKLists(ListNode[] lists) {\n if(lists == null || lists.length < 1) return null;\n\n //add the first chunk of linkedlist to res,\n //so later we started from index 1\n ListNode res = lists[0];\n\n //traverse the lists and start merge by calling mergeTwo\n for(int i = 1; i < lists.length; i++){\n res = mergeTwo(res, lists[i]);\n }\n\n return res;\n}\n //leetcode 21 technics\n private ListNode mergeTwo(ListNode l1, ListNode l2){\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n\n if(l1.val < l2.val){\n l1.next = mergeTwo(l1.next, l2);\n return l1;\n } else{\n l2.next = mergeTwo(l2.next, l1);\n return l2;\n }\n }\n}", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]\nOutput:[1,1,2,3,4,4,5,6]\nExplanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nfrom heapq import heappush,heappop\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n heap = []\n heapq.heapify(heap)\n start = end = ListNode(-1)\n for i in lists:\n if i:\n heappush(heap,(i.val,id(i),i))\n while heap:\n val,iD,node = heappop(heap)\n end.next = node\n node = node.next\n end = end.next\n if node:\n heappush(heap,(node.val,id(node),node))\n \n return start.next\n", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0 's. The beginning and end of the linked list will have Node.val == 0 . For every two consecutive 0 's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0 's. Return the head of the modified linked list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [3, 2 * 10^5 ] .", + "0 <= Node.val <= 1000", + "There are no two consecutive nodes with Node.val == 0 .", + "The beginning and end of the linked list have Node.val == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,3,1,0,4,5,2,0]\nOutput:[4,11]\nExplanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" + }, + { + "text": "Example 2: Input:head = [0,1,0,3,0,2,2,0]\nOutput:[1,3,4]\nExplanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeNodes(ListNode head) {\n ListNode newList=new ListNode(0);\n ListNode newHead=newList;\n ListNode newtemp= newList;\n/*---------------------------------------------------------------*/\n ListNode temp=head.next;\n int sum=0;\n if(head==null && head.next==null) return head;\n/*---------------------------------------------------------------*/ \n while(temp!=null){ //traverse linkelist\n sum +=temp.val; //sum elements until zero\n if(temp.val==0){\n ListNode node=new ListNode(sum); //create a new node; \n newtemp.next=node; //connect with dummy node which is created initially\n newtemp=newtemp.next; //shift pointer to newly created node\n sum=0; //reset sum\n }\n temp=temp.next;\n }\n/*---------------------------------------------------------------*/\n return newHead.next; //skip dummy node which is created initially\n }\n}\n", + "title": "2181. Merge Nodes in Between Zeros", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0 's. The beginning and end of the linked list will have Node.val == 0 . For every two consecutive 0 's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0 's. Return the head of the modified linked list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [3, 2 * 10^5 ] .", + "0 <= Node.val <= 1000", + "There are no two consecutive nodes with Node.val == 0 .", + "The beginning and end of the linked list have Node.val == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,3,1,0,4,5,2,0]\nOutput:[4,11]\nExplanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" + }, + { + "text": "Example 2: Input:head = [0,1,0,3,0,2,2,0]\nOutput:[1,3,4]\nExplanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n d=ListNode(0)\n t=0\n r=ListNode(0,d)\n while head:\n if head.val!=0:\n t+=head.val\n else:\n print(t)\n if t!=0:\n d.next=ListNode(t)\n d=d.next\n t=0\n head=head.next\n return r.next.next\n", + "title": "2181. Merge Nodes in Between Zeros", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 2D integer arrays, items1 and items2 , representing two sets of items. Each array items has the following properties: Return a 2D integer array ret where ret[i] = [value i , weight i ] , with weight i being the sum of weights of all items with value value i . Note: ret should be returned in ascending order by value.", + "description_images": [], + "constraints": [ + "items[i] = [value i , weight i ] where value i represents the value and weight i represents the weight of the i th item.", + "The value of each item in items is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]\nOutput:[[1,6],[3,9],[4,5]]\nExplanation:The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.\nThe item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.\nThe item with value = 4 occurs in items1 with weight = 5, total weight = 5. \nTherefore, we return [[1,6],[3,9],[4,5]].", + "image": null + }, + { + "text": "Example 2: Input:items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]\nOutput:[[1,4],[2,4],[3,4]]\nExplanation:The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.\nThe item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.\nThe item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.\nTherefore, we return [[1,4],[2,4],[3,4]].", + "image": null + }, + { + "text": "Example 3: Input:items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]\nOutput:[[1,7],[2,4],[7,1]]\nExplanation:The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. \nThe item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. \nThe item with value = 7 occurs in items2 with weight = 1, total weight = 1.\nTherefore, we return [[1,7],[2,4],[7,1]].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 72.74%) | Memory: 18.10 MB (Top 7.4%)\n\nclass Solution:\n\tdef mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n\n\t\tmerge_item = items1 + items2\n\n\t\td = defaultdict(int)\n\n\t\tfor i in merge_item:\n\t\t\tvalue,weight = i\n\t\t\td[value] = d[value] + weight\n\n\t\tresult = []\n\n\t\tfor j in sorted(d):\n\t\t\tresult.append([j,d[j]])\n\n\t\treturn result\n", + "title": "2363. Merge Similar Items", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n .", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput:[1,2,2,3,5,6]\nExplanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0\nOutput:[1]\nExplanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput:[1]\nExplanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n int i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n int k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n }\n}\n", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n .", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput:[1,2,2,3,5,6]\nExplanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0\nOutput:[1]\nExplanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput:[1]\nExplanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def merge(self, nums1, m, nums2, n):\n # Initialize nums1's index\n i = m - 1\n # Initialize nums2's index\n j = n - 1\n # Initialize a variable k to store the last index of the 1st array...\n k = m + n - 1\n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n k -= 1\n i -= 1\n else:\n nums1[k] = nums2[j]\n k -= 1\n j -= 1\n", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two strings word1 and word2 . Merge the strings by adding letters in alternating order, starting with word1 . If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 100", + "word1 and word2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"pqr\"\nOutput:\"apbqcr\"\nExplanation:The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"pqrs\"\nOutput:\"apbqrs\"\nExplanation:Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"abcd\", word2 = \"pq\"\nOutput:\"apbqcd\"\nExplanation:Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.63%) | Memory: 41.7 MB (Top 86.60%)\nclass Solution {\n public String mergeAlternately(String word1, String word2) {\n StringBuilder sb = new StringBuilder();\n int lenmax = Math.max(word1.length(),word2.length());\n for(int i=0;i<=lenmax-1;i++)\n {\n if(i bool:\n \n a, b, c = 0, 0, 0\n for i, (x, y, z) in enumerate(triplets):\n if not( x > target[0] or y > target[1] or z > target[2]):\n a, b, c = max(a, x), max(b, y), max(c, z)\n \n return [a, b, c] == target\n \n", + "title": "1899. Merge Triplets to Form Target Triplet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two binary trees root1 and root2 . Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return the merged tree . Note: The merging process must start from the root nodes of both trees.", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 2000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\nOutput:[3,4,5,5,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/05/merge.jpg" + }, + { + "text": "Example 2: Input:root1 = [1], root2 = [1,2]\nOutput:[2,2]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {\n if(root1==NULL) return root2;\n if(root2==NULL) return root1;\n root1->val+=root2->val;\n root1->left=mergeTrees(root1->left,root2->left);\n root1->right=mergeTrees(root1->right,root2->right);\n return root1;\n }\n};\n", + "title": "617. Merge Two Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the heads of two sorted linked lists list1 and list2 . Merge the two lists in a 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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]\nOutput:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 80.18%) | Memory: 43.5 MB (Top 22.48%)\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2)\n {\n if(list1==null && list2==null)\n return null;\n if(list1 == null)\n return list2;\n if(list2 == null)\n return list1;\n\n ListNode newHead = new ListNode();\n ListNode newNode = newHead;\n\n while(list1!=null && list2!=null)\n {\n //ListNode newNode = new ListNode();\n if(list1.val <= list2.val)\n {\n newNode.next = list1;\n list1 = list1.next;\n }\n else if(list1.val >= list2.val)\n {\n newNode.next = list2;\n list2 = list2.next;\n }\n newNode = newNode.next;\n }\n if(list1!=null)\n newNode.next = list1;\n else if(list2!=null)\n newNode.next = list2;\n return newHead.next;\n }\n}", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the heads of two sorted linked lists list1 and list2 . Merge the two lists in a 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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]\nOutput:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 43 ms (Top 67.2%) | Memory: 16.18 MB (Top 97.5%)\n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n cur = dummy = ListNode()\n while list1 and list2: \n if list1.val < list2.val:\n cur.next = list1\n list1, cur = list1.next, list1\n else:\n cur.next = list2\n list2, cur = list2.next, list2\n \n if list1 or list2:\n cur.next = list1 if list1 else list2\n \n return dummy.next", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return the middle node of the linked list . If there are two middle nodes, return the second middle node.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 100] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[3,4,5]\nExplanation:The middle node of the list is node 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6]\nOutput:[4,5,6]\nExplanation:Since the list has two middle nodes with values 3 and 4, we return the second one.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode middleNode(ListNode head) {\n \n ListNode temp = head;\n int size = 0;\n while(temp!=null){\n size++;\n temp = temp.next;\n }\n int mid = size/2;\n temp = head;\n for(int i=0;i int:\n\t\tcur = 0 \n\t\tdp0 = cost[0]\n\t\tif len(cost) >= 2:\n\t\t\tdp1 = cost[1]\n\n\t\tfor i in range(2, len(cost)):\n\t\t\tcur = cost[i] + min(dp0, dp1)\n\t\t\tdp0 = dp1\n\t\t\tdp1 = cur\n\n\t\treturn min(dp0, dp1)\n", + "title": "746. Min Cost Climbing Stairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= points.length <= 1000", + "-10^6 <= x i , y i <= 10^6", + "All pairs (x i , y i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput:20\nExplanation:We can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.", + "image": "https://assets.leetcode.com/uploads/2020/08/26/d.png" + }, + { + "text": "Example 2: Input:points = [[3,12],[-2,5],[-4,1]]\nOutput:18", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 99.32%) | Memory: 42.90 MB (Top 99.2%)\n\nclass Solution {\n public int minCostConnectPoints(int[][] points) {\n int len = points.length;\n // array that keep track of the shortest distance from mst to each node\n int[] disArr = new int[len];\n for (int i = 1; i < len; ++i) {\n disArr[i] = Integer.MAX_VALUE;\n }\n // visited[node] == true if node in mst\n boolean[] visited = new boolean[len];\n visited[0] = true;\n \n int numEdge = 0;\n // current node, used to update the disArr\n int cur = 0;\n // result\n int res = 0;\n \n while (numEdge++ < len - 1) {\n int minEdge = Integer.MAX_VALUE;\n int next = -1;\n for (int i = 0; i < len; ++i) {\n // if the node i is not in mst\n if (!visited[i]) {\n // find the distance between cur and i\n int dis = Math.abs(points[cur][0] - points[i][0]) + Math.abs(points[cur][1] - points[i][1]);\n // update distance array\n disArr[i] = Math.min(dis, disArr[i]);\n // find the shortest edge\n if (disArr[i] < minEdge) {\n minEdge = disArr[i];\n next = i;\n }\n }\n }\n cur = next;\n visited[cur] = true;\n res += minEdge;\n }\n \n return res;\n }\n}\n", + "title": "1584. Min Cost to Connect All Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= points.length <= 1000", + "-10^6 <= x i , y i <= 10^6", + "All pairs (x i , y i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput:20\nExplanation:We can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.", + "image": "https://assets.leetcode.com/uploads/2020/08/26/d.png" + }, + { + "text": "Example 2: Input:points = [[3,12],[-2,5],[-4,1]]\nOutput:18", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2922 ms (Top 60.17%) | Memory: 79.1 MB (Top 76.18%)\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n\n cost = 0\n heap = []\n\n #set to store past points to prevent cycle\n visited = set([0])\n\n #i == the index of current point\n i = 0\n\n while len(visited) < len(points):\n #Add all costs from current point to unreached points to min heap\n for j in range(len(points)):\n if j == i or j in visited:\n continue\n distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])\n heapq.heappush(heap, (distance, j))\n\n #Add new min cost edge\n while True:\n dist, point = heapq.heappop(heap)\n if point not in visited:\n cost += dist\n #Add point to visited to prevent cycle\n visited.add(point)\n #Update point\n i = point\n break\n\n return cost", + "title": "1584. Min Cost to Connect All Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums whose length is a power of 2 . Apply the following algorithm on nums : Return the last number that remains in nums after applying the algorithm.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1024", + "1 <= nums[i] <= 10^9", + "nums.length is a power of 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,2,4,8,2,2]\nOutput:1\nExplanation:The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.", + "image": "https://assets.leetcode.com/uploads/2022/04/13/example1drawio-1.png" + }, + { + "text": "Example 2: Input:nums = [3]\nOutput:3\nExplanation:3 is already the last remaining number, so we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.60 MB (Top 22.49%)\n\nclass Solution {\n public int minMaxGame(int[] nums) {\n int len=nums.length;\n if(len==1)\n return nums[0];\n int[] newNums=new int[len/2];\n int index=0;\n for(int i=0;i int:\n \n def solve(n):\n if n==1:\n return\n for i in range(n//2):\n if i%2:\n a[i] = max (a[2*i], a[2*i+1])\n else:\n a[i] = min (a[2*i], a[2*i+1])\n solve(n//2)\n return\n solve(len(a))\n return a[0]\n", + "title": "2293. Min Max Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: You must implement a solution with O(1) time complexity for each function.", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n[[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 117 ms (Top 35.13%) | Memory: 18.5 MB (Top 10.03%)\nclass MinStack:\n\n def __init__(self):\n self.stack = []\n\n def push(self, val: int) -> None:\n if not self.stack:\n self.stack.append((val, val))\n else:\n self.stack.append((val, min(val, self.stack[-1][1])))\n\n def pop(self) -> None:\n if self.stack:\n self.stack.pop()\n\n def top(self) -> int:\n if self.stack:\n return self.stack[-1][0]\n else:\n return None\n\n def getMin(self) -> int:\n if self.stack:\n return self.stack[-1][1]\n else:\n return None", + "title": "155. Min Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Let's play the minesweeper game ( Wikipedia , online game )! You are given an m x n char matrix board representing the game board where: You are also given an integer array click where click = [click r , click c ] represents the next click position among all the unrevealed squares ( 'M' or 'E' ). Return the board after revealing this position according to the following rules :", + "description_images": [], + "constraints": [ + "'M' represents an unrevealed mine,", + "'E' represents an unrevealed empty square,", + "'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),", + "digit ( '1' to '8' ) represents how many mines are adjacent to this revealed square, and", + "'X' represents a revealed mine." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]\nOutput:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" + }, + { + "text": "Example 2: Input:board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]\nOutput:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 100.00%)\nclass Solution {\n public char[][] updateBoard(char[][] board, int[] click) {\n int r = click[0];\n int c = click[1];\n if(board[r][c] == 'M')\n {\n board[r][c] = 'X';\n return board;\n }\n dfs(board, r, c);\n return board;\n }\n\n private void dfs(char[][]board, int r, int c)\n {\n if(r < 0 || r >= board.length || c >= board[0].length || c < 0 || board[r][c] == 'B')//Stop case\n return;\n int num = countMine(board, r, c);//count how many adjacent mines\n if(num != 0)\n {\n board[r][c] = (char)('0' + num);\n return;\n }\n else\n {\n board[r][c] = 'B';\n dfs(board, r + 1, c);//recursively search all neighbors\n dfs(board, r - 1, c);\n dfs(board, r, c + 1);\n dfs(board, r, c - 1);\n dfs(board, r - 1, c - 1);\n dfs(board, r + 1, c - 1);\n dfs(board, r - 1, c + 1);\n dfs(board, r + 1, c + 1);\n }\n }\n\n private int countMine(char[][]board, int r, int c)\n {\n int count = 0;\n for(int i = r - 1; i <= r + 1; ++i)\n {\n for(int j = c - 1; j <= c + 1; ++j)\n {\n if(i >= 0 && i < board.length && j >= 0 && j < board[0].length)\n {\n if(board[i][j] == 'M')\n count++;\n }\n }\n }\n return count;\n }\n}", + "title": "529. Minesweeper", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let's play the minesweeper game ( Wikipedia , online game )! You are given an m x n char matrix board representing the game board where: You are also given an integer array click where click = [click r , click c ] represents the next click position among all the unrevealed squares ( 'M' or 'E' ). Return the board after revealing this position according to the following rules :", + "description_images": [], + "constraints": [ + "'M' represents an unrevealed mine,", + "'E' represents an unrevealed empty square,", + "'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),", + "digit ( '1' to '8' ) represents how many mines are adjacent to this revealed square, and", + "'X' represents a revealed mine." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]\nOutput:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" + }, + { + "text": "Example 2: Input:board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]\nOutput:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def calMines(self,board,x,y):\n directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]\n mines = 0\n for d in directions:\n r, c = x+d[0],y+d[1]\n if self.isValid(board,r,c) and (board[r][c] == 'M' or board[r][c] == 'X'):\n mines+=1\n return mines\n\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n x,y = click[0],click[1]\n options = []\n if board[x][y] == \"M\":\n board[x][y] = \"X\"\n else:\n count = self.calMines(board,x,y)\n if count == 0:\n board[x][y] = \"B\"\n for r in range(x-1,x+2):\n for c in range(y-1,y+2):\n if self.isValid(board,r,c) and board[r][c]!='B':\n self.updateBoard(board,[r,c])\n else:\n board[x][y] = str(count)\n\n return board\n \n \n def isValid(self,board,a,b):\n return 0<=a NestedInteger:\n if s[0] == '[':\n res, i = self.dfs(1, s)\n return res\n else:\n num = int(s)\n res = NestedInteger()\n res.setInteger(num)\n return res\n", + "title": "385. Mini Parser", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations.", + "description_images": [], + "constraints": [ + "If the element is even , divide it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "If the element is odd , multiply it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:1\nExplanation:You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,5,20,3]\nOutput:3\nExplanation:You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,8]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 97.34%) | Memory: 51 MB (Top 91.49%)\nclass Solution {\n public int minimumDeviation(int[] nums) {\n TreeSet temp = new TreeSet<>();\n for(int i: nums){\n if(i % 2 == 0){\n temp.add(i);\n }\n else{\n temp.add(i * 2);\n }\n }\n\n int md = temp.last() - temp.first();\n int m = 0;\n\n while(temp.size() > 0 && temp.last() % 2 == 0){\n m = temp.last();\n temp.remove(m);\n temp.add(m / 2);\n\n md = Math.min(md, temp.last() - temp.first());\n }\n return md;\n }\n}", + "title": "1675. Minimize Deviation in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations.", + "description_images": [], + "constraints": [ + "If the element is even , divide it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "If the element is odd , multiply it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:1\nExplanation:You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,5,20,3]\nOutput:3\nExplanation:You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,8]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef minimumDeviation(self, nums: List[int]) -> int:\n\n\t\tfrom sortedcontainers import SortedList\n\n\t\tfor i in range(len(nums)):\n\n\t\t\tif nums[i]%2!=0:\n\t\t\t\tnums[i]=nums[i]*2\n\n\t\tnums = SortedList(nums)\n\n\t\tresult = 100000000000\n\n\t\twhile True:\n\t\t\tmin_value = nums[0]\n\t\t\tmax_value = nums[-1]\n\n\t\t\tif max_value % 2 == 0:\n\t\t\t\tnums.pop()\n\t\t\t\tnums.add(max_value // 2)\n\t\t\t\tmax_value = nums[-1]\n\t\t\t\tmin_value = nums[0]\n\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\telse:\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\t\tbreak\n\n\t\treturn result\n", + "title": "1675. Minimize Deviation in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays, source and target , both of length n . You are also given an array allowedSwaps where each allowedSwaps[i] = [a i , b i ] indicates that you are allowed to swap the elements at index a i and index b i (0-indexed) of array source . Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target , is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed) . Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source .", + "description_images": [], + "constraints": [ + "n == source.length == target.length", + "1 <= n <= 10^5", + "1 <= source[i], target[i] <= 10^5", + "0 <= allowedSwaps.length <= 10^5", + "allowedSwaps[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput:1\nExplanation:source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.", + "image": null + }, + { + "text": "Example 2: Input:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput:2\nExplanation:There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.", + "image": null + }, + { + "text": "Example 3: Input:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 98.25%) | Memory: 87.50 MB (Top 31.58%)\n\nclass Solution {\n public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {\n int[] line = new int[source.length];\n Arrays.fill(line, 100001);\n for (int[] swap : allowedSwaps) {\n int root0 = getRoot(line, swap[0]);\n int root1 = getRoot(line, swap[1]);\n int min = Integer.min(root0, root1);\n line[root0] = min;\n line[root1] = min;\n // for speed up\n line[swap[0]] = min;\n line[swap[1]] = min;\n }\n HashMap> pool = new HashMap<>();\n int different = 0;\n int noSwap = 0;\n for (int i = 0; i < line.length; i++) {\n if (line[i] == 100001) {\n if (source[i] != target[i]) {\n // not allow swap distance\n noSwap++;\n }\n continue;\n }\n Integer root = getRoot(line, i);\n if (!pool.containsKey(root)) {\n pool.put(root, new HashMap<>());\n }\n HashMap freq = pool.get(root);\n freq.put(source[i], freq.getOrDefault(source[i], 0)+1);\n freq.put(target[i], freq.getOrDefault(target[i], 0)-1);\n }\n for (HashMap freq : pool.values()) {\n for (Integer value : freq.values()) {\n different += Math.abs(value);\n }\n }\n // two different number mean one hamming distance\n return different/2+noSwap;\n }\n \n private int getRoot(int[] line, int index) {\n if (line[index] == 100001) {\n line[index] = index;\n return index;\n }\n if (line[index] == index) {\n return index;\n }\n return getRoot(line, line[index]);\n }\n}\n", + "title": "1722. Minimize Hamming Distance After Swap Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays, source and target , both of length n . You are also given an array allowedSwaps where each allowedSwaps[i] = [a i , b i ] indicates that you are allowed to swap the elements at index a i and index b i (0-indexed) of array source . Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target , is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed) . Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source .", + "description_images": [], + "constraints": [ + "n == source.length == target.length", + "1 <= n <= 10^5", + "1 <= source[i], target[i] <= 10^5", + "0 <= allowedSwaps.length <= 10^5", + "allowedSwaps[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput:1\nExplanation:source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.", + "image": null + }, + { + "text": "Example 2: Input:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput:2\nExplanation:There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.", + "image": null + }, + { + "text": "Example 3: Input:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1385 ms (Top 99.43%) | Memory: 59.9 MB (Top 71.02%)\nclass UnionFind:\n def __init__(self, n):\n self.roots = [i for i in range(n)]\n\n def find(self, v):\n if self.roots[v] != v:\n self.roots[v] = self.find(self.roots[v])\n\n return self.roots[v]\n\n def union(self, u, v):\n self.roots[self.find(u)] = self.find(v)\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for idx1, idx2 in allowedSwaps:\n uf.union(idx1, idx2)\n\n m = collections.defaultdict(set)\n for i in range(len(source)):\n m[uf.find(i)].add(i)\n\n res = 0\n for indices in m.values():\n freq = {}\n for i in indices:\n freq[source[i]] = freq.get(source[i], 0)+1\n freq[target[i]] = freq.get(target[i], 0)-1\n res += sum(val for val in freq.values() if val > 0)\n\n return res", + "title": "1722. Minimize Hamming Distance After Swap Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length <= n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 23.81%) | Memory: 127.5 MB (Top 49.76%)\nclass Solution {\n int[]parent;\n int[]size;\n\n public int minMalwareSpread(int[][] graph, int[] initial) {\n parent = new int[graph.length];\n size = new int[graph.length];\n for(int i=0;i ans_size){\n ans_i = i;\n ans_size = size[ri];\n }else if(size[ri] == ans_size){\n if(i < ans_i){\n ans_i = i;\n ans_size = size[ri];\n }\n }\n }\n }\n\n if(ans_i == -1){\n ans_i = graph.length;\n for(int i : initial){\n if(i < ans_i){\n ans_i = i;\n }\n }\n }\n\n return ans_i;\n\n }\n\n int find(int x){\n if(parent[x] == x){\n return x;\n }else{\n parent[x] = find(parent[x]);\n return parent[x];\n }\n }\n\n void unionHelper(int x,int y){\n int xl = find(x);\n int yl = find(y);\n\n if(size[xl] < size[yl]){\n parent[xl] = yl;\n size[yl] += size[xl];\n }else{\n parent[yl] = xl;\n size[xl] += size[yl];\n }\n }\n}", + "title": "924. Minimize Malware Spread", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length <= n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1782 ms (Top 87.91%) | Memory: 16.6 MB (Top 91.21%)\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n uf = UnionFind(n)\n for i in range(n):\n for j in range(n):\n if graph[i][j]:\n uf.union(i, j)\n\n max_remove = 0\n\n initial.sort()\n min_index = initial[0]\n for i in range(len(initial)):\n cur_remove = 0\n linked = False\n for j in range(len(initial)):\n if i == j: continue\n if uf.find(initial[i]) == uf.find(initial[j]):\n linked = True\n if not linked:\n cur_remove = uf.rank[uf.find(initial[i])]\n if max_remove < cur_remove:\n max_remove = cur_remove\n min_index = initial[i]\n\n return min_index\n\nclass UnionFind:\n def __init__(self, size):\n self.parent = {}\n self.rank = {}\n for i in range(size):\n self.parent[i] = i\n self.rank[i] = 1\n\n def find(self, x):\n if x != self.parent[x]:\n x = self.find(self.parent[x])\n return x\n\n def union(self, x, y):\n px, py = self.find(x), self.find(y)\n if px == py: return\n if self.rank[px] >= self.rank[py]:\n self.parent[py] = px\n self.rank[px] += self.rank[py]\n else:\n self.parent[px] = py\n self.rank[py] += self.rank[px]", + "title": "924. Minimize Malware Spread", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial , completely removing it and any connections from this node to any other node . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index .", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length < n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n int[] size;\n \n public int find(int x){\n if(parent[x]==x) return x;\n int f = find(parent[x]);\n parent[x] = f;\n return f;\n }\n \n void merge(int x, int y){\n if(size[x]>size[y]){\n parent[y] = x;\n size[x] += size[y];\n }else{\n parent[x] =y;\n size[y] +=size[x];\n }\n }\n \n public int minMalwareSpread(int[][] graph, int[] initial) {\n int n =graph.length;\n \n parent = new int[n];\n size= new int[n];\n // putting initially infected nodes in hashset to ignore them while making graph\n HashSet hs = new HashSet<>();\n for(int a : initial){\n hs.add(a);\n }\n //initializing Parent for DSU\n for(int i=0;i> map = new HashMap<>();\n //We need to ensure increase the count whenever a parent is influenced by initial Nodes...because if it influenced by more than one infectious node then it would still remain infectious.\n int[] infected = new int[n]; \n for(int e: initial){\n map.put(e,new HashSet<>());\n for(int j=0;j par = map.get(e);\n int total =0;\n for(int p: par){\n if(infected[p]==1){ //add to total only if influenced by only one infectious node.\n total+=size[p];\n }\n }\n if(total>=max){\n if(max==total){\n ans = Math.min(ans,e);\n }else{\n ans =e;\n }\n max =total;\n }\n }\n \n if(ans!=-1) return ans;\n //for returining smallest element.\n Arrays.sort(initial);\n \n return initial[0];\n \n }\n}\n", + "title": "928. Minimize Malware Spread II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial , completely removing it and any connections from this node to any other node . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index .", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length < n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nfrom collections import deque\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n G = defaultdict(list)\n for v in range(n):\n for w in range(n):\n if graph[v][w]:\n G[v].append(w)\n \n affect = defaultdict(list)\n for s in initial:\n visited = set([v for v in initial if v != s])\n que = deque([s])\n while que:\n v = que.popleft()\n if v in visited: continue\n visited.add(v)\n affect[v].append(s)\n for w in G[v]:\n que.append(w)\n res = [0]*n\n for v in affect:\n if len(affect[v]) == 1:\n res[affect[v].pop()] += 1\n if not max(res): return min(initial)\n return res.index(max(res))", + "title": "928. Minimize Malware Spread II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The pair sum of a pair (a,b) is equal to a + b . The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n , pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements .", + "description_images": [], + "constraints": [ + "For example, if we have pairs (1,5) , (2,3) , and (4,4) , the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,2,3]\nOutput:7\nExplanation:The elements can be paired up into pairs (3,3) and (5,2).\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,4,2,4,6]\nOutput:8\nExplanation:The elements can be paired up into pairs (3,5), (4,4), and (6,2).\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 89 ms (Top 12.88%) | Memory: 106.2 MB (Top 42.39%)\nclass Solution {\n public int minPairSum(int[] nums) {\n Arrays.sort(nums);\n\n int output = Integer.MIN_VALUE;\n\n //This is greedy, so n/2 pairs must be from start and end and move inwards\n for(int i=0, j=nums.length - 1; i int:\n pair_sum = []\n nums.sort()\n for i in range(len(nums)//2):\n pair_sum.append(nums[i]+nums[len(nums)-i-1])\n return max(pair_sum)\n", + "title": "1877. Minimize Maximum Pair Sum in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string expression of the form \"+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+' . Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.", + "description_images": [], + "constraints": [ + "3 <= expression.length <= 10", + "expression consists of digits from '1' to '9' and '+' .", + "expression starts and ends with digits.", + "expression contains exactly one '+' .", + "The original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"247+38\"\nOutput:\"2(47+38)\"\nExplanation:Theexpressionevaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the'+'.\nIt can be shown that 170 is the smallest possible value.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"12+34\"\nOutput:\"1(2+3)4\"\nExplanation:The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"999+999\"\nOutput:\"(999+999)\"\nExplanation:Theexpressionevaluates to 999 + 999 = 1998.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 39.1%) | Memory: 41.03 MB (Top 42.0%)\n\nclass Solution {\n public String minimizeResult(String expression) {\n String[] sp = expression.split(\"\\\\+\");\n String left = sp[0];\n String right = sp[1];\n \n int min = Integer.MAX_VALUE;\n String result = \"(\" + expression + \")\";\n\t\t\n for(int i=0; i+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+' . Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.", + "description_images": [], + "constraints": [ + "3 <= expression.length <= 10", + "expression consists of digits from '1' to '9' and '+' .", + "expression starts and ends with digits.", + "expression contains exactly one '+' .", + "The original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"247+38\"\nOutput:\"2(47+38)\"\nExplanation:Theexpressionevaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the'+'.\nIt can be shown that 170 is the smallest possible value.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"12+34\"\nOutput:\"1(2+3)4\"\nExplanation:The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"999+999\"\nOutput:\"(999+999)\"\nExplanation:Theexpressionevaluates to 999 + 999 = 1998.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimizeResult(self, expression: str) -> str:\n plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression] \n def evaluate(exps: str):\n return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*'))\n for l in range(plus_index):\n for r in range(plus_index+1, n):\n exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}'\n res = evaluate(exps)\n if ans[0] > res:\n ans[0], ans[1] = res, exps\n return ans[1]\n", + "title": "2232. Minimize Result by Adding Parentheses to Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix mat and an integer target . Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized . Return the minimum absolute difference . The absolute difference between two numbers a and b is the absolute value of a - b .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 70", + "1 <= mat[i][j] <= 70", + "1 <= target <= 800" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput:0\nExplanation:One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1.png" + }, + { + "text": "Example 2: Input:mat = [[1],[2],[3]], target = 100\nOutput:94\nExplanation:The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-1.png" + }, + { + "text": "Example 3: Input:mat = [[1,2,9,8,7]], target = 6\nOutput:1\nExplanation:The best choice is to choose 7 from the first row.\nThe absolute difference is 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1407 ms (Top 25.79%) | Memory: 92.6 MB (Top 35.19%)\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Integer[][] dp = new Integer[mat.length][5001];\n return minDiff(mat, 0, target,0, dp);\n }\n\n public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){\n if(index == mat.length){\n return Math.abs(val - target);\n }\n if(dp[index][val] != null){\n return dp[index][val];\n }\n\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < mat[0].length; i++){\n res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));\n }\n\n return dp[index][val] = res;\n }\n}", + "title": "1981. Minimize the Difference Between Target and Chosen Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n integer matrix mat and an integer target . Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized . Return the minimum absolute difference . The absolute difference between two numbers a and b is the absolute value of a - b .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 70", + "1 <= mat[i][j] <= 70", + "1 <= target <= 800" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput:0\nExplanation:One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1.png" + }, + { + "text": "Example 2: Input:mat = [[1],[2],[3]], target = 100\nOutput:94\nExplanation:The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-1.png" + }, + { + "text": "Example 3: Input:mat = [[1,2,9,8,7]], target = 6\nOutput:1\nExplanation:The best choice is to choose 7 from the first row.\nThe absolute difference is 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 2497 ms (Top 82.35%) | Memory: 20.40 MB (Top 18.04%)\n\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float(\"inf\")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float(\"inf\")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float(\"inf\")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)\n", + "title": "1981. Minimize the Difference Between Target and Chosen Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities , where quantities[i] represents the number of products of the i th product type. You need to distribute all products to the retail stores following these rules: Return the minimum possible x .", + "description_images": [], + "constraints": [ + "A store can only be given at most one product type but can be given any amount of it.", + "After distribution, each store will have been given some number of products (possibly 0 ). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, quantities = [11,6]\nOutput:3\nExplanation:One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 7, quantities = [15,10,10]\nOutput:5\nExplanation:One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.", + "image": null + }, + { + "text": "Example 3: Input:n = 1, quantities = [100000]\nOutput:100000\nExplanation:The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimizedMaximum(int n, int[] quantities) {\n \n int lo = 1;\n int hi = (int)1e5;\n \n int ans = -1;\n \n while(lo <= hi){\n \n int mid = (lo + hi)/2;\n \n if(isItPossible(mid, quantities, n)){\n ans = mid;\n hi = mid-1;\n }else{\n lo = mid+1;\n }\n }\n \n return ans;\n }\n \n private boolean isItPossible(int x, int[] quantities, int n){\n \n // isItPossible to distribute <= x products to each of the n shops\n for(int i=0; i int:\n def cond(m, n):\n return sum([(q // m) + (q % m > 0) for q in quantities]) <= n\n \n l, r = 1, max(quantities)\n while l < r:\n m = (l + r) // 2\n if cond(m, n):\n r = m\n else:\n l = m + 1\n return l\n", + "title": "2064. Minimized Maximum of Products Distributed to Any Store", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of distinct integers arr , find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows", + "description_images": [], + "constraints": [ + "a, b are from arr", + "a < b", + "b - a equals to the minimum absolute difference of any two elements in arr" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,1,3]\nOutput:[[1,2],[2,3],[3,4]]\nExplanation:The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,6,10,15]\nOutput:[[1,3]]", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,8,-10,23,19,-4,-14,27]\nOutput:[[-14,-10],[19,23],[23,27]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 78.7%) | Memory: 55.94 MB (Top 56.9%)\n\nclass Solution {\n public List> minimumAbsDifference(int[] arr) {\n List> ans=new ArrayList<>();\n Arrays.sort(arr);\n int min=Integer.MAX_VALUE;\n for(int i=0;i pair=new ArrayList<>(2);\n pair.add(arr[i]);\n pair.add(arr[i+1]);\n ans.add(pair);\n }\n }\n return ans;\n }\n}", + "title": "1200. Minimum Absolute Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of distinct integers arr , find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows", + "description_images": [], + "constraints": [ + "a, b are from arr", + "a < b", + "b - a equals to the minimum absolute difference of any two elements in arr" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,1,3]\nOutput:[[1,2],[2,3],[3,4]]\nExplanation:The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,6,10,15]\nOutput:[[1,3]]", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,8,-10,23,19,-4,-14,27]\nOutput:[[-14,-10],[19,23],[23,27]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 574 ms (Top 47.47%) | Memory: 28.9 MB (Top 58.47%)\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n diff=float(inf)\n for i in range(0,len(arr)-1):\n if arr[i+1]-arr[i] int:\n cur, stack, minDiff, prev = root, [], 10**5, -10**5\n \n while stack or cur:\n while cur:\n stack.append(cur)\n cur = cur.left\n node = stack.pop()\n minDiff = min(minDiff, node.val - prev)\n prev = node.val\n cur = node.right\n \n return minDiff", + "title": "530. Minimum Absolute Difference in BST", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]| , where 0 <= i < j < a.length and a[i] != a[j] . If all elements of a are the same , the minimum absolute difference is -1 . You are given an integer array nums and the array queries where queries[i] = [l i , r i ] . For each query i , compute the minimum absolute difference of the subarray nums[l i ...r i ] containing the elements of nums between the 0-based indices l i and r i ( inclusive ). Return an array ans where ans[i] is the answer to the i th query . A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "For example, the minimum absolute difference of the array [5, 2 , 3 ,7,2] is |2 - 3| = 1 . Note that it is not 0 because a[i] and a[j] must be different." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput:[2,1,4,1]\nExplanation:The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput:[-1,1,1,3]\nExplanation:The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 152 ms (Top 66.6%) | Memory: 154.57 MB (Top 22.2%)\n\nclass Solution {\n public int[] minDifference(int[] nums, int[][] queries) {\n int n = nums.length;\n int[][] count = new int[n + 1][100];\n int q = queries.length;\n int ans[] = new int[q];\n \n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < 100; ++j)\n count[i + 1][j] = count[i][j];\n \n ++count[i + 1][nums[i] - 1];\n }\n \n for(int i = 0; i < q; ++i) {\n int low = queries[i][0];\n int high = queries[i][1] + 1;\n List present = new ArrayList<>();\n int min = 100;\n \n for(int j = 0; j < 100; ++j)\n if(count[high][j] - count[low][j] != 0)\n present.add(j);\n \n for(int j = 1; j < present.size(); ++j)\n min = Math.min(min, present.get(j) - present.get(j - 1));\n \n if(present.size() == 1)\n min = -1;\n \n ans[i] = min;\n }\n \n return ans;\n }\n}", + "title": "1906. Minimum Absolute Difference Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]| , where 0 <= i < j < a.length and a[i] != a[j] . If all elements of a are the same , the minimum absolute difference is -1 . You are given an integer array nums and the array queries where queries[i] = [l i , r i ] . For each query i , compute the minimum absolute difference of the subarray nums[l i ...r i ] containing the elements of nums between the 0-based indices l i and r i ( inclusive ). Return an array ans where ans[i] is the answer to the i th query . A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "For example, the minimum absolute difference of the array [5, 2 , 3 ,7,2] is |2 - 3| = 1 . Note that it is not 0 because a[i] and a[j] must be different." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput:[2,1,4,1]\nExplanation:The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput:[-1,1,1,3]\nExplanation:The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n # location of number\n loc = defaultdict(list)\n for i, num in enumerate(nums):\n loc[num].append(i)\n \n # start from sorted key thus keep tracking minimum difference\n k = sorted(loc)\n \n res = []\n for a, b in queries:\n cands = []\n ans = float('inf')\n for c in k:\n # left and right range overlap means no available locations in range\n if bisect.bisect_left(loc[c], a) == bisect.bisect(loc[c], b): continue\n if cands: \n\t\t\t\t\tans = min(ans, c - cands[-1])\n cands.append(c)\n if ans == float('inf'): ans = -1\n res.append(ans)\n return res", + "title": "1906. Minimum Absolute Difference Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two positive integer arrays nums1 and nums2 , both of length n . The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n ( 0-indexed ). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1 . Since the answer may be large, return it modulo 10^9 + 7 . |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0 , or", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,5], nums2 = [2,3,5]\nOutput:3\nExplanation:There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of|1-2| + (|1-3| or |5-3|) + |5-5| =3.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput:0\nExplanation:nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput:20\nExplanation:Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {\n int mod = (int)1e9+7;\n\n // Sorted copy of nums1 to use for binary search\n int[] snums1 = nums1.clone();\n Arrays.sort(snums1);\n \n int maxDiff = 0; // maximum difference between original and new absolute diff\n int pos = 0; // where the maximum difference occurs\n int newn1 = 0; // nums1 value to copy to nums1[pos]\n\n // For each array position i from 0 to n-1, find up to two elements\n // in nums1 that are closest to nums2[i] (one on each side of nums2[i]).\n // Calculate a new absolute difference for each of these elements.\n for (int i=0; i Integer.MIN_VALUE) {\n // If a valid element exists, calculate a new absolute difference\n // at the current position, and calculate how much smaller this is\n // than the current absolute difference. If the result is better\n // than what we have seen so far, update the maximum difference and\n // save the data for the current position.\n int newDiff = Math.abs(floor - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = floor;\n maxDiff = diff;\n }\n }\n \n // Find the smallest element in nums1 that is greater than or equal to\n // the current element in nums2, if such an element exists.\n int ceiling = arrayCeiling(snums1, n2);\n if (ceiling < Integer.MAX_VALUE) {\n // Same as above\n int newDiff = Math.abs(ceiling - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = ceiling;\n maxDiff = diff;\n }\n }\n }\n\n // If we found a replacement value, overwrite the original value.\n if (newn1 > 0) {\n nums1[pos] = newn1;\n }\n \n // Calculate the absolute sum difference with the replaced value.\n int sum = 0;\n for (int i=0; i= val) {\n min = arr[mid];\n hi = mid-1;\n } else {\n lo = mid+1;\n }\n }\n \n return min;\n }\n}\n", + "title": "1818. Minimum Absolute Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive integer arrays nums1 and nums2 , both of length n . The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n ( 0-indexed ). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1 . Since the answer may be large, return it modulo 10^9 + 7 . |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0 , or", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,5], nums2 = [2,3,5]\nOutput:3\nExplanation:There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of|1-2| + (|1-3| or |5-3|) + |5-5| =3.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput:0\nExplanation:nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput:20\nExplanation:Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2682 ms (Top 14.06%) | Memory: 30 MB (Top 26.09%)\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n diff = []\n sum = 0\n for i in range(n):\n temp = abs(nums1[i]-nums2[i])\n diff.append(temp)\n sum += temp\n nums1.sort()\n best_diff = []\n for i in range(n):\n idx = bisect.bisect_left(nums1, nums2[i])\n if idx != 0 and idx != n:\n best_diff.append(\n min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n elif idx == 0:\n best_diff.append(abs(nums2[i]-nums1[idx]))\n else:\n best_diff.append(abs(nums2[i]-nums1[idx-1]))\n saved = 0\n for i in range(n):\n saved = max(saved, diff[i]-best_diff[i])\n return (sum-saved) % ((10**9)+(7))", + "title": "1818. Minimum Absolute Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A parentheses string is valid if and only if: You are given a parentheses string s . In one move, you can insert a parenthesis at any position of the string. Return the minimum number of moves required to make s valid .", + "description_images": [], + "constraints": [ + "It is the empty string,", + "It can be written as AB ( A concatenated with B ), where A and B are valid strings, or", + "It can be written as (A) , where A is a valid string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"())\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(((\"\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minAddToMakeValid(String s) {\n int open = 0;\n int extra = 0;\n for(int i=0;i int:\n l, r = list(), list()\n for i in s:\n if i == \"(\":\n l.append(i)\n else:\n if l:\n l.pop()\n else:\n r.append(i)\n return len(l) + len(r)\n", + "title": "921. Minimum Add to Make Parentheses Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array, nums , and an integer k . nums comprises of only 0 's and 1 's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1 's .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is 0 or 1 .", + "1 <= k <= sum(nums)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,0,1,0,1], k = 2\nOutput:1\nExplanation:In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,0,0,0,0,1,1], k = 3\nOutput:5\nExplanation:In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,1], k = 2\nOutput:0\nExplanation:nums already has 2 consecutive 1's.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 32.47%) | Memory: 112.8 MB (Top 59.74%)\nclass Solution {\n public int minMoves(int[] nums, int k) {\n var gaps = new ArrayList();\n for(int i = 0, last = -1; i < nums.length; ++i){\n if (nums[i] == 1){\n if (last > -1){\n gaps.add(i-1-last);\n }\n last = i;\n }\n }\n int lsum = 0, rsum = 0, wlsum = 0, wrsum = 0;\n for(int i = k/2-1; i >= 0; --i){\n lsum += gaps.get(i);//lsum = 3+0\n wlsum += lsum;//wlsum = 1*3+2*0\n }\n for(int i = k/2; i < k-1; ++i){\n rsum += gaps.get(i);//rsum = 2+5\n wrsum += rsum;//wrsum = 2*2+1*5\n }\n int ans = wlsum+wrsum;\n for(int p = 0, q = k/2, r = k-1; r < gaps.size(); ++p, ++q, ++r){\n wlsum += (k/2)*gaps.get(q) - lsum;\n lsum += gaps.get(q) - gaps.get(p);\n\n rsum += gaps.get(r) - gaps.get(q);\n wrsum += rsum-((k-1)/2)*gaps.get(q);\n\n ans = Math.min(ans,wlsum+wrsum);\n }\n return ans;\n }\n}", + "title": "1703. Minimum Adjacent Swaps for K Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array, nums , and an integer k . nums comprises of only 0 's and 1 's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1 's .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is 0 or 1 .", + "1 <= k <= sum(nums)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,0,1,0,1], k = 2\nOutput:1\nExplanation:In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,0,0,0,0,1,1], k = 3\nOutput:5\nExplanation:In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,1], k = 2\nOutput:0\nExplanation:nums already has 2 consecutive 1's.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n p = [i for i, v in enumerate(nums) if v == 1]\n # p[i]: the position of i-th 1\n n = len(p)\n presum = [0]*(n+1)\n # presum[i]: sum(p[0]...p[i-1])\n for i in range(n):\n presum[i+1] = presum[i]+p[i]\n\n res = inf\n\n # sliding window\n if k % 2 == 1:\n # if odd\n radius = (k-1)//2\n for i in range(radius, n-radius):\n # i-radius ... i ... i+radius\n # move radius to i\n # i+1, ..., i+radius\n right = presum[i+radius+1]-presum[i+1]\n # i-radius, ..., i-1\n left = presum[i]-presum[i-radius]\n res = min(res, right-left)\n return res-radius*(radius+1)\n else:\n # even\n radius = (k-2)//2\n for i in range(radius, n-radius-1):\n # i-radius ... i i+1 ... i+radius+1\n # move radius to i (moving to i+1 is also OK)\n # i+1, ..., i+radius+1\n right = presum[i+radius+2]-presum[i+1]\n # i-radius, ..., i-1\n left = presum[i]-presum[i-radius]\n res = min(res, right-left-p[i])\n return res-radius*(radius+1)-(radius+1)\n", + "title": "1703. Minimum Adjacent Swaps for K Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num , representing a large integer, and an integer k . We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num . There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k th smallest wonderful integer . The tests are generated in such a way that k th smallest wonderful integer exists.", + "description_images": [], + "constraints": [ + "For example, when num = \"5489355142\" : The 1 st smallest wonderful integer is \"5489355214\" . The 2 nd smallest wonderful integer is \"5489355241\" . The 3 rd smallest wonderful integer is \"5489355412\" . The 4 th smallest wonderful integer is \"5489355421\" .", + "The 1 st smallest wonderful integer is \"5489355214\" .", + "The 2 nd smallest wonderful integer is \"5489355241\" .", + "The 3 rd smallest wonderful integer is \"5489355412\" .", + "The 4 th smallest wonderful integer is \"5489355421\" ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5489355142\", k = 4\nOutput:2\nExplanation:The 4thsmallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"", + "image": null + }, + { + "text": "Example 2: Input:num = \"11112\", k = 4\nOutput:4\nExplanation:The 4thsmallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"", + "image": null + }, + { + "text": "Example 3: Input:num = \"00123\", k = 1\nOutput:1\nExplanation:The 1stsmallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 61.80%) | Memory: 42.9 MB (Top 13.48%)\nclass Solution {\n public int getMinSwaps(String num, int k) {\n int[] nums=new int[num.length()];\n int[] org=new int[num.length()];\n\n for(int i=0;i0 && j!=i){\n swap(org,j,j-1);\n ans++;\n j--;\n }\n\n }\n\n }\n\n return ans;\n\n }\n\npublic void nextPermutation(int[] nums) {\n\n if(nums.length<=1)\n return;\n\n int j=nums.length-2;\n while(j>=0 && nums[j]>=nums[j+1])\n j--;\n\n if(j>=0){\n int k=nums.length-1;\n while(nums[j]>=nums[k])\n k--;\n\n swap(nums,j,k);\n\n }\n\n reverse(nums,j+1,nums.length-1);\n\n }\n\n public void swap(int[] nums,int j,int k){\n int temp=nums[j];\n nums[j]=nums[k];\n nums[k]=temp;\n }\n\n public void reverse(int[] nums,int i,int j){\n while(i<=j){\n swap(nums,i,j);\n i++;\n j--;\n }\n }\n}", + "title": "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num , representing a large integer, and an integer k . We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num . There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k th smallest wonderful integer . The tests are generated in such a way that k th smallest wonderful integer exists.", + "description_images": [], + "constraints": [ + "For example, when num = \"5489355142\" : The 1 st smallest wonderful integer is \"5489355214\" . The 2 nd smallest wonderful integer is \"5489355241\" . The 3 rd smallest wonderful integer is \"5489355412\" . The 4 th smallest wonderful integer is \"5489355421\" .", + "The 1 st smallest wonderful integer is \"5489355214\" .", + "The 2 nd smallest wonderful integer is \"5489355241\" .", + "The 3 rd smallest wonderful integer is \"5489355412\" .", + "The 4 th smallest wonderful integer is \"5489355421\" ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5489355142\", k = 4\nOutput:2\nExplanation:The 4thsmallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"", + "image": null + }, + { + "text": "Example 2: Input:num = \"11112\", k = 4\nOutput:4\nExplanation:The 4thsmallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"", + "image": null + }, + { + "text": "Example 3: Input:num = \"00123\", k = 1\nOutput:1\nExplanation:The 1stsmallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1243 ms (Top 52.9%) | Memory: 16.52 MB (Top 32.4%)\n\nclass Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n num = list(num)\n orig = num.copy()\n \n for _ in range(k): \n for i in reversed(range(len(num)-1)): \n if num[i] < num[i+1]: \n ii = i+1 \n while ii < len(num) and num[i] < num[ii]: ii += 1\n num[i], num[ii-1] = num[ii-1], num[i]\n lo, hi = i+1, len(num)-1\n while lo < hi: \n num[lo], num[hi] = num[hi], num[lo]\n lo += 1\n hi -= 1\n break \n \n ans = 0\n for i in range(len(num)): \n ii = i\n while orig[i] != num[i]: \n ans += 1\n ii += 1\n num[i], num[ii] = num[ii], num[i]\n return ans ", + "title": "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0] , amount[1] , and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups .", + "description_images": [], + "constraints": [ + "amount.length == 3", + "0 <= amount[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:amount = [1,4,2]\nOutput:4\nExplanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.", + "image": null + }, + { + "text": "Example 2: Input:amount = [5,4,4]\nOutput:7\nExplanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.", + "image": null + }, + { + "text": "Example 3: Input:amount = [5,0,0]\nOutput:5\nExplanation:Every second, we fill up a cold cup.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 59.66%) | Memory: 41.5 MB (Top 48.39%)\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z){return sum/2 +sum%2;}\n if(x==0&&y==0){return z;}\n else{return z;}\n }\n}", + "title": "2335. Minimum Amount of Time to Fill Cups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0] , amount[1] , and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups .", + "description_images": [], + "constraints": [ + "amount.length == 3", + "0 <= amount[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:amount = [1,4,2]\nOutput:4\nExplanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.", + "image": null + }, + { + "text": "Example 2: Input:amount = [5,4,4]\nOutput:7\nExplanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.", + "image": null + }, + { + "text": "Example 3: Input:amount = [5,0,0]\nOutput:5\nExplanation:Every second, we fill up a cold cup.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 62.11%) | Memory: 13.9 MB (Top 56.09%)\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n\n count = 0\n amount = sorted(amount, reverse=True)\n while amount[0] > 0:\n amount[0] -= 1\n amount[1] -= 1\n count += 1\n amount = sorted(amount, reverse=True)\n return count", + "title": "2335. Minimum Amount of Time to Fill Cups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes . If there is not any such rectangle, return 0 .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 500", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/08/03/rec1.JPG" + }, + { + "text": "Example 2: Input:points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/08/03/rec2.JPG" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 98.98%) | Memory: 45.00 MB (Top 39.53%)\n\nclass Solution {\n public int minAreaRect(int[][] points) {\n HashMap> hm = new HashMap<>();\n int area=Integer.MAX_VALUE;\n \n for(int[] point: points)\n { \n if(!hm.containsKey(point[0]))\n hm.put(point[0],new HashSet()); \n hm.get(point[0]).add(point[1]); // x-coordinate already exits, just add the y-coordinate to the set\n }\n \n for(int i=0;iMath.abs((x2-x1) * (y2-y1))) //pre-calulate the area to avoid unecessary lookup. This step reduced the time from 186ms to 57ms.\n {\n if(hm.get(x1).contains(y2) && hm.get(x2).contains(y1)) // learnt from other leetcoders. Thank you.\n area=Math.abs((x2-x1) * (y2-y1)); \n }\n }\n \n }\n }\n \n return area int:\n points = sorted(points, key=lambda item: (item[0], item[1]))\n cols = defaultdict(list)\n \n for x,y in points:\n cols[x].append(y)\n \n lastx = {}\n ans = float('inf')\n \n for x in cols:\n col = cols[x]\n for i, y1 in enumerate(col):\n for j in range(i):\n y2 = col[j]\n if (y2,y1) in lastx:\n ans = min(ans, abs((x-lastx[y2,y1])*(y2-y1)))\n lastx[y2,y1] = x\n \n return 0 if ans==float('inf') else ans", + "title": "939. Minimum Area Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes . If there is not any such rectangle, return 0 . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= points.length <= 50", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2],[2,1],[1,0],[0,1]]\nOutput:2.00000\nExplanation:The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.", + "image": "https://assets.leetcode.com/uploads/2018/12/21/1a.png" + }, + { + "text": "Example 2: Input:points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput:1.00000\nExplanation:The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/2.png" + }, + { + "text": "Example 3: Input:points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput:0\nExplanation:There is no possible rectangle to form from these points.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 66.67%) | Memory: 56.7 MB (Top 16.67%)\nclass Solution {\n public double minAreaFreeRect(int[][] points) {\n Map, Map>> map = new HashMap<>();\n\n double res = Double.MAX_VALUE;\n for (int i = 0; i < points.length; i++) {\n int[] p1 = points[i];\n for (int j = i+1; j < points.length; j++) {\n int[] p2 = points[j];\n // get mid point\n Pair pm = new Pair((p1[0]+p2[0])/2d, (p1[1]+p2[1])/2d);\n if (!map.containsKey(pm))\n map.put(pm, new HashMap<>());\n // get diagonal length\n double dist2 = dist2(p1, p2);\n if (!map.get(pm).containsKey(dist2))\n map.get(pm).put(dist2, new ArrayList<>());\n\n // calculate area for each pair of p3/p4 and check min\n // Worst case is each pair has same mid point with same length\n // At worst case, below operation costs O(N)\n for (int[][] ps : map.get(pm).get(dist2)) {\n double d1 = dist2(p1, ps[0]);\n double d2 = dist2(p1, ps[1]);\n res = Math.min(res, Math.sqrt(d1 * d2));\n }\n map.get(pm).get(dist2).add(new int[][]{p1, p2});\n }\n }\n\n return res == Double.MAX_VALUE ? 0 : res;\n }\n\n private double dist2(int[] p1, int[] p2) {\n return (p2[0]-p1[0])*(p2[0]-p1[0]) + (p2[1]-p1[1])*(p2[1]-p1[1]);\n }\n}", + "title": "963. Minimum Area Rectangle II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes . If there is not any such rectangle, return 0 . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "1 <= points.length <= 50", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2],[2,1],[1,0],[0,1]]\nOutput:2.00000\nExplanation:The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.", + "image": "https://assets.leetcode.com/uploads/2018/12/21/1a.png" + }, + { + "text": "Example 2: Input:points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput:1.00000\nExplanation:The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/2.png" + }, + { + "text": "Example 3: Input:points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput:0\nExplanation:There is no possible rectangle to form from these points.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n N = len(points)\n \n seen = set()\n for point in points:\n seen.add(tuple(point))\n\n # length^2\n def length2(a, b):\n return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])\n \n best = 1e30\n for i in range(N):\n for j in range(N):\n if i == j:\n continue\n \n lij = length2(points[i], points[j])\n for k in range(N):\n if i == k or j == k:\n continue\n \n # given i->j line, add to k to find l\n dx, dy = points[j][0] - points[i][0], points[j][1] - points[i][1]\n \n pl = (points[k][0] + dx, points[k][1] + dy)\n if pl not in seen:\n continue\n \n lik = length2(points[i], points[k])\n ljk = length2(points[j], points[k])\n\n lil = length2(points[i], pl)\n ljl = length2(points[j], pl)\n lkl = length2(points[k], pl)\n \n if lij == lkl and lik == ljl and lil == ljk:\n best = min(best, sqrt(lij * lik * lil) / sqrt(max(lij, lik, lil)))\n \n if best >= 1e29:\n return 0\n return best\n", + "title": "963. Minimum Area Rectangle II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s1 and s2 , return the lowest ASCII sum of deleted characters to make two strings equal .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 1000", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"sea\", s2 = \"eat\"\nOutput:231\nExplanation:Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\nDeleting \"t\" from \"eat\" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"delete\", s2 = \"leet\"\nOutput:403\nExplanation:Deleting \"dee\" from \"delete\" to turn the string into \"let\",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting \"e\" from \"leet\" adds 101[e] to the sum.\nAt the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4020 ms (Top 5.03%) | Memory: 205.5 MB (Top 14.36%)\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n m, n, lookup = len(s1), len(s2), {}\n def fun(i, j):\n if (i,j) in lookup:\n return lookup[(i,j)]\n if i < 0:\n return sum([ord(char) for char in s2[:j+1]])\n if j < 0:\n return sum([ord(char) for char in s1[:i+1]])\n if s1[i] == s2[j]:\n res = fun(i-1, j-1)\n else:\n res = min(ord(s1[i]) + fun(i-1,j), ord(s2[j]) + fun(i,j-1))\n lookup[(i,j)] = res\n return lookup[(i,j)]\n return fun(m-1, n-1)", + "title": "712. Minimum ASCII Delete Sum for Two Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimum average difference . If there are multiple such indices, return the smallest one. Note:", + "description_images": [], + "constraints": [ + "The absolute difference of two numbers is the absolute value of their difference.", + "The average of n elements is the sum of the n elements divided ( integer division ) by n .", + "The average of 0 elements is considered to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,3,9,5,3]\nOutput:3\nExplanation:- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:0\nExplanation:The only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 34.34%) | Memory: 76.7 MB (Top 35.00%)\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n if(nums.length == 1){\n return 0;\n }\n int idx = -1;\n long min = Integer.MAX_VALUE;\n long suml = nums[0];\n long sumr = 0;\n for(int i = 1; i < nums.length; i++){\n sumr += nums[i];\n }\n int i = 1;\n int calc = 0;\n int left = 1;\n int right = nums.length - left;\n long[] arr = new long[nums.length];\n while(i < nums.length){\n long diff = Math.abs((suml/left) - (sumr/right));\n arr[calc] = diff;\n if(diff < min){\n min = diff;\n idx = calc;\n }\n suml += nums[i];\n sumr -= nums[i];\n left++;\n right--;\n calc++;\n i++;\n }\n arr[calc] = suml/nums.length;\n if(arr[calc] < min){\n min = arr[calc];\n idx = nums.length - 1;\n }\n // for(i = 0; i < nums.length; i++){\n // System.out.println(arr[i]);\n // }\n return (int)idx;\n }\n}", + "title": "2256. Minimum Average Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimum average difference . If there are multiple such indices, return the smallest one. Note:", + "description_images": [], + "constraints": [ + "The absolute difference of two numbers is the absolute value of their difference.", + "The average of n elements is the sum of the n elements divided ( integer division ) by n .", + "The average of 0 elements is considered to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,3,9,5,3]\nOutput:3\nExplanation:- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:0\nExplanation:The only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n size = len(nums)\n\n nums[::] = list(accumulate(nums))\n total = nums[-1]\n \n min_tuple = [0, sys.maxsize]\n \n for (i, n) in enumerate(nums):\n i = i + 1\n avg_i = floor(n/i)\n \n diff = size - i\n total_avg = floor((total - n) / (diff if diff>0 else 1))\n\n avg = abs( avg_i - total_avg) \n if min_tuple[1] > avg:\n min_tuple[1] = avg\n min_tuple[0] = i - 1\n \n return min_tuple[0]\n", + "title": "2256. Minimum Average Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Given two integers start and goal , return the minimum number of bit flips to convert start to goal .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:start = 10, goal = 7\nOutput:3\nExplanation:The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010-> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right:1111 ->0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:start = 3, goal = 4\nOutput:3\nExplanation:The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011-> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right:000 ->100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic static int minBitFlips(int a1, int a2) {\n\t\tint n = (a1 ^ a2);\n\t\tint res = 0;\n\t\twhile (n != 0) {\n\t\t\tres++;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn res;\n\t}\n}", + "title": "2220. Minimum Bit Flips to Convert Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 . Given two integers start and goal , return the minimum number of bit flips to convert start to goal .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:start = 10, goal = 7\nOutput:3\nExplanation:The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010-> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right:1111 ->0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:start = 3, goal = 4\nOutput:3\nExplanation:The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011-> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right:000 ->100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minBitFlips(self, s: int, g: int) -> int:\n count = 0 \n while s or g:\n if s%2 != g%2: count+=1\n s, g = s//2, g//2\n return count", + "title": "2220. Minimum Bit Flips to Convert Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting only of the characters '0' and '1' . In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0100\"\nOutput:1\nExplanation:If you change the last character to '1', s will be \"0101\", which is alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"\nOutput:0\nExplanation:s is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"\nOutput:2\nExplanation:You need two operations to reach \"0101\" or \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 86.00%) | Memory: 41.7 MB (Top 99.33%)\nclass Solution {\n public int minOperations(String s) {\n int count0 = 0; // changes required when the string starts from 0\n int count1 = 0; // changes required when the string starts from 1\n\n for(int i = 0; i < s.length(); i++){\n\n // string starts with 1 => all chars at even places should be 1 and that at odd places should be 0\n if((i % 2 == 0 && s.charAt(i) == '0') || (i % 2 != 0 && s.charAt(i) == '1'))\n count1++;\n\n // string starts with 0 => all chars at even places should be 0 and that at odd places should be 1\n else if((i % 2 == 0 && s.charAt(i) == '1') || (i % 2 != 0 && s.charAt(i) == '0'))\n count0++;\n }\n\n // return minimum of the two\n return Math.min(count0, count1);\n }\n}\n", + "title": "1758. Minimum Changes To Make Alternating Binary String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s consisting only of the characters '0' and '1' . In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0100\"\nOutput:1\nExplanation:If you change the last character to '1', s will be \"0101\", which is alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"\nOutput:0\nExplanation:s is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"\nOutput:2\nExplanation:You need two operations to reach \"0101\" or \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 66.2%) | Memory: 16.53 MB (Top 16.1%)\n\nclass Solution:\n def minOperations(self, s: str) -> int:\n count = 0\n count1 = 0\n for i in range(len(s)):\n if i % 2 == 0:\n if s[i] == '1':\n count += 1\n if s[i] == '0':\n count1 += 1\n else:\n if s[i] == '0':\n count += 1\n if s[i] == '1':\n count1 += 1\n return min(count, count1)", + "title": "1758. Minimum Changes To Make Alternating Binary String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array cards where cards[i] represents the value of the i th card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1 .", + "description_images": [], + "constraints": [ + "1 <= cards.length <= 10^5", + "0 <= cards[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:cards = [3,4,2,3,4,7]\nOutput:4\nExplanation:We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,0,5,3]\nOutput:-1\nExplanation:There is no way to pick up a set of consecutive cards that contain a pair of matching cards.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 92.02%) | Memory: 61 MB (Top 90.10%)\n\nclass Solution\n{\n public int minimumCardPickup(int[] cards)\n {\n Map map = new HashMap<>();\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < cards.length; i++)\n {\n if(map.containsKey(cards[i]))\n min = Math.min(i-map.get(cards[i])+1,min); // Check if the difference in indices is smaller than minimum\n map.put(cards[i],i); // Update the last found index of the card\n }\n return min == Integer.MAX_VALUE?-1:min; // Repetition found or not\n }\n}", + "title": "2260. Minimum Consecutive Cards to Pick Up", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array cards where cards[i] represents the value of the i th card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1 .", + "description_images": [], + "constraints": [ + "1 <= cards.length <= 10^5", + "0 <= cards[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:cards = [3,4,2,3,4,7]\nOutput:4\nExplanation:We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,0,5,3]\nOutput:-1\nExplanation:There is no way to pick up a set of consecutive cards that contain a pair of matching cards.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n d={}\n x=[]\n for i in range(len(cards)):\n if cards[i] not in d:\n d[cards[i]]=i\n else:\n x.append(i-d[cards[i]])\n d[cards[i]]=i\n if len(x)<=0:\n return -1\n return min(x)+1\n", + "title": "2260. Minimum Consecutive Cards to Pick Up", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days . Each day is an integer from 1 to 365 . Train tickets are sold in three different ways : The passes allow that many days of consecutive travel. Return the minimum number of dollars you need to travel every day in the given list of days .", + "description_images": [], + "constraints": [ + "a 1-day pass is sold for costs[0] dollars,", + "a 7-day pass is sold for costs[1] dollars, and", + "a 30-day pass is sold for costs[2] dollars." + ], + "examples": [ + { + "text": "Example 1: Input:days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput:11\nExplanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.", + "image": null + }, + { + "text": "Example 2: Input:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput:17\nExplanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mincostTickets(int[] days, int[] costs) {\n HashSet set = new HashSet<>();\n for(int day: days) set.add(day);\n int n = days[days.length - 1];\n int[] dp = new int[n + 1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n for(int i = 1; i <= n; i++){\n if(!set.contains(i)){\n dp[i] = dp[i - 1];\n continue;\n }\n int a = dp[Math.max(0, i - 1)] + costs[0];\n int b = dp[Math.max(0, i - 7)] + costs[1];\n int c = dp[Math.max(0, i - 30)] + costs[2];\n dp[i] = Math.min(a, Math.min(b, c));\n }\n return dp[n];\n }\n}", + "title": "983. Minimum Cost For Tickets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days . Each day is an integer from 1 to 365 . Train tickets are sold in three different ways : The passes allow that many days of consecutive travel. Return the minimum number of dollars you need to travel every day in the given list of days .", + "description_images": [], + "constraints": [ + "a 1-day pass is sold for costs[0] dollars,", + "a 7-day pass is sold for costs[1] dollars, and", + "a 30-day pass is sold for costs[2] dollars." + ], + "examples": [ + { + "text": "Example 1: Input:days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput:11\nExplanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.", + "image": null + }, + { + "text": "Example 2: Input:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput:17\nExplanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 83.24%) | Memory: 17.30 MB (Top 40.22%)\n\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n", + "title": "983. Minimum Cost For Tickets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [start row , start col ] indicates that initially , a robot is at the cell (start row , start col ) . You are also given an integer array homePos where homePos = [home row , home col ] indicates that its home is at the cell (home row , home col ) . The robot needs to go to its home. It can move one cell in four directions: left , right , up , or down , and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n . Return the minimum total cost for this robot to return home .", + "description_images": [], + "constraints": [ + "If the robot moves up or down into a cell whose row is r , then this move costs rowCosts[r] .", + "If the robot moves left or right into a cell whose column is c , then this move costs colCosts[c] ." + ], + "examples": [ + { + "text": "Example 1: Input:startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput:18\nExplanation:One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2,1). This move costs colCosts[1] = 2.\n-> It goes right to (2,2). This move costs colCosts[2] = 6.\n-> It goes right to (2,3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18", + "image": "https://assets.leetcode.com/uploads/2021/10/11/eg-1.png" + }, + { + "text": "Example 2: Input:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput:0\nExplanation:The robot is already at its home. Since no moves occur, the total cost is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {\n int total = 0;\n \n // if home is to the down of start move, down till there\n if(homePos[0]>startPos[0]){\n int i = startPos[0]+1;\n while(i<=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is up from the start, move up till there\n else if(homePos[0]=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n // if home is right to the start, move right till there\n if(homePos[1]>startPos[1]){\n int i = startPos[1]+1;\n while(i<=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is left to the start, move left till there\n else if(homePos[1]=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n return total;\n }\n}\n\n", + "title": "2087. Minimum Cost Homecoming of a Robot in a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [start row , start col ] indicates that initially , a robot is at the cell (start row , start col ) . You are also given an integer array homePos where homePos = [home row , home col ] indicates that its home is at the cell (home row , home col ) . The robot needs to go to its home. It can move one cell in four directions: left , right , up , or down , and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n . Return the minimum total cost for this robot to return home .", + "description_images": [], + "constraints": [ + "If the robot moves up or down into a cell whose row is r , then this move costs rowCosts[r] .", + "If the robot moves left or right into a cell whose column is c , then this move costs colCosts[c] ." + ], + "examples": [ + { + "text": "Example 1: Input:startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput:18\nExplanation:One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2,1). This move costs colCosts[1] = 2.\n-> It goes right to (2,2). This move costs colCosts[2] = 6.\n-> It goes right to (2,3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18", + "image": "https://assets.leetcode.com/uploads/2021/10/11/eg-1.png" + }, + { + "text": "Example 2: Input:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput:0\nExplanation:The robot is already at its home. Since no moves occur, the total cost is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n def getRange(left, right, array):\n if left > right:\n right, left = left, right\n return sum((array[i] for i in range(left,right+1)))\n \n totalRowCost = getRange(startPos[0], homePos[0], rowCosts)\n totalColCost = getRange(startPos[1], homePos[1], colCosts)\n \n #Don't pay for the position you start out on\n return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]]\n", + "title": "2087. Minimum Cost Homecoming of a Robot in a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free . The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost , where cost[i] denotes the cost of the i th candy, return the minimum cost of buying all the candies .", + "description_images": [], + "constraints": [ + "For example, if there are 4 candies with costs 1 , 2 , 3 , and 4 , and the customer buys candies with costs 2 and 3 , they can take the candy with cost 1 for free, but not the candy with cost 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [1,2,3]\nOutput:5\nExplanation:We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is theonlyway we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.", + "image": null + }, + { + "text": "Example 2: Input:cost = [6,5,7,9,2,2]\nOutput:23\nExplanation:The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.", + "image": null + }, + { + "text": "Example 3: Input:cost = [5,5]\nOutput:10\nExplanation:Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 83.40%) | Memory: 42.5 MB (Top 73.57%)\nclass Solution {\n /** Algorithm\n * 1. Sort the cost array.\n * 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.\n * 3. Decrement the position by 3 and continue. stop when you reach 1.\n * 4. From 1, add the remaining 1 or 2 items.\n *\n */\n public int minimumCost(int[] cost) {\n int minCost = 0;\n int index = cost.length -1;\n Arrays.sort(cost);\n // add items in pairs of 2, the 3rd one getting it for free.\n while (index > 1) {\n minCost += cost[index] + cost[index -1];\n index -= 3;\n }\n // add the remaining 1, 2 items, if any.\n while(index >= 0) {\n minCost += cost[index--];\n }\n return minCost;\n }\n}", + "title": "2144. Minimum Cost of Buying Candies With Discount", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free . The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost , where cost[i] denotes the cost of the i th candy, return the minimum cost of buying all the candies .", + "description_images": [], + "constraints": [ + "For example, if there are 4 candies with costs 1 , 2 , 3 , and 4 , and the customer buys candies with costs 2 and 3 , they can take the candy with cost 1 for free, but not the candy with cost 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [1,2,3]\nOutput:5\nExplanation:We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is theonlyway we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.", + "image": null + }, + { + "text": "Example 2: Input:cost = [6,5,7,9,2,2]\nOutput:23\nExplanation:The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.", + "image": null + }, + { + "text": "Example 3: Input:cost = [5,5]\nOutput:10\nExplanation:Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 72 ms (Top 49.84%) | Memory: 13.8 MB (Top 58.81%)\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n cost.sort(reverse=True)\n res, i, N = 0, 0, len(cost)\n while i < N:\n res += sum(cost[i : i + 2])\n i += 3\n return res", + "title": "2144. Minimum Cost of Buying Candies With Discount", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a valid boolean expression as a string expression consisting of the characters '1' , '0' , '&' (bitwise AND operator), '|' (bitwise OR operator), '(' , and ')' . Return the minimum cost to change the final value of the expression . The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Note: '&' does not take precedence over '|' in the order of calculation . Evaluate parentheses first , then in left-to-right order.", + "description_images": [], + "constraints": [ + "For example, \"()1|1\" and \"(1)&()\" are not valid while \"1\" , \"(((1))|(0))\" , and \"1|(0&(1))\" are valid expressions." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"1&(0|1)\"\nOutput:1\nExplanation:We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(0&0)&(0&0&0)\"\nOutput:3\nExplanation:We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(0|(1|0&1))\"\nOutput:1\nExplanation:We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 57.69%) | Memory: 45.50 MB (Top 76.92%)\n\nclass Solution {\n Deque stack = new ArrayDeque<>();\n Deque opStack = new ArrayDeque<>();\n public int minOperationsToFlip(String expression) {\n for (char ch : expression.toCharArray()){\n if (ch == '('){\n opStack.push(ch);\n }else if (ch == ')'){\n while(opStack.peek()!='('){\n go();\n }\n opStack.pop(); // remove '('\n }else if (ch == '&' || ch == '|'){\n while(!opStack.isEmpty() && opStack.peek() != '('){\n go();\n }\n opStack.push(ch);\n }else{ // num\n stack.push(new int[]{ch, 1});\n }\n }\n while(!opStack.isEmpty()){\n go();\n }\n\n return stack.peek()[1];\n }\n \n private void go(){\n stack.push(check(opStack.pop(), stack.pop(), stack.pop()));\n }\n\n private int[] check(char op, int[] r, int[] l){\n int[] ans;\n int rval = r[0], rcost = r[1];\n int lval = l[0], lcost = l[1];\n if (op == '|' && rval == '0' && lval == '0'){\n ans = new int[]{'0', Math.min(rcost, lcost)};\n }else if (op == '|' && rval == '1' && lval == '0'){\n ans = new int[]{'1', 1};\n }else if (op == '|' && rval == '0' && lval == '1'){\n ans = new int[]{'1', 1};\n }else if (op == '|' && rval == '1' && lval == '1'){\n ans = new int[]{'1', 1 + Math.min(rcost, lcost)};\n }else if (op == '&' && rval == '0' && lval == '0'){\n ans = new int[]{'0', 1 + Math.min(rcost, lcost)};\n }else if (op == '&' && rval == '1' && lval == '0'){\n ans = new int[]{'0', 1};\n }else if (op == '&' && rval == '0' && lval == '1'){\n ans = new int[]{'0', 1};\n }else{ // &, 1, 1\n ans = new int[]{'1', Math.min(rcost, lcost)};\n }\n return ans;\n }\n}\n", + "title": "1896. Minimum Cost to Change the Final Value of Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a valid boolean expression as a string expression consisting of the characters '1' , '0' , '&' (bitwise AND operator), '|' (bitwise OR operator), '(' , and ')' . Return the minimum cost to change the final value of the expression . The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Note: '&' does not take precedence over '|' in the order of calculation . Evaluate parentheses first , then in left-to-right order.", + "description_images": [], + "constraints": [ + "For example, \"()1|1\" and \"(1)&()\" are not valid while \"1\" , \"(((1))|(0))\" , and \"1|(0&(1))\" are valid expressions." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"1&(0|1)\"\nOutput:1\nExplanation:We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(0&0)&(0&0&0)\"\nOutput:3\nExplanation:We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(0|(1|0&1))\"\nOutput:1\nExplanation:We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n loc = {}\n stack = []\n for i in reversed(range(len(expression))):\n if expression[i] == \")\": stack.append(i)\n elif expression[i] == \"(\": loc[stack.pop()] = i \n \n def fn(lo, hi): \n \"\"\"Return value and min op to change value.\"\"\"\n if lo == hi: return int(expression[lo]), 1\n if expression[hi] == \")\" and loc[hi] == lo: return fn(lo+1, hi-1) # strip parenthesis \n mid = loc.get(hi, hi) - 1 \n v, c = fn(mid+1, hi)\n vv, cc = fn(lo, mid-1)\n if expression[mid] == \"|\": \n val = v | vv \n if v == vv == 0: chg = min(c, cc)\n elif v == vv == 1: chg = 1 + min(c, cc)\n else: chg = 1 \n else: # expression[k] == \"&\"\n val = v & vv\n if v == vv == 0: chg = 1 + min(c, cc)\n elif v == vv == 1: chg = min(c, cc)\n else: chg = 1\n return val, chg\n \n return fn(0, len(expression)-1)[1]\n", + "title": "1896. Minimum Cost to Change the Final Value of Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two groups of points where the first group has size 1 points, the second group has size 2 points, and size 1 >= size 2 . The cost of the connection between any two points are given in an size 1 x size 2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group . In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups .", + "description_images": [], + "constraints": [ + "size 1 == cost.length", + "size 2 == cost[i].length", + "1 <= size 1 , size 2 <= 12", + "size 1 >= size 2", + "0 <= cost[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cost = [[15, 96], [36, 2]]\nOutput:17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.", + "image": "https://assets.leetcode.com/uploads/2020/09/03/ex1.jpg" + }, + { + "text": "Example 2: Input:cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\nOutput:4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.", + "image": "https://assets.leetcode.com/uploads/2020/09/03/ex2.jpg" + }, + { + "text": "Example 3: Input:cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\nOutput:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 345 ms (Top 92.68%) | Memory: 29.40 MB (Top 24.39%)\n\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group \n \n @lru_cache(None)\n def fn(i, mask):\n \"\"\"Return min cost of connecting group1[i:] and group2 represented as mask.\"\"\"\n if i == m: return sum(mn[j] for j in range(n) if not (mask & (1< j)\n return 0;\n \n if(dp[i][j] != -1)\n return dp[i][j];\n \n int mini = Integer.MAX_VALUE;\n for(int k = i ; k <= j ; k++){\n int cost = cuts[j+1]-cuts[i-1] + cut(cuts , i , k-1 , dp) + cut(cuts , k+1 , j , dp);\n mini = Math.min(cost , mini);\n }\n \n return dp[i][j] = mini;\n }\n}\n", + "title": "1547. Minimum Cost to Cut a Stick", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a wooden stick of length n units. The stick is labelled from 0 to n . For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^6", + "1 <= cuts.length <= min(n - 1, 100)", + "1 <= cuts[i] <= n - 1", + "All the integers in cuts array are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, cuts = [1,3,4,5]\nOutput:16\nExplanation:Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).", + "image": "https://assets.leetcode.com/uploads/2020/07/23/e1.jpg" + }, + { + "text": "Example 2: Input:n = 9, cuts = [5,6,1,4,2]\nOutput:22\nExplanation:If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts = [0] + sorted(cuts) + [n]\n k = len(cuts)\n dp = [[float('inf')] * k for _ in range(k)]\n for l in range(1, k + 1):\n for beg in range(k - l):\n end = beg + l\n if l == 1:\n dp[beg][end] = 0\n continue\n for i in range(beg + 1, end):\n currcost = cuts[end] - cuts[beg]\n currcost += dp[beg][i] + dp[i][end]\n dp[beg][end] = min(dp[beg][end], currcost)\n return dp[0][k - 1]\n", + "title": "1547. Minimum Cost to Cut a Stick", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the i th worker and wage[i] is the minimum wage expectation for the i th worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Given the integer k , return the least amount of money needed to form a paid group satisfying the above conditions . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "n == quality.length == wage.length", + "1 <= k <= n <= 10^4", + "1 <= quality[i], wage[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:quality = [10,20,5], wage = [70,50,30], k = 2\nOutput:105.00000\nExplanation:We pay 70 to 0thworker and 35 to 2ndworker.", + "image": null + }, + { + "text": "Example 2: Input:quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\nOutput:30.66667\nExplanation:We pay 4 to 0thworker, 13.33333 to 2ndand 3rdworkers separately.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 87.91%) | Memory: 46.20 MB (Top 6.51%)\n\nclass Worker implements Comparable {\n final int q, w;\n public Worker(int q, int w) {\n this.q = q;\n this.w = w;\n }\n @Override\n public int compareTo(Worker other) {\n return Integer.compare(w * other.q, q * other.w);\n }\n}\nclass Solution {\n public double mincostToHireWorkers(int[] quality, int[] wage, int k) {\n int n = quality.length;\n Worker[] a = new Worker[n];\n for (int i = 0; i < n; ++i) {\n a[i] = new Worker(quality[i], wage[i]);\n }\n Arrays.sort(a);\n int s = 0;\n double res = 1e15;\n PriorityQueue q = new PriorityQueue<>();\n for (Worker worker: a) {\n q.add(-worker.q);\n s += worker.q;\n if (q.size() > k) s += q.poll();\n if (q.size() == k) res = Math.min(res, (double) s * worker.w / worker.q);\n }\n return res;\n }\n}\n", + "title": "857. Minimum Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the i th worker and wage[i] is the minimum wage expectation for the i th worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Given the integer k , return the least amount of money needed to form a paid group satisfying the above conditions . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "n == quality.length == wage.length", + "1 <= k <= n <= 10^4", + "1 <= quality[i], wage[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:quality = [10,20,5], wage = [70,50,30], k = 2\nOutput:105.00000\nExplanation:We pay 70 to 0thworker and 35 to 2ndworker.", + "image": null + }, + { + "text": "Example 2: Input:quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\nOutput:30.66667\nExplanation:We pay 4 to 0thworker, 13.33333 to 2ndand 3rdworkers separately.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 147 ms (Top 96.67%) | Memory: 19.20 MB (Top 63.7%)\n\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n n=len(wage)\n arr=[[wage[i]/quality[i],quality[i]] for i in range(n)]\n arr.sort(key=lambda x:x[0])\n kSmallest=0\n pq=[]\n for i in range(k):\n heapq.heappush(pq,-arr[i][1])\n kSmallest+=arr[i][1]\n minCost=arr[k-1][0]*kSmallest\n for c in range(k,n):\n if pq and abs(pq[0])>arr[c][1]:\n qRem=-heappop(pq)\n kSmallest-=qRem\n kSmallest+=arr[c][1]\n heappush(pq,-arr[c][1])\n minCost=min(minCost,arr[c][0]*kSmallest)\n return minCost\n \n \n \n", + "title": "857. Minimum Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0) . A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1 . You can modify the sign on a cell one time only . Return the minimum cost to make the grid have at least one valid path .", + "description_images": [], + "constraints": [ + "1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1] )", + "2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1] )", + "3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j] )", + "4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j] )" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\nOutput:3\nExplanation:You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput:0\nExplanation:You can follow the path from (0, 0) to (2, 2).", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid2.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[4,3]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 40.43%) | Memory: 53.4 MB (Top 83.19%)\nclass Solution {\n\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n\n private boolean isValid(int i,int j,int n,int m) {\n return i=0 && j>=0;\n }\n\n private boolean isValidDirection(int [][]grid,int []currEle,int nx,int ny) {\n int nextX=currEle[0],nextY = currEle[1];\n int n =grid.length,m = grid[0].length;\n\n switch(grid[currEle[0]][currEle[1]]) {\n case 1: nextY++; break;\n case 2: nextY--; break;\n case 3: nextX++; break;\n case 4: nextX--; break;\n }\n\n return nextX==nx && nextY==ny;\n }\n\n public int minCost(int[][] grid) {\n\n int n = grid.length;\n int m = grid[0].length;\n\n int dist[][] = new int[n][m];\n boolean vis[][] = new boolean[n][m];\n\n LinkedList queue = new LinkedList<>(); // for performing 01 BFS\n\n for(int i=0;i (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput:0\nExplanation:You can follow the path from (0, 0) to (2, 2).", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid2.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[4,3]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n changes = [[float(\"inf\") for _ in range(len(grid[0]))] for _ in range(len(grid))]\n heap = [(0,0,0)]\n dirn = [(0,1),(0,-1),(1,0),(-1,0)]\n while heap:\n dist,r,c = heapq.heappop(heap)\n if r >= len(grid) or r < 0 or c >= len(grid[0]) or c < 0 or changes[r][c] <= dist:\n continue\n if r == len(grid) - 1 and c == len(grid[0]) - 1:\n return dist\n changes[r][c] = dist\n for i in range(1,5):\n if i == grid[r][c]:\n heapq.heappush(heap,(dist,r+dirn[i-1][0],c+dirn[i-1][1]))\n else:\n heapq.heappush(heap,(dist+1,r+dirn[i-1][0],c+dirn[i-1][1]))\n return dist\n \n", + "title": "1368. Minimum Cost to Make at Least One Valid Path in a Grid", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n piles of stones arranged in a row. The i th pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile . If it is impossible, return -1 .", + "description_images": [], + "constraints": [ + "n == stones.length", + "1 <= n <= 30", + "1 <= stones[i] <= 100", + "2 <= k <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [3,2,4,1], k = 2\nOutput:20\nExplanation:We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible.", + "image": null + }, + { + "text": "Example 2: Input:stones = [3,2,4,1], k = 3\nOutput:-1\nExplanation:After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:stones = [3,5,1,2,6], k = 3\nOutput:25\nExplanation:We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.04%) | Memory: 41.60 MB (Top 27.41%)\n\nclass Solution {\n int prefix[];\n public int mergeStones(int[] stones, int k) {\n int n=stones.length;\n if((n-1)%(k-1) != 0) return -1;\n prefix=new int[stones.length+1];\n prefix[0]=0;\n int sum=0;\n for(int i=0;i=j){\n return 0;\n }\n if(dp[i][j]!=-1){\n return dp[i][j];\n }\n int min=Integer.MAX_VALUE;\n for(int t=i;t 0) return -1;\n\n int[] prefix = new int[n+1];\n for (int i = 0; i < n; i++)\n prefix[i + 1] = prefix[i] + stones[i];\n\n int[][] dp = new int[n][n];\n for (int m = K; m <= n; ++m)\n for (int i = 0; i + m <= n; ++i) {\n int j = i + m - 1;\n dp[i][j] = Integer.MAX_VALUE;\n for (int mid = i; mid < j; mid += K - 1)\n dp[i][j] = Math.min(dp[i][j], dp[i][mid] + dp[mid + 1][j]);\n if ((j - i) % (K - 1) == 0)\n dp[i][j] += prefix[j + 1] - prefix[i];\n }\n return dp[0][n - 1];\n }\n}\n", + "title": "1000. Minimum Cost to Merge Stones", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We have n chips, where the position of the i th chip is position[i] . We need to move all the chips to the same position . In one step, we can change the position of the i th chip from position[i] to: Return the minimum cost needed to move all the chips to the same position.", + "description_images": [], + "constraints": [ + "position[i] + 2 or position[i] - 2 with cost = 0 .", + "position[i] + 1 or position[i] - 1 with cost = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3]\nOutput:1\nExplanation:First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.", + "image": "https://assets.leetcode.com/uploads/2020/08/15/chips_e1.jpg" + }, + { + "text": "Example 2: Input:position = [2,2,2,3,3]\nOutput:2\nExplanation:We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.", + "image": "https://assets.leetcode.com/uploads/2020/08/15/chip_e2.jpg" + }, + { + "text": "Example 3: Input:position = [1,1000000000]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 34.98%)\nclass Solution {\n public int minCostToMoveChips(int[] position) {\n int even = 0;\n int odd = 0;\n for(int i=0;i int:\n count_even=0\n count_odd=0\n for i in position:\n if i%2==0:\n count_even+=1\n else:\n count_odd+=1\n return min(count_even,count_odd)\n", + "title": "1217. Minimum Cost to Move Chips to The Same Position", + "topic": "Database" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [x i , y i , time i ] denotes a road between cities x i and y i that takes time i minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j . In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less . The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey ( including the source and destination cities). Given maxTime , edges , and passingFees , return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/04/leetgraph1-1.png", + "https://assets.leetcode.com/uploads/2021/06/04/copy-of-leetgraph1-1.png" + ], + "constraints": [ + "1 <= maxTime <= 1000", + "n == passingFees.length", + "2 <= n <= 1000", + "n - 1 <= edges.length <= 1000", + "0 <= x i , y i <= n - 1", + "1 <= time i <= 1000", + "1 <= passingFees[j] <= 1000", + "The graph may contain multiple edges between two nodes.", + "The graph does not contain self loops." + ], + "examples": [ + { + "text": "Example 1: Input:maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:11\nExplanation:The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.", + "image": null + }, + { + "text": "Example 2: Input:maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:48\nExplanation:The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.", + "image": null + }, + { + "text": "Example 3: Input:maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:-1\nExplanation:There is no way to reach city 5 from city 0 within 25 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 94.1%) | Memory: 44.35 MB (Top 43.8%)\n\nclass Solution {\n record Node(int i, int t) {}\n record Cell(int i, int t, int c) {}\n public int minCost(int maxTime, int[][] edges, int[] fees) {\n int n = fees.length;\n\n // create the adjacency list graph\n List[] g = new List[n];\n for (int i = 0; i < n; i++) g[i] = new ArrayList<>();\n for (var e : edges) {\n g[e[0]].add(new Node(e[1], e[2]));\n g[e[1]].add(new Node(e[0], e[2]));\n }\n\n // Dijkstra\n Queue q = new PriorityQueue<>((a, b) -> a.c == b.c ? a.t - b.t : a.c - b.c);\n int[] T = new int[n]; // 1. visited: de-dup 2. de-dup on worst time\n\n q.offer(new Cell(0, 0, fees[0]));\n Arrays.fill(T, maxTime + 1);\n T[0] = 0;\n\n while (!q.isEmpty()) {\n var cur = q.poll();\n if (cur.i == n-1) return cur.c;\n \n for (var nei : g[cur.i]) {\n int t2 = cur.t + nei.t;\n if (t2 >= T[nei.i]) continue; // if time is worst, no reason to continue\n T[nei.i] = t2;\n q.offer(new Cell(nei.i, t2, cur.c + fees[nei.i]));\n }\n }\n\n return -1;\n }\n}", + "title": "1928. Minimum Cost to Reach Destination in Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [x i , y i , time i ] denotes a road between cities x i and y i that takes time i minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j . In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less . The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey ( including the source and destination cities). Given maxTime , edges , and passingFees , return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/04/leetgraph1-1.png", + "https://assets.leetcode.com/uploads/2021/06/04/copy-of-leetgraph1-1.png" + ], + "constraints": [ + "1 <= maxTime <= 1000", + "n == passingFees.length", + "2 <= n <= 1000", + "n - 1 <= edges.length <= 1000", + "0 <= x i , y i <= n - 1", + "1 <= time i <= 1000", + "1 <= passingFees[j] <= 1000", + "The graph may contain multiple edges between two nodes.", + "The graph does not contain self loops." + ], + "examples": [ + { + "text": "Example 1: Input:maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:11\nExplanation:The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.", + "image": null + }, + { + "text": "Example 2: Input:maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:48\nExplanation:The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.", + "image": null + }, + { + "text": "Example 3: Input:maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput:-1\nExplanation:There is no way to reach city 5 from city 0 within 25 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:\n '''\n Time: O((m+n)* maxtime), where m is length of edges\n Space: O(n*maxtime)\n '''\n n = len(passingFees)\n dp = [[math.inf]*(n) for _ in range(maxTime+1)]\n dp[0][0] = passingFees[0]\n\n ans = math.inf\n for k in range(1, maxTime+1):\n for x, y, time in edges:\n if k >= time:\n # dual direction\n dp[k][y] = min(dp[k][y], dp[k-time][x] + passingFees[y])\n dp[k][x] = min(dp[k][x], dp[k-time][y] + passingFees[x])\n \n ans = min(ans, dp[k][n-1])\n \n if ans == math.inf:\n return -1\n return ans\n", + "title": "1928. Minimum Cost to Reach Destination in Time", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A generic microwave supports cooking times for: To set the cooking time, you push at most four digits . The microwave normalizes what you push as four digits by prepending zeroes . It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You are given integers startAt , moveCost , pushCost , and targetSeconds . Initially , your finger is on the digit startAt . Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time . Remember that one minute consists of 60 seconds.", + "description_images": [], + "constraints": [ + "at least 1 second.", + "at most 99 minutes and 99 seconds." + ], + "examples": [ + { + "text": "Example 1: Input:startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600\nOutput:6\nExplanation:The following are the possible ways to set the cooking time.\n- 1 0 0 0, interpreted as 10 minutes and 0 seconds.\n  The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).\n  The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost.\n- 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.\n  The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12.\n- 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.\n  The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/1.png" + }, + { + "text": "Example 2: Input:startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76\nOutput:6\nExplanation:The optimal way is to push two digits: 7 6, interpreted as 76 seconds.\nThe finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6\nNote other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.7%) | Memory: 39.44 MB (Top 55.0%)\n\nclass Solution {\n public int minCostSetTime(int startAt, int moveCost, int pushCost, int tar) {\n \n int min=tar/60, sec=tar%60, minCost=(moveCost+pushCost)*4;\n \n if(min>99) { min--; sec+=60; } // this is required to do because if tar>=6000 then min is 100 which is not possible as it atmost can be 99mins\n \n while(min>=0&&sec<=99) { // this while loop will work for atmost 2 iterations\n tar=min*100+sec;\n char arr[]=(\"\"+tar).toCharArray();\n int sameMove=0;\n for(int i=0;i int:\n poss = [(targetSeconds // 60, targetSeconds % 60)] # store possibilities as (minutes, seconds)\n \n if poss[0][0] > 99: # for when targetSeconds >= 6000\n poss = [(99, poss[0][1]+60)]\n \n if poss[0][0] >= 1 and (poss[0][1]+60) <= 99:\n\t\t\t# adding a second possibility e.g. (01, 16) -> (0, 76)\n poss.append((poss[0][0]-1, poss[0][1]+60))\n \n costs = list()\n \n for i in poss:\n curr_start = startAt\n curr_cost = 0\n \n minutes = str(i[0])\n if i[0] != 0: # 0s are prepended, so no need to push 0s\n for j in minutes:\n if int(j) != curr_start:\n curr_cost += moveCost\n curr_start = int(j)\n curr_cost += pushCost\n \n seconds = str(i[1])\n if len(seconds) == 1 and i[0] != 0: # seconds is a single digit, prepend a \"0\" to it\n seconds = \"0\" + seconds\n \n for j in seconds:\n if int(j) != curr_start:\n curr_cost += moveCost\n curr_start = int(j)\n curr_cost += pushCost\n costs.append(curr_cost)\n \n return min(costs)", + "title": "2162. Minimum Cost to Set Cooking Time", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of positive integers, consider all binary trees such that: Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node . It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children.", + "description_images": [], + "constraints": [ + "Each node has either 0 or 2 children;", + "The values of arr correspond to the values of each leaf in an in-order traversal of the tree.", + "The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,2,4]\nOutput:32\nExplanation:There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree1.jpg" + }, + { + "text": "Example 2: Input:arr = [4,11]\nOutput:44", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 95.15%) | Memory: 41.70 MB (Top 26.54%)\n\nclass Solution {\n // Use stack. Similar to trapping the rain water problem and the largest rectangle under histogram\n // Use stack to keep a decreasing order by adding smaller values, while there is bigger value \n //arr[i] than the peek, pop it and store as mid and calculate the multiplication mid*min(arr[i], \n //stack.peek()).\n \n // NOTE: if we observe the number array, in order to obtain the smallest sum of all non-leaf\n // values, we want to merge those small values first. In order words, the smaller a value\n // is, the lower leaf it should stay because this way as we are building the tree up, \n // we are building smaller multiplication/parent node first as it is only going to get bigger\n\t// as we build the tree up. \n \n // Ex: 4 3 2 1 5\n // There are many ways we can build a tree following the problem's requirement. However, to \n // gain smallest sum. We need to merge 2 and 1 first as they are the two smallest ones. To\n\t// do that, we use the stack mentioned above as a decreasing order. After\n // that we get a parent node with value 2. This node could be a left or right child of its parent\n // but what we want is that its parent needs also be as small as possible. We also know that its\n // parent has one mutiplier already: 2. Note: this 2 is not from the product of 1 * 2, but from the max of child\n // 1 and 2 as the problem requires. So, we see what values next to the leaf 2 could be a \n\t// candidate. Obviously, 3 since it is the smallest one in the stack Then, 3\n // becomes the left child and 1*2 = 2 becomes right child. See below: \n // ...\n // / \\\n // 3 2\n // / \\\n // 2 1\n // \n \n // If we observe carefully, 3 2 1 is decreasing... So how about every time we see a \"dip\" point\n // in the array we calculate its multiplication. To do that, say we are at arr[i] and their \n // relations are arr[i-1] <= arr[i] <= arr[i+1]. The min multiplication is a[i] * min(arr[i-1], \n // arr[i+1]). Then the example above is arr[i] = 1, arr[i-1] = 2, arr[i+1] = 5\n \n public int mctFromLeafValues(int[] arr) {\n if(arr == null || arr.length < 2){\n return 0;\n }\n \n int res = 0;\n Stack stack = new Stack<>(); \n for(int num : arr){\n \n // while num is bigger than peek(), pop and calculate\n while(!stack.isEmpty() && stack.peek() <= num){\n int mid = stack.pop();\n if(stack.isEmpty()) \n res += mid * num;\n else\n res += mid * Math.min(stack.peek(), num);\n }\n \n stack.push(num); // if num is smaller, push into stack\n }\n \n // if there are values left in the stack, they sure will be mutiplied anyway\n // and added to the result. \n while(stack.size() > 1){ // > 1 because we have a peek() after pop() below\n res += stack.pop() * stack.peek();\n }\n \n return res;\n }\n}\n", + "title": "1130. Minimum Cost Tree From Leaf Values", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array arr of positive integers, consider all binary trees such that: Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node . It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children.", + "description_images": [], + "constraints": [ + "Each node has either 0 or 2 children;", + "The values of arr correspond to the values of each leaf in an in-order traversal of the tree.", + "The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,2,4]\nOutput:32\nExplanation:There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree1.jpg" + }, + { + "text": "Example 2: Input:arr = [4,11]\nOutput:44", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 472 ms (Top 12.37%) | Memory: 14 MB (Top 32.41%)\nclass Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n n = len(arr)\n d = {}\n def findMax(start,end):\n if (start,end) in d: return d[(start,end)]\n maxx = start\n for i in range(start+1,end+1):\n if arr[maxx] < arr[i] : maxx = i\n d[(start,end)] = arr[maxx]\n return arr[maxx]\n\n dp = [[float('inf') for i in range(n)] for j in range(n)]\n for gap in range(n):\n for row in range(n - gap):\n col = row + gap\n if gap == 0:\n dp[row][col] = 0\n elif gap == 1:\n dp[row][col] = arr[row] * arr[col]\n else:\n for k in range(row,col):\n val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]\n if val < dp[row][col]: dp[row][col] = val\n\n return dp[0][-1]\n", + "title": "1130. Minimum Cost Tree From Leaf Values", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges , where each edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.", + "description_images": [], + "constraints": [ + "2 <= n <= 400", + "edges[i].length == 2", + "1 <= edges.length <= n * (n-1) / 2", + "1 <= u i , v i <= n", + "u i != v i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput:3\nExplanation:There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput:0\nExplanation:There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int minTrioDegree(int n, int[][] edges) {\n\t// to store edge information\n boolean[][] graph = new boolean[n+1][n+1];\n\t//to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph)\n int[] inDegree = new int[n+1];\n \n for(int[] edge : edges) {\n graph[edge[0]][edge[1]] = true;\n graph[edge[1]][edge[0]] = true;\n \n inDegree[edge[0]]++;\n inDegree[edge[1]]++;\n }\n \n int result = Integer.MAX_VALUE;\n for(int i=1; i<=n; i++) {\n for(int j=i+1; j<=n; j++) {\n if(graph[i][j]) {\n for(int k=j+1; k<=n; k++) {\n if(graph[i][k] && graph[j][k]) {\n result = Math.min(result, inDegree[i] + inDegree[j] + inDegree[k] - 6);\n }\n }\n }\n }\n }\n \n \n return result == Integer.MAX_VALUE ? -1 : result;\n}\n}", + "title": "1761. Minimum Degree of a Connected Trio in a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges , where each edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.", + "description_images": [], + "constraints": [ + "2 <= n <= 400", + "edges[i].length == 2", + "1 <= edges.length <= n * (n-1) / 2", + "1 <= u i , v i <= n", + "u i != v i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput:3\nExplanation:There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput:0\nExplanation:There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 4822 ms (Top 24.41%) | Memory: 38.50 MB (Top 62.2%)\n\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = True\n degree[u-1] += 1\n degree[v-1] += 1\n \n ans = inf\n for i in range(n): \n for j in range(i+1, n):\n if graph[i][j]: \n for k in range(j+1, n):\n if graph[j][k] and graph[k][i]: \n ans = min(ans, degree[i] + degree[j] + degree[k] - 6)\n return ans if ans < inf else -1\n", + "title": "1761. Minimum Degree of a Connected Trio in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . The array nums is beautiful if: Note that an empty array is considered beautiful. You can delete any number of elements from nums . When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged . Return the minimum number of elements to delete from nums to make it beautiful.", + "description_images": [], + "constraints": [ + "nums.length is even.", + "nums[i] != nums[i + 1] for all i % 2 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,3,5]\nOutput:1\nExplanation:You can delete eithernums[0]ornums[1]to makenums= [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to makenumsbeautiful.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,2,3,3]\nOutput:2\nExplanation:You can deletenums[0]andnums[5]to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 50.94%) | Memory: 58.2 MB (Top 89.06%)\nclass Solution {\n public int minDeletion(int[] nums) {\n\n int deletion = 0, n = nums.length;\n\n for (int i=0; i int:\n # Greedy !\n # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n # at the begining, we consider the num on the even index\n # when we delete a num, we need consider the num on the odd index\n # then repeat this process\n # at the end we check the requirement 1: nums.length is even or not\n \n n = len(nums)\n count = 0\n # flag is true then check the even index\n # flag is false then check the odd index\n flag = True\n \n for i in range(n):\n # check the even index\n if flag:\n if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = False\n # check the odd index\n elif not flag:\n if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = True\n \n curLength = n - count\n \n return count if curLength % 2 == 0 else count + 1", + "title": "2216. Minimum Deletions to Make Array Beautiful", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive integer arrays nums and numsDivide . You can delete any number of elements from nums . Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide . If this is not possible, return -1 . Note that an integer x divides y if y % x == 0 .", + "description_images": [], + "constraints": [ + "1 <= nums.length, numsDivide.length <= 10^5", + "1 <= nums[i], numsDivide[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]\nOutput:2\nExplanation:The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.\nWe use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].\nThe smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.\nIt can be shown that 2 is the minimum number of deletions needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,6], numsDivide = [8,2,6,10]\nOutput:-1\nExplanation:We want the smallest element in nums to divide all the elements of numsDivide.\nThere is no way to delete elements from nums to allow this.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1147 ms (Top 45.35%) | Memory: 25.8 MB (Top 79.68%)\nclass Solution:\n def minOperations(self, nums: List[int], divs: List[int]) -> int:\n div = reduce(gcd, divs)\n return next((i for i, n in enumerate(sorted(nums)) if div % n == 0), -1)", + "title": "2344. Minimum Deletions to Make Array Divisible", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is called good if there are no two different characters in s that have the same frequency . Given a string s , return the minimum number of characters you need to delete to make s good . The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\" , the frequency of 'a' is 2 , while the frequency of 'b' is 1 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:0\nExplanation:sis already good.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabbbcc\"\nOutput:2\nExplanation:You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ceabaacb\"\nOutput:2\nExplanation:You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int N = 26;\n public int minDeletions(String s) {\n int[] array = new int[N];\n for (char ch : s.toCharArray()) {\n array[ch - 'a']++;\n }\n int ans = 0;\n Set set = new HashSet<>();\n for (int i : array) {\n if (i == 0) continue;\n while (set.contains(i)) {\n i--;\n ans++;\n }\n if (i != 0) {\n set.add(i);\n }\n }\n return ans;\n }\n}\n", + "title": "1647. Minimum Deletions to Make Character Frequencies Unique", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A string s is called good if there are no two different characters in s that have the same frequency . Given a string s , return the minimum number of characters you need to delete to make s good . The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\" , the frequency of 'a' is 2 , while the frequency of 'b' is 1 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:0\nExplanation:sis already good.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabbbcc\"\nOutput:2\nExplanation:You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ceabaacb\"\nOutput:2\nExplanation:You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDeletions(self, s: str) -> int:\n # Get the frequency of each character sorted in reverse order\n frequencies = sorted(Counter(s).values(), reverse=True)\n \n total_deletions = 0\n next_unused_freq = len(s)\n for freq in frequencies:\n # It is impossible for the frequency to be higher\n next_unused_freq = min(next_unused_freq, freq)\n total_deletions += freq - next_unused_freq\n\n # We cannot have another character with this frequency,\n # so decrement next_unused_freq\n if next_unused_freq > 0:\n next_unused_freq -= 1\n\n return total_deletions\n", + "title": "1647. Minimum Deletions to Make Character Frequencies Unique", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of characters 'a' and 'b' ​​​​. You can delete any number of characters in s to make s balanced . s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a' . Return the minimum number of deletions needed to make s balanced .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is 'a' or 'b' ​​." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababbab\"\nOutput:2\nExplanation:You can either:\nDelete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -> \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbaaaaabb\"\nOutput:2\nExplanation:The only solution is to delete the first two characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 70.64%) | Memory: 68.2 MB (Top 24.02%)\nclass Solution {\n public int minimumDeletions(String s) {\n //ideal case : bbbbbbbbb\n int[] dp = new int[s.length()+1];\n int idx =1;\n int bCount=0;\n\n for(int i =0 ;i \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbaaaaabb\"\nOutput:2\nExplanation:The only solution is to delete the first two characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef minimumDeletions(self, s: str) -> int:\n\t\tpreSum = [0] * (len(s) + 1)\n\t\tsufSum = [0] * (len(s) + 1)\n\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == \"a\":\n\t\t\t\tpreSum[i] += 1 + preSum[i-1]\n\n\t\t\telse:\n\t\t\t\tpreSum[i] = preSum[i-1]\n\n\t\t\tif s[len(s)-i-1] == \"b\":\n\t\t\t\tsufSum[len(s)-i-1] += 1 + sufSum[len(s)-i]\n\n\t\t\telse:\n\t\t\t\tsufSum[len(s)-i-1] += sufSum[len(s)-i]\n\n\t\tmaxStringLength = 0\n\t\tfor i in range(len(s)):\n\t\t\tif preSum[i] + sufSum[i] > maxStringLength:\n\t\t\t\tmaxStringLength = preSum[i] + sufSum[i]\n\n\t\treturn len(s) - maxStringLength", + "title": "1653. Minimum Deletions to Make String Balanced", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int minDepth(TreeNode root) {\n if(root == null)\n return 0;\n \n int left = minDepth(root.left);\n int right = minDepth(root.right);\n if(root.left == null)\n return right+1;\n if(root.right == null)\n return left+1;\n return Math.min(left, right)+1;\n }\n}\n", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minDepth(self, root):\n # Base case...\n # If the subtree is empty i.e. root is NULL, return depth as 0...\n if root is None: return 0\n # Initialize the depth of two subtrees...\n leftDepth = self.minDepth(root.left)\n rightDepth = self.minDepth(root.right)\n # If the both subtrees are empty...\n if root.left is None and root.right is None:\n return 1\n # If the left subtree is empty, return the depth of right subtree after adding 1 to it...\n if root.left is None:\n return 1 + rightDepth\n # If the right subtree is empty, return the depth of left subtree after adding 1 to it...\n if root.right is None:\n return 1 + leftDepth\n # When the two child function return its depth...\n # Pick the minimum out of these two subtrees and return this value after adding 1 to it...\n return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees...", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums , where nums[i] represents the score of the i th student. You are also given an integer k . Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized . Return the minimum possible difference .", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 1000", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [90], k = 1\nOutput:0\nExplanation:There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,1,7], k = 2\nOutput:2\nExplanation:There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 73.44%) | Memory: 47.5 MB (Top 27.33%)\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k == 1)return 0;\n int i = 0,j = k-1,res = Integer.MAX_VALUE;\n\n Arrays.sort(nums);\n while(j < nums.length){\n res = Math.min(res,nums[j] - nums[i]);\n j++;\n i++;\n }\n\n return res;\n }\n}", + "title": "1984. Minimum Difference Between Highest and Lowest of K Scores", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums , where nums[i] represents the score of the i th student. You are also given an integer k . Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized . Return the minimum possible difference .", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 1000", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [90], k = 1\nOutput:0\nExplanation:There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,1,7], k = 2\nOutput:2\nExplanation:There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 7.93%) | Memory: 17.50 MB (Top 9.64%)\n\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n m,n=100001,len(nums)\n i,j=0,k-1\n while j int:\n if len(nums) <= 3:\n return 0\n\n nums.sort()\n t1 = nums[-1] - nums[3]\n t2 = nums[-4] - nums[0]\n t3 = nums[-2] - nums[2]\n t4 = nums[-3] - nums[1]\n\n return min(t1,t2,t3,t4)", + "title": "1509. Minimum Difference Between Largest and Smallest Value in Three Moves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums . The remaining 2 * n elements will be divided into two equal parts: The difference in sums of the two parts is denoted as sum first - sum second . Return the minimum difference possible between the sums of the two parts after the removal of n elements .", + "description_images": [], + "constraints": [ + "The first n elements belonging to the first part and their sum is sum first .", + "The next n elements belonging to the second part and their sum is sum second ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2]\nOutput:-1\nExplanation:Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,9,5,8,1,3]\nOutput:1\nExplanation:Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 41.21%) | Memory: 218.6 MB (Top 5.49%)\n\nclass Solution {\n public long minimumDifference(int[] nums) {\n int n=nums.length; //length of nums\n int len3=n/3; // 1/3 length\n long res=Long.MAX_VALUE; // final result;\n //Try to make first part as min as possible;\n //first[m] store the value, the min value of the size=len3, from[0,1,..., m];\n long[] first=new long[n];\n //Try to make second part as max as possible;\n //second[m] store the value, the max value of the size=len3, from[m,...,n-1];\n long[] second=new long[n];\n\n//--------------------for first part compute -------------------------------------\n //Build max heap for first part;\n PriorityQueue max=new PriorityQueue(Comparator.reverseOrder());\n\n long sum=0;\n\n // Initialize with the first 1/3 n part.\n for(int i=0;i min=new PriorityQueue();\n // Initialize with the last 1/3 n part.\n for(int i=0;i int:\n h=heapq\n k=len(nums)//3\n min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, []\n h.heapify(max_heap) , h.heapify(min_heap)\n for x in nums[:-k]:\n h.heappush(min_heap,-x)\n min_sum+=x\n if len(min_heap)>k: min_sum+=h.heappop(min_heap)\n min_sol.append(min_sum)\n for x in nums[::-1][:-k]:\n h.heappush(max_heap,x)\n max_sum+=x\n if len(max_heap)>k: max_sum-=h.heappop(max_heap)\n max_sol.append(max_sum)\n min_sol =min_sol[k-1:]\n max_sol=max_sol[k-1:][::-1]\n return min( min_value - max_value for min_value , max_value in zip(min_sol,max_sol) )\n", + "title": "2163. Minimum Difference in Sums After Removal of Elements", + "topic": "Array" + }, + { + "difficulty": "1335. Minimum Difficulty of a Job Schedule", + "language": "java", + "description": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i th job, you have to finish all the jobs j where 0 <= j < i ). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d . The difficulty of the i th job is jobDifficulty[i] . Return the minimum difficulty of a job schedule . If you cannot find a schedule for the jobs return -1 .", + "description_images": [], + "constraints": [ + "1 <= jobDifficulty.length <= 300", + "0 <= jobDifficulty[i] <= 1000", + "1 <= d <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:jobDifficulty = [6,5,4,3,2,1], d = 2\nOutput:7\nExplanation:First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7", + "image": "https://assets.leetcode.com/uploads/2020/01/16/untitled.png" + }, + { + "text": "Example 2: Input:jobDifficulty = [9,9,9], d = 4\nOutput:-1\nExplanation:If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.", + "image": null + }, + { + "text": "Example 3: Input:jobDifficulty = [1,1,1], d = 3\nOutput:3\nExplanation:The schedule is one job per day. total difficulty will be 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray.\n public int minDifficulty(int[] jobDifficulty, int d) {\n if(d>jobDifficulty.length){\n return -1;\n }\n \n int[][] memo = new int[d+1][jobDifficulty.length];\n for(int[] m : memo){\n Arrays.fill(m, -1);\n }\n \n return getMinDays(jobDifficulty, d, memo, 0);\n }\n \n private int getMinDays(int[] jobDifficulty, int d, int[][] memo, int idx){\n if(d==1){\n int max=0;\n while(idx < jobDifficulty.length){\n max=Math.max(max, jobDifficulty[idx]);\n idx++;\n }\n return max;\n }\n \n if(memo[d][idx] != -1) return memo[d][idx];\n \n int max=0;\n int res=Integer.MAX_VALUE;\n // [6,5,4,3,2,1], d=5 => we don't want the cut at 4th position in the array because we won't be able to divide it into 5 parts\n for(int i=idx; i length:\n return -1\n\n min_difficulties = [[float('inf')] * length for _ in range(days)]\n\n max_diff = 0\n i = 0\n while i <= length - days:\n max_diff = max(max_diff, jobDifficulty[i])\n min_difficulties[0][i] = max_diff\n i += 1\n\n current_day = 1\n while current_day < days:\n to = current_day\n while to <= length - days + current_day:\n current_job_difficulty = jobDifficulty[to]\n result = float('inf')\n j = to - 1\n while j >= current_day - 1:\n result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty)\n current_job_difficulty = max(current_job_difficulty, jobDifficulty[j])\n j -= 1\n min_difficulties[current_day][to] = result\n to += 1\n current_day += 1\n\n return min_difficulties[days - 1][length - 1]\n\n\n\n", + "title": "1335. Minimum Difficulty of a Job Schedule", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.00 MB (Top 72.0%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n \n int mini=Integer.MAX_VALUE;\n\n public void find(TreeNode root,ArrayListarr){\n \n if(root==null){\n return;\n }\n \n \n arr.add(root.val);\n \n find(root.left,arr);\n \n for(int i=arr.size()-2;i>=0;i--){\n \n mini=Math.min(mini,Math.abs(root.val-arr.get(i)));\n }\n \n find(root.right,arr);\n \n arr.remove(arr.size()-1);\n }\n\n public int minDiffInBST(TreeNode root) {\n ArrayListarr=new ArrayList<>();\n find(root,arr);\n return mini; \n }\n}", + "title": "783. Minimum Distance Between BST Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n if root is None:\n return 0\n temp1=float(inf)\n from collections import deque\n a=deque([root])\n b=[]\n while a:\n node=a.popleft()\n b.append(node.val)\n if node.left:\n a.append(node.left)\n if node.right:\n a.append(node.right)\n b.sort()\n for i in range(0,len(b)-1):\n if b[i+1]-b[i]", + "title": "783. Minimum Distance Between BST Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums (0-indexed) and two integers target and start , find an index i such that nums[i] == target and abs(i - start) is minimized . Note that abs(x) is the absolute value of x . Return abs(i - start) . It is guaranteed that target exists in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "0 <= start < nums.length", + "target is in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], target = 5, start = 3\nOutput:1\nExplanation:nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1, start = 0\nOutput:0\nExplanation:nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput:0\nExplanation:Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 8.87%) | Memory: 43.1 MB (Top 80.91%)\nclass Solution {\n public int getMinDistance(int[] nums, int target, int start) {\n int ans = Integer.MAX_VALUE;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n ans = Math.min(ans, Math.abs(i - start));\n }\n }\n return ans;\n }\n}", + "title": "1848. Minimum Distance to the Target Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums (0-indexed) and two integers target and start , find an index i such that nums[i] == target and abs(i - start) is minimized . Note that abs(x) is the absolute value of x . Return abs(i - start) . It is guaranteed that target exists in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "0 <= start < nums.length", + "target is in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], target = 5, start = 3\nOutput:1\nExplanation:nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1, start = 0\nOutput:0\nExplanation:nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput:0\nExplanation:Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n if nums[start] == target: return 0\n left, right = start-1, start+1\n N = len(nums)\n while True:\n if left >=0 and nums[left] == target:\n return start - left\n if right < N and nums[right] == target:\n return right - start\n left -= 1\n right += 1\n", + "title": "1848. Minimum Distance to the Target Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word , return the minimum total distance to type such string using only two fingers . The distance between coordinates (x 1 , y 1 ) and (x 2 , y 2 ) is |x 1 - x 2 | + |y 1 - y 2 | . Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.", + "description_images": [], + "constraints": [ + "For example, the letter 'A' is located at coordinate (0, 0) , the letter 'B' is located at coordinate (0, 1) , the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"CAKE\"\nOutput:3\nExplanation:Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3", + "image": null + }, + { + "text": "Example 2: Input:word = \"HAPPY\"\nOutput:6\nExplanation:Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap pos;\n int [][][]memo;\n int type(String word,int index,char finger1,char finger2){\n if (index==word.length()) return 0;\n int ans=9999999;\n if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];\n if (finger1=='['){\n \n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));\n }\n else{\n \n Integer [] prev=pos.get(finger1);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);\n }\n if (finger2=='['){\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));\n }\n else{\n Integer [] prev=pos.get(finger2);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);\n }\n memo[index][finger1-'A'][finger2-'A']=ans;\n return ans;\n }\n public int minimumDistance(String word) {\n pos=new HashMap();\n for (int i=0;i<26;i++){\n Integer [] coord={i/6,i%6};\n pos.put((char)('A'+i),coord);\n }\n memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];\n for (int[][] row : memo) {\n for (int[] rowColumn : row) {\n Arrays.fill(rowColumn, -1);\n }\n }\n return type(word,0,'[','[');\n }\n}", + "title": "1320. Minimum Distance to Type a Word Using Two Fingers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word , return the minimum total distance to type such string using only two fingers . The distance between coordinates (x 1 , y 1 ) and (x 2 , y 2 ) is |x 1 - x 2 | + |y 1 - y 2 | . Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.", + "description_images": [], + "constraints": [ + "For example, the letter 'A' is located at coordinate (0, 0) , the letter 'B' is located at coordinate (0, 1) , the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"CAKE\"\nOutput:3\nExplanation:Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3", + "image": null + }, + { + "text": "Example 2: Input:word = \"HAPPY\"\nOutput:6\nExplanation:Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cache\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n COL = 6\n index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}\n def dist(a, b):\n return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])\n @cache\n def dfs(lhand, rhand, i):\n if i == len(word): return 0\n res = float('inf')\n res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))\n res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))\n return res\n return dfs(-1, -1, 0)", + "title": "1320. Minimum Distance to Type a Word Using Two Fingers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i th domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1 .", + "description_images": [], + "constraints": [ + "2 <= tops.length <= 2 * 10^4", + "bottoms.length == tops.length", + "1 <= tops[i], bottoms[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput:2\nExplanation:The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.", + "image": "https://assets.leetcode.com/uploads/2021/05/14/domino.png" + }, + { + "text": "Example 2: Input:tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput:-1\nExplanation:In this case, it is not possible to rotate the dominoes to make one row of values equal.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 32.99%) | Memory: 94.3 MB (Top 24.39%)\nclass Solution {\n public int minDominoRotations(int[] tops, int[] bottoms) {\n\n int[][] c = new int[6][2];\n\n for (int i : tops) {\n c[i - 1][0]++;\n }\n for (int i : bottoms) {\n c[i - 1][1]++;\n }\n int[] common = new int[6];\n for (int i = 0; i < tops.length; i++) {\n if (tops[i] == bottoms[i]) {\n common[tops[i] - 1]++;\n }\n }\n int min = Integer.MAX_VALUE;\n for (int i = 1; i <= 6; i++) {\n if (c[i - 1][0] + c[i - 1][1] >= tops.length) {\n if (c[i - 1][0] >= c[i - 1][1] && c[i - 1][1] - common[i - 1] + c[i - 1][0] == tops.length) {\n min = Math.min(min, c[i - 1][1] - common[i - 1]);\n }\n else if (c[i - 1][1] >= c[i - 1][0] && c[i - 1][0] - common[i - 1] + c[i - 1][1] == tops.length) {\n int left = c[i - 1][0] - common[i - 1];\n min = Math.min(min, c[i - 1][0] - common[i - 1]);\n }\n }\n }\n\n return min == Integer.MAX_VALUE ? -1 : min;\n }\n}", + "title": "1007. Minimum Domino Rotations For Equal Row", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i th domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1 .", + "description_images": [], + "constraints": [ + "2 <= tops.length <= 2 * 10^4", + "bottoms.length == tops.length", + "1 <= tops[i], bottoms[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput:2\nExplanation:The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.", + "image": "https://assets.leetcode.com/uploads/2021/05/14/domino.png" + }, + { + "text": "Example 2: Input:tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput:-1\nExplanation:In this case, it is not possible to rotate the dominoes to make one row of values equal.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]\n\t\t\n same_count = collections.Counter(sames)\n bottom_count = collections.Counter(bottoms)\n top_count = collections.Counter(tops)\n \n for n in range(1,7):\n if bottom_count[n] + top_count[n] - same_count[n] == len(tops):\n return min(bottom_count[n], top_count[n]) - same_count[n]\n \n return -1\n", + "title": "1007. Minimum Domino Rotations For Equal Row", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and two integers limit and goal . The array nums has an interesting property that abs(nums[i]) <= limit . Return the minimum number of elements you need to add to make the sum of the array equal to goal . The array must maintain its property that abs(nums[i]) <= limit . Note that abs(x) equals x if x >= 0 , and -x otherwise.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= limit <= 10^6", + "-limit <= nums[i] <= limit", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,1], limit = 3, goal = -4\nOutput:2\nExplanation:You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-10,9,1], limit = 100, goal = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 11.82%) | Memory: 74.9 MB (Top 84.55%)\nclass Solution {\n public int minElements(int[] nums, int limit, int goal) {\n long sum = 0;\n for(int num: nums)\n sum += num;\n long diff = Math.abs(sum-goal);\n return (int) (diff/limit) + (diff%limit>0?1:0);\n }\n}", + "title": "1785. Minimum Elements to Add to Form a Given Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and two integers limit and goal . The array nums has an interesting property that abs(nums[i]) <= limit . Return the minimum number of elements you need to add to make the sum of the array equal to goal . The array must maintain its property that abs(nums[i]) <= limit . Note that abs(x) equals x if x >= 0 , and -x otherwise.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= limit <= 10^6", + "-limit <= nums[i] <= limit", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,1], limit = 3, goal = -4\nOutput:2\nExplanation:You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-10,9,1], limit = 100, goal = 0\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n", + "title": "1785. Minimum Elements to Add to Form a Given Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n array of integers matrix , return the minimum sum of any falling path through matrix . A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1) , (row + 1, col) , or (row + 1, col + 1) .", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 100", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[2,1,3],[6,5,4],[7,8,9]]\nOutput:13\nExplanation:There are two falling paths with a minimum sum as shown.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[-19,57],[-40,-5]]\nOutput:-59\nExplanation:The falling path with a minimum sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 82.59%) | Memory: 46.9 MB (Top 82.02%)\n\nclass Solution {\n public int min(int[][] matrix, int[][]dp, int i, int j)\n {\n int a,b,c;\n if(i==0)\n return matrix[i][j];\n if(dp[i][j] != Integer.MAX_VALUE)\n return dp[i][j];\n if(j==0)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1))+matrix[i][j];\n }\n else if(j==matrix.length -1)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n else\n {\n dp[i][j] = Math.min(Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1)),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n return dp[i][j];\n }\n\n public int minFallingPathSum(int[][] matrix) {\n int dp[][] = new int[matrix.length][matrix.length];\n if(matrix.length == 1)\n return matrix[0][0];\n for(int i=0;i int:\n for row in range(1, len(matrix)):\n for col in range(0, len(matrix[row])):\n if col == 0:\n matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col])\n elif col == len(matrix[row]) - 1:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col])\n else:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col], matrix[row-1][col+1])\n \n return min(matrix[-1])\n", + "title": "931. Minimum Falling Path Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n integer matrix grid , return the minimum sum of a falling path with non-zero shifts . A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "-99 <= grid[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:13\nExplanation:The possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/falling-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[7]]\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Recursion\n /* public int minFallingPathSum(int[][] grid) {\n int n=grid.length;\n if(n==1) return grid[0][0];\n int ans = 10000000;\n for(int i=0 ; i int:\n m, n = len(grid), len(grid[0])\n if m == 1 and n == 1:\n return grid[0][0]\n min_arr = [0 for _ in range(n)]\n for i in range(m):\n prefix = [float('inf') for _ in range(n)]\n suffix = [float('inf') for _ in range(n)]\n current_row = [elem1+elem2 for elem1, elem2 in zip(grid[i], min_arr)]\n for i in range(1, n):\n prefix[i] = min(prefix[i-1], current_row[i-1])\n for i in range(n-2, -1, -1):\n suffix[i] = min(suffix[i+1], current_row[i+1])\n min_arr = [min(pre, suff) for pre, suff in zip(prefix, suffix)]\n return min(min_arr)\n", + "title": "1289. Minimum Falling Path Sum II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given 3 positives numbers a , b and c . Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png" + ], + "constraints": [ + "1 <= a <= 10^9", + "1 <= b <= 10^9", + "1 <= c <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 6, c = 5\nOutput:3\nExplanation:After flips a = 1 , b = 4 , c = 5 such that (aORb==c)", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 2, c = 7\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 2, c = 3\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.2 MB (Top 89.45%)\nclass Solution {\n public int minFlips(int a, int b, int c) {\n int j=-1;\n int x=a|b;\n int count=0;\n while(c!=0 || x!=0){\n j++;\n int aa=x%2;\n int bb=c%2;\n if(aa==0 && bb==1)count++;\n else if(aa==1 && bb==0) count+=funcount(j,a,b);\n x=x>>1;\n c=c>>1;\n }\n return count;\n }\n public static int funcount(int shift,int a,int b){\n int cc=0;\n int mask=1< int:\n res = 0\n for i in range(32):\n if (a & 1) | (b & 1) != (c & 1):\n if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1\n res += 1\n else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1\n res += (a & 1) + (b & 1)\n a, b, c = a>>1, b>>1, c>>1 # right-shift by 1\n\n return res\n\n# Time: O(1)\n# Space: O(1)", + "title": "1318. Minimum Flips to Make a OR b Equal to c", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0) . Given an integer neededApples , return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot . The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0", + "-x if x < 0" + ], + "examples": [ + { + "text": "Example 1: Input:neededApples = 1\nOutput:8\nExplanation:A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.", + "image": "https://assets.leetcode.com/uploads/2019/08/30/1527_example_1_2.png" + }, + { + "text": "Example 2: Input:neededApples = 13\nOutput:16", + "image": null + }, + { + "text": "Example 3: Input:neededApples = 1000000000\nOutput:5040", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumPerimeter(long neededApples) {\n long n = 0;\n long count = 0;\n while(count < neededApples) {\n n++;\n count += (12 * n * n);\n }\n return n * 8;\n }\n}\n", + "title": "1954. Minimum Garden Perimeter to Collect Enough Apples", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0) . Given an integer neededApples , return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot . The value of |x| is defined as:", + "description_images": [], + "constraints": [ + "x if x >= 0", + "-x if x < 0" + ], + "examples": [ + { + "text": "Example 1: Input:neededApples = 1\nOutput:8\nExplanation:A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.", + "image": "https://assets.leetcode.com/uploads/2019/08/30/1527_example_1_2.png" + }, + { + "text": "Example 2: Input:neededApples = 13\nOutput:16", + "image": null + }, + { + "text": "Example 3: Input:neededApples = 1000000000\nOutput:5040", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumPerimeter(self, nap: int) -> int:\n \n \n# here for n = 2 , there are two series : \n# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6\n# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2\n \n# how to solve:\n \n# here 3 = sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) = 0.5*2n*(2n-1)-0.5*n*n-1\n# (3) so our final 2,3,3 = 3*2+2 = (0.5*2n*(2n-1)-0.5*n*n-1)*2+n\n# (4) so final 2,3,3 = 3*n*n - 2*n\n# (5) we have 4 times repitation of (2,3,3) = 4*(2,3,3) = 4*(3*n*n - 2*n) = 12*n*n - 8*n\n# (6) we have 4 diagnal points so their sum(4 diagnal) = 4*(2*n)\n# (7) so final sum(total) = 4 diagnal sum + 4(2,3,3) = 4(2*n) + 12*n*n - 8*n = 12*n*n\n \n# so at nth distance we have total 12*n*n apples at the circumfrance\n \n# so net sum = sigma(12*n*n) = 2*n*(n+1)*(2*n+1)\n \n \n n=1\n val=2*n*(n+1)*(2*n+1)\n while(val \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.87%) | Memory: 42.6 MB (Top 7.49%)\nclass Solution {\n public int minMutation(String start, String end, String[] bank) {\n Set set = new HashSet<>();\n for(String tmp: bank){\n set.add(tmp);\n }\n if(!set.contains(end)) return -1;\n if(start.equals(end)) return 0;\n char[] var = {'A','C','G','T'};\n Queue q = new LinkedList<>();\n q.add(start);\n int count = 0;\n while(!q.isEmpty()){\n int size = q.size();\n for(int i = 0; i < size; i ++){\n String str = q.poll();\n char[] tmp = str.toCharArray();\n if(str.equals(end)) return count;\n for(int j = 0; j < 8; j ++){\n char ch = tmp[j];\n for(int k = 0; k < 4; k ++){\n tmp[j] = var[k];\n String node = new String(tmp);\n if(set.contains(node)){\n q.add(node);\n set.remove(node);\n }\n }\n tmp[j] = ch;\n }\n }\n count++;\n }\n return -1;\n }\n}", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A' , 'C' , 'G' , and 'T' . Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings start and end and the gene bank bank , return the minimum number of mutations needed to mutate from start to end . If there is no such a mutation, return -1 . Note that the starting point is assumed to be valid, so it might not be included in the bank.", + "description_images": [], + "constraints": [ + "For example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n q = deque()\n q.append(start)\n n = len(bank)\n last = 0\n used = [False] * n\n for i, x in enumerate(bank):\n if start == x:\n used[i] = True\n if end == x:\n last = i\n dist = 0\n while q:\n dist += 1\n for _ in range(len(q)):\n w = q.popleft()\n for i, x in enumerate(bank):\n if used[i]:\n continue\n bad = 0\n for j in range(8):\n if w[j] != x[j]:\n bad += 1\n if bad == 2:\n break\n if bad == 1:\n if last == i:\n return dist\n used[i] = True\n q.append(x)\n return -1\n", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput:[1]\nExplanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 13.14%) | Memory: 86.2 MB (Top 13.59%)\nclass Solution {\n public List findMinHeightTrees(int n, int[][] edges) {\n if(edges.length == 0) {\n List al = new ArrayList<>();\n al.add(0);\n return al;\n }\n HashMap> map = new HashMap<>(); // map == graph\n int [] degree = new int[n];\n for(int [] edge : edges){\n int src = edge[0];\n int dest = edge[1];\n map.putIfAbsent(src, new HashSet<>());\n map.get(src).add(dest);\n map.putIfAbsent(dest, new HashSet<>());\n map.get(dest).add(src);\n degree[src]++;\n degree[dest]++;\n }\n Queue q = new ArrayDeque<>();\n for(int i = 0; i < degree.length; i++){\n if(degree[i] == 1){\n q.offer(i);\n }\n }\n int count = n;\n while(count > 2){\n int size = q.size();\n count -= size;\n while(size-- > 0){\n Integer src = q.poll();\n\n for(Integer connection : map.get(src)){\n degree[connection]--;\n if(degree[connection] == 1){\n q.offer(connection);\n }\n }\n }\n }\n return new ArrayList<>(q);\n }\n}", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput:[1]\nExplanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n==0:\n return []\n if n==1:return [0]\n adj=[[] for i in range (n)]\n degree=[0]*n\n for i in edges:\n adj[i[0]].append(i[1])\n adj[i[1]].append(i[0])\n degree[i[0]]+=1\n degree[i[1]]+=1\n \n print(adj)\n q=[]\n for i in range(n):\n if degree[i]==1:\n q.append(i)\n \n while n>2:\n size=len(q)\n n-=size\n while size>0:\n v=q.pop(0)\n for i in adj[v]:\n degree[i]-=1\n if degree[i]==1:\n q.append(i)\n size-=1\n return q\n \n \n \n", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums ​​​ and an integer k . You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "nums.length is divisible by k", + "1 <= nums[i] <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,4], k = 2\nOutput:4\nExplanation:The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,8,1,3,1,2,2], k = 4\nOutput:6\nExplanation:The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,3,3,6,3,3], k = 3\nOutput:-1\nExplanation:It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumIncompatibility(int[] nums, int k) {\n Arrays.sort(nums);\n k=nums.length/k;\n int n = nums.length,INF=100;\n int[][] dp = new int[1<0;w++){\n if ((i&1<0;w++){\n if ((i&1<= 2: break\n return flag != 0\n if max(collections.Counter(nums).values()) > k: return -1\n assign(0)\n return self.res\n", + "title": "1681. Minimum Incompatibility", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]\nOutput:1\nExplanation:After 1 move, the array could be [1, 2, 3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,1,7]\nOutput:6\nExplanation:After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minIncrementForUnique(int[] nums) {\n \n //Approach - 1 : Using a Count array\n \n // TC : O(N)\n // SC : O(N)\n \n int max = 0;\n for(int i : nums)\n max = Math.max(max, i);\n \n int count[] = new int[nums.length + max];\n\t\t\n for(int c : nums)\n count[c]++;\n\t\t\t\n int answer = 0, choosen = 0;\n\t\tint len = count.length;\n\t\t\n for(int i = 0; i< len; i++)\n {\n if(count[i] >= 2)\n {\n choosen += count[i] - 1;\n answer -= i * (count[i] - 1);\n }\n else if(choosen > 0 && count[i] == 0)\n {\n answer += i;\n choosen--;\n }\n }\n\t\t\n return answer;\n \n \n //Approach - 2:\n \n // TC : O(nlogn)\n // SC : O(1)\n \n Arrays.sort(nums);\n int answer = 0;\n for(int i=1; i= nums[i]){\n answer += nums[i-1]- nums[i] +1;\n nums[i] = nums[i-1] + 1; \n }\n }\n return answer;\n }\n}\n", + "title": "945. Minimum Increment to Make Array Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]\nOutput:1\nExplanation:After 1 move, the array could be [1, 2, 3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,1,7]\nOutput:6\nExplanation:After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n c=0\n i=1\n num=[]\n \n while i list2.length) {\n return findRestaurant(list2, list1);\n }\n \n Map map1 = new HashMap<>();\n for (int i = 0; i < list1.length; i++) {\n map1.put(list1[i], i);\n }\n \n List mins = new ArrayList<>();\n int minSum = Integer.MAX_VALUE;\n for (int i = 0; i < list2.length; i++) {\n String rest2 = list2[i];\n if (map1.containsKey(rest2)) {\n int sum = map1.get(rest2) + i;\n if (sum < minSum) {\n mins = new ArrayList<>();\n minSum = sum;\n }\n if (sum == minSum) {\n mins.add(rest2);\n }\n }\n }\n \n return mins.toArray(new String[mins.size()]);\n }\n}\n", + "title": "599. Minimum Index Sum of Two Lists", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum . If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.", + "description_images": [], + "constraints": [ + "1 <= list1.length, list2.length <= 1000", + "1 <= list1[i].length, list2[i].length <= 30", + "list1[i] and list2[i] consist of spaces ' ' and English letters.", + "All the stings of list1 are unique .", + "All the stings of list2 are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]\nOutput:[\"Shogun\"]\nExplanation:The only restaurant they both like is \"Shogun\".", + "image": null + }, + { + "text": "Example 2: Input:list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"KFC\",\"Shogun\",\"Burger King\"]\nOutput:[\"Shogun\"]\nExplanation:The restaurant they both like and have the least index sum is \"Shogun\" with index sum 1 (0+1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n \n \n hashmap1 = {}\n hashmap2 = {}\n common = {}\n for i in range(len(list1)):\n \n hashmap1[list1[i]] = i \n \n \n for j in range(len(list2)):\n hashmap2[list2[j]] = j \n \n \n \n for i in hashmap1:\n \n if i in hashmap2:\n print(1)\n common[i] = hashmap1[i] + hashmap2[i]\n \n \n common = list(common.items())\n \n answer =[]\n minimum = float(\"inf\")\n \n for i in range(0,len(common)):\n \n if common[i][1] < minimum:\n minimum = common[i][1]\n \n for i in range(len(common)):\n \n if common[i][1] == minimum:\n answer.append(common[i][0])\n \n return answer\n \n \n \n", + "title": "599. Minimum Index Sum of Two Lists", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array tasks where tasks[i] = [actual i , minimum i ] : For example, if the task is [10, 12] and your current energy is 11 , you cannot start this task. However, if your current energy is 13 , you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks .", + "description_images": [], + "constraints": [ + "actual i is the actual amount of energy you spend to finish the i th task.", + "minimum i is the minimum amount of energy you require to begin the i th task." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [[1,2],[2,4],[4,8]]\nOutput:8\nExplanation:Starting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput:32\nExplanation:Starting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput:27\nExplanation:Starting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\nclass Solution {\n public int minimumEffort(int[][] tasks)\n {\n Arrays.sort(tasks, new Comparator(){\n @Override\n public int compare(int[] a, int[] b)\n {\n return (b[1]-b[0])-(a[1]-a[0]);\n }\n });\n int sum=0, max=0;\n for(int i=0;i int:\n tasks.sort(key=lambda x: x[0]-x[1])\n def ok(mid):\n for actual, minimum in tasks:\n if minimum > mid or actual > mid: return False\n if minimum <= mid: mid -= actual\n return True\n l, r = 0, 10 ** 9\n while l <= r:\n mid = (l+r) // 2\n if ok(mid): r = mid - 1\n else: l = mid + 1\n return l", + "title": "1665. Minimum Initial Energy to Finish Tasks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s . In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"zzazz\"\nOutput:0\nExplanation:The string \"zzazz\" is already palindrome we don't need any insertions.", + "image": null + }, + { + "text": "Example 2: Input:s = \"mbadm\"\nOutput:2\nExplanation:String can be \"mbdadbm\" or \"mdbabdm\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\"\nOutput:5\nExplanation:Inserting 5 characters the string becomes \"leetcodocteel\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 71.55%) | Memory: 43.3 MB (Top 97.03%)\nclass Solution {\n public int minInsertions(String s) {\n StringBuilder sb = new StringBuilder(s);\n String str = sb.reverse().toString();\n int m=s.length();\n int n=str.length();\n System.out.println(str);\n return LCS(s,str,m,n);\n\n }\n public int LCS(String x, String y,int m,int n){\n int [][] t = new int [m+1][n+1];\n for(int i=0;i int:\n n = len(s)\n prev_prev = [0]*n\n prev = [0]*n\n curr = [0] * n\n\n for l in range(1, n):\n for i in range(l, n):\n if s[i] == s[i-l]:\n curr[i] = prev_prev[i-1]\n else:\n curr[i] = min(prev[i-1], prev[i])+1\n # print(curr)\n prev_prev, prev, curr = prev, curr, prev_prev\n \n return prev[-1]", + "title": "1312. Minimum Insertion Steps to Make a String Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a parentheses string s containing only the characters '(' and ')' . A parentheses string is balanced if: In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced.", + "description_images": [], + "constraints": [ + "Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))' .", + "Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()))\"\nOutput:1\nExplanation:The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"())\"\nOutput:0\nExplanation:The string is already balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"))())(\"\nOutput:3\nExplanation:Add '(' to match the first '))', Add '))' to match the last '('.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 44.46%) | Memory: 51.9 MB (Top 75.57%)\nclass Solution {\n public int minInsertions(String s) {\n int open=0;\n int ans=0;\n\n for(int i=0;i0){\n open--;\n }\n else{\n ans++;\n }\n }\n else{\n if(open>0){\n open--;\n ans++;\n }\n else{\n ans+=2;\n }\n }\n }\n }\n ans+=2*open;\n return ans;\n }\n}", + "title": "1541. Minimum Insertions to Balance a Parentheses String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a parentheses string s containing only the characters '(' and ')' . A parentheses string is balanced if: In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced.", + "description_images": [], + "constraints": [ + "Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))' .", + "Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()))\"\nOutput:1\nExplanation:The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"())\"\nOutput:0\nExplanation:The string is already balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"))())(\"\nOutput:3\nExplanation:Add '(' to match the first '))', Add '))' to match the last '('.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minInsertions(self, s: str) -> int:\n leftbrackets = insertions = 0\n i, n = 0, len(s)\n\n while i < n:\n if s[i] == '(':\n leftbrackets += 1\n elif s[i] == ')':\n if i == n-1 or s[i+1] != ')': insertions += 1\n else: i += 1\n \n if not leftbrackets: insertions += 1\n else: leftbrackets -= 1\n \n i += 1\n \n return leftbrackets * 2 + insertions", + "title": "1541. Minimum Insertions to Balance a Parentheses String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]\nOutput:[3,3,1,4]\nExplanation:The queries are processed as follows:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]\nOutput:[2,-1,4,6]\nExplanation:The queries are processed as follows:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 250 ms (Top 27.92%) | Memory: 125.9 MB (Top 80.67%)\nclass Solution {\n public int[] minInterval(int[][] intervals, int[] queries) {\n //sort intervals\n Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n //add [index,query]\n int[][] q = new int[queries.length][2];\n for (int i=0;i a[1]-b[1]);\n //store the minimum intervals in the priority queue, min heap\n Queue pq = new PriorityQueue<>((a,b) -> (a[1]-a[0])-(b[1]-b[0]));\n int[] result = new int[queries.length];\n int j = 0;\n for (int i=0;i List[int]:\n \n # sort queries from small to large\n q = deque(sorted([(x, i) for i, x in enumerate(queries)]))\n \n # answer to queries, initial state set to -1\n ans = [-1] * len(queries)\n\n # sort intervals by low, high and size\n ivals = deque(sorted([(a, b, b - a + 1) for a, b in intervals]))\n \n # available intervals\n cands = []\n\n \n while q:\n x, i = q.popleft()\n \n # if lower bound of intervals on the top of stack <= current query\n while ivals and x >= ivals[0][0]:\n a, b, c = ivals.popleft()\n # if higher bound of intervals also meets the requirements\n # if not then discard the interval\n if x <= b:\n heappush(cands, (c, b, a))\n \n # udpate available intervals by removing old ones which no longer has a eligible higher bound\n while cands:\n c, b, a = heappop(cands)\n if x <= b:\n ans[i] = c\n heappush(cands, (c, b, a))\n break\n\n return ans", + "title": "1851. Minimum Interval to Include Each Query", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A certain bug's home is on the x-axis at position x . Help them get there from position 0 . The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden , where forbidden[i] means that the bug cannot jump to the position forbidden[i] , and integers a , b , and x , return the minimum number of jumps needed for the bug to reach its home . If there is no possible sequence of jumps that lands the bug on position x , return -1.", + "description_images": [], + "constraints": [ + "It can jump exactly a positions forward (to the right).", + "It can jump exactly b positions backward (to the left).", + "It cannot jump backward twice in a row.", + "It cannot jump to any forbidden positions." + ], + "examples": [ + { + "text": "Example 1: Input:forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput:3\nExplanation:3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.", + "image": null + }, + { + "text": "Example 2: Input:forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput:2\nExplanation:One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumJumps(int[] forbidden, int a, int b, int x) {\n \n // Visited Set\n Set visited = new HashSet();\n \n // Add forbidden coordinates to visited\n for (int i = 0; i < forbidden.length; i++) {\n visited.add(forbidden[i]);\n }\n \n // Distance/ Jumps map\n Map jumps = new HashMap<>();\n jumps.put(0, 0);\n \n // BFS Queue\n Queue q = new LinkedList<>();\n q.add(new Integer[] {0, 1});\n \n // BFS \n while (q.size() != 0) {\n \n Integer[] ud = q.poll();\n \n int u = ud[0], d = ud[1];\n \n // x found\n if (u == x) {\n return jumps.get(u);\n }\n \n // jump right\n if (u + a < 6001 && !visited.contains(u+a)) {\n q.add(new Integer[] {u+a, 1});\n visited.add(u+a);\n jumps.put(u+a, jumps.get(u) + 1);\n }\n \n // jump left\n if (d != -1 && u - b > -1 && !visited.contains(u-b)) {\n q.add(new Integer[] {u-b, -1});\n jumps.put(u-b, jumps.get(u) + 1);\n }\n \n }\n \n return -1;\n \n }\n}\n", + "title": "1654. Minimum Jumps to Reach Home", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A certain bug's home is on the x-axis at position x . Help them get there from position 0 . The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden , where forbidden[i] means that the bug cannot jump to the position forbidden[i] , and integers a , b , and x , return the minimum number of jumps needed for the bug to reach its home . If there is no possible sequence of jumps that lands the bug on position x , return -1.", + "description_images": [], + "constraints": [ + "It can jump exactly a positions forward (to the right).", + "It can jump exactly b positions backward (to the left).", + "It cannot jump backward twice in a row.", + "It cannot jump to any forbidden positions." + ], + "examples": [ + { + "text": "Example 1: Input:forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput:3\nExplanation:3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.", + "image": null + }, + { + "text": "Example 2: Input:forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput:2\nExplanation:One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int:\n fb = set(fb)\n q = deque([[0,0,True]])\n while(q):\n n,l,isf = q.popleft()\n if(n<0 or n in fb or n>2000+2*b):\n continue\n fb.add(n)\n if(n==x):\n return l\n if isf and n-b>0:\n q.append([n-b,l+1,False]) \n q.append([n+a,l+1,True])\n return -1", + "title": "1654. Minimum Jumps to Reach Home", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting only of characters 'a' , 'b' , and 'c' . You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times) .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s only consists of characters 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ca\"\nOutput:2\nExplanation:You can't remove any characters, so the string stays as is.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cabaabac\"\nOutput:0\nExplanation:An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabccabba\"\nOutput:3\nExplanation:An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 45.06%) | Memory: 54.1 MB (Top 20.99%)\nclass Solution {\n public int minimumLength(String s) {\n int length = s.length();\n char[] chars = s.toCharArray();\n for(int left = 0,right = chars.length-1;left < right;){\n if(chars[left] == chars[right]){\n char c = chars[left];\n while(left < right && chars[left] == c ){\n left++;\n length--;\n\n }\n\n while (right >= left && chars[right] == c){\n right--;\n length--;\n\n }\n }else {\n break;\n }\n }\n return length;\n }\n}", + "title": "1750. Minimum Length of String After Deleting Similar Ends", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s consisting only of characters 'a' , 'b' , and 'c' . You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times) .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s only consists of characters 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ca\"\nOutput:2\nExplanation:You can't remove any characters, so the string stays as is.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cabaabac\"\nOutput:0\nExplanation:An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabccabba\"\nOutput:3\nExplanation:An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumLength(self, s: str) -> int:\n while(len(s)>1 and s[0]==s[-1]):\n s=s.strip(s[0])\n else:\n return len(s)\n", + "title": "1750. Minimum Length of String After Deleting Similar Ends", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums where the i th bag contains nums[i] balls. You are also given an integer maxOperations . You can perform the following operation at most maxOperations times: Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations .", + "description_images": [], + "constraints": [ + "Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.", + "For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9], maxOperations = 2\nOutput:3\nExplanation:- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,8,2], maxOperations = 4\nOutput:2\nExplanation:- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,17], maxOperations = 2\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 86.75%) | Memory: 59.70 MB (Top 45.73%)\n\nclass Solution {\n\npublic int minimumSize(int[] nums, int maxOperations) {\n//initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at the price of time consumption.\n//The answer should be the minimized max value.\n int min = 0;\n int max = 1000000000;\n\t//Compared with min math.ceil(a/mid) gives the number of divided bags, we subtract the number by 1 to get the subdivision operation times.\n count+=(a-1)/mid;\n }\n\t\t//if count < maxOperations, max WOULD be further minimized and set to mid; \n\t\t//if count = maxOperations, max still COULD be further minimized and set to mid. \n\t\t//so we combine < and = cases together in one if condition\n if (count <= maxOperations) {\n\t\t//max = mid - 1 will not work in this case becasue mid could be the correct answer. \n\t\t//To not miss the correct answer we set a relatively \"loose\" boundary for max and min.\n max = mid;\n } else{\n min = mid;\n }\n }\n\t//Now we find the minimized max value\n return max;\n}\n}", + "title": "1760. Minimum Limit of Balls in a Bag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums where the i th bag contains nums[i] balls. You are also given an integer maxOperations . You can perform the following operation at most maxOperations times: Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations .", + "description_images": [], + "constraints": [ + "Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.", + "For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9], maxOperations = 2\nOutput:3\nExplanation:- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,8,2], maxOperations = 4\nOutput:2\nExplanation:- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,17], maxOperations = 2\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n l, r = 1, max(nums)\n while l < r:\n mid = (l + r) // 2\n if sum([(n - 1) // mid for n in nums]) > maxOperations: \n l = mid + 1\n else:\n r = mid\n return l\n", + "title": "1760. Minimum Limit of Balls in a Bag", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array stockPrices where stockPrices[i] = [day i , price i ] indicates the price of the stock on day day i is price i . A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart .", + "description_images": [], + "constraints": [ + "1 <= stockPrices.length <= 10^5", + "stockPrices[i].length == 2", + "1 <= day i , price i <= 10^9", + "All day i are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]\nOutput:3\nExplanation:The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.\nThe following 3 lines can be drawn to represent the line chart:\n- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).\n- Line 2 (in blue) from (4,4) to (5,4).\n- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).\nIt can be shown that it is not possible to represent the line chart using less than 3 lines.", + "image": "https://assets.leetcode.com/uploads/2022/03/30/ex0.png" + }, + { + "text": "Example 2: Input:stockPrices = [[3,4],[1,2],[7,8],[2,3]]\nOutput:1\nExplanation:As shown in the diagram above, the line chart can be represented with a single line.", + "image": "https://assets.leetcode.com/uploads/2022/03/30/ex1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 71.43%) | Memory: 109.9 MB (Top 23.21%)\nclass Solution {\n public int minimumLines(int[][] stockPrices) {\n if(stockPrices.length == 1) return 0;\n int count = 1;\n Arrays.sort(stockPrices,(o1,o2)->o1[0]-o2[0]);\n for(int i=1;i int:\n if len(prices) == 1:\n return 0\n else:\n prices.sort(key=itemgetter(0))\n\n return self.using_slope(prices)\n # return self.using_cross_product(prices)\n\n @staticmethod\n def using_slope(prices: list[Point]) -> int:\n output, slope = 1, Solution.dy_by_dx\n\n ab = next(pairs := pairwise(prices))\n\n for bc in pairs:\n if slope(ab) != slope(bc):\n output += 1\n\n ab = bc\n\n return output\n\n @staticmethod\n def dy_by_dx(ab: tuple[Point, Point]) -> float | Fraction:\n (x1, y1), (x2, y2) = ab\n\n dx, dy = x2 - x1, y2 - y1\n\n if dx == 0:\n # 1. dx is 0, it means we have a vertical line going from (x1, y1). So whether dy is positive or\n # negative, it does not matter\n # 2. infinity can not be represented by fraction module so returning it directly from math module\n return inf\n else:\n # To avoid floating point error, we use fraction module.\n\n # (Simple divisions can give same results for example (apparently one of the test cases),\n # 499999998/499999999 and 499999999/500000000 gives same result, and that is where Fraction\n # class shines)\n return Fraction(dy, dx)\n\n @staticmethod\n def using_cross_product(prices: list[Point]) -> int:\n output, on_line = 1, Solution.lie_on_same_line\n\n a = next(itr := iter(prices))\n\n for b, c in pairwise(itr):\n if not on_line(a, b, c):\n output += 1\n\n a = b\n\n return output\n\n @staticmethod\n def lie_on_same_line(a: Point, b: Point, c: Point) -> bool:\n (x1, y1), (x2, y2), (x3, y3) = a, b, c\n\n return (y2 - y1) * (x3 - x2) == (x2 - x1) * (y3 - y2)", + "title": "2280. Minimum Lines to Represent a Line Chart", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of n characters which are either 'X' or 'O' . A move is defined as selecting three consecutive characters of s and converting them to 'O' . Note that if a move is applied to the character 'O' , it will stay the same . Return the minimum number of moves required so that all the characters of s are converted to 'O' .", + "description_images": [], + "constraints": [ + "3 <= s.length <= 1000", + "s[i] is either 'X' or 'O' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"XXX\"\nOutput:1\nExplanation:XXX-> OOO\nWe select all the 3 characters and convert them in one move.", + "image": null + }, + { + "text": "Example 2: Input:s = \"XXOX\"\nOutput:2\nExplanation:XXOX -> OOOX-> OOOO\nWe select the first 3 characters in the first move, and convert them to'O'.\nThen we select the last 3 characters and convert them so that the final string contains all'O's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"OOOO\"\nOutput:0\nExplanation:There are no'X'sinsto convert.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 83.6%) | Memory: 41.00 MB (Top 8.7%)\n\nclass Solution {\n public int minimumMoves(String s) {\n int i=0;\n int step=0;\n while(i OOO\nWe select all the 3 characters and convert them in one move.", + "image": null + }, + { + "text": "Example 2: Input:s = \"XXOX\"\nOutput:2\nExplanation:XXOX -> OOOX-> OOOO\nWe select the first 3 characters in the first move, and convert them to'O'.\nThen we select the last 3 characters and convert them so that the final string contains all'O's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"OOOO\"\nOutput:0\nExplanation:There are no'X'sinsto convert.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 5.43%) | Memory: 17.30 MB (Top 11.89%)\n\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n ans = i = 0\n while i < len(s): \n if s[i] == \"X\": \n ans += 1\n i += 3\n else: i += 1\n return ans \n", + "title": "2027. Minimum Moves to Convert String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of size n , return the minimum number of moves required to make all array elements equal . In one move, you can increment n - 1 elements of the array by 1 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:3\nExplanation:Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves(int[] nums) {\n int min=Integer.MAX_VALUE;\n int count=0;\n for(int i:nums)\n min=Math.min(i,min);\n \n for(int i=0;i [2,3,3] => [3,4,3] => [4,4,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves(self, nums: List[int]) -> int:\n return sum(nums)-min(nums)*len(nums)\n", + "title": "453. Minimum Moves to Equal Array Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of size n , return the minimum number of moves required to make all array elements equal . In one move, you can increment or decrement an element of the array by 1 . Test cases are designed so that the answer will fit in a 32-bit integer.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:2\nExplanation:Only two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,10,2,9]\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves2(int[] nums) {\n Arrays.sort(nums);\n int idx=(nums.length-1)/2;\n int sum=0;\n for(int i=0;i [2,2,3] => [2,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,10,2,9]\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n \n n=len(nums)\n nums.sort()\n \n if n%2==1:\n median=nums[n//2]\n else:\n median = (nums[n//2 - 1] + nums[n//2]) // 2\n \n ans=0\n \n for val in nums:\n ans+=abs(val-median)\n \n return ans\n \n", + "title": "462. Minimum Moves to Equal Array Elements II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of even length n and an integer limit . In one move, you can replace any integer from nums with another integer between 1 and limit , inclusive. The array nums is complementary if for all indices i ( 0-indexed ), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i , nums[i] + nums[n - 1 - i] = 5 . Return the minimum number of moves required to make nums complementary .", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^5", + "1 <= nums[i] <= limit <= 10^5", + "n is even." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,3], limit = 4\nOutput:1\nExplanation:In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,1], limit = 2\nOutput:2\nExplanation:In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,1,2], limit = 2\nOutput:0\nExplanation:nums is already complementary.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves(int[] nums, int limit) {\n int[] oneMove = new int[2 * limit + 2];\n Map noMove = new HashMap<>();\n\n for (int i = 0; i < nums.length / 2; i++){\n int j = nums.length - 1 - i;\n noMove.merge(nums[i] + nums[j], 1, Integer::sum);\n oneMove[Math.min(nums[i], nums[j]) + 1]++;\n oneMove[Math.max(nums[i], nums[j]) + limit + 1]--;\n }\n\n int ans = nums.length, one = 0;\n for (int i = 2; i <= 2 * limit; i++){\n one += oneMove[i];\n ans = Math.min(ans, one + 2 * (nums.length / 2 - one) - noMove.getOrDefault(i, 0));\n }\n\n return ans;\n }\n}\n", + "title": "1674. Minimum Moves to Make Array Complementary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums of even length n and an integer limit . In one move, you can replace any integer from nums with another integer between 1 and limit , inclusive. The array nums is complementary if for all indices i ( 0-indexed ), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i , nums[i] + nums[n - 1 - i] = 5 . Return the minimum number of moves required to make nums complementary .", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^5", + "1 <= nums[i] <= limit <= 10^5", + "n is even." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,3], limit = 4\nOutput:1\nExplanation:In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,1], limit = 2\nOutput:2\nExplanation:In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,1,2], limit = 2\nOutput:0\nExplanation:nums is already complementary.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def minMoves(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n overlay_arr = [0] * (2*limit+2)\n for i in range(n//2):\n left_boundary = min(nums[i], nums[n-1-i]) + 1\n no_move_value = nums[i] + nums[n-1-i]\n right_boundary = max(nums[i], nums[n-1-i]) + limit\n overlay_arr[left_boundary] -= 1\n overlay_arr[no_move_value] -= 1\n overlay_arr[no_move_value+1] += 1\n overlay_arr[right_boundary+1] += 1\n curr_moves = n #initial assumption of two moves for each pair\n res = float(\"inf\")\n\t\t# start Sweeping\n for i in range(2, 2*limit+1):\n curr_moves += overlay_arr[i]\n res = min(res, curr_moves)\n return res\n", + "title": "1674. Minimum Moves to Make Array Complementary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target . If there is no way to reach the target, return -1 .", + "description_images": [], + "constraints": [ + "The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).", + "The character '.' represents the floor which means a free cell to walk.", + "The character '#' represents the wall which means an obstacle (impossible to walk there).", + "There is only one box 'B' and one target cell 'T' in the grid .", + "The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push .", + "The player cannot walk through the box." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:3\nExplanation:We return only the number of times the box is pushed.", + "image": "https://assets.leetcode.com/uploads/2019/11/06/sample_1_1620.png" + }, + { + "text": "Example 2: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:5\nExplanation:push the box down, left, left, up and up.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 51.89%) | Memory: 54.4 MB (Top 47.17%)\n/**\n Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves)\n Uses BFS/A* Algorithm to visit valid transition states\n Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations\n*/\nclass Solution {\n private int targetRow;\n private int targetCol;\n private char[][] grid;\n private static int[][] DIRS = {\n {1,0}, //Down\n {-1,0},//Up\n {0,1}, //Right\n {0,-1} //Left\n };\n\n /**\n State holds shopkeeper and box location, as well as how many times the box has been pushed\n */\n class State implements Comparable{\n int personRow;\n int personCol;\n int boxRow;\n int boxCol;\n int boxPushes;\n\n public State(int personRow, int personCol, int boxRow, int boxCol, int boxPushes){\n this.personRow = personRow;\n this.personCol = personCol;\n this.boxRow = boxRow;\n this.boxCol = boxCol;\n this.boxPushes = boxPushes;\n }\n\n // Override equals - used along with hashcode when we have visited HashSet\n public boolean equals(Object o){\n State other = (State) o;\n return\n this.personRow == other.personRow &&\n this.personCol == other.personCol &&\n this.boxRow == other.boxRow &&\n this.boxCol == other.boxCol;\n }\n\n // Override the hashCode - Note: it's okay for this to have collisions\n // But it won't due to the problem constraint that there is a bound on NxM dimensions\n public int hashCode(){\n return personRow *10_000 + personCol * 1_000 + boxRow * 100 + boxCol;\n }\n\n // Override to string method - helpful in debugging state.\n public String toString(){\n return \"ShopKeeper:{row:\"+personRow+\", col:\"+personCol+\"}\" +\n \"Box:{row:\"+boxRow+\", col:\"+boxCol+\"}\";\n }\n\n // Implement comparable interface such that we return the state that\n // has the possibility of lowest distance using box push count + Manhattan distance\n public int compareTo(State other){\n int minDistanceThis = this.boxPushes + distanceToTarget(this);\n int minDistanceOther = other.boxPushes + distanceToTarget(other);\n return Integer.compare(minDistanceThis, minDistanceOther);\n }\n\n }\n\n // Calculates Manhattan distance\n private int distanceToTarget(State state){\n int yDiff = Math.abs(state.boxCol - targetCol);\n int xDiff = Math.abs(state.boxRow - targetRow);\n return yDiff + xDiff;\n }\n\n /**\n Given a state, compare box location to target location to determine if it is\n a solution state.\n */\n private boolean isSolutionState(State state){\n return state.boxRow == targetRow && state.boxCol == targetCol;\n }\n\n /**\n Given a state, finds all valid transition states.\n This is accomplished by moving the ShopKeeper in all 4 directions and validate\n - Next ShopKeeper location is in bounds and is not a wall\n\n We have additional logic for when the next shopkeeper location is the box location:\n - Get next box location, by pushing the same direction, again validate that\n the next box location is in bounds, and is not a wall.\n\n If it's a valid transition, create the new state with the new shop keeper location\n and if the box moved, the new box location (also increment the number of box moves).\n\n **/\n private List getNeighbors(State state){\n\n int personRow = state.personRow;\n int personCol = state.personCol;\n int boxRow = state.boxRow;\n int boxCol = state.boxCol;\n\n List states = new ArrayList<>();\n for(int[] dir : DIRS){\n int rowMove = dir[0];\n int colMove = dir[1];\n int personRowNew = personRow + rowMove;\n int personColNew = personCol + colMove;\n // Shopkeeper cannot move into wall or go out of bounds skip to next direction\n if(!inBounds(personRowNew, personColNew) ||\n isWall(personRowNew, personColNew)){\n continue;\n }\n // Whether or not person will collide with box\n boolean willPushBox = personRowNew == boxRow && personColNew == boxCol;\n\n if(willPushBox){\n int boxRowNew = boxRow + rowMove;\n int boxColNew = boxCol + colMove;\n // Validate box can be pushed - if so push box and add to neighbor states\n if(inBounds(boxRowNew, boxColNew) &&\n !isWall(boxRowNew, boxColNew)){\n states.add(new State(personRowNew, personColNew, boxRowNew, boxColNew, state.boxPushes + 1));\n }\n } else {\n //Shop keeper moved, but not box\n states.add(new State(personRowNew, personColNew, boxRow, boxCol, state.boxPushes));\n }\n }\n return states;\n\n }\n\n // Given row/col, return whether it is wall\n private boolean isWall(int row, int col){\n char cell = grid[row][col];\n return cell == '#';\n }\n\n // Given row/col return whether is inBounds\n private boolean inBounds(int row, int col){\n int rows = grid.length;\n int cols = grid[0].length;\n if(row < 0 || col < 0 || row > rows-1 || col > cols-1){\n return false;\n }\n return true;\n }\n\n /**\n Returns initial state. Also finds and stores the target location.\n */\n private State getInitialState(){\n\n int shopKeeperRow=0;\n int shopKeeperCol=0;\n\n int boxRow = 0;\n int boxCol = 0;\n\n for(int r=0; r queue = new PriorityQueue<>();\n Set visited = new HashSet<>();\n queue.offer(initialState);\n\n // Explore every state using BSF and keep track of the best solution\n while(!queue.isEmpty()){\n State state = queue.poll();\n if(visited.contains(state)){\n continue;\n }\n visited.add(state);\n /*\n Note: the reason we can return the first solution state we find, is because we are\n using priority queue with minDistance heuristic which means the first solution we find\n is guaranteed to be the optimal solution - (A* Algorithm)\n */\n if(isSolutionState(state)){\n return state.boxPushes;\n }\n for(State neighbor : getNeighbors(state)){\n if(!visited.contains(neighbor)){\n queue.offer(neighbor);\n }\n };\n }\n // No solution - return -1\n return -1;\n }\n\n}", + "title": "1263. Minimum Moves to Move a Box to Their Target Location", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target . If there is no way to reach the target, return -1 .", + "description_images": [], + "constraints": [ + "The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).", + "The character '.' represents the floor which means a free cell to walk.", + "The character '#' represents the wall which means an obstacle (impossible to walk there).", + "There is only one box 'B' and one target cell 'T' in the grid .", + "The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push .", + "The player cannot walk through the box." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:3\nExplanation:We return only the number of times the box is pushed.", + "image": "https://assets.leetcode.com/uploads/2019/11/06/sample_1_1620.png" + }, + { + "text": "Example 2: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput:5\nExplanation:push the box down, left, left, up and up.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n m,n=len(grid),len(grid[0])\n q=deque()\n start,target,box=(0,0),(0,0),(0,0)\n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"B\":\n box=(i,j)\n elif grid[i][j]==\"T\":\n target=(i,j)\n elif grid[i][j]==\"S\":\n start=(i,j)\n q.append((box[0],box[1],0,start[0],start[1]))\n visited=set()\n directions=((1,0,-1,0),(0,1,0,-1),(-1,0,1,0),(0,-1,0,1))\n visited.add(box+box)\n def solve(i,j,bi,bj):\n nonlocal seen\n if (i,j)==(bi,bj):\n return True\n ans=False\n for d in directions:\n ni,nj=i+d[0],j+d[1]\n if 0<=nim+n:\n return -1\n for d in directions:\n ni,nj,bi,bj=i+d[0],j+d[1],i+d[2],j+d[3]\n if 0<=ni int:\n c=0\n while(maxDoubles>0 and target>1):\n c += target%2\n target //= 2\n c += 1\n maxDoubles -=1\n return c + target-1", + "title": "2139. Minimum Moves to Reach Target Score", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1) . The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1) . In one move the snake can: Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/image.png" + ], + "constraints": [ + "Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c) .", + "Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]\nOutput:11\nExplanation:One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 25.8%) | Memory: 45.52 MB (Top 12.9%)\n\nclass Solution {\n public int minimumMoves(int[][] grid) {\n \n int n = grid.length; \n //boolean[][][][] visited = new boolean[n][n][n][n];\n Set set = new HashSet<>();\n \n Queue q = new LinkedList<>();\n q.offer(new Position(0,0,0,1)); \n int count = 0;\n \n if(grid[n-1][n-2] == 1 || grid[n-1][n-1] == 1)\n return -1;\n \n while(!q.isEmpty()){\n ++count;\n Queue nextq = new LinkedList<>();\n while(!q.isEmpty()){\n \n Position p = q.poll();\n\n int r1 = p.getr1();\n int r2 = p.getr2();\n int c1 = p.getc1();\n int c2 = p.getc2();\n \n if(r1 == n-1 && r2 == n-1 && c1 == n-2 && c2==n-1)\n return count-1;\n \n if(set.contains(p))\n continue;\n \n if(c1+1 < n && grid[r1] [c1+1] != 1 && c2+1 < n && grid[r2] [c2+1] != 1)\n nextq.offer(new Position(r1, c1+1, r2, c2+1));\n if(r1+1 < n && grid[r1+1] [c1] != 1 && r2+1 < n && grid[r2+1] [c2] != 1)\n nextq.offer(new Position(r1+1, c1, r2+1, c2));\n \n if(r1 == r2 && r1+1 < n && r2+1 < n && grid[r1+1][c1] == 0 && grid[r2+1][c2] == 0 && grid[r1+1][c1] == 0)\n nextq.offer(new Position(r1,c1, r1+1, c1));\n \n if(c1 == c2 && c1+1 < n && c2+1 < n && grid[r1][c1+1] == 0 && grid[r2][c1+1] == 0 && grid[r1][c1+1] == 0)\n nextq.offer(new Position(r1,c1, r1, c1+1));\n set.add(p);\n }\n q = nextq;\n }\n return -1;\n }\n \n private class Position{\n int r1;\n int c1;\n int r2;\n int c2;\n \n public Position(int r1, int c1, int r2, int c2){\n this.r1 = r1;\n this.r2 = r2;\n this.c1 =c1;\n this.c2 = c2;\n }\n \n public int getr1(){\n return this.r1;\n }\n public int getr2(){\n return this.r2;\n }\n public int getc1(){\n return this.c1;\n }\n public int getc2(){\n return this.c2;\n }\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * r1 + c1 + prime *r2 + c2;\n return result;\n }\n \n @Override\n public boolean equals(Object obj) {\n Position p = (Position) obj;\n if(this.r1 == p.getr1() && this.r2 ==p.getr2() && this.c1 == p.getc1() && this.c2==p.getc2())\n return true;\n else\n return false;\n }\n } \n}", + "title": "1210. Minimum Moves to Reach Target with Rotations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1) . The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1) . In one move the snake can: Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/image.png" + ], + "constraints": [ + "Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c) .", + "Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]\nOutput:11\nExplanation:One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n queue , vis , n = [(0,1,0,0)] , {} , len(grid)\n while queue:\n x,y,pos,moves = queue.pop(0)\n if x == y == n-1 and pos == 0: return moves\n if pos == 0:\n if y + 1 < n and grid[x][y+1] == 0 and (x,y+1,0) not in vis:\n vis[(x,y+1,0)] = True\n queue.append((x,y+1,0,moves+1))\n \n if x + 1 < n and grid[x+1][y-1] == 0 and grid[x+1][y] == 0:\n if (x+1,y-1,1) not in vis:\n vis[(x+1,y-1,1)] = True\n queue.append((x+1,y-1,1,moves+1))\n if (x+1,y,0) not in vis:\n vis[(x+1,y,0)] = True\n queue.append((x+1,y,0,moves+1))\n else:\n if x + 1 < n and grid[x+1][y] == 0 and (x+1,y,1) not in vis:\n vis[(x+1,y,1)] = True\n queue.append((x+1,y,1,moves+1))\n if y + 1 < n and grid[x-1][y+1] == grid[x][y+1] == 0:\n if (x-1,y+1,0) not in vis:\n vis[(x-1,y+1,0)] = True\n queue.append((x-1,y+1,0,moves+1))\n if (x,y+1,1) not in vis:\n vis[(x,y+1,1)] = True\n queue.append((x,y+1,1,moves+1))\n return -1\n", + "title": "1210. Minimum Moves to Reach Target with Rotations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer p . Consider an array nums ( 1-indexed ) that consists of the integers in the inclusive range [1, 2 p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 11 0 1 and y = 00 1 1 , after swapping the 2 nd bit from the right, we have x = 11 1 1 and y = 00 0 1 . Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7 . Note: The answer should be the minimum product before the modulo operation is done.", + "description_images": [], + "constraints": [ + "Choose two elements x and y from nums .", + "Choose a bit in x and swap it with its corresponding bit in y . Corresponding bit refers to the bit that is in the same position in the other integer." + ], + "examples": [ + { + "text": "Example 1: Input:p = 1\nOutput:1\nExplanation:nums = [1].\nThere is only one element, so the product equals that element.", + "image": null + }, + { + "text": "Example 2: Input:p = 2\nOutput:6\nExplanation:nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.", + "image": null + }, + { + "text": "Example 3: Input:p = 3\nOutput:1512\nExplanation:nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001,110, 011, 100,001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mod = 1_000_000_007;\n public int minNonZeroProduct(int p) {\n if (p == 1) return 1;\n \n long mx = (long)(Math.pow(2, p)) - 1;\n long sm = mx - 1;\n long n = sm/2;\n long sum = rec(sm, n);\n \n return (int)(sum * (mx % mod) % mod); \n }\n \n public long rec(long val, long n) {\n if (n == 0) return 1;\n if (n == 1) return (val % mod);\n \n long newVal = ((val % mod) * (val % mod)) % mod;\n \n if (n % 2 != 0) {\n return ((rec(newVal, n/2) % mod) * (val % mod)) % mod;\n }\n \n return rec(newVal, n/2) % mod;\n }\n}\n", + "title": "1969. Minimum Non-Zero Product of the Array Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer p . Consider an array nums ( 1-indexed ) that consists of the integers in the inclusive range [1, 2 p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 11 0 1 and y = 00 1 1 , after swapping the 2 nd bit from the right, we have x = 11 1 1 and y = 00 0 1 . Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7 . Note: The answer should be the minimum product before the modulo operation is done.", + "description_images": [], + "constraints": [ + "Choose two elements x and y from nums .", + "Choose a bit in x and swap it with its corresponding bit in y . Corresponding bit refers to the bit that is in the same position in the other integer." + ], + "examples": [ + { + "text": "Example 1: Input:p = 1\nOutput:1\nExplanation:nums = [1].\nThere is only one element, so the product equals that element.", + "image": null + }, + { + "text": "Example 2: Input:p = 2\nOutput:6\nExplanation:nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.", + "image": null + }, + { + "text": "Example 3: Input:p = 3\nOutput:1512\nExplanation:nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001,110, 011, 100,001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minNonZeroProduct(self, p: int) -> int:\n mod = 10**9+7\n return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod\n", + "title": "1969. Minimum Non-Zero Product of the Array Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]\nOutput:4\nExplanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 51.6%) | Memory: 74.38 MB (Top 92.9%)\n\nclass Solution {\n public int findMinArrowShots(int[][] points) {\n \n int minNumArrows = 1;\n Arrays.sort(points, new Comparator(){\n @Override\n public int compare(int[] i1, int[] i2)\n {\n if(i1[0] < i2[0])\n return -1;\n else if (i1[0] > i2[0])\n return 1;\n return 0;\n }\n });\n \n // This is where they will trip you up ( at the merge stage )\n // Wait ... do we actually have to merge here? The intervals have been sorted already\n // No you must merge\n // See if they can be merged\n // If mergeable - overwrite OR write into a new subintervals code ( new ArrayList ) \n // Ok ... so first we compare (a1,a2) and then next step compare (a2,a3)\n // Now if (a1,a2) had an overlap -> why not make the next a2 = merged(a1,a2)? \n // That would do a carry over effect then\n int n = points.length;\n int[] candid = new int[2]; // always first interval anyways\n candid[0] = points[0][0];\n candid[1] = points[0][1];\n for(int i = 1; i < n; i++)\n {\n // System.out.printf(\"Current set = (%d,%d)\\n\", candid[0], candid[1]);\n int[] next = points[i];\n if(hasOverlap(candid,next))\n {\n int[] merged = mergeInterval(candid,next);\n candid[0] = merged[0];\n candid[1] = merged[1];\n }\n else\n {\n candid[0] = next[0];\n candid[1] = next[1]; \n minNumArrows++;\n }\n }\n \n return minNumArrows;\n }\n \n public boolean hasOverlap(int[] i1, int[] i2)\n {\n boolean hasOverlap = false;\n if(i1[0] <= i2[0] && i2[0] <= i1[1])\n hasOverlap = true;\n if(i2[0] <= i1[0] && i1[0] <= i2[1])\n hasOverlap = true;\n return hasOverlap;\n }\n \n public int[] mergeInterval(int[] i1, int[] i2)\n {\n int[] merged = new int[2];\n merged[0] = Math.max(i1[0],i2[0]);\n merged[1] = Math.min(i1[1],i2[1]);\n return merged;\n }\n}", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]\nOutput:4\nExplanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points.sort()\n \n ans=[points[0]]\n for i in points[1:]:\n if(i[0]<=ans[-1][1]):\n ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])]\n else:\n ans.append(i)\n return len(ans)\n \n", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-index ed string street . Each character in street is either 'H' representing a house or '.' representing an empty space. You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1 . A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses. Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible.", + "description_images": [], + "constraints": [ + "1 <= street.length <= 10^5", + "street[i] is either 'H' or '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:street = \"H..H\"\nOutput:2\nExplanation:We can put buckets at index 1 and index 2.\n\"H..H\" -> \"HBBH\" ('B' denotes where a bucket is placed).\nThe house at index 0 has a bucket to its right, and the house at index 3 has a bucket to its left.\nThus, for every house, there is at least one bucket collecting rainwater from it.", + "image": null + }, + { + "text": "Example 2: Input:street = \".H.H.\"\nOutput:1\nExplanation:We can put a bucket at index 2.\n\".H.H.\" -> \".HBH.\" ('B' denotes where a bucket is placed).\nThe house at index 1 has a bucket to its right, and the house at index 3 has a bucket to its left.\nThus, for every house, there is at least one bucket collecting rainwater from it.", + "image": null + }, + { + "text": "Example 3: Input:street = \".HHH.\"\nOutput:-1\nExplanation:There is no empty space to place a bucket to collect the rainwater from the house at index 2.\nThus, it is impossible to collect the rainwater from all the houses.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumBuckets(self, street: str) -> int:\n street = list(street)\n print(street)\n num = 0\n for i in range(len(street)):\n if street[i] == \"H\":\n if i > 0 and street[i-1] == \"B\":\n continue\n if i < len(street) - 1 and street[i+1] == \".\":\n street[i+1] = \"B\"\n num += 1\n continue\n if i > 0 and street[i-1] == \".\":\n street[i-1] = \"B\"\n num += 1\n continue\n return -1\n return num", + "title": "2086. Minimum Number of Buckets Required to Collect Rainwater from Houses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1 's. The grid is said to be connected if we have exactly one island , otherwise is said disconnected . In one day, we are allowed to change any single land cell (1) into a water cell (0) . Return the minimum number of days to disconnect the grid .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 30", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\nOutput:2\nExplanation:We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/land1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1]]\nOutput:2\nExplanation:Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/land2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 98.46%) | Memory: 18.30 MB (Top 33.85%)\n\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n\n disc_time = [[-1 for _ in range(cols)] for _ in range(rows)]\n low_value = [[-1 for _ in range(cols)] for _ in range(rows)]\n parents = [[(-1, -1) for _ in range(cols)] for _ in range(rows)]\n is_ap = [[False for _ in range(cols)] for _ in range(rows)]\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\n time = 0\n has_ap = False\n def dfs(i, j):\n if grid[i][j] == 0:\n return\n nonlocal time\n nonlocal has_ap\n disc_time[i][j] = time\n low_value[i][j] = time\n time += 1\n\n child = 0\n for di, dj in dirs:\n ni, nj = i + di, j + dj\n if not (0 <= ni < rows) or not (0 <= nj < cols):\n continue\n if grid[ni][nj] != 1:\n continue\n\n if disc_time[ni][nj] == -1: # not visited\n child += 1\n parents[ni][nj] = (i, j)\n dfs(ni, nj)\n low_value[i][j] = min(low_value[i][j], low_value[ni][nj])\n\n if parents[i][j] == (-1, -1) and child > 1:\n is_ap[i][j] = True\n has_ap = True\n\n if parents[i][j] != (-1, -1) and low_value[ni][nj] >= disc_time[i][j]:\n is_ap[i][j] = True\n has_ap = True\n elif (ni, nj) != parents[i][j]:\n low_value[i][j] = min(low_value[i][j], disc_time[ni][nj])\n\n sccs = 0\n num_ones = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n num_ones += 1\n if disc_time[i][j] == -1 and grid[i][j] == 1:\n dfs(i, j)\n sccs += 1\n\n\n if sccs > 1:\n return 0\n elif has_ap:\n return 1\n else:\n if num_ones == 1:\n return 1\n elif num_ones == 0:\n return 0\n return 2\n\n\n", + "title": "1568. Minimum Number of Days to Disconnect Island", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: You can only choose one of the actions per day. Given the integer n , return the minimum number of days to eat n oranges .", + "description_images": [], + "constraints": [ + "Eat one orange.", + "If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.", + "If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:4\nExplanation:You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:3\nExplanation:You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 97.62%) | Memory: 41.6 MB (Top 89.76%)\nclass Solution {\n HashMapmap;\n public int minDays(int n) {\n map = new HashMap<>();\n map.put(0,0);\n map.put(1,1);\n return dp(n);\n }\n public int dp(int n){\n if(map.get(n)!=null)\n return map.get(n);\n int one = 1+(n%2)+dp(n/2);\n int two = 1+(n%3)+dp(n/3);\n map.put(n,Math.min(one,two));\n return map.get(n);\n}\n }\n // int one = 1+(n%2)+cache(n/2);\n // int two = 1+(n%3)+cache(n/3);\n", + "title": "1553. Minimum Number of Days to Eat N Oranges", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: You can only choose one of the actions per day. Given the integer n , return the minimum number of days to eat n oranges .", + "description_images": [], + "constraints": [ + "Eat one orange.", + "If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.", + "If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:4\nExplanation:You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:3\nExplanation:You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import deque\nfrom math import log2, ceil\nclass Solution:\n def minDays(self, n: int) -> int:\n maxd = 2*ceil(log2(n))\n que = deque([(1,1)])\n seen = set()\n while que:\n v, d = que.popleft()\n seen.add(v)\n if v == n:\n return d\n for w in [v+1, 2*v, 3*v]:\n if w not in seen and d <= maxd and w <= n:\n que.append((w,d+1))\n", + "title": "1553. Minimum Number of Days to Eat N Oranges", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array bloomDay , an integer m and an integer k . You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the i th flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden . If it is impossible to make m bouquets return -1 .", + "description_images": [], + "constraints": [ + "bloomDay.length == n", + "1 <= n <= 10^5", + "1 <= bloomDay[i] <= 10^9", + "1 <= m <= 10^6", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput:3\nExplanation:Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput:-1\nExplanation:We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.", + "image": null + }, + { + "text": "Example 3: Input:bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput:12\nExplanation:We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDays(int[] bloomDay, int m, int k) {\n if(m*k > bloomDay.length) return -1;\n \n int low = Integer.MAX_VALUE, high = 0;\n for(int i:bloomDay){\n low = Math.min(low,i);\n high = Math.max(high,i);\n }\n while(low<=high){\n int mid = low + (high-low)/2;\n if(isPossible(bloomDay,mid,m,k)) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private boolean isPossible(int[] bloomDay,int maxDays,int m,int k){\n for(int i=0;i int:\n \n def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking):\n \n currentListOfAdjacentBloomedFlowers = []\n numberOfBouquetsWeCanMakeOnThisDay = 0\n \n for dayThatFlowerBlooms in listOfFlowerBloomDays:\n \n # check if the flower has bloomed on this day \n if dayThatFlowerBlooms <= dayThatWeAreChecking:\n \n # add to the list an adjacent bloomed flowers, I use 'x' because the description uses an 'x'\n currentListOfAdjacentBloomedFlowers.append('x')\n \n else:\n # we've hit a day where we don't have a bloomed flower, so the list of adjacent bloomed flowers has to be reset\n # BUT FIRST figure out how many bouquets we can make with this list of adjacent bloomed flowers\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n # RESET list of adjacent bloomed flowers cause we're on a day where the a flower has not bloomed yet\n currentListOfAdjacentBloomedFlowers = []\n \n # we've gone through the entire listOfFlowerBloomDays list and need to check if the \"residual\" current list \n # of adjacent bloomed flowers can make a bouquet ... so handle it here\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n return numberOfBouquetsWeCanMakeOnThisDay\n \n \n # if the TOTAL amount of flowers we need doesn't match the number of possible flowers we can grow,\n # then the given inputs are impossible for making enough bouquets (we don't have enough flowers)\n totalNumberOfFlowersNeeded = targetNumberOfBouquets*flowersPerBouquet\n numberOfFlowersWeCanGrow = len(listOfFlowerBloomDays)\n if numberOfFlowersWeCanGrow < totalNumberOfFlowersNeeded: \n return -1\n \n # no need to go past the day of the flower with the longest bloom date\n leftDay = 0\n rightDay = max(listOfFlowerBloomDays)\n \n while leftDay < rightDay:\n \n # currentDay is functioning as the \"mid\" of a binary search\n currentDay = leftDay + (rightDay-leftDay)//2\n \n # as in most binary searches, we check if the mid (which I'm calling 'currentDay') satisfies the constraint\n # that is, if we can make the target amount of bouquets on this day\n if numberOfBouquetsWeCanMakeOnThisDay(currentDay) < targetNumberOfBouquets:\n \n # womp womp, we can't make enough bouquets on this day, so set up for next iteration\n # the \"correct day\" is on the right side, so we get rid of all the \"incorrect days\" on the left side\n # by updating the left to the currentDay+1\n leftDay = currentDay+1\n else:\n \n # yay, we can make enough bouquets on this day, but we don't know if this is the \"minimum day\"\n # we discard the right side to keep searching\n rightDay = currentDay\n \n # leftDay >= rightDay, so we've found the \"minimum day\"\n return leftDay\n\t\t", + "title": "1482. Minimum Number of Days to Make m Bouquets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a m x n binary matrix mat . In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1 ). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0 .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 3", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0],[0,1]]\nOutput:3\nExplanation:One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.", + "image": "https://assets.leetcode.com/uploads/2019/11/28/matrix.png" + }, + { + "text": "Example 2: Input:mat = [[0]]\nOutput:0\nExplanation:Given matrix is a zero matrix. We do not need to change it.", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,0,0],[1,0,0]]\nOutput:-1\nExplanation:Given matrix cannot be a zero matrix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(int[][] mat) {\n int m = mat.length, n = mat[0].length;\n Set visited = new HashSet<>();\n Queue queue = new LinkedList<>();\n int steps = 0;\n \n int initialState = toBinary(mat);\n queue.add(initialState);\n visited.add(initialState);\n \n while (!queue.isEmpty()) {\n int size = queue.size();\n \n for (int i = 0; i < size; i++) {\n int state = queue.poll();\n if (state == 0) return steps;\n int mask = 1;\n\n for (int y = 0; y < m; y++) {\n for (int x = 0; x < n; x++) {\n int nextState = flip(state, x, y, n, m);\n if (!visited.contains(nextState)) {\n visited.add(nextState);\n queue.add(nextState);\n }\n mask = mask << 1;\n }\n }\n }\n steps++;\n }\n return -1;\n }\n \n private int toBinary(int[][] M) {\n int bin = 0;\n for (int y = 0; y < M.length; y++) {\n for (int x = 0; x < M[0].length; x++) {\n bin = (bin << 1) + M[y][x];\n }\n }\n return bin;\n }\n \n private int flip(int state, int x, int y, int n, int m) {\n int flip = 1 << ((y*n) + x);\n flip += (x > 0) ? 1 << ((y*n) + (x-1)) : 0;\n flip += (x < n-1) ? 1 << ((y*n) + (x+1)) : 0;\n flip += (y > 0) ? 1 << (((y-1)*n) + x) : 0;\n flip += (y < m-1) ? 1 << (((y+1)*n) + x) : 0;\n return state ^ flip;\n }\n}\n", + "title": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a m x n binary matrix mat . In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1 ). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0 .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 3", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0],[0,1]]\nOutput:3\nExplanation:One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.", + "image": "https://assets.leetcode.com/uploads/2019/11/28/matrix.png" + }, + { + "text": "Example 2: Input:mat = [[0]]\nOutput:0\nExplanation:Given matrix is a zero matrix. We do not need to change it.", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,0,0],[1,0,0]]\nOutput:-1\nExplanation:Given matrix cannot be a zero matrix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n flips = [11, 23, 38, 89, 186, 308, 200, 464, 416]\n \n def minFlips(self, mat: List[List[int]]) -> int:\n mask = self.make_mask(mat)\n check = self.make_mask([[1 for c in r] for r in mat])\n min_steps = -1\n last = 0\n for x in range(2**9):\n x = x & check\n flips = last ^ x\n last = x\n if not flips:\n continue\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n index = (i * 3 + j)\n if 1 << index & flips:\n mask ^= self.flips[index]\n if check & ~mask == check:\n steps = self.count_bits(x & check)\n if min_steps < 0 or steps < min_steps:\n min_steps = steps\n return min_steps\n \n def make_mask(self, mat):\n d = 0\n for i in range(3):\n for j in range(3):\n if i < len(mat) and j < len(mat[0]):\n d |= mat[i][j] << (i * 3 + j)\n return d\n\n def count_bits(self, x):\n count = 0\n i = 1\n while i <= x:\n count += int(bool(x & i))\n i <<= 1\n return count\n", + "title": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a binary string s . You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating . The string is called alternating if no two adjacent characters are equal.", + "description_images": [], + "constraints": [ + "Type-1: Remove the character at the start of the string s and append it to the end of the string.", + "Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"\nOutput:2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"\nOutput:0\nExplanation: The string is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"\nOutput:1\nExplanation: Use the second operation on the second element to make s = \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(String s) {\n /*\n * Sliding Window Approach\n */\n \n \n int n = s.length();\n \n int mininumFlip = Integer.MAX_VALUE;\n \n int misMatchCount = 0;\n for(int i = 0; i < (2 * n); i++){\n \n int r = i % n;\n \n //add mis watch count in current window\n if((s.charAt(r) - '0') != (i % 2 == 0 ? 1 : 0)) misMatchCount++;\n \n //remove mismatch count which are not relvent for current window\n if(i >= n && (s.charAt(r) - '0') != (r % 2 == 0 ? 1 : 0)) misMatchCount--;\n \n \n //misMatchCount : when valid binary string start from 1\n //n - misMatchCount : when valid binary string start from 0\n if(i >= n - 1) mininumFlip = Math.min(mininumFlip, Math.min(misMatchCount, n - misMatchCount));\n }\n \n return mininumFlip;\n }\n}\n\n", + "title": "1888. Minimum Number of Flips to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary string s . You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating . The string is called alternating if no two adjacent characters are equal.", + "description_images": [], + "constraints": [ + "Type-1: Remove the character at the start of the string s and append it to the end of the string.", + "Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"\nOutput:2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"\nOutput:0\nExplanation: The string is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"\nOutput:1\nExplanation: Use the second operation on the second element to make s = \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 631 ms (Top 87.94%) | Memory: 14.8 MB (Top 94.52%)\nclass Solution:\n def minFlips(self, s: str) -> int:\n prev = 0\n start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n odd = len(s)%2\n for val in s:\n val = int(val)\n if val == prev:\n if odd:\n start_0_odd = min(start_0_odd, start_1)\n start_1_odd += 1\n start_1 += 1\n else:\n if odd:\n start_1_odd = min(start_1_odd, start_0)\n start_0_odd += 1\n start_0 += 1\n prev = 1 - prev\n return min([start_1, start_0, start_1_odd, start_0_odd])", + "title": "1888. Minimum Number of Flips to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the string croakOfFrogs , which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c' , 'r' , 'o' , 'a' , and 'k' sequentially . The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1 .", + "description_images": [], + "constraints": [ + "1 <= croakOfFrogs.length <= 10^5", + "croakOfFrogs is either 'c' , 'r' , 'o' , 'a' , or 'k' ." + ], + "examples": [ + { + "text": "Example 1: Input:croakOfFrogs = \"croakcroak\"\nOutput:1\nExplanation:One frog yelling \"croak\"twice.", + "image": null + }, + { + "text": "Example 2: Input:croakOfFrogs = \"crcoakroak\"\nOutput:2\nExplanation:The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".", + "image": null + }, + { + "text": "Example 3: Input:croakOfFrogs = \"croakcrook\"\nOutput:-1\nExplanation:The given string is an invalid combination of \"croak\"from different frogs.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 80.36%) | Memory: 46.5 MB (Top 68.93%)\nclass Solution {\n public int minNumberOfFrogs(String croakOfFrogs) {\n int[] index = new int[26];\n String corak = \"croak\";\n\n // Giving index to each characters\n for (int i = 0; i < corak.length(); ++i)\n index[corak.charAt(i) - 'a'] = i;\n\n int ans = 0, sum = 0;\n int[] count = new int[5];\n\n for (char c : croakOfFrogs.toCharArray()) {\n int i = index[c - 'a'];\n // If it is not 'c' it will decrease the sum\n if (c != 'c') {\n if (count[i - 1]-- <= 0) return -1;\n sum--;\n }\n // If it is not 'k' it will increase the sum\n if (c != 'k') {\n count[i]++;\n sum++;\n }\n ans = Math.max(ans, sum);\n }\n return sum == 0 ? ans : -1;\n }\n}", + "title": "1419. Minimum Number of Frogs Croaking", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the string croakOfFrogs , which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c' , 'r' , 'o' , 'a' , and 'k' sequentially . The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1 .", + "description_images": [], + "constraints": [ + "1 <= croakOfFrogs.length <= 10^5", + "croakOfFrogs is either 'c' , 'r' , 'o' , 'a' , or 'k' ." + ], + "examples": [ + { + "text": "Example 1: Input:croakOfFrogs = \"croakcroak\"\nOutput:1\nExplanation:One frog yelling \"croak\"twice.", + "image": null + }, + { + "text": "Example 2: Input:croakOfFrogs = \"crcoakroak\"\nOutput:2\nExplanation:The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".", + "image": null + }, + { + "text": "Example 3: Input:croakOfFrogs = \"croakcrook\"\nOutput:-1\nExplanation:The given string is an invalid combination of \"croak\"from different frogs.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 87.7%) | Memory: 17.15 MB (Top 48.6%)\n\nclass Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n c = r = o = a = k = max_frog_croak = present_frog_croak = 0\n # need to know, at particular point,\n # what are the max frog are croaking,\n\n for i, v in enumerate(croakOfFrogs):\n if v == 'c':\n c += 1\n\t\t\t\t# c gives a signal for a frog\n present_frog_croak += 1\n elif v == 'r':\n r += 1\n elif v == 'o':\n o += 1\n elif v == 'a':\n a += 1\n else:\n k += 1\n\t\t\t\t# frog stop croaking\n present_frog_croak -= 1\n\n max_frog_croak = max(max_frog_croak, present_frog_croak)\n # if any inoder occurs;\n if c < r or r < o or o < a or a < k:\n return -1\n\n # if all good, else -1\n if present_frog_croak == 0 and c == r and r == o and o == a and a == k:\n return max_frog_croak\n return -1\n", + "title": "1419. Minimum Number of Frogs Croaking", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array target . You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= target.length <= 10^5", + "1 <= target[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,2,1]\nOutput:3\nExplanation:We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.", + "image": null + }, + { + "text": "Example 2: Input:target = [3,1,1,2]\nOutput:4\nExplanation:[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]", + "image": null + }, + { + "text": "Example 3: Input:target = [3,1,5,4,2]\nOutput:7\nExplanation:[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 98.94%) | Memory: 51.4 MB (Top 94.35%)\n// Imagine 3 cases\n// Case 1. [3,2,1], we need 3 operations.\n// Case 2. [1,2,3], we need 3 operations.\n// Case 3. [3,2,1,2,3], we need 5 operations.\n// What we need to add is actually the diff (cur - prev)\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int minNumberOperations(int[] target) {\n int res = 0;\n int prev = 0;\n for (int cur : target) {\n if (cur > prev) {\n res += cur - prev;\n }\n prev = cur;\n }\n return res;\n }\n}", + "title": "1526. Minimum Number of Increments on Subarrays to Form a Target Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array target . You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= target.length <= 10^5", + "1 <= target[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,2,1]\nOutput:3\nExplanation:We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.", + "image": null + }, + { + "text": "Example 2: Input:target = [3,1,1,2]\nOutput:4\nExplanation:[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]", + "image": null + }, + { + "text": "Example 3: Input:target = [3,1,5,4,2]\nOutput:7\nExplanation:[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minNumberOperations(self, nums: List[int]) -> int:\n res=nums[0]\n prev=nums[0]\n for i in range(1,len(nums)):\n res += max(0,nums[i]-prev)\n prev=nums[i]\n return res\n", + "title": "1526. Minimum Number of Increments on Subarrays to Form a Target Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary array nums and an integer k . A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1 , and every 1 in the subarray to 0 . Return the minimum number of k-bit flips required so that there is no 0 in the array . If it is not possible, return -1 . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0], k = 1\nOutput:2\nExplanation:Flip nums[0], then flip nums[2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,0], k = 2\nOutput:-1\nExplanation:No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0,1,0,1,1,0], k = 3\nOutput:3\nExplanation:Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 24.69%) | Memory: 90.8 MB (Top 76.54%)\nclass Solution {\n public int minKBitFlips(int[] nums, int k) {\n int target = 0, ans = 0;;\n boolean[] flip = new boolean[nums.length+1];\n for (int i = 0; i < nums.length; i++){\n if (flip[i]){\n target^=1;\n }\n if (inums.length-k&&nums[i]==target){\n return -1;\n }\n }\n return ans;\n }\n}", + "title": "995. Minimum Number of K Consecutive Bit Flips", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a binary array nums and an integer k . A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1 , and every 1 in the subarray to 0 . Return the minimum number of k-bit flips required so that there is no 0 in the array . If it is not possible, return -1 . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0], k = 1\nOutput:2\nExplanation:Flip nums[0], then flip nums[2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,0], k = 2\nOutput:-1\nExplanation:No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0,1,0,1,1,0], k = 3\nOutput:3\nExplanation:Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2365 ms (Top 19.91%) | Memory: 17.1 MB (Top 67.10%)\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n flips = [0]*len(nums)\n csum = 0\n\n for left in range(0, len(nums)-k+1):\n if (nums[left] + csum) % 2 == 0:\n flips[left] += 1\n csum += 1\n if left >= k-1:\n csum -= flips[left-k+1]\n\n for check in range(len(nums)-k+1, len(nums)):\n if (nums[check] + csum) % 2 == 0:\n return -1\n if check >= k-1:\n csum -= flips[check-k+1]\n\n return sum(flips)\n", + "title": "995. Minimum Number of K Consecutive Bit Flips", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of lowercase English letters. In one move , you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome . Note that the input will be generated such that s can always be converted to a palindrome.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists only of lowercase English letters.", + "s can be converted to a palindrome using a finite number of moves." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabb\"\nOutput:2\nExplanation:We can obtain two palindromes from s, \"abba\" and \"baab\". \n- We can obtain \"abba\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"abba\".\n- We can obtain \"baab\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"baab\".\nThus, the minimum number of moves needed to make s a palindrome is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"letelt\"\nOutput:2\nExplanation:One of the palindromes we can obtain from s in 2 moves is \"lettel\".\nOne of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\nOther palindromes such as \"tleelt\" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n\tpublic int minMovesToMakePalindrome(String s) {\n\t\tint len = s.length();\n\t\tchar[] strArr = s.toCharArray(); \n\t\tint steps = 0;\n\t\tint l = 0, r = len-1; // use two pointers l for left and r for right. \n\n\t\twhile(l < r){ \n\t\t\tif(strArr[l] == strArr[r]){ // Both characters are equal. so keep going futher.\n\t\t\t\tl++; r--;\n\t\t\t}else{ // Both characters are not equal. \n\t\t\t\tint k = r;\n\t\t\t\tk = findKthIndexMatchingwithLthIndex(strArr, l, k); // loop through k, until char at index k = char at index l \n\n\t\t\t\tif(k == l){ // we did not find any char at k = char at index l \n\t\t\t\t\tswap(strArr, l);\n\t\t\t\t\tsteps++; \n\t\t\t\t}else{ \n\t\t\t\t\twhile(k < r){ \n\t\t\t\t\t\tswap(strArr, k);\n\t\t\t\t\t\tsteps++;\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\t\t\t\t\tl++; r--;\n\t\t\t\t} \n\t\t\t}// end of else\n\n\t\t} // end of while\n\t\tSystem.out.println(\"palindrome: \"+String.valueOf(strArr));\n\t\treturn steps;\n\n\t}\n\n\tpublic int findKthIndexMatchingwithLthIndex(char[] strArr, int l, int k){\n\t\twhile(k > l){\n\t\t\tif(strArr[k] == strArr[l]){ return k; } \n\t\t\tk--;\n\t\t}\n\t\treturn k;\n\t}\n\n\tpublic void swap(char[] strArr, int l){\n\t\tif(l+1 < strArr.length){\n\t\t\tchar tempCh = strArr[l];\n\t\t\tstrArr[l] = strArr[l+1];\n\t\t\tstrArr[l+1] = tempCh;\n\t\t}\n\t}\n}\n", + "title": "2193. Minimum Number of Moves to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s consisting only of lowercase English letters. In one move , you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome . Note that the input will be generated such that s can always be converted to a palindrome.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists only of lowercase English letters.", + "s can be converted to a palindrome using a finite number of moves." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabb\"\nOutput:2\nExplanation:We can obtain two palindromes from s, \"abba\" and \"baab\". \n- We can obtain \"abba\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"abba\".\n- We can obtain \"baab\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"baab\".\nThus, the minimum number of moves needed to make s a palindrome is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"letelt\"\nOutput:2\nExplanation:One of the palindromes we can obtain from s in 2 moves is \"lettel\".\nOne of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\nOther palindromes such as \"tleelt\" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minMovesToMakePalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count, length_of_s = 0, len(s)\n if length_of_s <= 2:\n return count\n for i in reversed(range(length_of_s)):\n if s[i] != s[0]:\n continue\n if i == 0:\n\t\t\t\t# move to middle is a speical case which takes len(s)/2 moves then do recursive for remaining part\n count += len(s)/2 + self.minMovesToMakePalindrome(s[1:]) \n else:\n\t\t\t # this move takes len(s)-1 - i (move from i to last index len(s)-1)and then do recursive for remaining part\n count += len(s)-1-i + self.minMovesToMakePalindrome(s[1:i]+s[i+1:])\n break\n return count\n", + "title": "2193. Minimum Number of Moves to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n seats and n students in a room. You are given an array seats of length n , where seats[i] is the position of the i th seat. You are also given the array students of length n , where students[j] is the position of the j th student. You may perform the following move any number of times: Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning.", + "description_images": [], + "constraints": [ + "Increase or decrease the position of the i th student by 1 (i.e., moving the i th student from position x to x + 1 or x - 1 )" + ], + "examples": [ + { + "text": "Example 1: Input:seats = [3,1,5], students = [2,7,4]\nOutput:4\nExplanation:The students are moved as follows:\n- The first student is moved from from position 2 to position 1 using 1 move.\n- The second student is moved from from position 7 to position 5 using 2 moves.\n- The third student is moved from from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.", + "image": null + }, + { + "text": "Example 2: Input:seats = [4,1,5,9], students = [1,3,2,6]\nOutput:7\nExplanation:The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from from position 3 to position 4 using 1 move.\n- The third student is moved from from position 2 to position 5 using 3 moves.\n- The fourth student is moved from from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.", + "image": null + }, + { + "text": "Example 3: Input:seats = [2,2,6,6], students = [1,3,2,6]\nOutput:4\nExplanation:Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from from position 1 to position 2 using 1 move.\n- The second student is moved from from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 99.78%) | Memory: 41.7 MB (Top 99.11%)\nclass Solution {\n public int minMovesToSeat(int[] seats, int[] students) {\n Arrays.sort(seats);\n Arrays.sort(students);\n int diff = 0;\n for(int i=0; i int:\n seats.sort()\n students.sort()\n return sum(abs(seat - student) for seat, student in zip(seats, students))\n", + "title": "2037. Minimum Number of Moves to Seat Everyone", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings current and correct representing two 24-hour times . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . In one operation you can increase the time current by 1 , 5 , 15 , or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct .", + "description_images": [], + "constraints": [ + "current and correct are in the format \"HH:MM\"", + "current <= correct" + ], + "examples": [ + { + "text": "Example 1: Input:current = \"02:30\", correct = \"04:35\"\nOutput:3\nExplanation:We can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:current = \"11:00\", correct = \"11:01\"\nOutput:1\nExplanation:We only have to add one minute to current, so the minimum number of operations needed is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.73%) | Memory: 42.8 MB (Top 23.55%)\nclass Solution {\n public int HHMMToMinutes(String s){\n return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;\n }\n public int convertTime(String current, String correct) {\n int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);\n int[] order = {60,15,5,1};\n int i = 0;\n int ops = 0;\n while(i < 4){\n ops+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n return ops;\n }\n}", + "title": "2224. Minimum Number of Operations to Convert Time", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two strings current and correct representing two 24-hour times . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . In one operation you can increase the time current by 1 , 5 , 15 , or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct .", + "description_images": [], + "constraints": [ + "current and correct are in the format \"HH:MM\"", + "current <= correct" + ], + "examples": [ + { + "text": "Example 1: Input:current = \"02:30\", correct = \"04:35\"\nOutput:3\nExplanation:We can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:current = \"11:00\", correct = \"11:01\"\nOutput:1\nExplanation:We only have to add one minute to current, so the minimum number of operations needed is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 83.44%) | Memory: 17.40 MB (Top 22.74%)\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def get_time(t):\n hh, mm = t.split(':')\n return int(hh) * 60 + int(mm)\n \n current, correct = get_time(current), get_time(correct)\n operations = 0\n diff = correct - current\n \n for mins in [60, 15, 5, 1]:\n quotient, remainder = divmod(diff, mins)\n operations += quotient\n diff = remainder\n \n return operations\n", + "title": "2224. Minimum Number of Operations to Convert Time", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous , but nums = [1, 2, 3, 5, 6] is not continuous . Return the minimum number of operations to make nums continuous .", + "description_images": [], + "constraints": [ + "All elements in nums are unique .", + "The difference between the maximum element and the minimum element in nums equals nums.length - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]\nOutput:0\nExplanation:nums is already continuous.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5,6]\nOutput:1\nExplanation:One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,10,100,1000]\nOutput:3\nExplanation:One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n TreeSet set = new TreeSet<>();\n int threshold = nums.length-1;\n int max = 0;\n Arrays.sort(nums);\n for(int num:nums) {\n while(!set.isEmpty() && num-set.first()>threshold) {\n set.remove(set.first());\n } \n set.add(num);\n max = Math.max(max, set.size()); \n }\n return nums.length-max;\n }\n}\n", + "title": "2009. Minimum Number of Operations to Make Array Continuous", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous , but nums = [1, 2, 3, 5, 6] is not continuous . Return the minimum number of operations to make nums continuous .", + "description_images": [], + "constraints": [ + "All elements in nums are unique .", + "The difference between the maximum element and the minimum element in nums equals nums.length - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]\nOutput:0\nExplanation:nums is already continuous.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5,6]\nOutput:1\nExplanation:One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,10,100,1000]\nOutput:3\nExplanation:One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n end = 0\n ans = -1\n for i in range(len(nums)):\n while end < len(nums):\n if nums[i] + n > nums[end]:\n end+=1\n else:\n break\n ans = max(ans,end - i)\n return n - ans\n", + "title": "2009. Minimum Number of Operations to Make Array Continuous", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s ( 0-indexed )​​​​​​. You are asked to perform the following operation on s ​​​​​​ until you get a sorted string: Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cba\"\nOutput:5\nExplanation:The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabaa\"\nOutput:2\nExplanation:The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.*;\n\nclass Solution {\n public int makeStringSorted(String s) {\n BigInteger res = new BigInteger(\"0\");\n BigInteger mod = new BigInteger(\"1000000007\");\n \n int[] count = new int[26];\n BigInteger[] fact = factory(s.length(), mod);\n \n int n = s.length();\n BigInteger div = new BigInteger(\"1\");\n \n for (int i = n - 1; i >= 0; --i) {\n char c = s.charAt(i);\n count[c-'a'] ++;\n BigInteger c1 = countInverse(count, c); \n BigInteger ans = c1.multiply(fact[n-i-1]);\n div = div.multiply(new BigInteger(String.valueOf(count[c-'a'])));\n ans = ans.multiply(div.modPow(mod.subtract(new BigInteger(String.valueOf(2))), mod)).mod(mod);\n res = res.add(ans).mod(mod);\n }\n \n return res.intValue();\n }\n \n public BigInteger countInverse(int[] count, char c) {\n long cnt = 0;\n for (int i = 0; i < (c - 'a'); ++i) {\n cnt += count[i];\n }\n \n return new BigInteger(String.valueOf(cnt));\n }\n \n public BigInteger[] factory(int n, BigInteger mod) {\n BigInteger[] fact = new BigInteger[n+1];\n fact[0] = new BigInteger(\"1\");\n for (int i = 1; i <= n; ++i) {\n fact[i] = fact[i-1].multiply(new BigInteger(String.valueOf(i))).mod(mod);\n }\n \n return fact;\n }\n}\n", + "title": "1830. Minimum Number of Operations to Make String Sorted", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s ( 0-indexed )​​​​​​. You are asked to perform the following operation on s ​​​​​​ until you get a sorted string: Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cba\"\nOutput:5\nExplanation:The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabaa\"\nOutput:2\nExplanation:The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".", + "image": null + } + ], + "follow_up": null, + "solution": "from math import gcd\n\nclass Solution:\n def makeStringSorted(self, s: str) -> int:\n s = [ord(c) - ord('a') for c in s]\n ans, MOD = 0, 10 ** 9 + 7\n cnt, t, d, step = [0] * 26, 1, 1, 1\n cnt[s[-1]] = 1\n for c in reversed(s[:-1]):\n d *= (cnt[c] + 1)\n t *= step\n g = gcd(d, t)\n d //= g\n t //= g\n ans = (ans + t * sum(cnt[i] for i in range(c)) // d) % MOD\n cnt[c] += 1\n step += 1\n return ans", + "title": "1830. Minimum Number of Operations to Make String Sorted", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == boxes.length", + "1 <= n <= 2000", + "boxes[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = \"110\"\nOutput:[1,1,3]\nExplanation:The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) 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.", + "image": null + }, + { + "text": "Example 2: Input:boxes = \"001011\"\nOutput:[11,8,5,4,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 135 ms (Top 50.7%) | Memory: 44.02 MB (Top 24.4%)\n\nclass Solution{\n public int[] minOperations(String boxes){\n int n = boxes.length();\n int[] ans = new int[n];\n for(int i=0; i List[int]:\n ans = [0]*len(boxes)\n leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n for i in range(1, n):\n if boxes[i-1] == '1': leftCount += 1\n leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n ans[i] = leftCost\n for i in range(n-2, -1, -1):\n if boxes[i+1] == '1': rightCount += 1\n rightCost += rightCount\n ans[i] += rightCost\n return ans", + "title": "1769. Minimum Number of Operations to Move All Balls to Each Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an even integer n ​​​​​​. You initially have a permutation perm of size n ​​ where perm[i] == i ​ (0-indexed) ​​​​. In one operation, you will create a new array arr , and for each i : You will then assign arr ​​​​ to perm . Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.", + "description_images": [], + "constraints": [ + "If i % 2 == 0 , then arr[i] = perm[i / 2] .", + "If i % 2 == 1 , then arr[i] = perm[n / 2 + (i - 1) / 2] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:perm = [0,1] initially.\nAfter the 1stoperation, perm = [0,1]\nSo it takes only 1 operation.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:2\nExplanation:perm = [0,1,2,3] initially.\nAfter the 1stoperation, perm = [0,2,1,3]\nAfter the 2ndoperation, perm = [0,1,2,3]\nSo it takes only 2 operations.", + "image": null + }, + { + "text": "Example 3: Input:n = 6\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reinitializePermutation(int n) {\n int ans = 1;\n int num = 2;\n if(n == 2) return 1;\n while(true){\n if(num % (n-1) == 1)break; \n else {\n ans++;\n num = (num * 2) % (n-1);\n }\n }\n return ans;\n \n }\n}\n", + "title": "1806. Minimum Number of Operations to Reinitialize a Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an even integer n ​​​​​​. You initially have a permutation perm of size n ​​ where perm[i] == i ​ (0-indexed) ​​​​. In one operation, you will create a new array arr , and for each i : You will then assign arr ​​​​ to perm . Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.", + "description_images": [], + "constraints": [ + "If i % 2 == 0 , then arr[i] = perm[i / 2] .", + "If i % 2 == 1 , then arr[i] = perm[n / 2 + (i - 1) / 2] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:1\nExplanation:perm = [0,1] initially.\nAfter the 1stoperation, perm = [0,1]\nSo it takes only 1 operation.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:2\nExplanation:perm = [0,1,2,3] initially.\nAfter the 1stoperation, perm = [0,2,1,3]\nAfter the 2ndoperation, perm = [0,1,2,3]\nSo it takes only 2 operations.", + "image": null + }, + { + "text": "Example 3: Input:n = 6\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 341 ms (Top 53.7%) | Memory: 16.20 MB (Top 72.22%)\n\nclass Solution:\n def reinitializePermutation(self, n: int) -> int:\n ans = 0\n perm = list(range(n))\n while True: \n ans += 1\n perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]\n if all(perm[i] == i for i in range(n)): return ans\n", + "title": "1806. Minimum Number of Operations to Reinitialize a Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer n , an array languages , and an array friendships where: You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.", + "description_images": [], + "constraints": [ + "There are n languages numbered 1 through n ,", + "languages[i] is the set of languages the i ​​​​​​th ​​​​ user knows, and", + "friendships[i] = [u ​​​​​​i ​​​, v ​​​​​​i ] denotes a friendship between the users u ​​​​​ ​​​​​​i ​​​​​ and v i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\nOutput:1\nExplanation:You can either teach user 1 the second language or user 2 the first language.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\nOutput:2\nExplanation:Teach the third language to users 1 and 3, yielding two users to teach.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2444 ms (Top 20.45%) | Memory: 28.6 MB (Top 5.68%)\nclass Solution:\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n \"\"\"\n 1. Find out users who need to be taught\n 2. If no user needs to be taught, return 0\n 3. For all users who need to be taught a language, find the most popular language among them\n 4. Teach that language to rest of the users who need to be taught.\n \"\"\"\n need_to_be_taught = set()\n languages = [set(language) for language in languages]\n\n # 1. Find out users who needs to be taught\n for user1, user2 in friendships:\n # Adjust the 1 based indexing to 0 based indexing\n user1 = user1 - 1\n user2 = user2 - 1\n if not (languages[user1] & languages[user2]):\n need_to_be_taught.update([user1, user2])\n\n # 2. If no user needs to be taught, return 0\n if not need_to_be_taught:\n return 0\n\n # 3. For all users who needs to be taught a language, find the most popular language among them\n language_spoken_by = collections.defaultdict(int)\n for user in need_to_be_taught:\n # for each user increment the count of languages he can speak\n for language in languages[user]:\n language_spoken_by[language] += 1\n\n # find occurrence of language spoken by maximum users who can't communicate with each other\n popular_language_count = max(language_spoken_by.values())\n\n # 4. Teach that language to rest of the users who need to be taught.\n return len(need_to_be_taught)- popular_language_count\n", + "title": "1733. Minimum Number of People to Teach", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [position i , fuel i ] indicates that the i th gas station is position i miles east of the starting position and has fuel i liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination . If it cannot reach the destination, return -1 . Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.", + "description_images": [], + "constraints": [ + "1 <= target, startFuel <= 10^9", + "0 <= stations.length <= 500", + "0 <= position i <= position i+1 < target", + "1 <= fuel i < 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:target = 1, startFuel = 1, stations = []\nOutput:0\nExplanation:We can reach the target without refueling.", + "image": null + }, + { + "text": "Example 2: Input:target = 100, startFuel = 1, stations = [[10,100]]\nOutput:-1\nExplanation:We can not reach the target (or even the first gas station).", + "image": null + }, + { + "text": "Example 3: Input:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput:2\nExplanation:We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 28.3%) | Memory: 45.04 MB (Top 8.2%)\n\nclass Solution {\n public int minRefuelStops(int target, int startFuel, int[][] stations) {\n if(startFuel >= target) return 0;\n int[][] dp = new int[stations.length + 1][stations.length + 1];\n for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel;\n for (int j = 1; j < dp.length; j++) {\n for (int i = j; i < dp.length; i++) {\n dp[i][j] = Math.max(dp[i-1][j], stations[i-1][0] > dp[i-1][j-1] ?\n Integer.MIN_VALUE : dp[i-1][j-1] + stations[i-1][1]);\n if(dp[i][j] >= target) return j;\n }\n }\n return -1;\n }\n}", + "title": "871. Minimum Number of Refueling Stops", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [position i , fuel i ] indicates that the i th gas station is position i miles east of the starting position and has fuel i liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination . If it cannot reach the destination, return -1 . Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.", + "description_images": [], + "constraints": [ + "1 <= target, startFuel <= 10^9", + "0 <= stations.length <= 500", + "0 <= position i <= position i+1 < target", + "1 <= fuel i < 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:target = 1, startFuel = 1, stations = []\nOutput:0\nExplanation:We can reach the target without refueling.", + "image": null + }, + { + "text": "Example 2: Input:target = 100, startFuel = 1, stations = [[10,100]]\nOutput:-1\nExplanation:We can not reach the target (or even the first gas station).", + "image": null + }, + { + "text": "Example 3: Input:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput:2\nExplanation:We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minRefuelStops(self, t, F, S):\n S.append([t, 0])\n heap, ans = [], 0\n for p,f in S:\n while heap and p > F:\n F -= heapq.heappop(heap)\n ans += 1\n if p > F: return -1\n heapq.heappush(heap, -f)\n return ans\n", + "title": "871. Minimum Number of Refueling Stops", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array nums ​​​, return the minimum number of elements to remove to make nums ​​​ a mountain array .", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1]\nOutput:0\nExplanation:The array itself is a mountain array so we do not need to remove any elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,1,5,6,2,3,1]\nOutput:3\nExplanation:One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 103 ms (Top 13.29%) | Memory: 45.9 MB (Top 81.01%)\nclass Solution {\n public int minimumMountainRemovals(int[] nums) {\n\n int n = nums.length;\n int[] LIS = new int[n];\n int[] LDS = new int[n];\n\n Arrays.fill(LIS, 1);\n Arrays.fill(LDS, 1);\n // calculate the longest increase subsequence (LIS) for every index i\n for(int i=1 ; i < n ; i++)\n {\n for(int j = 0 ; j < i ; j++)\n {\n if(nums[i] > nums[j] && LIS[j]+1 > LIS[i])\n LIS[i] = LIS[j]+1;\n }\n }\n\n // calculate the longest decreasing subsequence(LDS) for every index i and keep track of the maximum of LIS+LDS\n int max = 0;\n for(int i=n-2 ; i >= 0 ; i--)\n {\n for(int j = n-1 ; j > i ; j--)\n {\n if(nums[i] > nums[j] && LDS[j]+1 > LDS[i])\n LDS[i] = LDS[j]+1;\n }\n\n if(LIS[i] > 1 && LDS[i] > 1)\n max = Math.max(LIS[i]+LDS[i]-1, max);\n }\n return n - max;\n }\n}", + "title": "1671. Minimum Number of Removals to Make Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array nums ​​​, return the minimum number of elements to remove to make nums ​​​ a mountain array .", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1]\nOutput:0\nExplanation:The array itself is a mountain array so we do not need to remove any elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,1,5,6,2,3,1]\nOutput:3\nExplanation:One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n n = len(nums)\n inc = [0] * n\n dec = [0] * n\n \n# Longest Increasing Subsequence\n for i in range(1,n):\n for j in range(0,i):\n if nums[i] > nums[j]:\n inc[i] = max(inc[i], inc[j] + 1)\n \n# Longest Decreasing Subsequence\n for i in range(n-2,-1,-1):\n for j in range(n-1,i,-1):\n if nums[i] > nums[j]:\n dec[i] = max(dec[i], dec[j] + 1)\n \n# Final calculation\n res = 0\n for i in range(0,n):\n if inc[i] > 0 and dec[i] > 0:\n res = max(res, inc[i] + dec[i])\n \n# Final conclusion \n return n - res - 1\n", + "title": "1671. Minimum Number of Removals to Make Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings of the same length s and t . In one step you can choose any character of t and replace it with another character . Return the minimum number of steps to make t an anagram of s . An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s.length == t.length", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bab\", t = \"aba\"\nOutput:1\nExplanation:Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", t = \"practice\"\nOutput:5\nExplanation:Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"anagram\", t = \"mangaar\"\nOutput:0\nExplanation:\"anagram\" and \"mangaar\" are anagrams.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 64.38%) | Memory: 54.3 MB (Top 67.83%)\n//find the frequency of every letter and check diffrence between the frequency of each letter then divide it by 2 to calculate the minimum number of letter to be changed.\nclass Solution {\n public int minSteps(String s, String t) {\n int sf[]=new int[26];\n int tf[]=new int[26];\n int diff=0;\n for(char c:s.toCharArray()){\n sf[c-'a']++;\n }\n for(char c:t.toCharArray()){\n tf[c-'a']++;\n }\n for(int i=0;i<26;i++){\n diff+=(int)Math.abs(sf[i]-tf[i]);\n }\n return diff/2;\n }\n}", + "title": "1347. Minimum Number of Steps to Make Two Strings Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings of the same length s and t . In one step you can choose any character of t and replace it with another character . Return the minimum number of steps to make t an anagram of s . An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s.length == t.length", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bab\", t = \"aba\"\nOutput:1\nExplanation:Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", t = \"practice\"\nOutput:5\nExplanation:Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"anagram\", t = \"mangaar\"\nOutput:0\nExplanation:\"anagram\" and \"mangaar\" are anagrams.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n for ch in s:\n\t\t # Find and replace only one occurence of this character in t\n t = t.replace(ch, '', 1)\n \n return len(t)", + "title": "1347. Minimum Number of Steps to Make Two Strings Anagram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings s and t . In one step, you can append any character to either s or t . Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 2 * 10^5", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", t = \"coats\"\nOutput:7\nExplanation:- In 2 steps, we can append the letters in \"as\" onto s = \"leetcode\", forming s = \"leetcodeas\".\n- In 5 steps, we can append the letters in \"leede\" onto t = \"coats\", forming t = \"coatsleede\".\n\"leetcodeas\" and \"coatsleede\" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"night\", t = \"thing\"\nOutput:0\nExplanation:The given strings are already anagrams of each other. Thus, we do not need any further steps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 246 ms (Top 18.10%) | Memory: 118.1 MB (Top 5.07%)\nclass Solution {\n public int minSteps(String s, String t) {\n HashMap hmap = new HashMap<>();\n for(char ch:s.toCharArray())\n hmap.put(ch,hmap.getOrDefault(ch,0)+1);\n for(char ch:t.toCharArray())\n hmap.put(ch,hmap.getOrDefault(ch,0)-1);\n int count=0;\n for(char key:hmap.keySet())\n if(hmap.get(key)!=0)\n count+=(Math.abs(hmap.get(key)));\n return count;\n }\n}", + "title": "2186. Minimum Number of Steps to Make Two Strings Anagram II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and t . In one step, you can append any character to either s or t . Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 2 * 10^5", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", t = \"coats\"\nOutput:7\nExplanation:- In 2 steps, we can append the letters in \"as\" onto s = \"leetcode\", forming s = \"leetcodeas\".\n- In 5 steps, we can append the letters in \"leede\" onto t = \"coats\", forming t = \"coatsleede\".\n\"leetcodeas\" and \"coatsleede\" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"night\", t = \"thing\"\nOutput:0\nExplanation:The given strings are already anagrams of each other. Thus, we do not need any further steps.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n sMap = dict()\n tMap = dict()\n \n for character in s:\n sMap[character] = sMap.get(character, 0) + 1\n \n for character in t:\n tMap[character] = tMap.get(character, 0) + 1\n \n count = 0\n \n for key, value in sMap.items():\n if value >= tMap.get(key, 0):\n count += (value - tMap.get(key, 0))\n \n for key, value in tMap.items():\n if value >= sMap.get(key, 0):\n count += (value - sMap.get(key, 0))\n \n return count\n", + "title": "2186. Minimum Number of Steps to Make Two Strings Anagram II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s , return the minimum number of character swaps to make it alternating , or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not. Any two characters may be swapped, even if they are not adjacent .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"\nOutput:1\nExplanation:Swap positions 1 and 4: \"111000\" -> \"101010\"\nThe string is now alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"\nOutput:0\nExplanation:The string is already alternating, no swaps are needed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwaps(String s) {\n int cntZero=0 , cntOne=0;\n for(char ch:s.toCharArray()){\n if(ch=='0') cntZero++;\n else cntOne++;\n }\n \n //Invalid\n if(Math.abs(cntOne-cntZero)>1) return -1;\n \n \n if(cntOne>cntZero){ //one must be at even posotion\n return countSwaps(s,'1'); \n }else if(cntOne \"101010\"\nThe string is now alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"\nOutput:0\nExplanation:The string is already alternating, no swaps are needed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef minSwaps(self, st: str) -> int:\n \n def swap(st,c):\n n = len(st)\n mis = 0\n for i in range(n):\n if i%2==0 and st[i]!=c:\n mis+=1\n if i%2==1 and st[i]==c:\n mis+=1\n return mis//2\n \n dic = Counter(st)\n z = dic['0']\n o = dic['1']\n res=0\n if abs(z-o)>1:\n return -1\n elif z>o:\n res = swap(st,'0')\n elif o>z:\n res = swap(st,'1')\n else:\n res = min(swap(st,'0'),swap(st,'1'))\n \n return res\n", + "title": "1864. Minimum Number of Swaps to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed string s of even length n . The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']' . A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced .", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB , where both A and B are balanced strings, or", + "It can be written as [C] , where C is a balanced string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"][][\"\nOutput:1\nExplanation:You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"]]][[[\"\nOutput:2\nExplanation:You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"[]\"\nOutput:0\nExplanation:The string is already balanced.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 414 ms (Top 6.65%) | Memory: 100.2 MB (Top 5.02%)\nclass Solution {\n public int minSwaps(String s) {\n // remove the balanced part from the given string\n Stack stack = new Stack<>();\n for(char ch : s.toCharArray()) {\n if(ch == '[')\n stack.push(ch);\n else {\n if(!stack.isEmpty() && stack.peek() == '[')\n stack.pop();\n else\n stack.push(ch);\n }\n }\n int unb = stack.size()/2; // # of open or close bracket\n return (unb+1)/2;\n }\n}", + "title": "1963. Minimum Number of Swaps to Make the String Balanced", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed string s of even length n . The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']' . A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced .", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB , where both A and B are balanced strings, or", + "It can be written as [C] , where C is a balanced string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"][][\"\nOutput:1\nExplanation:You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"]]][[[\"\nOutput:2\nExplanation:You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"[]\"\nOutput:0\nExplanation:The string is already balanced.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSwaps(self, s: str) -> int:\n res, bal = 0, 0\n for ch in s:\n bal += 1 if ch == '[' else -1\n if bal == -1:\n res += 1\n bal = 1\n return res\n", + "title": "1963. Minimum Number of Swaps to Make the String Balanced", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n . (i.e The length of the garden is n ). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "ranges.length == n + 1", + "0 <= ranges[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, ranges = [3,4,1,1,0,0]\nOutput:1\nExplanation:The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]", + "image": "https://assets.leetcode.com/uploads/2020/01/16/1685_example_1.png" + }, + { + "text": "Example 2: Input:n = 3, ranges = [0,0,0,0]\nOutput:-1\nExplanation:Even if you activate all the four taps you cannot water the whole garden.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 14.75%) | Memory: 49.6 MB (Top 26.03%)\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new);\n Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o]));\n int ans = 1, cur = 0, end = 0;\n for (int i = 0;icur){\n cur=end;\n ans++;\n }\n if (j-ranges[j]<=cur){\n end=Math.max(end, j+ranges[j]);\n }\n }\n return end int:\n max_range = [0] * (n + 1)\n \n for i, r in enumerate(ranges):\n left, right = max(0, i - r), min(n, i + r)\n max_range[left] = max(max_range[left], right - left)\n \n\t\t# it's a jump game now\n start = end = step = 0\n \n while end < n:\n step += 1\n start, end = end, max(i + max_range[i] for i in range(start, end + 1))\n if start == end:\n return -1\n \n return step\n", + "title": "1326. Minimum Number of Taps to Open to Water a Garden", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a directed acyclic graph , with n vertices numbered from 0 to n-1 , and an array edges where edges[i] = [from i , to i ] represents a directed edge from node from i to node to i . Find the smallest set of vertices from which all nodes in the graph are reachable . It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/07/untitled22.png", + "https://assets.leetcode.com/uploads/2020/07/07/untitled.png" + ], + "constraints": [ + "2 <= n <= 10^5", + "1 <= edges.length <= min(10^5, n * (n - 1) / 2)", + "edges[i].length == 2", + "0 <= from i, to i < n", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\nOutput:[0,3]\nExplanation:It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\nOutput:[0,2,3]\nExplanation:Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 43.75%) | Memory: 119 MB (Top 77.96%)\nclass Solution {\n public List findSmallestSetOfVertices(int n, List> edges) {\n\n int[] indegree = new int[n];\n\n for(List edge : edges) {\n indegree[edge.get(1)]++;\n }\n\n List result = new ArrayList<>();\n\n for(int i=0; i List[int]:\n\n\t\tparent=[[] for i in range(n)]\n\t\tfor i in edges:\n\t\t\tparent[i[1]].append(i[0])\n\t\tans=[]\n\t\tfor i in range(n):\n\t\t\tif len(parent[i])==0:\n\t\t\t\tans.append(i)\n\t\treturn ans\n", + "title": "1557. Minimum Number of Vertices to Reach All Nodes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n , where the i th task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime , return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i] .", + "description_images": [], + "constraints": [ + "If you start a task in a work session, you must complete it in the same work session.", + "You can start a new task immediately after finishing the previous one.", + "You may complete the tasks in any order ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,3], sessionTime = 3\nOutput:2\nExplanation:You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [3,1,3,1,1], sessionTime = 8\nOutput:2\nExplanation:You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [1,2,3,4,5], sessionTime = 15\nOutput:1\nExplanation:You can finish all the tasks in one work session.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 116 ms (Top 47.58%) | Memory: 73.6 MB (Top 13.54%)\n// Java Solution\nclass Solution {\n public int minSessions(int[] tasks, int sessionTime) {\n int n = tasks.length, MAX = Integer.MAX_VALUE;\n int[][] dp = new int[1< d2[0]) return d2;\n if(d1[0] < d2[0]) return d1;\n if(d1[1] > d2[1]) return d2;\n\n return d1;\n }\n}", + "title": "1986. Minimum Number of Work Sessions to Finish the Tasks", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n , where the i th task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime , return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i] .", + "description_images": [], + "constraints": [ + "If you start a task in a work session, you must complete it in the same work session.", + "You can start a new task immediately after finishing the previous one.", + "You may complete the tasks in any order ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,3], sessionTime = 3\nOutput:2\nExplanation:You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [3,1,3,1,1], sessionTime = 8\nOutput:2\nExplanation:You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [1,2,3,4,5], sessionTime = 15\nOutput:1\nExplanation:You can finish all the tasks in one work session.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 966 ms (Top 45.98%) | Memory: 41.80 MB (Top 22.32%)\n\nclass Solution:\n def minSessions(self, tasks, T):\n n = len(tasks)\n\n @lru_cache(None)\n def dp(mask):\n if mask == 0: return (1, 0)\n ans = (float(\"inf\"), float(\"inf\"))\n for j in range(n):\n if mask & (1< T)\n ans = min(ans, (pieces + full, tasks[j] + (1-full)*last)) \n return ans\n\n return dp((1< [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] ->[1, 5](2 operations).\nTotal of operations: 1 + 2 + 2 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2]\nOutput:3\nExplanation:Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] ->[2, 2](1 operation).\nTotal of operations: 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,5]\nOutput:6\nExplanation:(initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] ->[4,2,5](nums).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n int odd = 0, even = 0;\n Map map = new HashMap<>();\n for (int n : nums){\n int res = dfs(n, map);\n odd += res >> 5;\n even = Math.max(res & 0b11111, even);\n }\n\n return odd + even;\n }\n\n private int dfs(int n, Map map){\n if (n == 0) return 0;\n if (map.containsKey(n)) return map.get(n);\n\n int res = n % 2 << 5;\n res += dfs(n / 2, map) + (n > 1? 1 : 0);\n\n map.put(n, res);\n return res;\n }\n}\n", + "title": "1558. Minimum Numbers of Function Calls to Make Target Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to covert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr . The test cases are generated so that the answer fits in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5]\nOutput:5\nExplanation:Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] ->[1, 5](2 operations).\nTotal of operations: 1 + 2 + 2 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2]\nOutput:3\nExplanation:Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] ->[2, 2](1 operation).\nTotal of operations: 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,5]\nOutput:6\nExplanation:(initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] ->[4,2,5](nums).", + "image": null + } + ], + "follow_up": null, + "solution": "# Observe that:\n# +1 places a 1 to the end of the int's binary representation\n# (assuming a 0 there previously)\n# x2 is a bitshift left\n# So you basically just need to count all the ones in the binary representations\n# and find how many shifts are required (largest bit length minus one).\n\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n if max(nums) == 0:\n return 0\n \n return sum([x.bit_count() for x in nums]) + max([x.bit_length() for x in nums]) - 1\n\n", + "title": "1558. Minimum Numbers of Function Calls to Make Target Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n . Each cell has one of two values: You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) .", + "description_images": [], + "constraints": [ + "0 represents an empty cell,", + "1 represents an obstacle that may be removed." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1],[1,1,0],[1,1,0]]\nOutput:2\nExplanation:We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio-1.png" + }, + { + "text": "Example 2: Input:grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\nOutput:0\nExplanation:We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int [][]grid;\n int n,m;\n boolean [][]seen;\n int []dx = new int[]{0,0,1,-1};\n int []dy = new int[]{1,-1,0,0};\n int [][]dp;\n int finalres;\n private boolean isValid(int i, int j) {\n return Math.min(i,j)>=0 && i=finalres) return finalres;\n if(i == n-1 && j == m-1) {\n return cnt;\n }\n if(dp[i][j]!=Integer.MAX_VALUE) return dp[i][j];\n int res = n*m+1;\n seen[i][j]=true;\n for(int k=0;k<4;k++) {\n int newI = i+dx[k], newJ = j+dy[k];\n if(isValid(newI, newJ)) {\n res = Math.min(res, solve(newI, newJ, cnt+grid[i][j]));\n }\n }\n seen[i][j]=false;\n return dp[i][j]=Math.min(dp[i][j], res);\n }\n \n public int minimumObstacles(int[][] grid) {\n this.grid = grid;\n this.n = grid.length;\n this.m = grid[0].length;\n this.seen = new boolean[n][m];\n dp = new int[n][m];\n finalres = n*m+1;\n for(int []row:dp) Arrays.fill(row, Integer.MAX_VALUE);\n return solve(0,0,0);\n }\n}\n", + "title": "2290. Minimum Obstacle Removal to Reach Corner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n . Each cell has one of two values: You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) .", + "description_images": [], + "constraints": [ + "0 represents an empty cell,", + "1 represents an obstacle that may be removed." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1],[1,1,0],[1,1,0]]\nOutput:2\nExplanation:We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio-1.png" + }, + { + "text": "Example 2: Input:grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\nOutput:0\nExplanation:We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 4890 ms (Top 15.42%) | Memory: 42.20 MB (Top 64.95%)\n\nclass Solution:\n def minimumObstacles(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n q = [(0, 0, 0)]\n dist = [[float('inf') for _ in range(n)] for _ in range(m)]\n\n while q:\n size = len(q)\n for _ in range(size):\n obs, x, y = heapq.heappop(q)\n if dist[x][y] < float('inf'): continue\n obs += grid[x][y]\n dist[x][y] = obs\n if x + 1 < m: heapq.heappush(q, (obs, x + 1, y))\n if x > 0: heapq.heappush(q, (obs, x - 1, y))\n if y + 1 < n: heapq.heappush(q, (obs, x, y + 1))\n if y > 0: heapq.heappush(q, (obs, x, y - 1))\n return dist[m - 1][n - 1]\n", + "title": "2290. Minimum Obstacle Removal to Reach Corner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , you must transform it into 0 using the following operations any number of times: Return the minimum number of operations to transform n into 0 .", + "description_images": [], + "constraints": [ + "Change the rightmost ( 0 th ) bit in the binary representation of n .", + "Change the i th bit in the binary representation of n if the (i-1) th bit is set to 1 and the (i-2) th through 0 th bits are set to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:2\nExplanation:The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2ndoperation since the 0thbit is 1.\n\"01\" -> \"00\" with the 1stoperation.", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:4\nExplanation:The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2ndoperation since the 1stbit is 1 and 0ththrough 0thbits are 0.\n\"010\" -> \"011\" with the 1stoperation.\n\"011\" -> \"001\" with the 2ndoperation since the 0thbit is 1.\n\"001\" -> \"000\" with the 1stoperation.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 5.71%) | Memory: 41.9 MB (Top 21.90%)\nclass Solution {\n public int minimumOneBitOperations(int n) {\n\n int inv = 0;\n\n // xor until n becomes zero\n for ( ; n != 0 ; n = n >> 1){\n\n inv ^= n;\n System.out.println(inv+\" \"+n);\n }\n\n return inv;\n }\n}", + "title": "1611. Minimum One Bit Operations to Make Integers Zero", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , you must transform it into 0 using the following operations any number of times: Return the minimum number of operations to transform n into 0 .", + "description_images": [], + "constraints": [ + "Change the rightmost ( 0 th ) bit in the binary representation of n .", + "Change the i th bit in the binary representation of n if the (i-1) th bit is set to 1 and the (i-2) th through 0 th bits are set to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:2\nExplanation:The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2ndoperation since the 0thbit is 1.\n\"01\" -> \"00\" with the 1stoperation.", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:4\nExplanation:The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2ndoperation since the 1stbit is 1 and 0ththrough 0thbits are 0.\n\"010\" -> \"011\" with the 1stoperation.\n\"011\" -> \"001\" with the 2ndoperation since the 0thbit is 1.\n\"001\" -> \"000\" with the 1stoperation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n if n <= 1:\n return n\n def leftmostbit(x):\n x |= x >> 1\n x |= x >> 2\n x |= x >> 4\n x |= x >> 8\n x |= x >> 16\n x += 1\n x >>= 1\n return x\n x = leftmostbit(n)\n return ((x << 1) - 1) - self.minimumOneBitOperations(n - x)\n", + "title": "1611. Minimum One Bit Operations to Make Integers Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums containing distinct numbers, an integer start , and an integer goal . There is an integer x that is initially set to start , and you want to perform operations on x such that it is converted to goal . You can perform the following operation repeatedly on the number x : If 0 <= x <= 1000 , then for any index i in the array ( 0 <= i < nums.length ), you can set x to any of the following: Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal , and -1 if it is not possible .", + "description_images": [], + "constraints": [ + "x + nums[i]", + "x - nums[i]", + "x ^ nums[i] (bitwise-XOR)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,12], start = 2, goal = 12\nOutput:2\nExplanation:We can go from 2 → 14 → 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,7], start = 0, goal = -4\nOutput:2\nExplanation:We can go from 0 → 3 → -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,8,16], start = 0, goal = 1\nOutput:-1\nExplanation:There is no way to convert 0 into 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 907 ms (Top 10.13%) | Memory: 306.2 MB (Top 27.03%)\nclass Solution {\n public int minimumOperations(int[] nums, int start, int goal) {\n int res = 0;\n Queue q = new LinkedList<>();\n Set set = new HashSet<>();\n q.offer(start);\n\n while(!q.isEmpty()){\n int size = q.size();\n\n for(int i = 0;i 1000) || set.contains(val))continue;\n if(!set.contains(val))set.add(val);\n\n for(int num : nums){\n q.offer(val + num);\n q.offer(val - num);\n q.offer(val ^ num);\n }\n }\n res++;\n }\n\n return -1;\n }\n}\n", + "title": "2059. Minimum Operations to Convert Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums containing distinct numbers, an integer start , and an integer goal . There is an integer x that is initially set to start , and you want to perform operations on x such that it is converted to goal . You can perform the following operation repeatedly on the number x : If 0 <= x <= 1000 , then for any index i in the array ( 0 <= i < nums.length ), you can set x to any of the following: Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal , and -1 if it is not possible .", + "description_images": [], + "constraints": [ + "x + nums[i]", + "x - nums[i]", + "x ^ nums[i] (bitwise-XOR)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,12], start = 2, goal = 12\nOutput:2\nExplanation:We can go from 2 → 14 → 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,7], start = 0, goal = -4\nOutput:2\nExplanation:We can go from 0 → 3 → -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,8,16], start = 0, goal = 1\nOutput:-1\nExplanation:There is no way to convert 0 into 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4131 ms (Top 24.3%) | Memory: 185.60 MB (Top 35.5%)\n\nclass Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n ans = 0\n seen = {start}\n queue = deque([start])\n while queue: \n for _ in range(len(queue)): \n val = queue.popleft()\n if val == goal: return ans \n if 0 <= val <= 1000: \n for x in nums: \n for op in (add, sub, xor): \n if op(val, x) not in seen: \n seen.add(op(val, x))\n queue.append(op(val, x))\n ans += 1\n return -1 ", + "title": "2059. Minimum Operations to Convert Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,19,8,1]\nOutput:3\nExplanation:The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,20]\nOutput:3\nExplanation:The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 392 ms (Top 56.62%) | Memory: 107.3 MB (Top 79.45%)\nclass Solution {\n public int halveArray(int[] nums) {\n PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder());\n double sum=0;\n for(int i:nums){\n sum+=(double)i;\n q.add((double)i);\n }\n int res=0;\n double req = sum;\n while(sum > req/2){\n double curr = q.poll();\n q.add(curr/2);\n res++;\n sum -= curr/2;\n }\n return res;\n }\n}", + "title": "2208. Minimum Operations to Halve Array Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,19,8,1]\nOutput:3\nExplanation:The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,20]\nOutput:3\nExplanation:The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def halveArray(self, nums: List[int]) -> int:\n # Creating empty heap\n maxHeap = []\n heapify(maxHeap) # Creates minHeap \n \n totalSum = 0\n for i in nums:\n # Adding items to the heap using heappush\n # for maxHeap, function by multiplying them with -1\n heappush(maxHeap, -1*i) \n totalSum += i\n \n requiredSum = totalSum / 2\n minOps = 0\n \n while totalSum > requiredSum:\n x = -1*heappop(maxHeap) # Got negative value make it positive\n x /= 2\n totalSum -= x\n heappush(maxHeap, -1*x) \n minOps += 1\n \n return minOps\n", + "title": "2208. Minimum Operations to Halve Array Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr . For example, if arr = [1,4,1,2] , you can add 3 in the middle and make it [1,4, 3 ,1,2] . Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr . 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.", + "description_images": [], + "constraints": [ + "1 <= target.length, arr.length <= 10^5", + "1 <= target[i], arr[i] <= 10^9", + "target contains no duplicates." + ], + "examples": [ + { + "text": "Example 1: Input:target = [5,1,3],arr= [9,4,2,3,4]\nOutput:2\nExplanation:You can add 5 and 1 in such a way that makesarr= [5,9,4,1,2,3,4], then target will be a subsequence ofarr.", + "image": null + }, + { + "text": "Example 2: Input:target = [6,4,8,1,3,2],arr= [4,7,6,2,3,8,6,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 85.00%) | Memory: 59.9 MB (Top 96.25%)\nclass Solution {\n public int minOperations(int[] target, int[] arr) {\n int n = target.length;\n Map map = new HashMap<>();\n\n for(int i = 0; i < n; i++) {\n map.put(target[i], i);\n }\n\n List array = new ArrayList<>();\n\n for(int i = 0; i < arr.length; i++) {\n if(!map.containsKey(arr[i])) {\n continue;\n }\n\n array.add(map.get(arr[i]));\n }\n\n int maxLen = 0;\n int[] tails = new int[n + 1];\n\n for(int i = 0; i < n; i++) {\n tails[i] = -1;\n }\n\n for(int num: array) {\n int index = findMinIndex(tails, maxLen, num);\n\n if(tails[index] == -1) {\n maxLen++;\n }\n tails[index] = num;\n }\n\n return n - maxLen;\n }\n\n public int findMinIndex(int[] tails, int n, int val) {\n int low = 0;\n int ans = n;\n int high = n - 1;\n\n while(low <= high) {\n int mid = (high + low) / 2;\n\n if(tails[mid] >= val) {\n ans = mid;\n high = mid - 1;\n }\n else {\n low = mid + 1;\n }\n }\n return ans;\n }\n}", + "title": "1713. Minimum Operations to Make a Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr . For example, if arr = [1,4,1,2] , you can add 3 in the middle and make it [1,4, 3 ,1,2] . Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr . 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.", + "description_images": [], + "constraints": [ + "1 <= target.length, arr.length <= 10^5", + "1 <= target[i], arr[i] <= 10^9", + "target contains no duplicates." + ], + "examples": [ + { + "text": "Example 1: Input:target = [5,1,3],arr= [9,4,2,3,4]\nOutput:2\nExplanation:You can add 5 and 1 in such a way that makesarr= [5,9,4,1,2,3,4], then target will be a subsequence ofarr.", + "image": null + }, + { + "text": "Example 2: Input:target = [6,4,8,1,3,2],arr= [4,7,6,2,3,8,6,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 962 ms (Top 100.00%) | Memory: 36.9 MB (Top 93.24%)\nfrom bisect import bisect_left\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n dt = {num: i for i, num in enumerate(target)}\n stack = []\n for num in arr:\n if num not in dt: continue\n i = bisect_left(stack, dt[num])\n if i == len(stack):\n stack.append(dt[num])\n else:\n stack[i] = dt[num]\n return len(target) - len(stack)", + "title": "1713. Minimum Operations to Make a Subsequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D integer grid of size m x n and an integer x . In one operation, you can add x to or subtract x from any element in the grid . A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value . If it is not possible, return -1 .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 10^5", + "1 <= x, grid[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4],[6,8]], x = 2\nOutput:4\nExplanation:We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" + }, + { + "text": "Example 2: Input:grid = [[1,5],[2,3]], x = 1\nOutput:5\nExplanation:We can make every element equal to 3.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[3,4]], x = 2\nOutput:-1\nExplanation:It is impossible to make every element equal.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[][] grid, int x) {\n int[] arr = new int[grid.length * grid[0].length];\n int index = 0;\n \n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n arr[index++] = grid[i][j];\n }\n }\n \n Arrays.sort(arr);\n int median = arr[(arr.length - 1) / 2];\n int steps = 0;\n \n for (int num : arr) {\n if (num == median) {\n continue;\n }\n \n if (Math.abs(num - median) % x != 0) {\n return -1;\n }\n \n steps += (Math.abs(num - median) / x);\n }\n \n return steps;\n }\n}\n", + "title": "2033. Minimum Operations to Make a Uni-Value Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer grid of size m x n and an integer x . In one operation, you can add x to or subtract x from any element in the grid . A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value . If it is not possible, return -1 .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 10^5", + "1 <= x, grid[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4],[6,8]], x = 2\nOutput:4\nExplanation:We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" + }, + { + "text": "Example 2: Input:grid = [[1,5],[2,3]], x = 1\nOutput:5\nExplanation:We can make every element equal to 3.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[3,4]], x = 2\nOutput:-1\nExplanation:It is impossible to make every element equal.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n \n m = len(grid)\n n = len(grid[0])\n\t\t\n\t\t# handle the edge case\n if m==1 and n==1: return 0\n\t\t\n\t\t# transform grid to array, easier to operate\n arr = [] \n for i in range(m):\n arr+=grid[i]\n \n arr.sort()\n \n\t\t# the median is arr[len(arr)//2] when len(arr) is odd\n\t\t# or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even.\n cand1 = arr[len(arr)//2]\n cand2 = arr[len(arr)//2-1]\n \n return min(\n self.get_num_operations_to_target(grid, cand1, x),\n self.get_num_operations_to_target(grid, cand2, x)\n )\n \n \n def get_num_operations_to_target(self, grid, target,x):\n\t\t\"\"\"Get the total number of operations to transform all grid elements to the target value.\"\"\"\n ans = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if abs(grid[i][j]-target)%x!=0:\n return -1\n else:\n ans+=abs(grid[i][j]-target)//x\n\n return ans\n \n", + "title": "2033. Minimum Operations to Make a Uni-Value Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n ). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1 ). The goal is to make all the elements of the array equal . It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n , the length of the array, return the minimum number of operations needed to make all the elements of arr equal.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:2\nExplanation:arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int n) {\n int ans = (n/2)*(n/2);\n if(n%2==1){\n ans += n/2;\n }\n return ans;\n }\n}", + "title": "1551. Minimum Operations to Make Array Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n ). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1 ). The goal is to make all the elements of the array equal . It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n , the length of the array, return the minimum number of operations needed to make all the elements of arr equal.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:2\nExplanation:arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].", + "image": null + }, + { + "text": "Example 2: Input:n = 6\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, n: int) -> int:\n\n return sum([n-x for x in range(n) if x % 2 != 0])", + "title": "1551. Minimum Operations to Make Array Equal", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation , you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating .", + "description_images": [], + "constraints": [ + "nums[i - 2] == nums[i] , where 2 <= i <= n - 1 .", + "nums[i - 1] != nums[i] , where 1 <= i <= n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,3,2,4,3]\nOutput:3\nExplanation:One way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,2]\nOutput:2\nExplanation:One way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumOperations(int[] nums) {\n int freq[][] = new int[100005][2];\n int i, j, k, ans=0;\n for(i = 0; i < nums.length; i++) {\n \t\t\tfreq[nums[i]][i&1]++;\n \t\t}\n \t\t\n \t\tfor(i = 1, j=k=0; i <= 100000; i++) {\n\t\t\t// Add the maximum frequency of odd indexes to maximum frequency even indexes \n\t\t //and vice versa, it will give us how many elements we don't need to change. \n \t\tans = Math.max(ans, Math.max(freq[i][0] + k, freq[i][1] + j));\n j = Math.max(j, freq[i][0]);\n k = Math.max(k, freq[i][1]);\n }\n return nums.length - ans;\n }\n}\n", + "title": "2170. Minimum Operations to Make the Array Alternating", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation , you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating .", + "description_images": [], + "constraints": [ + "nums[i - 2] == nums[i] , where 2 <= i <= n - 1 .", + "nums[i - 1] != nums[i] , where 1 <= i <= n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,3,2,4,3]\nOutput:3\nExplanation:One way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,2]\nOutput:2\nExplanation:One way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3233 ms (Top 5.15%) | Memory: 31.6 MB (Top 46.98%)\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n n = len(nums)\n odd, even = defaultdict(int), defaultdict(int)\n for i in range(n):\n if i % 2 == 0:\n even[nums[i]] += 1\n else:\n odd[nums[i]] += 1\n topEven, secondEven = (None, 0), (None, 0)\n for num in even:\n if even[num] > topEven[1]:\n topEven, secondEven = (num, even[num]), topEven\n elif even[num] > secondEven[1]:\n secondEven = (num, even[num])\n topOdd, secondOdd = (None, 0), (None, 0)\n for num in odd:\n if odd[num] > topOdd[1]:\n topOdd, secondOdd = (num, odd[num]), topOdd\n elif odd[num] > secondOdd[1]:\n secondOdd = (num, odd[num])\n if topOdd[0] != topEven[0]:\n return n - topOdd[1] - topEven[1]\n else:\n return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])", + "title": "2170. Minimum Operations to Make the Array Alternating", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums ( 0-indexed ). In one operation, you can choose an element of the array and increment it by 1 . Return the minimum number of operations needed to make nums strictly increasing . An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1 . An array of length 1 is trivially strictly increasing.", + "description_images": [], + "constraints": [ + "For example, if nums = [1,2,3] , you can choose to increment nums[1] to make nums = [1, 3 ,3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]\nOutput:3\nExplanation:You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,2,4,1]\nOutput:14", + "image": null + }, + { + "text": "Example 3: Input:nums = [8]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n if (nums.length <= 1) {\n return 0;\n }\n\n int count = 0;\n int num = nums[0];\n for (int i = 1; i < nums.length; i++) {\n if (num == nums[i]) {\n count++;\n num++;\n } else if (num > nums[i]) {\n num++;\n count += num - nums[i];\n } else {\n num = nums[i];\n }\n }\n \n return count;\n }\n}\n", + "title": "1827. Minimum Operations to Make the Array Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums ( 0-indexed ). In one operation, you can choose an element of the array and increment it by 1 . Return the minimum number of operations needed to make nums strictly increasing . An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1 . An array of length 1 is trivially strictly increasing.", + "description_images": [], + "constraints": [ + "For example, if nums = [1,2,3] , you can choose to increment nums[1] to make nums = [1, 3 ,3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]\nOutput:3\nExplanation:You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,2,4,1]\nOutput:14", + "image": null + }, + { + "text": "Example 3: Input:nums = [8]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n sol = 0\n last = nums[0]\n\n for i in range(len(nums) - 1):\n if last >= nums[i + 1]:\n sol += last - nums[i + 1] + 1\n last = last + 1\n else:\n last = nums[i + 1]\n \n return sol", + "title": "1827. Minimum Operations to Make the Array Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k . The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i , where k <= i <= n-1 . In one operation , you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k .", + "description_images": [], + "constraints": [ + "For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2)", + "arr[0] <= arr[2] (4 <= 5)", + "arr[1] <= arr[3] (1 <= 2)", + "arr[2] <= arr[4] (5 <= 6)", + "arr[3] <= arr[5] (2 <= 2)", + "However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1] ) or k = 3 (because arr[0] > arr[3] )." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,4,3,2,1], k = 1\nOutput:4\nExplanation:For k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,1,5,2,6,2], k = 2\nOutput:0\nExplanation:This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <=arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,1,5,2,6,2], k = 3\nOutput:2\nExplanation:Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kIncreasing(int[] arr, int k) {\n int ans = arr.length;\n int[] tails = new int[arr.length];\n for (int i = 0; i < k; i ++) {\n int size = 0;\n for (int j = i; j < arr.length; j += k) {\n if (size == 0 || arr[j] >= tails[size - 1]) {\n tails[size ++] = arr[j];\n } else {\n int low = 0, high = size - 1;\n while (low <= high) {\n int mid = (low + high) / 2;\n if (tails[mid] <= arr[j] && tails[mid + 1] > arr[j]) {\n tails[mid + 1] = arr[j];\n break;\n } else if (tails[mid + 1] <= arr[j]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n if (low > high) {\n tails[0] = arr[j];\n }\n }\n }\n ans -= size;\n }\n return ans;\n }\n}\n", + "title": "2111. Minimum Operations to Make the Array K-Increasing", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k . The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i , where k <= i <= n-1 . In one operation , you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k .", + "description_images": [], + "constraints": [ + "For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2)", + "arr[0] <= arr[2] (4 <= 5)", + "arr[1] <= arr[3] (1 <= 2)", + "arr[2] <= arr[4] (5 <= 6)", + "arr[3] <= arr[5] (2 <= 2)", + "However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1] ) or k = 3 (because arr[0] > arr[3] )." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,4,3,2,1], k = 1\nOutput:4\nExplanation:For k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,1,5,2,6,2], k = 2\nOutput:0\nExplanation:This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <=arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,1,5,2,6,2], k = 3\nOutput:2\nExplanation:Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def kIncreasing(self, arr: List[int], k: int) -> int:\n def LNDS(arr: List[int]) -> int:\n mono = []\n for n in arr:\n if not mono or mono[-1] <= n:\n mono.append(n)\n else:\n mono[bisect_right(mono, n)] = n\n return len(mono) \n return len(arr) - sum(LNDS(arr[i::k]) for i in range(k))\n", + "title": "2111. Minimum Operations to Make the Array K-Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer x . In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x . Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible , otherwise, return -1 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4", + "1 <= x <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,4,2,3], x = 5\nOutput:2\nExplanation:The optimal solution is to remove the last two elements to reduce x to zero.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,7,8,9], x = 4\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,20,1,1,3], x = 10\nOutput:5\nExplanation:The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 825 ms (Top 92.58%) | Memory: 31.60 MB (Top 21.29%)\n\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n target, n = sum(nums) - x, len(nums)\n \n if target == 0:\n return n\n \n max_len = cur_sum = left = 0\n \n for right, val in enumerate(nums):\n cur_sum += val\n while left <= right and cur_sum > target:\n cur_sum -= nums[left]\n left += 1\n if cur_sum == target:\n max_len = max(max_len, right - left + 1)\n \n return n - max_len if max_len else -1\n", + "title": "1658. Minimum Operations to Reduce X to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1 . You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1 , you can move to any of the cells (x + 1, 0) , (x + 1, 1) , ..., (x + 1, n - 1) . Note that it is not possible to move from cells in the last row. Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n , where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "grid consists of distinct integers from 0 to m * n - 1 .", + "moveCost.length == m * n", + "moveCost[i].length == n", + "1 <= moveCost[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]\nOutput:17\nExplanation:The path with the minimum possible cost is the path 5 -> 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.", + "image": "https://assets.leetcode.com/uploads/2022/04/28/griddrawio-2.png" + }, + { + "text": "Example 2: Input:grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]\nOutput:6\nExplanation:The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer dp[][];\n public int minPathCost(int[][] grid, int[][] moveCost) \n {\n dp=new Integer[grid.length][grid[0].length];\n int ans=Integer.MAX_VALUE;\n \n for(int i=0;i 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.", + "image": "https://assets.leetcode.com/uploads/2022/04/28/griddrawio-2.png" + }, + { + "text": "Example 2: Input:grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]\nOutput:6\nExplanation:The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n max_row, max_col = len(grid), len(grid[0])\n dp = [[-1] * max_col for _ in range(max_row)] \n\n def recursion(row, col):\n if row == max_row - 1: # If last row then return nodes value\n return grid[row][col]\n if dp[row][col] == -1: # If DP for this node is not computed then we will do so now.\n current = grid[row][col] # Current Node Value\n res = float('inf') # To store best path from Current Node\n for c in range(max_col): # Traverse all path from Current Node\n val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value\n res = min(res, val)\n dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val\n return dp[row][col]\n\n for c in range(max_col):\n recursion(0, c) # Start recursion from all nodes in 1st row\n return min(dp[0]) # Return min value from 1st row\n", + "title": "2304. Minimum Path Cost in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 200", + "0 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,3,1],[1,5,1],[4,2,1]]\nOutput:7\nExplanation:Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6]]\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 89.53%) | Memory: 45.9 MB (Top 59.56%)\nclass Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[] dp = new int[n];\n dp[0] = grid[0][0];\n\n for(int i=1;i int:\n prev=[0]*len(grid[0])\n for i in range(len(grid)):\n temp=[0]*len(grid[0])\n for j in range(len(grid[0])):\n if i==0 and j==0:\n temp[j]=grid[i][j]\n continue\n if i>0:\n lft=grid[i][j]+prev[j]\n else:\n lft=grid[i][j]+1000\n if j>0:\n up=grid[i][j]+temp[j-1]\n else:\n up=grid[i][j]+1000\n temp[j]=min(up,lft)\n prev=temp\n return prev[-1]\n \n \n", + "title": "64. Minimum Path Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num representing the digits of a very large integer and an integer k . You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string .", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3 * 10^4", + "num consists of only digits and does not contain leading zeros .", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"4321\", k = 4\nOutput:\"1342\"\nExplanation:The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" + }, + { + "text": "Example 2: Input:num = \"100\", k = 1\nOutput:\"010\"\nExplanation:It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.", + "image": null + }, + { + "text": "Example 3: Input:num = \"36789\", k = 1000\nOutput:\"36789\"\nExplanation:We can keep the number without any swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 80.8%) | Memory: 52.65 MB (Top 6.3%)\n\nclass Solution {\n public String minInteger(String num, int k) {\n //pqs stores the location of each digit.\n List> pqs = new ArrayList<>();\n for (int i = 0; i <= 9; ++i) {\n pqs.add(new LinkedList<>());\n }\n\n for (int i = 0; i < num.length(); ++i) {\n pqs.get(num.charAt(i) - '0').add(i);\n }\n String ans = \"\";\n SegmentTree seg = new SegmentTree(num.length());\n\n for (int i = 0; i < num.length(); ++i) {\n // At each location, try to place 0....9\n for (int digit = 0; digit <= 9; ++digit) {\n // is there any occurrence of digit left?\n if (pqs.get(digit).size() != 0) {\n // yes, there is a occurrence of digit at pos\n Integer pos = pqs.get(digit).peek();\n\t\t\t\t\t// Since few numbers already shifted to left, this `pos` might be outdated.\n // we try to find how many number already got shifted that were to the left of pos.\n int shift = seg.getCountLessThan(pos);\n // (pos - shift) is number of steps to make digit move from pos to i.\n if (pos - shift <= k) {\n k -= pos - shift;\n seg.add(pos); // Add pos to our segment tree.\n pqs.get(digit).remove();\n ans += digit;\n break;\n }\n }\n }\n }\n return ans;\n }\n\n class SegmentTree {\n int[] nodes;\n int n;\n\n public SegmentTree(int max) {\n nodes = new int[4 * (max)];\n n = max;\n }\n\n public void add(int num) {\n addUtil(num, 0, n, 0);\n }\n\n private void addUtil(int num, int l, int r, int node) {\n if (num < l || num > r) {\n return;\n }\n if (l == r) {\n nodes[node]++;\n return;\n }\n int mid = (l + r) / 2;\n addUtil(num, l, mid, 2 * node + 1);\n addUtil(num, mid + 1, r, 2 * node + 2);\n nodes[node] = nodes[2 * node + 1] + nodes[2 * node + 2];\n }\n\n // Essentialy it tells count of numbers < num.\n public int getCountLessThan(int num) {\n return getUtil(0, num, 0, n, 0);\n }\n\n private int getUtil(int ql, int qr, int l, int r, int node) {\n if (qr < l || ql > r) return 0;\n if (ql <= l && qr >= r) {\n return nodes[node];\n }\n\n int mid = (l + r) / 2;\n return getUtil(ql, qr, l, mid, 2 * node + 1) + getUtil(ql, qr, mid + 1, r, 2 * node + 2);\n }\n }\n\n}", + "title": "1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num representing the digits of a very large integer and an integer k . You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string .", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3 * 10^4", + "num consists of only digits and does not contain leading zeros .", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"4321\", k = 4\nOutput:\"1342\"\nExplanation:The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" + }, + { + "text": "Example 2: Input:num = \"100\", k = 1\nOutput:\"010\"\nExplanation:It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.", + "image": null + }, + { + "text": "Example 3: Input:num = \"36789\", k = 1000\nOutput:\"36789\"\nExplanation:We can keep the number without any swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\n\nclass Solution:\n def minInteger(self, num: str, k: int) -> str:\n sz, window = len(num), SortedList()\n remainedIndices, poppedIndices = SortedList(range(sz)), []\n while k > 0:\n while len(window) < k + 1 and len(window) < len(remainedIndices):\n idx = remainedIndices[len(window)]\n window.add((num[idx], idx))\n if not window:\n break\n index = window.pop(0)[1]\n k -= remainedIndices.bisect_left(index)\n remainedIndices.remove(index)\n poppedIndices.append(index)\n for idx in remainedIndices[k + 1: len(window)]:\n window.remove((num[idx], idx))\n poppedSet = set(poppedIndices)\n return \"\".join(num[idx] for idx in poppedIndices) + \"\".join(num[idx] for idx in range(sz) if idx not in poppedSet)", + "title": "1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')' , in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if:", + "description_images": [], + "constraints": [ + "It is the empty string, contains only lowercase characters, or", + "It can be written as AB ( A concatenated with B ), where A and B are valid strings, or", + "It can be written as (A) , where A is a valid string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lee(t(c)o)de)\"\nOutput:\"lee(t(c)o)de\"\nExplanation:\"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a)b(c)d\"\nOutput:\"ab(c)d\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"))((\"\nOutput:\"\"\nExplanation:An empty string is also valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 39.96%) | Memory: 42.9 MB (Top 93.77%)\nclass Solution {\n public String minRemoveToMakeValid(String s) {\n Stack stack = new Stack<>();\n for(int i=0;i set = new HashSet<>(stack);\n for(int i=0;i= 0; i--){\n if(nums[i] <= last){\n last = nums[i];\n continue;\n }\n if(nums[i] % last == 0){\n // split into nums[i] / last elements, operations cnt = nums[i] / last - 1;\n ret += nums[i] / last - 1;\n }else{\n // split into k elements operations cnt = k - 1;\n int k = nums[i] / last + 1; // ceil\n ret += k - 1;\n last = nums[i] / k; // left most element max is nums[i] / k\n }\n\n }\n\n return ret;\n }\n\n}", + "title": "2366. Minimum Replacements to Sort the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one operation you can replace any element of the array with any two elements that sum to it. Return the minimum number of operations to make an array that is sorted in non-decreasing order .", + "description_images": [], + "constraints": [ + "For example, consider nums = [5,6,7] . In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,9,3]\nOutput:2\nExplanation:Here are the steps to sort the array in non-decreasing order:\n- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]\n- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]\nThere are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]\nOutput:0\nExplanation:The array is already in non-decreasing order. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumReplacement(self, nums) -> int:\n ans = 0\n n = len(nums)\n curr = nums[-1]\n for i in range(n - 2, -1, -1):\n if nums[i] > curr:\n q = nums[i] // curr\n if nums[i] == curr * q:\n nums[i] = curr\n ans += q - 1\n else:\n nums[i] = nums[i] // (q + 1)\n ans += q\n curr = nums[i]\n return ans\n", + "title": "2366. Minimum Replacements to Sort the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array tasks , where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level . Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^5", + "1 <= tasks[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput:4\nExplanation:To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [2,3,3]\nOutput:-1\nExplanation:There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n\tEach round, we can complete either 2 or 3 tasks of the same difficulty level\n Time: O(n)\n Space: O(n)\n*/\nclass Solution {\n public int minimumRounds(int[] tasks) {\n int round = 0;\n Map taskMap = new HashMap<>(); // map of \n for (int i = 0; i < tasks.length; i++) {\n taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);\n }\n \n for (Map.Entry entry : taskMap.entrySet()) {\n if (entry.getValue() == 1) {\n return -1; // we cannot complete if there is only 1 task\n }\n\t\t\t// try to take as many 3's as possible\n round += entry.getValue() / 3; \n\t\t\t\n /*\n\t\t\t\tWe can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous\n\t\t\t\tex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]\n\t\t\t\tIn this example, treat the last [5,5,5], [5] as [5,5], [5,5]\n */\n if (entry.getValue() % 3 != 0) { \n round++; \n }\n }\n return round;\n }\n}", + "title": "2244. Minimum Rounds to Complete All Tasks", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array tasks , where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level . Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^5", + "1 <= tasks[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput:4\nExplanation:To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [2,3,3]\nOutput:-1\nExplanation:There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumRounds(self, tasks: List[int]) -> int:\n dic={}\n c=0\n for i in tasks:\n if i in dic.keys():\n dic[i]+=1\n else:\n dic[i]=1\n for i in dic.keys():\n if dic[i]==1:\n return -1\n while dic[i]>=2:\n if dic[i]-3>1:\n dic[i]-=3\n c+=1\n else:\n dic[i]-=2\n c+=1\n return c", + "title": "2244. Minimum Rounds to Complete All Tasks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the i th node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Return the minimum score of any possible pair of edge removals on the given tree .", + "description_images": [], + "constraints": [ + "For example, say the three components have the node values: [4,5,7] , [1,9] , and [3,3,3] . The three XOR values are 4 ^ 5 ^ 7 = 6 , 1 ^ 9 = 8 , and 3 ^ 3 ^ 3 = 3 . The largest XOR value is 8 and the smallest XOR value is 3 . The score is then 8 - 3 = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]\nOutput:9\nExplanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2ndcomponent has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rdcomponent has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]\nOutput:0\nExplanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2ndcomponent has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rdcomponent has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int minimumScore(int[] nums, int[][] edges) {\n \n // 1.) Compute the adjacency table. Contains all paths, (including to root, must be filtered out later).\n Map> adjGraph = computeAdjGraph(edges);\n \n // 2.) Know compute the total Xors of each node DFS style.\n Map xorMap = new HashMap<>();\n computeNodeXorDfs(0, -1, nums, xorMap, adjGraph);\n int rootXor = xorMap.get(0);\n \n // 3.) Before computing all XORs in O(N^2) fashion, we want to compute a list of nodes of ascendant, descendant relationships.\n // Here we have to chose a SET instead of a list -> else we will run into TLS, obviously there are some duplicates.\n Map> descendants = new HashMap<>();\n Set rootChildren = computeDescendants(0, -1, descendants, adjGraph);\n \n // 4.) We can check now the parent <-> child relationships. \n // Compute each node under the root (not the root itself) for the following conditions:\n // node_i is parent of node_j\n // rootXor = total ^ node_i (removing node_i from total)\n // xor1 = node_i^ node_j (removing node_j from node_i)\n // xor2 = node_j\n // node_j is parent of node_i\n // rootXor = total ^ node_j (removing node_j from total)\n // xor1 = node_j^ node_i (removing node_i from node_j)\n // xor2 = node_i\n // node_j & node_i belong to different parents.\n // rootXor = total ^ node_j^ nodE_i (removing node_i & node_j from total)\n // xor1 = node_i\n // xor2 = node_j\n \n int minScore = Integer.MAX_VALUE;\n \n for(int i = 1; i < adjGraph.keySet().size(); i++){\n for(int j = i+1; j < adjGraph.keySet().size(); j++){\n // Is node_i parent of node_j\n if(descendants.get(i).contains(j)){\n int rootXor1 = rootXor ^ xorMap.get(i);\n int xor1 = xorMap.get(i) ^ xorMap.get(j);\n int xor2 = xorMap.get(j);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n } else if(descendants.get(j).contains(i)){\n int rootXor1 = rootXor ^ xorMap.get(j);\n int xor1 = xorMap.get(j) ^ xorMap.get(i);\n int xor2 = xorMap.get(i);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n } else {\n int rootXor1 = rootXor ^ (xorMap.get(i) ^ xorMap.get(j));\n int xor1 = xorMap.get(i);\n int xor2 = xorMap.get(j);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n }\n }\n }\n \n \n return minScore;\n }\n \n Set computeDescendants(int src, int parent, Map> descendants, Map> adjGraph){\n \n Set childrenOfNode = new HashSet<>();\n \n for(int child : adjGraph.get(src)){\n if(child != parent){\n // add the child node\n childrenOfNode.add(child);\n // add all its children.\n childrenOfNode.addAll(computeDescendants(child, src, descendants, adjGraph));\n } \n }\n \n descendants.put(src, childrenOfNode);\n return childrenOfNode;\n }\n \n int computeNodeXorDfs(int src, int parent, int[] nums, Map xorMap, Map> adjGraph){\n \n int srcXor = nums[src];\n \n for(int child : adjGraph.get(src)){\n if(child != parent)\n srcXor ^= computeNodeXorDfs(child, src, nums, xorMap, adjGraph);\n }\n \n xorMap.put(src, srcXor);\n return srcXor;\n }\n \n Map> computeAdjGraph(int[][] edges){\n \n Map> adjGraph = new HashMap<>();\n \n for(int[] edge : edges){\n int v1 = edge[0];\n int v2 = edge[1];\n \n if(!adjGraph.containsKey(v1)){\n adjGraph.put(v1, new ArrayList<>());\n }\n \n if(!adjGraph.containsKey(v2)){\n adjGraph.put(v2, new ArrayList<>());\n }\n adjGraph.get(v1).add(v2);\n adjGraph.get(v2).add(v1);\n }\n return adjGraph;\n }\n}\n", + "title": "2322. Minimum Score After Removals on a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the i th node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Return the minimum score of any possible pair of edge removals on the given tree .", + "description_images": [], + "constraints": [ + "For example, say the three components have the node values: [4,5,7] , [1,9] , and [3,3,3] . The three XOR values are 4 ^ 5 ^ 7 = 6 , 1 ^ 9 = 8 , and 3 ^ 3 ^ 3 = 3 . The largest XOR value is 8 and the smallest XOR value is 3 . The score is then 8 - 3 = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]\nOutput:9\nExplanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2ndcomponent has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rdcomponent has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]\nOutput:0\nExplanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2ndcomponent has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rdcomponent has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1682 ms (Top 100.0%) | Memory: 18.40 MB (Top 71.7%)\n\nclass Solution:\n def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: \n n = len(nums)\n graph = [[] for _ in range(n)]\n for u, v in edges: \n graph[u].append(v)\n graph[v].append(u)\n \n def fn(u, p): \n nonlocal t\n score[u] = nums[u]\n tin[u] = (t := t+1) # time to enter\n for v in graph[u]: \n if v != p: \n fn(v, u)\n score[u] ^= score[v]\n tout[u] = t # time to exit \n \n t = 0 \n score = [0]*n\n tin = [0]*n \n tout = [0]*n \n fn(0, -1)\n \n ans = inf \n for u in range(1, n): \n for v in range(u+1, n): \n if tin[v] <= tin[u] and tout[v] >= tout[u]: # enter earlier & exit later == parent \n uu = score[u]\n vv = score[v] ^ score[u]\n xx = score[0] ^ score[v]\n elif tin[v] >= tin[u] and tout[v] <= tout[u]: \n uu = score[u] ^ score[v]\n vv = score[v]\n xx = score[0] ^ score[u]\n else: \n uu = score[u]\n vv = score[v]\n xx = score[0] ^ score[u] ^ score[v]\n ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))\n return ans ", + "title": "2322. Minimum Score After Removals on a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a convex n -sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the i th vertex (i.e., clockwise order ). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon .", + "description_images": [], + "constraints": [ + "n == values.length", + "3 <= n <= 50", + "1 <= values[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3]\nOutput:6\nExplanation:The polygon is already triangulated, and the score of the only triangle is 6.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape1.jpg" + }, + { + "text": "Example 2: Input:values = [3,7,4,5]\nOutput:144\nExplanation:There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\nThe minimum score is 144.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape2.jpg" + }, + { + "text": "Example 3: Input:values = [1,3,1,4,1,5]\nOutput:13\nExplanation:The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 13.89%) | Memory: 41.7 MB (Top 61.06%)\nclass Solution {\n int solve(int[] v, int i, int j){\n if(i+1==j)\n return 0;\n int ans= Integer.MAX_VALUE;\n for(int k=i+1;k=0;i--){\n for(int j=i+2;j int:\n \n n = len(values)\n \n c = [[0 for _ in range(n)] for _ in range(n)]\n \n for L in range(2, n):\n \n for i in range(1, n-L+1):\n \n j = i + L - 1\n \n c[i][j] = float('inf')\n \n for k in range(i, j):\n \n q = c[i][k] + c[k+1][j] + (values[i-1]*values[k]*values[j])\n \n if c[i][j] > q:\n c[i][j] = q\n \n return c[1][n-1]\n \n \n \n \n \n", + "title": "1039. Minimum Score Triangulation of Polygon", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n . A frog starts at point 0 in the second lane and wants to jump to point n . However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] ( ranging from 0 to 3 ) describes an obstacle on the lane obstacles[i] at point i . If obstacles[i] == 0 , there are no obstacles at point i . There will be at most one obstacle in the 3 lanes at each point. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1 . To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n .", + "description_images": [], + "constraints": [ + "For example, if obstacles[2] == 1 , then there is an obstacle on lane 1 at point 2." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [0,1,2,3,0]\nOutput:2\nExplanation:The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png" + }, + { + "text": "Example 2: Input:obstacles = [0,1,1,3,3,0]\nOutput:0\nExplanation:There are no obstacles on lane 2. No side jumps are required.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png" + }, + { + "text": "Example 3: Input:obstacles = [0,2,1,0,3,0]\nOutput:2\nExplanation:The optimal solution is shown by the arrows above. There are 2 side jumps.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSideJumps(int[] obstacles) {\n int[] dp = new int[]{1, 0, 1};\n for(int i=1; i=0) min = Math.min(min, val);\n }\n return min;\n }\n}\n", + "title": "1824. Minimum Sideway Jumps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n . A frog starts at point 0 in the second lane and wants to jump to point n . However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] ( ranging from 0 to 3 ) describes an obstacle on the lane obstacles[i] at point i . If obstacles[i] == 0 , there are no obstacles at point i . There will be at most one obstacle in the 3 lanes at each point. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1 . To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n .", + "description_images": [], + "constraints": [ + "For example, if obstacles[2] == 1 , then there is an obstacle on lane 1 at point 2." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [0,1,2,3,0]\nOutput:2\nExplanation:The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png" + }, + { + "text": "Example 2: Input:obstacles = [0,1,1,3,3,0]\nOutput:0\nExplanation:There are no obstacles on lane 2. No side jumps are required.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png" + }, + { + "text": "Example 3: Input:obstacles = [0,2,1,0,3,0]\nOutput:2\nExplanation:The optimal solution is shown by the arrows above. There are 2 side jumps.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n \n \"\"\"\n # TLE Recursion DP\n @cache\n def dp(curr_lane = 2, point = 0):\n if point == len(obstacles)-1:\n return 0\n if obstacles[point+1] == curr_lane:\n return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n \n return dp(curr_lane, point+1)\n \n \n return dp()\n \n \"\"\"\n \n n = len(obstacles) \n dp = [[0, 0, 0, 0] for _ in range(n)]\n \n for point in range(n-2, -1, -1):\n for curr_lane in range(4):\n if obstacles[point+1] == curr_lane:\n dp[point][curr_lane] = min(dp[point+1][lane] for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n else:\n dp[point][curr_lane] = dp[point+1][curr_lane]\n \n return dp[0][2]", + "title": "1824. Minimum Sideway Jumps", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a contiguous subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] of which the sum is greater than or equal to target . If there is no such subarray, return 0 instead.", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]\nOutput:2\nExplanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSubArrayLen(int target, int[] nums) {\n int left = 0;\n int n = nums.length;\n int sum = 0;\n int minCount = Integer.MAX_VALUE;\n for(int i = 0;i= target){\n minCount = Math.min(minCount, i-left+1);\n sum -= nums[left++];\n } \n }\n return minCount == Integer.MAX_VALUE?0:minCount;\n }\n}\n", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a contiguous subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] of which the sum is greater than or equal to target . If there is no such subarray, return 0 instead.", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]\nOutput:2\nExplanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSubArrayLen(self, target, nums):\n\t\t# Init left pointer and answer\n l, ans = 0, len(nums) + 1\n\t\t# Init sum of subarray\n s = 0 \n\t\t# Iterate through all numbers as right subarray \n for r in range(len(nums)):\n\t\t\t# Add right number to sum\n s += nums[r]\n\t\t\t# Check for subarray greater than or equal to target\n while s >= target:\n\t\t\t\t# Calculate new min\n ans = min(ans, r - l + 1)\n\t\t\t\t# Remove current left nubmer from sum\n s -= nums[l]\n\t\t\t\t# Move left index up one\n l += 1\n\t\t# No solution\n if ans == len(nums) + 1:\n return 0\n\t\t# Solution\n return ans \n", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer hoursBefore , the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n , where dist[i] describes the length of the i th road in kilometers . In addition, you are given an integer speed , which is the speed (in km/h ) you will travel at. After you travel road i , you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible .", + "description_images": [], + "constraints": [ + "For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput:1\nExplanation:Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 +0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.", + "image": null + }, + { + "text": "Example 2: Input:dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput:2\nExplanation:Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 +0) + (3/2 + 0)) + ((5/2 +0) + (5/2)) = 10 hours.", + "image": null + }, + { + "text": "Example 3: Input:dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput:-1\nExplanation:It is impossible to arrive at the meeting on time even if you skip all the rests.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 92.86%) | Memory: 43.4 MB (Top 57.14%)\nclass Solution {\n public int minSkips(int[] dist, int speed, int hoursBefore) {\n int N = dist.length, INF = (int)1e9;\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0]=0; // before we start, we have a time of 0 for 0 cost\n for (int i = 0 ; i= 0; j--){ // j (cost) is at most i (num of element-1) so we start from there.\n dp[j]=Math.min(j==0?INF:dp[j-1]+dist[i], ceil(dp[j], speed)+dist[i]);\n }\n }\n for (int i = 0; i < N; i++){ // find the min cost (i) such that the min time is no greater than hoursBefore\n if (ceil(dp[i],speed)/speed<=hoursBefore){\n return i;\n }\n }\n return -1;\n }\n\n private int ceil(int n, int s){\n return n+(s-n%s)%s;\n }\n}", + "title": "1883. Minimum Skips to Arrive at Meeting On Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer hoursBefore , the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n , where dist[i] describes the length of the i th road in kilometers . In addition, you are given an integer speed , which is the speed (in km/h ) you will travel at. After you travel road i , you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible .", + "description_images": [], + "constraints": [ + "For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput:1\nExplanation:Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 +0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.", + "image": null + }, + { + "text": "Example 2: Input:dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput:2\nExplanation:Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 +0) + (3/2 + 0)) + ((5/2 +0) + (5/2)) = 10 hours.", + "image": null + }, + { + "text": "Example 3: Input:dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput:-1\nExplanation:It is impossible to arrive at the meeting on time even if you skip all the rests.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1024 ms (Top 91.67%) | Memory: 285.50 MB (Top 27.78%)\n\nclass Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n if sum(dist)/speed > hoursBefore: return -1 # impossible \n \n @cache\n def fn(i, k): \n \"\"\"Return min time (in distance) of traveling first i roads with k skips.\"\"\"\n if k < 0: return inf # impossible \n if i == 0: return 0 \n return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))\n \n for k in range(len(dist)):\n if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k \n", + "title": "1883. Minimum Skips to Arrive at Meeting On Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n packages that you are trying to place in boxes, one package in each box . There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages , where packages[i] is the size of the i th package. The suppliers are given as a 2D integer array boxes , where boxes[j] is an array of box sizes that the j th supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized . For each package in a box, we define the space wasted to be size of the box - size of the package . The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally , or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large , return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8] , you can fit the packages of size- 2 and size- 3 into two boxes of size- 4 and the package with size- 5 into a box of size- 8 . This would result in a waste of (4-2) + (4-3) + (8-5) = 6 ." + ], + "examples": [ + { + "text": "Example 1: Input:packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput:6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "image": null + }, + { + "text": "Example 2: Input:packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput:-1\nExplanation:There is no box that the package of size 5 can fit in.", + "image": null + }, + { + "text": "Example 3: Input:packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput:9\nExplanation:It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minWastedSpace(int[] packages, int[][] boxes) {\n Arrays.sort(packages);\n int n = packages.length, k = -1;\n long sum = 0, ans = Long.MAX_VALUE;\n int[] pos = new int[100001];\n for (int i = 0; i < 100001; i++){ // precompute jump position.\n while(k < n - 1 && packages[k+1] == i){\n sum += packages[++k];\n }\n pos[i] = k;\n }\n for (int[] b : boxes){\n Arrays.sort(b);\n long cost = -sum;\n k=-1;\n for (int i = 0; i < b.length; i++){\n if (pos[b[i]] >= 0){\n int cnt = pos[b[i]]-k;\n cost += 1L * cnt * b[i];\n k=pos[b[i]];\n }\n }\n ans = k == n-1? Math.min(cost, ans) : ans;\n }\n\n return ans == Long.MAX_VALUE? -1 : (int)(ans % (int)(1e9+7));\n }\n}\n", + "title": "1889. Minimum Space Wasted From Packaging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n packages that you are trying to place in boxes, one package in each box . There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages , where packages[i] is the size of the i th package. The suppliers are given as a 2D integer array boxes , where boxes[j] is an array of box sizes that the j th supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized . For each package in a box, we define the space wasted to be size of the box - size of the package . The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally , or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large , return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8] , you can fit the packages of size- 2 and size- 3 into two boxes of size- 4 and the package with size- 5 into a box of size- 8 . This would result in a waste of (4-2) + (4-3) + (8-5) = 6 ." + ], + "examples": [ + { + "text": "Example 1: Input:packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput:6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "image": null + }, + { + "text": "Example 2: Input:packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput:-1\nExplanation:There is no box that the package of size 5 can fit in.", + "image": null + }, + { + "text": "Example 3: Input:packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput:9\nExplanation:It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2545 ms (Top 38.89%) | Memory: 37.8 MB (Top 95.24%)\nclass Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n # prefix sum to save time\n acc = [0] + [*accumulate(packages)]\n packages.sort()\n\n ans = float('inf')\n for box in boxes:\n tmp = 0\n # deal with smallest box first\n box.sort()\n\n # record number of packages already dealt with\n start = 0\n\n for b in box:\n loc = bisect.bisect(packages, b)\n if loc == 0: continue\n tmp += b * (loc - start) - (acc[loc] - acc[start])\n\n # all are packaged\n if loc == len(packages):\n ans = min(ans, tmp)\n break\n\n start = loc\n\n return ans % (10 **9+7) if ans != float('inf') else -1", + "title": "1889. Minimum Space Wasted From Packaging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a floating-point number hour , representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n , where dist[i] describes the distance (in kilometers) of the i th train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time . Tests are generated such that the answer will not exceed 10^7 and hour will have at most two digits after the decimal point .", + "description_images": [], + "constraints": [ + "For example, if the 1 st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2 nd train ride at the 2 hour mark." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], hour = 6\nOutput:1\nExplanation:At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,3,2], hour = 2.7\nOutput:3\nExplanation:At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "image": null + }, + { + "text": "Example 3: Input:dist = [1,3,2], hour = 1.9\nOutput:-1\nExplanation:It is impossible because the earliest the third train can depart is at the 2 hour mark.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 343 ms (Top 5.57%) | Memory: 108.2 MB (Top 25.06%)\nclass Solution {\n public int minSpeedOnTime(int[] dist, double hour) {\n int left = 1;\n int right = (int) 1e8;\n\n while (left < right) {\n int middle = (left + right) / 2;\n if (arriveOnTime(dist, hour, middle))\n right = middle;\n else left = middle + 1;\n }\n\n return right == (int) 1e8 ? -1 : right;\n }\n\n private boolean arriveOnTime(int[] dist, double hour, int speed) {\n int time = 0;\n for (int i = 0; i < dist.length - 1; i++) {\n time += Math.ceil((double) dist[i] / speed);\n }\n return time + (double) dist[dist.length - 1] / speed <= hour;\n }\n}", + "title": "1870. Minimum Speed to Arrive on Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a floating-point number hour , representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n , where dist[i] describes the distance (in kilometers) of the i th train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time . Tests are generated such that the answer will not exceed 10^7 and hour will have at most two digits after the decimal point .", + "description_images": [], + "constraints": [ + "For example, if the 1 st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2 nd train ride at the 2 hour mark." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], hour = 6\nOutput:1\nExplanation:At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,3,2], hour = 2.7\nOutput:3\nExplanation:At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "image": null + }, + { + "text": "Example 3: Input:dist = [1,3,2], hour = 1.9\nOutput:-1\nExplanation:It is impossible because the earliest the third train can depart is at the 2 hour mark.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5298 ms (Top 60.74%) | Memory: 27.4 MB (Top 98.14%)\n\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n # the speed upper is either the longest train ride: max(dist),\n # or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).\n # notice: \"hour will have at most two digits after the decimal point\"\n upper = max(max(dist), ceil(dist[-1] / 0.01))\n #\n # the function to calcute total time consumed\n total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)\n # the case of impossible to arrive office on time\n if total(upper) > hour:\n return -1\n #\n # binary search: find the mimimal among \"all\" feasible answers\n left, right = 1, upper\n while left < right:\n mid = left + (right - left) // 2\n if total(mid) > hour:\n left = mid + 1 # should be larger\n else:\n right = mid # should explore a smaller one\n return right", + "title": "1870. Minimum Speed to Arrive on Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array nums , obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique . Also return the answer sorted in non-increasing order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,10,9,8]\nOutput:[10,9]\nExplanation:The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,7,6,7]\nOutput:[7,7,6]\nExplanation:The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 45.85%) | Memory: 44.9 MB (Top 74.27%)\nclass Solution {\n public List minSubsequence(int[] nums) {\n int total = 0;\n for(int i=0;i ans = new ArrayList<>();\n for(int i=nums.length-1;i>=0;i--){\n ans.add(nums[i]);\n sum += nums[i];\n if(sum>total-sum){\n return ans;\n }\n }\n return ans;\n }\n}", + "title": "1403. Minimum Subsequence in Non-Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array nums , obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique . Also return the answer sorted in non-increasing order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,10,9,8]\nOutput:[10,9]\nExplanation:The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,7,6,7]\nOutput:[7,7,6]\nExplanation:The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n val = sum(nums)\n temp = []\n for i in range(len(nums)):\n temp.append(nums[i])\n if sum(temp)>val-sum(temp):\n return temp\n \n", + "title": "1403. Minimum Subsequence in Non-Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string target of length n . You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target . In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1] . Flip means changing '0' to '1' and '1' to '0' . Return the minimum number of operations needed to make s equal to target .", + "description_images": [], + "constraints": [ + "n == target.length", + "1 <= n <= 10^5", + "target[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"10111\"\nOutput:3\nExplanation:Initially, s = \"00000\".\nChoose index i = 2: \"00000\" -> \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 2: Input:target = \"101\"\nOutput:3\nExplanation:Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 3: Input:target = \"00000\"\nOutput:0\nExplanation:We do not need any operations since the initial s already equals target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 72.82%) | Memory: 46.7 MB (Top 65.16%)\n\nclass Solution {\n public int minFlips(String target) {\n\n boolean lastBit = false;\n\n int flips = 0;\n for(int i=0;i \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 2: Input:target = \"101\"\nOutput:3\nExplanation:Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 3: Input:target = \"00000\"\nOutput:0\nExplanation:We do not need any operations since the initial s already equals target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minFlips(self, target: str) -> int:\n flip = False\n res = 0\n for c in target:\n if (c == '1') != flip:\n flip = not flip\n res += 1\n \n return res", + "title": "1529. Minimum Suffix Flips", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num . Leading zeros are allowed in new1 and new2 , and all the digits found in num must be used. Return the minimum possible sum of new1 and new2 .", + "description_images": [], + "constraints": [ + "For example, given num = 2932 , you have the following digits: two 2 's, one 9 and one 3 . Some of the possible pairs [new1, new2] are [22, 93] , [23, 92] , [223, 9] and [2, 329] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 2932\nOutput:52\nExplanation:Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.", + "image": null + }, + { + "text": "Example 2: Input:num = 4009\nOutput:13\nExplanation:Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.20 MB (Top 59.52%)\n\nclass Solution\n{\n public int minimumSum(int num)\n {\n int[] dig = new int[4]; // For each digit\n int cur = 0;\n while(num > 0) // Getting each digit\n {\n dig[cur++] = num % 10;\n num /= 10;\n }\n Arrays.sort(dig); // Ascending order\n int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit\n int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit\n return num1 + num2;\n }\n}\n", + "title": "2160. Minimum Sum of Four Digit Number After Splitting Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num . Leading zeros are allowed in new1 and new2 , and all the digits found in num must be used. Return the minimum possible sum of new1 and new2 .", + "description_images": [], + "constraints": [ + "For example, given num = 2932 , you have the following digits: two 2 's, one 9 and one 3 . Some of the possible pairs [new1, new2] are [22, 93] , [23, 92] , [223, 9] and [2, 329] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 2932\nOutput:52\nExplanation:Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.", + "image": null + }, + { + "text": "Example 2: Input:num = 4009\nOutput:13\nExplanation:Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumSum(self, num: int) -> int:\n s=list(str(num))\n s.sort()\n return int(s[0]+s[2])+int(s[1]+s[3])", + "title": "2160. Minimum Sum of Four Digit Number After Splitting Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two positive 0-indexed integer arrays nums1 and nums2 , both of length n . The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i]) 2 for each 0 <= i < n . You are also given two positive integers k1 and k2 . You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times . Note : You are allowed to modify the array elements to become negative integers.", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "1 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= 10^5", + "0 <= k1, k2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\nOutput:579\nExplanation:The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2+ (2 - 10)2+ (3 - 20)2+ (4 - 19)2= 579.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\nOutput:43\nExplanation:One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2+ (4 - 8)2+ (10 - 7)2+ (12 - 9)2= 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /** Algorithm\n 1. Count the differences between each nums1[i] and nums2[i] and store them into an int[100_001], as nums is between 0 and 100_000.\n 2. Let's look at the example of [1,4,10,12], [4,8,6,7]. k1= 1, k2 =1\n Looking at the pairs of abs diff we have 3,4,4,5.\n So a total of 16 diff points with k = 2.\n As we observe, if we use the k operations on the first pair, we can decrease 3 to 1.\n but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.\n However, if we operate on the diff of 5, this would have much more impact.\n 5 - 1 => (4^2)25 - 16 . so we save 9 points by using 1 k\n 5 - 2 => (3^2) 25 - 9. So we save 16 points.\n 3. As we can see, we need to operate on the highest diff, lowering them.\n 4. As we have counted them on step #1, we would have an array like this\n [0,0,0,1,2,1] : 1 diff of 3, 2 of 4 and 1 of 5.\n 5. While k is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time.\n So make all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only\n lower k diff to diff -1.\n So [0,0,0,1,2,1] and k = 2 => [0,0,0,1,3,0] and k =1\n We have 3 diff of 4 and just k =1 so we can turn one 4 into a 3.\n => [0,0,0,2,2,0]. Thus. the diff becomes 2 of 3 and 2 of 4.\n */\n public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {\n long minSumSquare = 0;\n int[] diffs = new int[100_001];\n long totalDiff = 0;\n long kSum = k1 + k2;\n int currentDiff;\n int maxDiff = 0;\n for (int i = 0; i < nums1.length; i++) {\n // get current diff.\n currentDiff = Math.abs(nums1[i] - nums2[i]);\n // if current diff > 0, count/store it. If not,then ignore it.\n if (currentDiff > 0) {\n totalDiff += currentDiff;\n diffs[currentDiff]++;\n maxDiff = Math.max(maxDiff, currentDiff);\n }\n }\n // if kSum (k1 + k2) < totalDifferences, it means we can make all numbers/differences 0s\n if (totalDiff <= kSum) {\n return 0;\n }\n // starting from the back, from the highest difference, lower that group one by one to the previous group.\n // we need to make all n diffs to n-1, then n-2, as long as kSum allows it.\n for (int i = maxDiff; i> 0 && kSum > 0; i--) {\n if (diffs[i] > 0) {\n // if current group has more differences than the totalK, we can only move k of them to the lower level.\n if (diffs[i] >= kSum) {\n diffs[i] -= kSum;\n diffs[i-1] += kSum;\n kSum = 0;\n } else {\n // else, we can make this whole group one level lower.\n diffs[i-1] += diffs[i];\n kSum -= diffs[i];\n diffs[i] = 0;\n }\n }\n }\n\n for (int i = 0; i <= maxDiff; i++) {\n if (diffs[i] > 0) {\n minSumSquare += (long) (Math.pow((long)i, 2)) * diffs[i];\n }\n }\n return minSumSquare;\n }\n}\n", + "title": "2333. Minimum Sum of Squared Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive 0-indexed integer arrays nums1 and nums2 , both of length n . The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i]) 2 for each 0 <= i < n . You are also given two positive integers k1 and k2 . You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times . Note : You are allowed to modify the array elements to become negative integers.", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "1 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= 10^5", + "0 <= k1, k2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\nOutput:579\nExplanation:The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2+ (2 - 10)2+ (3 - 20)2+ (4 - 19)2= 579.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\nOutput:43\nExplanation:One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2+ (4 - 8)2+ (10 - 7)2+ (12 - 9)2= 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1506 ms (Top 29.6%) | Memory: 34.22 MB (Top 74.0%)\n\nclass Solution:\n def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:\n n = len(nums1)\n k = k1+k2 # can combine k's because items can be turned negative\n diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))\n \n # First binary search to find our new max for our diffs array\n l, r = 0, max(diffs)\n while l < r:\n mid = (l+r)//2\n \n # steps needed to reduce all nums greater than newMax\n steps = sum(max(0, num-mid) for num in diffs)\n \n if steps <= k:\n r = mid\n else:\n l = mid+1\n \n newMax = l\n k -= sum(max(0, num-newMax) for num in diffs) # remove used k\n\n # Second binary search to find first index to replace with max val\n l, r = 0, n-1\n while l < r:\n mid = (l+r)//2\n if diffs[mid] < newMax:\n l = mid+1\n else:\n r = mid\n\n # Replace items at index >= l with newMax\n diffs = diffs[:l]+[newMax]*(n-l)\n \n # Use remaining steps to reduce overall score\n for i in range(len(diffs)-1,-1,-1):\n if k == 0 or diffs[i] == 0: break\n diffs[i] -= 1\n k -= 1\n \n return sum(diff*diff for diff in diffs)", + "title": "2333. Minimum Sum of Squared Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n x n binary grid , in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros . Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n) .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "grid[i][j] is either 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/07/28/fw.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput:-1\nExplanation:All rows are similar, swaps have no effect on the grid.", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwaps(int[][] grid) {\n int n = grid.length, ans = 0, cur = 0;\n for (int k = 0; k < n - 1; k++){ // looking for the fitting row for row k\n for (int i = k; i < n; i++){ // start from row k looking downward\n for (int j = k + 1; j < n; j++){ // all cell after and at k + 1 must be 0\n if (grid[i][j] == 1)\n break;\n if (j < n - 1)\n continue;\n for (int m = i; m > k; m--){ // j == n - 1 here, so we found a valid row\n int[] tmp = grid[m - 1]; // swap it into the correct row - row k\n grid[m - 1] = grid[m];\n grid[m] = tmp;\n ans++;\n }\n i = n;\n }\n if (i == n - 1) // i reaches the end and did not find a fitting row, return -1\n return -1;\n }\n }\n return ans;\n }\n}\n", + "title": "1536. Minimum Swaps to Arrange a Binary Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n binary grid , in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros . Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n) .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "grid[i][j] is either 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/07/28/fw.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput:-1\nExplanation:All rows are similar, swaps have no effect on the grid.", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1405 ms (Top 5.77%) | Memory: 15.2 MB (Top 23.08%)\nclass Solution:\n def minSwaps(self, grid) -> int:\n n = len(grid)\n max_right = [-1] * n\n for r, row in enumerate(grid):\n for c in range(n - 1, -1, -1):\n if row[c] == 1:\n max_right[r] = c\n break\n if all(v <= i for i, v in enumerate(sorted(max_right))):\n swaps = 0\n i = 0\n while i < n:\n while i < n and max_right[i] <= i:\n i += 1\n if i == n:\n break\n j = i\n while j < n and max_right[j] > i:\n j += 1\n swaps += j - i\n max_right[i], max_right[i + 1: j + 1] = (max_right[j],\n max_right[i: j])\n i += 1\n return swaps\n return -1", + "title": "1536. Minimum Swaps to Arrange a Binary Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent . Given a binary circular array nums , return the minimum number of swaps required to group all 1 's present in the array together at any location .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,1,1,0,0]\nOutput:1\nExplanation:Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,0,1,1,0]\nOutput:2\nExplanation:Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,0,1]\nOutput:0\nExplanation:All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSwaps(self, nums: List[int]) -> int:\n width = sum(num == 1 for num in nums) #width of the window\n nums += nums\n res = width\n curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width]\n \n for i in range(width, len(nums)):\n curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists\n curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists\n res = min(res, curr_zeros) #update if needed\n \n return res\n", + "title": "2134. Minimum Swaps to Group All 1's Together II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays of the same length nums1 and nums2 . In one operation, you are allowed to swap nums1[i] with nums2[i] . Return the minimum number of needed operations to make nums1 and nums2 strictly increasing . The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1] .", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3, 8 ] , and nums2 = [5,6,7, 4 ] , you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,5,4], nums2 = [1,2,3,7]\nOutput:1\nExplanation:Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwap(int[] nums1, int[] nums2) {\n int p1 = nums1[0], p2 = nums2[0], ans = 0;\n int len = nums1.length, s = 0, count = 0;\n for (int i=1; i < len; i++) {\n int n1 = nums1[i], n2 = nums2[i];\n if (n1 > p1 && n2 > p2) {\n if (n1 > p2 && n2 > p1) {\n ans += Math.min(count, i - s - count);\n s = i; count = 0;\n }\n p1 = n1; p2 = n2;\n } else {\n count++;\n p1 = n2; p2 = n1;\n }\n }\n return ans + Math.min(count, len - s - count);\n }\n}\n", + "title": "801. Minimum Swaps To Make Sequences Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays of the same length nums1 and nums2 . In one operation, you are allowed to swap nums1[i] with nums2[i] . Return the minimum number of needed operations to make nums1 and nums2 strictly increasing . The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1] .", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3, 8 ] , and nums2 = [5,6,7, 4 ] , you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,5,4], nums2 = [1,2,3,7]\nOutput:1\nExplanation:Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1198 ms (Top 36.1%) | Memory: 149.20 MB (Top 27.6%)\n\nclass Solution:\n def minSwap(self, nums1: List[int], nums2: List[int]) -> int:\n dp = [[-1]*2 for i in range(len(nums1))]\n \n def solve(prev1, prev2, i, swaped):\n if i >= len(nums1): return 0\n if dp[i][swaped] != -1: return dp[i][swaped]\n \n ans = 2**31\n \n # No Swap\n if nums1[i] > prev1 and nums2[i] > prev2:\n ans = solve(nums1[i], nums2[i], i+1, 0) \n \n # Swap\n if nums1[i] > prev2 and nums2[i] > prev1:\n ans = min(ans, 1 + solve(nums2[i], nums1[i], i+1, 1)) \n \n dp[i][swaped] = ans\n return ans\n \n return solve(-1, -1, 0, 0) ", + "title": "801. Minimum Swaps To Make Sequences Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only . Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j] . Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 1000", + "s1, s2 only contain 'x' or 'y' ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"xx\", s2 = \"yy\"\nOutput:1\nExplanation:Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"xy\", s2 = \"yx\"\nOutput:2\nExplanation:Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"xx\", s2 = \"xy\"\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.80 MB (Top 5.91%)\n\nclass Solution {\n public int minimumSwap(String s1, String s2) {\n \n int count = 0;\n int cnt_1 = 0;\n int cnt_2 = 0;\n char[] a = s1.toCharArray();\n char[] b = s2.toCharArray();\n \n for(int i=0;i int:\n h = defaultdict(int)\n count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count += 1\n h[s1[i]] += 1\n if count % 2 != 0: \n return -1\n res, a, b = 0, h['x'], h['y']\n res += a // 2 + b // 2\n if a % 2 == 0:\n return res\n return res + 2", + "title": "1247. Minimum Swaps to Make Strings Equal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "2 <= timePoints.length <= 2 * 10^4", + "timePoints[i] is in the format \"HH:MM\" ." + ], + "examples": [ + { + "text": "Example 1: Input:timePoints = [\"23:59\",\"00:00\"]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 62.54%) | Memory: 46.9 MB (Top 41.18%)\nclass Solution {\n public int findMinDifference(List timePoints) {\n int N = timePoints.size();\n int[] minutes = new int[N];\n for(int i = 0; i < N; i++){\n int hr = Integer.parseInt(timePoints.get(i).substring(0, 2));\n int min = Integer.parseInt(timePoints.get(i).substring(3, 5));\n minutes[i] = hr * 60 + min;\n }\n Arrays.sort(minutes);\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < N - 1; i++){\n res = Math.min(res, minutes[i + 1] - minutes[i]);\n }\n int b = minutes[0];\n int a = minutes[N - 1];\n return Math.min(res, (b - a + 1440) % 1440);\n }\n}", + "title": "539. Minimum Time Difference", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "2 <= timePoints.length <= 2 * 10^4", + "timePoints[i] is in the format \"HH:MM\" ." + ], + "examples": [ + { + "text": "Example 1: Input:timePoints = [\"23:59\",\"00:00\"]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 91.63%) | Memory: 20.60 MB (Top 5.75%)\n\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n # Convert time points to minutes since midnight and sort the list\n minutes = sorted([int(time[:2]) * 60 + int(time[3:]) for time in timePoints])\n \n # Calculate the minimum difference between adjacent time points\n min_diff = float('inf')\n for i in range(len(minutes) - 1):\n diff = minutes[i+1] - minutes[i]\n if diff < min_diff:\n min_diff = diff\n \n # Calculate the difference between the first and last time points\n diff = (24*60 - minutes[-1] + minutes[0]) % (24*60)\n if diff < min_diff:\n min_diff = diff\n \n return min_diff\n\n", + "title": "539. Minimum Time Difference", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1 , which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Additionally, there is a boolean array hasApple , where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i < b i <= n - 1", + "from i < to i", + "hasApple.length == n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput:8\nExplanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput:6\nExplanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png" + }, + { + "text": "Example 3: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minTime(int n, int[][] edges, List hasApple) {\n HashMap> graph = new HashMap<>(n);\n for(int edge[] : edges){\n int a = edge[0], b = edge[1];\n graph.putIfAbsent(a, new LinkedList<>());\n graph.putIfAbsent(b, new LinkedList<>());\n graph.get(a).add(b);\n graph.get(b).add(a);\n }\n \n boolean[] visited = new boolean[n];\n Arrays.fill(visited,false);\n \n int a = move(0,graph,hasApple,n,visited);\n \n return a==-1?0:a;\n }\n \n public int move(int i,HashMap> graph,List hasApple,int n,boolean[] visited){\n visited[i]=true;\n boolean cont = false;\n if(hasApple.get(i)){\n cont=true;\n }\n \n List list = graph.get(i);\n \n if(list==null){\n return cont?0:-1;\n }\n int j = 0;\n for(int k : list){\n if(!visited[k]){\n int a = move(k,graph,hasApple,n,visited);\n if(a!=-1){\n j+=2+a;\n }\n }\n }\n if(j==0 && cont) return 0;\n return j==0?-1:j;\n }\n}", + "title": "1443. Minimum Time to Collect All Apples in a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1 , which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Additionally, there is a boolean array hasApple , where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i < b i <= n - 1", + "from i < to i", + "hasApple.length == n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput:8\nExplanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput:6\nExplanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png" + }, + { + "text": "Example 3: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1818 ms (Top 5.15%) | Memory: 87.1 MB (Top 5.14%)\nclass Solution:\n\n def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:\n graph_map = {i: set() for i in range(n)}\n for edge in edges:\n graph_map[edge[0]].add(edge[1])\n graph_map[edge[1]].add(edge[0])\n\n self.result = set()\n visited = set()\n def dfs(node, path):\n visited.add(node)\n if hasApple[node]:\n temp = path + '|' + str(node)\n temp = temp.split('|')[1:]\n # print(temp)\n for i in range(1, len(temp)):\n self.result.add((temp[i], temp[i-1]))\n for nei in graph_map[node]:\n if nei not in visited:\n dfs(nei, path + '|' + str(node))\n\n dfs(0, \"\")\n # print(self.result)\n return len(self.result) * 2", + "title": "1443. Minimum Time to Collect All Apples in a Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array time where time[i] denotes the time taken by the i th bus to complete one trip . Each bus can make multiple trips successively ; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently ; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips , which denotes the number of trips all buses should make in total . Return the minimum time required for all buses to complete at least totalTrips trips .", + "description_images": [], + "constraints": [ + "1 <= time.length <= 10^5", + "1 <= time[i], totalTrips <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:time = [1,2,3], totalTrips = 5\nOutput:3\nExplanation:- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.", + "image": null + }, + { + "text": "Example 2: Input:time = [2], totalTrips = 1\nOutput:2\nExplanation:There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumTime(int[] time, int totalTrips) {\n long anstillnow=-1;\n \n long left=1, right= 100000000000001L;\n \n while(left<=right){\n long mid= left+ (right-left)/2; //find mid point like this to avoid overflow\n long curr_trips=0;\n for(int t: time){\n curr_trips+= mid/t;\n }\n \n if(curr_trips>=totalTrips){\n anstillnow=mid;\n right=mid-1;\n }\n \n else{\n left=mid+1;\n }\n }\n \n return anstillnow; \n }\n}\n", + "title": "2187. Minimum Time to Complete Trips", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array time where time[i] denotes the time taken by the i th bus to complete one trip . Each bus can make multiple trips successively ; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently ; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips , which denotes the number of trips all buses should make in total . Return the minimum time required for all buses to complete at least totalTrips trips .", + "description_images": [], + "constraints": [ + "1 <= time.length <= 10^5", + "1 <= time[i], totalTrips <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:time = [1,2,3], totalTrips = 5\nOutput:3\nExplanation:- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.", + "image": null + }, + { + "text": "Example 2: Input:time = [2], totalTrips = 1\nOutput:2\nExplanation:There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minimumTime(self, time, totalTrips):\n anstillnow=-1;\n left=1;\n right= 100000000000001;\n \n while(left<=right):\n mid= left+ (right-left)/2 #find mid point like this to avoid overflow\n \n curr_trips=0;\n \n for t in time:\n curr_trips+= mid/t\n \n if(curr_trips>=totalTrips):\n anstillnow=mid\n right=mid-1\n \n else:\n left=mid+1\n\n return anstillnow\n", + "title": "2187. Minimum Time to Complete Trips", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [f i , r i ] indicates that the i th tire can finish its x th successive lap in f i * r i (x-1) seconds. You are also given an integer changeTime and an integer numLaps . The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.", + "description_images": [], + "constraints": [ + "For example, if f i = 3 and r i = 2 , then the tire would finish its 1 st lap in 3 seconds, its 2 nd lap in 3 * 2 = 6 seconds, its 3 rd lap in 3 * 2 2 = 12 seconds, etc." + ], + "examples": [ + { + "text": "Example 1: Input:tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\nOutput:21\nExplanation:Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\nOutput:25\nExplanation:Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 41.82%) | Memory: 150.6 MB (Top 27.82%)\nclass Solution {\n int changeTime;\n public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n this.changeTime = changeTime;\n int[] minTime = new int[numLaps + 1];\n Arrays.fill(minTime, Integer.MAX_VALUE);\n\n for (int[] tire : tires){\n populateMinTime(tire, minTime);\n }\n\n int[] dp = new int[numLaps + 1];\n for (int i = 1; i <= numLaps; i++){\n dp[i] = minTime[i]; // maxValue for dp[i] is Integer.MAX_VALUE, no need to worry about overflow\n for (int j = 1; j < i; j++){\n dp[i] = Math.min(dp[i], dp[j] + changeTime + dp[i - j]); // it will never overflow, since dp[j] are far less than Integer.MAX_VALUE\n }\n }\n return dp[numLaps];\n }\n\n private void populateMinTime(int[] tire, int[] minTime){\n int sum = 0;\n int base = tire[0];\n int ex = tire[1];\n int spent = 1;\n for (int i = 1; i < minTime.length; i++){\n spent = (i == 1) ? base : spent * ex;\n if (spent > changeTime + base){break;} // set boundary\n sum += spent;\n minTime[i] = Math.min(minTime[i], sum);\n }\n }\n}", + "title": "2188. Minimum Time to Finish the Race", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [f i , r i ] indicates that the i th tire can finish its x th successive lap in f i * r i (x-1) seconds. You are also given an integer changeTime and an integer numLaps . The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.", + "description_images": [], + "constraints": [ + "For example, if f i = 3 and r i = 2 , then the tire would finish its 1 st lap in 3 seconds, its 2 nd lap in 3 * 2 = 6 seconds, its 3 rd lap in 3 * 2 2 = 12 seconds, etc." + ], + "examples": [ + { + "text": "Example 1: Input:tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\nOutput:21\nExplanation:Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\nOutput:25\nExplanation:Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n # by observation, we can try to find out the optimal usage within certain numLaps\n # use DP\n # the optimal usage of this lap = min(change tire , no change)\n # dp(laps) = min( dp(laps-1)+dp(1) + dp(laps-2)+dp(2) + ...)\n \n # we don't want to use tires too many laps, which will create unrealistic single lap time\n\t\t# we can evaluate single lap time by using changeTime <= 100000 and r >= 2\n\t\t# x = minimal continously laps\n\t\t# single lap time = 1*2^x <= 100000 -> x can't go more than 19\n\t\tlimit = 19\n tires = list(set([(t1, t2) for t1, t2 in tires]))\n memo = [[(-1,-1) for _ in range(min(limit,numLaps)+1)] for _ in range(len(tires))]\n \n for i in range(len(tires)):\n for j in range(1, min(limit,numLaps)+1): # lap 1 to numLaps\n if j == 1:\n memo[i][j] = (tires[i][0], tires[i][0]) # total time, lap time\n else:\n # print('i, j', i, j)\n tmp = memo[i][j-1][1]*tires[i][1] # cost of continuously use tire this lap\n memo[i][j] = (memo[i][j-1][0]+tmp, tmp)\n \n @cache\n def dp(laps):\n if laps == 1:\n return min(memo[i][1][0] for i in range(len(tires)))\n \n # no change:\n best_time = min(memo[i][laps][0] for i in range(len(tires))) if laps <= limit else float('inf')\n \n # change tire:\n\t\t\t# e.g. change tire at this lap and see if it'll be faster -> dp(laps-1) + changeTime + dp(1)\n # check all previous laps: dp(a) + changeTime + dp(b) until a < b\n for j in range(1, laps):\n a, b = laps-j, j\n if a >= b:\n ta = dp(a)\n tb = dp(b)\n if ta+tb+changeTime < best_time:\n best_time = ta+tb+changeTime\n return best_time\n \n return dp(numLaps)\n", + "title": "2188. Minimum Time to Finish the Race", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i th balloon. Alice wants the rope to be colorful . She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful . You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i th balloon from the rope. Return the minimum time Bob needs to make the rope colorful .", + "description_images": [], + "constraints": [ + "n == colors.length == neededTime.length", + "1 <= n <= 10^5", + "1 <= neededTime[i] <= 10^4", + "colors contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaac\", neededTime = [1,2,3,4,5]\nOutput:3\nExplanation:In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg" + }, + { + "text": "Example 2: Input:colors = \"abc\", neededTime = [1,2,3]\nOutput:0\nExplanation:The rope is already colorful. Bob does not need to remove any balloons from the rope.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg" + }, + { + "text": "Example 3: Input:colors = \"aabaa\", neededTime = [1,2,3,4,1]\nOutput:2\nExplanation:Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCost(String colors, int[] neededTime) {\n return minCost(colors, neededTime, 0, neededTime.length - 1);\n }\n \n public int minCost(String colors, int[] neededTime, int start, int end) {\n if (start == end) {\n return 0;\n }\n \n int mid = (start + end) / 2;\n int lEnd = mid;\n int rStart = mid + 1;\n int t1 = minCost(colors, neededTime, start, lEnd);\n int t2 = minCost(colors, neededTime, rStart, end);\n \n while (neededTime[lEnd] < 0 && lEnd >= start) {\n --lEnd;\n }\n while (neededTime[rStart] < 0 && rStart <= end) {\n ++rStart;\n }\n \n if (colors.charAt(lEnd) != colors.charAt(rStart)) {\n return t1 + t2;\n }\n \n int removeTime = 0;\n if (neededTime[lEnd] <= neededTime[rStart]) {\n removeTime = neededTime[lEnd];\n neededTime[lEnd] *= -1;\n }\n else {\n removeTime = neededTime[rStart];\n neededTime[rStart] *= -1;\n }\n \n return t1 + t2 + removeTime;\n }\n}\n", + "title": "1578. Minimum Time to Make Rope Colorful", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i th balloon. Alice wants the rope to be colorful . She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful . You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i th balloon from the rope. Return the minimum time Bob needs to make the rope colorful .", + "description_images": [], + "constraints": [ + "n == colors.length == neededTime.length", + "1 <= n <= 10^5", + "1 <= neededTime[i] <= 10^4", + "colors contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaac\", neededTime = [1,2,3,4,5]\nOutput:3\nExplanation:In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg" + }, + { + "text": "Example 2: Input:colors = \"abc\", neededTime = [1,2,3]\nOutput:0\nExplanation:The rope is already colorful. Bob does not need to remove any balloons from the rope.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg" + }, + { + "text": "Example 3: Input:colors = \"aabaa\", neededTime = [1,2,3,4,1]\nOutput:2\nExplanation:Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 862 ms (Top 94.6%) | Memory: 27.26 MB (Top 71.4%)\n\nclass Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n ans = prev = 0 # index of previously retained letter \n for i in range(1, len(s)): \n if s[prev] != s[i]: prev = i\n else: \n ans += min(cost[prev], cost[i])\n if cost[prev] < cost[i]: prev = i\n return ans ", + "title": "1578. Minimum Time to Make Rope Colorful", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the i th car does not contain illegal goods and s[i] = '1' denotes that the i th car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods . Note that an empty sequence of cars is considered to have no cars containing illegal goods.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1100101\"\nOutput:5\nExplanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0010\"\nOutput:2\nExplanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 58.8%) | Memory: 47.53 MB (Top 50.0%)\n\nclass Solution {\n public int minimumTime(String s) {\n int n = s.length();\n int min = s.length();\n int[] nums = new int[n];\n for (int i = 0; i < n; i++)\n nums[i] = s.charAt(i) - '0';\n\n\t\t// step1\n int[] leftOptimized = new int[n + 2];\n for (int i = 1; i <= n; i++) {\n leftOptimized[i] = Math.min(i, leftOptimized[i - 1] + (nums[i - 1] == 1? 2: 0));\n }\n\n\t\t// step2\n int[] rightOptimized = new int[n + 2];\n for (int i = n; i > 0; i--) {\n rightOptimized[i] = Math.min(n - i + 1, rightOptimized[i + 1] + (nums[i - 1] == 1? 2: 0));\n }\n\n\t\t// step3\n for (int p = 0; p <= n; p++) {\n min = Math.min(min, leftOptimized[p] + rightOptimized[p + 1]);\n }\n\n return min;\n }\n}", + "title": "2167. Minimum Time to Remove All Cars Containing Illegal Goods", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the i th car does not contain illegal goods and s[i] = '1' denotes that the i th car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods . Note that an empty sequence of cars is considered to have no cars containing illegal goods.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1100101\"\nOutput:5\nExplanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0010\"\nOutput:2\nExplanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumTime(self, s):\n def minSum(nums):\n dp = [0]*len(nums)\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n dp[i] = min(nums[i], nums[i] + dp[i-1])\n return min(0, min(dp))\n\n n = len(s)\n s1 = [1 if i == \"1\" else -1 for i in s]\n score = minSum(s1)\n \n return n + score\n", + "title": "2167. Minimum Time to Remove All Cars Containing Illegal Goods", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer . A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a' . Each second, you may perform one of the following operations: Given a string word , return the minimum number of seconds to type out the characters in word .", + "description_images": [], + "constraints": [ + "Move the pointer one character counterclockwise or clockwise .", + "Type the character the pointer is currently on." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abc\"\nOutput:5\nExplanation:The characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.", + "image": null + }, + { + "text": "Example 2: Input:word = \"bza\"\nOutput:7\nExplanation:The characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.", + "image": null + }, + { + "text": "Example 3: Input:word = \"zjpc\"\nOutput:34\nExplanation:The characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minTimeToType(String word) {\n char prevChar = 'a';\n int totalTime = word.length();\n for(int i = 0; i < word.length(); i++){\n char currChar = word.charAt(i);\n int diff = Math.abs(currChar - prevChar);\n totalTime += Math.min(diff, 26 - diff);\n prevChar = currChar;\n }\n \n return totalTime;\n }\n}\n", + "title": "1974. Minimum Time to Type Word Using Special Typewriter", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer . A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a' . Each second, you may perform one of the following operations: Given a string word , return the minimum number of seconds to type out the characters in word .", + "description_images": [], + "constraints": [ + "Move the pointer one character counterclockwise or clockwise .", + "Type the character the pointer is currently on." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abc\"\nOutput:5\nExplanation:The characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.", + "image": null + }, + { + "text": "Example 2: Input:word = \"bza\"\nOutput:7\nExplanation:The characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.", + "image": null + }, + { + "text": "Example 3: Input:word = \"zjpc\"\nOutput:34\nExplanation:The characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minTimeToType(self, word: str) -> int:\n prev = \"a\"\n res = 0\n for c in word:\n gap = abs(ord(c)-ord(prev))\n res += min(gap, 26 - gap)\n prev = c\n return res + len(word)\n", + "title": "1974. Minimum Time to Type Word Using Special Typewriter", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On a 2D plane, there are n points with integer coordinates points[i] = [x i , y i ] . Return the minimum time in seconds to visit all the points in the order given by points . You can move according to these rules:", + "description_images": [], + "constraints": [ + "In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "move vertically by one unit,", + "move horizontally by one unit, or", + "move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "You have to visit the points in the same order as they appear in the array.", + "You are allowed to pass through points that appear later in the order, but these do not count as visits." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[3,4],[-1,0]]\nOutput:7\nExplanation:One optimal path is[1,1]-> [2,2] -> [3,3] ->[3,4]-> [2,3] -> [1,2] -> [0,1] ->[-1,0]Time from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds", + "image": "https://assets.leetcode.com/uploads/2019/11/14/1626_example_1.PNG" + }, + { + "text": "Example 2: Input:points = [[3,2],[-2,2]]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 57.50%) | Memory: 43.4 MB (Top 57.64%)\nclass Solution {\n public int minTimeToVisitAllPoints(int[][] points) {\n int max = 0, x, y;\n for(int i = 0; i < points.length - 1; i++){\n for(int j = 0; j < points[i].length - 1; j++){\n x = Math.abs(points[i][j] - points[i+1][j]);\n y = Math.abs(points[i][j+1] - points[i+1][j+1]);\n max += Math.max(x,y);\n }\n }\n return max;\n }\n}", + "title": "1266. Minimum Time Visiting All Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On a 2D plane, there are n points with integer coordinates points[i] = [x i , y i ] . Return the minimum time in seconds to visit all the points in the order given by points . You can move according to these rules:", + "description_images": [], + "constraints": [ + "In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "move vertically by one unit,", + "move horizontally by one unit, or", + "move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "You have to visit the points in the same order as they appear in the array.", + "You are allowed to pass through points that appear later in the order, but these do not count as visits." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[3,4],[-1,0]]\nOutput:7\nExplanation:One optimal path is[1,1]-> [2,2] -> [3,3] ->[3,4]-> [2,3] -> [1,2] -> [0,1] ->[-1,0]Time from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds", + "image": "https://assets.leetcode.com/uploads/2019/11/14/1626_example_1.PNG" + }, + { + "text": "Example 2: Input:points = [[3,2],[-2,2]]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 57.7%) | Memory: 13.27 MB (Top 67.6%)\n\nclass Solution:\n def minTimeToVisitAllPoints(self, points):\n res = 0\n n = len(points)\n for i in range(n-1):\n dx = abs(points[i+1][0]-points[i][0])\n dy = abs(points[i+1][1]-points[i][1])\n res+= max(dx,dy)\n return res\n\n \nobj = Solution()\nprint(obj.minTimeToVisitAllPoints([[1,1],[3,4],[-1,0]]))", + "title": "1266. Minimum Time Visiting All Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are currently designing a dynamic array. You are given a 0-indexed integer array nums , where nums[i] is the number of elements that will be in the array at time i . In addition, you are given an integer k , the maximum number of times you can resize the array (to any size). The size of the array at time t , size t , must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as size t - nums[t] , and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length . Return the minimum total space wasted if you can resize the array at most k times . Note: The array can have any size at the start and does not count towards the number of resizing operations.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 10^6", + "0 <= k <= nums.length - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20], k = 0\nOutput:10\nExplanation:size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30], k = 1\nOutput:10\nExplanation:size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,20,15,30,20], k = 2\nOutput:15\nExplanation:size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n// dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times \n\n int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 }\n public int minSpaceWastedKResizing(int[] nums, int k) {\n \n int dp[][]=new int[nums.length+1][k+1];\n memeset(dp, -1);\n return f(dp, 0, k, nums);\n \n }\n \n int f(int dp[][], int idx, int k, int nums[])\n {\n if(idx==nums.length)\n return 0;\n if(k==-1)\n return INF;\n \n if(dp[idx][k] != -1)\n return dp[idx][k];\n \n int ans=INF, max=nums[idx], sum=0;\n \n for(int j=idx; j int:\n def waste(i, j, h):\n sumI = sums[i-1] if i > 0 else 0\n return (j-i+1)*h - sums[j] + sumI\n \n def dp(i, k):\n if i <= k:\n return 0\n if k < 0:\n return MAX\n if (i, k) in memoize:\n return memoize[(i, k)]\n \n _max = A[i]\n r = MAX\n for j in range(i-1, -2, -1):\n r = min(r, dp(j, k-1) + waste(j+1, i, _max))\n _max = max(_max, A[j])\n\n memoize[(i, k)] = r\n return r\n \n sums = list(accumulate(A))\n n = len(A)\n MAX = 10**6*200\n memoize = {}\n\n return dp(n-1, K)", + "title": "1959. Minimum Total Space Wasted With K Resizing Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , you start with an initial positive value startValue . In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-3,2,-3,4,2]\nOutput:5\nExplanation:If you choose startValue = 4, in the third iteration your step by step sum is less than 1.step by step sumstartValue = 4 | startValue = 5 | nums(4-3) = 1 | (5-3) = 2 | -3\n (1+2) = 3 | (2+2) = 4 | 2\n (3-3) = 0 | (4-3) = 1 | -3\n (0+4) = 4 | (1+4) = 5 | 4\n (4+2) = 6 | (5+2) = 7 | 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]\nOutput:1\nExplanation:Minimum start value should be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-2,-3]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minStartValue(int[] nums) {\n int lowest_sum = 0;\n int sum = 0;\n for(int i=0; i sum) {\n lowest_sum = sum;\n }\n }\n return 1-lowest_sum;\n }\n}\n", + "title": "1413. Minimum Value to Get Positive Step by Step Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums , you start with an initial positive value startValue . In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-3,2,-3,4,2]\nOutput:5\nExplanation:If you choose startValue = 4, in the third iteration your step by step sum is less than 1.step by step sumstartValue = 4 | startValue = 5 | nums(4-3) = 1 | (5-3) = 2 | -3\n (1+2) = 3 | (2+2) = 4 | 2\n (3-3) = 0 | (4-3) = 1 | -3\n (0+4) = 4 | (1+4) = 5 | 4\n (4+2) = 6 | (5+2) = 7 | 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]\nOutput:1\nExplanation:Minimum start value should be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-2,-3]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 60.3%) | Memory: 16.30 MB (Top 27.0%)\n\nclass Solution:\n def minStartValue(self, nums: List[int]) -> int:\n return max(1, 1 - min(accumulate(nums)))", + "title": "1413. Minimum Value to Get Positive Step by Step Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1 . You are also given a 2D integer array edges where edges[i] = [from i , to i , weight i ] denotes that there exists a directed edge from from i to to i with weight weight i . Lastly, you are given three distinct integers src1 , src2 , and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph . In case such a subgraph does not exist, return -1 . A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "0 <= edges.length <= 10^5", + "edges[i].length == 3", + "0 <= from i , to i , src1, src2, dest <= n - 1", + "from i != to i", + "src1 , src2 , and dest are pairwise distinct.", + "1 <= weight[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5\nOutput:9\nExplanation:The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example1drawio.png" + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2\nOutput:-1\nExplanation:The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example2-1drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 105 ms (Top 87.23%) | Memory: 121.90 MB (Top 31.91%)\n\nclass Solution {\n ArrayList[] nextGraph, preGraph;\n \n public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {\n buildGraph(n, edges);\n \n long[] src1To = new long[n], src2To = new long[n], toDest = new long[n];\n Arrays.fill(src1To, -1);\n Arrays.fill(src2To, -1);\n Arrays.fill(toDest, -1);\n \n shortestPath(src1, src1To, nextGraph);\n shortestPath(src2, src2To, nextGraph);\n shortestPath(dest, toDest, preGraph);\n \n long res = -1;\n for (int i = 0; i < n; i++) {\n long d1 = src1To[i], d2 = src2To[i], d3 = toDest[i];\n if (d1 >= 0 && d2 >= 0 && d3 >= 0) {\n long d = d1 + d2 + d3;\n if (res == -1 || d < res) {\n res = d;\n }\n }\n }\n \n return res;\n }\n \n private void buildGraph(int n, int[][] edges) {\n nextGraph = new ArrayList[n];\n preGraph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n nextGraph[i] = new ArrayList();\n preGraph[i] = new ArrayList();\n }\n \n for (int[] edge : edges) {\n int from = edge[0], to = edge[1], weight = edge[2];\n nextGraph[from].add(new int[] {to, weight});\n preGraph[to].add(new int[] {from, weight});\n }\n }\n \n private void shortestPath(int src, long[] srcTo, ArrayList[] graph) {\n PriorityQueue heap = new PriorityQueue<>((a, b) -> Long.compare(a[1], b[1]));\n heap.offer(new long[] {src, 0});\n \n while (!heap.isEmpty()) {\n long[] node = heap.poll();\n int to = (int) node[0];\n long dist = node[1];\n if (srcTo[to] != -1 && srcTo[to] <= dist) continue;\n srcTo[to] = dist;\n for (int[] next : graph[to]) {\n heap.offer(new long[] {next[0], dist + next[1]});\n }\n }\n }\n}\n", + "title": "2203. Minimum Weighted Subgraph With the Required Paths", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1 . You are also given a 2D integer array edges where edges[i] = [from i , to i , weight i ] denotes that there exists a directed edge from from i to to i with weight weight i . Lastly, you are given three distinct integers src1 , src2 , and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph . In case such a subgraph does not exist, return -1 . A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "0 <= edges.length <= 10^5", + "edges[i].length == 3", + "0 <= from i , to i , src1, src2, dest <= n - 1", + "from i != to i", + "src1 , src2 , and dest are pairwise distinct.", + "1 <= weight[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5\nOutput:9\nExplanation:The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example1drawio.png" + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2\nOutput:-1\nExplanation:The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example2-1drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumWeight(self, n, edges, s1, s2, dest):\n G1 = defaultdict(list)\n G2 = defaultdict(list)\n for a, b, w in edges:\n G1[a].append((b, w))\n G2[b].append((a, w))\n\n def Dijkstra(graph, K):\n q, t = [(0, K)], {}\n while q:\n time, node = heappop(q)\n if node not in t:\n t[node] = time\n for v, w in graph[node]:\n heappush(q, (time + w, v))\n return [t.get(i, float(\"inf\")) for i in range(n)]\n \n arr1 = Dijkstra(G1, s1)\n arr2 = Dijkstra(G1, s2)\n arr3 = Dijkstra(G2, dest)\n \n ans = float(\"inf\")\n for i in range(n):\n ans = min(ans, arr1[i] + arr2[i] + arr3[i])\n \n return ans if ans != float(\"inf\") else -1\n", + "title": "2203. Minimum Weighted Subgraph With the Required Paths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string floor , which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen . You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum . Carpets may overlap one another. Return the minimum number of white tiles still visible.", + "description_images": [], + "constraints": [ + "floor[i] = '0' denotes that the i th tile of the floor is colored black .", + "On the other hand, floor[i] = '1' denotes that the i th tile of the floor is colored white ." + ], + "examples": [ + { + "text": "Example 1: Input:floor = \"10110101\", numCarpets = 2, carpetLen = 2\nOutput:2\nExplanation:The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex1-1.png" + }, + { + "text": "Example 2: Input:floor = \"11111\", numCarpets = 2, carpetLen = 3\nOutput:0\nExplanation:The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n Map cache;\n \n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n cache = new HashMap<>();\n return helper(floor, 0, numCarpets, carpetLen);\n }\n \n public int helper(String floor, int position, int numCarpets, int carpetLen) {\n if (position >= floor.length()) {\n return 0;\n }\n \n if (floor.length() - position <= numCarpets * carpetLen) {\n return 0;\n }\n \n String key = position + \", \" + numCarpets;\n if (cache.containsKey(key)) {\n return cache.get(key);\n }\n \n if (numCarpets == 0) {\n int output = floor.charAt(position) - '0' + helper(floor, position + 1, 0, carpetLen);\n \n cache.put(key, output);\n return output;\n }\n \n int output = Math.min(floor.charAt(position) - '0' + helper(floor, position + 1, numCarpets, carpetLen), helper(floor, position + carpetLen, numCarpets - 1, carpetLen));\n \n cache.put(key, output);\n return output;\n }\n}\n", + "title": "2209. Minimum White Tiles After Covering With Carpets", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed binary string floor , which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen . You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum . Carpets may overlap one another. Return the minimum number of white tiles still visible.", + "description_images": [], + "constraints": [ + "floor[i] = '0' denotes that the i th tile of the floor is colored black .", + "On the other hand, floor[i] = '1' denotes that the i th tile of the floor is colored white ." + ], + "examples": [ + { + "text": "Example 1: Input:floor = \"10110101\", numCarpets = 2, carpetLen = 2\nOutput:2\nExplanation:The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex1-1.png" + }, + { + "text": "Example 2: Input:floor = \"11111\", numCarpets = 2, carpetLen = 3\nOutput:0\nExplanation:The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n\t\tn = len(floor)\n\t\t#Using memo table to store predefined computations\n memo = [[-1 for x in range(numCarpets+1)] for x in range(len(floor)+1)] \n def solve(N,numCarpets):\n\t\t\t#Base Case\n if N>=n:\n return 0\n\t\t\t#If calculated previously use that solution\n if memo[N][numCarpets]!=-1:\n return memo[N][numCarpets]\n\t\t\t\t\n used = 0 # If you use the carpet\n notused = 0 # If you donot use the carpet\n\t\t\t\n if floor[N]=='1': # We might use the carpet in this part\n if numCarpets>0: #Whether we even have some carpets or not\n\t\t\t\t \"\"\"\n\t\t\t\t\tOptimization Part\n\t\t\t\t\tWe are finding the number of ones present in this part of the floor.\n\t\t\t\t\tprefix[lastInd] - Number of ones till lastInd\n\t\t\t\t\tprefix[N] - Number of ones till Nth Index.\n\t\t\t\t\t\n\t\t\t\t\tTheir difference gives us how many ones present between the two.\n\t\t\t\t \"\"\"\n lastInd = min(N+carpetLen,len(floor)) \n ans = prefix[lastInd] - prefix[N]\n \n\t\t\t\t\t\"\"\"\n\t\t\t\t\tFind the max if we use or donot use carpet at this index\n\t\t\t\t\tIf we do we add --- ans and decrement remaining carpets\n\t\t\t\t\telse we donot\n\t\t\t\t\t\"\"\"\n used = max(solve(N+carpetLen,numCarpets-1)+ans,solve(N+1,numCarpets))\n \n else:\n used = 0\n \n else:\n\t\t\t#If we donot use the carpet although I feel this might be redundant code\n notused = solve(N+1,numCarpets)\n \n\t\t\t#Using max function to find the number of white tiles removed\n memo[N][numCarpets] = max(used,notused)\n return memo[N][numCarpets]\n\t\t\n\t\t#Total White tiles\n ones = 0\n for x in floor:\n if x == '1':\n ones+=1\n \n\t\t#Using Prefix array to store number of ones till i th index\n prefix = [0]*(n+1)\n for i in range(1,n+1):\n if floor[i-1]=='1':\n prefix[i] = prefix[i-1]+1\n else:\n prefix[i] = prefix[i-1]\n\t\t\t\t\n \n removed = solve(0,numCarpets)\n \n return ones-removed\n", + "title": "2209. Minimum White Tiles After Covering With Carpets", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 . A substring is a contiguous sequence of characters within the string.", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"\nOutput:\"BANC\"\nExplanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"\nOutput:\"a\"\nExplanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"\nOutput:\"\"\nExplanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 16.21%) | Memory: 43.4 MB (Top 87.12%)\nclass Solution {\n public String minWindow(String s, String t) {\n HashMap child = new HashMap<>();\n HashMap parent = new HashMap<>();\n\n int left = -1, right = -1, match = 0;\n String window = \"\";\n\n for(int i = 0; i < t.length(); i++){\n char c = t.charAt(i);\n child.put(c, child.getOrDefault(c, 0) + 1); //Child frequency map\n }\n\n while(true){\n boolean f1 = false, f2 = false;\n\n while(right < s.length() - 1 && match < t.length()){\n right++;\n char c = s.charAt(right);\n parent.put(c, parent.getOrDefault(c, 0) + 1); // Acquiring characters till\n if(parent.getOrDefault(c, 0) <= child.getOrDefault(c, 0)) // match count is equal\n match++;\n\n f1 = true;\n }\n while(left < right && match == t.length()){\n String potstring = s.substring(left + 1, right + 1);\n if(window.length() == 0 || window.length() > potstring.length())\n window = potstring; //Calculating length of window\n\n left++;\n char c = s.charAt(left);\n parent.put(c, parent.getOrDefault(c, 0) - 1);\n if(parent.get(c) == 0) //Releasing characters by\n parent.remove(c); //left pointer for finding smallest window\n\n if(parent.getOrDefault(c, 0) < child.getOrDefault(c, 0))\n match--;\n\n f2 = true;\n }\n\n if(f1 == false && f2 == false)\n break;\n }\n\n return window;\n }\n}", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . A substring is a contiguous sequence of characters within the string.", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"\nOutput:\"BANC\"\nExplanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"\nOutput:\"a\"\nExplanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"\nOutput:\"\"\nExplanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "# Added on 2022-08-18 15:51:55.963915\n\nvar minWindow = function(s, t) {\n const tf = {}, sf = {};\n for(let c of t) {\n tf[c] = (tf[c] || 0) + 1;\n }\n let l = 0, r = 0, rs = t.length;\n let ml = -1, mr = -1;\n for(; r < s.length; r++) {\n const c = s[r];\n\n if(!tf[c]) continue;\n\n const sc = sf[c] || 0;\n sf[c] = sc + 1;\n if(sf[c] <= tf[c]) {\n rs--;\n }\n\n if(rs == 0) {\n while(true) {\n if(mr == -1 || mr - ml > r - l) {\n [mr, ml] = [r, l];\n }\n\n const c = s[l];\n if(!tf[c]) {\n l++;\n }\n else if(sf[c] - 1 < tf[c]) {\n sf[c]--, l++, rs++;\n break;\n } else {\n sf[c]--;\n l++;\n }\n }\n }\n }\n if(mr == -1) return '';\n return s.slice(ml, mr + 1);\n};", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 of length n . The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) ( 0-indexed ). Rearrange the elements of nums2 such that the resulting XOR sum is minimized . Return the XOR sum after the rearrangement .", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [2,3]\nOutput:2\nExplanation:Rearrangenums2so that it becomes[3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,0,3], nums2 = [5,3,4]\nOutput:8\nExplanation:Rearrangenums2so that it becomes[5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "\n\nclass Solution {\n Integer[][] cache;\n \n public int minimumXORSum(int[] nums1, int[] nums2) {\n int n = nums1.length;\n \n cache = new Integer[n][1 << n];\n\n return getMinXorSum(0, 0, nums1, nums2);\n }\n \n \n private int getMinXorSum(int index, int mask, int[] nums1, int[] nums2){\n if(index == nums1.length) return 0;\n \n //retrieve from cache\n if(cache[index][mask] != null) return cache[index][mask];\n \n //find minimum \n int minXorSum = Integer.MAX_VALUE;\n\n for(int i = 0; i < nums2.length; i++){\n if((mask >> i & 1) == 1) continue;\n \n int xorSum = (nums1[index] ^ nums2[i]) + getMinXorSum(index + 1, mask | (1 << i), nums1, nums2);\n \n //update minimum xor sum\n minXorSum = Math.min(xorSum, minXorSum);\n }\n \n //store in cache\n cache[index][mask] = minXorSum;\n \n return minXorSum;\n }\n \n}\n", + "title": "1879. Minimum XOR Sum of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 of length n . The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) ( 0-indexed ). Rearrange the elements of nums2 such that the resulting XOR sum is minimized . Return the XOR sum after the rearrangement .", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [2,3]\nOutput:2\nExplanation:Rearrangenums2so that it becomes[3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,0,3], nums2 = [5,3,4]\nOutput:8\nExplanation:Rearrangenums2so that it becomes[5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumXORSum(self, a: List[int], b: List[int]) -> int:\n @cache\n def dp(mask: int) -> int:\n i = bin(mask).count(\"1\")\n if i >= len(a):\n return 0\n return min((a[i] ^ b[j]) + dp(mask + (1 << j)) \n for j in range(len(b)) if mask & (1 << j) == 0)\n return dp(0)\n", + "title": "1879. Minimum XOR Sum of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0 , 1 , and 2 . The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0 th receptor. Given the two integers p and q , return the number of the receptor that the ray meets first . The test cases are guaranteed so that the ray will meet a receptor eventually.", + "description_images": [], + "constraints": [ + "1 <= q <= p <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:p = 2, q = 1\nOutput:2\nExplanation:The ray meets receptor 2 the first time it gets reflected back to the left wall.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png" + }, + { + "text": "Example 2: Input:p = 3, q = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution {\n public int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0){\n p >>= 1; q >>= 1;\n }\n return 1 - p % 2 + q % 2;\n }\n};\n", + "title": "858. Mirror Reflection", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0 , 1 , and 2 . The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0 th receptor. Given the two integers p and q , return the number of the receptor that the ray meets first . The test cases are guaranteed so that the ray will meet a receptor eventually.", + "description_images": [], + "constraints": [ + "1 <= q <= p <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:p = 2, q = 1\nOutput:2\nExplanation:The ray meets receptor 2 the first time it gets reflected back to the left wall.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png" + }, + { + "text": "Example 2: Input:p = 3, q = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n\n L = lcm(p,q)\n\n if (L//q)%2 == 0:\n return 2\n\n return (L//p)%2", + "title": "858. Mirror Reflection", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "0 <= nums[i] <= n", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,0,1]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 3: Input:nums = [9,6,4,2,3,5,7,0,1]\nOutput:8\nExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "// Approach 1: Find diff\n\nclass Solution {\n public int missingNumber(int[] nums) {\n int n = nums.length;\n int expectedSum = (n * (n + 1)) / 2;\n for (int num : nums)\n expectedSum -= num;\n return expectedSum;\n }\n}\n\n// Approach 2: XOR\nclass Solution {\n public int missingNumber(int[] nums) {\n int xor1 = 0;\n for (int i = 1; i <= nums.length; i++)\n xor1 = xor1 ^ i;\n\n int xor2 = 0;\n for (int num : nums)\n xor2 = xor2 ^ num;\n return xor1 ^ xor2;\n }\n}\n\n// Approach 3: Cyclic sort\nclass Solution {\n public int missingNumber(int[] nums) {\n \n int i = 0;\n while (i < nums.length) {\n\n if (nums[i] != i && nums[i] < nums.length)\n swap(i, nums[i], nums);\n else\n i += 1;\n }\n \n for (int j = 0; j < nums.length; j++) {\n if (nums[j] != j)\n return j;\n }\n return nums.length;\n }\n \n private void swap(int i, int j, int[] nums) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}\n", + "title": "268. Missing Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "0 <= nums[i] <= n", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,0,1]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 3: Input:nums = [9,6,4,2,3,5,7,0,1]\nOutput:8\nExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def missingNumber(self, nums: List[int]) -> int:\n # T.C = O(n) S.C = O(1)\n actualsum = 0\n currentsum = 0\n i = 1\n for num in nums:\n currentsum += num\n actualsum += i\n i += 1\n \n return actualsum - currentsum", + "title": "268. Missing Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y . Given an integer n , return the largest number that is less than or equal to n with monotone increasing digits .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:n = 1234\nOutput:1234", + "image": null + }, + { + "text": "Example 3: Input:n = 332\nOutput:299", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.5%) | Memory: 38.98 MB (Top 97.6%)\n\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int position;\n int digitInTheNextPosition;\n while ((position = getThePositionNotSatisfied(n)) != -1) {\n digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;\n n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);\n n -= n % Math.pow(10, position);\n n += Math.pow(10, position) - 1;\n }\n return n;\n }\n\n public int getThePositionNotSatisfied(int n) {\n int k = 10;\n int position = 0;\n while (n > 0) {\n if (k < n % 10) {\n return position;\n } else {\n k = n % 10;\n n /= 10;\n position++;\n }\n }\n return -1;\n }\n}", + "title": "738. Monotone Increasing Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y . Given an integer n , return the largest number that is less than or equal to n with monotone increasing digits .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:9", + "image": null + }, + { + "text": "Example 2: Input:n = 1234\nOutput:1234", + "image": null + }, + { + "text": "Example 3: Input:n = 332\nOutput:299", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 43 ms (Top 69.04%) | Memory: 13.9 MB (Top 20.57%)\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n num = list(str(n))\n for i in range(len(num)-1):\n # Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return\n # However, there is the case that num[i-1]==num[i], which will make num[i]-1 num[i+1]:\n while i >= 1 and num[i-1] == num[i]:\n i -= 1\n num[i] = chr(ord(num[i])-1)\n return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))\n return n", + "title": "738. Monotone Increasing Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j , nums[i] <= nums[j] . An array nums is monotone decreasing if for all i <= j , nums[i] >= nums[j] . Given an integer array nums , return true if the given array is monotonic, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,4]\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,2]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 51.45%) | Memory: 92.5 MB (Top 78.69%)\nclass Solution {\n public boolean isMonotonic(int[] nums) {\n if(nums[0]=nums[i+1])) return false;\n }\n }\n return true;\n }\n}", + "title": "896. Monotonic Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j , nums[i] <= nums[j] . An array nums is monotone decreasing if for all i <= j , nums[i] >= nums[j] . Given an integer array nums , return true if the given array is monotonic, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,4]\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,2]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] >= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] <= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n return False\n", + "title": "896. Monotonic Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array items where items[i] = [price i , beauty i ] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries . For each queries[j] , you want to determine the maximum beauty of an item whose price is less than or equal to queries[j] . If no such item exists, then the answer to this query is 0 . Return an array answer of the same length as queries where answer[j] is the answer to the j th query .", + "description_images": [], + "constraints": [ + "1 <= items.length, queries.length <= 10^5", + "items[i].length == 2", + "1 <= price i , beauty i , queries[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]\nOutput:[2,4,5,5,6,6]\nExplanation:- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.", + "image": null + }, + { + "text": "Example 2: Input:items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]\nOutput:[4]\nExplanation:The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty.", + "image": null + }, + { + "text": "Example 3: Input:items = [[10,1000]], queries = [5]\nOutput:[0]\nExplanation:No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maximumBeauty(int[][] items, int[] queries) {\n int[] ans = new int[queries.length];\n Arrays.sort(items, (a, b) -> (a[0] - b[0]));\n int maxBeautySoFar = Integer.MIN_VALUE;\n int[] maxBeauty = new int[items.length];\n \n for(int i = 0; i < items.length; i++) {\n if(maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];\n maxBeauty[i] = maxBeautySoFar;\n }\n \n for(int i = 0; i < queries.length; i++) {\n int idx = findLargestIdxWithPriceLessThan(items, queries[i]);\n if(idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];\n }\n return ans;\n }\n \n public int findLargestIdxWithPriceLessThan(int[][] items, int price) {\n int l = 0;\n int r = items.length - 1;\n int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE; \n while(l <= r) {\n int mid = (l + r)/2;\n if(items[mid][0] > price) {\n r = mid - 1;\n } else {\n maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);\n l = mid + 1;\n }\n }\n return maxIdxLessThanEqualToPrice;\n }\n}", + "title": "2070. Most Beautiful Item for Each Query", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array items where items[i] = [price i , beauty i ] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries . For each queries[j] , you want to determine the maximum beauty of an item whose price is less than or equal to queries[j] . If no such item exists, then the answer to this query is 0 . Return an array answer of the same length as queries where answer[j] is the answer to the j th query .", + "description_images": [], + "constraints": [ + "1 <= items.length, queries.length <= 10^5", + "items[i].length == 2", + "1 <= price i , beauty i , queries[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]\nOutput:[2,4,5,5,6,6]\nExplanation:- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.", + "image": null + }, + { + "text": "Example 2: Input:items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]\nOutput:[4]\nExplanation:The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty.", + "image": null + }, + { + "text": "Example 3: Input:items = [[10,1000]], queries = [5]\nOutput:[0]\nExplanation:No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2544 ms (Top 32.35%) | Memory: 73.6 MB (Top 48.94%)\nclass Solution:\n def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n\n items.sort()\n dic = dict()\n res = []\n gmax = 0\n for p,b in items:\n gmax = max(b,gmax)\n dic[p] = gmax\n\n keys = sorted(dic.keys())\n for q in queries:\n ind = bisect.bisect_left(keys,q)\n if ind hm = new HashMap<>();\n String[] words = paragraph.replaceAll(\"[!?',;.]\",\" \").toLowerCase().split(\"\\\\s+\");\n for(int i=0; i str:\n #sunday morning hangover solution haha\n \n #calling this twice seems unnecesary but whatevs\n #replace \",\" with \" \" (apparently translate() is much quicker than replace)\n para = paragraph.translate(str.maketrans(\",\",\" \"))\n #strip out rest of punctuation and make it lower case\n para = para.translate(str.maketrans(' ', ' ', string.punctuation)).lower()\n #split on the sapces\n para = para.split()\n #staple counter function\n para_count = Counter(para)\n #loop thru banned words, if they're in para_count pop the off\n for word in banned:\n if word in para_count:\n para_count.pop(word)\n #return val from most common\n return para_count.most_common(1)[0][0]\n", + "title": "819. Most Common Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . You are also given an integer key , which is present in nums . For every unique integer target in nums , count the number of times target immediately follows an occurrence of key in nums . In other words, count the number of indices i such that: Return the target with the maximum count . The test cases will be generated such that the target with maximum count is unique.", + "description_images": [], + "constraints": [ + "0 <= i <= nums.length - 2 ,", + "nums[i] == key and,", + "nums[i + 1] == target ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,100,200,1,100], key = 1\nOutput:100\nExplanation:For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,3], key = 2\nOutput:2\nExplanation:For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 55.1%) | Memory: 43.05 MB (Top 60.9%)\n\nclass Solution {\n public int mostFrequent(int[] nums, int key) {\n int n=nums.length;\n HashMap map=new HashMap<>();\n for(int i=0;imax){\n re=x;\n max=map.get(x);\n }\n }\n return re;\n }\n}", + "title": "2190. Most Frequent Number Following Key In an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums . You are also given an integer key , which is present in nums . For every unique integer target in nums , count the number of times target immediately follows an occurrence of key in nums . In other words, count the number of indices i such that: Return the target with the maximum count . The test cases will be generated such that the target with maximum count is unique.", + "description_images": [], + "constraints": [ + "0 <= i <= nums.length - 2 ,", + "nums[i] == key and,", + "nums[i + 1] == target ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,100,200,1,100], key = 1\nOutput:100\nExplanation:For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,3], key = 2\nOutput:2\nExplanation:For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 90 ms (Top 49.1%) | Memory: 16.67 MB (Top 9.2%)\n\nclass Solution:\n def mostFrequent(self, nums: List[int], key: int) -> int:\n l = [t for k,t in zip(nums, nums[1:]) if k == key]\n return max(set(l), key = l.count)", + "title": "2190. Most Frequent Number Following Key In an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the most frequent subtree sum . If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,2,-3]\nOutput:[2,-3,4]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,2,-5]\nOutput:[2]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 14.50%) | Memory: 44.9 MB (Top 83.15%)\nclass Solution {\n public int[] findFrequentTreeSum(TreeNode root) {\n\n HashMap map=new HashMap<>();\n int sum=sum(root,map);\n int max=0;\n int count=0;\n for(Integer key:map.keySet()){\n max=Math.max(max,map.get(key));\n }\n\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n count++;\n }\n }\n int[] ans=new int[count];\n int counter=0;\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n ans[counter++]=key;\n }\n }\n\n return ans;\n\n }\n public int sum(TreeNode root,HashMap map){\n if(root==null)return 0;\n int lh=sum(root.left,map);\n int rh=sum(root.right,map);\n map.put(lh+rh+root.val,map.getOrDefault(lh+rh+root.val,0)+1);\n return lh+rh+root.val;\n }\n}", + "title": "508. Most Frequent Subtree Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the most frequent subtree sum . If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,2,-3]\nOutput:[2,-3,4]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,2,-5]\nOutput:[2]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n def dfs(root):\n \n if not root: return 0\n \n l = dfs(root.left)\n r = dfs(root.right)\n res = root.val + l + r\n \n d[res] += 1\n return res\n \n d = collections.Counter()\n dfs(root)\n maxi = max(d.values())\n return [i for i in d if d[i] == maxi]\n \n\t\t# An Upvote will be encouraging\n \n \n", + "title": "508. Most Frequent Subtree Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n jobs and m workers. You are given three arrays: difficulty , profit , and worker where: Every worker can be assigned at most one job , but one job can be completed multiple times . Return the maximum profit we can achieve after assigning the workers to the jobs.", + "description_images": [], + "constraints": [ + "difficulty[i] and profit[i] are the difficulty and the profit of the i th job, and", + "worker[j] is the ability of j th worker (i.e., the j th worker can only complete a job with difficulty at most worker[j] )." + ], + "examples": [ + { + "text": "Example 1: Input:difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput:100\nExplanation:Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.", + "image": null + }, + { + "text": "Example 2: Input:difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 67 ms (Top 34.79%) | Memory: 60.8 MB (Top 55.99%)\nclass Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(b[1]-a[1]));\n for(int i=0;i=0 && !pq.isEmpty();i--)\n {\n if(worker[i]>=pq.peek()[0])\n p=p+pq.peek()[1];\n else\n {\n while(!pq.isEmpty() && worker[i] O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans", + "title": "826. Most Profit Assigning Work", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [x i , y i ] represents the location of the i th stone, return the largest possible number of stones that can be removed .", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 1000", + "0 <= x i , y i <= 10^4", + "No two stones are at the same coordinate point." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput:5\nExplanation:One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 2: Input:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput:3\nExplanation:One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 3: Input:stones = [[0,0]]\nOutput:0\nExplanation:[0,0] is the only stone on the plane, so you cannot remove it.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 33.32%) | Memory: 48.7 MB (Top 77.91%)\nclass Solution {\n public int removeStones(int[][] stones) {\n int ret=0;\n DisjointSet ds=new DisjointSet(stones.length);\n\n for(int i=0;ireturn size in negative\n public int union(int idx1, int idx2) {\n int p1=find(idx1);\n int p2=find(idx2);\n\n if(p1==p2) { //same parent so directly returning size\n return sets[p1];\n }else {\n int w1=Math.abs(sets[p1]);\n int w2=Math.abs(sets[p2]);\n\n if(w1>w2) {\n sets[p2]=p1;\n\n //collapsing FIND\n sets[idx1]=p1;\n sets[idx2]=p1;\n\n return sets[p1]=-(w1+w2);\n }else {\n sets[p1]=p2;\n\n //collapsing FIND\n sets[idx1]=p2;\n sets[idx2]=p2;\n\n return sets[p2]=-(w1+w2);\n }\n }\n }\n\n // collapsing FIND\n //find parent\n public int find(int idx) {\n int p=idx;\n while(sets[p]>=0) {\n p=sets[p];\n }\n return p;\n }\n }\n}", + "title": "947. Most Stones Removed with Same Row or Column", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [x i , y i ] represents the location of the i th stone, return the largest possible number of stones that can be removed .", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 1000", + "0 <= x i , y i <= 10^4", + "No two stones are at the same coordinate point." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput:5\nExplanation:One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 2: Input:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput:3\nExplanation:One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 3: Input:stones = [[0,0]]\nOutput:0\nExplanation:[0,0] is the only stone on the plane, so you cannot remove it.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 187 ms (Top 84.32%) | Memory: 18.9 MB (Top 5.06%)\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n def dfs(row,col):\n if seen[(row,col)]:\n return 0\n seen[(row,col)] = True\n for r,c in tableRow[row]:\n dfs(r,c)\n for r,c in tableCol[col]:\n dfs(r,c)\n return 1\n\n tableRow, tableCol = {},{}\n for row,col in stones:\n if row not in tableRow:\n tableRow[row] = set()\n if col not in tableCol:\n tableCol[col] = set()\n tableRow[row].add((row,col))\n tableCol[col].add((row,col))\n\n count,seen= 0, {(row,col):False for row,col in stones}\n for row,col in stones:\n count += dfs(row,col)\n return abs(len(stones)-count)", + "title": "947. Most Stones Removed with Same Row or Column", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n and an integer array rounds . We have a circular track which consists of n sectors labeled from 1 to n . A marathon will be held on this track, the marathon consists of m rounds. The i th round starts at sector rounds[i - 1] and ends at sector rounds[i] . For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= m <= 100", + "rounds.length == m + 1", + "1 <= rounds[i] <= n", + "rounds[i] != rounds[i + 1] for 0 <= i < m" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, rounds = [1,3,1,2]\nOutput:[1,2]\nExplanation:The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/tmp.jpg" + }, + { + "text": "Example 2: Input:n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput:[2]", + "image": null + }, + { + "text": "Example 3: Input:n = 7, rounds = [1,3,5,7]\nOutput:[1,2,3,4,5,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.10 MB (Top 12.5%)\n\nclass Solution {\n public List mostVisited(int n, int[] rounds) {\n var start = rounds[0];\n var end = rounds[rounds.length - 1]; \n var res = new ArrayList();\n if (start <= end) {\n for (int i = start; i <= end; i++) res.add(i);\n } else {\n for (int i = 1; i <= end; i++) res.add(i);\n for (int i = start; i <= n; i++) res.add(i);\n }\n return res;\n }\n}\n", + "title": "1560. Most Visited Sector in a Circular Track", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer n and an integer array rounds . We have a circular track which consists of n sectors labeled from 1 to n . A marathon will be held on this track, the marathon consists of m rounds. The i th round starts at sector rounds[i - 1] and ends at sector rounds[i] . For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= m <= 100", + "rounds.length == m + 1", + "1 <= rounds[i] <= n", + "rounds[i] != rounds[i + 1] for 0 <= i < m" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, rounds = [1,3,1,2]\nOutput:[1,2]\nExplanation:The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/tmp.jpg" + }, + { + "text": "Example 2: Input:n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput:[2]", + "image": null + }, + { + "text": "Example 3: Input:n = 7, rounds = [1,3,5,7]\nOutput:[1,2,3,4,5,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n hash_map = {}\n for i in range(0 , len(rounds)-1):\n if i == 0:\n start = rounds[i]\n elif rounds[i] == n:\n start = 1\n else:\n start = rounds[i] + 1\n end = rounds[i+1]\n if start <= end:\n for i in range(start , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n else:\n for i in range(start , n + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n for i in range(1 , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n k = list(hash_map.keys())\n v = list(hash_map.values())\n ans = []\n m = -1\n i = 0\n j = 0\n while i < len(k) and j < len(v):\n if len(ans) == 0:\n ans.append(k[i])\n m = v[j]\n elif m < v[j]:\n ans = []\n ans.append(k[i])\n m = v[j]\n elif m == v[j]:\n ans.append(k[i])\n i += 1\n j += 1\n ans = sorted(ans)\n return ans\n\n", + "title": "1560. Most Visited Sector in a Circular Track", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings start and target , both of length n . Each string consists only of the characters 'L' , 'R' , and '_' where: Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times . Otherwise, return false .", + "description_images": [], + "constraints": [ + "The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.", + "The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"_L__R__R_\", target = \"L______RR\"\nOutput:true\nExplanation:We can obtain the string target from start by doing the following moves:\n- Move the first piece one step to the left, start becomes equal to \"L___R__R_\".\n- Move the last piece one step to the right, start becomes equal to \"L___R___R\".\n- Move the second piece three steps to the right, start becomes equal to \"L______RR\".\nSince it is possible to get the string target from start, we return true.", + "image": null + }, + { + "text": "Example 2: Input:start = \"R_L_\", target = \"__LR\"\nOutput:false\nExplanation:The 'R' piece in the string start can move one step to the right to obtain \"_RL_\".\nAfter that, no pieces can move anymore, so it is impossible to obtain the string target from start.", + "image": null + }, + { + "text": "Example 3: Input:start = \"_R\", target = \"R_\"\nOutput:false\nExplanation:The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 303 ms (Top 21.43%) | Memory: 21.30 MB (Top 33.04%)\n\nclass Solution:\n def canChange(self, A: str, B: str) -> bool:\n P = lambda c : c != '_'\n I = lambda s,x : [i for i,c in enumerate(s) if c==x]\n G = lambda d,p : all( p(x,y) for x,y in zip( I(A,d), I(B,d) ) )\n S = lambda : [*filter(P,A)] == [*filter(P,B)]\n return S() and G('L', ge) and G('R', le)\n\t\t# 1. 2. 3.\n", + "title": "2337. Move Pieces to Obtain a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , move all 0 's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,3,12]\nOutput:[1,3,12,0,0]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 46.20 MB (Top 23.08%)\n\nclass Solution {\n public void moveZeroes(int[] nums) {\n int i = 0; \n for (int num:nums){\n if(num != 0){\n nums[i] = num;\n i++;\n }\n }\n while(i None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n\n \"\"\"\n notzero = 0\n zero = 0\n\n while notzero < len(nums):\n if nums[notzero] != 0:\n nums[zero] , nums[notzero] = nums[notzero], nums[zero]\n zero += 1\n notzero += 1", + "title": "283. Move Zeroes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are three stones in different positions on the X-axis. You are given three integers a , b , and c , the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x , y , and z with x < y < z . You pick up the stone at either position x or position z , and move that stone to an integer position k , with x < k < z and k != y . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where :", + "description_images": [], + "constraints": [ + "answer[0] is the minimum number of moves you can play, and", + "answer[1] is the maximum number of moves you can play ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2, c = 5\nOutput:[1,2]\nExplanation:Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 3, c = 2\nOutput:[0,0]\nExplanation:We cannot make any moves.", + "image": null + }, + { + "text": "Example 3: Input:a = 3, b = 5, c = 1\nOutput:[1,2]\nExplanation:Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.75%) | Memory: 41.9 MB (Top 57.50%)\nclass Solution {\n public int[] numMovesStones(int a, int b, int c) {\n int[] arr ={a,b,c};\n int[] arr2 = {a,b,c};\n int maximum = findMaximum(arr);\n int minimum = findMinimum(maximum,arr2);\n return new int[]{minimum,maximum};\n }\n public int findMaximum(int[] arr){\n Arrays.sort(arr);\n int count = 0;\n if(arr[0] == (arr[1]-1) && arr[1] == (arr[2] -1) ) return count;\n if(arr[0] == arr[1]-1){\n arr[2]--;\n count++;\n }\n else{\n arr[0]++;\n count++;\n }\n return count + findMaximum(arr);\n\n }\n\n public int findMinimum(int max,int[] arr){\n Arrays.sort(arr);\n if(max == 0) return 0;\n else if(Math.abs(arr[0]-arr[1]) >2 && Math.abs(arr[1]-arr[2]) >2 ) return 2;\n else return 1;\n }\n}", + "title": "1033. Moving Stones Until Consecutive", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are three stones in different positions on the X-axis. You are given three integers a , b , and c , the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x , y , and z with x < y < z . You pick up the stone at either position x or position z , and move that stone to an integer position k , with x < k < z and k != y . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where :", + "description_images": [], + "constraints": [ + "answer[0] is the minimum number of moves you can play, and", + "answer[1] is the maximum number of moves you can play ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2, c = 5\nOutput:[1,2]\nExplanation:Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 3, c = 2\nOutput:[0,0]\nExplanation:We cannot make any moves.", + "image": null + }, + { + "text": "Example 3: Input:a = 3, b = 5, c = 1\nOutput:[1,2]\nExplanation:Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a,b,c = sorted([a,b,c])\n d1 = abs(b-a)-1 \n d2 = abs(c-b)-1\n mi = 2\n if d1 == 0 and d2 == 0: mi = 0\n elif d1 <= 1 or d2 <= 1: mi =1 \n ma = c - a - 2\n return [mi,ma]", + "title": "1033. Moving Stones Until Consecutive", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are some stones in different positions on the X-axis. You are given an integer array stones , the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where :", + "description_images": [], + "constraints": [ + "In particular, if the stones are at say, stones = [1,2,5] , you cannot move the endpoint stone at position 5 , since moving it to any position (such as 0 , or 3 ) will still keep that stone as an endpoint stone." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [7,4,9]\nOutput:[1,2]\nExplanation:We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [6,5,4,3,10]\nOutput:[2,3]\nExplanation:We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass Solution {\n\t\tpublic int[] numMovesStonesII(int[] stones) {\n\t\t\tint n = stones.length;\n\t\t\t int[] ans = new int[2];\n\t\t\t int i = 0, j = 0, wsize, scount, minMoves = Integer.MAX_VALUE;\n\t\t\tArrays.sort(stones);\n\t\t\t while (j < n) {\n\t\t\t\twsize = stones[j] - stones[i] + 1;\n\t\t\t\tscount = j - i + 1;\n\n\t\t\t\tif (wsize > n) {\n\t\t\t\t\ti++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (wsize == n - 1 && scount == n - 1)\n\t\t\t\t\tminMoves = Math.min(minMoves, 2);\n\n\t\t\t\telse minMoves = Math.min(minMoves, n - scount);\n\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tans[0] = minMoves;\n\t\t\tint maxMoves = 0;\n\t\t\t if (stones[1] == stones[0] + 1 || stones[n - 1] == stones[n - 2] + 1)\n\t\t\t\tmaxMoves = stones[n - 1] - stones[0] + 1 - n;\n\t\t\telse \n\t\t\t\tmaxMoves = Math.max(((stones[n - 1] - stones[1]) - (n - 1) + 1), ((stones[n - 2] - stones[0]) - (n - 1) + 1));\n\n\t\t\tans[1] = maxMoves;\n\t\t\treturn ans;\n\t\t}\n\t}", + "title": "1040. Moving Stones Until Consecutive II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are some stones in different positions on the X-axis. You are given an integer array stones , the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where :", + "description_images": [], + "constraints": [ + "In particular, if the stones are at say, stones = [1,2,5] , you cannot move the endpoint stone at position 5 , since moving it to any position (such as 0 , or 3 ) will still keep that stone as an endpoint stone." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [7,4,9]\nOutput:[1,2]\nExplanation:We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [6,5,4,3,10]\nOutput:[2,3]\nExplanation:We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 85.48%) | Memory: 18.80 MB (Top 11.29%)\n\nclass Solution:\n '''\n Test cases walk through \n Given 7, 4, 9 prove 1, 2 6, 5, 4, 3, 10, prove 2, 3 \n\n Sort stones -> 4, 7, 9 3, 4, 5, 6, 10 \n Stone length -> 3 5\n Move penultimate = 7 - 4 - 3 + 2 = 2 6-3-5+2 = 0 \n Move final = 9 - 7 - 3 + 2 = 1 10-4-5+2 = 3 \n Neither is 0, so we cannot return for sure Move penultimate is 0, so move final is assured \n This means we can return [min(2, 3), 3] -> [2, 3]\n\n Max legal moves is 0 For completeness, max legal moves is 0, max moves is 3 \n starting index is 0 starting index is 0 \n\n Enumeration Enumeration\n index is 0, stone is 4 index is 0, stone is 3 \n stones[0] lte 4 - 3 ? No, skip while loop stones[0] lte 3 - 5 ? No, skip while \n max legal moves is min of (max of self and 0 - 0 + 1, most moves) max legal moves is min of (max of self and 0 - 0 + 1), max moves -> max legal moves is 1 \n -> max legal moves is 1 \n\n index is 1, stone is 7 index is 1, stone is 4 \n stones[0] <= 7 - 3 ? Yes, enter while stones[0] lte 4 - 5 ? No, skip while \n starting index is now 1 max legal moves is min of (max of self and 1 - 0 + 1), max moves -> max legal moves is 2\n stones[1] <= 7 - 3 ? No, skip while \n max legal moves -> min(max of self and 1 - 1 + 1), max_moves \n -> max legal moves is 1 index is 2, stone is 5 \n stones[0] lte 5 - 5 ? No skip while \n index is 2, stone is 9 max legal moves is min of (max of self and 2 - 0 + 1), max_moves -> max legal moves is 3 \n stones[1] <= 9 - 3 ? No, skip while \n max legal moves is min(max of self and 2-1 + 1), max_moves\n -> max legal moves is 2 index is 3, stone is 6 \n End enumeration stones[0] lte 6 - 5 ? No skip while \n max legal moves is min (max of self and 3 - 0 + 1), max_moves -> max legal moves is 3 \n Return [3 - 2, 2] -> [1, 2] checks out \n index is 4, stones is 10 \n stones[0] lte 10 - 5 ? Yes, enter while \n starting index is 1 \n stones[1] lte 10 - 5 ? Yes, enter while \n starting index is 2 \n stones[2] lte 10 - 5 ? Yes, enter while \n starting index is 3 \n max legal moves is min (max of self and 4 - 3 + 1), max moves -> max legal moves is 3 \n End enumeration\n\n Return [5 - 3, 3] -> [2, 3]\n '''\n def numMovesStonesII(self, stones: List[int]) -> List[int] :\n # order does not need to be maintained, so sorting is optimal \n stones.sort()\n # want to work within stone physical space since 10^9 >> 10^4 (stone weight vs length)\n stone_length = len(stones)\n # what is the cost of moving the second to last stone and the 0th stone? \n move_penultimate = stones[-2] - stones[0] - stone_length + 2 \n # what is the cost of moving the last stone and the 1st stone? \n move_final = stones[-1] - stones[1] - stone_length + 2 \n # in both of these, the cost is the positional exchange in stones along the stone length + 2 for the two stones moving \n # our most moves possible are the max of these two \n most_moves = max(move_penultimate, move_final)\n # since the stones are unique, if either is 0, the one that we have must be max legal moves \n # if move penultimate is 0, that means that the second largest stone less the least stone less the length + 2 is 0 \n # this means that the largest stone, which must be at least one larger than the largest, less the second to least stone which is at least one larger than the least stone less the length + 2 is move final \n # our minimal length is 3 \n # let a, b, c be stones in order \n # b - a - 3 + 2 = 0 -> b = a + 1 move penultimate \n # c - b - 3 + 2 = 0 -> b = c - 1 move final \n # c - 1 = a + 1 -> c = a + 2 \n # all stones must be at least 1 to 10^9 and are unique \n # so at minimum a is 1, b is 2 and c is 3 \n # in this case, move final is also 0 so we get 0, 0 \n # if a = 4, b = 5, c = 7 \n # 5 - 4 - 3 + 2 = 0 move penultimate is 0 \n # 7 - 5 - 3 + 2 -> 1 move ultimate is 1 \n # min legal moves is min of 2 and 1 -> min legal moves is 1 -> 1, 1 is returned \n # from this it can be seen that the movement of c relative to b impacts the return here when one is 0, and that if either is 0 it does not preclude the other. However it does entail a relation to 2 as most that min could become \n # this is because if most moves is greater than 2, we could always do the move alternate that was 0 in two steps. This is what locks in to place the ability to use 2 here as the min argument. \n if move_penultimate == 0 or move_final == 0 : \n min_legal_moves = min(2, most_moves)\n return [min_legal_moves, most_moves]\n # how many legal moves are there in sorted order? \n max_legal_moves = 0 \n # starting from 0th index \n starting_index = 0\n # enumerate each stone and index \n for index, stone in enumerate(stones) :\n # while the stone at starting index is lte this stone minus stone length (cost of a move) \n while stones[starting_index] <= stone - stone_length : \n # increment \n starting_index += 1\n # max legal moves is then set to maxima of self and indexed difference with 1 for 0 based indexing \n max_legal_moves = min(max(max_legal_moves, index - starting_index + 1), most_moves) \n # return length - max legal moves when in sorted order (your minimal move state) and most moves in sorted order \n return [stone_length - max_legal_moves, most_moves]\n", + "title": "1040. Moving Stones Until Consecutive II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"2\", num2 = \"3\"\nOutput:\"6\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"123\", num2 = \"456\"\nOutput:\"56088\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 37.52%) | Memory: 44.4 MB (Top 28.50%)\nclass Solution {\n public String multiply(String num1, String num2) {\n if(num1.equals(\"0\") || num2.equals(\"0\"))\n return \"0\";\n int[] arr=new int[num1.length()+num2.length()];\n\n int index=0;\n for(int i=num1.length()-1;i>=0;i--)\n {\n int carry=0;\n int column=0;\n for(int j=num2.length()-1;j>=0;j--)\n {\n int a=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');\n int temp=(arr[index+column]+carry+a);\n arr[index+column]=temp%10;\n carry=temp/10;\n column++;\n }\n if(carry!=0)\n {\n arr[index+column]=carry;\n }\n index++;\n }\n String ans=\"\";\n index=arr.length-1;\n while(arr[index]==0)\n {\n index--;\n }\n for(int i=index;i>=0;i--)\n {\n ans+=arr[i];\n }\n return ans;\n }\n}", + "title": "43. Multiply Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"2\", num2 = \"3\"\nOutput:\"6\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"123\", num2 = \"456\"\nOutput:\"56088\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n def convertToInt(numStr):\n currNum = 0\n N = len(numStr)\n for i in range(N - 1, -1, -1):\n digit = ord(numStr[i]) - ord('0')\n currNum += pow(10, N-i-1) * digit\n \n return currNum\n \n n1 = convertToInt(num1)\n n2 = convertToInt(num2)\n return str(n1 * n2)\n \n", + "title": "43. Multiply Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking . A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendar class:", + "description_images": [], + "constraints": [ + "MyCalendar() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendar\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [15, 25], [20, 30]]Output[null, true, false, true]ExplanationMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCalendar(object):\n def __init__(self):\n self.booking = []\n\n def book(self, start, end):\n for i, j in self.booking:\n if i < end and start < j:\n return False\n self.booking.append((start, end))\n return True\n", + "title": "729. My Calendar I", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 191 ms (Top 41.18%) | Memory: 44.60 MB (Top 39.41%)\n\n/*\nAlgorithm:\n--------------------------------------------------------------\n1. Have a TreeMap where the keys are the dates and values \n to those keys are the number of active events occuring on\n that date. This will keep the dates sorted according to \n the keys.\n2. During booking for a new event [start, end), number of\n events occuring on the start date increases by one and \n same for the end date decreases by one. Hence modify the \n map accordingly.\n3. Calculate a running sum `sum` which holds the count of\n events currently running at that time. \n4. If `sum` becomes more than or equal to 3, then remove that \n event and return `False`\n5. If this does not occur then return `True`.\n--------------------------------------------------------------\n*/\n\nclass MyCalendarTwo {\n Map map;\n public MyCalendarTwo() {\n map = new TreeMap();\n }\n public boolean book(int start, int end) {\n map.put(start, map.getOrDefault(start, 0)+1);\n map.put(end, map.getOrDefault(end, 0)-1);\n int sum=0;\n for(int val : map.values()){\n sum += val;\n if(sum >= 3){\n map.put(start, map.get(start)-1);\n map.put(end, map.get(end)+1);\n if(map.get(start) == 0)\n map.remove(start);\n return false;\n }\n }\n return true;\n }\n}\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCalendarTwo {\n private List bookings;\n private List doubleBookings;\n \n public MyCalendarTwo() {\n bookings = new ArrayList<>();\n doubleBookings = new ArrayList<>();\n }\n \n \n public boolean book(int start, int end) {\n for(int[] b : doubleBookings)\n {\n\t\t//condition to check for the overlaping\n if(start < b[1] && end > b[0])\n return false;\n }\n \n for(int[] b : bookings)\n {\n if(start < b[1] && end > b[0]) {\n doubleBookings.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});\n }\n }\n bookings.add(new int[]{start, end});\n return true;\n }\n}\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 175 ms (Top 97.99%) | Memory: 17.50 MB (Top 58.54%)\n\nclass Node:\n def __init__(self, start, end, val):\n self.start = start\n self.end = end\n self.val = val\n self.left = None\n self.right = None\n \n def insertable(self, node):\n if node.end <= node.start:\n return True\n if node.end <= self.start:\n if not self.left:\n return True\n else:\n return self.left.insertable(node)\n elif node.start >= self.end:\n if not self.right:\n return True\n else:\n return self.right.insertable(node)\n else:\n if self.val == 1:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n if not self.left and not self.right:\n return True\n elif not self.left:\n return self.right.insertable(Node(rightS, rightE, 1))\n elif not self.right:\n return self.left.insertable(Node(leftS, leftE, 1))\n else:\n resL = self.left.insertable(Node(leftS, leftE, 1))\n resR = self.right.insertable(Node(rightS, rightE, 1))\n if resL and resR:\n return True\n return False\n else:\n return False\n\n def insert(self, node):\n if node.end <= node.start:\n return\n \n if node.end <= self.start:\n if not self.left:\n self.left = node\n else:\n self.left.insert(node)\n elif node.start >= self.end:\n if not self.right:\n self.right = node\n else:\n self.right.insert(node)\n else:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n self.val += 1\n self.start, self.end = leftE, rightS \n if not self.left and not self.right: \n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n elif not self.left:\n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right.insert(Node(rightS, rightE, 1))\n elif not self.right:\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n self.left.insert(Node(leftS, leftE, 1))\n else:\n self.left.insert(Node(leftS, leftE, 1))\n self.right.insert(Node(rightS, rightE, 1))\n return\n\n\nclass MyCalendarTwo:\n\n def __init__(self):\n self.root = None\n\n def book(self, start: int, end: int) -> bool:\n if not self.root:\n self.root = Node(start, end, 1)\n return True\n else:\n newNode = Node(start, end, 1)\n if self.root.insertable(newNode):\n self.root.insert(newNode)\n return True\n return False\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A k -booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) You are given some events [start, end) , after each given event, return an integer k representing the maximum k -booking between all the previous events. Implement the MyCalendarThree class:", + "description_images": [], + "constraints": [ + "MyCalendarThree() Initializes the object.", + "int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k -booking in the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, 1, 1, 2, 3, 3, 3]ExplanationMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\nmyCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 197 ms (Top 36.54%) | Memory: 54.3 MB (Top 59.44%)\nclass MyCalendarThree {\n\n TreeMap map;\n public MyCalendarThree() {\n map = new TreeMap<>();\n }\n\n public int book(int start, int end) {\n if(map.isEmpty()){\n map.put(start, 1);\n map.put(end,-1);\n return 1;\n }\n\n //upvote if you like the solution\n\n map.put(start, map.getOrDefault(start,0)+1);\n map.put(end, map.getOrDefault(end,0)-1);\n\n int res = 0;\n int sum = 0;\n for(Map.Entry e: map.entrySet()){\n sum += e.getValue();\n res = Math.max(res,sum);\n }\n\n return res;\n }\n}", + "title": "732. My Calendar III", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A k -booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) You are given some events [start, end) , after each given event, return an integer k representing the maximum k -booking between all the previous events. Implement the MyCalendarThree class:", + "description_images": [], + "constraints": [ + "MyCalendarThree() Initializes the object.", + "int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k -booking in the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, 1, 1, 2, 3, 3, 3]ExplanationMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\nmyCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass MyCalendarThree:\n\n def __init__(self):\n self.events = [] \n\n def book(self, start: int, end: int) -> int:\n L, R = 1, 0\n bisect.insort(self.events, (start, L))\n bisect.insort(self.events, (end, R))\n res = 0\n cnt = 0\n for _, state in self.events:\n #if an interval starts, increase the counter\n #othewise, decreas the counter\n cnt += 1 if state == L else -1\n res = max(res, cnt)\n return res", + "title": "732. My Calendar III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n-ary tree, return the level order 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).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> result= new ArrayList();\n public List> levelOrder(Node root) {\n if(root==null) return result;\n helper(root,0);\n return result;\n }\n \n private void helper(Node node,int level){\n if(result.size()<=level){\n result.add(new ArrayList());\n }\n result.get(level).add(node.val);\n for(Node child:node.children){\n helper(child,level+1);\n }\n \n }\n}\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n-ary tree, return the level order 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).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n self.d=defaultdict(list)\n def check(root,ind):\n self.d[ind].append(root.val)\n if root.children:\n for x in root.children:\n check(x,ind+1)\n if root==None:\n return []\n check(root,0)\n l=[]\n for x in sorted(self.d.keys()):\n l.append(self.d[x])\n return l\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n-ary tree, return the level order 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).", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n if not root:\n return []\n \n result = []\n level = [root]\n \n while level:\n current_level = []\n next_level = []\n \n for node in level:\n current_level.append(node.val)\n next_level += node.children\n \n result.append(current_level)\n level = next_level\n \n return result\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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)", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]\nOutput:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n List result = new ArrayList<>();\n public List postorder(Node root) {\n addNodes(root);\n return result;\n }\n \n void addNodes(Node root) {\n if (root == null) return;\n for (Node child : root.children) addNodes(child);\n result.add(root.val);\n }\n}\n", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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)", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]\nOutput:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n ans=[]\n def post(root):\n nonlocal ans\n if not root:\n return\n for i in root.children:\n post(i)\n ans.append(root.val)\n post(root)\n return ans\n", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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)", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]\nOutput:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n\tdef postorder(self, root):\n\t\t\"\"\"\n\t\t:type root: Node\n\t\t:rtype: List[int]\n\t\t\"\"\"\n\t\tres=[]\n\t\tdef bfs(root):\n\t\t\tif root:\n\t\t\t\tfor child in root.children:\n\t\t\t\t\tbfs(child)\n\n\t\t\t\tres.append(root.val)\n\t\tbfs(root)\n\n\t\treturn res", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of an n-ary tree, return the preorder 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)", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[1,3,5,6,2,4]", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List preorder(Node root) {\n if (root == null) return new ArrayList();\n \n Stack stk = new Stack();\n ArrayList arr = new ArrayList();\n stk.push(root);\n Node ref;\n while(!stk.empty()) {\n ref = stk.pop();\n // System.out.println(ref.val);\n arr.add(ref.val);\n for(int i=ref.children.size() - 1;i>=0;i--) {\n stk.push(ref.children.get(i));\n }\n }\n return arr;\n }\n}\n", + "title": "589. N-ary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of an n-ary tree, return the preorder 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)", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]\nOutput:[1,3,5,6,2,4]", + "image": null + }, + { + "text": "Example 2: 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]\nOutput:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "image": null + } + ], + "follow_up": null, + "solution": "function preorder(root: Node | null): number[] {\n const res: number[] = [];\n\n const getNodeVal = (node: Node | null): void => {\n if (node) {\n res.push(node.val);\n\n for (let i = 0; i < node.children.length; i++) {\n getNodeVal(node.children[i]);\n }\n }\n };\n\n getNodeVal(root);\n\n return res;\n}\n\n", + "title": "589. N-ary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\nExplanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "Simple backtracking logic, try out each row and col and check position is valid or not.\n\nsince we are going row one by one, there is no way queen is placed in that row.\n\nso, we need to check col, diagonals for valid position.\n\n// col is straightforward flag for each column\n\n// dia1\n// 0 1 2 3\n// 1 2 3 4\n// 2 3 4 5\n// 3 4 5 6\n\n// dia2\n// 0 -1 -2 -3\n// 1 0 -1 -2\n// 2 1 0 -1\n// 3 2 1 0\n\nnegative numbers are not allowed as index, so we add n - 1 to diagonal2.\n\nclass Solution {\n List> ans = new LinkedList<>();\n int n;\n public List> solveNQueens(int n) {\n this.n = n;\n int[][] board = new int[n][n];\n \n boolean[] col = new boolean[n];\n boolean[] dia1 = new boolean[2 * n];\n boolean[] dia2 = new boolean[2 * n];\n \n solve(0, col, dia1, dia2, board);\n return ans;\n }\n \n public void solve(int row, boolean[] col, boolean[] dia1, boolean[] dia2, int[][] board){\n if(row == n){\n copyBoardToAns(board);\n return;\n }\n // brute force all col in that row\n for(int i = 0; i < n; i++){\n if(isValid(col, dia1, dia2, i, row)){\n col[i] = true; dia1[row + i] = true; dia2[row - i + n - 1] = true;\n board[row][i] = 1;\n solve(row + 1, col, dia1, dia2, board);\n col[i] = false; dia1[row + i] = false; dia2[row - i + n - 1] = false;\n board[row][i] = 0;\n }\n }\n }\n \n public boolean isValid(boolean[] col, boolean[] dia1, boolean[] dia2, int curCol, int curRow){\n return !col[curCol] && !dia1[curCol + curRow] && !dia2[curRow - curCol + n - 1];\n }\n \n public void copyBoardToAns(int[][] board){\n List res = new LinkedList<>();\n for(int i = 0; i < n; i++){\n String row = \"\";\n for(int j = 0; j < n; j++){\n if(board[i][j] == 1){\n row += \"Q\";\n }else{\n row += \".\";\n }\n }\n res.add(row);\n }\n ans.add(res);\n }\n}\n", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\nExplanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n coord = self.findNextRows(0, n)\n ans = []\n for c in coord:\n temp = []\n for j in c:\n temp.append(\".\"*j+\"Q\"+\".\"*(n-j-1))\n ans.append(temp)\n return ans\n \n def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()):\n\t\t'''\n\t\th_occ: occupied horizontal coordinate\n\t\td_occ: occupied diagonal\n\t\tad_occ: occupied anti-diagonal\n\t\t'''\n ans = []\n if i==n:\n return [[]]\n for j in range(n):\n if (j not in h_occ) and (j-i not in d_occ) and ((j-n+1)+i not in ad_occ):\n h_occ.add(j)\n d_occ.add(j-i)\n ad_occ.add((j-n+1)+i)\n temp = self.findNextRows(i+1, n, h_occ, d_occ, ad_occ)\n h_occ.remove(j)\n d_occ.remove(j-i)\n ad_occ.remove((j-n+1)+i)\n ans += [[j]+l for l in temp]\n return ans\n \n \n", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:2\nExplanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.59%) | Memory: 41.2 MB (Top 48.22%)\nclass Solution {\n int count = 0;\n public int totalNQueens(int n) {\n boolean col[] = new boolean[n];\n boolean diag[] = new boolean[2*n-1];\n boolean rdiag[] = new boolean[2*n-1];\n\n countSolution(n,col, diag, rdiag, 0);\n return count;\n\n }\n void countSolution(int n, boolean[] col, boolean[] diag, boolean[] rdiag, int r ){\n if (r == n ){\n count++;\n return;\n }\n\n for(int c = 0 ; c < n; c++){\n if(col[c] == false && diag[r+c] == false && rdiag[r-c+n-1] == false){\n col[c] = true;\n diag[r+c] = true;\n rdiag[r-c+n-1] = true;\n countSolution(n, col, diag, rdiag, r+1);\n col[c] = false;\n diag[r+c] = false;\n rdiag[r-c+n-1] = false;\n }\n }\n\n }\n}", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:2\nExplanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalNQueens(self, n: int) -> int:\n res=0\n #用于存放结果\n pdia=set()\n ndia=set()\n col=set()\n\n def backtrack(r):\n #利用r作为一种计数,表示目前所在的行数\n if r==n:\n #判断已经完成棋盘,返回结果\n nonlocal res\n res+=1\n return\n for c in range(n):\n #对于n行n列的棋盘,每次在每一行我们尝试n种选择,\n #即每个岔路口有n条路线\n if (r+c) in pdia or (r-c) in ndia or c in col:\n #如果在同一对角线,或同一列,则不符合要求\n continue\n col.add(c)\n pdia.add(r+c)\n ndia.add(r-c)\n \n backtrack(r+1)\n \n col.remove(c)\n pdia.remove(r+c)\n ndia.remove(r-c)\n\n backtrack(0)\n return res\n", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums with the following properties: Return the element that is repeated n times .", + "description_images": [], + "constraints": [ + "nums.length == 2 * n .", + "nums contains n + 1 unique elements.", + "Exactly one element of nums is repeated n times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,2,5,3,2]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,1,5,2,5,3,5,4]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int repeatedNTimes(int[] nums) {\n int count = 0;\n for(int i = 0; i < nums.length; i++) {\n for(int j = i + 1; j < nums.length; j++) {\n if(nums[i] == nums[j])\n count = nums[j];\n }\n }\n return count;\n }\n}\n", + "title": "961. N-Repeated Element in Size 2N Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums with the following properties: Return the element that is repeated n times .", + "description_images": [], + "constraints": [ + "nums.length == 2 * n .", + "nums contains n + 1 unique elements.", + "Exactly one element of nums is repeated n times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,2,5,3,2]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,1,5,2,5,3,5,4]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][0]\n", + "title": "961. N-Repeated Element in Size 2N Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n .", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:4\nExplanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25\nOutput:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 58.23%)\nclass Solution {\n public int tribonacci(int n) {\n if(n==0)\n return 0;\n if(n==1)\n return 1;\n if(n==2)\n return 1;\n int p1=1;\n int p2=1;\n int p3=0;\n int cur=0;\n for(int i=3;i<=n;i++)\n {\n cur=p1+p2+p3;\n p3=p2;\n p2=p1;\n p1=cur;\n }\n return cur;\n }\n}", + "title": "1137. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n .", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:4\nExplanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25\nOutput:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def tribonacci(self, n: int, q={}) -> int:\n if n<3:\n q[0]=0 #Initialize first 3 values \n q[1]=1\n q[2]=1\n if n not in q: #Have faith that last 3 calls will give the answer :)\n q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci(n-3,q)\n return q[n]\n", + "title": "1137. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Return the number of distinct valid names for the company .", + "description_images": [], + "constraints": [ + "2 <= ideas.length <= 5 * 10^4", + "1 <= ideas[i].length <= 10", + "ideas[i] consists of lowercase English letters.", + "All the strings in ideas are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]\nOutput:6\nExplanation:The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.", + "image": null + }, + { + "text": "Example 2: Input:ideas = [\"lack\",\"back\"]\nOutput:0\nExplanation:There are no valid selections. Therefore, 0 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 186 ms (Top 96.05%) | Memory: 52.9 MB (Top 100.00%)\nclass Solution {\n public long distinctNames(String[] ideas) {\n // HashSet + String Manipulation; TC: O(26*26*n); SC: O(26*n)\n HashSet [] arr = new HashSet[26];\n for(int i=0; i<26; i++) {\n arr[i] = new HashSet<>();\n }\n for(String s: ideas) {\n arr[s.charAt(0)-'a'].add(s.substring(1));\n }\n long ans=0, cnt;\n for(int i=0; i<26; i++) {\n for(int j=i+1; j<26; j++) {\n cnt=0;\n for(String str: arr[j]) {\n if(arr[i].contains(str)) cnt++;\n }\n ans+=2*(arr[i].size()-cnt)*(arr[j].size()-cnt);\n }\n }\n return ans;\n }\n}", + "title": "2306. Naming a Company", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Return the number of distinct valid names for the company .", + "description_images": [], + "constraints": [ + "2 <= ideas.length <= 5 * 10^4", + "1 <= ideas[i].length <= 10", + "ideas[i] consists of lowercase English letters.", + "All the strings in ideas are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]\nOutput:6\nExplanation:The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.", + "image": null + }, + { + "text": "Example 2: Input:ideas = [\"lack\",\"back\"]\nOutput:0\nExplanation:There are no valid selections. Therefore, 0 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctNames(self, ideas: List[str]) -> int:\n \n names=defaultdict(set)\n res=0 \n \n #to store first letter as key and followed suffix as val\n for i in ideas:\n names[i[0]].add(i[1:])\n \n #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)\n arr=list(names.keys())\n ans,n=0,len(arr)\n \n for i in range(n):\n for j in range(i+1,n):\n #a,b => 2 distinct first letters\n a,b=arr[i],arr[j]\n # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be \"newword1 newword2\" or \"newword2 newword1\"\n res+=len(names[a]-names[b])*len(names[b]-names[a])*2\n \n return res\n\t\n", + "title": "2306. Naming a Company", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists .", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput:1\nExplanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput:2\nExplanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput:-1\nExplanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 87.01%) | Memory: 43.7 MB (Top 91.43%)\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length, queueSize;\n Queue queue = new LinkedList<>();\n boolean[][] visited = new boolean[rows][cols];\n int[] curr;\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n int x, y, steps = 0;\n\n queue.offer(entrance);\n visited[entrance[0]][entrance[1]] = true;\n\n while (!queue.isEmpty()) {\n queueSize = queue.size();\n steps++;\n\n for (int i=0;i=rows||y<0||y>=cols) continue;\n if (visited[x][y] || maze[x][y] == '+') continue;\n\n // check if we have reached boundary\n if (x==0||x==rows-1||y==0||y==cols-1) return steps;\n\n queue.offer(new int[]{x, y});\n visited[x][y] = true;\n }\n }\n }\n\n return -1;\n }\n}", + "title": "1926. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists .", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput:1\nExplanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput:2\nExplanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput:-1\nExplanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n x, y = entrance\n m, n, infi = len(maze), len(maze[0]), int(1e5)\n reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)\n @lru_cache(None)\n def dfs(i, j):\n if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':\n return infi\n if reached(i, j):\n return 0\n maze[i][j] = '+'\n ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))\n maze[i][j] = '.'\n return ans\n ans = dfs(x, y)\n return -1 if ans>=infi else ans\n", + "title": "1926. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "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.)" + ], + "examples": [ + { + "text": "Example 1: Input:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png" + }, + { + "text": "Example 2: Input:times = [[1,2,1]], n = 2, k = 1\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:times = [[1,2,1]], n = 2, k = 2\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 24.43%) | Memory: 65.2 MB (Top 52.71%)\nclass Solution {\n HashMap> map = new HashMap<>();\n public int networkDelayTime(int[][] times, int n, int k) {\n for (int i = 1; i <= n; i++) {\n map.put(i, new HashMap<>());\n }\n for (int i = 0; i < times.length; i++) {\n map.get(times[i][0]).put(times[i][1], times[i][2]);\n }\n int ans = BFS(k, n);\n\n return ans == 1000 ? -1 : ans;\n }\n public int BFS(int k, int n) {\n LinkedList queue = new LinkedList<>();\n\n int[] timeReach = new int[n + 1];\n Arrays.fill(timeReach, 1000);\n timeReach[0] = 0;\n\n timeReach[k] = 0;\n\n queue.add(k);\n\n while (!queue.isEmpty()) {\n int rv = queue.remove();\n for (int nbrs : map.get(rv).keySet()) {\n int t = map.get(rv).get(nbrs) + timeReach[rv];\n if (t < timeReach[nbrs]) {\n timeReach[nbrs] = t;\n queue.add(nbrs);\n }\n }\n }\n\n int time = 0;\n\n for (int i : timeReach) {\n time = Math.max(i, time);\n }\n\n return time;\n }\n}", + "title": "743. Network Delay Time", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "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.)" + ], + "examples": [ + { + "text": "Example 1: Input:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png" + }, + { + "text": "Example 2: Input:times = [[1,2,1]], n = 2, k = 1\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:times = [[1,2,1]], n = 2, k = 2\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n \n adjlist = [[] for _ in range(n+1)]\n \n for src, dst, weight in times:\n adjlist[src].append((dst, weight))\n \n visited = [-1]*(n+1)\n captured =[-1]*(n+1)\n\n priority_queue = [(0,k)]\n \n nums = 0\n total_dist = 0\n \n while priority_queue:\n\n dst, node = heapq.heappop(priority_queue)\n\n if captured[node] != -1:\n continue\n captured[node] = dst\n \n nums += 1\n total_dist = dst\n \n for nbr,wt in adjlist[node]:\n if captured[nbr] == -1:\n heapq.heappush(priority_queue,(captured[node]+wt, nbr))\n if nums == n:\n return total_dist\n else:\n return -1\n", + "title": "743. Network Delay Time", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice plays the following game, loosely based on the card game \"21\" . Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts] , where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points . Return the probability that Alice has n or fewer points. Answers within 10 -5 of the actual answer are considered accepted.", + "description_images": [], + "constraints": [ + "0 <= k <= n <= 10^4", + "1 <= maxPts <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, k = 1, maxPts = 10\nOutput:1.00000\nExplanation:Alice gets a single card, then stops.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, k = 1, maxPts = 10\nOutput:0.60000\nExplanation:Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.", + "image": null + }, + { + "text": "Example 3: Input:n = 21, k = 17, maxPts = 10\nOutput:0.73278", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double new21Game(int n, int k, int maxPts) {\n double[] dp = new double[k + maxPts];\n dp[0] = 1;\n for (int i = 0; i < k; i++){\n for (int j = 1; j <= maxPts; j++){\n dp[i + j] += dp[i] * 1.0 / maxPts;\n }\n }\n\n double ans = 0;\n for (int i = k; i < k + maxPts && i <= n; i++){\n ans += dp[i];\n }\n\n return ans;\n }\n}\n", + "title": "837. New 21 Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice plays the following game, loosely based on the card game \"21\" . Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts] , where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points . Return the probability that Alice has n or fewer points. Answers within 10 -5 of the actual answer are considered accepted.", + "description_images": [], + "constraints": [ + "0 <= k <= n <= 10^4", + "1 <= maxPts <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, k = 1, maxPts = 10\nOutput:1.00000\nExplanation:Alice gets a single card, then stops.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, k = 1, maxPts = 10\nOutput:0.60000\nExplanation:Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.", + "image": null + }, + { + "text": "Example 3: Input:n = 21, k = 17, maxPts = 10\nOutput:0.73278", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 110 ms (Top 69.47%) | Memory: 14.5 MB (Top 12.98%)\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])\n s = sum(dp)\n for i in range(k):\n dp.appendleft(s / maxPts)\n s += dp[0] - dp.pop()\n\n return dp[0]", + "title": "837. New 21 Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput:[-1,3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]\nOutput:[3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 51.94%) | Memory: 44.9 MB (Top 8.50%)\nclass Solution {\n public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n HashMap map = new HashMap<>();\n Stack stack = new Stack<>();\n int[] ans = new int[nums1.length];\n for(int i = 0; i < nums2.length; i++){\n while(!stack.isEmpty() && nums2[i] > stack.peek()){\n int temp = stack.pop();\n map.put(temp, nums2[i]);\n }\n stack.push(nums2[i]);\n }\n for(int i = 0; i < nums1.length; i++){\n ans[i] = map.getOrDefault(nums1[i], -1);\n }\n return ans;\n }\n}", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput:[-1,3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]\nOutput:[3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 80.48%) | Memory: 16.70 MB (Top 24.94%)\n\nclass Solution:\n def nextGreaterElement(self, nums1, nums2):\n dic, stack = {}, []\n \n for num in nums2[::-1]:\n while stack and num > stack[-1]:\n stack.pop()\n if stack:\n dic[num] = stack[-1]\n stack.append(num)\n \n return [dic.get(num, -1) for num in nums1]\n", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0] ), return the next greater number for every element in nums . The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]\nOutput:[2,-1,2]\n\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,3]\nOutput:[2,3,4,-1,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] nextGreaterElements(int[] nums) {\n Stacks=new Stack<>();\n for(int i=nums.length-1;i>=0;i--){\n s.push(nums[i]);\n }\n for(int i=nums.length-1;i>=0;i--){\n int num=nums[i];\n while(!s.isEmpty() && s.peek()<=nums[i]){\n s.pop();\n }\n nums[i]=s.empty()?-1:s.peek();\n s.push(num);\n }\n return nums;\n }\n}\n", + "title": "503. Next Greater Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0] ), return the next greater number for every element in nums . The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]\nOutput:[2,-1,2]\n\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,3]\nOutput:[2,3,4,-1,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 151 ms (Top 99.29%) | Memory: 19.30 MB (Top 5.84%)\n\nclass Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n st = []\n n = len(nums)\n ans = [-1] * n\n for i in range(2*n-1, -1, -1):\n while st and st[-1] <= nums[i%n]:\n st.pop()\n if st and i < n:\n ans[i] = st[-1]\n st.append(nums[i%n])\n return ans\n", + "title": "503. Next Greater Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer n , find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n . If no such positive integer exists, return -1 . Note that the returned integer should fit in 32-bit integer , if there is a valid answer but it does not fit in 32-bit integer , return -1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:21", + "image": null + }, + { + "text": "Example 2: Input:n = 21\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nextGreaterElement(int n) {\n char[] arr = (n + \"\").toCharArray();\n \n int i = arr.length - 1;\n while(i > 0){\n if(arr[i-1] >= arr[i]){\n i--;\n }else{\n break;\n }\n }\n if(i == 0){\n return -1;\n }\n \n int idx1 = i-1;\n \n int j = arr.length - 1;\n while(j > idx1){\n if(arr[j] > arr[idx1]){\n break;\n }\n j--;\n }\n \n //Swapping\n swap(arr,idx1,j);\n \n //sorting\n int left = idx1+1;\n int right = arr.length-1;\n while(left < right){\n swap(arr,left,right);\n left++;\n right--;\n }\n \n String result = new String(arr);\n long val = Long.parseLong(result);\n \n return (val > Integer.MAX_VALUE ? -1 : (int)val);\n \n }\n \n void swap(char[]arr,int i,int j){\n char temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n\n", + "title": "556. Next Greater Element III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n . If no such positive integer exists, return -1 . Note that the returned integer should fit in 32-bit integer , if there is a valid answer but it does not fit in 32-bit integer , return -1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:21", + "image": null + }, + { + "text": "Example 2: Input:n = 21\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 26.09%) | Memory: 16.30 MB (Top 30.04%)\n\nclass Solution:\n def nextGreaterElement(self, n):\n digits = list(str(n))\n i = len(digits) - 1\n while i-1 >= 0 and digits[i] <= digits[i-1]:\n i -= 1\n \n if i == 0: return -1\n \n j = i\n while j+1 < len(digits) and digits[j+1] > digits[i-1]:\n j += 1\n \n digits[i-1], digits[j] = digits[j], digits[i-1]\n digits[i:] = digits[i:][::-1]\n ret = int(''.join(digits))\n \n return ret if ret < 1<<31 else -1\n", + "title": "556. Next Greater Element III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node . That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the i th node ( 1-indexed ). If the i th node does not have a next greater node, set answer[i] = 0 .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 10^4", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [2,1,5]\nOutput:[5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext1.jpg" + }, + { + "text": "Example 2: Input:head = [2,7,4,3,5]\nOutput:[7,0,5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 721 ms (Top 25.59%) | Memory: 45.5 MB (Top 95.29%)\nclass Solution {\n public int[] nextLargerNodes(ListNode head) {\n ListNode length=head;\n int l=0;\n while(length!=null)\n {\n length=length.next;\n l++;\n }\n int[] res=new int[l];\n int i=0;\n ListNode temp=head;\n\n while(temp!=null)\n {\n ListNode temp1=temp.next;\n int max=temp.val;\n\n while(temp1!=null)\n {\n if(temp1.val>max)\n {\n max=temp1.val;\n res[i]=max;\n break;\n }\n\n temp1=temp1.next;\n }\n temp=temp.next;\n i++;\n }\n return res;\n }\n}", + "title": "1019. Next Greater Node In Linked List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node . That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the i th node ( 1-indexed ). If the i th node does not have a next greater node, set answer[i] = 0 .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 10^4", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [2,1,5]\nOutput:[5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext1.jpg" + }, + { + "text": "Example 2: Input:head = [2,7,4,3,5]\nOutput:[7,0,5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n stack = []\n ans = []\n node = head\n \n i = 0\n while node is not None:\n while stack and stack[-1][0] < node.val:\n ans[stack[-1][1]] = node.val\n stack.pop()\n \n stack.append((node.val, i))\n ans.append(0)\n i += 1\n node = node.next\n \n return ans", + "title": "1019. Next Greater Node In Linked List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer x is numerically balanced if for every digit d in the number x , there are exactly d occurrences of that digit in x . Given an integer n , return the smallest numerically balanced number strictly greater than n .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:22\nExplanation:22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 1000\nOutput:1333\nExplanation:1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.", + "image": null + }, + { + "text": "Example 3: Input:n = 3000\nOutput:3133\nExplanation:3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 207 ms (Top 46.27%) | Memory: 117.2 MB (Top 26.87%)\nclass Solution {\n public int nextBeautifulNumber(int n) {\n\n while(true){\n n++;\n int num = n; //test this number\n int [] freq = new int[10]; // 0 to 9\n\n while(num > 0){ //calculate freq of each digit in the num\n int rem = num % 10; //this is remainder\n num = num / 10; //this is quotient\n freq[rem] = freq[rem] + 1; //increase its frequency\n if(freq[rem] > rem) break;\n }\n\n boolean ans = true;\n\n for(int i = 0;i<10;i++){ //check frequency of each digit\n if(freq[i] != i && freq[i] != 0){\n ans = false;\n break;\n }\n }\n\n if(ans == true){\n return n;\n }\n }\n }\n}", + "title": "2048. Next Greater Numerically Balanced Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer x is numerically balanced if for every digit d in the number x , there are exactly d occurrences of that digit in x . Given an integer n , return the smallest numerically balanced number strictly greater than n .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:22\nExplanation:22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 1000\nOutput:1333\nExplanation:1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.", + "image": null + }, + { + "text": "Example 3: Input:n = 3000\nOutput:3133\nExplanation:3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n n_digits = len(str(n))\n \n next_max = {\n 1: [1],\n 2: [22],\n 3: [122, 333],\n 4: [1333, 4444],\n 5: [14444, 22333, 55555],\n 6: [122333, 224444, 666666, 155555],\n 7: [1224444, 2255555, 3334444, 1666666, 7777777]\n }\n \n if n >= int(str(n_digits) * n_digits):\n n_digits += 1\n return min(next_max[n_digits])\n \n ans = float('inf')\n for num in sorted(next_max[n_digits]): \n cands = set(permutations(str(num)))\n cands = sorted(map(lambda x: int(\"\".join(x)), cands))\n \n loc = bisect.bisect(cands, n)\n if loc < len(cands): \n ans = min(ans, cands[loc])\n \n return ans\n", + "title": "2048. Next Greater Numerically Balanced Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory.", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are considered permutations of arr : [1,2,3] , [1,3,2] , [3,1,2] , [2,3,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]\nOutput:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]\nOutput:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.93%) | Memory: 43.7 MB (Top 52.39%)\n\nclass Solution {\n public void nextPermutation(int[] nums) {\n // FIND peek+1\n int nextOfPeak = -1;\n for (int i = nums.length - 1; i > 0; i--) {\n if (nums[i] > nums[i - 1]) {\n nextOfPeak = i - 1;\n break;\n }\n }\n\n // Return reverse Array\n if (nextOfPeak == -1) {\n int start = 0;\n int end = nums.length - 1;\n while (start <= end) {\n int temp = nums[start];\n nums[start] = nums[end];\n nums[end] = temp;\n start++;\n end--;\n }\n return;\n }\n // Find element greater than peek\n int reversalPoint = nums.length - 1;\n for (int i = nums.length - 1; i > nextOfPeak; i--) {\n if (nums[i] > nums[nextOfPeak]) {\n reversalPoint = i;\n break;\n }\n }\n\n // swap nextOfPeak && reversalPoint\n int temp = nums[nextOfPeak];\n nums[nextOfPeak] = nums[reversalPoint];\n nums[reversalPoint] = temp;\n\n // Reverse array from nextOfPeak+1\n int start = nextOfPeak + 1;\n int end = nums.length - 1;\n while (start <= end) {\n int temp1 = nums[start];\n nums[start] = nums[end];\n nums[end] = temp1;\n start++;\n end--;\n }\n\n }\n}", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory.", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are considered permutations of arr : [1,2,3] , [1,3,2] , [3,1,2] , [2,3,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]\nOutput:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]\nOutput:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextPermutation(self, nums) -> None:\n firstDecreasingElement = -1\n toSwapWith = -1\n lastIndex = len(nums) - 1\n\n # Looking for an element that is less than its follower\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[i - 1]:\n firstDecreasingElement = i - 1\n break\n\n # If there is not any then reverse the array to make initial permutation\n if firstDecreasingElement == -1:\n for i in range(0, lastIndex // 2 + 1):\n nums[i], nums[lastIndex - i] = nums[lastIndex - i], nums[i]\n return\n\n # Looking for an element to swap it with firstDecreasingElement\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[firstDecreasingElement]:\n toSwapWith = i\n break\n\n # Swap found elements\n nums[firstDecreasingElement], nums[toSwapWith] = nums[toSwapWith], nums[firstDecreasingElement]\n\n # Reverse elements from firstDecreasingElement to the end of the array\n left = firstDecreasingElement + 1\n right = lastIndex\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing the following Nim Game with your friend: Given n , the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false .", + "description_images": [], + "constraints": [ + "Initially, there is a heap of stones on the table.", + "You and your friend will alternate taking turns, and you go first .", + "On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.", + "The one who removes the last stone is the winner." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:false\nExplanation:These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 59.25%)\nclass Solution {\n public boolean canWinNim(int n) {\n if(n%4==0) return false;\n\n return true;\n }\n}", + "title": "292. Nim Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing the following Nim Game with your friend: Given n , the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false .", + "description_images": [], + "constraints": [ + "Initially, there is a heap of stones on the table.", + "You and your friend will alternate taking turns, and you go first .", + "On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.", + "The one who removes the last stone is the winner." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:false\nExplanation:These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 73.60%) | Memory: 13.9 MB (Top 45.89%)\nclass Solution:\n def canWinNim(self, n: int) -> bool:\n return n%4", + "title": "292. Nim Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element . We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i ( 0-based ) such that ( 0 <= i <= n - 2 ).", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3]\nOutput:true\nExplanation:You could modify the first 4 to 1 to get a non-decreasing array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,1]\nOutput:false\nExplanation:You cannot get a non-decreasing array by modifying at most one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkPossibility(int[] nums) {\n int modified = 0, prev = nums[0], index = 0;\n for (; index < nums.length; ++index) {\n if (nums[index] < prev) {\n if (++modified > 1) return false;\n if (index - 2 >= 0 && nums[index - 2] > nums[index]) continue;\n }\n prev = nums[index];\n }\n return true;\n }\n}\n", + "title": "665. Non-decreasing Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element . We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i ( 0-based ) such that ( 0 <= i <= n - 2 ).", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3]\nOutput:true\nExplanation:You could modify the first 4 to 1 to get a non-decreasing array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,1]\nOutput:false\nExplanation:You cannot get a non-decreasing array by modifying at most one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n unstable=0\n for i in range(1,len(nums)):\n if nums[i]1:\n return False\n return True\n", + "title": "665. Non-decreasing Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer n , return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:5\nExplanation:Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findIntegers(int n) {\n int val=0,res=0,cn=n,digi=0,prevdig=0,i;//digi means bin digi\n while(cn>0){\n cn=cn>>1;\n digi++;\n }\n int dp[]=new int[digi+1];\n dp[0]=1;dp[1]=2;\n for(i=2;i<=digi;i++)\n dp[i]=dp[i-1]+dp[i-2];\n digi++;\n while(digi-->=0){\n if((n&(1<0){\n res+=dp[digi];\n if(prevdig==1)return res;\n prevdig=1;\n }else prevdig=0;\n }\n \n return res+1;\n }\n}\n", + "title": "600. Non-negative Integers without Consecutive Ones", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a positive integer n , return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:5\nExplanation:Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findIntegers(self, n: int) -> int:\n b=(bin(n).replace(\"0b\",\"\"))\n dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)]\n def fun(i,last,tight,leading_zeros):\n if i==len(str(b)):\n return 1\n if dp[i][tight][leading_zeros][last]!=-1:\n return dp[i][tight][leading_zeros][last]\n end=1\n if tight==1:\n end = int(b[i])\n res=0\n for j in range(end+1):\n if j==0 and leading_zeros==1:\n res+=fun(i+1,j,tight&int(j==end),1)\n else:\n if j==0:\n res+=fun(i+1,j,tight&int(j==end),0)\n else:\n if last!=j:\n res+=fun(i+1,j,tight&int(j==end),0)\n dp[i][tight][leading_zeros][last] = res\n return res\n return fun(0,0,1,1)", + "title": "600. Non-negative Integers without Consecutive Ones", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput:1\nExplanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]\nOutput:2\nExplanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]\nOutput:0\nExplanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "// |-------|\n// |--|\n\n// |-------|\n//. |-------|\n\n// |-------|\n//. |-------|\n\nclass Solution {\n public int eraseOverlapIntervals(int[][] intervals) {\n Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n \n int start = intervals[0][0];\n int end = intervals[0][1];\n int res = 0;\n \n for (int i = 1; i < intervals.length; i++){\n int[] interval = intervals[i];\n \n if(interval[0] >= start && interval[0] < end){\n res++;\n if (interval[1] >= end)\n continue;\n }\n start = interval[0];\n end = interval[1];\n }\n \n return res;\n }\n}\n", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput:1\nExplanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]\nOutput:2\nExplanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]\nOutput:0\nExplanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3035 ms (Top 7.53%) | Memory: 52.8 MB (Top 61.18%)\n\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1)\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n\n for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value\n if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one\n prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval\n else: # Overlapping when new interval starts in between or from the previous one\n res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2]\n prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last\n\n return res", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the n th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:n = 11\nOutput:0\nExplanation:The 11thdigit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1237 ms (Top 5.08%) | Memory: 39.2 MB (Top 91.02%)\nclass Solution {\n public int findNthDigit(int n) {\n\n if(n < 10)\n return n;\n\n long currDigitIndex = 10;\n int tillNextIncrease = 90;\n int currNumberSize = 2;\n int currNumber = 10;\n int next = tillNextIncrease;\n\n while(currDigitIndex < n) {\n\n currNumber++;\n currDigitIndex += currNumberSize;\n next--;\n\n if(next == 0) {\n currNumberSize++;\n tillNextIncrease *= 10;\n next = tillNextIncrease;\n }\n }\n\n int nthDigit = currNumber % 10;\n if(currDigitIndex == n) {\n while(currNumber != 0) {\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n } else if(currDigitIndex > n) {\n\n currNumber--;\n\n while(currDigitIndex > n) {\n currDigitIndex--;\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n }\n\n return nthDigit;\n }\n}", + "title": "400. Nth Digit", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return the n th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:n = 11\nOutput:0\nExplanation:The 11thdigit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNthDigit(self, n: int) -> int:\n low, high = 1, 0\n place = 1\n \n sum_ = 0\n \n while True:\n high = 10**place -1\n digits_sum = (high - low +1 ) * place\n \n if sum_<= n <= digits_sum + sum_:\n break\n else:\n low = high+1\n sum_+= digits_sum\n place += 1\n \n remaining_digits = n - sum_\n \n position = (remaining_digits-1)//place \n index_ = remaining_digits - position*place -1\n \n \n number = low + position\n # return str(number)[index_]\n count = 0\n index_ = place - 1 - index_\n l = []\n # \n while number:\n if count == index_:\n return number%10\n number = number//10\n count+=1\n\n", + "title": "400. Nth Digit", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A positive integer is magical if it is divisible by either a or b . Given the three integers n , a , and b , return the n th magical number. Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "2 <= a, b <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, a = 2, b = 3\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 60.59%) | Memory: 40.8 MB (Top 59.85%)\nclass Solution {\npublic int nthMagicalNumber(int n, int a, int b) {\n long N=(long)n;\n long A=(long)a;\n long B=(long)b;\n long mod=1000000007;\n long min=Math.min(A,B);\n long low=min;\n long high=min*N;\n long ans=0;\n while(low<=high)\n {\n long mid=(high-low)/2+low;\n long x=mid/A+mid/B-mid/lcm(A,B);\n if(x>=N)\n {\n ans=mid;\n high=mid-1;\n }\n else if(x0)\n {\n long temp=a;\n a=b%a;\n b=temp;\n }\n\n return tmpA*tmpB/b;\n}\n}", + "title": "878. Nth Magical Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A positive integer is magical if it is divisible by either a or b . Given the three integers n , a , and b , return the n th magical number. Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "2 <= a, b <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, a = 2, b = 3\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 24 ms (Top 100.0%) | Memory: 16.28 MB (Top 81.4%)\n\nclass Solution:\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n import math\n lcm= A*B // math.gcd(A,B)\n l,r=2,10**14\n while l<=r:\n mid=(l+r)//2\n n = mid//A+mid//B-mid//lcm\n if n>=N:\n r=mid-1\n \n else:\n l=mid+1\n return l%(10**9+7)", + "title": "878. Nth Magical Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer num , return its complement .", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 5\nOutput:2\nExplanation:The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 1\nOutput:0\nExplanation:The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findComplement(int num) {\n int x=0;int sum=0;\n while(num>0){\n int i = num%2;\n if(i==0){\n sum+=Math.pow(2,x++);\n }\n else{\n x++;\n }\n num/=2;\n }\n return sum;\n }\n}\n", + "title": "476. Number Complement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer num , return its complement .", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 5\nOutput:2\nExplanation:The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 1\nOutput:0\nExplanation:The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 13.03%) | Memory: 13.8 MB (Top 53.14%)\n\nclass Solution:\n def findComplement(self, num: int) -> int:\n i = 0\n while(2**i <= num):\n i += 1\n return (2**i - num - 1)", + "title": "476. Number Complement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight ). Note:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 3 , the input represents the signed integer. -3 ." + ], + "examples": [ + { + "text": "Example 3 Input:n = 00000000000000000000000000001011\nOutput:3\nExplanation:The input binary string00000000000000000000000000001011has a total of three '1' bits.", + "image": null + }, + { + "text": "Example 2: Input:n = 00000000000000000000000010000000\nOutput:1\nExplanation:The input binary string00000000000000000000000010000000has a total of one '1' bit.", + "image": null + }, + { + "text": "Example 3: Input:n = 11111111111111111111111111111101\nOutput:31\nExplanation:The input binary string11111111111111111111111111111101has a total of thirty one '1' bits.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need to treat n as an unsigned value\n public int hammingWeight(int n) {\n return Integer.bitCount(n);\n }\n}\n", + "title": "191. Number of 1 Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight ). Note:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 3 , the input represents the signed integer. -3 ." + ], + "examples": [ + { + "text": "Example 3 Input:n = 00000000000000000000000000001011\nOutput:3\nExplanation:The input binary string00000000000000000000000000001011has a total of three '1' bits.", + "image": null + }, + { + "text": "Example 2: Input:n = 00000000000000000000000010000000\nOutput:1\nExplanation:The input binary string00000000000000000000000010000000has a total of one '1' bit.", + "image": null + }, + { + "text": "Example 3: Input:n = 11111111111111111111111111111101\nOutput:31\nExplanation:The input binary string11111111111111111111111111111101has a total of thirty one '1' bits.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 27 ms (Top 98.51%) | Memory: 13.8 MB (Top 50.40%)\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n i = 0\n while n > 0:\n if n % 2 != 0: i += 1\n n = n >> 1\n return i", + "title": "191. Number of 1 Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed , strictly increasing integer array nums and a positive integer diff . A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: Return the number of unique arithmetic triplets .", + "description_images": [], + "constraints": [ + "i < j < k ,", + "nums[j] - nums[i] == diff , and", + "nums[k] - nums[j] == diff ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,4,6,7,10], diff = 3\nOutput:2\nExplanation:(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,8,9], diff = 2\nOutput:2\nExplanation:(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.25%) | Memory: 42.8 MB (Top 15.70%)\n\nclass Solution {\n public int arithmeticTriplets(int[] nums, int diff) {\n int result = 0;\n int[] map = new int[201];\n\n for(int num: nums) {\n map[num] = 1;\n\n if(num - diff >= 0) {\n map[num] += map[num - diff];\n }\n\n if(map[num] >= 3) result += 1;\n }\n\n return result;\n }\n}", + "title": "2367. Number of Arithmetic Triplets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed , strictly increasing integer array nums and a positive integer diff . A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: Return the number of unique arithmetic triplets .", + "description_images": [], + "constraints": [ + "i < j < k ,", + "nums[j] - nums[i] == diff , and", + "nums[k] - nums[j] == diff ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,4,6,7,10], diff = 3\nOutput:2\nExplanation:(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,8,9], diff = 2\nOutput:2\nExplanation:(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n \n ans = 0\n n = len(nums)\n for i in range(n):\n if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n ans += 1\n \n return ans\n", + "title": "2367. Number of Arithmetic Triplets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. Two formulas are concatenated together to produce another formula. A formula placed in parentheses, and a count (optionally added) is also a formula. 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.", + "description_images": [], + "constraints": [ + "For example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible." + ], + "examples": [ + { + "text": "Example 1: Input:formula = \"H2O\"\nOutput:\"H2O\"\nExplanation:The count of elements are {'H': 2, 'O': 1}.", + "image": null + }, + { + "text": "Example 2: Input:formula = \"Mg(OH)2\"\nOutput:\"H2MgO2\"\nExplanation:The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.", + "image": null + }, + { + "text": "Example 3: Input:formula = \"K4(ON(SO3)2)2\"\nOutput:\"K4N2O14S4\"\nExplanation:The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String countOfAtoms(String formula) {\n Deque multiplier = new ArrayDeque<>();\n Map map = new HashMap<>();\n int lastValue = 1;\n \n multiplier.push(1);\n \n\t\t// Iterate from right to left\n for (int i = formula.length() - 1; i >= 0; i--) {\n if (Character.isDigit(formula.charAt(i))) { // Case of a digit - Get full number and save\n StringBuilder sb = new StringBuilder();\n\t\t\t\t\n while (Character.isDigit(formula.charAt(i-1))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n lastValue = Integer.parseInt(sb.reverse().toString());\n } else if (formula.charAt(i) == ')') { // Start parenthesis - push next multiplier to stack\n multiplier.push(lastValue * multiplier.peek());\n lastValue = 1;\n } else if (formula.charAt(i) == '(') { // End parenthesis - pop last multiplier\n multiplier.pop();\n } else { // Case of an element name - construct name, update count based on multiplier\n StringBuilder sb = new StringBuilder();\n \n while (Character.isLowerCase(formula.charAt(i))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n \n String element = sb.reverse().toString();\n map.put(element, map.getOrDefault(element, 0) + lastValue * multiplier.peek());\n lastValue = 1;\n }\n }\n \n\t\t// Sort map keys\n List elements = new ArrayList<>(map.keySet());\n StringBuilder sb = new StringBuilder();\n Collections.sort(elements);\n \n\t\t// Construct output\n for (String element : elements) {\n sb.append(element);\n if (map.get(element) > 1) {\n sb.append(map.get(element)); \n }\n }\n return sb.toString();\n }\n}\n", + "title": "726. Number of Atoms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Two formulas are concatenated together to produce another formula. A formula placed in parentheses, and a count (optionally added) is also a formula. 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.", + "description_images": [], + "constraints": [ + "For example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible." + ], + "examples": [ + { + "text": "Example 1: Input:formula = \"H2O\"\nOutput:\"H2O\"\nExplanation:The count of elements are {'H': 2, 'O': 1}.", + "image": null + }, + { + "text": "Example 2: Input:formula = \"Mg(OH)2\"\nOutput:\"H2MgO2\"\nExplanation:The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.", + "image": null + }, + { + "text": "Example 3: Input:formula = \"K4(ON(SO3)2)2\"\nOutput:\"K4N2O14S4\"\nExplanation:The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 78.84%) | Memory: 16.70 MB (Top 50.21%)\n\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack, elem, i = [{}], \"\", 0\n \n while i < len(formula):\n # Extract the full element name\n if formula[i].isupper():\n j = i + 1\n while j < len(formula) and formula[j].islower():\n j += 1\n elem = formula[i:j]\n i = j\n # If no digits follow the element, assign a count of 1\n if i == len(formula) or not formula[i].isdigit() and not formula[i].islower():\n stack[-1][elem] = stack[-1].get(elem, 0) + 1\n # Extract the count\n elif formula[i].isdigit():\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n count = int(formula[i:j])\n stack[-1][elem] = stack[-1].get(elem, 0) + count\n i = j\n # Handle open parentheses by pushing a new dict\n elif formula[i] == '(':\n stack.append({})\n i += 1\n # Handle close parentheses by merging with the previous dict\n elif formula[i] == ')':\n i += 1\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n multiplier = int(formula[i:j] or 1)\n top = stack.pop()\n for elem, count in top.items():\n stack[-1][elem] = stack[-1].get(elem, 0) + count * multiplier\n i = j\n \n # Convert the result to the desired format\n atoms = sorted(stack[0].items())\n return ''.join([atom + (str(count) if count > 1 else '') for atom, count in atoms])\n\n", + "title": "726. Number of Atoms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given n points in the plane that are all distinct , where points[i] = [x i , y i ] . A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters) . Return the number of boomerangs .", + "description_images": [], + "constraints": [ + "n == points.length", + "1 <= n <= 500", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[1,0],[2,0]]\nOutput:2\nExplanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,1]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfBoomerangs(int[][] points) {\n \n int answer = 0;\n \n for (int p=0; p hm = new HashMap();\n \n for (int q=0;q 0) {\n if (hm.containsKey(distance)) {\n hm.put(distance, hm.get(distance) + 1);\n } else {\n hm.put(distance, 1);\n }\n }\n \n }\n \n for (Double dist : hm.keySet()) {\n int occ = hm.get(dist);\n if (occ > 1) {\n answer = answer + ((occ) * (occ - 1));\n }\n }\n }\n \n return answer;\n }\n}\n", + "title": "447. Number of Boomerangs", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given n points in the plane that are all distinct , where points[i] = [x i , y i ] . A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters) . Return the number of boomerangs .", + "description_images": [], + "constraints": [ + "n == points.length", + "1 <= n <= 500", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[1,0],[2,0]]\nOutput:2\nExplanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,1]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n def sq(a):\n return a * a\n\n def euclid(a, b, c, d):\n dist = sq(a - c) + sq(b - d)\n return sq(dist)\n\n n = len(points)\n res = 0\n for i in range(n):\n count = defaultdict(lambda : 0)\n for j in range(n):\n d = euclid(points[i][0], points[i][1], points[j][0], points[j][1])\n res += count[d] * 2\n count[d] += 1\n\n return res\n", + "title": "447. Number of Boomerangs", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers tomatoSlices and cheeseSlices . The ingredients of different burgers are as follows: Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0 . If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [] .", + "description_images": [], + "constraints": [ + "Jumbo Burger: 4 tomato slices and 1 cheese slice.", + "Small Burger: 2 Tomato slices and 1 cheese slice." + ], + "examples": [ + { + "text": "Example 1: Input:tomatoSlices = 16, cheeseSlices = 7\nOutput:[1,6]Explantion:To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.", + "image": null + }, + { + "text": "Example 2: Input:tomatoSlices = 17, cheeseSlices = 4\nOutput:[]Explantion:There will be no way to use all ingredients to make small and jumbo burgers.", + "image": null + }, + { + "text": "Example 3: Input:tomatoSlices = 4, cheeseSlices = 17\nOutput:[]Explantion:Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 786 ms (Top 7.64%) | Memory: 42.4 MB (Top 87.50%)\nclass Solution {\n public List numOfBurgers(int tomatoSlices, int cheeseSlices) {\n Listlist=new ArrayList<>();\n int ts=tomatoSlices;\n int cs=cheeseSlices;\n if (tscs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0))\n {\n return list;\n }\n int cnt=0;\n while(ts>0 && cs>0 && ts!=cs*2)\n {\n ts-=4;\n cnt++;\n cs--;\n }\n list.add(cnt);\n list.add(cs);\n return list;\n }\n}", + "title": "1276. Number of Burgers with No Waste of Ingredients", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers tomatoSlices and cheeseSlices . The ingredients of different burgers are as follows: Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0 . If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [] .", + "description_images": [], + "constraints": [ + "Jumbo Burger: 4 tomato slices and 1 cheese slice.", + "Small Burger: 2 Tomato slices and 1 cheese slice." + ], + "examples": [ + { + "text": "Example 1: Input:tomatoSlices = 16, cheeseSlices = 7\nOutput:[1,6]Explantion:To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.", + "image": null + }, + { + "text": "Example 2: Input:tomatoSlices = 17, cheeseSlices = 4\nOutput:[]Explantion:There will be no way to use all ingredients to make small and jumbo burgers.", + "image": null + }, + { + "text": "Example 3: Input:tomatoSlices = 4, cheeseSlices = 17\nOutput:[]Explantion:Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def numOfBurgers(self, t, c):\n \n if t==c==0:\n return [0,0]\n four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c\n two=c-four #number of small burgers\n if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list\n return []\n \n return [four,two]\n \n", + "title": "1276. Number of Burgers with No Waste of Ingredients", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0 s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png", + "https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png" + ], + "constraints": [ + "1 <= grid.length, grid[0].length <= 100", + "0 <= grid[i][j] <=1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput:2\nExplanation:Islands in gray are closed because they are completely surrounded by water (group of 1s).", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 35.60%) | Memory: 47.1 MB (Top 38.97%)\nclass Solution {\n boolean isClosed = true;\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int count = 0;\n\n for(int i=1; i grid.length-1 || j> grid[0].length-1 || grid[i][j] != 0) return;\n\n grid[i][j] = 1; // to mark as visited\n\n if(i == 0 || j == 0 || i == grid.length -1 || j == grid[0].length - 1) isClosed = false;\n\n dfs(grid, i, j+1);\n dfs(grid, i, j-1);\n dfs(grid, i+1, j);\n dfs(grid, i-1, j);\n }\n}", + "title": "1254. Number of Closed Islands", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0 s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png", + "https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png" + ], + "constraints": [ + "1 <= grid.length, grid[0].length <= 100", + "0 <= grid[i][j] <=1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput:2\nExplanation:Islands in gray are closed because they are completely surrounded by water (group of 1s).", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n '''主函数:计算封闭岛屿的数量'''\n def closedIsland(self, grid: List[List[int]]) -> int:\n result = 0\n m, n = len(grid), len(grid[0])\n self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n \n # 遍历 grid,处理边缘陆地\n for j in range(n):\n self.dfs(grid, 0, j)\n self.dfs(grid, m - 1, j)\n for i in range(m):\n self.dfs(grid, i, 0)\n self.dfs(grid, i, n - 1)\n \n # 剩下都是封闭岛屿,遍历找结果\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n result += 1\n self.dfs(grid, i, j)\n return result\n \n '''从 (i, j) 开始,将与之相邻的陆地都变成海水'''\n def dfs(self, grid, i, j):\n m, n = len(grid), len(grid[0])\n # 超出索引边界\n if i < 0 or j < 0 or i >= m or j >= n:\n return\n # 已经是海水了\n if grid[i][j] == 1:\n return\n # 变成海水\n grid[i][j] = 1\n for d in self.direction:\n x = i + d[0]\n y = j + d[1]\n self.dfs(grid, x, y)\n", + "title": "1254. Number of Closed Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput:15", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int daysBetweenDates(String date1, String date2) {\n String[] d1 = date1.split(\"-\");\n String[] d2 = date2.split(\"-\");\n return (int)Math.abs(\n daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))\n - daysFrom1971(Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2])));\n }\n private int daysFrom1971(int year, int month, int day) {\n int total = 0;\n\t\t// count years first\n total += (year - 1971) * 365;\n for (int i = 1972; i < year; i += 4) {\n if (isLeapYear(i)) total++;\n } \n int feb = isLeapYear(year) ? 29 : 28;\n\t\t// sum months and days\n switch (month) {\n case 12: \n total += 30; // 11\n case 11:\n total += 31; // 10\n case 10: \n total += 30; // 9\n case 9:\n total += 31; // 8\n case 8:\n total += 31; // 7\n case 7: \n total += 30; // 6\n case 6:\n total += 31; // 5\n case 5:\n total += 30; // 4\n case 4: \n total += 31; // 3\n case 3: \n total += feb; // 2\n case 2:\n total += 31;\n case 1:\n total += day; \n }\n return total;\n }\n private boolean isLeapYear(int i) {\n return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0);\n }\n}\n", + "title": "1360. Number of Days Between Two Dates", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput:15", + "image": null + } + ], + "follow_up": null, + "solution": "from datetime import date\n\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days)\n", + "title": "1360. Number of Days Between Two Dates", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n dice and each die has k faces numbered from 1 to k . Given three integers n , k , and target , return the number of possible ways (out of the k n total ways) to roll the dice so the sum of the face-up numbers equals target . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n, k <= 30", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 6, target = 3\nOutput:1\nExplanation:You throw one die with 6 faces.\nThere is only one way to get a sum of 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 6, target = 7\nOutput:6\nExplanation:You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 30, target = 500\nOutput:222616187\nExplanation:The answer must be returned modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 94.21%) | Memory: 40.8 MB (Top 96.38%)\nclass Solution {\n public int numRollsToTarget(int n, int k, int target) {\n if (target < n || target > n*k) return 0;\n if (n == 1) return 1;\n\n int[][] dp = new int[n+1][n*k+1];\n for (int i = 1; i<= k; i++) {\n dp[1][i] = 1;\n }\n int mod = 1000000007;\n for (int i = 2; i <= n; i++) {\n for (int j = i; j <= i*k && j <= target; j++) {\n for (int x = 1; x <= k; x++) {\n if (j-x >= 1) {\n dp[i][j] += dp[i-1][j-x];\n if (dp[i][j] >= mod) {\n dp[i][j] %= mod;\n }\n }\n }\n }\n }\n return dp[n][target]%mod;\n }\n}", + "title": "1155. Number of Dice Rolls With Target Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n dice and each die has k faces numbered from 1 to k . Given three integers n , k , and target , return the number of possible ways (out of the k n total ways) to roll the dice so the sum of the face-up numbers equals target . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n, k <= 30", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 6, target = 3\nOutput:1\nExplanation:You throw one die with 6 faces.\nThere is only one way to get a sum of 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 6, target = 7\nOutput:6\nExplanation:You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 30, target = 500\nOutput:222616187\nExplanation:The answer must be returned modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 782 ms (Top 50.50%) | Memory: 18.9 MB (Top 42.22%)\n\nclass Solution(object):\n def numRollsToTarget(self, n, k, target):\n \"\"\"\n :type n: int\n :type k: int\n :type target: int\n :rtype: int\n \"\"\"\n\n mem = {}\n\n def dfs(i,currSum):\n\n if currSum > target:\n return 0\n\n if i == n:\n if currSum == target:\n return 1\n return 0\n\n if (i,currSum) in mem:\n return mem[(i,currSum)]\n\n ans = 0\n for dicenumber in range(1,k+1):\n ans += dfs(i+1,currSum+dicenumber)\n\n mem[(i,currSum)] = ans\n\n return mem[(i,currSum)]\n\n return dfs(0,0) % (10**9 + 7)\n", + "title": "1155. Number of Dice Rolls With Target Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\" . Notice that you are left with some integers that are separated by at least one space: \"123\" , \"34\" , \"8\" , and \"34\" . Return the number of different integers after performing the replacement operations on word . Two integers are considered different if their decimal representations without any leading zeros are different.", + "description_images": [], + "constraints": [ + "1 <= word.length <= 1000", + "word consists of digits and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"a123bc34d8ef34\"\nOutput:3\nExplanation:The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:word = \"leet1234code234\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:word = \"a1b01c001\"\nOutput:1\nExplanation:The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 16.67%) | Memory: 44.5 MB (Top 21.67%)\nclass Solution {\n public int numDifferentIntegers(String word) {\n String[] arr = word.replaceAll(\"[a-zA-Z]\", \" \").split(\"\\\\s+\");\n Set set = new HashSet();\n\n for (String str : arr) {\n if (!str.isEmpty())\n set.add(String.valueOf(str.replaceAll(\"^0*\",\"\")));\n }\n\n return set.size();\n }\n}", + "title": "1805. Number of Different Integers in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\" . Notice that you are left with some integers that are separated by at least one space: \"123\" , \"34\" , \"8\" , and \"34\" . Return the number of different integers after performing the replacement operations on word . Two integers are considered different if their decimal representations without any leading zeros are different.", + "description_images": [], + "constraints": [ + "1 <= word.length <= 1000", + "word consists of digits and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"a123bc34d8ef34\"\nOutput:3\nExplanation:The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:word = \"leet1234code234\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:word = \"a1b01c001\"\nOutput:1\nExplanation:The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 85.83%) | Memory: 16.50 MB (Top 46.61%)\n\nclass Solution:\n def numDifferentIntegers(self, word: str) -> int:\n word = re.findall('(\\d+)', word)\n nums = [int(i) for i in word]\n \n return len(set(nums))\n", + "title": "1805. Number of Different Integers in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums .", + "description_images": [], + "constraints": [ + "For example, the GCD of the sequence [4,6,16] is 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,10,3]\nOutput:5\nExplanation:The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.", + "image": "https://assets.leetcode.com/uploads/2021/03/17/image-1.png" + }, + { + "text": "Example 2: Input:nums = [5,15,40,5,6]\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1084 ms (Top 15.1%) | Memory: 56.26 MB (Top 90.9%)\n\nclass Solution {\n int max = 0;\n Set exist = new HashSet();\n public int countDifferentSubsequenceGCDs(int[] nums) {\n getMax(nums);\n for(int num : nums) exist.add(num);\n int count = 0;\n for (int i=1;i<=max;i++) if(findGCD(i)) count++; // <---- findGCD\n return count;\n }\n public void getMax(int[] nums){\n for(int i : nums) max = Math.max(max, i);\n }\n public int gcd(int a, int b){\n return (a == 0) ? b : gcd(b % a, a);\n }\n\tpublic boolean findGCD(int num){\n int val = 0;\n for(int i = num; i <= max; i+= num)\n if(exist.contains(i)) val = gcd(i, val); // <---- gcd between two number\n return (val == num);\n }\n}", + "title": "1819. Number of Different Subsequences GCDs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums .", + "description_images": [], + "constraints": [ + "For example, the GCD of the sequence [4,6,16] is 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,10,3]\nOutput:5\nExplanation:The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.", + "image": "https://assets.leetcode.com/uploads/2021/03/17/image-1.png" + }, + { + "text": "Example 2: Input:nums = [5,15,40,5,6]\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5748 ms (Top 75.00%) | Memory: 34.4 MB (Top 21.43%)\nimport math\n\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n max_n = max(nums) + 1\n seen = set(nums)\n\n ans = 0\n for k in range(1, max_n): # iterate candidate k\n gcd = 0\n for multiple in range(k, max_n, k): # compute gcd of all array multiples of k\n if multiple in seen:\n gcd = math.gcd(gcd, multiple)\n if gcd == k: # check the candidate\n ans += 1\n return ans", + "title": "1819. Number of Different Subsequences GCDs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , count the total number of digit 1 appearing in all non-negative integers less than or equal to n .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution {\n\tint max(int a, int b){\n\t\tif(a>b)\n\t\t\treturn a;\n\t\telse\n\t\t\treturn b;\n\t}\n\n\tint min(int a, int b){\n\t\tif(a>b)\n\t\t\treturn b;\n\t\telse\n\t\t\treturn a;\n\t}\n\n\tpublic int countDigitOne(int n) {\n\t\tint c = 0;\n\t\tfor(int i=1; i<=n; i*=10){\n\t\t\tint divider = i*10;\n\t\t\tc += (n/divider)*i + min(max((n%divider -i + 1), 0),i);\n\t\t}\n\t\treturn c;\n\t}\n}\n\n// T.C. - O(log n)\n", + "title": "233. Number of Digit One", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , count the total number of digit 1 appearing in all non-negative integers less than or equal to n .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 7.05%) | Memory: 13.8 MB (Top 68.36%)\nclass Solution:\n def countDigitOne(self, n: int) -> int:\n num = str(n)[::-1]\n count = 0\n for i in range(len(num)-1, -1, -1):\n pv = 10**i # placevalue\n # mulitplicity of current digit (how many times it will be repeated)\n mul = n//(pv*10)\n rem = n % pv # remainder of current place value\n count += mul * pv # count for number of times 1 occurs in this place when the current digit is considered to be less than 1\n # if the current digit is greater than 1 then additional number of 1's are added to the count (equivalent to the place value)\n if num[i] > '1':\n count += pv\n # if the current digit is equal to 1 then additional number of 1's are added to the count (equivalent to the number modded by the current place value)\n if num[i] == '1':\n count += rem + 1\n return count\n", + "title": "233. Number of Digit One", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: Return the total number of distinct sequences possible . Since the answer may be very large, return it modulo 10^9 + 7 . Two sequences are considered distinct if at least one element is different.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:184\nExplanation:Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\nSome invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).\n(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).\n(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.\nThere are a total of 184 distinct sequences possible, so we return 184.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:22\nExplanation:Some of the possible sequences are (1, 2), (2, 1), (3, 2).\nSome invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\nThere are a total of 22 distinct sequences possible, so we return 22.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 361 ms (Top 36.73%) | Memory: 68 MB (Top 53.88%)\nclass Solution {\n static long[][] dp;\n public int distinctSequences(int n) {\n if(n==1) return 6;\n int mod = 1_000_000_007;\n dp =new long[][]\n {\n {0,1,1,1,1,1},\n {1,0,1,0,1,0},\n {1,1,0,1,1,0},\n {1,0,1,0,1,0},\n {1,1,1,1,0,1},\n {1,0,0,0,1,0}\n };\n for(int i=2;i int:\n return func(n,-1,-1)\n", + "title": "2318. Number of Distinct Roll Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary matrix grid , where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent ( 4-directionally ) land cell or walking off the boundary of the grid . Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput:3\nExplanation:There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput:0\nExplanation:All 1s are either on the boundary or can reach the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 84.26%) | Memory: 54.7 MB (Top 92.39%)\n\n class Solution {\n public int numEnclaves(int[][] grid) {\n int maxcount = 0;\n // if(grid.length==10)\n // {\n // return 3;\n // }\n for(int i = 0;i=grid.length||coldash>=grid[0].length||\n grid[rowdash][coldash]==0)\n {\n continue;\n }\n\n if(grid[rowdash][coldash]==1)\n {\n dfs(grid,rowdash,coldash);\n }\n\n }\n\n }\n}", + "title": "1020. Number of Enclaves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary matrix grid , where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent ( 4-directionally ) land cell or walking off the boundary of the grid . Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput:3\nExplanation:There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput:0\nExplanation:All 1s are either on the boundary or can reach the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def recursion(self, grid, row, col, m, n):\n if 0<=row int:\n m, n = len(grid), len(grid[0])\n if not m or not n:\n return 0\n # mark all boundary lands and neighbors with 0\n for row in range(m):\n self.recursion(grid, row, 0, m, n)\n self.recursion(grid, row, n-1, m, n)\n \n for col in range(n):\n self.recursion(grid, 0, col, m, m)\n self.recursion(grid, m-1, col, m, n)\n \n result = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n result += 1\n \n \n return result\n", + "title": "1020. Number of Enclaves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of dominoes , dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either ( a == c and b == d ), or ( a == d and b == c ) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length , and dominoes[i] is equivalent to dominoes[j] .", + "description_images": [], + "constraints": [ + "1 <= dominoes.length <= 4 * 10^4", + "dominoes[i].length == 2", + "1 <= dominoes[i][j] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = [[1,2],[2,1],[3,4],[5,6]]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /** Algorithm\n 1. Brute force cannot be used because of the set size.\n 2. Traverse the dominos and group & count them by min-max value.\n As pieces can be from 1 to 9, means their groups will be from 11 to 99.\n eg: [1,2] will be the same as [2,1]. Their value is 10 * (min(1,2)) + max(1,2)\n => 10 * 1 + 2 = 12.\n so pieces[12]++;\n 3. After finishing traversing, iterate over the counted pieces and if the count is\n > 1, calculate the combinations of X by 2.\n 4. The formula is n!/ (k! * (n-k)!)\n As n! can be very large, use the short version of it; (n * (n-1)) / 2. EG n= 40\n Eg: 40! simplify this(divide by 38!) 39 * 40\n -------- --------- \n 2! * (38!) 2\n 5. Return the total result \n */\n public int numEquivDominoPairs(int[][] dominoes) {\n int[] pieces = new int[100];\n for (int[] domino : dominoes) {\n pieces[10 * Math.min(domino[0], domino[1]) + Math.max(domino[0], domino[1])]++;\n }\n int pairs = 0;\n for (int i = 11; i <= 99; i++) {\n if (pieces[i] > 1) {\n pairs += getCombinations(pieces[i]);\n }\n }\n \n return pairs; \n }\n \n private int getCombinations(int n) {\n return (n * (n-1)) / 2;\n }\n}\n", + "title": "1128. Number of Equivalent Domino Pairs", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list of dominoes , dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either ( a == c and b == d ), or ( a == d and b == c ) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length , and dominoes[i] is equivalent to dominoes[j] .", + "description_images": [], + "constraints": [ + "1 <= dominoes.length <= 4 * 10^4", + "dominoes[i].length == 2", + "1 <= dominoes[i][j] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = [[1,2],[2,1],[3,4],[5,6]]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "import math\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n d=dict()\n for i in dominoes:\n i.sort() #Just to make everything equal and comparable\n if(tuple(i) in d.keys()): #In python, lists are unhashable so converted the list into tuples\n d[tuple(i)]+=1\n else:\n d[tuple(i)]=1\n count=0\n for x,y in d.items():\n if(y>1):\n\t\t\t\tcount+=y*(y-1)//2 #To check the number of pairs, if 2 elements pairs is 1,if 3 pair is 3 and so on.....formula is n*n-1/2\n return count\n \n\n\n", + "title": "1128. Number of Equivalent Domino Pairs", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed positive integer array nums and a positive integer k . A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Return the number of distinct excellent pairs . Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d . For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.", + "description_images": [], + "constraints": [ + "Both the numbers num1 and num2 exist in the array nums .", + "The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k , where OR is the bitwise OR operation and AND is the bitwise AND operation." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3\nOutput:5\nExplanation:The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1], k = 10\nOutput:0\nExplanation:There are no excellent pairs for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 785 ms (Top 5.01%) | Memory: 176.5 MB (Top 5.07%)\nclass Solution {\n public long countExcellentPairs(int[] nums, int k) {\n HashMap> map = new HashMap<>();\n for(int i : nums){\n int x = Integer.bitCount(i);\n map.putIfAbsent(x,new HashSet<>());\n map.get(x).add(i);\n }\n long ans = 0;\n HashSet vis = new HashSet<>();\n for(int i : nums){\n if(vis.contains(i)) continue;\n int need = Math.max(0,k-Integer.bitCount(i));\n for(int key : map.keySet()) // runs at max 30 times\n if(key >= need) ans += (long) map.get(key).size();\n vis.add(i);\n }\n return ans;\n }\n}", + "title": "2354. Number of Excellent Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed positive integer array nums and a positive integer k . A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Return the number of distinct excellent pairs . Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d . For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.", + "description_images": [], + "constraints": [ + "Both the numbers num1 and num2 exist in the array nums .", + "The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k , where OR is the bitwise OR operation and AND is the bitwise AND operation." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3\nOutput:5\nExplanation:The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1], k = 10\nOutput:0\nExplanation:There are no excellent pairs for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2052 ms (Top 44.44%) | Memory: 32.2 MB (Top 22.19%)\n\nclass Solution:\n def countExcellentPairs(self, nums: List[int], k: int) -> int:\n hamming = sorted([self.hammingWeight(num) for num in set(nums)])\n ans = 0\n for h in hamming:\n ans += len(hamming) - bisect.bisect_left(hamming, k - h)\n return ans\n\n def hammingWeight(self, n):\n ans = 0\n while n:\n n &= (n - 1)\n ans += 1\n return ans", + "title": "2354. Number of Excellent Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array flowers , where flowers[i] = [start i , end i ] means the i th flower will be in full bloom from start i to end i ( inclusive ). You are also given a 0-indexed integer array persons of size n , where persons[i] is the time that the i th person will arrive to see the flowers. Return an integer array answer of size n , where answer[i] is the number of flowers that are in full bloom when the i th person arrives.", + "description_images": [], + "constraints": [ + "1 <= flowers.length <= 5 * 10^4", + "flowers[i].length == 2", + "1 <= start i <= end i <= 10^9", + "1 <= persons.length <= 5 * 10^4", + "1 <= persons[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]\nOutput:[1,2,2,2]\nExplanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg" + }, + { + "text": "Example 2: Input:flowers = [[1,10],[3,3]], persons = [3,3,2]\nOutput:[2,2,1]\nExplanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 204 ms (Top 31.03%) | Memory: 131.5 MB (Top 7.83%)\nclass Solution {\npublic int[] fullBloomFlowers(int[][] flowers, int[] persons) {\n int n = persons.length;\n int[] result = new int[n];\n\n TreeMap treeMap = new TreeMap<>();\n // See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clean-Code\n for (int[] flower : flowers) {\n treeMap.put(flower[0], treeMap.getOrDefault(flower[0], 0) + 1);\n // use end + 1 instead of end\n treeMap.put(flower[1] + 1, treeMap.getOrDefault(flower[1] + 1, 0) - 1);\n }\n\n TreeMap sum = new TreeMap<>();\n int prev = 0;\n for (Map.Entry entry : treeMap.entrySet()) {\n prev += entry.getValue();\n sum.put(entry.getKey(), prev);\n }\n\n for (int i = 0; i < n; i++) {\n Map.Entry entry = sum.floorEntry(persons[i]);\n // if entry is null then result[i] = 0\n if (entry != null) result[i] = entry.getValue();\n }\n return result;\n }\n}", + "title": "2251. Number of Flowers in Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array flowers , where flowers[i] = [start i , end i ] means the i th flower will be in full bloom from start i to end i ( inclusive ). You are also given a 0-indexed integer array persons of size n , where persons[i] is the time that the i th person will arrive to see the flowers. Return an integer array answer of size n , where answer[i] is the number of flowers that are in full bloom when the i th person arrives.", + "description_images": [], + "constraints": [ + "1 <= flowers.length <= 5 * 10^4", + "flowers[i].length == 2", + "1 <= start i <= end i <= 10^9", + "1 <= persons.length <= 5 * 10^4", + "1 <= persons[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]\nOutput:[1,2,2,2]\nExplanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg" + }, + { + "text": "Example 2: Input:flowers = [[1,10],[3,3]], persons = [3,3,2]\nOutput:[2,2,1]\nExplanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 931 ms (Top 66.6%) | Memory: 45.16 MB (Top 22.2%)\n\nclass Solution:\n def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n #we ADD flowers in the order in which they start, but we remove them in the order they \n #end. For this reason, we sort the flowers by starting time but put them in a heap, \n #in which we remove them by ending time\n starts = sorted(flowers) #keep flowers untouched in case array should be constant\n blooming = [] #heap of active flowers\n answer = [-1] * len(people) #output array\n hours = [(people[i], i) for i in range(len(people))] #the people, ordered and indexed by their time\n hours.sort()\n\n i = 0 #going through starts\n for hour, person in hours:\n #add all flowers that have started\n while i < len(starts) and starts[i][0] <= hour:\n heappush(blooming, (starts[i][1], starts[i][0]))\n i += 1\n #now remove all flowers that have ended. Note that we only care about the absolute smallest, \n #and in python minheaps, that is always the first element - even if no other element's order \n #is guaranteed\n while blooming and blooming[0][0] < hour: #as long as the soonest to end blooming flower hasn't already stopped\n heappop(blooming)\n answer[person] = len(blooming)\n \n return answer", + "title": "2251. Number of Flowers in Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree and an integer distance . A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance . Return the number of good leaf node pairs in the tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 10 ].", + "1 <= Node.val <= 100", + "1 <= distance <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,4], distance = 3\nOutput:1\nExplanation:The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7], distance = 3\nOutput:2\nExplanation:The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e2.jpg" + }, + { + "text": "Example 3: Input:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput:1\nExplanation:The only good pair is [2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 86 ms (Top 15.89%) | Memory: 53.6 MB (Top 51.73%)\nclass Solution {\n static int res;\n public int countPairs(TreeNode root, int distance) {\n res=0;\n rec(root,distance);\n return res;\n }\n static List rec(TreeNode root,int dist){\n if(root==null){\n return new LinkedList();\n }\n List left=rec(root.left,dist);\n List right=rec(root.right,dist);\n if(left.size()==0&&right.size()==0){\n List temp=new LinkedList<>();\n temp.add(1);\n return temp;\n }\n for(int i:left){\n for(int j:right){\n if(i+j<=dist){\n res++;\n }\n }\n }\n List temp=new LinkedList<>();\n for(int i:left){\n temp.add(i+1);\n }\n for(int i:right){\n temp.add(i+1);\n }\n return temp;\n }\n}", + "title": "1530. Number of Good Leaf Nodes Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree and an integer distance . A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance . Return the number of good leaf node pairs in the tree.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 10 ].", + "1 <= Node.val <= 100", + "1 <= distance <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,4], distance = 3\nOutput:1\nExplanation:The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7], distance = 3\nOutput:2\nExplanation:The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e2.jpg" + }, + { + "text": "Example 3: Input:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput:1\nExplanation:The only good pair is [2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n adjList=defaultdict(list)\n leaves=[]\n ct=0\n \n [#undirected graph two way using parent and node in postorder style]\n def dfs(node, parent):\n if node:\n if not node.left and not node.right:\n leaves.append(node)\n adjList[node].append(parent)\n adjList[parent].append(node)\n dfs(node.left,node)\n dfs(node.right,node)\n \n [#construct graph and get all the leaves]\n dfs(root, None)\n \n #bfs from each leaf till we find another leaf\n for leaf in leaves:\n q=deque([(leaf,0)] )\n seen=set()\n while q:\n curr,dist = q.popleft()\n seen.add(curr)\n if dist>distance:\n break \n for nbr in adjList[curr]:\n if nbr and nbr not in seen:\n if nbr in leaves and dist+1<=distance:\n ct+=1\n q.append((nbr,dist+1))\n \n return ct//2", + "title": "1530. Number of Good Leaf Nodes Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , return the number of good pairs . A pair (i, j) is called good if nums[i] == nums[j] and i < j .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1,1,3]\nOutput:4\nExplanation:There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1]\nOutput:6\nExplanation:Each pair in the array aregood.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 85.5%) | Memory: 40.27 MB (Top 18.8%)\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int len =nums.length;\n int counter=0;\n for (int i =0;i int:\n res = 0\n\t\tnums_set = set(nums)\n nums_coppy = nums\n for number in nums_set:\n number_found = []\n deleted = 0\n while True:\n try:\n found = nums_coppy.index(number)\n nums_coppy.remove(number)\n if deleted > 0:\n number_found.append(found + deleted)\n else:\n number_found.append(found + deleted)\n deleted += 1\n except:\n comb = list(combinations(number_found, 2))\n res += len(comb)\n break\n return res\n", + "title": "1512. Number of Good Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s . A split is called good if you can split s into two non-empty strings s left and s right where their concatenation is equal to s (i.e., s left + s right = s ) and the number of distinct letters in s left and s right is the same. Return the number of good splits you can make in s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacaba\"\nOutput:2\nExplanation:There are 5 ways to split\"aacaba\"and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"\nOutput:1\nExplanation:Split the string as follows (\"ab\", \"cd\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSplits(String s) {\n int a[] = new int[26];\n int b[] = new int[26];\n int ds1=0,ds2=0;\n int count=0;\n for(int i=0;i int:\n one = set()\n two = set()\n dic = {}\n \n for i in s:\n dic[i] = dic.get(i, 0) + 1\n two.add(i)\n tot = 0\n \n for i in s:\n one.add(i)\n dic[i] -= 1\n if dic[i] == 0:\n two.remove(i)\n \n if len(one) == len(two):\n tot += 1\n return tot\n", + "title": "1525. Number of Good Ways to Split a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid , where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7 . Two paths are considered different if they do not have exactly the same sequence of visited cells.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[3,4]]\nOutput:8\nExplanation:The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.", + "image": "https://assets.leetcode.com/uploads/2022/05/10/griddrawio-4.png" + }, + { + "text": "Example 2: Input:grid = [[1],[2]]\nOutput:3\nExplanation:The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n long[][] dp;\n int mod = 1_000_000_007;\n public int countPaths(int[][] grid) {\n dp = new long[grid.length][grid[0].length];\n long sum=0L;\n for(int i=0;i=grid.length||j>=grid[0].length) return 0;\n if(grid[i][j]<=pre) return 0;\n if(dp[i][j]>0) return dp[i][j];\n long a = dfs(grid,i+1,j,grid[i][j]);\n long b = dfs(grid,i,j+1,grid[i][j]);\n long c = dfs(grid,i-1,j,grid[i][j]);\n long d = dfs(grid,i,j-1,grid[i][j]);\n dp[i][j] = (1+a+b+c+d)%mod;\n return dp[i][j];\n }\n}\n", + "title": "2328. Number of Increasing Paths in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid , where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7 . Two paths are considered different if they do not have exactly the same sequence of visited cells.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[3,4]]\nOutput:8\nExplanation:The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.", + "image": "https://assets.leetcode.com/uploads/2022/05/10/griddrawio-4.png" + }, + { + "text": "Example 2: Input:grid = [[1],[2]]\nOutput:3\nExplanation:The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2506 ms (Top 21.4%) | Memory: 118.67 MB (Top 7.1%)\n\nclass Solution:\n def __init__(self):\n self.dp = None\n self.di = [0, 0, -1, 1]\n self.dj = [-1, 1, 0, 0]\n self.mod = 1000000007\n \n def countPaths(self, grid):\n n = len(grid)\n m = len(grid[0])\n self.dp = [[0] * m for _ in range(n)]\n ans = 0\n for i in range(n):\n for j in range(m):\n ans = (ans + self.dfs(grid, i, j, -1)) % self.mod\n return ans\n \n def dfs(self, grid, i, j, prev):\n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= prev:\n return 0\n if self.dp[i][j] != 0:\n return self.dp[i][j]\n self.dp[i][j] = 1\n for k in range(4):\n self.dp[i][j] += self.dfs(grid, i + self.di[k], j + self.dj[k], grid[i][j])\n self.dp[i][j] %= self.mod\n return self.dp[i][j] % self.mod\n", + "title": "2328. Number of Increasing Paths in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 97.42%) | Memory: 50.7 MB (Top 93.44%)\nclass Solution {\n public int numIslands(char[][] grid) {\n int count = 0;\n int r = grid.length;\n int c = grid[0].length;\n for(int i=0;i=grid.length || j>=grid[0].length || grid[i][j]=='0'){\n return;\n }\n grid[i][j] = '0';\n dfs(grid,i,j+1);\n dfs(grid,i,j-1);\n dfs(grid,i+1,j);\n dfs(grid,i-1,j);\n }\n}", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 353 ms (Top 84.15%) | Memory: 28.7 MB (Top 5.01%)\n\nseen=set()\ndef dfs(i,j,m,n,grid):\n global seen\n if (i<0 or i>=m or j<0 or j>=n):return\n if (i,j) in seen:return\n seen.add((i,j))\n if grid[i][j]==\"1\":\n dfs(i,j+1,m,n,grid)\n dfs(i,j-1,m,n,grid)\n dfs(i+1,j,m,n,grid)\n dfs(i-1,j,m,n,grid)\n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n global seen\n m=len(grid) #no of rows\n n=len(grid[0]) #no of columns\n count=0\n for i in range(m):\n for j in range(n):\n if (i,j) not in seen and grid[i][j]==\"1\":\n dfs(i,j,m,n,grid)\n count+=1\n seen.clear()\n return count", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the i th row, consisting of '0' s and '1' s. '0' means the cell is empty, while '1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank .", + "description_images": [], + "constraints": [ + "The two devices are located on two different rows : r 1 and r 2 , where r 1 < r 2 .", + "For each row i where r 1 < i < r 2 , there are no security devices in the i th row." + ], + "examples": [ + { + "text": "Example 1: Input:bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\nOutput:8\nExplanation:Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0throw with any on the 3rdrow.\nThis is because the 2ndrow contains security devices, which breaks the second condition.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg" + }, + { + "text": "Example 2: Input:bank = [\"000\",\"111\",\"000\"]\nOutput:0\nExplanation:There does not exist two devices located on two different rows.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 22.34%) | Memory: 54.9 MB (Top 32.26%)\nclass Solution {\n public int numberOfBeams(String[] bank) {\n int ans = 0, pre = 0;\n for (int i = 0;i < bank.length; i ++) {\n int n = 0;\n for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++;\n if (n == 0) continue;\n ans += pre * n;;\n pre = n;\n }\n return ans;\n }\n}", + "title": "2125. Number of Laser Beams in a Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the i th row, consisting of '0' s and '1' s. '0' means the cell is empty, while '1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank .", + "description_images": [], + "constraints": [ + "The two devices are located on two different rows : r 1 and r 2 , where r 1 < r 2 .", + "For each row i where r 1 < i < r 2 , there are no security devices in the i th row." + ], + "examples": [ + { + "text": "Example 1: Input:bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\nOutput:8\nExplanation:Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0throw with any on the 3rdrow.\nThis is because the 2ndrow contains security devices, which breaks the second condition.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg" + }, + { + "text": "Example 2: Input:bank = [\"000\",\"111\",\"000\"]\nOutput:0\nExplanation:There does not exist two devices located on two different rows.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def numberOfBeams(self, bank):\n ans, pre = 0, 0\n for s in bank:\n n = s.count('1')\n if n == 0: continue\n ans += pre * n\n pre = n\n return ans\n", + "title": "2125. Number of Laser Beams in a Bank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a' , widths[1] is the width of 'b' , and so on. You are trying to write s across several lines, where each line is no longer than 100 pixels . Starting at the beginning of s , write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s , continue writing as many letters as you can on the second line. Continue this process until you have written all of s . Return an array result of length 2 where:", + "description_images": [], + "constraints": [ + "result[0] is the total number of lines.", + "result[1] is the width of the last line in pixels." + ], + "examples": [ + { + "text": "Example 1: Input:widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput:[3,60]\nExplanation:You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.", + "image": null + }, + { + "text": "Example 2: Input:widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput:[2,4]\nExplanation:You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 73.53%) | Memory: 41.8 MB (Top 76.89%)\nclass Solution {\n public int[] numberOfLines(int[] widths, String s) {\n int sum=0,count=0;\n for(int j=0;j100)\n {\n j--;\n count++;\n sum=0;\n continue;\n }\n }\n int[] arr = new int[2];\n arr[0]=count+1;\n arr[1]=sum;\n return arr;\n }\n}", + "title": "806. Number of Lines To Write String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a' , widths[1] is the width of 'b' , and so on. You are trying to write s across several lines, where each line is no longer than 100 pixels . Starting at the beginning of s , write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s , continue writing as many letters as you can on the second line. Continue this process until you have written all of s . Return an array result of length 2 where:", + "description_images": [], + "constraints": [ + "result[0] is the total number of lines.", + "result[1] is the width of the last line in pixels." + ], + "examples": [ + { + "text": "Example 1: Input:widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput:[3,60]\nExplanation:You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.", + "image": null + }, + { + "text": "Example 2: Input:widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput:[2,4]\nExplanation:You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfLines(self, w: List[int], s: str) -> List[int]:\n r=[0]*2\n px=0\n l=1\n for i in range(len(s)):\n px+=w[ord(s[i])-97]\n if px>100:\n l+=1\n px=w[ord(s[i])-97]\n \n print(ord(s[i]))\n r[0]=l\n r[1]=px\n return r\n ", + "title": "806. Number of Lines To Write String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2000", + "-10^6 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]\nOutput:2\nExplanation:The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]\nOutput:5\nExplanation:The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 72.27%) | Memory: 44.7 MB (Top 20.08%)\nclass Solution {\n public int findNumberOfLIS(int[] nums) {\n int N = nums.length;\n int []dp =new int[N];\n int []count = new int[N];\n Arrays.fill(dp,1);Arrays.fill(count,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j]+1;\n //inherit a new one\n count[i]=count[j];\n maxi = Math.max(dp[i],maxi);\n }else if(nums[j] < nums[i] && dp[j]+1 == dp[i]){\n //got one as same len, increase count\n count[i]+=count[j];\n }\n }\n }//for ends\n int maxlis=0;\n for(int i=0;i int:\n \n if not nums or len(nums) == 0:\n return 0\n \n def find_pos(sub, val):\n left, right = 0, len(sub) - 1\n while left < right:\n mid = (left + right) >> 1\n if sub[mid] >= val: \n right = mid\n else:\n left = mid + 1\n return left \n \n \n sub_list = []\n \n for val in nums:\n if len(sub_list) == 0 or val > sub_list[-1][-1][0]:\n # should append a new element at the end\n cur_count = sum([x[1] for x in sub_list[-1] if val > x[0]]) if len(sub_list) != 0 else 1\n sub_list.append([(val, cur_count)])\n else:\n # get the last number to turn it back to a LIS problem\n cur_sub = [array[-1][0] for array in sub_list]\n pos = find_pos(cur_sub, val)\n # if pos == 0, means it is smallest, no need to look the previous level and set it to be 1\n cur_count = sum([x[1] for x in sub_list[pos - 1] if val > x[0]]) if pos > 0 else 1\n sub_list[pos].append((val, cur_count))\n \n return sum([x[1] for x in sub_list[-1]])", + "title": "673. Number of Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s and an array of strings words , return the number of words[i] that is a subsequence of s . 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.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\nOutput:3\nExplanation:There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numMatchingSubseq(String s, String[] words) {\n int count = 0;\n Map map = new HashMap<>();\n for(String word : words){\n if(!map.containsKey(word)){\n map.put(word, 1);\n }\n else{\n map.put(word, map.get(word)+1);\n }\n }\n for(String word : map.keySet()){\n if(isSeq(word, s)){\n count += map.get(word);\n }\n }\n return count;\n }\n public boolean isSeq(String s1, String s2){\n int s1ind = 0;\n int s2ind = 0;\n int counter = 0;\n if(s1.length() > s2.length()){\n return false;\n }\n while(s1ind < s1.length() && s2ind < s2.length()){\n if(s1.charAt(s1ind) == s2.charAt(s2ind)){\n counter++;\n s1ind++;\n s2ind++;\n }\n else{\n s2ind++;\n }\n }\n return counter == s1.length();\n }\n}\n", + "title": "792. Number of Matching Subsequences", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s and an array of strings words , return the number of words[i] that is a subsequence of s . 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.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\nOutput:3\nExplanation:There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 851 ms (Top 55.45%) | Memory: 16.4 MB (Top 32.26%)\nclass Solution:\n def numMatchingSubseq(self, s: str, words: List[str]) -> int:\n word_dict = defaultdict(list)\n numMatch = 0\n # add words into bucket with key as order of the first letter\n for w in words:\n word_dict[ord(w[0])-ord('a')].append(w)\n # loop through the characters in s\n for c in s:\n qualified = word_dict[ord(c)-ord('a')]\n word_dict[ord(c)-ord('a')] = []\n for q in qualified:\n # if the word starts with the specified letter. i.e this is the last letter of the word\n if len(q) == 1:\n numMatch += 1\n else:\n word_dict[ord(q[1])-ord('a')].append(q[1:])\n return numMatch\n", + "title": "792. Number of Matching Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Given n , goal , and k , return the number of possible playlists that you can create . Since the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "Every song is played at least once .", + "A song can only be played again only if k other songs have been played." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, goal = 3, k = 1\nOutput:6\nExplanation:There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].", + "image": null + }, + { + "text": "Example 2: Input:n = 2, goal = 3, k = 0\nOutput:6\nExplanation:There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].", + "image": null + }, + { + "text": "Example 3: Input:n = 2, goal = 3, k = 1\nOutput:2\nExplanation:There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 77.87%) | Memory: 13.9 MB (Top 86.89%)\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n prev_p, cur_p = [0] * (n+1), [0] * (n+1)\n\n for i in range(k+1, goal+1):\n if i == k+1:\n prev_p[i] = math.factorial(n) // math.factorial(n-i)\n else:\n for j in range(k+1, min(i, n)+1):\n cur_p[j] = prev_p[j-1] * (n - j + 1) + prev_p[j] * (j-k)\n prev_p, cur_p = cur_p, [0] * (n+1)\n return prev_p[n] % (10**9 + 7)", + "title": "920. Number of Music Playlists", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges . The root of the tree is the node 0 , and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i] ). The edges array is given on the form edges[i] = [a i , b i ] , which means there is an edge between nodes a i and b i in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the i th node which have the same label as node i . A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "labels.length == n", + "labels is consisting of only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\nOutput:[2,1,1,1,1,1,1]\nExplanation:Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\nOutput:[4,2,1,1]\nExplanation:The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" + }, + { + "text": "Example 3: Input:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\nOutput:[3,2,1,1,1]", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] res;\n\n public int[] countSubTrees(int n, int[][] edges, String labels) {\n res = new int[n];\n Map> adjList = new HashMap<>();\n for (int i = 0; i < n; i++) {\n adjList.put(i, new ArrayList<>());\n }\n for (int[] edge : edges) {\n adjList.get(edge[0]).add(edge[1]);\n adjList.get(edge[1]).add(edge[0]);\n }\n postOrderDfs(adjList, labels, 0, -1);\n return res;\n }\n\n int[] postOrderDfs(Map> adjList, String labels, int n, int parent) {\n int[] chars = new int[26];\n chars[labels.charAt(n) - 'a']++;\n for (int next : adjList.get(n)) {\n if (next != parent) mergeArrCounts(chars, postOrderDfs(adjList, labels, next, n));\n }\n res[n] = chars[labels.charAt(n) - 'a'];\n return chars;\n }\n\n // Merge from B to A\n void mergeArrCounts(int[] A, int[] B) {\n for (int i = 0; i < 26; i++) {\n A[i] += B[i];\n }\n }\n}\n", + "title": "1519. Number of Nodes in the Sub-Tree With the Same Label", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges . The root of the tree is the node 0 , and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i] ). The edges array is given on the form edges[i] = [a i , b i ] , which means there is an edge between nodes a i and b i in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the i th node which have the same label as node i . A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "labels.length == n", + "labels is consisting of only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\nOutput:[2,1,1,1,1,1,1]\nExplanation:Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\nOutput:[4,2,1,1]\nExplanation:The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" + }, + { + "text": "Example 3: Input:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\nOutput:[3,2,1,1,1]", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n we can solve this using dfs based approach\n identify the root of the tree and start a dfs from there \n \"\"\"\n def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:\n graph_map = {i: set() for i in range(n)}\n for edge in edges:\n graph_map[edge[0]].add(edge[1])\n graph_map[edge[1]].add(edge[0])\n \n result = [None for _ in range(n)]\n \n visited = set()\n def dfs(index):\n visited.add(index)\n temp = [0 for _ in range(26)]\n temp[ord(labels[index])-97]+=1\n for idx in graph_map[index]:\n if idx not in visited:\n x = dfs(idx)\n temp = [a + b for a, b in zip(temp, x)]\n result[index] = temp[ord(labels[index])-97]\n return temp\n \n dfs(0)\n return result\n", + "title": "1519. Number of Nodes in the Sub-Tree With the Same Label", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a i , b i ] represents a connection between computers a i and b i . Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections . You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected . If it is not possible, return -1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= connections.length <= min(n * (n - 1) / 2, 10^5 )", + "connections[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated connections.", + "No two computers are connected by more than one cable." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput:1\nExplanation:Remove cable between computer 1 and 2 and place between computers 1 and 3.", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png" + }, + { + "text": "Example 2: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png" + }, + { + "text": "Example 3: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput:-1\nExplanation:There are not enough cables.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int makeConnected(int n, int[][] connections) {\n int m = connections.length;\n if(m < n - 1) return -1;\n UnionFind uf = new UnionFind(n);\n \n for(int[] connection: connections){\n uf.union(connection[0], connection[1]);\n }\n return uf.getIsolated();\n }\n}\nclass UnionFind{\n int[] root;\n int[] rank;\n int isolated;\n public UnionFind(int n){\n root = new int[n];\n rank = new int[n];\n for(int i = 0; i < n; i++){\n root[i] = i;\n rank[i] = 1;\n }\n isolated = 0;\n }\n public int find(int x){\n if(root[x] != x) root[x] = find(root[x]);\n return root[x];\n }\n public void union(int x, int y){\n int rootx = find(x);\n int rooty = find(y);\n if(rootx == rooty) return;\n if(rank[rootx] > rank[rooty]){\n root[rooty] = rootx;\n }else if(rank[rootx] < rank[rooty]){\n root[rootx] = rooty;\n }else{\n root[rootx] = rooty;\n rank[rooty] += 1;\n }\n }\n public int getIsolated(){\n for(int i = 0; i < root.length; i ++){\n if(root[i] == i) isolated++;\n }\n return isolated - 1;\n }\n}\n", + "title": "1319. Number of Operations to Make Network Connected", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a i , b i ] represents a connection between computers a i and b i . Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections . You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected . If it is not possible, return -1 .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= connections.length <= min(n * (n - 1) / 2, 10^5 )", + "connections[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated connections.", + "No two computers are connected by more than one cable." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput:1\nExplanation:Remove cable between computer 1 and 2 and place between computers 1 and 3.", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png" + }, + { + "text": "Example 2: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png" + }, + { + "text": "Example 3: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput:-1\nExplanation:There are not enough cables.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 772 ms (Top 55.10%) | Memory: 34.3 MB (Top 72.08%)\nclass Solution(object):\n def __init__(self):\n self.parents = []\n self.count = []\n\n def makeConnected(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n if len(connections) < n-1:\n return -1\n self.parents = [i for i in range(n)]\n self.count = [1 for _ in range(n)]\n for connection in connections:\n a, b = connection[0], connection[1]\n self.union(a, b)\n return len({self.find(i) for i in range(n)}) - 1\n\n def find(self, node):\n \"\"\"\n :type node: int\n :rtype: int\n \"\"\"\n while(node != self.parents[node]):\n node = self.parents[node];\n return node\n\n def union(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: None\n \"\"\"\n a_parent, b_parent = self.find(a), self.find(b)\n a_size, b_size = self.count[a_parent], self.count[b_parent]\n\n if a_parent != b_parent:\n if a_size < b_size:\n self.parents[a_parent] = b_parent\n self.count[b_parent] += a_size\n else:\n self.parents[b_parent] = a_parent\n self.count[a_parent] += b_size", + "title": "1319. Number of Operations to Make Network Connected", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array orders , where each orders[i] = [price i , amount i , orderType i ] denotes that amount i orders have been placed of type orderType i at the price price i . The orderType i is: Note that orders[i] represents a batch of amount i independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i . There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input . Since this number can be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "0 if it is a batch of buy orders, or", + "1 if it is a batch of sell orders." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\nOutput:6\nExplanation:Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rdorder is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4thorder is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex1.png" + }, + { + "text": "Example 2: Input:orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\nOutput:999999984\nExplanation:Here is what happens with the orders:\n- 109orders of type sell with price 7 are placed. There are no buy orders, so the 109orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109+ 7).", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n PriorityQueue buyBackLog;\n PriorityQueue sellBackLog;\n \n static int MOD = 1_000_000_007;\n \n \n public int getNumberOfBacklogOrders(int[][] orders) {\n \n //max heap, heapify on price\n buyBackLog = new PriorityQueue((a, b) -> (b.price - a.price));\n //min heap, heapify on price\n sellBackLog = new PriorityQueue((a, b) -> (a.price - b.price));\n \n \n //handle all order\n for(int[] order : orders){\n int price = order[0];\n int quantity = order[1];\n int orderType = order[2];\n \n if(orderType == 0){\n //buy order \n handleBuyOrder(new Order(price, quantity));\n \n }else if(orderType == 1){ \n //sell order\n handleSellOrder(new Order(price, quantity));\n }\n }\n \n long counts = 0L;\n \n //count buy backlog\n while(!buyBackLog.isEmpty()){\n counts += buyBackLog.remove().quantity; \n counts %= MOD;\n }\n \n //count sell backlog\n while(!sellBackLog.isEmpty()){\n counts += sellBackLog.remove().quantity; \n counts %= MOD;\n }\n \n \n return (int) (counts % MOD);\n }\n \n \n \n \n private void handleBuyOrder(Order buyOrder){\n //just add buyorder, if there is no sell back log\n if(sellBackLog.isEmpty()){\n buyBackLog.add(buyOrder);\n return;\n }\n \n \n while(!sellBackLog.isEmpty() && buyOrder.price >= sellBackLog.peek().price && buyOrder.quantity > 0){\n //selloder with minumum price\n Order sellOrder = sellBackLog.remove();\n \n if(buyOrder.quantity >= sellOrder.quantity){\n buyOrder.quantity -= sellOrder.quantity;\n sellOrder.quantity = 0;\n } else {\n //decrement sell order, add remaining sellorder\n sellOrder.quantity -= buyOrder.quantity;\n sellBackLog.add(sellOrder);\n \n buyOrder.quantity = 0;\n }\n }\n \n //add reaming buyorder\n if(buyOrder.quantity > 0){\n buyBackLog.add(buyOrder);\n }\n }\n \n \n private void handleSellOrder(Order sellOrder){\n //just add sell order, if there is no buy backlog\n if(buyBackLog.isEmpty()){\n sellBackLog.add(sellOrder);\n return;\n }\n \n \n while(!buyBackLog.isEmpty() && buyBackLog.peek().price >= sellOrder.price && sellOrder.quantity > 0){\n //buy order with maximum price\n Order buyOrder = buyBackLog.remove();\n \n if(sellOrder.quantity >= buyOrder.quantity){\n sellOrder.quantity -= buyOrder.quantity;\n buyOrder.quantity = 0;\n \n }else{\n //decrement buy order quantity, add remaining buyorder\n buyOrder.quantity -= sellOrder.quantity;\n buyBackLog.add(buyOrder);\n \n sellOrder.quantity = 0;\n }\n }\n \n //add remaining sell order\n if(sellOrder.quantity > 0){\n sellBackLog.add(sellOrder);\n }\n }\n}\n\nclass Order{\n int price;\n int quantity;\n \n public Order(int price, int quantity){\n this.price = price;\n this.quantity = quantity;\n }\n}\n", + "title": "1801. Number of Orders in the Backlog", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 2D integer array orders , where each orders[i] = [price i , amount i , orderType i ] denotes that amount i orders have been placed of type orderType i at the price price i . The orderType i is: Note that orders[i] represents a batch of amount i independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i . There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input . Since this number can be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "0 if it is a batch of buy orders, or", + "1 if it is a batch of sell orders." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\nOutput:6\nExplanation:Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rdorder is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4thorder is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex1.png" + }, + { + "text": "Example 2: Input:orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\nOutput:999999984\nExplanation:Here is what happens with the orders:\n- 109orders of type sell with price 7 are placed. There are no buy orders, so the 109orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109+ 7).", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 689 ms (Top 70.7%) | Memory: 55.89 MB (Top 32.0%)\n\nclass Solution:\n def getNumberOfBacklogOrders(self, orders):\n b, s = [], []\n heapq.heapify(b)\n heapq.heapify(s)\n \n for p,a,o in orders:\n if o == 0:\n heapq.heappush(b, [-p, a])\n \n elif o == 1:\n heapq.heappush(s, [p, a])\n \n # Check \"good\" condition\n while s and b and s[0][0] <= -b[0][0]:\n a1, a2 = b[0][1], s[0][1]\n \n if a1 > a2:\n b[0][1] -= a2\n heapq.heappop(s)\n elif a1 < a2:\n s[0][1] -= a1\n heapq.heappop(b)\n else:\n heapq.heappop(b)\n heapq.heappop(s)\n \n count = sum([a for p,a in b]) + sum([a for p,a in s])\n return count % (10**9 + 7)", + "title": "1801. Number of Orders in the Backlog", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles , where rectangles[i] = [width i , height i ] denotes the width and height of the i th rectangle. Two rectangles i and j ( i < j ) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if width i /height i == width j /height j (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles .", + "description_images": [], + "constraints": [ + "n == rectangles.length", + "1 <= n <= 10^5", + "rectangles[i].length == 2", + "1 <= width i , height i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput:6\nExplanation:The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[4,5],[7,8]]\nOutput:0\nExplanation:There are no interchangeable pairs of rectangles.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 81.13%) | Memory: 99.50 MB (Top 16.9%)\n\nclass Solution {\n \n public long interchangeableRectangles(int[][] rectangles) {\n Map hash = new HashMap<>();\n \n for (int i = 0; i < rectangles.length; i++) {\n Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]);\n \n hash.put(tmp, hash.getOrDefault(tmp, 0L) + 1);\n }\n \n long ans = 0;\n for (Map.Entry entry : hash.entrySet()) {\n if (entry.getValue() > 1) {\n Long n = entry.getValue();\n ans += (n * (n - 1)) / 2;\n }\n }\n \n return ans;\n }\n}\n", + "title": "2001. Number of Pairs of Interchangeable Rectangles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles , where rectangles[i] = [width i , height i ] denotes the width and height of the i th rectangle. Two rectangles i and j ( i < j ) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if width i /height i == width j /height j (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles .", + "description_images": [], + "constraints": [ + "n == rectangles.length", + "1 <= n <= 10^5", + "rectangles[i].length == 2", + "1 <= width i , height i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput:6\nExplanation:The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[4,5],[7,8]]\nOutput:0\nExplanation:There are no interchangeable pairs of rectangles.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n ratios = defaultdict(int)\n for x, y in rectangles:\n ratios[x/y] += 1\n res = 0\n for val in ratios.values():\n res += (val*(val-1)//2)\n return res\n", + "title": "2001. Number of Pairs of Interchangeable Rectangles", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digit strings nums and a digit string target , return the number of pairs of indices (i, j) (where i != j ) such that the concatenation of nums[i] + nums[j] equals target .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "1 <= nums[i].length <= 100", + "2 <= target.length <= 100", + "nums[i] and target consist of digits.", + "nums[i] and target do not have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\nOutput:4\nExplanation:Valid pairs are:\n- (0, 1): \"777\" + \"7\"\n- (1, 0): \"7\" + \"777\"\n- (2, 3): \"77\" + \"77\"\n- (3, 2): \"77\" + \"77\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\nOutput:2\nExplanation:Valid pairs are:\n- (0, 1): \"123\" + \"4\"\n- (2, 3): \"12\" + \"34\"", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"1\",\"1\",\"1\"], target = \"11\"\nOutput:6\nExplanation:Valid pairs are:\n- (0, 1): \"1\" + \"1\"\n- (1, 0): \"1\" + \"1\"\n- (0, 2): \"1\" + \"1\"\n- (2, 0): \"1\" + \"1\"\n- (1, 2): \"1\" + \"1\"\n- (2, 1): \"1\" + \"1\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfPairs(String[] nums, String target) {\n \n HashMap map = new HashMap<>();\n for (int i = 0; i board) {\n int M = (int)1e9+7;\n int m = board.size();\n int n = board.get(0).length();\n int[][] dp = new int[m][n];\n int[][] ways = new int[m][n];\n ways[0][0]=1; // base case.\n int[][] dirs = {{-1, 0}, {0, -1}, {-1, -1}}; // all 3 ways where we can travel.\n for (int i=0;idp[i][j]){\n dp[i][j]=cur+dp[x][y];\n ways[i][j]=0;\n }\n if (cur+dp[x][y]==dp[i][j]){\n ways[i][j]+=ways[x][y];\n ways[i][j]%=M;\n }\n }\n }\n }\n return new int[]{dp[m-1][n-1], ways[m-1][n-1]};\n }\n}", + "title": "1301. Number of Paths with Max Score", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S' . You need to reach the top left square marked with the character 'E' . The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X' . In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7 . In case there is no path, return [0, 0] .", + "description_images": [], + "constraints": [ + "2 <= board.length == board[i].length <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"E23\",\"2X2\",\"12S\"]\nOutput:[7,1]", + "image": null + }, + { + "text": "Example 2: Input:board = [\"E12\",\"1X1\",\"21S\"]\nOutput:[4,2]", + "image": null + }, + { + "text": "Example 3: Input:board = [\"E11\",\"XXX\",\"11S\"]\nOutput:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 321 ms (Top 53.09%) | Memory: 26.5 MB (Top 8.64%)\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n\n ## Basic information: height and width of board\n h, w = len(board), len(board[0])\n\n # ----------------------------------------------------------------------------\n\n # Use pathon native cahce as memoization for DP\n @cache\n def visit(i, j):\n\n if i == h-1 and j == w-1:\n ## Base case:\n\n # score for start coordinate = 0\n # paht count for start coordinate = 1\n return 0, 1\n\n elif i >= w or j >= h or board[i][j] == 'X':\n\n ## Base case:\n # Out-of-boundary, or meet obstacle\n return 0, 0\n\n ## General case:\n # update from three possible preivous moves from right, down, and diagonal\n\n right_score, right_path_count = visit(i, j+1)\n down_score, down_path_count = visit(i+1, j)\n diag_score, diag_path_count = visit(i+1, j+1)\n\n max_prevScore = max(right_score, down_score, diag_score)\n\n cur_path_count = 0\n cur_score = int(board[i][j]) if board[i][j] != \"E\" else 0\n\n if right_score == max_prevScore : cur_path_count += right_path_count\n if down_score == max_prevScore : cur_path_count += down_path_count\n if diag_score == max_prevScore : cur_path_count += diag_path_count\n\n return max_prevScore + cur_score, cur_path_count\n # ----------------------------------------------------------------------------\n\n ## Remark: Remember to take modulo by constant, this is defined by description\n CONST = 10**9 + 7\n maxScore, validPathCount = visit(0, 0)\n\n return [maxScore % CONST, validPathCount % CONST] if validPathCount else [0, 0]", + "title": "1301. Number of Paths with Max Score", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On day 1 , one person discovers a secret. You are given an integer delay , which means that each person will share the secret with a new person every day , starting from delay days after discovering the secret. You are also given an integer forget , which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n , return the number of people who know the secret at the end of day n . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= delay < forget <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, delay = 2, forget = 4\nOutput:5\nExplanation:Day 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)", + "image": null + }, + { + "text": "Example 2: Input:n = 4, delay = 1, forget = 3\nOutput:6\nExplanation:Day 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 38.08%) | Memory: 41.3 MB (Top 54.72%)\nclass Solution {\n public int peopleAwareOfSecret(int n, int delay, int forget) {\n long mod = 1000000007L;\n long[] shares = new long[n + 1];\n long[] forgets = new long[n + 1];\n\n if (delay < n) {\n shares[delay + 1] = 1;\n }\n if (forget < n) {\n forgets[forget + 1] = 1;\n }\n\n long shareToday = 0;\n long peopleKnow = 1;\n for (int i = delay; i <= n; i++) {\n shareToday += shares[i] % mod;\n shareToday -= forgets[i] % mod;\n\n peopleKnow -= forgets[i] % mod;\n peopleKnow += shareToday % mod;\n\n if (i + delay < n + 1) {\n shares[i + delay] += shareToday % mod;\n }\n if (i + forget < n + 1) {\n forgets[i + forget] += shareToday % mod;\n }\n }\n\n return (int) (peopleKnow % mod);\n }\n}", + "title": "2327. Number of People Aware of a Secret", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On day 1 , one person discovers a secret. You are given an integer delay , which means that each person will share the secret with a new person every day , starting from delay days after discovering the secret. You are also given an integer forget , which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n , return the number of people who know the secret at the end of day n . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= delay < forget <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, delay = 2, forget = 4\nOutput:5\nExplanation:Day 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)", + "image": null + }, + { + "text": "Example 2: Input:n = 4, delay = 1, forget = 3\nOutput:6\nExplanation:Day 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)", + "image": null + } + ], + "follow_up": null, + "solution": "\n```class Solution:\n def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n table = [0]*(forget+1)\n table[1] = 1\n days = 1\n while days<=n-1:\n count = 0\n for k in range(forget-1,-1,-1):\n if k+1>delay:\n table[k+1] = table[k]\n count+=table[k]\n elif k+1<=delay:\n table[k+1] = table[k]\n table[1] = count\n days+=1\n count = 0\n for k in range(1,forget+1):\n count+=table[k]\n return count%(pow(10,9)+7)\n\t\t\nTC---O(forget*n)\nsc---O(forget)\n \n", + "title": "2327. Number of People Aware of a Secret", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b , and city b is connected directly with city c , then city a is connected indirectly with city c . A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the i th city and the j th city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces .", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n == isConnected.length", + "n == isConnected[i].length", + "isConnected[i][j] is 1 or 0 .", + "isConnected[i][i] == 1", + "isConnected[i][j] == isConnected[j][i]" + ], + "examples": [ + { + "text": "Example 1: Input:isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg" + }, + { + "text": "Example 2: Input:isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 22.65%) | Memory: 42.7 MB (Top 99.36%)\nclass Solution {\n public int findCircleNum(int[][] isConnected) {\n int size = isConnected.length;\n boolean[] isCheck = new boolean[size+1];\n int ans = 0;\n\n for(int i=1; i<=size; i++){\n\n if(!isCheck[i]){ // Doing BFS if it's false in isCheck[]\n Queue q = new LinkedList<>();\n q.add(i);\n ans++; // No. of queue = No. of Graphs\n\n while(!q.isEmpty()){\n int temp = q.remove();\n isCheck[temp] = true;\n\n for(int j=0; j int:\n graph = defaultdict(list)\n for i,x in enumerate(isConnected):\n for j,n in enumerate(x):\n if j!=i and n == 1:\n graph[i].append(j)\n \n visit = set()\n \n def dfs(node):\n if node not in graph:\n return \n for neighbor in graph[node]:\n if neighbor not in visit:\n visit.add(neighbor)\n dfs(neighbor)\n count = 0\n for i in range(len(isConnected)):\n if i in visit:\n continue\n count+=1\n dfs(i)\n return count\n", + "title": "547. Number of Provinces", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1373 ms (Top 10.1%) | Memory: 52.32 MB (Top 27.9%)\n\nclass RecentCounter {\n ArrayList calls ;\n public RecentCounter() {\n calls = new ArrayList();\n }\n \n public int ping(int t) {\n calls.add(t);\n int count = 0;\n for(Integer call:calls){\n if( t-call<=3000) count++;\n }\n return count;\n \n }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */", + "title": "933. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 676 ms (Top 17.97%) | Memory: 19.4 MB (Top 70.89%)\nclass RecentCounter:\n # Here we use list to store ping details.\n def __init__(self):\n self.store = []\n\n def ping(self, t: int) -> int:\n # Basically what we need to return is how many pings fall in the range(t-3000, t).\n # So here we append every t. Now in loop how many t from left side < t-3000, we just pop them\n # and return the length of the list, which'd contain elements in range(t-3000, t).\n # And since every t is going to greater than previous, we don't need to think about duplicates.\n\n self.store.append(t)\n\n while self.store[0] < t-3000:\n self.store.pop(0)\n\n return len(self.store)", + "title": "933. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array rectangles where rectangles[i] = [l i , w i ] represents the i th rectangle of length l i and width w i . You can cut the i th rectangle to form a square with a side length of k if both k <= l i and k <= w i . For example, if you have a rectangle [4,6] , you can cut it to get a square with a side length of at most 4 . Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen .", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 1000", + "rectangles[i].length == 2", + "1 <= l i , w i <= 10^9", + "l i != w i" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[5,8],[3,9],[5,12],[16,5]]\nOutput:3\nExplanation:The largest squares you can get from each rectangle are of lengths [5,3,5,5].\nThe largest possible square is of length 5, and you can get it out of 3 rectangles.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[2,3],[3,7],[4,3],[3,7]]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countGoodRectangles(int[][] rectangles) {\n List list=new LinkedList();\n int max=0,count=0;\n for(int i = 0 ; i < rectangles.length ; i++){\n if(rectangles[i][0]>rectangles[i][1]){\n list.add(rectangles[i][1]);\n if(max int:\n\n #Runtime: 184 ms, faster than 65.71% of Python3 online submissions\n #Memory Usage: 14.9 MB, less than 39.90% of Python3 online submissions\n\n res = []\n\n minSide = 0\n maxLen = 0\n\n for l, w in rectangles:\n\n minSide = min(l, w) #Gets minSide of each rectangle\n\n if minSide > maxLen: #Checks if rectangle holds new maxLen\n maxLen = minSide #Tracks the current maxLen\n\n res.append(minSide) #Holds each rectangles minSIde\n\n return res.count(maxLen)#Returns the count of rectangles whos minSide is equal to maxLen\n", + "title": "1725. Number Of Rectangles That Can Form The Largest Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n , and an array edges where each edges[i] = [u i , v i , weight i ] denotes that there is an edge between nodes u i and v i with weight equal to weight i . A path from node start to node end is a sequence of nodes [z 0 , z 1 , z 2 , ..., z k ] such that z 0 = start and z k = end and there is an edge between z i and z i+1 where 0 <= i <= k-1 . The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x . A restricted path is a path that also satisfies that distanceToLastNode(z i ) > distanceToLastNode(z i+1 ) where 0 <= i <= k-1 . Return the number of restricted paths from node 1 to node n . Since that number may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "n - 1 <= edges.length <= 4 * 10^4", + "edges[i].length == 3", + "1 <= u i , v i <= n", + "u i != v i", + "1 <= weight i <= 10^5", + "There is at most one edge between any two nodes.", + "There is at least one path between any two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput:3\nExplanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput:1\nExplanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The only restricted path is 1 --> 3 --> 7.", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 10.95%) | Memory: 130.5 MB (Top 57.67%)\nclass Solution {\n int dp[];\n //We use memoization\n public int countRestrictedPaths(int n, int[][] edges) {\n int[] dist = new int[n+1];\n dp = new int[n+1];\n Arrays.fill(dp,-1);\n Map> graph = new HashMap<>();\n //Create the graph from input edges\n for(int[] e : edges){\n graph.putIfAbsent(e[0], new HashMap<>());\n graph.putIfAbsent(e[1], new HashMap<>());\n graph.get(e[0]).put(e[1],e[2]);\n graph.get(e[1]).put(e[0],e[2]);\n }\n //Single source shortest distance - something like Dijkstra's\n PriorityQueue pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));\n int[] base = new int[2];\n base[0]=n;\n pq.offer(base);\n while(!pq.isEmpty()){\n int[] currNode = pq.poll();\n\n for(Map.Entry neighbour: graph.get(currNode[0]).entrySet()){\n int node = neighbour.getKey();\n int d = neighbour.getValue()+currNode[1];\n if(node==n) continue;\n //Select only those neighbours, whose new distance is less than existing distance\n //New distance = distance of currNode from n + weight of edge between currNode and neighbour\n\n if( dist[node]==0 || d < dist[node]){\n int[] newNode = new int[2];\n newNode[0]=node;\n newNode[1]=d;\n pq.offer(newNode);\n dist[node]= d;\n }\n }\n }\n\n return find(1,graph,n,dist);\n }\n //This method traverses all the paths from source node to n though it's neigbours\n private int find(int node, Map> graph, int n, int[] dist ){\n if(node==n){\n return 1;\n }\n\n //Memoization avoid computaion of common subproblems.\n if(dp[node]!=-1) return dp[node];\n\n int ans = 0;\n for(Map.Entry neighbour: graph.get(node).entrySet()){\n int currNode = neighbour.getKey();\n int d = dist[currNode];\n if( dist[node] > d){\n ans = (ans + find(currNode, graph, n, dist)) % 1000000007;\n }\n }\n\n return dp[node] = ans;\n }\n}", + "title": "1786. Number of Restricted Paths From First to Last Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n , and an array edges where each edges[i] = [u i , v i , weight i ] denotes that there is an edge between nodes u i and v i with weight equal to weight i . A path from node start to node end is a sequence of nodes [z 0 , z 1 , z 2 , ..., z k ] such that z 0 = start and z k = end and there is an edge between z i and z i+1 where 0 <= i <= k-1 . The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x . A restricted path is a path that also satisfies that distanceToLastNode(z i ) > distanceToLastNode(z i+1 ) where 0 <= i <= k-1 . Return the number of restricted paths from node 1 to node n . Since that number may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "n - 1 <= edges.length <= 4 * 10^4", + "edges[i].length == 3", + "1 <= u i , v i <= n", + "u i != v i", + "1 <= weight i <= 10^5", + "There is at most one edge between any two nodes.", + "There is at least one path between any two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput:3\nExplanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput:1\nExplanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The only restricted path is 1 --> 3 --> 7.", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n dct_nd = {}\n dist_to_n = {}\n queue = deque() # from n-node to 1-node\n visited = set()\n \n # 1 step: create dictionary with nodes and nodes' distances to n\n\n # create dictionary with format (weight, node_to)\n # heap will automatically sort weight and node_to in ascending order\n for l, r, w in edges:\n dct_nd[l] = dct_nd.get(l, []) + [(w, r)]\n dct_nd[r] = dct_nd.get(r, []) + [(w, l)]\n \n dist_to_n[n] = 0\n queue.append(n)\n visited.add(n)\n \n hpf = dct_nd[n].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change\n heapify(hpf)\n while hpf:\n el_w, el_nd = heappop(hpf)\n if el_nd in visited: continue\n \n dist_to_n[el_nd] = el_w\n visited.add(el_nd)\n queue.append(el_nd)\n\n if el_nd == 1: break # you don't need to traverse more if you've reached 1-node\n # other distances will be more than distance of 1-node\n for (i_w, i_nd) in dct_nd[el_nd]:\n if i_nd not in visited:\n heappush(hpf, (el_w + i_w, i_nd))\n # step 1: end\n\n # add to dictionary one more field: number of routes to n\n dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}\n dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 1\n \n # step 2: Dynamic Programming\n visited.clear()\n while queue:\n # start from n and traverse futher and futher\n nd_prv = queue.popleft()\n visited.add(nd_prv)\n for (w_cur, nd_cur) in dct_nd[nd_prv]:\n if nd_cur not in visited and \\\n nd_cur in dist_to_n.keys() and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:\n # to current node add number of routes from previous node\n dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]\n # !!! careful !!! you need to add modulo operation (as said in the task)\n dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9+7))\n # step 2: End\n \n return dist_to_n[1][1] # return number of routes for 1-node\n", + "title": "1786. Number of Restricted Paths From First to Last Node", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return the number of segments in the string . A segment is defined to be a contiguous sequence of non-space characters .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 300", + "s consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\" .", + "The only space character in s is ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello, my name is John\"\nOutput:5\nExplanation:The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"Hello\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 35.26%)\nclass Solution {\n public int countSegments(String s) {\n int length = 0;\n boolean flag = false;\n\n for(Character c : s.toCharArray()) {\n if(c == ' ' && flag) {\n length++;\n flag = !flag;\n } else if(c != ' ') {\n flag = true;\n }\n }\n\n return flag ? length + 1 : length;\n }\n}", + "title": "434. Number of Segments in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the number of segments in the string . A segment is defined to be a contiguous sequence of non-space characters .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 300", + "s consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\" .", + "The only space character in s is ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello, my name is John\"\nOutput:5\nExplanation:The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"Hello\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countSegments(self, s: str) -> int:\n return len(s.split())\n", + "title": "434. Number of Segments in a String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given n points on a 1-D plane, where the i th point (from 0 to n-1 ) is at x = i , find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates . The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments . Since this number can be huge, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= k <= n-1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2\nOutput:5\nExplanation:The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.", + "image": "https://assets.leetcode.com/uploads/2020/09/07/ex1.png" + }, + { + "text": "Example 2: Input:n = 3, k = 1\nOutput:3\nExplanation:The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 7\nOutput:796297179\nExplanation:The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109+ 7 gives us 796297179.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer[][][] memo;\n int n;\n public int numberOfSets(int n, int k) {\n this.n = n;\n this.memo = new Integer[n+1][k+1][2];\n return dp(0, k, 1);\n }\n int dp(int i, int k, int isStart) {\n if (memo[i][k][isStart] != null) return memo[i][k][isStart];\n if (k == 0) return 1; // Found a way to draw k valid segments\n if (i == n) return 0; // Reach end of points\n\n int ans = dp(i+1, k, isStart); // Skip ith point\n if (isStart == 1)\n ans += dp(i+1, k, 0); // Take ith point as start\n else\n ans += dp(i, k-1, 1); // Take ith point as end\n\n return memo[i][k][isStart] = ans % 1_000_000_007;\n }\n}\n", + "title": "1621. Number of Sets of K Non-Overlapping Line Segments", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given n points on a 1-D plane, where the i th point (from 0 to n-1 ) is at x = i , find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates . The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments . Since this number can be huge, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= k <= n-1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2\nOutput:5\nExplanation:The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.", + "image": "https://assets.leetcode.com/uploads/2020/09/07/ex1.png" + }, + { + "text": "Example 2: Input:n = 3, k = 1\nOutput:3\nExplanation:The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 7\nOutput:796297179\nExplanation:The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109+ 7 gives us 796297179.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @lru_cache(None)\n def dp(i, k, isStart):\n if k == 0: return 1 # Found a way to draw k valid segments\n if i == n: return 0 # Reach end of points\n ans = dp(i+1, k, isStart) # Skip ith point\n if isStart:\n ans += dp(i+1, k, False) # Take ith point as start\n else:\n ans += dp(i, k-1, True) # Take ith point as end\n return ans % MOD\n return dp(0, k, True)\n", + "title": "1621. Number of Sets of K Non-Overlapping Line Segments", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the i th day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1 . The first day of the period is exempted from this rule. Return the number of smooth descent periods .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "1 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,2,1,4]\nOutput:7\nExplanation:There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition.", + "image": null + }, + { + "text": "Example 2: Input:prices = [8,6,7,7]\nOutput:4\nExplanation:There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.", + "image": null + }, + { + "text": "Example 3: Input:prices = [1]\nOutput:1\nExplanation:There is 1 smooth descent period: [1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 24.69%) | Memory: 88.4 MB (Top 55.38%)\nclass Solution {\n public long getDescentPeriods(int[] prices) {\n int i=0;\n int j=1;\n long ans=1;\n while(j int: \n def calculate(k,ans):\n if k>1:\n ans+=((k-1)*(k))//2 \n\t\t\t\t#Sum of Natural Numbers\n return ans\n else:\n return ans\n end = 0\n start = 0\n prev= sys.maxsize\n k= 0\n ans = 0\n while end1:\n ans = calculate(k,ans)\n\t\t\t\n return ans+len(prices)\n", + "title": "2110. Number of Smooth Descent Periods of a Stock", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An array is squareful if the sum of every pair of adjacent elements is a perfect square . Given an integer array nums, return the number of permutations of nums that are squareful . Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 12", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,17,8]\nOutput:2\nExplanation:[1,8,17] and [17,8,1] are the valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42 MB (Top 28.32%)\nclass Solution {\n int count;\n public int numSquarefulPerms(int[] nums) {\n int n = nums.length;\n if(n<2)\n return count;\n backtrack(nums,n,0);\n return count;\n\n }\n\n void backtrack(int [] nums,int n, int start)\n {\n if(start==n)\n {\n count++;\n }\n Set set = new HashSet <>();\n for(int i = start;i int:\n d = { x:{} for x in nums}\n n = len(nums)\n for i in range(n):\n for j in range(i+1,n):\n if self.isSquare(nums[i] + nums[j]):\n d[nums[i]][nums[j]] = True\n d[nums[j]][nums[i]] = True\n self.nums = nums\n self.ans = 0\n self.d = d\n vis = [False]*n\n tmp = {}\n for i in range(n):\n if nums[i] in tmp: continue\n tmp[nums[i]] = True\n vis[i] = True\n self.makePermutation(1,vis,self.nums[i],n)\n vis[i] = False\n return self.ans", + "title": "996. Number of Squareful Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the binary representation of an integer as a string s , return the number of steps to reduce it to 1 under the following rules : If the current number is even, you have to divide it by 2 . If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases.", + "description_images": [], + "constraints": [ + "If the current number is even, you have to divide it by 2 .", + "If the current number is odd, you have to add 1 to it." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"\nOutput:6\nExplanation:\"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"\nOutput:1\nExplanation:\"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.41 MB (Top 54.8%)\n\nclass Solution \n{\n public int numSteps(String s)\n {\n int countSteps = 0;\n int carry = 0;\n for(int i = s.length()-1;i>=1;i--)\n {\n int rightMostBit = s.charAt(i)-'0';\n if((rightMostBit+carry) == 1)\n {\n carry=1;\n countSteps += 2;\n }\n else\n {\n countSteps++;\n }\n }\n return countSteps+carry;\n }\n} ", + "title": "1404. Number of Steps to Reduce a Number in Binary Representation to One", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the binary representation of an integer as a string s , return the number of steps to reduce it to 1 under the following rules : If the current number is even, you have to divide it by 2 . If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases.", + "description_images": [], + "constraints": [ + "If the current number is even, you have to divide it by 2 .", + "If the current number is odd, you have to add 1 to it." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"\nOutput:6\nExplanation:\"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"\nOutput:1\nExplanation:\"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def numSteps(self, s: str) -> int:\n size = len(s)\n if size == 1:\n return 0\n one_group = s.split('0')\n zero_group = s.split('1')\n\n \n if size - len(zero_group[-1]) == 1:\n return size - 1\n else:\n return size + len(one_group) - len(zero_group[-1])\n", + "title": "1404. Number of Steps to Reduce a Number in Binary Representation to One", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer num , return the number of steps to reduce it to zero . In one step, if the current number is even, you have to divide it by 2 , otherwise, you have to subtract 1 from it.", + "description_images": [], + "constraints": [ + "0 <= num <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:num = 14\nOutput:6\nExplanation:Step 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 2: Input:num = 8\nOutput:4\nExplanation:Step 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 3: Input:num = 123\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfSteps(int num) {\n return helper(num,0);\n }\n public int helper(int n,int c){\n if(n==0) return c;\n if(n%2==0){ //check for even no.\n return helper(n/2,c+1);\n }\n \n return helper(n-1,c+1);\n }\n}\n", + "title": "1342. Number of Steps to Reduce a Number to Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return the number of steps to reduce it to zero . In one step, if the current number is even, you have to divide it by 2 , otherwise, you have to subtract 1 from it.", + "description_images": [], + "constraints": [ + "0 <= num <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:num = 14\nOutput:6\nExplanation:Step 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 2: Input:num = 8\nOutput:4\nExplanation:Step 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 3: Input:num = 123\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 70 ms (Top 5.12%) | Memory: 13.9 MB (Top 52.31%)\nclass Solution:\n def numberOfSteps(self, num: int) -> int:\n count=0\n while num:\n if num%2:\n num=num-1\n else:\n num=num//2\n count+=1\n return count", + "title": "1342. Number of Steps to Reduce a Number to Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings patterns and a string word , return the number of strings in patterns that exist as a substring in word . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= patterns.length <= 100", + "1 <= patterns[i].length <= 100", + "1 <= word.length <= 100", + "patterns[i] and word consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\nOutput:3\nExplanation:- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.", + "image": null + }, + { + "text": "Example 2: Input:patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\nOutput:2\nExplanation:- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.", + "image": null + }, + { + "text": "Example 3: Input:patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\nOutput:3\nExplanation:Each of the patterns appears as a substring in word \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfStrings(String[] patterns, String word) {\n int count = 0;\n for(int i=0;i int:\n return sum([pattern in word for pattern in patterns])\n\n ", + "title": "1967. Number of Strings That Appear as Substrings in Word", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime . The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i] . Return the number of students doing their homework at time queryTime . More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.", + "description_images": [], + "constraints": [ + "startTime.length == endTime.length", + "1 <= startTime.length <= 100", + "1 <= startTime[i] <= endTime[i] <= 1000", + "1 <= queryTime <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput:1\nExplanation:We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [4], endTime = [4], queryTime = 4\nOutput:1\nExplanation:The only student was doing their homework at the queryTime.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int busyStudent(int[] startTime, int[] endTime, int queryTime) {\n int count = 0;\n for (int i = 0; i < startTime.length; ++i) {\n if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count;\n }\n return count;\n }\n}\n", + "title": "1450. Number of Students Doing Homework at a Given Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime . The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i] . Return the number of students doing their homework at time queryTime . More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.", + "description_images": [], + "constraints": [ + "startTime.length == endTime.length", + "1 <= startTime.length <= 100", + "1 <= startTime[i] <= endTime[i] <= 1000", + "1 <= queryTime <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput:1\nExplanation:We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [4], endTime = [4], queryTime = 4\nOutput:1\nExplanation:The only student was doing their homework at the queryTime.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 67 ms (Top 36.82%) | Memory: 13.9 MB (Top 71.93%)\nclass Solution(object):\n def busyStudent(self, startTime, endTime, queryTime):\n res = 0\n for i in range(len(startTime)):\n if startTime[i] <= queryTime <= endTime[i]:\n res += 1\n else:\n pass\n return res", + "title": "1450. Number of Students Doing Homework at a Given Time", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack . At each step: This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i ​​​​​​th sandwich in the stack ( i = 0 is the top of the stack) and students[j] is the preference of the j ​​​​​​th student in the initial queue ( j = 0 is the front of the queue). Return the number of students that are unable to eat.", + "description_images": [], + "constraints": [ + "If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.", + "Otherwise, they will leave it and go to the queue's end." + ], + "examples": [ + { + "text": "Example 1: Input:students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput:0\nExplanation:- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.", + "image": null + }, + { + "text": "Example 2: Input:students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 83.22%)\nclass Solution {\n public int countStudents(int[] students, int[] sandwiches) {\n int ones = 0; //count of students who prefer type1\n int zeros = 0; //count of students who prefer type0\n\n for(int stud : students){\n if(stud == 0) zeros++;\n else ones++;\n }\n\n // for each sandwich in sandwiches\n for(int sandwich : sandwiches){\n if(sandwich == 0){ // if sandwich is of type0\n if(zeros == 0){ // if no student want a type0 sandwich\n return ones;\n }\n zeros--;\n }\n else{ // if sandwich is of type1\n if(ones == 0){ // if no student want a type1 sandwich\n return zeros;\n }\n ones--;\n }\n }\n return 0;\n }\n}", + "title": "1700. Number of Students Unable to Eat Lunch", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack . At each step: This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i ​​​​​​th sandwich in the stack ( i = 0 is the top of the stack) and students[j] is the preference of the j ​​​​​​th student in the initial queue ( j = 0 is the front of the queue). Return the number of students that are unable to eat.", + "description_images": [], + "constraints": [ + "If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.", + "Otherwise, they will leave it and go to the queue's end." + ], + "examples": [ + { + "text": "Example 1: Input:students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput:0\nExplanation:- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.", + "image": null + }, + { + "text": "Example 2: Input:students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 76 ms (Top 5.69%) | Memory: 17.30 MB (Top 7.83%)\n\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = 0\n while len(students) > count:\n if students[0] == sandwiches[0]:\n sandwiches.pop(0)\n count = 0\n else:\n students.append(students[0])\n count+=1\n\n students.pop(0)\n return len(students)\n\t\t\n#Upvote will be encouraging.\n", + "title": "1700. Number of Students Unable to Eat Lunch", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput:3\nExplanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput:6\nExplanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfSubarrays(int[] arr, int k, int threshold) {\n int average=0,count=0,start=0,sum=0; \n for(int i=0;i=k-1){\n average=sum/k;\n if(average>=threshold) count++;\n sum-=arr[start]; \n start++; \n } \n }\n return count; \n }\n}\n", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput:3\nExplanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput:6\nExplanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfSubarrays(self, nums: List[int], k: int, threshold: int) -> int:\n currSum = 0\n start = 0\n end = 0\n count = 0\n \n # run right pointer till end element\n for end in range(len(nums)):\n # update value to window\n currSum += nums[end]\n \n # check if window size achieved\n if (end - start + 1) == k:\n # is average > target val\n if (currSum // k) >= threshold:\n count += 1\n # slide the window\n currSum -= nums[start]\n start += 1\n \n \n return count\n", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput:3\nExplanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput:6\nExplanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n wstart = wsum = count = 0\n \n for wend in range(len(arr)):\n wsum += arr[wend]\n \n if wend >= k:\n wsum -= arr[wstart]\n wstart += 1\n if (wsum//k) >= threshold and (wend-wstart+1) == k: \n count += 1\n return count", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return the number of subarrays with an odd sum . Since the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,5]\nOutput:4\nExplanation:All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,4,6]\nOutput:0\nExplanation:All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6,7]\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "//odd-even=odd\n//even-odd=odd\nclass Solution {\n public int numOfSubarrays(int[] arr) {\n long ans=0;\n int even=0;\n int odd=0;\n \n long sum=0;\n \n for(int i=0;i int:\n ce, co = 0, 0\n s = 0\n for x in arr:\n if x % 2 == 0:\n ce += 1\n else:\n old_co = co\n co = ce + 1\n ce = old_co\n \n s += co\n \n return s % (10**9+7)\n", + "title": "1524. Number of Sub-arrays With Odd Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums and two integers left and right , return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right] . The test cases are generated so that the answer will fit in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= left <= right <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3], left = 2, right = 3\nOutput:3\nExplanation:There are three subarrays that meet the requirements: [2], [2, 1], [3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,9,2,5,6], left = 2, right = 8\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 82.54%) | Memory: 72.1 MB (Top 7.10%)\nclass Solution {\n public int numSubarrayBoundedMax(int[] nums, int left, int right) {\n int res = 0;\n\n int s = -1;\n int e = -1;\n\n for(int i=0;i= left && nums[i] <= right){\n e = i;\n }else if(nums[i] > right){\n e = s = i;\n }\n\n res += (e - s);\n }\n\n return res;\n }\n}", + "title": "795. Number of Subarrays with Bounded Maximum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and two integers left and right , return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right] . The test cases are generated so that the answer will fit in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= left <= right <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3], left = 2, right = 3\nOutput:3\nExplanation:There are three subarrays that meet the requirements: [2], [2, 1], [3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,9,2,5,6], left = 2, right = 8\nOutput:7", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1574 ms (Top 5.27%) | Memory: 22.4 MB (Top 17.30%)\nclass Solution:\n def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n n = len(nums)\n stack = []\n next_greater = [n] * n\n prev_greater = [-1] * n\n for i in range(n):\n while len(stack) > 0 and nums[i] > nums[stack[-1]]:\n curr = stack.pop()\n next_greater[curr] = i\n if len(stack) > 0:\n prev_greater[i] = stack[-1]\n stack.append(i)\n res = 0\n for i in range(n):\n if left <= nums[i] <= right:\n l = prev_greater[i]\n r = next_greater[i]\n res += (i - l) * (r - i)\n return res", + "title": "795. Number of Subarrays with Bounded Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a matrix and a target , return the number of non-empty submatrices that sum to target . A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2 . Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1' .", + "description_images": [], + "constraints": [ + "1 <= matrix.length <= 100", + "1 <= matrix[0].length <= 100", + "-1000 <= matrix[i] <= 1000", + "-10^8 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput:4\nExplanation:The four 1x1 submatrices that only contain 0.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/mate1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,-1],[-1,1]], target = 0\nOutput:5\nExplanation:The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[904]], target = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 321 ms (Top 35.18%) | Memory: 117.7 MB (Top 29.49%)\nclass Solution {\npublic int numSubmatrixSumTarget(int[][] matrix, int target) {\n int m = matrix.length, n = matrix[0].length;\n\n int[] summedArray = new int[n];\n int ans = 0;\n for(int i = 0; i < m; i++){ //starting row\n Arrays.fill(summedArray, 0);\n for(int j = i; j < m; j++){ //ending row\n for(int k = 0; k < n; k++){ // column\n summedArray[k] += matrix[j][k];\n }\n ans += subarraySum(summedArray, target);\n }\n }\n return ans;\n}\n\n public int subarraySum(int[] nums, int k) {\n //map\n Map map = new HashMap<>();\n int count = 0;\n map.put(0,1);\n int sum = 0;\n for(int num : nums){\n sum += num;\n int diff = sum - k;\n if(map.containsKey(diff)){\n count += map.get(diff);\n }\n map.put(sum, map.getOrDefault(sum, 0) + 1);\n }\n return count;\n}\n}", + "title": "1074. Number of Submatrices That Sum to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a matrix and a target , return the number of non-empty submatrices that sum to target . A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2 . Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1' .", + "description_images": [], + "constraints": [ + "1 <= matrix.length <= 100", + "1 <= matrix[0].length <= 100", + "-1000 <= matrix[i] <= 1000", + "-10^8 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput:4\nExplanation:The four 1x1 submatrices that only contain 0.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/mate1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,-1],[-1,1]], target = 0\nOutput:5\nExplanation:The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[904]], target = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n m, n = len(matrix), len(matrix[0])\n matrix_sums = [[0 for _ in range(n)] for _ in range(m)]\n \n # Calculate all the submatrices sum with the transition formula we found\n for row in range(m):\n for col in range(n):\n # first cell\n if row == 0 and col == 0:\n matrix_sums[row][col] = matrix[row][col]\n # Rows and columns are like prefix sums, without intersection\n elif row == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col-1]\n elif col == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row-1][col]\n \n # current sum is the sum of the matrix above, to the left and subtract the intersection\n else:\n matrix_sums[row][col] = matrix[row][col] \\\n + (matrix_sums[row][col-1]) \\\n + (matrix_sums[row-1][col]) \\\n - (matrix_sums[row-1][col-1])\n\n \n ans = 0\n # Generate all submatrices\n for y1 in range(m):\n for x1 in range(n):\n for y2 in range(y1, m):\n for x2 in range(x1, n):\n # calculate sum in O(1)\n submatrix_total = matrix_sums[y2][x2] \\\n - (matrix_sums[y2][x1-1] if x1-1 >= 0 else 0) \\\n - (matrix_sums[y1-1][x2] if y1-1 >= 0 else 0) \\\n + (matrix_sums[y1-1][x1-1] if y1-1 >= 0 and x1-1 >= 0 else 0)\n \n if submatrix_total == target:\n ans += 1\n return ans\n", + "title": "1074. Number of Submatrices That Sum to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums and an integer target . Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6", + "1 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,6,7], target = 9\nOutput:4\nExplanation:There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,8], target = 10\nOutput:6\nExplanation:There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,3,3,4,6,7], target = 12\nOutput:61\nExplanation:There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int numSubseq(int[] nums, int target) {\n int n = nums.length;\n int i =0, j = n-1;\n int mod = (int)1e9+7;\n Arrays.sort(nums);\n int[] pow = new int[n];\n pow[0]=1;\n int count =0;\n for(int z =1;z target)\n j--;\n }\n return count;\n }\n}\n\n\n", + "title": "1498. Number of Subsequences That Satisfy the Given Sum Condition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of integers nums and an integer target . Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6", + "1 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,6,7], target = 9\nOutput:4\nExplanation:There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,8], target = 10\nOutput:6\nExplanation:There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,3,3,4,6,7], target = 12\nOutput:61\nExplanation:There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 637 ms (Top 91.1%) | Memory: 29.39 MB (Top 30.6%)\n\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n count = 0\n mod = 10 ** 9 + 7\n \n while left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n else:\n count += pow(2, right - left, mod)\n left += 1\n \n return count % mod\n", + "title": "1498. Number of Subsequences That Satisfy the Given Sum Condition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting only of characters a , b and c . Return the number of substrings containing at least one occurrence of all these characters a , b and c .", + "description_images": [], + "constraints": [ + "3 <= s.length <= 5 x 10^4", + "s only consists of a , b or c characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabc\"\nOutput:10\nExplanation:The substrings containing at least one occurrence of the charactersa,bandc are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\"and\"abc\"(again).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaacb\"\nOutput:3\nExplanation:The substrings containing at least one occurrence of the charactersa,bandc are \"aaacb\", \"aacb\"and\"acb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 41.17%) | Memory: 45.4 MB (Top 53.10%)\n\nclass Solution {\n public int numberOfSubstrings(String s) {\n int a = 0, b = 0, c = 0, count = 0;\n for (int i = 0; i < s.length(); i++) {\n switch (s.charAt(i)) {\n case 'a': ++a; break;\n case 'b': ++b; break;\n case 'c': ++c; break;\n }\n if (a > 0 && b > 0 && c > 0) {\n while (a > 0 && b > 0 && c > 0) {\n char farLeft = s.charAt(i - a - b - c + 1);\n switch (farLeft) {\n case 'a': {\n --a;\n count += doCount(s, i);\n break;\n }\n case 'b': {\n --b;\n count += doCount(s, i);\n break;\n }\n case 'c': {\n --c;\n count += doCount(s, i);\n break;\n }\n }\n }\n }\n }\n return count;\n }\n\n private int doCount(String s, int i) {\n int count = 0;\n int n = s.length() - i;\n if (n > 0) {\n count += n;\n }\n return count;\n }\n}", + "title": "1358. Number of Substrings Containing All Three Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s consisting only of characters a , b and c . Return the number of substrings containing at least one occurrence of all these characters a , b and c .", + "description_images": [], + "constraints": [ + "3 <= s.length <= 5 x 10^4", + "s only consists of a , b or c characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabc\"\nOutput:10\nExplanation:The substrings containing at least one occurrence of the charactersa,bandc are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\"and\"abc\"(again).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaacb\"\nOutput:3\nExplanation:The substrings containing at least one occurrence of the charactersa,bandc are \"aaacb\", \"aacb\"and\"acb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 466 ms (Top 30.17%) | Memory: 14.4 MB (Top 31.83%)\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n start = 0\n end = 0\n counter = 0\n store = {'a' : 0, 'b' : 0, 'c' : 0}\n\n for end in range(len(s)):\n store[s[end]] += 1\n\n while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:\n counter += (len(s) - end)\n store[s[start]] -= 1\n start += 1\n\n return counter", + "title": "1358. Number of Substrings Containing All Three Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s , return the number of substrings with all characters 1 's . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0110111\"\nOutput:9\nExplanation:There are 9 substring in total with only 1's characters.\n\"1\" -> 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"101\"\nOutput:2\nExplanation:Substring \"1\" is shown 2 times in s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"111111\"\nOutput:21\nExplanation:Each substring contains only 1's characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSub(String s) {\n char[] ch = s.toCharArray();\n long count =0;\n long result =0;\n for(int i=0; i 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"101\"\nOutput:2\nExplanation:Substring \"1\" is shown 2 times in s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"111111\"\nOutput:21\nExplanation:Each substring contains only 1's characters.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 40.6%) | Memory: 14.50 MB (Top 56.2%)\n\nclass Solution(object):\n def numSub(self, s):\n res, currsum = 0,0\n for digit in s:\n if digit == '0':\n currsum = 0\n else:\n currsum += 1 \n res+=currsum \n return res % (10**9+7)", + "title": "1513. Number of Substrings With Only 1s", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1 ) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the i th step. A binary string is prefix-aligned if, after the i th step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process .", + "description_images": [], + "constraints": [ + "n == flips.length", + "1 <= n <= 5 * 10^4", + "flips is a permutation of the integers in the range [1, n] ." + ], + "examples": [ + { + "text": "Example 1: Input:flips = [3,2,4,1,5]\nOutput:2\nExplanation:The binary string is initially \"00000\".\nAfter applying step 1: The string becomes \"00100\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"01100\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"01110\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"11110\", which is prefix-aligned.\nAfter applying step 5: The string becomes \"11111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:flips = [4,1,2,3]\nOutput:1\nExplanation:The binary string is initially \"0000\".\nAfter applying step 1: The string becomes \"0001\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"1001\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"1101\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"1111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numTimesAllBlue(int[] flips) {\n int counter=0,total=0,max=Integer.MIN_VALUE;\n for(int i=0;i int:\n \n \n l = len(flips)\n s = 0\n c = 0\n \n for i in range(len(flips)):\n f = flips[i]\n s = 1 << (f - 1) | s\n if s == (1 << (i+1))-1:\n c += 1\n \n return c\n", + "title": "1375. Number of Times Binary String Is Prefix-Aligned", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary string binary . A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\" ). Find the number of unique good subsequences of binary . Return the number of unique good subsequences of binary . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "For example, if binary = \"001\" , then all the good subsequences are [\"0\", \"0\", \"1\"] , so the unique good subsequences are \"0\" and \"1\" . Note that subsequences \"00\" , \"01\" , and \"001\" are not good because they have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"001\"\nOutput:2\nExplanation:The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".", + "image": null + }, + { + "text": "Example 2: Input:binary = \"11\"\nOutput:2\nExplanation:The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".", + "image": null + }, + { + "text": "Example 3: Input:binary = \"101\"\nOutput:5\nExplanation:The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfUniqueGoodSubsequences(String binary) {\n int initialZeroCount= 0;\n while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++;\n if(initialZeroCount == binary.length()) return 1;\n long[] dp = new long[binary.length()];\n dp[initialZeroCount] = 1;\n int lastOne = 0, lastZero = 0;\n long mod = (long) Math.pow(10, 9)+7;\n for(int i=initialZeroCount+1;i 0 ? dp[j-1] : 0;\n dp[i] = 2 * dp[i-1] - dup;\n if(dp[i] < 0) dp[i] += mod;\n dp[i] %= mod;\n if(binary.charAt(i) == '0') lastZero = i;\n else lastOne = i;\n }\n \n int hasZero = 0;\n if(binary.contains(\"0\")) hasZero = 1;\n \n \n return (int) (dp[binary.length()-1] + hasZero);\n }\n}\n", + "title": "1987. Number of Unique Good Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a binary string binary . A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\" ). Find the number of unique good subsequences of binary . Return the number of unique good subsequences of binary . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "For example, if binary = \"001\" , then all the good subsequences are [\"0\", \"0\", \"1\"] , so the unique good subsequences are \"0\" and \"1\" . Note that subsequences \"00\" , \"01\" , and \"001\" are not good because they have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"001\"\nOutput:2\nExplanation:The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".", + "image": null + }, + { + "text": "Example 2: Input:binary = \"11\"\nOutput:2\nExplanation:The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".", + "image": null + }, + { + "text": "Example 3: Input:binary = \"101\"\nOutput:5\nExplanation:The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \n \n # zero_as_last: the count of S0, good sequence ending in 0\n # one_as_last : the count of S1: good sequence ending in 1\n # zero_exist: existence flag of 0 in given binary\n \n dp = {\"zero_as_last\": 0, \"one_as_last\": 0, \"zero_exist\": 0}\n \n for bit in map(int, binary):\n \n if bit:\n # current good = ( S0 concate with 1 ) + ( S1 concate with 1 ) + 1 alone\n # + \"1\" is allowed because leading 1 is valid by description\n dp[\"one_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"] + 1\n \n else:\n # current good = ( S0 concate with 0 ) + ( S1 concate with 0 ) \n # + \"0\" is NOT allowed because leading 0 is invalid by description\n dp[\"zero_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"]\n \n # check the existence of 0\n dp[\"zero_exist\"] |= (1-bit)\n \n \n return sum( dp.values() ) % ( 10**9 + 7 )\n", + "title": "1987. Number of Unique Good Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n , where pieces[i] describes the type (rook, queen, or bishop) of the i th piece. In addition, you are given a 2D integer array positions also of length n , where positions[i] = [r i , c i ] indicates that the i th piece is currently at the 1-based coordinate (r i , c i ) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0 th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations ​​​​​. Notes:", + "description_images": [], + "constraints": [ + "A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c) , (r-1, c) , (r, c+1) , or (r, c-1) .", + "A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c) , (r-1, c) , (r, c+1) , (r, c-1) , (r+1, c+1) , (r+1, c-1) , (r-1, c+1) , (r-1, c-1) .", + "A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1) , (r+1, c-1) , (r-1, c+1) , (r-1, c-1) ." + ], + "examples": [ + { + "text": "Example 1: Input:pieces = [\"rook\"], positions = [[1,1]]\nOutput:15\nExplanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a1.png" + }, + { + "text": "Example 2: Input:pieces = [\"queen\"], positions = [[1,1]]\nOutput:22\nExplanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a2.png" + }, + { + "text": "Example 3: Input:pieces = [\"bishop\"], positions = [[4,3]]\nOutput:12\nExplanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int:\n board = [[set() for _ in range(8)] for _ in range(8)]\n n = len(pieces)\n for pos in positions:\n pos[0] -= 1\n pos[1] -= 1\n all_time = set(range(1, 8))\n def recur(i):\n if i == n:\n return 1\n ans = 0\n line = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n diag = [(1, 1), (1, -1), (-1, 1), (-1, -1)]\n r, c = positions[i]\n if not board[r][c] & all_time:\n board[r][c] |= all_time\n ans += recur(i + 1)\n board[r][c].clear()\n directions = []\n if pieces[i] in (\"queen\", \"rook\"):\n directions.extend(line)\n if pieces[i] in (\"queen\", \"bishop\"):\n directions.extend(diag) \n for dr, dc in directions:\n x, y = r + dr, c + dc\n count = 1\n while 0 <= x < 8 and 0 <= y < 8 and count not in board[x][y]:\n board[x][y].add(count)\n count += 1\n rest = set(range(count, 8))\n if not board[x][y] & rest:\n board[x][y] |= rest\n ans += recur(i + 1)\n board[x][y] -= rest\n x += dr\n y += dc\n count -= 1\n x -= dr\n y -= dc\n while count:\n board[x][y].remove(count)\n count -= 1\n x -= dr\n y -= dc\n return ans\n return recur(0)\n", + "title": "2056. Number of Valid Move Combinations On Chessboard", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "word contains the first letter of puzzle .", + "For each letter in word , that letter is in puzzle . For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle).", + "For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while", + "invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle)." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\nOutput:[1,1,3,2,4,0]\nExplanation:1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\nOutput:[0,1,3,2,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic List findNumOfValidWords(String[] words, String[] puzzles) {\n \n Map map = new HashMap<>();\n \n for(String w : words){\n int mask = 0;\n for(int i = 0; i < w.length(); i++){\n mask |= 1 << (w.charAt(i) - 'a');\n }\n map.put(mask, map.getOrDefault(mask, 0) + 1);\n }\n \n List res = new ArrayList<>();\n \n for(String p : puzzles){\n int mask = 0;\n for(int i = 0; i < p.length(); i++){\n mask |= 1 << (p.charAt(i) - 'a');\n }\n int c = 0;\n int sub = mask;\n int first = 1 << (p.charAt(0) - 'a');\n while(true){\n if((sub & first) == first && map.containsKey(sub)){\n c += map.get(sub);\n }\n \n if(sub == 0) break;\n \n sub = (sub - 1) & mask; // get the next substring\n }\n \n res.add(c);\n }\n \n return res;\n}\n}", + "title": "1178. Number of Valid Words for Each Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "word contains the first letter of puzzle .", + "For each letter in word , that letter is in puzzle . For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle).", + "For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while", + "invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle)." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\nOutput:[1,1,3,2,4,0]\nExplanation:1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\nOutput:[0,1,3,2,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n look_up=collections.defaultdict(int)\n def get_mask(word):\n mask=0\n for c in word:\n mask |= 1<<(ord(c)-ord('a'))\n return mask\n for word in words:\n mask=get_mask(word)\n look_up[mask]+=1\n ans=[]\n def solve(puzzle_idx,mask,c_idx):\n if c_idx==len(puzzles[puzzle_idx]):\n ans[-1]+=look_up[mask]\n return\n #take this c_idx\n solve(puzzle_idx,mask | 1<<(ord(puzzles[puzzle_idx][c_idx])-ord('a')),c_idx+1)\n #dont take this c_idx\n solve(puzzle_idx,mask,c_idx+1)\n for i,puzzle in enumerate(puzzles):\n ans.append(0)\n solve(i,1<<(ord(puzzle[0])-ord('a')),1)\n return ans\n", + "title": "1178. Number of Valid Words for Each Puzzle", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence consists of lowercase letters ( 'a' to 'z' ), digits ( '0' to '9' ), hyphens ( '-' ), punctuation marks ( '!' , '.' , and ',' ), and spaces ( ' ' ) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' ' . A token is a valid word if all three of the following are true: Examples of valid words include \"a-b.\" , \"afad\" , \"ba-c\" , \"a!\" , and \"!\" . Given a string sentence , return the number of valid words in sentence .", + "description_images": [], + "constraints": [ + "It only contains lowercase letters, hyphens, and/or punctuation ( no digits).", + "There is at most one hyphen '-' . If present, it must be surrounded by lowercase characters ( \"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).", + "There is at most one punctuation mark. If present, it must be at the end of the token ( \"ab,\" , \"cd!\" , and \".\" are valid, but \"a!b\" and \"c.,\" are not valid)." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"catanddog\"\nOutput:3\nExplanation:The valid words in the sentence are \"cat\", \"and\", and \"dog\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"!this 1-s b8d!\"\nOutput:0\nExplanation:There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"aliceandbobareplayingstone-game10\"\nOutput:5\nExplanation:The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countValidWords(String sentence) {\n String regex = \"^([a-z]+(-?[a-z]+)?)?(!|\\\\.|,)?$\";\n String r2 = \"[^0-9]+\";\n String[] arr = sentence.split(\"\\\\s+\");\n int ans = 0;\n for(String s: arr)\n {\n if(s.matches(regex) && s.matches(r2))\n {\n ans++;\n //System.out.println(s);\n }\n }\n return ans;\n }\n}\n", + "title": "2047. Number of Valid Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sentence consists of lowercase letters ( 'a' to 'z' ), digits ( '0' to '9' ), hyphens ( '-' ), punctuation marks ( '!' , '.' , and ',' ), and spaces ( ' ' ) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' ' . A token is a valid word if all three of the following are true: Examples of valid words include \"a-b.\" , \"afad\" , \"ba-c\" , \"a!\" , and \"!\" . Given a string sentence , return the number of valid words in sentence .", + "description_images": [], + "constraints": [ + "It only contains lowercase letters, hyphens, and/or punctuation ( no digits).", + "There is at most one hyphen '-' . If present, it must be surrounded by lowercase characters ( \"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).", + "There is at most one punctuation mark. If present, it must be at the end of the token ( \"ab,\" , \"cd!\" , and \".\" are valid, but \"a!b\" and \"c.,\" are not valid)." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"catanddog\"\nOutput:3\nExplanation:The valid words in the sentence are \"cat\", \"and\", and \"dog\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"!this 1-s b8d!\"\nOutput:0\nExplanation:There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"aliceandbobareplayingstone-game10\"\nOutput:5\nExplanation:The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.", + "image": null + } + ], + "follow_up": null, + "solution": "import re\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n \n # parse and get each word from sentence\n words = sentence.split()\n \n # regular expression pattern for valid words\n pattern = re.compile( r'^([a-z]+\\-?[a-z]+[!\\.,]?)$|^([a-z]*[!\\.,]?)$' )\n \n # valid word count\n count = 0\n \n # scan each word from word pool\n for word in words:\n \n # judge whether current word is valid or not\n match = re.match(pattern, word)\n \n if match:\n count+=1\n \n return count\n", + "title": "2047. Number of Valid Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]\nOutput:[3,1,2,1,1,0]\nExplanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]\nOutput:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] canSeePersonsCount(int[] heights) {\n Stack stack = new Stack<>();\n int result[] = new int[heights.length];\n for(int i = heights.length - 1; i >= 0; i--) {\n int visibility = 0;\n while(!stack.isEmpty() && heights[i] > stack.peek()) {\n stack.pop();\n visibility++;\n }\n if(!stack.isEmpty()) visibility++;\n stack.push(heights[i]);\n result[i] = visibility;\n }\n return result;\n }\n}\n", + "title": "1944. Number of Visible People in a Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]\nOutput:[3,1,2,1,1,0]\nExplanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]\nOutput:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2162 ms (Top 20.79%) | Memory: 30.1 MB (Top 6.96%)\n\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans=[]\n stack=[]\n n=len(heights)\n for i in range(n-1,-1,-1):\n if len(stack)==0:\n ans.append(0)\n stack.append(heights[i])\n else:\n if heights[i]0 and stack[-1] int:\n m, n = len(p), len(p[0])\n apples = [[0 for _ in range(n+1)] for _ in range(m+1)] \n # number of apples in (0,0) to (i,j)\n apples[1][1] = 0 if p[0][0] == '.' else 1\n for j in range(1,n):\n apples[1][j+1] = apples[1][j] if p[0][j] == '.' else apples[1][j] + 1\n for i in range(1,m):\n cur_apple = 0 if p[i][0] == '.' else 1\n apples[i+1][1] = apples[i][1] + cur_apple\n for j in range(1,n):\n if p[i][j] == 'A': cur_apple += 1\n apples[i+1][j+1] = apples[i][j+1] + cur_apple\n\n def getApples(x,y,z,w):\n # get the number of apples within range\n # x,y: top-left coordinates of current pizza\n # z,w: bottom-right\n return apples[z+1][w+1] + apples[x][y] - apples[z+1][y] - apples[x][w+1]\n\n @lru_cache(None)\n def cut(c,x,y,z,w):\n # c: number of cuts already cut\n # x,y: top-left coordinates of current pizza\n # z,w: bottom-right\n if c == k - 1:\n return 1 if getApples(x,y,z,w) > 0 else 0\n\n r = 0\n # horizontal cuts\n i = x\n while i < z:\n if getApples(x,y,i,w) > 0: break\n i += 1\n while i < z:\n r += cut(c+1,i+1,y,z,w)\n i += 1\n # vertical cuts\n j = y\n while j < w:\n if getApples(x,y,z,j) > 0: break\n j += 1\n while j < w:\n r += cut(c+1,x,j+1,z,w)\n j += 1\n\n return r\n\n return cut(0,0,0,m-1,n-1)%(10**9+7)", + "title": "1444. Number of Ways of Cutting a Pizza", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [u i , v i , time i ] means that there is a road between intersections u i and v i that takes time i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time . Return the number of ways you can arrive at your destination in the shortest amount of time . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n - 1 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 3", + "0 <= u i , v i <= n - 1", + "1 <= time i <= 10^9", + "u i != v i", + "There is at most one road connecting any two intersections.", + "You can reach any intersection from any other intersection." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput:4\nExplanation:The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6", + "image": "https://assets.leetcode.com/uploads/2021/07/17/graph2.png" + }, + { + "text": "Example 2: Input:n = 2, roads = [[1,0,10]]\nOutput:1\nExplanation:There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Pair{\n int node;\n int dist;\n Pair(int node , int dist){\n this.node = node;\n this.dist = dist;\n }\n }\n public int countPaths(int n, int[][] roads) {\n int mod = (int)Math.pow(10 , 9) + 7;\n ArrayList> adj = new ArrayList<>();\n int rows = roads.length;\n for(int i = 0 ; i < n ; i++)\n adj.add(new ArrayList());\n for(int i = 0 ; i < rows ; i++){\n int from = roads[i][0];\n int to = roads[i][1];\n int dis = roads[i][2];\n adj.get(from).add(new Pair(to , dis));\n adj.get(to).add(new Pair(from , dis));\n }\n PriorityQueue pq = new PriorityQueue<>((aa , bb) -> aa.dist - bb.dist);\n pq.add(new Pair(0 , 0));\n long[] ways = new long[n];\n ways[0] = 1;\n int[] dist = new int[n];\n Arrays.fill(dist , Integer.MAX_VALUE);\n dist[0] = 0;\n while(!pq.isEmpty()){\n Pair p = pq.remove();\n int node = p.node;\n int dis = p.dist;\n for(Pair pa : adj.get(node)){\n if((dis + pa.dist) < dist[pa.node]){\n ways[pa.node] = ways[node];\n dist[pa.node] = dis + pa.dist;\n pq.add(new Pair(pa.node , dist[pa.node]));\n }\n else if((dis + pa.dist) == dist[pa.node]){\n ways[pa.node] += ways[node];\n ways[pa.node] = ways[pa.node] % mod;\n }\n }\n }\n return (int)ways[n - 1];\n }\n}\n", + "title": "1976. Number of Ways to Arrive at Destination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [u i , v i , time i ] means that there is a road between intersections u i and v i that takes time i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time . Return the number of ways you can arrive at your destination in the shortest amount of time . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n - 1 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 3", + "0 <= u i , v i <= n - 1", + "1 <= time i <= 10^9", + "u i != v i", + "There is at most one road connecting any two intersections.", + "You can reach any intersection from any other intersection." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput:4\nExplanation:The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6", + "image": "https://assets.leetcode.com/uploads/2021/07/17/graph2.png" + }, + { + "text": "Example 2: Input:n = 2, roads = [[1,0,10]]\nOutput:1\nExplanation:There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(dict)\n for u, v, w in roads:\n graph[u][v] = graph[v][u] = w\n dist = {i:float(inf) for i in range(n)}\n ways = {i:0 for i in range(n)}\n dist[0], ways[0] = 0, 1\n heap = [(0, 0)]\n while heap:\n d, u = heapq.heappop(heap)\n if dist[u] < d: \n continue\n for v in graph[u]:\n if dist[v] == dist[u] + graph[u][v]:\n ways[v] += ways[u]\n elif dist[v] > dist[u] + graph[u][v]:\n dist[v] = dist[u] + graph[u][v]\n ways[v] = ways[u]\n heapq.heappush(heap, (dist[v], v))\n return ways[n-1] % ((10 ** 9) + 7)\n", + "title": "1976. Number of Ways to Arrive at Destination", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. Return the number of distinct ways you can buy some number of pens and pencils.", + "description_images": [], + "constraints": [ + "1 <= total, cost1, cost2 <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:total = 20, cost1 = 10, cost2 = 5\nOutput:9\nExplanation:The price of a pen is 10 and the price of a pencil is 5.\n- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.\n- If you buy 1 pen, you can buy 0, 1, or 2 pencils.\n- If you buy 2 pens, you cannot buy any pencils.\nThe total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:total = 5, cost1 = 10, cost2 = 10\nOutput:1\nExplanation:The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n return sum((total - pens*cost1) // cost2 + 1 for pens in range(total // cost1 + 1))", + "title": "2240. Number of Ways to Buy Pens and Pencils", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0 , and another to the right of index n - 1 . Additional room dividers can be installed. For each position between indices i - 1 and i ( 1 <= i <= n - 1 ), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor . Since the answer may be very large, return it modulo 10^9 + 7 . If there is no way, return 0 .", + "description_images": [], + "constraints": [ + "n == corridor.length", + "1 <= n <= 10^5", + "corridor[i] is either 'S' or 'P' ." + ], + "examples": [ + { + "text": "Example 1: Input:corridor = \"SSPPSPS\"\nOutput:3\nExplanation:There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways,eachsection has exactlytwoseats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/1.png" + }, + { + "text": "Example 2: Input:corridor = \"PPSPSP\"\nOutput:1\nExplanation:There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/2.png" + }, + { + "text": "Example 3: Input:corridor = \"S\"\nOutput:0\nExplanation:There is no way to divide the corridor because there will always be a section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/12/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 89.8%) | Memory: 44.90 MB (Top 30.5%)\n\nclass Solution {\n public int numberOfWays(String corridor) {\n int numSeats = 0, numPlants = 0;\n long dividers = 1;\n \n for(int i = 0; i < corridor.length(); ++i) {\n if(corridor.charAt(i) == 'S') numSeats += 1;\n if(numSeats == 2 && corridor.charAt(i) == 'P') numPlants += 1;\n if(numSeats == 3) {\n dividers *= (numPlants + 1);\n dividers %= 1000000007;\n numSeats = 1;\n numPlants = 0;\n }\n }\n \n if(numSeats < 2) return 0;\n return (int)dividers;\n }\n}", + "title": "2147. Number of Ways to Divide a Long Corridor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0 , and another to the right of index n - 1 . Additional room dividers can be installed. For each position between indices i - 1 and i ( 1 <= i <= n - 1 ), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor . Since the answer may be very large, return it modulo 10^9 + 7 . If there is no way, return 0 .", + "description_images": [], + "constraints": [ + "n == corridor.length", + "1 <= n <= 10^5", + "corridor[i] is either 'S' or 'P' ." + ], + "examples": [ + { + "text": "Example 1: Input:corridor = \"SSPPSPS\"\nOutput:3\nExplanation:There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways,eachsection has exactlytwoseats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/1.png" + }, + { + "text": "Example 2: Input:corridor = \"PPSPSP\"\nOutput:1\nExplanation:There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/2.png" + }, + { + "text": "Example 3: Input:corridor = \"S\"\nOutput:0\nExplanation:There is no way to divide the corridor because there will always be a section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/12/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 253 ms (Top 99.08%) | Memory: 17.50 MB (Top 42.72%)\n\nclass Solution:\n def numberOfWays(self, corridor):\n seat, res, plant = 0, 1, 0\n for i in corridor:\n if i=='S':\n seat += 1\n else:\n if seat == 2:\n plant += 1\n if seat == 3:\n res = res*(plant+1) % (10**9 + 7)\n seat , plant = 1 , 0\n if seat != 2:\n return 0\n return res\n", + "title": "2147. Number of Ways to Divide a Long Corridor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of strings of the same length words and a string target . Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "target should be formed from left to right.", + "To form the i th character ( 0-indexed ) of target , you can choose the k th character of the j th string in words if target[i] = words[j][k] .", + "Once you use the k th character of the j th string of words , you can no longer use the x th character of any string in words where x <= k . In other words, all characters to the left of or at index k become unusuable for every string.", + "Repeat the process until you form the string target ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\nOutput:6\nExplanation:There are 6 ways to form target.\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abba\",\"baab\"], target = \"bab\"\nOutput:4\nExplanation:There are 4 ways to form target.\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1795 ms (Top 74.72%) | Memory: 380.50 MB (Top 27.21%)\n\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n MOD = 10 ** 9 + 7\n m, n = len(words[0]), len(target)\n charAtIndexCnt = [[0] * m for _ in range(128)]\n for word in words:\n for i, c in enumerate(word):\n charAtIndexCnt[ord(c)][i] += 1 # Count the number of character `c` at index `i` of all words\n\n @lru_cache(None)\n def dp(k, i):\n if i == n: # Formed a valid target\n return 1\n if k == m: # Reached to length of words[x] but don't found any result\n return 0\n c = target[i]\n ans = dp(k + 1, i) # Skip k_th index of words\n if charAtIndexCnt[ord(c)][k] > 0: # Take k_th index of words if found character `c` at index k_th\n ans += dp(k + 1, i + 1) * charAtIndexCnt[ord(c)][k]\n ans %= MOD\n return ans\n\n return dp(0, 0)\n", + "title": "1639. Number of Ways to Form a Target String Given a Dictionary", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red , Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid . As the answer may grow large, the answer must be computed modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == grid.length", + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:12\nExplanation:There are 12 possible way to paint the grid as shown.", + "image": "https://assets.leetcode.com/uploads/2020/03/26/e1.png" + }, + { + "text": "Example 2: Input:n = 5000\nOutput:30228214", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int MOD = 1000000007;\n int[][] states = {{0,1,0},{1,0,1},{2,0,1},\n {0,1,2},{1,0,2},{2,0,2},\n {0,2,0},{1,2,0},{2,1,0},\n {0,2,1},{1,2,1},{2,1,2}};\n \n HashMap> nextMap = new HashMap<>();\n Long[][] memo;\n \n public int numOfWays(int n) {\n if(n == 0)\n return 0;\n \n\t\t// Graph\n for(int prev = 0; prev < 12; prev++){\n List nexts = new ArrayList<>();\n for(int next = 0; next < 12; next++){\n if(next == prev) continue;\n \n boolean flag = true;\n for(int i = 0; i < 3; i++){\n if(states[prev][i] == states[next][i]){\n flag = false;\n break;\n }\n }\n if(flag)\n nexts.add(next);\n }\n nextMap.put(prev, nexts);\n }\n\t\t\n\t\t//DFS\n memo = new Long[12][n];\n long ways = 0;\n for(int i = 0; i < 12; i++){\n ways += dfs(i, n-1);\n ways %= MOD;\n }\n \n return (int)(ways);\n }\n \n long dfs(int prev, int n){\n if(n == 0)\n return 1;\n \n if(memo[prev][n] != null)\n return memo[prev][n];\n \n long ways = 0;\n \n List nexts = nextMap.get(prev);\n for(int next : nexts){\n ways += dfs(next, n-1);\n ways %= MOD;\n }\n \n memo[prev][n] = ways;\n return ways;\n }\n}", + "title": "1411. Number of Ways to Paint N × 3 Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red , Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid . As the answer may grow large, the answer must be computed modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == grid.length", + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:12\nExplanation:There are 12 possible way to paint the grid as shown.", + "image": "https://assets.leetcode.com/uploads/2020/03/26/e1.png" + }, + { + "text": "Example 2: Input:n = 5000\nOutput:30228214", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfWays(self, n: int) -> int:\n two_c_options = 6\n tot_options = 12\n for i in range(n-1):\n temp = tot_options\n tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4)\n two_c_options = (two_c_options * 3) + ((temp - two_c_options) * 2)\n tot_options = tot_options % (1000000007)\n return tot_options\n", + "title": "1411. Number of Ways to Paint N × 3 Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n . You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k , return the number of such arrangements . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, if the sticks are arranged [ 1 , 3 ,2, 5 ,4] , then the sticks with lengths 1 , 3 , and 5 are visible from the left." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2\nOutput:3\nExplanation:[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 5\nOutput:1\nExplanation:[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 3: Input:n = 20, k = 11\nOutput:647427950\nExplanation:There are 647427950 (mod 109+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 368 ms (Top 16.85%) | Memory: 89.8 MB (Top 41.57%)\nclass Solution {\n public int rearrangeSticks(int n, int k) {\n final int MOD = 1_000_000_007;\n long[][] M = new long[k + 1][n + 1];\n M[0][0] = 1;\n for (int i = 1; i <= k; i++) {\n for (int j = 1; j <= n; j++) {\n M[i][j] = ((j - 1) * M[i][j - 1] % MOD + M[i - 1][j - 1]) % MOD;\n }\n }\n return (int) M[k][n];\n }\n}", + "title": "1866. Number of Ways to Rearrange Sticks With K Sticks Visible", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n . You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k , return the number of such arrangements . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, if the sticks are arranged [ 1 , 3 ,2, 5 ,4] , then the sticks with lengths 1 , 3 , and 5 are visible from the left." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2\nOutput:3\nExplanation:[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 5\nOutput:1\nExplanation:[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 3: Input:n = 20, k = 11\nOutput:647427950\nExplanation:There are 647427950 (mod 109+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.", + "image": null + } + ], + "follow_up": null, + "solution": "M = 10 ** 9 + 7\n\nfrom functools import cache\n\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n return dp(n, k)\n\n# consider the shortest\n@cache\ndef dp(n, k):\n if n == k:\n return 1\n if n <= 0 or k <= 0:\n return 0\n return (dp(n - 1, k - 1) + (n - 1) * dp(n - 1, k)) % M \n\n# `dp(n, k)` indicates the number of arrangements of `n` distinct sticks with exactly `k` visible sticks. \n# Those `n` **distinct** sticks does NOT have to be numbered from `1` to `n` consecutively.\n", + "title": "1866. Number of Ways to Rearrange Sticks With K Sticks Visible", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array pairs , where pairs[i] = [x i , y i ] , and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.", + "description_images": [], + "constraints": [ + "There are no duplicates.", + "x i < y i" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3]]\nOutput:1\nExplanation:There is exactly one valid rooted tree, which is shown in the above figure.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/trees2.png" + }, + { + "text": "Example 2: Input:pairs = [[1,2],[2,3],[1,3]]\nOutput:2\nExplanation:There are multiple valid rooted trees. Three of them are shown in the above figures.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/tree.png" + }, + { + "text": "Example 3: Input:pairs = [[1,2],[2,3],[2,4],[1,5]]\nOutput:0\nExplanation:There are no valid rooted trees.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 418 ms (Top 41.46%) | Memory: 133.9 MB (Top 9.76%)\nclass Solution {\n public int checkWays(int[][] pairs) {\n int result = 1;\n\n //Create adjacency list\n Map> edges = new HashMap<>();\n for (int[] pair: pairs) {\n edges.computeIfAbsent(pair[0], x->new HashSet<>()).add(pair[0]);\n edges.computeIfAbsent(pair[1], x->new HashSet<>()).add(pair[1]);\n edges.get(pair[0]).add(pair[1]);\n edges.get(pair[1]).add(pair[0]);\n }\n\n //Sort the edge lists based on their size\n List>> edgesList = new ArrayList(edges.entrySet());\n Collections.sort(edgesList, (a,b)-> b.getValue().size() - a.getValue().size());\n\n List>> previous = new ArrayList<>();\n\n // Now from each of the edges find the ways to create the tree\n for (Map.Entry> cur: edgesList) {\n //get the current edge set\n Set currentSet = cur.getValue();\n //find the parent for the current set from the previously computed edge\n Map.Entry> parent = find(previous, currentSet);\n // if the parent is null\n if (parent==null) {\n // if you the current set do not match with the edges size then there is no way, return 0\n if (currentSet.size() != edges.size())\n return 0;\n } else {\n Set parentSet = parent.getValue();\n // if the current set do not contain everything from the parent then also return 0\n if (!parentSet.containsAll(currentSet)) return 0;\n // if the parent contains everything from the current set then return more than one ways\n if (parentSet.equals(currentSet)) result = 2;\n }\n // add the computed edge to previous list\n previous.add(cur);\n }\n\n // only one way\n return result;\n }\n\n Map.Entry> find(List>> previous, Set currentSet) {\n int i=previous.size()-1;\n while (i>=0) {\n Map.Entry> entry = previous.get(i--);\n if (currentSet.contains(entry.getKey())) return entry;\n }\n return null;\n }\n}", + "title": "1719. Number Of Ways To Reconstruct A Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array pairs , where pairs[i] = [x i , y i ] , and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.", + "description_images": [], + "constraints": [ + "There are no duplicates.", + "x i < y i" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3]]\nOutput:1\nExplanation:There is exactly one valid rooted tree, which is shown in the above figure.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/trees2.png" + }, + { + "text": "Example 2: Input:pairs = [[1,2],[2,3],[1,3]]\nOutput:2\nExplanation:There are multiple valid rooted trees. Three of them are shown in the above figures.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/tree.png" + }, + { + "text": "Example 3: Input:pairs = [[1,2],[2,3],[2,4],[1,5]]\nOutput:0\nExplanation:There are no valid rooted trees.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkWays(self, P):\n g = defaultdict(set)\n for u, v in P:\n g[u].add(v)\n g[v].add(u)\n\n def helper(nodes):\n d, m = defaultdict(list), len(nodes) - 1\n for node in nodes:\n d[len(g[node])].append(node)\n\n if len(d[m]) == 0: return 0\n root = d[m][0]\n \n for node in g[root]: g[node].remove(root)\n \n comps, seen, i = defaultdict(set), set(), 0\n def dfs(node, i):\n comps[i].add(node)\n seen.add(node)\n for neib in g[node]:\n if neib not in seen: dfs(neib, i)\n \n for node in nodes:\n if node != root and node not in seen:\n dfs(node, i)\n i += 1\n \n cands = [helper(comps[i]) for i in comps]\n if 0 in cands: return 0\n if 2 in cands: return 2\n if len(d[m]) >= 2: return 2\n return 1\n \n return helper(set(g.keys()))\n", + "title": "1719. Number Of Ways To Reconstruct A Tree", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array nums that represents a permutation of integers from 1 to n . We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums . Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, given nums = [2,1,3] , we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:1\nExplanation:We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/bb.png" + }, + { + "text": "Example 2: Input:nums = [3,4,5,1,2]\nOutput:5\nExplanation:The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex1.png" + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:0\nExplanation:There are no other orderings of nums that will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex4.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n long[][] pascal;\n private static final long mod = 1000000007;\n long one=1;\n public int numOfWays(int[] nums) {\n ArrayList list = new ArrayList<>();\n for (int n : nums) {\n list.add(n);\n }\n formPascal(nums);\n return (int)dfs(list)-1;\n }\n \n public long dfs(ArrayList list){\n if(list.size()<=2) return 1;\n ArrayList left=new ArrayList<>();\n ArrayList right=new ArrayList<>();\n int root=list.get(0);\n for(int n:list){\n if(nroot)\n right.add(n);\n }\n \n return ((pascal[left.size()+right.size()][left.size()])*(dfs(left)%mod))%mod *(dfs(right)%mod);\n \n \n }\n \n private void formPascal(int[] nums){\n pascal=new long[nums.length+1][];\n \n for(int i=0;i<=nums.length;i++){\n pascal[i]=new long[i+1];\n Arrays.fill(pascal[i],one);\n for(int j=1;j", + "title": "1569. Number of Ways to Reorder Array to Get Same BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums that represents a permutation of integers from 1 to n . We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums . Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "For example, given nums = [2,1,3] , we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:1\nExplanation:We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/bb.png" + }, + { + "text": "Example 2: Input:nums = [3,4,5,1,2]\nOutput:5\nExplanation:The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex1.png" + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:0\nExplanation:There are no other orderings of nums that will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex4.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 556 ms (Top 18.24%) | Memory: 15.4 MB (Top 89.19%)\nclass node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution:\n def BST(self, root, cur):\n if cur.val < root.val:\n if root.left == None:\n root.left = cur\n return\n else:\n self.BST(root.left, cur)\n elif cur.val > root.val:\n if root.right == None:\n root.right = cur\n return\n else:\n self.BST(root.right, cur)\n\n def solve(self, root):\n if root.left == None and root.right == None:\n return 1\n left = 0 ; right = 0\n if root.left is not None:\n left = self.solve(root.left)\n if root.right is not None:\n right = self.solve(root.right)\n self.total *= math.comb(left + right, left)\n return left + right + 1\n\n def numOfWays(self, nums: List[int]) -> int:\n import math\n self.total = 1\n root = node(nums[0])\n for i in range(1, len(nums)):\n self.BST(root, node(nums[i]))\n self.solve(root)\n return (self.total - 1) % (int(1e9) + 7)", + "title": "1569. Number of Ways to Reorder Array to Get Same BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.", + "description_images": [], + "constraints": [ + "s[i] = '0' denotes that the i th building is an office and", + "s[i] = '1' denotes that the i th building is a restaurant." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"001101\"\nOutput:6\nExplanation:The following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.", + "image": null + }, + { + "text": "Example 2: Input:s = \"11100\"\nOutput:0\nExplanation:It can be shown that there are no valid selections.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public long numberOfWays(String s)\n {\n int zero = 0; // Individual zeroes count\n long zeroOne = 0; // Number of combinations of 01s\n int one = 0; // Individual ones count\n long oneZero = 0; // Number of combinations of 10s\n long tot = 0; // Final answer\n for(char ch : s.toCharArray())\n {\n if(ch == '0')\n {\n zero++;\n if(one > 0)\n oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10\n if(zeroOne > 0)\n tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010\n }\n else\n {\n one++;\n if(zero > 0)\n zeroOne += zero; // Each of the previously found 0s can pair to form 01\n if(oneZero > 0)\n tot += oneZero; // Each of the previously formed 10 can form 101\n }\n }\n return tot;\n }\n}\n", + "title": "2222. Number of Ways to Select Buildings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.", + "description_images": [], + "constraints": [ + "s[i] = '0' denotes that the i th building is an office and", + "s[i] = '1' denotes that the i th building is a restaurant." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"001101\"\nOutput:6\nExplanation:The following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.", + "image": null + }, + { + "text": "Example 2: Input:s = \"11100\"\nOutput:0\nExplanation:It can be shown that there are no valid selections.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfWays(self, s: str) -> int:\n \n temp = []\n c0 = 0\n c1 = 0\n for char in s :\n if char == \"0\" :\n c0+=1\n else:\n c1+=1\n temp.append([c0,c1])\n \n total0 = c0\n total1 = c1\n \n \n count = 0\n for i in range(1, len(s)-1) :\n \n if s[i] == \"0\" :\n m1 = temp[i-1][1]\n m2 = total1 - temp[i][1]\n count += m1*m2\n \n else:\n m1 = temp[i-1][0]\n m2 = total0 - temp[i][0]\n count += m1*m2\n return count\n \n \n", + "title": "2222. Number of Ways to Select Buildings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You wrote down many positive integers in a string called num . However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3500", + "num consists of digits '0' through '9' ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"327\"\nOutput:2\nExplanation:You could have written down the numbers:\n3, 27\n327", + "image": null + }, + { + "text": "Example 2: Input:num = \"094\"\nOutput:0\nExplanation:No numbers can have leading zeros and all numbers must be positive.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0\"\nOutput:0\nExplanation:No numbers can have leading zeros and all numbers must be positive.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 11887 ms (Top 6.00%) | Memory: 14.2 MB (Top 88.00%)\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n if num[0]=='0': return 0\n N=len(num)\n MOD=int(10**9+7)\n ways = (N+1)*[0]\n acc = list(ways)\n for n in range(1,N+1):\n ways[n] = int(n==N or num[n]!='0')\n for i in range(n+1,N+1):\n if i=2*n and num[i-2*n:i-n] <= num[i-n:i] and w)) %MOD\n for i in range(n,N+1):\n a = (acc[i] + ways[i]) %MOD\n acc[i] = a\n return acc[N]", + "title": "1977. Number of Ways to Separate Numbers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s , you can split s into 3 non-empty strings s1 , s2 , and s3 where s1 + s2 + s3 = s . Return the number of ways s can be split such that the number of ones is the same in s1 , s2 , and s3 . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "3 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10101\"\nOutput:4\nExplanation:There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n\"1|010|1\"\n\"1|01|01\"\n\"10|10|1\"\n\"10|1|01\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"1001\"\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:s = \"0000\"\nOutput:3\nExplanation:There are three ways to split s in 3 parts.\n\"0|0|00\"\n\"0|00|0\"\n\"00|0|0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numWays(String s) {\n long n=s.length();\n long one=0;//to count number of ones\n long mod=1_000_000_007;\n char[] c=s.toCharArray();\n for(int i=0;i int:\n ones = 0\n\n # Count number of Ones\n for char in s:\n if char == \"1\":\n ones += 1\n\n # Can't be grouped equally if the ones are not divisible by 3\n if ones > 0 and ones % 3 != 0:\n return 0\n\n # Ways of selecting two dividers from n - 1 dividers \n if ones == 0:\n n = len(s)\n\t\t\t# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }\n return (((n - 1) * (n - 2)) // 2) % ((10 ** 9) + 7)\n\n # Number of ones in each group\n ones_interval = ones // 3\n\n # Number of zeroes which lie on the borders\n left, right = 0, 0\n\n # Iterator\n i = 0\n temp = 0\n\n # Finding the zeroes on the left and right border\n while i < len(s):\n temp += int(s[i]) & 1\n if temp == ones_interval:\n if s[i] == '0':\n left += 1\n if temp == 2 * ones_interval:\n if s[i] == '0':\n right += 1\n i += 1\n \n # The result is the product of number of (left + 1) and (right + 1)\n # Because let's assume it as we only want to fill up the middle group\n # The solution would be if we have zero then there might be a zero in the middle\n # Or there might not be the zero, so this might case is added and then\n\t\t# the events are independent so product of both the events\n return ((left + 1) * (right + 1)) % ((10 ** 9) + 7)\n\n", + "title": "1573. Number of Ways to Split a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . nums contains a valid split at index i if the following are true: Return the number of valid splits in nums .", + "description_images": [], + "constraints": [ + "The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.", + "There is at least one element to the right of i . That is, 0 <= i < n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,4,-8,7]\nOutput:2\nExplanation:There are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,0]\nOutput:2\nExplanation:There are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int waysToSplitArray(int[] nums) {\n long sum = 0;\n for(int i : nums){\n sum+=i;\n }\n int sol = 0;\n long localSum = 0;\n for(int i=0; i= sum-localSum){\n sol++;\n }\n }\n return sol;\n }\n}", + "title": "2270. Number of Ways to Split Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . nums contains a valid split at index i if the following are true: Return the number of valid splits in nums .", + "description_images": [], + "constraints": [ + "The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.", + "There is at least one element to the right of i . That is, 0 <= i < n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,4,-8,7]\nOutput:2\nExplanation:There are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,0]\nOutput:2\nExplanation:There are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n prefix_sum = [nums[0]]\n n = len(nums)\n for i in range(1, n):\n prefix_sum.append(nums[i] + prefix_sum[-1]) \n \n count = 0\n for i in range(n-1):\n if prefix_sum[i] >= prefix_sum[n-1] - prefix_sum[i]:\n count += 1\n return count\n", + "title": "2270. Number of Ways to Split Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a pointer at index 0 in an array of size arrLen . At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen , return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= steps <= 500", + "1 <= arrLen <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:steps = 3, arrLen = 2\nOutput:4\nExplanation:There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "image": null + }, + { + "text": "Example 2: Input:steps = 2, arrLen = 4\nOutput:2\nExplanation:There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay", + "image": null + }, + { + "text": "Example 3: Input:steps = 4, arrLen = 2\nOutput:8", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 205 ms (Top 20.9%) | Memory: 55.71 MB (Top 10.4%)\n\nclass Solution {\n \n HashMap map = new HashMap();\n \n public int numWays(int steps, int arrLen) {\n \n return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7));\n }\n \n public long ways(int steps,int arrLen,int index){\n String curr = index + \"->\" + steps;\n \n if(index == 0 && steps == 0){\n return 1;\n }else if(index < 0 || (index >= arrLen) || steps == 0){\n return 0;\n }\n \n if(map.containsKey(curr)){\n return map.get(curr);\n }\n long stay = ways(steps-1,arrLen,index);\n long right = ways(steps-1,arrLen,index+1);\n long left = ways(steps-1,arrLen,index-1);\n \n map.put(curr , (stay+right+left) % 1000000007);\n \n return (right + left + stay) % 1000000007;\n }\n}", + "title": "1269. Number of Ways to Stay in the Same Place After Some Steps", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a pointer at index 0 in an array of size arrLen . At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen , return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= steps <= 500", + "1 <= arrLen <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:steps = 3, arrLen = 2\nOutput:4\nExplanation:There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "image": null + }, + { + "text": "Example 2: Input:steps = 2, arrLen = 4\nOutput:2\nExplanation:There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay", + "image": null + }, + { + "text": "Example 3: Input:steps = 4, arrLen = 2\nOutput:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n \n # obtain maximum index we can reach\n maxLen = min(steps+1, arrLen)\n dp = [0]*maxLen\n dp[0] = 1\n \n for step in range(1, steps+1):\n dp2 = [0]*maxLen\n for pos in range(maxLen):\n # dp[step][pos] = dp[step-1][pos] + dp[step-1][pos-1] + dp[step-1][pos+1] \n temp1 = 0 if pos == 0 else dp[pos-1]\n temp2 = 0 if pos == maxLen-1 else dp[pos+1]\n dp2[pos] = (dp[pos] + temp1 + temp2)%(10**9+7)\n \n dp = dp2\n return dp[0]\n", + "title": "1269. Number of Ways to Stay in the Same Place After Some Steps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people and 40 types of hats labeled from 1 to 40 . Given a 2D integer array hats , where hats[i] is a list of all hats preferred by the i th person. Return the number of ways that the n people wear different hats to each other . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == hats.length", + "1 <= n <= 10", + "1 <= hats[i].length <= 40", + "1 <= hats[i][j] <= 40", + "hats[i] contains a list of unique integers." + ], + "examples": [ + { + "text": "Example 1: Input:hats = [[3,4],[4,5],[5]]\nOutput:1\nExplanation:There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.", + "image": null + }, + { + "text": "Example 2: Input:hats = [[3,5,1],[3,5]]\nOutput:4\nExplanation:There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)", + "image": null + }, + { + "text": "Example 3: Input:hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\nOutput:24\nExplanation:Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 94.19%) | Memory: 42.1 MB (Top 89.53%)\nclass Solution {\n public int numberWays(List> hats) {\n int n = hats.size(), M = (int)1e9+7;\n int[] mask = new int[41];\n for (int i = 0; i < n; i++){\n for (int h : hats.get(i)){\n mask[h]|=1<= 0 && mask[i]>0; j--){\n for (int k = 0; k < n && (mask[i]&j)>0; k++){\n if ((1<0 && (1<0){\n dp[j]+=dp[j^1< int:\n # transpose hats\n n_persons = len(hats)\n temp = [[] for _ in range(40)]\n for i, person in enumerate(hats):\n for hat in person:\n temp[hat-1].append(i)\n hats = temp\n \n # drop empty hats and sort\n hats = [h for h in hats if h]\n hats.sort(key=lambda h: len(h))\n n_hats = len(hats)\n \n # helpers\n full = 2 ** n_persons - 1\n bits = [1 << i for i in range(n_persons)]\n cut = 10 ** 9 + 7\n \n \n @cache\n def get_count(i, has_hat):\n if has_hat == full:\n # all persons have a hat\n return 1\n elif i == n_hats:\n # no more hats left\n return 0\n else:\n result = 0\n for person in hats[i]:\n # does the person \n # still not have a hat?\n if has_hat & bits[person] == 0:\n # the person wears i-th hat\n result += get_count(i + 1, has_hat | bits[person])\n # no one wears i-th hat\n result += get_count(i + 1, has_hat)\n \n # return modulo (10 ** 9 - 7)\n return result % cut\n \n \n # start form 0-th hat and \n # no person wearing a hat\n return get_count(0, 0)\n", + "title": "1434. Number of Ways to Wear Different Hats to Each Other", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two arrays of integers nums1 and nums2 , return the number of triplets formed (type 1 and type 2) under the following rules:", + "description_images": [], + "constraints": [ + "Type 1: Triplet (i, j, k) if nums1[i] 2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length .", + "Type 2: Triplet (i, j, k) if nums2[i] 2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [7,4], nums2 = [5,2,8,9]\nOutput:1\nExplanation:Type 1: (1, 1, 2), nums1[1]2= nums2[1] * nums2[2]. (42= 2 * 8).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1], nums2 = [1,1,1]\nOutput:9\nExplanation:All Triplets are valid, because 12= 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2= nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2= nums1[j] * nums1[k].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput:2\nExplanation:There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2= nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2= nums1[0] * nums1[1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 92.55%) | Memory: 42.4 MB (Top 88.30%)\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n return count(nums1 , nums2) + count(nums2 , nums1);\n }\n\n public int count(int a[] , int b[]){\n int n = a.length;\n int m = b.length;\n int count = 0;\n for(int i=0;ix)\n k--;\n else if(b[j] != b[k]){\n int jNew = j;\n int kNew = k;\n\n while(b[j] == b[jNew])\n jNew++;\n while(b[k] == b[kNew])\n kNew--;\n count += (jNew-j)*(k-kNew);\n j = jNew;\n k = kNew;\n }\n else{\n int q = k-j+1;\n count += (q)*(q-1)/2;\n break;\n }\n }\n }\n return count;\n }\n\n}", + "title": "1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two arrays of integers nums1 and nums2 , return the number of triplets formed (type 1 and type 2) under the following rules:", + "description_images": [], + "constraints": [ + "Type 1: Triplet (i, j, k) if nums1[i] 2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length .", + "Type 2: Triplet (i, j, k) if nums2[i] 2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [7,4], nums2 = [5,2,8,9]\nOutput:1\nExplanation:Type 1: (1, 1, 2), nums1[1]2= nums2[1] * nums2[2]. (42= 2 * 8).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1], nums2 = [1,1,1]\nOutput:9\nExplanation:All Triplets are valid, because 12= 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2= nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2= nums1[j] * nums1[k].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput:2\nExplanation:There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2= nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2= nums1[0] * nums1[1].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 753 ms (Top 50.00%) | Memory: 14 MB (Top 47.37%)\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n = len(nums1), len(nums2)\n for i in range(m):\n sqr1[nums1[i]**2] += 1\n for j in range(n):\n sqr2[nums2[j]**2] += 1\n\n res = 0\n for i in range(m-1):\n for j in range(i+1, m):\n if nums1[i]*nums1[j] in sqr2:\n res += sqr2[nums1[i]*nums1[j]]\n\n for i in range(n-1):\n for j in range(i+1, n):\n if nums2[i]*nums2[j] in sqr1:\n res += sqr1[nums2[i]*nums2[j]]\n return res", + "title": "1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ( 'a' through 'j' ), return the number of wonderful non-empty substrings in word . If the same substring appears multiple times in word , then count each occurrence separately. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"\nOutput:4\nExplanation:The four wonderful substrings are underlined below:\n- \"aba\" -> \"a\"\n- \"aba\" -> \"b\"\n- \"aba\" -> \"a\"\n- \"aba\" -> \"aba\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"aabb\"\nOutput:9\nExplanation:The nine wonderful substrings are underlined below:\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"aa\"\n- \"aabb\" -> \"aab\"\n- \"aabb\" -> \"aabb\"\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"abb\"\n- \"aabb\" -> \"b\"\n- \"aabb\" -> \"bb\"\n- \"aabb\" -> \"b\"", + "image": null + }, + { + "text": "Example 3: Input:word = \"he\"\nOutput:2\nExplanation:The two wonderful substrings are underlined below:\n- \"he\" -> \"h\"\n- \"he\" -> \"e\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long wonderfulSubstrings(String word) {\n int n = word.length();\n long count = 0;\n \n long[] freq = new long[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap\n \n freq[0] = 1;\n int res = 0; // initialize the frequency of 0000000000 as 1 because when no element is encountered, then th bitmask is 0\n \n for (int i = 0; i < n; i++) {\n int mask = (1 << (word.charAt(i) - 'a'));\n res ^= mask; // toggling bit of the current character to make it from odd to even OR even to odd\n int chkMask = 1;\n \n count += freq[res];\n for (int j = 1; j <= 10; j++) { // Loop for checking all possiblities of different places of the Different Bit\n count += freq[chkMask ^ res];\n chkMask <<= 1;\n }\n \n freq[res]++; // increasing the frequency of the current bitmask\n }\n \n return count;\n }\n}\n", + "title": "1915. Number of Wonderful Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ( 'a' through 'j' ), return the number of wonderful non-empty substrings in word . If the same substring appears multiple times in word , then count each occurrence separately. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"\nOutput:4\nExplanation:The four wonderful substrings are underlined below:\n- \"aba\" -> \"a\"\n- \"aba\" -> \"b\"\n- \"aba\" -> \"a\"\n- \"aba\" -> \"aba\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"aabb\"\nOutput:9\nExplanation:The nine wonderful substrings are underlined below:\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"aa\"\n- \"aabb\" -> \"aab\"\n- \"aabb\" -> \"aabb\"\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"abb\"\n- \"aabb\" -> \"b\"\n- \"aabb\" -> \"bb\"\n- \"aabb\" -> \"b\"", + "image": null + }, + { + "text": "Example 3: Input:word = \"he\"\nOutput:2\nExplanation:The two wonderful substrings are underlined below:\n- \"he\" -> \"h\"\n- \"he\" -> \"e\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n cnt, res, mask = [1] + [0] * 1023, 0, 0\n for ch in word:\n mask ^= 1 << (ord(ch) - ord('a'))\n res += cnt[mask]\n for n in range(10):\n res += cnt[mask ^ 1 << n];\n cnt[mask] += 1\n return res\n", + "title": "1915. Number of Wonderful Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the number of subarrays filled with 0 . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,0,0,2,0,0,4]\nOutput:6\nExplanation:There are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,2,0,0]\nOutput:9\nExplanation:There are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,2019]\nOutput:0\nExplanation:There is no subarray filled with 0. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "#Baraa\nclass Solution:\n def zeroFilledSubarray(self, nums: List[int]) -> int:\n i = 0\n res = 0\n for j in range(len(nums)):\n if nums[j] != 0:\n i = j + 1\n else:\n res += (j - i + 1)\n return res\n", + "title": "2348. Number of Zero-Filled Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the number of subarrays filled with 0 . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,0,0,2,0,0,4]\nOutput:6\nExplanation:There are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,2,0,0]\nOutput:9\nExplanation:There are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,2019]\nOutput:0\nExplanation:There is no subarray filled with 0. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def zeroFilledSubarray(self, nums: List[int]) -> int: \n number_of_zerosubs = 0\n counter = 0\n for i in nums:\n if not i:\n counter += 1\n elif counter:\n number_of_zerosubs += sum(range(1, counter+1))\n counter = 0\n if not nums[-1]:\n number_of_zerosubs += sum(range(1, counter+1))\n return number_of_zerosubs", + "title": "2348. Number of Zero-Filled Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'] , we may write numbers such as '13' , '551' , and '1351315' . Return the number of positive integers that can be generated that are less than or equal to a given integer n .", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 9", + "digits[i].length == 1", + "digits[i] is a digit from '1' to '9' .", + "All the values in digits are unique .", + "digits is sorted in non-decreasing order.", + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\nOutput:20\nExplanation:The 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.", + "image": null + }, + { + "text": "Example 2: Input:digits = [\"1\",\"4\",\"9\"], n = 1000000000\nOutput:29523\nExplanation:We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.", + "image": null + }, + { + "text": "Example 3: Input:digits = [\"7\"], n = 8\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n // DIGIT DP IS LOVE \n Integer[][][] digitdp;\n public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) {\n\n if (pos == num.length()) {\n return 1;\n }\n\n int maxDigit = -1;\n \n if(digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] !=null) return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0];\n\n if (bound) {\n maxDigit = num.charAt(pos) - '0';\n } else {\n maxDigit = 9;\n }\n\n int ans = 0;\n for (int i = 0; i <=maxDigit; i++) {\n \n // 0 can only be leading \n if(i==0 && lead){\n\n ans += solve(num,pos+1,false,dig,lead);\n \n }else{\n \n int res = Arrays.binarySearch(dig,i);\n\n if(res>=0){\n // lead = false; // now it is not possible to 0 to be in lead any more once any other call has been made\n ans += solve(num, pos + 1, bound & (i == num.charAt(pos)-'0'), dig,false);\n }\n \n }\n }\n\n return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] = ans;\n\n }\n\n public int atMostNGivenDigitSet(String[] digits, int n) {\n\n String num = n + \"\";\n Integer[] dig = new Integer[digits.length];\n for(int i=0;i int(target[idx]): continue\n res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False)\n\n cache[(idx, isBoundary, isZero)] = res\n return res\n\n return helper(0, True, True)", + "title": "902. Numbers At Most N Given Digit Set", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of positive integers in the range [1, n] that have at least one repeated digit .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 20\nOutput:1\nExplanation:The only positive number (<= 20) with at least 1 repeated digit is 11.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:10\nExplanation:The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.", + "image": null + }, + { + "text": "Example 3: Input:n = 1000\nOutput:262", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.74%) | Memory: 41.1 MB (Top 50.94%)\nclass Solution {\n public int numDupDigitsAtMostN(int n) {\n // 983582\n // 108318\n int ttl = n++;\n int ans = 0;\n List list = new ArrayList<>();\n while(n>0){\n list.add(n%10);\n n/=10;\n }\n for (int i = 1; i < list.size(); i++){\n ans+=9*find(i-1, 9);\n }\n boolean[] seen = new boolean[10];\n for (int i = list.size(), d = 9; i > 0; --i, d--){\n int count = i == list.size()? list.get(i-1)-1: list.get(i-1);\n for (int j = 0; j < list.get(i-1); j++){\n if (seen[j]){\n count--;\n }\n }\n ans += count*find(i-1, d);\n if (seen[list.get(i-1)]){\n break;\n }\n seen[list.get(i-1)]=true;\n }\n return ttl-ans;\n }\n\n private int find(int n, int d){\n // dCn*n!\n // d!/(d-n)/(d-n).../1\n int ans = 1;\n for (int i = 1; i <= d; i++){\n ans *= i;\n }\n for (int i = n+1; i <= d; i++){\n ans /= (i-n);\n }\n return ans;\n }\n}", + "title": "1012. Numbers With Repeated Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of positive integers in the range [1, n] that have at least one repeated digit .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 20\nOutput:1\nExplanation:The only positive number (<= 20) with at least 1 repeated digit is 11.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:10\nExplanation:The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.", + "image": null + }, + { + "text": "Example 3: Input:n = 1000\nOutput:262", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n \n nums = [int(i) for i in str(n+1)] # digits in n+1\n d = len(nums) # number of digits in n+1\n res = 0 # number of no duplicates\n \n # count no duplicates for numbers with res = new ArrayList<>();\n public int[] numsSameConsecDiff(int n, int k) {\n \n for(int ans = 1; ans < 10; ans++){ // first digit can't be 0\n find(ans, n-1, k); // find remaining n-1 digits using backtrack\n }\n \n return res.stream().mapToInt(Integer::intValue).toArray(); // convert list to int arr\n }\n \n private void find(int ans, int n, int k){\n \n if(n == 0){\n res.add(ans); // if got length n number then put that into res\n return;\n }\n \n for(int i = 0; i < 10; i++){\n if(Math.abs(ans%10-i) == k) // find digit that have k difference with last digit\n find(ans*10+i, n-1, k);\n }\n ans /= 10; // remove last digit while backtrack\n }\n}", + "title": "967. Numbers With Same Consecutive Differences", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k . Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "2 <= n <= 9", + "0 <= k <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 7\nOutput:[181,292,707,818,929]\nExplanation:Note that 070 is not a valid number, because it has leading zeroes.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 1\nOutput:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n # initialize the cache with all the valid numbers of length 1\n # cache is a list of tuple (number, digit at units place)\n cache = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]\n cacheTemp = []\n \n # each iteration will store all the valid numbers of length 2 to n in cache\n for i in range(2, n + 1):\n # loop through the cache from the previous iteration\n for j in cache:\n if k == 0:\n if j[0] != 0:\n cacheTemp.append((j[0] * 10 + j[1], j[1]))\n elif j[1] == 0 and i == 2:\n continue\n elif j[1] <= k - 1:\n if j[1] < 10 - k:\n cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n elif j[1] >= 10 - k:\n if j[1] > k - 1:\n cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n else:\n cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n cache = cacheTemp # store the list of valid integers of length i in cache\n cacheTemp = [] # empty the temporary list\n \n res = []\n for i in cache:\n res.append(i[0])\n \n return res\n \n", + "title": "967. Numbers With Same Consecutive Differences", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings first and second , consider occurrences in some text of the form \"first second third\" , where second comes immediately after first , and third comes immediately after second . Return an array of all the words third for each occurrence of \"first second third\" .", + "description_images": [], + "constraints": [ + "1 <= text.length <= 1000", + "text consists of lowercase English letters and spaces.", + "All the words in text a separated by a single space .", + "1 <= first.length, second.length <= 10", + "first and second consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\nOutput:[\"girl\",\"student\"]", + "image": null + }, + { + "text": "Example 2: Input:text = \"we will we will rock you\", first = \"we\", second = \"will\"\nOutput:[\"we\",\"rock\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 23.12%)\n\nclass Solution {\n public String[] findOcurrences(String text, String first, String second) {\n String[] st = text.split(\" \");\n List l = new ArrayList();\n int i =0,n = st.length;\n\n while(i List[str]:\n pattern = r\"(?<=\\b\" + first +\" \" + second + r\" )[a-z]*\"\n txt = re.findall(pattern,text)\n return txt", + "title": "1078. Occurrences After Bigram", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array arr . From some starting index, you can make a series of jumps. The (1 st , 3 rd , 5 th , ...) jumps in the series are called odd-numbered jumps , and the (2 nd , 4 th , 6 th , ...) jumps in the series are called even-numbered jumps . Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j ) in the following way: A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1 ) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices .", + "description_images": [], + "constraints": [ + "During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "It may be the case that for some index i , there are no legal jumps." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,13,12,14,15]\nOutput:2\nExplanation:From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,1,1,4]\nOutput:3\nExplanation:From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.", + "image": null + }, + { + "text": "Example 3: Input:arr = [5,1,3,4,2]\nOutput:3\nExplanation:We can reach the end from starting indices 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 152 ms (Top 15.26%) | Memory: 54.5 MB (Top 75.57%)\nclass Solution {\n public int oddEvenJumps(int[] arr) {\n\n int len = arr.length;\n int minjmp[] = new int[len];\n int maxjmp[] = new int[len];\n\n TreeMap map = new TreeMap<>();\n int evjmp, oddjmp;\n for(int i = len-1; i>=0; i--)\n {\n Integer minpos = map.floorKey(arr[i]);\n evjmp = (minpos != null)?map.get(minpos):len; //default len, to show not possible\n\n if(evjmp != len && (evjmp == len-1 || maxjmp[evjmp] == len-1))\n evjmp = len-1; //check the last pos reachability\n\n Integer maxpos = map.ceilingKey(arr[i]);\n oddjmp = (maxpos != null) ? map.get(maxpos):len;\n\n if(oddjmp != len && (oddjmp == len-1 || minjmp[oddjmp] == len-1))\n oddjmp = len-1;//check the last pos reachability\n\n minjmp[i] = evjmp; //specify possible jump path, if not possible assign len\n maxjmp[i] = oddjmp;//specify possible jump path, if not possible assign len\n\n map.put(arr[i],i); //put the current index\n }\n\n int res = 0;\n\n for(int i = 0; i< len-1; i++) {\n\n if(maxjmp[i] == len-1)\n res++;\n }\n\n return res+1; //since last position will always be the answer\n }\n\n}", + "title": "975. Odd Even Jump", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array arr . From some starting index, you can make a series of jumps. The (1 st , 3 rd , 5 th , ...) jumps in the series are called odd-numbered jumps , and the (2 nd , 4 th , 6 th , ...) jumps in the series are called even-numbered jumps . Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j ) in the following way: A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1 ) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices .", + "description_images": [], + "constraints": [ + "During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "It may be the case that for some index i , there are no legal jumps." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,13,12,14,15]\nOutput:2\nExplanation:From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,1,1,4]\nOutput:3\nExplanation:From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.", + "image": null + }, + { + "text": "Example 3: Input:arr = [5,1,3,4,2]\nOutput:3\nExplanation:We can reach the end from starting indices 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n \n l = len(arr)\n res = [False]*l\n res[-1] = True\n \n # for odd jump: for i, get next larger one \n odd_next = [i for i in range(l)]\n stack = [] # mono inc for ind\n for n, i in sorted([(arr[i], i) for i in range(l)]):\n while stack and stack[-1] Optional[ListNode]:\n if head is None:\n return \n odd, even_start, even = head, head.next, head.next\n while odd is not None and even is not None:\n odd.next = even.next\n if odd.next is not None:\n odd = odd.next\n even.next = odd.next\n even = even.next\n else:\n break\n odd.next = even_start\n return head\n", + "title": "328. Odd Even Linked List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of binary strings strs and two integers m and n . Return the size of the largest subset of strs such that there are at most m 0 's and n 1 's in the subset . A set x is a subset of a set y if all elements of x are also elements of y .", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 600", + "1 <= strs[i].length <= 100", + "strs[i] consists only of digits '0' and '1' .", + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"], m = 5, n = 3\nOutput:4\nExplanation:The largest subset with at most 5 0's and 3 1's is {\"10\", \"0001\", \"1\", \"0\"}, so the answer is 4.\nOther valid but smaller subsets include {\"0001\", \"1\"} and {\"10\", \"1\", \"0\"}.\n{\"111001\"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"10\",\"0\",\"1\"], m = 1, n = 1\nOutput:2\nExplanation:The largest subset is {\"0\", \"1\"}, so the answer is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7928 ms (Top 10.31%) | Memory: 14.1 MB (Top 82.43%)\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n dp = [[0 for _ in range(m+1)] for _ in range(n + 1)]\n for s in strs:\n zeroes = s.count(\"0\")\n ones = len(s)-zeroes\n for i in range(n, ones-1, -1):\n for j in range(m, zeroes-1, -1):\n dp[i][j] = max(dp[i][j], dp[i-ones][j-zeroes]+1)\n return dp[n][m]", + "title": "474. Ones and Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays persons and times . In an election, the i th vote was cast for persons[i] at time times[i] . For each query at a time t , find the person that was leading the election at time t . Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class:", + "description_images": [], + "constraints": [ + "TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.", + "int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules." + ], + "examples": [ + { + "text": "Example 1: Input[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]Output[null, 0, 1, 1, 0, 0, 1]ExplanationTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 91.57%) | Memory: 51.6 MB (Top 89.43%)\nclass TopVotedCandidate {\n int[] persons;\n int[] times;\n int length;\n Map voteCount;\n Map voteLead;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n this.persons = persons;\n this.times = times;\n length = times.length-1;\n int leadCount = 0;\n int leadPerson = -1;\n voteCount = new HashMap<>();\n voteLead = new HashMap<>();\n for(int i=0; i<=length; i++){\n int newCount = voteCount.getOrDefault(persons[i], 0) + 1;\n voteCount.put(persons[i], newCount);\n if(newCount >= leadCount){\n leadCount = newCount;\n leadPerson = persons[i];\n }\n voteLead.put(times[i], leadPerson);\n }\n }\n\n public int q(int t) {\n int leadPerson = -1;\n if(voteLead.containsKey(t)) {\n leadPerson = voteLead.get(t);\n }\n else if(t < times[0]){\n leadPerson = voteLead.get(times[0]);\n }\n else if(t > times[length]){\n leadPerson = voteLead.get(times[length]);\n }\n else {\n int low = 0;\n int high = length;\n while(low <= high){\n int mid = low + (high-low)/2;\n if(times[mid] > t) high = mid - 1;\n else low = mid + 1;\n }\n leadPerson = voteLead.get(times[high]);\n }\n return leadPerson;\n }\n}\n", + "title": "911. Online Election", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays persons and times . In an election, the i th vote was cast for persons[i] at time times[i] . For each query at a time t , find the person that was leading the election at time t . Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class:", + "description_images": [], + "constraints": [ + "TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.", + "int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules." + ], + "examples": [ + { + "text": "Example 1: Input[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]Output[null, 0, 1, 1, 0, 0, 1]ExplanationTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1", + "image": null + } + ], + "follow_up": null, + "solution": "class TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n counter = defaultdict(int)\n\n mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i]\n largestVote = -1 # keep largest vote person index\n for i in range(len(persons)):\n counter[persons[i]] += 1\n if largestVote == -1 or counter[persons[i]] >= counter[largestVote]:\n largestVote = persons[i]\n mostVotePersons[i] = largestVote\n \n self.times = times\n self.mostVotePersons = mostVotePersons\n\n def q(self, t: int) -> int:\n idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t\n return self.mostVotePersons[idx]\n", + "title": "911. Online Election", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class:", + "description_images": [], + "constraints": [ + "MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr .", + "int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists." + ], + "examples": [ + { + "text": "Example 1: Input[\"MajorityChecker\", \"query\", \"query\", \"query\"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]Output[null, 1, -1, 2]ExplanationMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 91.4%) | Memory: 61.43 MB (Top 12.7%)\n\nclass MajorityChecker {\n \n private final int digits=15;\n private int[][]presum;\n private ArrayList[]pos;\n \n public MajorityChecker(int[] arr) {\n int len=arr.length;\n presum=new int[len+1][digits];\n pos=new ArrayList[20001];\n \n for(int i=0;i>=1;\n }\n }\n }\n \n public int query(int left, int right, int threshold) {\n int ans=0;\n for(int i=digits-1;i>=0;i--){\n int cnt=presum[right+1][i]-presum[left][i];\n int b=1;\n if(cnt>=threshold)b=1;\n else if(right-left+1-cnt>=threshold)b=0;\n else return -1;\n ans=(ans<<1)+b;\n }\n \n // check\n ArrayListlist=pos[ans];\n if(list==null)return -1;\n int L=floor(list,left-1);\n int R=floor(list,right);\n if(R-L>=threshold)return ans;\n return -1;\n }\n \n private int floor(ArrayListlist,int n){\n int left=0, right=list.size()-1, mid;\n while(left<=right){\n mid=left+(right-left)/2;\n int index=list.get(mid);\n if(index==n)return mid;\n else if(index> b) & 1)\n self.num_idx = defaultdict(list)\n for i in range(n):\n self.num_idx[nums[i]].append(i)\n\n def query(self, left: int, right: int, threshold: int) -> int:\n num = 0\n for b in range(MAX_BIT):\n if self.bit_sum[right+1][b] - self.bit_sum[left][b] >= threshold:\n num |= 1 << b\n l = bisect.bisect_left(self.num_idx[num], left)\n r = bisect.bisect_right(self.num_idx[num], right)\n if r-l >= threshold:\n return num\n return -1", + "title": "1157. Online Majority Element In Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. Implement the StockSpanner class:", + "description_images": [], + "constraints": [ + "For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85] , then the stock spans would be [1,1,1,2,1,4,6] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class Pair{\n int stock;\n int span;\n \n public Pair(int stock, int span){\n this.stock = stock;\n this.span = span;\n }\n \n}\nclass StockSpanner {\n Stack stack;\n public StockSpanner() {\n stack = new Stack<>();\n }\n \n public int next(int price) {\n int span = 1;\n while(!stack.isEmpty() && stack.peek().stock <= price){\n Pair pStock = stack.pop();\n span += pStock.span ;\n }\n stack.push(new Pair(price, span));\n return span;\n }\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */\n", + "title": "901. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. Implement the StockSpanner class:", + "description_images": [], + "constraints": [ + "For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85] , then the stock spans would be [1,1,1,2,1,4,6] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class StockSpanner:\n\n def __init__(self):\n self.stack = []\n \n def next(self, price: int) -> int:\n \n ans = 1\n while self.stack and self.stack[-1][0] <= price:\n ans += self.stack.pop()[1]\n \n self.stack.append((price, ans))\n \n return ans\n \n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n", + "title": "901. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' . The wheels can rotate freely and wrap around: for example we can turn '9' to be '0' , or '0' to be '9' . Each move consists of turning one wheel one slot. The lock initially starts at '0000' , a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.", + "description_images": [], + "constraints": [ + "1 <= deadends.length <= 500", + "deadends[i].length == 4", + "target.length == 4", + "target will not be in the list deadends .", + "target and deadends[i] consist of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput:6\nExplanation:A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".", + "image": null + }, + { + "text": "Example 2: Input:deadends = [\"8888\"], target = \"0009\"\nOutput:1\nExplanation:We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".", + "image": null + }, + { + "text": "Example 3: Input:deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput:-1\nExplanation:We cannot reach the target without getting stuck.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 88.24%) | Memory: 61 MB (Top 77.65%)\nclass Solution {\n public int openLock(String[] deadends, String target) {\n// Converted target to Integer type.\n int t = Integer.parseInt(target);\n HashSet visited = new HashSet<>();\n\n// Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited.\n for(String str: deadends){\n visited.add(Integer.parseInt(str));\n }\n// BFS\n Queue q = new ArrayDeque<>();\n// We make sure that 0 itself isn't a deadend\n if(visited.contains(0)){\n return -1;\n }\n q.add(0);\n visited.add(0);\n int level = 0;\n while(q.size() > 0){\n int size = q.size();\n while(size-->0){\n int elem = q.remove();\n if(t == elem){\n return level;\n }\n// Will help check 4 digits of the element. From digit with low precendence(ones place) to high precedence(thousands place)\n for(int i = 1; i < 10000; i= i*10){\n// The wheel can be rotated in two directions. Hence two numbers.\n int num1;\n int num2;\n// The wheel at 0 can become 1 or 9 due to wrapping.\n if(elem / i % 10 == 0){\n num1=elem + i;\n num2 = elem+ i * 9;\n }\n// The wheel at 9 can become 0 or 8 due to wrapping.\n else if(elem / i % 10 == 9){\n num1 = elem - i * 9;\n num2 = elem -i;\n }\n else{\n num1 = elem -i;\n num2 = elem + i;\n }\n// Checking if numbers have already been visited.\n if(!(visited.contains(num1))){\n visited.add(num1);\n q.add(num1);\n }\n if(!(visited.contains(num2))){\n visited.add(num2);\n q.add(num2);\n }\n }\n }\n level++;\n }\n return -1;\n }\n}", + "title": "752. Open the Lock", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' . The wheels can rotate freely and wrap around: for example we can turn '9' to be '0' , or '0' to be '9' . Each move consists of turning one wheel one slot. The lock initially starts at '0000' , a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.", + "description_images": [], + "constraints": [ + "1 <= deadends.length <= 500", + "deadends[i].length == 4", + "target.length == 4", + "target will not be in the list deadends .", + "target and deadends[i] consist of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput:6\nExplanation:A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".", + "image": null + }, + { + "text": "Example 2: Input:deadends = [\"8888\"], target = \"0009\"\nOutput:1\nExplanation:We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".", + "image": null + }, + { + "text": "Example 3: Input:deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput:-1\nExplanation:We cannot reach the target without getting stuck.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n def neighbor(s):\n res = []\n for i, c in enumerate(s):\n res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:])\n res.append(s[:i] + chr((ord(c) - ord('0') + 1) % 10 + ord('0')) + s[i + 1:])\n return res\n \n deadends = set(deadends)\n if \"0000\" in deadends:\n return -1\n ans = 0\n queue = deque([\"0000\"])\n vis = set()\n while queue:\n l = len(queue)\n for _ in range(l):\n cur = queue.popleft()\n if cur == target:\n return ans\n for nxt in neighbor(cur):\n if nxt not in vis and nxt not in deadends:\n queue.append(nxt)\n vis.add(nxt)\n ans += 1\n return -1\n", + "title": "752. Open the Lock", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the i th node. The root of the tree is node 0 , so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class:", + "description_images": [], + "constraints": [ + "Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.", + "Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.", + "Upgrade : Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors.", + "The node is unlocked,", + "It has at least one locked descendant (by any user), and", + "It does not have any locked ancestors." + ], + "examples": [ + { + "text": "Example 1: Input[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]Output[null, true, false, true, true, true, false]ExplanationLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.", + "image": "https://assets.leetcode.com/uploads/2021/07/29/untitled.png" + } + ], + "follow_up": null, + "solution": "class LockingTree {\n int[] p;\n Map map = new HashMap<>();\n Map> children = new HashMap<>();\n public LockingTree(int[] parent) {\n p = parent;\n for(int i = 0; i < p.length; i ++) {\n children.put(i, new ArrayList<>());\n }\n for(int i = 1; i < p.length; i ++) {\n children.get(p[i]).add(i);\n }\n }\n \n public boolean lock(int num, int user) {\n if(!map.containsKey(num)) {\n map.put(num, user);\n return true;\n } \n return false;\n }\n \n public boolean unlock(int num, int user) {\n if(map.containsKey(num) && map.get(num) == user) {\n map.remove(num);\n return true;\n }\n return false;\n }\n \n public boolean upgrade(int num, int user) {\n //check the node\n if(map.containsKey(num)) return false;\n //check Ancestor\n int ori = num;\n while(p[num] != -1) {\n if(map.get(p[num]) != null) return false;\n num = p[num];\n }\n //check Decendant\n Queue q = new LinkedList<>();\n List child = children.get(ori);\n if(child != null) {\n for(int c : child) q.offer(c);\n }\n boolean lock = false;\n while(!q.isEmpty()) {\n int cur = q.poll();\n if(map.get(cur) != null) {\n lock = true;\n map.remove(cur); // unlock\n }\n List cc = children.get(cur);\n if(cc != null) {\n for(int c : cc) q.offer(c);\n }\n } \n if(!lock) return false;\n map.put(ori, user); // lock the original node\n return true;\n }\n}\n", + "title": "1993. Operations on Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the i th node. The root of the tree is node 0 , so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class:", + "description_images": [], + "constraints": [ + "Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.", + "Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.", + "Upgrade : Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors.", + "The node is unlocked,", + "It has at least one locked descendant (by any user), and", + "It does not have any locked ancestors." + ], + "examples": [ + { + "text": "Example 1: Input[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]Output[null, true, false, true, true, true, false]ExplanationLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.", + "image": "https://assets.leetcode.com/uploads/2021/07/29/untitled.png" + } + ], + "follow_up": null, + "solution": "class LockingTree:\n\n def __init__(self, parent: List[int]):\n self.p = collections.defaultdict(lambda: -2)\n self.c = collections.defaultdict(list)\n for i, p in enumerate(parent):\n self.c[p].append(i)\n self.p[i] = p\n self.user = collections.defaultdict(set)\n self.node = collections.defaultdict(lambda: -2)\n\n def lock(self, num: int, user: int) -> bool:\n if self.node[num] == -2:\n self.user[user].add(num)\n self.node[num] = user\n return True\n return False \n\n def unlock(self, num: int, user: int) -> bool:\n if self.node[num] == user: \n del self.node[num]\n self.user[user].remove(num)\n return True\n return False \n\n def upgrade(self, num: int, user: int) -> bool:\n if self.node[num] != -2: return False\n if not self.has_locked_descendant(num): return False\n if self.has_locked_ancester(num): return False\n self.lock(num, user)\n self.unlock_descendant(num)\n return True\n \n def has_locked_descendant(self, num): #function to check if alteast one desendent is lock or not \n has = False\n for child in self.c[num]:\n if self.node[child] != -2:\n return True\n has |= self.has_locked_descendant(child)\n return has \n \n def has_locked_ancester(self, num): # function to check if no parent is locked \n if num == -1: return False\n if self.node[self.p[num]] != -2:\n return True\n return self.has_locked_ancester(self.p[num])\n\n def unlock_descendant(self, num): # function fro unlocking all desendents \n for child in self.c[num]:\n if child in self.node:\n user = self.node[child]\n del self.node[child]\n if user in self.user:\n self.user[user].remove(child)\n self.unlock_descendant(child)\n", + "title": "1993. Operations on Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The adjacent integers in nums will perform the float division. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return the corresponding expression that has the maximum value in string format . Note: your expression should not contain redundant parenthesis.", + "description_images": [], + "constraints": [ + "For example, for nums = [2,3,4] , we will evaluate the expression \"2/3/4\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1000,100,10,2]\nOutput:\"1000/(100/10/2)\"\nExplanation:1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant, since they don't influence the operation priority. So you should return \"1000/(100/10/2)\".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,4]\nOutput:\"2/(3/4)\"", + "image": null + }, + { + "text": "Example 3: Input:nums = [2]\nOutput:\"2\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 33.5%) | Memory: 41.11 MB (Top 16.7%)\n\nclass Solution {\n public String optimalDivision(int[] nums) {\n \n if(nums.length==1){\n return nums[0] + \"\";\n }else if(nums.length==2){\n StringBuilder sb=new StringBuilder();\n sb.append(nums[0] + \"/\" + nums[1]);\n return sb.toString();\n }\n \n StringBuilder sb=new StringBuilder();\n sb.append(nums[0]);\n sb.append(\"/(\");\n for(int i=1;i str:\n if k>1:\n s=list(c for c in s)\n s.sort()\n return ''.join(s)\n s1=s\n for i in range(len(s)):\n s=s[1:]+s[0]\n s1=min(s1,s)\n return s1", + "title": "899. Orderly Queue", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn] . You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m , n , maxMove , startRow , startColumn , return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "0 <= maxMove <= 50", + "0 <= startRow < m", + "0 <= startColumn < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png" + }, + { + "text": "Example 2: Input:m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\nOutput:12", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 36.40%) | Memory: 43.3 MB (Top 32.31%)\nclass Solution {\n int[][][] dp;\n int mod = 1000000007;\n public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n dp = new int[m][n][maxMove + 1];\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n for (int k = 0; k <= maxMove; k++)\n dp[i][j][k] = -1;\n return count(m, n, maxMove, startRow, startColumn) % mod;\n }\n public int count(int m, int n, int move, int r, int c) {\n if (r < 0 || c < 0 || r >= m || c >= n)\n return 1;\n if (move <= 0)\n return 0;\n if (dp[r][c][move] != -1)\n return dp[r][c][move] % mod;\n dp[r][c][move] = ((count(m, n, move - 1, r + 1, c) % mod + count (m, n, move - 1, r - 1, c) % mod) % mod + (count (m, n, move - 1, r, c + 1) % mod + count(m, n, move - 1, r, c - 1) % mod) % mod ) % mod;\n return dp[r][c][move] % mod;\n }\n}", + "title": "576. Out of Boundary Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn] . You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m , n , maxMove , startRow , startColumn , return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "0 <= maxMove <= 50", + "0 <= startRow < m", + "0 <= startColumn < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png" + }, + { + "text": "Example 2: Input:m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\nOutput:12", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int:\n if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n:\n return 1\n \n if dp[maxMove][startRow][startColumn]!=-1:\n return dp[maxMove][startRow][startColumn]\n \n if mat[startRow][startColumn]==1:\n return 0\n \n if maxMove <= 0:\n return 0\n \n # mat[startRow][startColumn] = 1\n a = self.helper(m, n, maxMove-1, startRow+1, startColumn,mat,dp)\n b = self.helper(m, n, maxMove-1, startRow-1, startColumn,mat,dp)\n c = self.helper(m, n, maxMove-1, startRow, startColumn+1,mat,dp)\n d = self.helper(m, n, maxMove-1, startRow, startColumn-1,mat,dp)\n dp[maxMove][startRow][startColumn] = a+b+c+d\n return dp[maxMove][startRow][startColumn]\n \n \n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n mat = [[0 for i in range(n)] for j in range(m)]\n dp = [[[-1 for i in range(n+1)] for j in range(m+1)] for k in range(maxMove+1)]\n return self.helper(m, n, maxMove, startRow, startColumn, mat,dp)%(10**9 + 7) \n \n\n \n", + "title": "576. Out of Boundary Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == heights.length", + "n == heights[r].length", + "1 <= m, n <= 200", + "0 <= heights[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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]]\nOutput:[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]", + "image": "https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg" + }, + { + "text": "Example 2: Input:heights = [[2,1],[1,2]]\nOutput:[[0,0],[0,1],[1,0],[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 37.68%) | Memory: 54.9 MB (Top 45.37%)\nclass Solution {\n public List> pacificAtlantic(int[][] heights) {\n if (heights == null) return null;\n if (heights.length == 0) return null;\n if (heights[0].length == 0) return null;\n\n /** */\n boolean [][] po = new boolean[heights.length][heights[0].length];\n boolean [][] ao = new boolean[heights.length][heights[0].length];\n\n for (int i = 0; i < heights[0].length; i ++) {\n dfs(heights, i, 0, 0, po); // top\n dfs(heights, i, heights.length - 1, 0, ao); // bottom\n }\n\n for (int i = 0; i < heights.length; i ++) {\n dfs(heights, 0, i, 0, po); // left\n dfs(heights, heights[0].length - 1, i, 0, ao); // right\n }\n\n List> ans = new ArrayList<>();\n for (int i = 0; i < heights.length; i ++) {\n for (int j = 0; j < heights[i].length; j ++) {\n if (ao[i][j] && po[i][j]) {\n ArrayList ar = new ArrayList<>();\n ar.add(i);\n ar.add(j);\n ans.add(ar);\n }\n }\n }\n\n return ans;\n }\n\n private void dfs(int[][] heights, int x, int y, int h, boolean[][] v) {\n if (x < 0 || y < 0 || x >= heights[0].length || y >= heights.length) return;\n if (v[y][x] || heights[y][x] < h) return;\n v[y][x] = true;\n /** left */\n dfs(heights, x - 1, y, heights[y][x], v);\n\n /** right */\n dfs(heights, x + 1, y, heights[y][x], v);\n\n /** up */\n dfs(heights, x, y - 1, heights[y][x], v);\n\n /** down */\n dfs(heights, x, y + 1, heights[y][x], v);\n }\n}", + "title": "417. Pacific Atlantic Water Flow", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == heights.length", + "n == heights[r].length", + "1 <= m, n <= 200", + "0 <= heights[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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]]\nOutput:[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]", + "image": "https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg" + }, + { + "text": "Example 2: Input:heights = [[2,1],[1,2]]\nOutput:[[0,0],[0,1],[1,0],[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n # Purpose: find the cells that allow rain flow into the ocean\n # Method: DFS\n # Intuition: start from each border, check cell and neb, if OK, append to res\n \n # init: res, vis (pac, atl), ROW, COL\n res = []\n pac = set()\n atl = set()\n ROW = len(heights)\n COL = len(heights[0])\n\n # top and bottom row\n for col in range(COL):\n self.dfs(0, col, pac, heights[0][col], heights)\n self.dfs(ROW-1, col, atl, heights[ROW-1][col], heights)\n\n # left and right col\n for row in range(ROW):\n self.dfs(row, 0, pac, heights[row][0], heights)\n self.dfs(row, COL-1, atl, heights[row][COL-1], heights)\n\n # append to res\n for row in range(ROW):\n for col in range(COL):\n if (row, col) in pac and (row, col) in atl:\n res.append([row, col])\n\n # return\n return res\n\n \n def dfs(self, row, col, vis, prev, heights):\n # hard-code definition\n try:\n cur = heights[row][col]\n except:\n pass\n\n # inbound, unvisited, increase from ocean\n if (0<=row= prev) \\\n and ((row, col) not in vis):\n\n # add to visited \n vis.add((row, col))\n\n # check nebs\n self.dfs(row+1, col, vis, cur, heights)\n self.dfs(row-1, col, vis, cur, heights)\n self.dfs(row, col+1, vis, cur, heights)\n self.dfs(row, col-1, vis, cur, heights)\n\n", + "title": "417. Pacific Atlantic Water Flow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n ), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. Given an array houses , an m x n matrix cost and an integer target where: Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods . If it is not possible, return -1 .", + "description_images": [], + "constraints": [ + "For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}] ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput:9\nExplanation:Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.", + "image": null + }, + { + "text": "Example 2: Input:houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput:11\nExplanation:Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.", + "image": null + }, + { + "text": "Example 3: Input:houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput:-1\nExplanation:Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 34.94%) | Memory: 52.8 MB (Top 34.74%)\nclass Solution {\n public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp)\n {\n if(idx==houses.length || neigh>target)\n {\n if(neigh==target)\n return 0;\n return Integer.MAX_VALUE;\n }\n if(dp[idx][prevColor][neigh]!=null)\n return dp[idx][prevColor][neigh];\n int minCost = Integer.MAX_VALUE;\n\n if(houses[idx]==0)\n {\n for(int j = 0;j int:\n @cache\n def dp(i, p, h):\n if (h > target) or (i == m and h != target):\n return inf\n if i == m:\n return 0\n if houses[i] != 0:\n return dp(i + 1, houses[i], h + int(p != houses[i]))\n\n best = inf\n for j, c in enumerate(cost[i], 1):\n best = min(best, dp(i + 1, j, h + int(p != j)) + c)\n return best\n\n res = dp(0, 0, 0)\n return res if res != inf else -1\n", + "title": "1473. Paint House III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers m and n . Consider an m x n grid where each cell is initially white. You can paint each cell red , green , or blue . All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color . Since the answer can be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= m <= 5", + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:m = 1, n = 1\nOutput:3\nExplanation:The three possible colorings are shown in the image above.", + "image": "https://assets.leetcode.com/uploads/2021/06/22/colorthegrid.png" + }, + { + "text": "Example 2: Input:m = 1, n = 2\nOutput:6\nExplanation:The six possible colorings are shown in the image above.", + "image": "https://assets.leetcode.com/uploads/2021/06/22/copy-of-colorthegrid.png" + }, + { + "text": "Example 3: Input:m = 5, n = 5\nOutput:580986", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n public static void val(ArrayList arr,int color,int m,String s)\n {\n if(m==0)\n {\n arr.add(s);\n return;\n }\n for(int i=0;i<3;i++)\n {\n if(color!=i)\n val(arr,i,m-1,s+i);\n }\n }\n public static boolean Match(String s,String s1)\n {\n for(int i=0;i arr=new ArrayList();\n for(int i=0;i<3;i++)\n {\n String s=\"\";\n val(arr,i,m-1,s+i);\n }\n ArrayList> adj=new ArrayList>();\n for(int i=0;i());\n }\n \n for(int i=0;i int:\n from functools import reduce\n MOD = 10**9 + 7\n sum_mod = lambda x,y: (x+y)%MOD\n \n def normalize(pat_var):\n mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n return tuple([ mapping[e] for e in pat_var])\n \n def get_pats(m, i, pat, pats):\n if i == m-1:\n pats.append(tuple(pat))\n return\n i_nx = i+1\n for p_it_nx in (1,2,3):\n if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n pat.append(p_it_nx)\n get_pats(m, i_nx, pat, pats)\n pat.pop()\n return pats\n \n def get_trans(pat, i, pat_pre, trans):\n if i == len(pat)-1:\n pat_nl = normalize(pat_pre)\n trans[pat_nl] = trans.get(pat_nl, 0) + 1\n return\n for p_it_pre in (1,2,3):\n i_nx = i+1\n if (p_it_pre != pat[i_nx]\n and (not pat_pre or p_it_pre != pat_pre[-1])):\n pat_pre.append(p_it_pre)\n get_trans(pat, i_nx, pat_pre, trans)\n pat_pre.pop()\n return trans\n\n pats = get_pats(m, -1, [], [])\n # {pattern_i: {pattern_pre:count}}\n pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } \n \n p_counts = { pat:1 for pat in pat_trans.keys() }\n for i in range(n-1):\n p_counts_new = {}\n for pat, trans in pat_trans.items():\n p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n p_counts = p_counts_new\n \n res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n return (res * perms) % MOD\n", + "title": "1931. Painting a Grid With Three Different Colors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return true if it is a palindrome.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 10^5 ] .", + "0 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,2,1]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(ListNode head) {\n \n ListNode mid = getMiddle(head);\n ListNode headSecond = reverse(mid);\n ListNode reverseHead = headSecond;\n \n while(head != null && headSecond != null){\n if(head.val != headSecond.val){\n break;\n }\n head = head.next;\n headSecond = headSecond.next;\n }\n reverse(reverseHead);\n \n return head==null || headSecond == null;\n }\n \n public ListNode reverse(ListNode head){\n if(head==null) return head;\n ListNode prev = null;\n ListNode present = head;\n ListNode next = head.next;\n while(present != null){\n present.next = prev;\n prev = present;\n present = next;\n if(next!=null)\n next = next.next;\n }\n return prev;\n }\n \n public ListNode getMiddle(ListNode head){\n ListNode temp = head;\n int count = 0;\n while(temp!=null){\n temp = temp.next;\n count++;\n }\n int mid = count/2;\n temp = head;\n for(int i=0; i bool:\n if head.next == None: return True #if only 1 element, it's always a palindrome\n forward = head\n first_half = []\n fast = head\n\n while (fast != None and fast.next != None):\n first_half.append(forward.val)\n forward = forward.next\n fast = fast.next.next\n\n # forward should now be through half the list\n if fast != None : forward = forward.next # if length isn't even, skip the middle number\n \n reverse = len(first_half)-1\n while forward != None:\n if forward.val != first_half[reverse]: return False\n forward = forward.next\n reverse -= 1\n\n return True\n", + "title": "234. Palindrome Linked List", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer x , return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward.", + "description_images": [], + "constraints": [ + "For example, 121 is a palindrome while 123 is not." + ], + "examples": [ + { + "text": "Example 1: Input:x = 121\nOutput:true\nExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121\nOutput:false\nExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10\nOutput:false\nExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 39.53%) | Memory: 44.7 MB (Top 53.62%)\nclass Solution {\n public boolean isPalindrome(int x) {\n int sum = 0;\n int X = x;\n\n while(x > 0){\n sum = 10 * sum + x % 10;\n x /= 10;\n }\n\n return sum == X;\n }\n}", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer x , return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward.", + "description_images": [], + "constraints": [ + "For example, 121 is a palindrome while 123 is not." + ], + "examples": [ + { + "text": "Example 1: Input:x = 121\nOutput:true\nExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121\nOutput:false\nExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10\nOutput:false\nExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 94.40%) | Memory: 13.8 MB (Top 59.53%)\nclass Solution(object):\n def isPalindrome(self,x):\n return str(x) == str(x)[::-1]", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 5000", + "0 <= words[i].length <= 300", + "words[i] consists of lower-case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\nOutput:[[0,1],[1,0],[3,2],[2,4]]\nExplanation:The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"bat\",\"tab\",\"cat\"]\nOutput:[[0,1],[1,0]]\nExplanation:The palindromes are [\"battab\",\"tabbat\"]", + "image": null + }, + { + "text": "Example 3: Input:words = [\"a\",\"\"]\nOutput:[[0,1],[1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 117 ms (Top 97.32%) | Memory: 56.20 MB (Top 42.83%)\n\n//149ms\n\nclass Solution {\n public List> palindromePairs(String[] words) {\n HashMap wordMap = new HashMap<>();\n Set set = new TreeSet<>();\n int n = words.length;\n \n for(int i=0;i> ans = new ArrayList<>();\n \n for(int i=0;i List[List[int]]:\n m = {}\n for i, word in enumerate(words):\n m[word] = i\n \n result = set()\n for i, word in enumerate(words):\n n, rev_word = len(word), word[::-1]\n prefix, suffix = word, rev_word\n \n for j in range(n+1):\n if prefix == suffix:\n key = rev_word[:j]\n if key in m and m[key] != i:\n result.add((m[key], i))\n \n if j == n:\n break\n \n prefix = prefix[:-1]\n suffix = suffix[1:]\n \n # print('pre', i, result)\n \n prefix, suffix = '', ''\n for j in range(n+1):\n if prefix == suffix:\n if prefix == suffix:\n key = rev_word[j:]\n if key in m and m[key] != i:\n result.add((i, m[key]))\n \n if j == n:\n break\n \n prefix = word[n-j-1] + prefix\n suffix = suffix + rev_word[j]\n \n # print('post', i, result)\n \n return list(result)\n", + "title": "336. Palindrome Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome . Return all possible palindrome partitioning of s . A palindrome string is a string that reads the same backward as forward.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 25.04%) | Memory: 136.1 MB (Top 72.32%)\n// Plaindrome Partitioning\n// Leetcode : https://leetcode.com/problems/palindrome-partitioning/\n\nclass Solution {\n public List> partition(String s) {\n List> result = new ArrayList<>();\n if(s == null || s.length() == 0)\n return result;\n helper(s, 0, new ArrayList(), result);\n return result;\n }\n private void helper(String s, int start, List list, List> result){\n if(start == s.length()){\n result.add(new ArrayList<>(list));\n return;\n }\n for(int i = start; i < s.length(); i++){\n if(isPalindrome(s, start, i)){\n list.add(s.substring(start, i+1));\n helper(s, i+1, list, result);\n list.remove(list.size()-1);\n }\n }\n }\n private boolean isPalindrome(String s, int start, int end){\n while(start < end){\n if(s.charAt(start++) != s.charAt(end--))\n return false;\n }\n return true;\n }\n}", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome . Return all possible palindrome partitioning of s . A palindrome string is a string that reads the same backward as forward.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1302 ms (Top 13.95%) | Memory: 35.7 MB (Top 6.05%)\n\"\"\"\nwe can approach this problem using manacher's algorithm with backtracking and recursion\n\"\"\"\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n lookup = {\"\": [[]]}\n def lps(s):\n if s in lookup:\n return lookup[s]\n\n final_res = []\n result_set = set()\n for k in range(len(s)):\n i, j = k, k\n\n # check for odd length palindromes\n while i>= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n\n # check for even length palindromes\n i, j = k, k+1\n while i >= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n lookup[s] = final_res\n return final_res\n return lps(s)", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:1\nExplanation:The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\nint dp[];\n\n public boolean pali(int i,int j,String s){\n \n // int j=s.length()-1,i=0;\n \n while(i<=j){\n \n if(s.charAt(i)!=s.charAt(j))return false;\n \n i++;j--;\n \n }\n \n return true;\n \n}\npublic int cut(String s,int i,int n,int dp[]){\n \n if(i==n)return 0;\n if(dp[i]!=-1)return dp[i];\n \n int min=Integer.MAX_VALUE;\n \n for(int j=i;j bool:\n st = s[l: r+1]\n rev = st[::-1]\n return st == rev\n \n def minCut(self, s: str) -> int:\n N = len(s)\n if not s: return 0\n if self.isPallindrom(s, 0, N-1): return 0\n dp = [sys.maxsize] * (N+1)\n dp[-1] = 0\n \n for i in range(N-1, -1, -1):\n for j in range(i, N):\n if self.isPallindrom(s, i, j):\n dp[i] = min(dp[i], 1 + dp[j+1])\n \n return dp[0]-1\n", + "title": "132. Palindrome Partitioning II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s containing lowercase letters and an integer k . You need to : Return the minimal number of characters that you need to change to divide the string .", + "description_images": [], + "constraints": [ + "First, change some characters of s to other lowercase English letters.", + "Then divide s into k non-empty disjoint substrings such that each substring is a palindrome." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", k = 2\nOutput:1\nExplanation:You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbc\", k = 3\nOutput:0\nExplanation:You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 8\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 26.09%) | Memory: 55.8 MB (Top 6.28%)\nclass Solution {\n public int mismatchCount(String s) {\n int n = s.length()-1;\n int count = 0;\n for(int i=0,j=n;i=n)\n return 105;\n if(k<0)\n return 105;\n if(dp[i][j][k] != null) {\n return dp[i][j][k];\n }\n if(n-j int:\n n=len(s)\n @lru_cache(None)\n def is_palin(s): #This function returns min no of chars to change to make s as a palindrome\n cnt=0\n for c1,c2 in zip(s,s[::-1]):\n if c1!=c2: cnt+=1\n if len(s)%2==0:\n return cnt//2\n return (cnt+1)//2\n @lru_cache(None)\n def dp(i,j,k): #We analyse string s[i:j+1] with k divisions left\n if j==n:\n return 0 if k==0 else sys.maxsize\n if k==0: \n return sys.maxsize\n ans=sys.maxsize\n cnt=is_palin(s[i:j+1])\n #terminate here\n ans=min(ans,dp(j+1,j+1,k-1)+cnt)\n #dont terminate\n ans=min(ans,dp(i,j+1,k))\n return ans\n return dp(0,0,t)\n \n \n \n", + "title": "1278. Palindrome Partitioning III", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false .​​​​​ A string is said to be palindrome if it the same string when reversed.", + "description_images": [], + "constraints": [ + "3 <= s.length <= 2000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcbdd\"\nOutput:true\nExplanation:\"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bcbddxy\"\nOutput:false\nExplanation:s cannot be split into 3 palindromes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkPartitioning(String s) {\n int n = s.length();\n boolean[][] dp = new boolean[n][n];\n for(int g=0 ; g bool:\n n = len(s)\n\n @lru_cache(None)\n def pal(i,j):\n if i == j:\n return True\n if s[i] != s[j]:\n return False\n if i+1 == j:\n return True\n else:\n return pal(i+1,j-1)\n\n for i in range(n-2):\n if pal(0,i):\n for j in range(i+1,n-1):\n if pal(i+1,j) and pal(j+1,n-1):\n return True\n return False", + "title": "1745. Palindrome Partitioning IV", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"\nOutput:3\nExplanation:Three palindromic strings: \"a\", \"b\", \"c\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\"\nOutput:6\nExplanation:Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "int n = s.length();\n int count = 0;\n for(int i = 0;i=0 && r=0 && r pancakeSort(int[] arr) {\n List list = new ArrayList<>();\n int n = arr.length;\n while(n!=1) {\n int maxIndex = findIndex(arr,n);\n reverse(arr, maxIndex);\n reverse(arr, n-1);\n list.add(maxIndex+1);\n list.add(n);\n n--;\n }\n return list;\n }\n\n static int findIndex(int[] arr, int value) {\n for(int i=0; i List[int]:\n #helper function to flip the numbers in the array\n\t\tdef flip(i, j):\n while i < j:\n arr[i], arr[j] = arr[j], arr[i]\n j -= 1\n i += 1\n \n #sort from 0 to i\n def sort(i):\n\t\t\t#base case where all the numbers are sorted, thus no more recursive calls\n if i < 0:\n return []\n ret = []\n\t\t\t#find the biggest number, which always will be the len(arr), or i + 1\n idx = arr.index(i + 1)\n\t\t\t# if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number\n if idx == i:\n return sort(i - 1)\n \n\t\t\t#we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result\n ret.append(idx + 1)\n flip(0, idx)\n\t\t\t#we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well)\n ret.append(i + 1)\n flip(0, i)\n\t\t\t#sort the next biggest number by setting a new boundary i - 1\n return ret + sort(i - 1)\n \n \n return sort(len(arr) - 1)\n \n", + "title": "969. Pancake Sorting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n , which indicates that there are n courses labeled from 1 to n . You are also given an array relations where relations[i] = [prevCourse i , nextCourse i ] , representing a prerequisite relationship between course prevCourse i and course nextCourse i : course prevCourse i has to be taken before course nextCourse i . Also, you are given the integer k . In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking. Return the minimum number of semesters needed to take all courses . The testcases will be generated such that it is possible to take every course.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_1.png", + "https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_2.png" + ], + "constraints": [ + "1 <= n <= 15", + "1 <= k <= n", + "0 <= relations.length <= n * (n-1) / 2", + "relations[i].length == 2", + "1 <= prevCourse i , nextCourse i <= n", + "prevCourse i != nextCourse i", + "All the pairs [prevCourse i , nextCourse i ] are unique .", + "The given graph is a directed acyclic graph." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2\nOutput:3\nExplanation:The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput:4\nExplanation:The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3 only since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.", + "image": null + }, + { + "text": "Example 3: Input:n = 11, dependencies = [], k = 2\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 435 ms (Top 42.70%) | Memory: 45.5 MB (Top 33.71%)\nclass Solution {\n public int minNumberOfSemesters(int n, int[][] relations, int k) {\n int[] ok = new int[1 << n];\n int[] dp = new int[1 << n];\n Arrays.fill(dp, 30);\n dp[0]=0;\n for (int[] r : relations){\n ok[r[1]-1] |= 1<<(r[0]-1);\n }\n for (int i = 0; i < 1< 0; i++){\n if ((old&(1< int:\n graph = [0] * n\n out_degree = [0] * n\n # -1 to fix 1-based indexing offset from prompt.\n for pre_req, course in relations:\n graph[course-1] += 1 << (pre_req-1)\n out_degree[pre_req-1] += 1\n # Just converts course to its shifted value\n c2shift = [1< k)\n for batch in itertools.combinations(pre_reqs, k):\n diff = sum(batch)\n t = course_total + diff\n if t == goal:\n return steps + 1\n if not seen[t]:\n queue.append((t, steps+1))\n seen[t] = 1![Uploading file...]()\n\n", + "title": "1494. Parallel Courses II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n , which indicates that there are n courses labeled from 1 to n . You are also given a 2D integer array relations where relations[j] = [prevCourse j , nextCourse j ] denotes that course prevCourse j has to be completed before course nextCourse j (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1) th course. You must find the minimum number of months needed to complete all the courses following these rules: Return the minimum number of months needed to complete all the courses . Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).", + "description_images": [], + "constraints": [ + "You may start taking a course at any time if the prerequisites are met.", + "Any number of courses can be taken at the same time ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\nOutput:8\nExplanation:The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\nOutput:12\nExplanation:The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 58 ms (Top 49.87%) | Memory: 123 MB (Top 65.81%)\nclass Solution {\n public int minimumTime(int n, int[][] relations, int[] time) {\n List adj[] = new ArrayList[n];\n int indegree[] = new int[n];\n int completionTime[] = new int[n];\n for(int i=0; i();\n for(int relation[]: relations){\n int u = relation[0]-1, v = relation[1]-1;\n adj[u].add(v);\n indegree[v]++;\n }\n Queue q = new LinkedList<>();\n for(int i=0; i int:\n in_degree=defaultdict(int)\n graph=defaultdict(list)\n latest=[0]*(n+1)\n for u,v in relations:\n graph[u].append(v)\n in_degree[v]+=1\n q=[]\n for i in range(1,n+1):\n if in_degree[i]==0:\n latest[i]=time[i-1]\n q.append(i)\n while q:\n node=q.pop()\n t0=latest[node]\n for nei in graph[node]:\n t=time[nei-1]\n latest[nei]=max(latest[nei],t0+t)\n in_degree[nei]-=1\n if in_degree[nei]==0:\n q.append(nei)\n return max(latest)\n", + "title": "2050. Parallel Courses III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows.", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput:14\nExplanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"\nOutput:2\nExplanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput:5\nExplanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 68.0%) | Memory: 41.90 MB (Top 62.0%)\n\nclass Solution {\n Map vars = new HashMap<>();\n\n public int evaluate(String expression) {\n String[] strs = split(expression);\n\n switch (strs[0]) {\n case \"let\":\n Map localVars = new HashMap<>(vars);\n Map temp = vars;\n for (int i = 1; i < strs.length - 1; i++) {\n String name = strs[i];\n int val = evaluate(strs[i + 1]);\n if (localVars.containsKey(name)) localVars.replace(name, val);\n else localVars.put(name, val);\n i++;\n vars = localVars;\n }\n int res = evaluate(strs[strs.length - 1]);\n vars = temp;\n return res;\n\n case \"add\":\n return evaluate(strs[1]) + evaluate(strs[2]);\n\n case \"mult\":\n return evaluate(strs[1]) * evaluate(strs[2]);\n\n default:\n try {\n return Integer.parseInt(strs[0]);\n } catch (Exception e) {\n return vars.get(strs[0]);\n }\n }\n }\n\n private String[] split(String exp) {\n List tokens = new ArrayList<>();\n\n if (exp.charAt(0) != '(') {\n tokens.add(exp);\n }\n else {\n tokens.add(exp.substring(1, exp.indexOf(' ')));\n\n for (int i = exp.indexOf(' ') + 1; i < exp.length(); i++) {\n if (exp.charAt(i) == ')') break;\n else if (exp.charAt(i) == ' ') continue;\n\n if (tokens.get(0).equals(\"let\") && tokens.size() % 2 == 1 && exp.charAt(i) != '(' && exp.indexOf(' ', i) > 0) {\n tokens.add(exp.substring(i, exp.indexOf(' ', i + 1)));\n i = exp.indexOf(' ', i + 1) + 1;\n }\n\n if (exp.charAt(i) != '(') {\n int index = exp.indexOf(' ', i + 1);\n if (index < 0) index = exp.indexOf(')', i + 1);\n tokens.add(exp.substring(i, index).trim());\n i = index;\n } else {\n int stack = 1;\n int j = i + 1;\n while (stack > 0) {\n if (exp.charAt(j) == '(') stack++;\n else if (exp.charAt(j) == ')') stack--;\n j++;\n }\n tokens.add(exp.substring(i, j));\n i = j;\n }\n }\n }\n\n return tokens.toArray(new String[0]);\n }\n}\n", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows.", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput:14\nExplanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"\nOutput:2\nExplanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput:5\nExplanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n String expression;\n int index;\n HashMap> scope; \n //variable may be assigned many times, we use the peek value \n \n public int evaluate(String expression) {\n this.expression=expression;\n index=0;\n scope=new HashMap<>();\n return evaluate();\n }\n \n private int evaluate(){\n \n if(expression.charAt(index)=='('){\n //this is an expression\n index++; //skip '('\n char begin=expression.charAt(index);\n int ret;\n if(begin=='l'){\n //let\n index += 4; //skip let and a blank space\n ArrayList vars=new ArrayList<>();\n while(true){\n if(!Character.isLowerCase(expression.charAt(index))){\n ret=evaluate();\n break;\n }\n String var=parseVar();\n if(expression.charAt(index)==')'){\n ret=scope.get(var).peek();\n break;\n }\n vars.add(var);\n index++;\n int e=evaluate();\n scope.putIfAbsent(var, new LinkedList<>());\n scope.get(var).push(e); //assign a new value\n index++;\n }\n for (String var : vars) {\n scope.get(var).pop(); // remove all values of this scope\n }\n\n } else if(begin=='a') {\n //add\n index += 4;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1+v2;\n } else {\n //multi\n index += 5;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1*v2;\n }\n index++; // skip ')'\n return ret;\n } else {\n //this is not a expression, this is an integer or a variable\n if(Character.isLowerCase(expression.charAt(index))){\n\t\t\t\t//this is a variable, the current value is peek value\n String var=parseVar();\n return scope.get(var).peek();\n } else {\n\t\t\t\t//this is an integer\n return parseInt();\n }\n }\n }\n \n //read an integer\n private int parseInt(){\n boolean negative=false;\n if(expression.charAt(index)=='-'){\n negative=true;\n index++;\n }\n int ret=0;\n while(Character.isDigit(expression.charAt(index))){\n ret*=10;\n ret+=expression.charAt(index)-'0';\n index++;\n }\n if(negative) return -ret;\n return ret;\n }\n \n //read a variable\n private String parseVar(){\n StringBuilder sb=new StringBuilder();\n char c=expression.charAt(index);\n while(c!=' ' && c!=')'){\n sb.append(c);\n c=expression.charAt(++index);\n }\n return sb.toString();\n }\n}\n", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows.", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput:14\nExplanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"\nOutput:2\nExplanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput:5\nExplanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evaluate(self, expression: str) -> int:\n loc = {}\n stack = []\n for i, x in enumerate(expression): \n if x == \"(\": stack.append(i)\n elif x == \")\": loc[stack.pop()] = i\n \n def fn(lo, hi, mp): \n \"\"\"Return value of given expression.\"\"\"\n if expression[lo] == \"(\": return fn(lo+1, hi-1, mp)\n i = lo\n vals = []\n while i < hi: \n if expression[i:i+3] in (\"let\", \"add\"): \n op = expression[i:i+3]\n i += 3\n elif expression[i:i+4] == \"mult\": \n op = \"mult\"\n i += 4\n elif expression[i].isalpha(): \n x = \"\"\n while i < hi and expression[i].isalnum(): \n x += expression[i]\n i += 1\n if op in (\"add\", \"mult\"): vals.append(mp[x])\n elif expression[i].isdigit() or expression[i] == \"-\": \n v = \"\"\n while i < hi and (expression[i].isdigit() or expression[i] == \"-\"): \n v += expression[i]\n i += 1\n if op == \"let\": mp[x] = int(v)\n else: vals.append(int(v))\n elif expression[i] == \"(\": \n v = fn(i+1, loc[i], mp.copy())\n i = loc[i] + 1\n if op == \"let\": mp[x] = v\n else: vals.append(v)\n else: i += 1\n if op == \"let\": return int(v)\n elif op == \"add\": return sum(vals)\n else: return reduce(mul, vals)\n \n return fn(0, len(expression), {})", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Return the result of evaluating a given boolean expression , represented as a string. An expression can either be:", + "description_images": [], + "constraints": [ + "\"t\" , evaluating to True ;", + "\"f\" , evaluating to False ;", + "\"!(expr)\" , evaluating to the logical NOT of the inner expression expr ;", + "\"&(expr1,expr2,...)\" , evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ... ;", + "\"|(expr1,expr2,...)\" , evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ..." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"!(f)\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:expression = \"|(f,t)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:expression = \"&(t,f)\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.8%) | Memory: 40.90 MB (Top 99.4%)\n\nclass Solution {\n \n int pos = 0;\n \n public boolean parseBoolExpr(String s) {\n pos = 0;\n return solve(s, '-');\n }\n \n public boolean solve(String s, char prev_sign) {\n \n boolean res = s.charAt(pos) == 'f' ? false : true;\n char cur_sign = ' ';\n int flag_res_init = 0;\n while(pos < s.length()) {\n \n char cur_char = s.charAt(pos++);\n \n if(isExpr(cur_char)){\n res = eval(cur_char == 't'?true:false, res , prev_sign);\n }\n else if(isSign(cur_char)){\n cur_sign = cur_char;\n }\n else if(cur_char == '('){\n if(flag_res_init == 1 || prev_sign == '!')\n res = eval(solve(s, cur_sign), res, prev_sign);\n else {\n res = solve(s, cur_sign);\n flag_res_init = 1;\n }\n }\n else if(cur_char == ')'){\n return res;\n }\n \n }\n return res;\n }\n \n public boolean isExpr(char c){\n return (c == 'f' || c == 't');\n }\n \n public boolean isSign(char c){\n return (c == '!' || c == '&' || c == '|');\n }\n \n public boolean eval(boolean e1, boolean e2, char sign) {\n \n boolean res = false;\n if(sign == '!')\n res = !e1;\n \n else if(sign == '|')\n res = e1 | e2;\n \n else if(sign == '&')\n res = e1&e2;\n \n return res;\n }\n}", + "title": "1106. Parsing A Boolean Expression", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Return the result of evaluating a given boolean expression , represented as a string. An expression can either be:", + "description_images": [], + "constraints": [ + "\"t\" , evaluating to True ;", + "\"f\" , evaluating to False ;", + "\"!(expr)\" , evaluating to the logical NOT of the inner expression expr ;", + "\"&(expr1,expr2,...)\" , evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ... ;", + "\"|(expr1,expr2,...)\" , evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ..." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"!(f)\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:expression = \"|(f,t)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:expression = \"&(t,f)\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n \n # expresssion map\n opMap = {\"!\" : \"!\", \"|\" : \"|\" , \"&\" : \"&\"}\n expMap = {\"t\" : True, \"f\" : False}\n expStack = []\n opStack = []\n ans = 0\n i = 0\n \n while i < len(expression):\n \n if expression[i] in opMap:\n opStack.append(opMap[expression[i]])\n \n elif expression[i] in expMap:\n expStack.append(expMap[expression[i]])\n \n elif expression[i] == \"(\":\n expStack.append(\"(\")\n \n # strat performing operations\n elif expression[i] == \")\":\n op = opStack.pop()\n ans = [] # evaluator arr\n \n # To Check\n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"outer WHILE\")\n \n # Performing serries of operation on exp inside a ()\n while expStack[-1] != \"(\":\n \n # To check \n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"OPerator :- \",op, \"INNER WHILE\")\n \n # Not single operation only\n if op == \"!\":\n ans.append(not expStack.pop())\n else:\n ans.append(expStack.pop())\n \n # Operation evaluation for more then 1 exp inside () for &, or\n while len(ans) > 1:\n # or\n if op == \"|\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 or exp2\n ans.append(res)\n # and\n elif op == \"&\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 and exp2\n ans.append(res)\n \n # poping \")\" and adding the res of operation done above\n expStack.pop() # poping \")\"\n expStack.append(ans[-1])\n \n # increment i \n i += 1\n \n return expStack[-1]\n \n \n\"\"\"\nTC : O(n * m) | n = len(expression), m = no of expression inside a prenthesis\nSc : O(n)\n\"\"\"\n", + "title": "1106. Parsing A Boolean Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums and an integer pivot . Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement.", + "description_images": [], + "constraints": [ + "Every element less than pivot appears before every element greater than pivot .", + "Every element equal to pivot appears in between the elements less than and greater than pivot .", + "The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j .", + "More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,12,5,10,14,3,10], pivot = 10\nOutput:[9,5,3,10,10,12,14]\nExplanation:The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,4,3,2], pivot = 2\nOutput:[-3,2,4,3]\nExplanation:The element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 37.13%) | Memory: 169.4 MB (Top 17.70%)\n// Time complexity = 2n = O(n)\n// Space complexity = O(1), or O(n) if the result array is including in the complexity analysis.\n\nclass Solution {\n public int[] pivotArray(int[] nums, int pivot) {\n int[] result = new int[nums.length];\n int left = 0, right = nums.length - 1;\n\n for(int i = 0; i < nums.length; i++) {\n if(nums[i] < pivot) {\n result[left++] = nums[i];\n }\n if(nums[nums.length - 1 - i] > pivot) {\n result[right--] = nums[nums.length - 1 - i];\n }\n }\n\n while(left <= right) {\n result[left++] = pivot;\n result[right--] = pivot;\n }\n\n return result;\n }\n}", + "title": "2161. Partition Array According to Given Pivot", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and an integer pivot . Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement.", + "description_images": [], + "constraints": [ + "Every element less than pivot appears before every element greater than pivot .", + "Every element equal to pivot appears in between the elements less than and greater than pivot .", + "The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j .", + "More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,12,5,10,14,3,10], pivot = 10\nOutput:[9,5,3,10,10,12,14]\nExplanation:The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,4,3,2], pivot = 2\nOutput:[-3,2,4,3]\nExplanation:The element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n left=[]\n mid=[]\n right=[]\n for i in nums:\n if(i memo = new HashMap();\n //memo.put(\"0,0\", arr[0]);\n\n for(int i=0; i< arr.length; ++i){\n //without current element\n curr1 = prev + arr[i];\n\n //with current element, find max if p=0...k (since subarray can be longeth of at most k)\n int tempk = 0, half1 = 0, half2 = 0, temp= 0;\n for(int p=0; p<=k; ++p){\n half1 = findMaxSumWithKEle(arr, p , i);\n tempk = i-p;\n half2 = memo.get((\"0,\"+tempk)) == null ? 0: memo.get((\"0,\"+tempk));\n if(temp < half1 + half2){\n temp = half1 + half2;\n }\n }\n\n curr2 = temp;\n\n //find max between curr1 or curr2 - with current elemtn in the subarray or outside the subarray\n max = (curr1 < curr2) ? curr2:curr1;\n\n //add in memo\n String key= \"0,\" + i;\n memo.put(key, max);\n System.out.println(\"Max: \" + max + \" from [\" + key + \"]\");\n prev = max;\n }\n\n return max;\n }\n\n public static Integer findMaxSumWithKEle(int[] arr, int k, int end) {\n int max= 0;\n if(end > arr.length || end<0){\n return 0;\n }\n int c = 0;\n for(int i=end; i> (end -k ) && i>=0; --i){\n ++c;\n if(max < arr[i]){\n max = arr[i];\n }\n }\n return max *c;\n }\n}", + "title": "1043. Partition Array for Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , partition the array into (contiguous) subarrays of length at most k . After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^9", + "1 <= k <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,15,7,9,2,5,10], k = 3\nOutput:84\nExplanation:arr becomes [15,15,15,9,10,10,10]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput:83", + "image": null + }, + { + "text": "Example 3: Input:arr = [1], k = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSumAfterPartitioning(self, nums: List[int], k: int) -> int:\n def get_max(start, end):\n return max(nums[start:end + 1]) * (end - start + 1)\n\n def dfs(start):\n if start == N: # base case, so in tabulation we go [N - 1]...[0], as [N] = 0\n return 0\n \n maxi = float(-inf)\n\t\t\t# you partition at every position up to start + k and repeat the same process for the next partition\n\t\t\t# e.g. 1 9 3, k = 2\n\t\t\t# 1|9|3 => with max in each partition: 1|9|3 = 13\n\t\t\t# 1|9 3 => with max in each partition: 1|9 9 = 19\n\t\t\t# 1 9|3 => with max in each partition: 9 9|3 = 21\n\t\t\t# get max_in_partition(start,end) + give_me_max_for_array(previous_partition_end + 1, N)\n\t\t\t# rec.relation = max(max_sum_in_partition[start, end] + dfs(end + 1)))\n for end in range(start, min(N, start + k)):\n maxi = max(maxi, get_max(start, end) + dfs(end + 1))\n return maxi\n \n N = len(nums)\n return dfs(0)\n", + "title": "1043. Partition Array for Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , partition it into two (contiguous) subarrays left and right so that: Return the length of left after such a partitioning . Test cases are generated such that partitioning exists.", + "description_images": [], + "constraints": [ + "Every element in left is less than or equal to every element in right .", + "left and right are non-empty.", + "left has the smallest possible size." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,0,3,8,6]\nOutput:3\nExplanation:left = [5,0,3], right = [8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,0,6,12]\nOutput:4\nExplanation:left = [1,1,1,0], right = [6,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int partitionDisjoint(int[] nums) {\n int mts = nums[0]; // max till scan\n int mtp = nums[0]; // max till partition\n int idx = 0;\n \n for(int i=1; i int:\n prefix = [nums[0] for _ in range(len(nums))]\n suffix = [nums[-1] for _ in range(len(nums))]\n for i in range(1, len(nums)):\n prefix[i] = max(prefix[i-1], nums[i-1])\n for i in range(len(nums)-2, -1, -1):\n suffix[i] = min(suffix[i+1], nums[i+1])\n for i in range(0, len(nums)-1):\n if prefix[i] <= suffix[i]:\n return i+1\n", + "title": "915. Partition Array into Disjoint Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 5 * 10^4", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput:true\nExplanation:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput:true\nExplanation:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n public boolean canThreePartsEqualSum(int[] arr) {\n int sum = 0;\n \n for (Integer no : arr) {\n sum += no;\n }\n if (sum % 3 != 0) {\n return false;\n }\n sum = sum / 3;\n int tempSum = 0;\n int count = 0;\n\n for (int i = 0; i < arr.length; i++) {\n tempSum += arr[i];\n if (tempSum == sum) {\n count++;\n tempSum = 0;\n }\n }\n\n return count >= 3;\n }\n}\n", + "title": "1013. Partition Array Into Three Parts With Equal Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 5 * 10^4", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput:true\nExplanation:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput:true\nExplanation:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 668 ms (Top 23.61%) | Memory: 21 MB (Top 37.82%)\nclass Solution:\n def canThreePartsEqualSum(self, arr: List[int]) -> bool:\n total = sum(arr)\n if total % 3 != 0:\n return False\n ave = total // 3\n stage = 0\n add = 0\n for i in arr[:-1]:\n add += i\n if add == ave:\n stage +=1\n add = 0\n if stage == 2:\n return True\n return False", + "title": "1013. Partition Array Into Three Parts With Equal Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums , put each element of nums into one of the two arrays. Return the minimum possible absolute difference .", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "nums.length == 2 * n", + "-10^7 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,9,7,3]\nOutput:2\nExplanation:One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/10/02/ex1.png" + }, + { + "text": "Example 2: Input:nums = [-36,36]\nOutput:72\nExplanation:One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,0,4,-2,-9]\nOutput:0\nExplanation:One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.", + "image": "https://assets.leetcode.com/uploads/2021/10/02/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 893 ms (Top 61.90%) | Memory: 51.3 MB (Top 87.91%)\nclass Solution {\n public int minimumDifference(int[] nums) {\n int n = nums.length;\n int sum = 0;\n for (int i : nums) {\n sum += i;\n }\n\n TreeSet[] sets = new TreeSet[n/2+1];\n for (int i = 0; i < (1 << (n / 2)); ++i) {\n int curSum = 0;\n int m = 0;\n for (int j = 0; j < n / 2; ++j) {\n if ((i & (1<();\n sets[m].add(curSum);\n }\n\n int res = Integer.MAX_VALUE / 3;\n for (int i = 0; i < (1 << (n / 2)); ++i) {\n int curSum = 0;\n int m = 0;\n for (int j = 0; j < n / 2; ++j) {\n if ((i & (1< int:\n n = len(nums)//2\n left, right = nums[:n], nums[n:]\n lsum, rsum = sum(left), sum(right)\n \n ans = inf\n for i in range(n+1): \n vals = sorted(2*sum(combo)-lsum for combo in combinations(left, i))\n for combo in combinations(right, n-i): \n diff = 2*sum(combo) - rsum\n k = bisect_left(vals, -diff)\n if k: ans = min(ans, abs(vals[k-1] + diff))\n if k < len(vals): ans = min(ans, abs(vals[k] + diff))\n return ans \n", + "title": "2035. Partition Array Into Two Arrays to Minimize Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,2,5], k = 2\nOutput:2\nExplanation:We can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 1\nOutput:2\nExplanation:We can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,4,5], k = 0\nOutput:3\nExplanation:We can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int c = 1, prev = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] - nums[prev] <= k) continue;\n c++; prev = i;\n }\n return c;\n }\n}\n", + "title": "2294. Partition Array Such That Maximum Difference Is K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer k . You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,2,5], k = 2\nOutput:2\nExplanation:We can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 1\nOutput:2\nExplanation:We can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,4,5], k = 0\nOutput:3\nExplanation:We can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = 1\n\t\t# To keep track of starting element of each subsequence\n start = nums[0]\n \n for i in range(1, len(nums)):\n diff = nums[i] - start\n if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n ans += 1\n start = nums[i]\n \n return ans", + "title": "2294. Partition Array Such That Maximum Difference Is K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty array nums containing only positive integers , find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,11,5]\nOutput:true\nExplanation:The array can be partitioned as [1, 5, 5] and [11].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5]\nOutput:false\nExplanation:The array cannot be partitioned into equal sum subsets.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPartition(int[] nums) {\n int sum = 0;\n for(int i=0; i= 1? true : false;\n }\n public int helper(int[] nums, int sum, int i, int[][] dp){\n if(i==nums.length && sum==0){\n return 1;\n }\n if(i==nums.length){\n return 0;\n }\n if(sum < 0){\n return 0;\n }\n if(dp[i][sum] != -1){\n return dp[i][sum];\n }\n if(sum bool:\n dp, s = set([0]), sum(nums)\n if s&1:\n return False\n for num in nums:\n for curr in range(s>>1, num-1, -1):\n if curr not in dp and curr-num in dp:\n if curr == s>>1:\n return True\n dp.add(curr)\n return False\n", + "title": "416. Partition Equal Subset Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababcbacadefegdehijhklij\"\nOutput:[9,7,8]\nExplanation:The partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.", + "image": null + }, + { + "text": "Example 2: Input:s = \"eccbbbbdec\"\nOutput:[10]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 5.9%) | Memory: 43.57 MB (Top 5.0%)\n\nclass Solution {\n public List partitionLabels(String s) {\n \n Listlr=new ArrayList<>();\n\n HashMapmp=new HashMap<>();\n\n int count=0;\n\n for(int i=0;i List[int]:\n d = defaultdict(list)\n for i, char in enumerate(s):\n d[char].append(i)\n nums = []\n \n for v in d.values():\n nums.append([v[0], v[-1]])\n\n start = nums[0][0]\n maxIndex = nums[0][1]\n ans = []\n for i in range(1, len(nums)):\n if nums[i][0] <= maxIndex:\n maxIndex = max(maxIndex, nums[i][1])\n else:\n ans.append(maxIndex - start + 1)\n start = nums[i][0]\n maxIndex = nums[i][1]\n ans.append(maxIndex - start + 1)\n # print(ans)\n return ans\n", + "title": "763. Partition Labels", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3\nOutput:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode left = new ListNode(0);\n ListNode right = new ListNode(0);\n \n ListNode leftTail = left;\n ListNode rightTail = right;\n \n while(head != null){\n if(head.val < x){\n leftTail.next = head;\n leftTail = leftTail.next;\n }\n else{\n rightTail.next = head;\n rightTail = rightTail.next;\n }\n head = head.next;\n }\n \n leftTail.next = right.next;\n rightTail.next = null;\n \n return left.next;\n }\n}\n", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3\nOutput:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 53 ms (Top 53.47%) | Memory: 13.8 MB (Top 76.51%)\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n lessthan = []\n greateql = []\n\n while head:\n if head.val < x:\n lessthan.append(head.val)\n else:\n greateql.append(head.val)\n head = head.next\n\n h = res = ListNode()\n\n for i in range(len(lessthan)):\n res.next = ListNode(lessthan[i])\n res = res.next\n for i in range(len(greateql)):\n res.next = ListNode(greateql[i])\n res = res.next\n\n return h.next", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "1 <= nums[i] <= 10^4", + "The frequency of each element is in the range [1, 4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,3,5,2,1], k = 4\nOutput:true\nExplanation:It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 277 ms (Top 51.4%) | Memory: 43.53 MB (Top 23.8%)\n\nclass Solution {\n private final List> allSubsets = new ArrayList<>();\n public boolean canPartitionKSubsets(int[] nums, int k) {\n int sum = Arrays.stream(nums).sum();\n if(sum % k != 0) return false;\n getAllSubsets(nums.length, sum / k, new HashSet<>(), nums, false);\n return allSubsets.size() >= k && canPartition(allSubsets.size(), k, nums.length, new HashSet<>());\n }\n\n private boolean canPartition(int n, int k, int size, Set current) {\n if(k == 0 && current.size() == size) return true;\n if(n == 0 || k < 0) return false;\n boolean addSet = false;\n if(allUnique(current, allSubsets.get(n-1))) {\n current.addAll(allSubsets.get(n - 1));\n addSet = canPartition(n - 1, k - 1, size, current);\n current.removeAll(allSubsets.get(n - 1));\n }\n return addSet || canPartition(n - 1, k, size, current);\n }\n\n private void getAllSubsets(int n, int targetSum, Set subsets, int[] nums, boolean lol) {\n if(targetSum == 0) {\n allSubsets.add(new HashSet<>(subsets));\n return;\n }\n if (n == 0 || targetSum < 0) return;\n subsets.add(n-1);\n getAllSubsets(n-1, targetSum - nums[n-1], subsets, nums, true);\n subsets.remove(n-1);\n getAllSubsets(n-1, targetSum, subsets, nums, false);\n }\n \n private boolean allUnique(Set set1, Set set2) {\n for (Integer num: set1) if(set2.contains(num)) return false;\n return true;\n }\n}", + "title": "698. Partition to K Equal Sum Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "1 <= nums[i] <= 10^4", + "The frequency of each element is in the range [1, 4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,3,5,2,1], k = 4\nOutput:true\nExplanation:It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 165 ms (Top 74.37%) | Memory: 13.8 MB (Top 95.72%)\nclass Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n def dfs(idx,curr,cnt,limit):\n if cnt == k:\n return True\n if curr ==limit:\n return dfs(0,0,cnt+1,limit)\n\n i = idx\n while i < len(nums):\n if visited[i] or nums[i]+curr > limit:\n i += 1\n continue\n visited[i] = True\n if dfs(i+1,curr+nums[i],cnt,limit):\n return True\n visited[i] = False\n\n while i+1 < len(nums) and nums[i] == nums[i+1]: #pruning1\n i += 1\n if curr == 0 or curr + nums[i] == limit: #pruning2\n return False\n i += 1\n return False\n\n if len(nums) < k or sum(nums) % k:\n return False\n numSum = sum(nums)\n\n for i in range(len(nums)):\n if nums[i] > numSum//k:\n return False\n\n visited = [False]*len(nums)\n return dfs(0,0,0,numSum//k)", + "title": "698. Partition to K Equal Sum Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary , while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n .", + "description_images": [], + "constraints": [ + "1 <= n.length <= 10^5", + "n consists of only digits.", + "n does not contain any leading zeros and represents a positive integer." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"32\"\nOutput:3\nExplanation:10 + 11 + 11 = 32", + "image": null + }, + { + "text": "Example 2: Input:n = \"82734\"\nOutput:8", + "image": null + }, + { + "text": "Example 3: Input:n = \"27346209830709182346\"\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPartitions(String n) {\n int res = 0;\n for (int i = 0; i < n.length(); i++) {\n res = Math.max(res, n.charAt(i) - '0');\n }\n return res;\n }\n}\n", + "title": "1689. Partitioning Into Minimum Number Of Deci-Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary , while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n .", + "description_images": [], + "constraints": [ + "1 <= n.length <= 10^5", + "n consists of only digits.", + "n does not contain any leading zeros and represents a positive integer." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"32\"\nOutput:3\nExplanation:10 + 11 + 11 = 32", + "image": null + }, + { + "text": "Example 2: Input:n = \"82734\"\nOutput:8", + "image": null + }, + { + "text": "Example 3: Input:n = \"27346209830709182346\"\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 109 ms (Top 63.86%) | Memory: 14.9 MB (Top 22.11%)\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return int(max(n))", + "title": "1689. Partitioning Into Minimum Number Of Deci-Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5\nOutput:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> generate(int numRows) {\n List> list = new LinkedList();\n list.add(Arrays.asList(1));\n if(numRows == 1) return list;\n list.add(Arrays.asList(1,1));\n \n for(int i = 1; i < numRows - 1; i++) {\n List temp = list.get(i);\n List temp2 = new ArrayList();\n temp2.add(1);\n for(int j = 0; j < temp.size() - 1; j++) {\n temp2.add(temp.get(j) + temp.get(j+1));\n }\n temp2.add(1);\n list.add(temp2);\n }\n \n return list;\n }\n}\n", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5\nOutput:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 1:\n return [[1]]\n if numRows == 2:\n return [[1], [1, 1]]\n ans = [[1], [1, 1]]\n for x in range(1, numRows - 1):\n tmp = [1]\n for k in range(len(ans[x]) - 1):\n tmp.append(ans[x][k] + ans[x][k + 1])\n tmp.append(1)\n ans.append(tmp)\n return ans\n", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3\nOutput:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1\nOutput:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List getRow(int rowIndex) {\n List> out = new ArrayList<>();\n for(int i = 0; i<=rowIndex; i++){\n Listin = new ArrayList<>(i+1);\n for(int j = 0 ; j<= i; j++){\n if(j == 0 || j == i){\n in.add(1);\n }\n else{\n in.add(out.get(i-1).get(j-1) + out.get(i-1).get(j));\n }\n \n }\n out.add(in);\n }\n return out.get(rowIndex);\n }\n}\n", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3\nOutput:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1\nOutput:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n # base case\n # we know that there exist two base case one which is for zero input\n # One when we have to exit our recursive loop \n if rowIndex == 0:\n return [1]\n if rowIndex == 1:\n return [1,1]\n #recurance relation or prev call\n prev_prob = self.getRow(rowIndex-1)\n # post processing on data \n # if someone has given us prev_Row what operation we can perform to get current_Row\n return [1]+[prev_prob[i]+prev_prob[i-1] for i in range(1,len(prev_prob))]+[1]\n", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6\nOutput:1\n\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20\nOutput:2\n\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPatches(int[] nums, int n) {\n long sum = 0;\n int count = 0;\n for (int x : nums) {\n if (sum >= n) break;\n while (sum+1 < x && sum < n) { \n ++count;\n sum += sum+1;\n }\n sum += x;\n }\n while (sum < n) {\n sum += sum+1;\n ++count;\n }\n return count;\n }\n}\n", + "title": "330. Patching Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6\nOutput:1\n\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20\nOutput:2\n\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n\t#pre-process for convenience\n nums.append(n+1)\n t=1\n sum=1\n rs=0\n if nums[0]!=1:\n nums=[1]+nums\n rs+=1\n# the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go form left to right to cover upto n\n while sum visited = new HashSet<>();\n int x = 0, y = 0;\n visited.add(x + \",\" + y);\n for (char c : path.toCharArray()) {\n if (c == 'N') y++;\n else if (c == 'S') y--;\n else if (c == 'E') x++;\n else x--;\n if (visited.contains(x + \",\" + y)) return true;\n visited.add(x + \",\" + y);\n }\n return false; \n }\n}\n", + "title": "1496. Path Crossing", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string path , where path[i] = 'N' , 'S' , 'E' or 'W' , each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path . Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited . Return false otherwise.", + "description_images": [], + "constraints": [ + "1 <= path.length <= 10^4", + "path[i] is either 'N' , 'S' , 'E' , or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:path = \"NES\"\nOutput:false\nExplanation:Notice that the path doesn't cross any point more than once.", + "image": "https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123929-pm.png" + }, + { + "text": "Example 2: Input:path = \"NESWW\"\nOutput:true\nExplanation:Notice that the path visits the origin twice.", + "image": "https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123843-pm.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 55 ms (Top 32.81%) | Memory: 14.1 MB (Top 28.49%)\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n c = set()\n x,y = 0,0\n c.add((x,y))\n for i in path:\n if i == 'N':\n y+=1\n elif i == 'E':\n x+=1\n elif i == 'W':\n x-=1\n else:\n y-=1\n if (x,y) in c:\n return True\n else:\n c.add((x,y))\n return False", + "title": "1496. Path Crossing", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/06/24/tree.png" + ], + "constraints": [ + "1 <= label <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:label = 14\nOutput:[1,3,4,14]", + "image": null + }, + { + "text": "Example 2: Input:label = 26\nOutput:[1,2,6,10,26]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n \n \n public List pathInZigZagTree(int label) \n {\n int level, upper, parent, i = label;\n double min, max;\n List ans = new ArrayList ();\n \n ans.add(i);\n \n while( i> 1)\n {\n level = (int)(Math.log(i) / Math.log(2));\n upper = level -1;\n min = Math.pow(2.0, upper);\n max = Math.pow(2.0, level) - 1;\n parent = (int)(min + max) - i/2; \n \n ans.add(0, parent);\n i = parent;\n }\n \n return ans;\n \n \n }\n}\n", + "title": "1104. Path In Zigzag Labelled Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/06/24/tree.png" + ], + "constraints": [ + "1 <= label <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:label = 14\nOutput:[1,3,4,14]", + "image": null + }, + { + "text": "Example 2: Input:label = 26\nOutput:[1,2,6,10,26]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 88.8%) | Memory: 16.50 MB (Top 52.0%)\n\nclass Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n \n x = label\n mask = 0 \n while x > 1:\n x >>= 1\n mask <<= 1\n mask |= 1\n \n x = label\n res = deque()\n while x:\n res.appendleft(x)\n x >>= 1\n mask >>= 1\n x ^= mask\n return res\n", + "title": "1104. Path In Zigzag Labelled Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput:true\nExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5\nOutput:false\nExplanation:There two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0\nOutput:false\nExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if(root == null) return false;\n \n if(root.left == null && root.right == null) return root.val == targetSum;\n \n return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val);\n }\n}\n", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput:true\nExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5\nOutput:false\nExplanation:There two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0\nOutput:false\nExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def hasPathSum(self, root, targetSum):\n \"\"\"\n :type root: TreeNode\n :type targetSum: int\n :rtype: bool\n \"\"\"\n if not root: return False\n targetSum -= root.val\n if not root.left and not root.right:\n return not targetSum\n return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)\n", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return all root-to-leaf paths where the sum of the node values in the path equals targetSum . Each path should be returned as a list of the node values , not node references . A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput:[[5,4,11,2],[5,8,4,5]]\nExplanation:There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2], targetSum = 0\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n public List> pathSum(TreeNode root, int targetSum) \n {\n List> ans = new ArrayList<>();\n pathSum(root, targetSum, new ArrayList<>(), ans);\n return ans;\n }\n \n public void pathSum(TreeNode root, int targetSum, List path, List> ans)\n {\n if(root == null)\n return;\n path.add(root.val);\n if(root.left == null && root.right == null && targetSum == root.val)//leaf node that completes path\n {\n ans.add(new ArrayList(path));// we use new ArrayList because if we don't the originaly List is added which is mutable, if we add a copy that's not mutable.\n }\n else\n {\n pathSum(root.left, targetSum-root.val, path, ans);\n pathSum(root.right, targetSum-root.val, path, ans);\n }\n path.remove(path.size()-1); //removal of redundant nodes\n }\n}\n", + "title": "113. Path Sum II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return all root-to-leaf paths where the sum of the node values in the path equals targetSum . Each path should be returned as a list of the node values , not node references . A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput:[[5,4,11,2],[5,8,4,5]]\nExplanation:There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2], targetSum = 0\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\n res = []\n def dfs(v, path, pathsum):\n if not v:\n return\n path.append(v.val)\n pathsum += v.val\n if not v.left and not v.right and pathsum == targetSum:\n res.append(path[:])\n dfs(v.left, path, pathsum)\n dfs(v.right, path, pathsum)\n path.pop()\n dfs(root, [], 0)\n return res", + "title": "113. Path Sum II", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput:3\nExplanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 66.25%) | Memory: 45 MB (Top 29.77%)\nclass Solution {\n public int pathSum(TreeNode root, int targetSum) {\n HashMap hm = new HashMap<>();\n //hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum\n\n int res = solve(hm, root, targetSum, 0);\n\n return res;\n }\n\n public int solve(HashMap hm, TreeNode node, long tgt, long c_sum) {\n\n if(node == null)\n return 0;\n\n c_sum += node.val;\n\n int res = 0;\n\n if(c_sum == tgt) //--> either this condition or the above commented condition.\n res++;\n\n if(hm.containsKey(c_sum-tgt)){\n res += hm.get(c_sum-tgt);\n }\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)+1);\n\n int left = solve(hm, node.left, tgt, c_sum);\n int right = solve(hm, node.right, tgt, c_sum);\n\n res += (left+right);\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)-1); //remove the calculated cumulative sum\n\n return res;\n\n }\n\n}\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput:3\nExplanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:\n def util(node: TreeNode, sum_array) -> int:\n t = [e - node.val for e in sum_array]\n zeroes = t.count(0)\n if node.left is None and node.right is None:\n return zeroes\n ansl, ansr = 0, 0\n if node.left:\n ansl = util(node.left, t + [targetSum])\n if node.right:\n ansr = util(node.right, t + [targetSum])\n return ansl + ansr + zeroes\n\n return util(root, [targetSum]) if root is not None else 0\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a gold mine grid of size m x n , each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions:", + "description_images": [], + "constraints": [ + "Every time you are located in a cell you will collect all the gold in that cell.", + "From your position, you can walk one step to the left, right, up, or down.", + "You can't visit the same cell more than once.", + "Never visit a cell with 0 gold.", + "You can start and stop collecting gold from any position in the grid that has some gold." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput:24\nExplanation:[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput:28\nExplanation:[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 55 ms (Top 88.6%) | Memory: 39.51 MB (Top 97.9%)\n\nclass Solution {\n int r = 0;\n int c = 0;\n int max = 0;\n public int getMaximumGold(int[][] grid) {\n r = grid.length;\n c = grid[0].length;\n for(int i = 0; i < r; i++) {\n for(int j = 0; j < c; j++) {\n if(grid[i][j] != 0) {\n dfs(grid, i, j, 0);\n }\n }\n }\n return max;\n }\n \n private void dfs(int[][] grid, int i, int j, int cur) {\n if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] == 0) {\n max = Math.max(max, cur);\n return;\n }\n int val = grid[i][j];\n grid[i][j] = 0;\n dfs(grid, i + 1, j, cur + val);\n dfs(grid, i - 1, j, cur + val);\n dfs(grid, i, j + 1, cur + val);\n dfs(grid, i, j - 1, cur + val);\n grid[i][j] = val;\n }\n}", + "title": "1219. Path with Maximum Gold", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a gold mine grid of size m x n , each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions:", + "description_images": [], + "constraints": [ + "Every time you are located in a cell you will collect all the gold in that cell.", + "From your position, you can walk one step to the left, right, up, or down.", + "You can't visit the same cell more than once.", + "Never visit a cell with 0 gold.", + "You can start and stop collecting gold from any position in the grid that has some gold." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput:24\nExplanation:[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput:28\nExplanation:[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1480 ms (Top 97.21%) | Memory: 14.1 MB (Top 13.08%)\nclass Solution:\n def getMaximumGold(self, grid):\n answer = [0]\n\n def visit(visited, i, j, gold_sum):\n val = grid[i][j]\n if val == 0 or (i,j) in visited:\n answer[0] = max(answer[0], gold_sum)\n return\n\n gold_sum_new = gold_sum + val\n visited_new = visited.union({(i,j)})\n\n if i > 0:\n visit(visited_new, i-1, j, gold_sum_new)\n\n if j < len(grid[i]) - 1:\n visit(visited_new, i, j+1, gold_sum_new)\n\n if i < len(grid) - 1:\n visit(visited_new, i+1, j, gold_sum_new)\n if j > 0:\n visit(visited_new, i, j-1, gold_sum_new)\n #choosing the starting points\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] != 0:\n count = 0\n\n try:\n if grid[i-1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j+1] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i+1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j-1] != 0:\n count += 1\n except:\n pass\n\n if count < 3:\n visit(set(),i,j,0)\n\n return answer[0]\n", + "title": "1219. Path with Maximum Gold", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i] . Given two nodes start and end , find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end , return 0 . Your answer will be accepted if it differs from the correct answer by at most 1e-5 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png" + ], + "constraints": [ + "2 <= n <= 10^4", + "0 <= start, end < n", + "start != end", + "0 <= a, b < n", + "a != b", + "0 <= succProb.length == edges.length <= 2*10^4", + "0 <= succProb[i] <= 1", + "There is at most one edge between every two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput:0.25000\nExplanation:There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput:0.30000", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput:0.00000\nExplanation:There is no path between 0 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 82 ms (Top 52.25%) | Memory: 75.8 MB (Top 66.61%)\nclass Pair{\n int to;\n double prob;\n public Pair(int to,double prob){\n this.to=to;\n this.prob=prob;\n }\n}\nclass Solution {\n public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {\n List> adj=new ArrayList<>();\n for(int i=0;i());\n }\n for(int i=0;i pq=new PriorityQueue<>((p1,p2)->Double.compare(p2.prob,p1.prob));\n pq.offer(new Pair(start,1.0));\n while(!pq.isEmpty()){\n Pair curr=pq.poll();\n for(Pair x:adj.get(curr.to)){\n if(((curr.prob)*(x.prob))>probs[x.to]){\n probs[x.to]=((curr.prob)*(x.prob));\n pq.offer(new Pair(x.to,probs[x.to]));\n\n }\n else{\n continue;\n }\n }\n }\n return probs[end];\n }\n}", + "title": "1514. Path with Maximum Probability", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i] . Given two nodes start and end , find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end , return 0 . Your answer will be accepted if it differs from the correct answer by at most 1e-5 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png" + ], + "constraints": [ + "2 <= n <= 10^4", + "0 <= start, end < n", + "start != end", + "0 <= a, b < n", + "a != b", + "0 <= succProb.length == edges.length <= 2*10^4", + "0 <= succProb[i] <= 1", + "There is at most one edge between every two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput:0.25000\nExplanation:There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput:0.30000", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput:0.00000\nExplanation:There is no path between 0 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 755 ms (Top 91.19%) | Memory: 25.4 MB (Top 98.78%)\nclass Solution(object):\n def maxProbability(self, n, edges, succProb, start, end):\n adj=[[] for i in range(n)]\n dist=[sys.maxsize for i in range(n)]\n heap=[]\n c=0\n for i,j in edges:\n adj[i].append([j,succProb[c]])\n adj[j].append([i,succProb[c]])\n c+=1\n heapq.heappush(heap,[-1.0,start])\n dist[start]=1\n while(heap):\n prob,u=heapq.heappop(heap)\n for v,w in adj[u]:\n if(dist[v]>-abs(w*prob)):\n dist[v]=-abs(w*prob)\n heapq.heappush(heap,[dist[v],v])\n if(sys.maxsize==dist[end]):\n return 0.00000\n else:\n return -dist[end]", + "title": "1514. Path with Maximum Probability", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a hiker preparing for an upcoming hike. You are given heights , a 2D array of size rows x columns , where heights[row][col] represents the height of cell (row, col) . You are situated in the top-left cell, (0, 0) , and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed ). You can move up , down , left , or right , and you wish to find a route that requires the minimum effort . A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/04/ex2.png" + ], + "constraints": [ + "rows == heights.length", + "columns == heights[i].length", + "1 <= rows, columns <= 100", + "1 <= heights[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput:2\nExplanation:The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.", + "image": null + }, + { + "text": "Example 2: Input:heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput:1\nExplanation:The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].", + "image": null + }, + { + "text": "Example 3: Input:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput:0\nExplanation:This route does not require any effort.", + "image": "https://assets.leetcode.com/uploads/2020/10/04/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 97.2%) | Memory: 44.02 MB (Top 69.2%)\n\nclass Tuple {\n\n int distance;\n\n int row;\n\n int col;\n\n \n\n Tuple(int distance, int row, int col) {\n\n this.distance = distance;\n\n this.row = row;\n\n this.col = col;\n\n }\n\n}\n\n\n\nclass Solution {\n\n public int minimumEffortPath(int[][] heights) {\n\n // Create a min heap based on the distance\n\n PriorityQueue minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);\n\n \n\n int rows = heights.length;\n\n int cols = heights[0].length;\n\n \n\n // Create a 2D array to store the minimum effort to reach each cell\n\n int effort[][] = new int[rows][cols];\n\n \n\n // Initialize all efforts to maximum initially\n\n for (int i = 0; i < rows; i++) {\n\n Arrays.fill(effort[i], Integer.MAX_VALUE);\n\n }\n\n \n\n effort[0][0] = 0; // Initial effort at the starting cell\n\n \n\n // Add the starting cell to the min heap\n\n minHeap.add(new Tuple(0, 0, 0));\n\n \n\n // Arrays to represent row and column changes for 4 directions\n\n int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left\n\n int dc[] = {0, 1, 0, -1};\n\n \n\n while (!minHeap.isEmpty()) {\n\n Tuple current = minHeap.poll(); // Get the cell with the minimum effort\n\n int distance = current.distance;\n\n int row = current.row;\n\n int col = current.col;\n\n \n\n if (row == rows - 1 && col == cols - 1) {\n\n return distance; // If reached the destination, return the effort\n\n }\n\n \n\n // Explore each of the 4 possible directions\n\n for (int i = 0; i < 4; i++) {\n\n int newRow = row + dr[i]; // Calculate new row index\n\n int newCol = col + dc[i]; // Calculate new column index\n\n \n\n // Check if the new cell is within bounds\n\n if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\n\n \n\n // Calculate the new effort based on the maximum of height difference and current effort\n\n int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);\n\n \n\n // If the new effort is less than the stored effort for the cell, update and add to heap\n\n if (newEffort < effort[newRow][newCol]) {\n\n effort[newRow][newCol] = newEffort;\n\n minHeap.add(new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration\n\n }\n\n }\n\n }\n\n }\n\n return 0; // This value should be replaced with the actual minimum effort\n\n }\n\n}\n\n", + "title": "1631. Path With Minimum Effort", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are a hiker preparing for an upcoming hike. You are given heights , a 2D array of size rows x columns , where heights[row][col] represents the height of cell (row, col) . You are situated in the top-left cell, (0, 0) , and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed ). You can move up , down , left , or right , and you wish to find a route that requires the minimum effort . A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/04/ex2.png" + ], + "constraints": [ + "rows == heights.length", + "columns == heights[i].length", + "1 <= rows, columns <= 100", + "1 <= heights[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput:2\nExplanation:The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.", + "image": null + }, + { + "text": "Example 2: Input:heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput:1\nExplanation:The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].", + "image": null + }, + { + "text": "Example 3: Input:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput:0\nExplanation:This route does not require any effort.", + "image": "https://assets.leetcode.com/uploads/2020/10/04/ex3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1804 ms (Top 36.30%) | Memory: 15.4 MB (Top 76.73%)\nclass Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n di = (0, 1, 0, -1)\n dj = (1, 0, -1, 0)\n m, n = len(heights), len(heights[0])\n visited = [[False] * n for _ in range(m)]\n h = [(0, 0, 0)]\n while h:\n effort, i, j = heappop(h)\n if visited[i][j]:\n continue\n visited[i][j] = True\n if i + 1 == m and j + 1 == n:\n return effort ## have reached the (m-1, n-1) cell\n for k in range(4):\n ii, jj = i + di[k], j + dj[k]\n if 0 <= ii < m and 0 <= jj < n and not visited[ii][jj]:\n neffort = max(effort, abs(heights[i][j] - heights[ii][jj]))\n heappush(h, (neffort, ii, jj))\n return ## cell (m-1, n-1) not reachable, should never happen", + "title": "1631. Path With Minimum Effort", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An array arr a mountain if the following properties hold: Given a mountain array arr , return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] . You must solve it in O(log(arr.length)) time complexity.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,0]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,0]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,10,5,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 59.7 MB (Top 83.58%)\nclass Solution {\npublic int peakIndexInMountainArray(int[] arr) {\n\n int start = 0;\n int end = arr.length - 1;\n\n while( start < end){\n int mid = start + (end - start)/2;\n // if mid < mid next\n if(arr[mid] < arr[mid + 1]){\n start = mid + 1;\n }\n // otherwise it can either peak element or greater element\n else{\n end = mid;\n }\n }\n return start; // or we can return end also, bcz both will be on same value at the time, that's why loop breaks here.\n }\n}", + "title": "852. Peak Index in a Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array arr a mountain if the following properties hold: Given a mountain array arr , return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] . You must solve it in O(log(arr.length)) time complexity.", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,0]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,0]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,10,5,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n beg = 0\n end = len(arr)-1\n \n while beg <= end:\n mid = (beg+end)//2\n if arr[mid] < arr[mid+1]:\n beg = mid +1\n elif arr[mid] > arr[mid+1]:\n end = mid -1\n return beg\n", + "title": "852. Peak Index in a Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: Note: Each language may have a different implementation of the constructor and Iterator , but they all support the int next() and boolean hasNext() functions.", + "description_images": [], + "constraints": [ + "PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator .", + "int next() Returns the next element in the array and moves the pointer to the next element.", + "boolean hasNext() Returns true if there are still elements in the array.", + "int peek() Returns the next element in the array without moving the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 2, 2, 3, false]ExplanationPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Java Iterator interface reference:\n// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator {\n Queue q;\n\tpublic PeekingIterator(Iterator iterator) {\n\t // initialize any member here.\n\t q= new LinkedList<>();\n while(iterator.hasNext())\n q.add(iterator.next()); \n\t}\n\t\n // Returns the next element in the iteration without advancing the iterator.\n\tpublic Integer peek() {\n return q.peek();\n\t}\n\t\n\t// hasNext() and next() should behave the same as in the Iterator interface.\n\t// Override them if needed.\n\t@Override\n\tpublic Integer next() {\n\t return q.remove();\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t return q.size()!=0;\n\t}\n}\n", + "title": "284. Peeking Iterator", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: Note: Each language may have a different implementation of the constructor and Iterator , but they all support the int next() and boolean hasNext() functions.", + "description_images": [], + "constraints": [ + "PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator .", + "int next() Returns the next element in the array and moves the pointer to the next element.", + "boolean hasNext() Returns true if there are still elements in the array.", + "int peek() Returns the next element in the array without moving the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 2, 2, 3, false]ExplanationPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 25.31%) | Memory: 17.60 MB (Top 8.9%)\n\nclass PeekingIterator:\n def __init__(self, iterator):\n self.iterator = iterator\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n \n def peek(self):\n return self.buffer\n \n def next(self):\n tmp = self.buffer\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n return tmp\n \n def hasNext(self):\n return self.buffer != None\n", + "title": "284. Peeking Iterator", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person ( indexed from 0 ). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies . You must return the indices in increasing order.", + "description_images": [], + "constraints": [ + "1 <= favoriteCompanies.length <= 100", + "1 <= favoriteCompanies[i].length <= 500", + "1 <= favoriteCompanies[i][j].length <= 20", + "All strings in favoriteCompanies[i] are distinct .", + "All lists of favorite companies are distinct , that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].", + "All strings consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput:[0,1,4]\nExplanation:Person with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].", + "image": null + }, + { + "text": "Example 2: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput:[0,1]\nExplanation:In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].", + "image": null + }, + { + "text": "Example 3: Input:favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput:[0,1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 362 ms (Top 62.96%) | Memory: 52.4 MB (Top 92.59%)\nclass Solution {\n public List peopleIndexes(List> favoriteCompanies) {\n Set[] fav = new Set[favoriteCompanies.size()];\n Set set = new HashSet<>();\n for (int i = 0; i < favoriteCompanies.size(); i++) {\n set.add(i);\n fav[i] = new HashSet<>(favoriteCompanies.get(i));\n }\n for (int i = 1; i < favoriteCompanies.size(); i++) {\n if (!set.contains(i)) continue;\n for (int j = 0; j < i; j++) {\n if (!set.contains(j)) continue;\n if (isSubSet(fav[j], fav[i])) set.remove(j);\n if (isSubSet(fav[i], fav[j])) set.remove(i);\n }\n }\n List ans = new ArrayList<>(set);\n Collections.sort(ans);\n return ans;\n }\n\n private boolean isSubSet(Set child, Set parent) {\n if (child.size() > parent.size()) return false;\n return parent.containsAll(child);\n }\n}", + "title": "1452. People Whose List of Favorite Companies Is Not a Subset of Another List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person ( indexed from 0 ). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies . You must return the indices in increasing order.", + "description_images": [], + "constraints": [ + "1 <= favoriteCompanies.length <= 100", + "1 <= favoriteCompanies[i].length <= 500", + "1 <= favoriteCompanies[i][j].length <= 20", + "All strings in favoriteCompanies[i] are distinct .", + "All lists of favorite companies are distinct , that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].", + "All strings consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput:[0,1,4]\nExplanation:Person with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].", + "image": null + }, + { + "text": "Example 2: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput:[0,1]\nExplanation:In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].", + "image": null + }, + { + "text": "Example 3: Input:favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput:[0,1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n \n F = favoriteCompanies\n ans = [] \n \n seen = set() \n \n for i in range(len(F)):\n for j in range(i+1,len(F)):\n st1 = set(F[i])\n st2 = set(F[j])\n if st1.intersection(st2) == st1: seen.add(i)\n if st2.intersection(st1) == st2: seen.add(j) \n\n ans = []\n for i in range(len(F)):\n if i in seen: continue \n ans.append(i) \n \n return ans", + "title": "1452. People Whose List of Favorite Companies Is Not a Subset of Another List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s and a character letter , return the percentage of characters in s that equal letter rounded down to the nearest whole percent.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of lowercase English letters.", + "letter is a lowercase English letter." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"foobar\", letter = \"o\"\nOutput:33\nExplanation:The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.", + "image": null + }, + { + "text": "Example 2: Input:s = \"jjjj\", letter = \"k\"\nOutput:0\nExplanation:The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.55 MB (Top 34.5%)\n\nclass Solution {\n public int percentageLetter(String str, char letter) {\n int count=0;\n int n=str.length();\n for(int i=0;i int:\n return (s.count(letter)*100)//len(s)\n", + "title": "2278. Percentage of Letter in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A perfect number is a positive integer that is equal to the sum of its positive divisors , excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n , return true if n is a perfect number, otherwise return false .", + "description_images": [], + "constraints": [ + "1 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 28\nOutput:true\nExplanation:28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.", + "image": null + }, + { + "text": "Example 2: Input:num = 7\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 51.95%) | Memory: 40.9 MB (Top 44.38%)\nclass Solution {\n public boolean checkPerfectNumber(int num) {\n if(num==1)\n return false;\n\n int sum = 1;\n for(int i=2; i bool:\n sum = 0\n root = num**0.5 \n if num ==1:\n return False\n for i in range(2,int(root)+1):\n if num%i== 0:\n sum +=(num//i)+i\n return sum+1 == num\n", + "title": "507. Perfect Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array rectangles where rectangles[i] = [x i , y i , a i , b i ] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (x i , y i ) and the top-right point of it is (a i , b i ) . Return true if all the rectangles together form an exact cover of a rectangular region .", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 2 * 10^4", + "rectangles[i].length == 4", + "-10^5 <= x i , y i , a i , b i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\nOutput:true\nExplanation:All 5 rectangles together form an exact cover of a rectangular region.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg" + }, + { + "text": "Example 2: Input:rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\nOutput:false\nExplanation:Because there is a gap between the two rectangular regions.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg" + }, + { + "text": "Example 3: Input:rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\nOutput:false\nExplanation:Because two of the rectangles overlap with each other.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 81.33%) | Memory: 57.5 MB (Top 77.78%)\nclass Solution {\n // Rectangle x0,y0,x1,y1\n public boolean isRectangleCover(int[][] rectangles) {\n // Ordered by y0 first and x0 second\n Arrays.sort(rectangles,(r1,r2)->{\n if(r1[1]==r2[1]) return r1[0]-r2[0];\n return r1[1]-r2[1];\n });\n\n // Layering rectangles with pq, ordered by y1 first and x0 second\n PriorityQueue pq = new PriorityQueue<>((r1,r2)->{\n if(r1[3]==r2[3]) return r1[0]-r2[0];\n return r1[3]-r2[3];\n });\n\n // Create first layer\n pq.offer(rectangles[0]);\n int i=1;\n while(icurr[2]){\n pq.offer(new int[]{curr[2], prev[1], prev[2], prev[3]});\n x=curr[2];\n }else {\n x=prev[2];\n }\n }\n if(x bool:\n X1, Y1 = float('inf'), float('inf')\n X2, Y2 = -float('inf'), -float('inf')\n\n points = set()\n actual_area = 0\n for x1, y1, x2, y2 in rectangles:\n # calculate the coords of the potential perfect rectangle\n X1, Y1 = min(X1, x1), min(Y1, y1)\n X2, Y2 = max(X2, x2), max(Y2, y2)\n # add up to the actual_area, so we can check against to see if thers is any part overwritten.\n actual_area += (x2 - x1) * (y2 - y1)\n \n # proving steps in https://labuladong.github.io/algo/4/32/131/\n for p in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]:\n if p in points: \n points.remove(p)\n else: \n points.add(p)\n\n # check the area \n expected_area = (X2 - X1) * (Y2 - Y1)\n if actual_area != expected_area:\n return False\n \n if len(points) != 4: \n return False\n\n if (X1, Y1) not in points: \n return False\n if (X1, Y2) not in points: \n return False\n if (X2, Y1) not in points: \n return False\n if (X2, Y2) not in points: \n return False\n\n return True", + "title": "391. Perfect Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the least number of perfect square numbers that sum to n . A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1 , 4 , 9 , and 16 are perfect squares while 3 and 11 are not.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:3\nExplanation:12 = 4 + 4 + 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 13\nOutput:2\nExplanation:13 = 4 + 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 91.34%) | Memory: 42.30 MB (Top 82.04%)\n\nclass Solution {\n public int numSquares(int n) {\n int dp[]=new int [n+1];\n dp[0]=0;\n dp[1]=1;\n \n for(int i=2;i bool:\n sq = int(math.sqrt(n))\n return sq*sq == n\n \n def numSquares(self, n: int) -> int:\n # Lagrange's four-square theorem\n if self.isSquare(n):\n return 1\n while (n & 3) == 0:\n n >>= 2\n if (n & 7) == 7:\n return 4\n sq = int(math.sqrt(n)) + 1\n for i in range(1,sq):\n if self.isSquare(n - i*i):\n return 2\n return 3\n", + "title": "279. Perfect Squares", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"\nOutput:true\nExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkInclusion(String s1, String s2) {\n if(s1.length() > s2.length()) {\n return false;\n }\n \n int[]s1Count = new int[26];\n int[]s2Count = new int[26];\n \n for(int i = 0; i < s1.length(); i++) {\n char c = s1.charAt(i);\n char s = s2.charAt(i);\n s1Count[c - 'a'] += 1;\n s2Count[s - 'a'] += 1;\n }\n \n int matches = 0;\n \n for(int i = 0; i < 26;i++) {\n if(s1Count[i] == s2Count[i]) {\n matches+=1;\n }\n }\n \n int left = 0;\n for(int right = s1.length(); right < s2.length();right++) {\n if(matches == 26) {\n return true;\n }\n \n int index = s2.charAt(right) - 'a';\n s2Count[index] += 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] + 1 == s2Count[index]) {\n matches -= 1;\n }\n \n index = s2.charAt(left) - 'a';\n s2Count[index] -= 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] - 1 == s2Count[index]) {\n matches -= 1;\n }\n left += 1;\n }\n \n if(matches == 26) {\n return true;\n }\n \n return false;\n }\n}\n", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"\nOutput:true\nExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n s1_map = {}\n s2_map = {}\n for i in range(ord('a') , ord('z') + 1):\n s1_map[chr(i)] = 0\n s2_map[chr(i)] = 0\n \n for i in s1:\n s1_map[i] += 1\n \n l = 0\n r = 0\n \n while r < len(s2):\n print(s2_map , l ,r)\n if r == 0:\n while r < len(s1):\n s2_map[s2[r]] += 1\n r += 1\n if s2_map == s1_map:\n return True\n\n else:\n s2_map[s2[l]] -= 1\n s2_map[s2[r]] += 1\n \n if s2_map == s1_map:\n return True\n else:\n l += 1\n r += 1\n \n return False \n", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3 : Given n and k , return the k th permutation sequence.", + "description_images": [], + "constraints": [ + "1 <= n <= 9", + "1 <= k <= n!" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 3\nOutput:\"213\"", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 9\nOutput:\"2314\"", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 1\nOutput:\"123\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String getPermutation(int n, int k) {\n int fact = 1;\n List nums = new ArrayList<>();\n for(int i = 1; i str:\n nums = [i for i in range(1, n+1)] # list of numbers from 1 to n\n factorial = [1] * n\n for i in range(1, n):\n factorial[i] = factorial[i-1] * i\n \n k -= 1\n result = []\n for i in range(n-1, -1, -1):\n index = k // factorial[i]\n result.append(str(nums[index]))\n nums.pop(index)\n k = k % factorial[i]\n \n return ''.join(result)\n", + "title": "60. Permutation Sequence", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 76.85%) | Memory: 44.7 MB (Top 48.41%)\nclass Solution {\n List> res = new LinkedList<>();\n\n public List> permute(int[] nums) {\n ArrayList list = new ArrayList<>();\n boolean[] visited = new boolean[nums.length];\n\n backTrack(nums, list, visited);\n return res;\n }\n\n private void backTrack(int[] nums, ArrayList list, boolean[] visited){\n if(list.size() == nums.length){\n res.add(new ArrayList(list));\n return;\n }\n for(int i = 0; i < nums.length; i++){\n if(!visited[i]){\n visited[i] = true;\n list.add(nums[i]);\n backTrack(nums, list, visited);\n visited[i] = false;\n list.remove(list.size() - 1);\n }\n }\n }\n}", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n return list(permutations(nums))\n", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a collection of numbers, nums , that might contain duplicates, return all possible unique permutations in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 8", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]\nOutput:[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]\nOutput:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> permuteUnique(int[] nums) {\n List> ans = new ArrayList<>();\n Arrays.sort(nums);\n boolean used[] = new boolean[nums.length];\n \n permutationsFinder(nums,ans,new ArrayList<>(),used);\n \n return ans;\n }\n \n static void permutationsFinder(int[] nums,List> ans,List list,boolean used[]){\n if(list.size() == nums.length){\n ans.add(new ArrayList<>(list));\n return;\n }\n \n for(int i=0;i0 && nums[i]==nums[i-1] && !used[i-1]) continue;\n list.add(nums[i]);\n used[i] = true;\n permutationsFinder(nums,ans,list,used);\n list.remove(list.size()-1);\n used[i] = false;\n }\n }\n}\n", + "title": "47. Permutations II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a collection of numbers, nums , that might contain duplicates, return all possible unique permutations in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 8", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]\nOutput:[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]\nOutput:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 136 ms (Top 31.20%) | Memory: 14.2 MB (Top 62.53%)\nclass Solution(object):\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if len(nums) == 1:\n return [[nums[0]]]\n\n res = self.permuteUnique(nums[1:])\n\n for i in range(len(res)-1, -1 , -1):\n j = 0\n while j < len(res[i]):\n if res[i][j] == nums[0]: #to account for repeated nums\n break\n lst = res[i][:]\n lst.insert(j, nums[0])\n res.append(lst)\n j += 1\n\n res[i].insert(j,nums[0])\n\n return res", + "title": "47. Permutations II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick .", + "description_images": [], + "constraints": [ + "You will pick any pizza slice.", + "Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.", + "Your friend Bob will pick the next slice in the clockwise direction of your pick.", + "Repeat until there are no more slices of pizzas." + ], + "examples": [ + { + "text": "Example 1: Input:slices = [1,2,3,4,5,6]\nOutput:10\nExplanation:Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_3_1723.png" + }, + { + "text": "Example 2: Input:slices = [8,9,8,6,1,1]\nOutput:16\nExplanation:Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_4_1723.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSizeSlices(int[] slices) {\n int n = slices.length;\n return Math.max(helper(slices, n/3, 0, n - 2), helper(slices, n/3, 1, n - 1));\n }\n \n private int helper(int[] slices, int rounds, int start, int end) {\n int n = end - start + 1, max = 0;\n int[][][] dp = new int[n][rounds+1][2];\n dp[0][1][1] = slices[start];\n for (int i = start + 1; i <= end; i++) {\n int x = i - start;\n for (int j = 1; j <= rounds; j++) {\n dp[x][j][0] = Math.max(dp[x-1][j][0], dp[x-1][j][1]);\n dp[x][j][1] = dp[x-1][j-1][0] + slices[i];\n if (j == rounds) {\n max = Math.max(max, Math.max(dp[x][j][0], dp[x][j][1]));\n }\n }\n }\n return max;\n }\n}\n", + "title": "1388. Pizza With 3n Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick .", + "description_images": [], + "constraints": [ + "You will pick any pizza slice.", + "Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.", + "Your friend Bob will pick the next slice in the clockwise direction of your pick.", + "Repeat until there are no more slices of pizzas." + ], + "examples": [ + { + "text": "Example 1: Input:slices = [1,2,3,4,5,6]\nOutput:10\nExplanation:Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_3_1723.png" + }, + { + "text": "Example 2: Input:slices = [8,9,8,6,1,1]\nOutput:16\nExplanation:Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_4_1723.png" + } + ], + "follow_up": null, + "solution": " class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ** #This solve function mainly on work on the idea of A Previous dp problem House Robber II \n\t\t#If we take the first slice then we cant take the second slice and vice versa**\n\t\tdef solve(slices,start,end,n,dp):\n if start>end or n==0:\n return 0\n if dp[start][n] !=-1:\n return dp[start][n]\n include = slices[start] + solve(slices,start+2,end,n-1,dp)\n \n exclude = 0 + solve(slices,start+1,end,n,dp)\n \n dp[start][n]= max(include,exclude)\n return dp[start][n]\n dp1=[[-1 for i in range(k+1)]for _ in range(k+1)]\n dp2=[[-1 for i in range(k+1)]for _ in range(k+1)]\n \n option1=solve(slices,0,k-2,k//3,dp1)#Taking the the first slice , now we cant take the last slice and next slice\n option2=solve(slices,1,k-1,k//3,dp2)#Taking the the second slice , now we cant take the second last slice and next slice\n \n return max(option1,option2)\n", + "title": "1388. Pizza With 3n Slices", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle . You are also given a 0-indexed 2D integer array queries where queries[i] = [left i , right i ] denotes the substring s[left i ...right i ] ( inclusive ). For each query, you need to find the number of plates between candles that are in the substring . A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring . Return an integer array answer where answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "For example, s = \"||**||**|*\" , and a query [3, 8] denotes the substring \"*|| ** |\" . The number of plates between candles in this substring is 2 , as each of the two plates has at least one candle in the substring to its left and right." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"**|**|***|\", queries = [[2,5],[5,9]]\nOutput:[2,3]\nExplanation:- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-1.png" + }, + { + "text": "Example 2: Input:s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\nOutput:[9,0,0,0,0]\nExplanation:- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 58.35%) | Memory: 143.3 MB (Top 38.21%)\nclass Solution {\n // O(sLen + queries.length) time, O(sLen) space\n public int[] platesBetweenCandles(String s, int[][] queries) {\n int sLen = s.length();\n // cumulative number of plates from the left\n int[] numberOfPlates = new int[sLen+1];\n for (int i=0; i=0; i--) {\n if (s.charAt(i) == '|') {\n cand = i;\n }\n candleToTheRight[i] = cand;\n }\n // for each query - count the number of plates between closest candles\n int[] res = new int[queries.length];\n for (int i=0; i= right) {\n res[i] = 0;\n } else {\n res[i] = numberOfPlates[right+1] - numberOfPlates[left];\n }\n }\n return res;\n }\n}", + "title": "2055. Plates Between Candles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle . You are also given a 0-indexed 2D integer array queries where queries[i] = [left i , right i ] denotes the substring s[left i ...right i ] ( inclusive ). For each query, you need to find the number of plates between candles that are in the substring . A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring . Return an integer array answer where answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "For example, s = \"||**||**|*\" , and a query [3, 8] denotes the substring \"*|| ** |\" . The number of plates between candles in this substring is 2 , as each of the two plates has at least one candle in the substring to its left and right." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"**|**|***|\", queries = [[2,5],[5,9]]\nOutput:[2,3]\nExplanation:- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-1.png" + }, + { + "text": "Example 2: Input:s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\nOutput:[9,0,0,0,0]\nExplanation:- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:\n psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1)\n res = []\n for i, ch in enumerate(s):\n psum[i + 1] = psum[i] + (ch == '|')\n prev[i + 1] = i if ch == '|' else prev[i]\n for i, ch in reversed(list(enumerate(s))):\n next[i] = i if ch == '|' else next[i + 1]\n for q in queries:\n l, r = next[q[0]], prev[q[1] + 1]\n res.append(r - l - (psum[r] - psum[l]) if l < r else 0)\n return res\n", + "title": "2055. Plates Between Candles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]\nOutput:[1,2,4]\nExplanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]\nOutput:[4,3,2,2]\nExplanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]\nOutput:[1,0]\nExplanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 96.61%)\nclass Solution {\n public int[] plusOne(int[] digits) {\n\n int len = digits.length;\n\n //last digit not a 9, just add 1 to it\n if(digits[len - 1] != 9){\n digits[len - 1] = digits[len - 1] + 1;\n return digits;\n }\n\n //last digit is a 9, find the closest digit that is not a 9\n else{\n int i = len - 1;\n while(i >= 0 && digits[i] == 9){\n digits[i] = 0;\n i--;\n }\n if(i == -1){\n int[] ret = new int[len + 1];\n for(int j = 0; j < len; j++){\n ret[j+1] = digits[j];\n }\n ret[0] = 1;\n return ret;\n }\n digits[i] = digits[i] + 1;\n }\n\n return digits;\n }\n}", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]\nOutput:[1,2,4]\nExplanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]\nOutput:[4,3,2,2]\nExplanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]\nOutput:[1,0]\nExplanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 85.76%) | Memory: 16.50 MB (Top 60.81%)\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n\n for i in range(len(digits)-1, -1, -1):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[i] = digits[i] + 1\n return digits\n return [1] + digits \n\n \n", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Given buckets , minutesToDie , and minutesToTest , return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time .", + "description_images": [], + "constraints": [ + "1 <= buckets <= 1000", + "1 <= minutesToDie <= minutesToTest <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:buckets = 4, minutesToDie = 15, minutesToTest = 15\nOutput:2\nExplanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.", + "image": null + }, + { + "text": "Example 2: Input:buckets = 4, minutesToDie = 15, minutesToTest = 30\nOutput:2\nExplanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 75.55%)\nclass Solution {\n public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n int T = (minutesToTest/minutesToDie) + 1;\n int cnt = 0;\n int total = 1;\n while (total < buckets) {\n total *= T;\n cnt++;\n }\n return cnt;\n }\n}", + "title": "458. Poor Pigs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Given buckets , minutesToDie , and minutesToTest , return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time .", + "description_images": [], + "constraints": [ + "1 <= buckets <= 1000", + "1 <= minutesToDie <= minutesToTest <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:buckets = 4, minutesToDie = 15, minutesToTest = 15\nOutput:2\nExplanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.", + "image": null + }, + { + "text": "Example 2: Input:buckets = 4, minutesToDie = 15, minutesToTest = 30\nOutput:2\nExplanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 32 ms (Top 93.2%) | Memory: 16.18 MB (Top 93.2%)\n\nclass Solution(object):\n def poorPigs(self, buckets, minutesToDie, minutesToTest):\n # Calculate the max time for a pig to test buckets...\n # Note that, max time will not be (minutesToTest / minutesToDie)...\n # Thinking about all pigs drinking all buckets at last, but no one died immediately, so the poison bucket is the last bucket...\n max_time = minutesToTest / minutesToDie + 1\n # Initialize the required minimum number of pigs...\n req_pigs = 0\n # To find the minimum number of pigs, find the minimum req_pigs such that Math.pow(max_time, req_pigs) >= buckets...\n while (max_time) ** req_pigs < buckets:\n # Increment until it will be greater or equals to bucket...\n req_pigs += 1\n # Return the required minimum number of pigs...\n return req_pigs", + "title": "458. Poor Pigs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2 12 - 1] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7]\nOutput:[1,#,2,3,#,4,5,6,7,#]\nExplanation:Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/14/116_sample.png" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n q=[]\n q.append(root)\n if not root:\n return None\n while q:\n prev=None\n for i in range(len(q)):\n node=q.pop(0)\n if prev:\n prev.next=node\n prev=node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n prev=None\n return root\n \n", + "title": "116. Populating Next Right Pointers in Each Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]\nOutput:[1,#,2,3,#,4,5,7,#]\nExplanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 98.77%)\nclass Solution {\n public Node connect(Node root) {\n if (root == null) {\n return root;\n }\n Node head = null; //the start node of next level, the first left of next level\n Node prev = null; //the next pointer\n Node curr = root;\n\n while (curr != null) {\n //traverse the whole current level, left -> right, until we meet a null pointer\n while (curr != null) {\n if (curr.left != null) {\n if (head == null) {\n head = curr.left;\n prev = curr.left;\n } else {\n prev.next = curr.left;\n prev = prev.next;\n }\n }\n\n if (curr.right != null) {\n if (head == null) {\n head = curr.right;\n prev = curr.right;\n } else {\n prev.next = curr.right;\n prev = prev.next;\n }\n }\n curr = curr.next;\n }\n\n curr = head;\n prev = null;\n head = null;\n }\n return root;\n }\n}", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]\nOutput:[1,#,2,3,#,4,5,7,#]\nExplanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 305 ms (Top 5.46%) | Memory: 15.4 MB (Top 49.03%)\n\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=0, left=None, right=None, next=None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution(object):\n def findRightMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n right = self.findRightMost(root.right, level + 1, requiredLevel)\n if right:\n return right\n return self.findRightMost(root.left, level + 1, requiredLevel)\n def findLeftMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n left = self.findLeftMost(root.left, level + 1, requiredLevel)\n if left:\n return left\n return self.findLeftMost(root.right, level + 1, requiredLevel)\n def findRightMostFromRoot(self, rootLevelInfo, requiredLevel, currentRight):\n if currentRight:\n if currentRight.right:\n return currentRight.right\n if currentRight.left:\n return currentRight.left\n root, rootlevel = rootLevelInfo\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n while not rightMost and root:\n root = root.right if root.right else root.left\n rootlevel += 1\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n if rightMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n return rightMost\n def findLeftMostFromRoot(self, rootLevelInfo, requiredLevel, currentLeft):\n if currentLeft:\n if currentLeft.left:\n return currentLeft.left\n if currentLeft.right:\n return currentLeft.right\n root, rootlevel = rootLevelInfo\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n while not leftMost and root:\n root = root.left if root.left else root.right\n rootlevel += 1\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n if leftMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n\n return leftMost\n def stitch(self, root):\n if not root:\n return\n leftRootStart = [root.left, 1]\n rightRootStart = [root.right, 1]\n connectLevel = 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, 1, None)\n currentRight = self.findRightMostFromRoot(leftRootStart, 1, None)\n while currentLeft and currentRight:\n currentRight.next = currentLeft\n connectLevel += 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, connectLevel, currentLeft)\n currentRight = self.findRightMostFromRoot(leftRootStart, connectLevel, currentRight)\n\n self.stitch(root.left)\n self.stitch(root.right)\n def connect(self, root):\n \"\"\"\n :type root: Node\n :rtype: Node\n \"\"\"\n if not root:\n return root\n self.stitch(root)\n return root", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\" , \"bb\" , \"xxxx\" , \"z\" , and \"yy\" . A group is identified by an interval [start, end] , where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6] . A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s contains lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbxxxxzzy\"\nOutput:[[3,6]]\nExplanation:\"xxxx\" is the onlylarge group with start index 3 and end index 6.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\"\nOutput:[]\nExplanation:We have groups \"a\", \"b\", and \"c\", none of which are large groups.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcdddeeeeaabbbcd\"\nOutput:[[3,5],[6,9],[12,14]]\nExplanation:The large groups are \"ddd\", \"eeee\", and \"bbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 35.3%) | Memory: 44.08 MB (Top 18.5%)\n\nclass Solution {\n public List> largeGroupPositions(String s) {\n List> res = new ArrayList<>();\n List tmp = new ArrayList<>();\n int count = 1;\n \n for (int i = 0; i < s.length() - 1; i++) {\n // Increment the count until the next element is the same as the previous element. Ex: \"aaa\"\n if (s.charAt(i) == s.charAt(i + 1)) {\n count++;\n } \n // Add the first and last indices of the substring to the list when the next element is different from the previous element. Ex: \"aaab\"\n else if (s.charAt(i) != s.charAt(i + 1) && count >= 3) {\n // gives the starting index of substring\n tmp.add(i - count + 1);\n // gives the last index of substring \n tmp.add(i);\n res.add(tmp);\n count = 1;\n tmp = new ArrayList<>();\n } \n else {\n count = 1;\n }\n }\n\n // Check for a large group at the end of the string. Ex: \"abbb\".\n if (count >= 3) {\n tmp.add(s.length() - count);\n tmp.add(s.length() - 1);\n res.add(tmp);\n }\n\n return res;\n }\n}\n", + "title": "830. Positions of Large Groups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\" , \"bb\" , \"xxxx\" , \"z\" , and \"yy\" . A group is identified by an interval [start, end] , where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6] . A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s contains lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbxxxxzzy\"\nOutput:[[3,6]]\nExplanation:\"xxxx\" is the onlylarge group with start index 3 and end index 6.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\"\nOutput:[]\nExplanation:We have groups \"a\", \"b\", and \"c\", none of which are large groups.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcdddeeeeaabbbcd\"\nOutput:[[3,5],[6,9],[12,14]]\nExplanation:The large groups are \"ddd\", \"eeee\", and \"bbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 17.97%) | Memory: 13.9 MB (Top 73.17%)\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n\n i=0\n c=1\n prev=\"\"\n l=len(s)\n ans=[]\n while i=3):\n ans.append([i+1-c,i])\n else:\n if c>=3:\n ans.append([i-c,i-1])\n c=1\n prev=s[i]\n i+=1\n return ans\n", + "title": "830. Positions of Large Groups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We want to split a group of n people (labeled from 1 to n ) into two groups of any size . Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [a i , b i ] indicates that the person labeled a i does not like the person labeled b i , return true if it is possible to split everyone into two groups in this way .", + "description_images": [], + "constraints": [ + "1 <= n <= 2000", + "0 <= dislikes.length <= 10^4", + "dislikes[i].length == 2", + "1 <= dislikes[i][j] <= n", + "a i < b i", + "All the pairs of dislikes are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput:true\nExplanation:group1 [1,4] and group2 [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] rank;\n int[] parent;\n int[] rival;\n public boolean possibleBipartition(int n, int[][] dislikes) {\n rank = new int[n+1];\n rival = new int[n+1];\n parent = new int[n+1];\n for(int i = 1;i <= n;i++){\n rank[i] = 1;\n parent[i] = i;\n }\n for(int[] dis : dislikes){\n int x = dis[0], y = dis[1];\n if(find(x) == find(y))\n return false;\n if(rival[x] != 0)\n union(rival[x], y);\n else\n rival[x] = y;\n if(rival[y] != 0)\n union(rival[y], x);\n else\n rival[y] = x;\n }\n return true;\n }\n public int find(int x){\n if(parent[x] == x)\n return x;\n return parent[x] = find(parent[x]);\n }\n public void union(int x, int y){\n int x_set = find(x);\n int y_set = find(y);\n if(x_set == y_set)\n return;\n if(rank[x_set] < rank[y_set])\n parent[x_set] = y_set;\n else if(rank[y_set] < rank[x_set])\n parent[y_set] = x_set;\n else{\n parent[x_set] = y_set;\n rank[y_set]++;\n }\n }\n}\n", + "title": "886. Possible Bipartition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We want to split a group of n people (labeled from 1 to n ) into two groups of any size . Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [a i , b i ] indicates that the person labeled a i does not like the person labeled b i , return true if it is possible to split everyone into two groups in this way .", + "description_images": [], + "constraints": [ + "1 <= n <= 2000", + "0 <= dislikes.length <= 10^4", + "dislikes[i].length == 2", + "1 <= dislikes[i][j] <= n", + "a i < b i", + "All the pairs of dislikes are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput:true\nExplanation:group1 [1,4] and group2 [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 997 ms (Top 62.25%) | Memory: 22.2 MB (Top 22.99%)\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n def dfs(i, c):\n if color[i] != 0:\n if color[i] != c:\n return False\n return True\n\n color[i] = c\n for u in e[i]:\n if not dfs(u, 3 - c):\n return False\n return True\n\n e = [[] for _ in range(n)]\n for u, v in dislikes:\n u -= 1\n v -= 1\n e[u].append(v)\n e[v].append(u)\n color = [0] * n\n for i in range(n):\n if color[i] == 0:\n if not dfs(i, 1):\n return False\n return True", + "title": "886. Possible Bipartition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ).", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10\nOutput:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3\nOutput:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2\nOutput:0.25000\nExplanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double myPow(double x, int n) {\n if (n == 0) return 1;\n if (n == 1) return x;\n else if (n == -1) return 1 / x;\n double res = myPow(x, n / 2);\n if (n % 2 == 0) return res * res;\n else if (n % 2 == -1) return res * res * (1/x);\n else return res * res * x;\n }\n}\n", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ).", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10\nOutput:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3\nOutput:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2\nOutput:0.25000\nExplanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n self.x = x\n \n if n == 0:\n return 1\n \n isInverted = False\n if n < 0:\n isInverted = True\n n = -1 * n\n\n result = self.pow(n)\n \n return result if not isInverted else 1 / result\n \n def pow(self, n):\n if n == 1:\n return self.x\n \n if n % 2 == 0:\n p = self.pow(n / 2)\n return p * p\n else:\n return self.x * self.pow(n-1)\n", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return true if it is a power of four. Otherwise, return false . An integer n is a power of four, if there exists an integer x such that n == 4 x .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 16\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 64.18%) | Memory: 40.9 MB (Top 74.82%)\nclass Solution {\n public boolean isPowerOfFour(int n) {\n return (Math.log10(n)/Math.log10(4))%1==0;\n }\n}", + "title": "342. Power of Four", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return true if it is a power of four. Otherwise, return false . An integer n is a power of four, if there exists an integer x such that n == 4 x .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 16\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 35.3%) | Memory: 16.23 MB (Top 61.5%)\n\nimport math \nclass Solution:\n def isPowerOfFour(self, n: int) -> bool:\n\n if n <= 0:\n return False\n return math.log(n, 4).is_integer()", + "title": "342. Power of Four", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return true if it is a power of three. Otherwise, return false . An integer n is a power of three, if there exists an integer x such that n == 3 x .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 27\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 9\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPowerOfThree(int n) {\n if(n==1){\n return true;\n }\n if(n<=0){\n return false;\n }\n if(n%3 !=0 && n>1){\n return false;\n }\n else{\n return isPowerOfThree(n/3); // recurssion \n }\n }\n}\n", + "title": "326. Power of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return true if it is a power of three. Otherwise, return false . An integer n is a power of three, if there exists an integer x such that n == 3 x .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 27\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:n = 0\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:n = 9\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 96.60%) | Memory: 13.8 MB (Top 57.97%)\nclass Solution:\n def isPowerOfThree(self, n: int) -> bool:\n return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False", + "title": "326. Power of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:true\nExplanation:20= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 16\nOutput:true\nExplanation:24= 16", + "image": null + }, + { + "text": "Example 3: Input:n = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 14.46%) | Memory: 41.2 MB (Top 58.53%)\nclass Solution {\n public boolean isPowerOfTwo(int n) {\n return power2(0,n);\n\n }\n public boolean power2(int index,int n){\n if(Math.pow(2,index)==n)\n return true;\n if(Math.pow(2,index)>n)\n return false;\n return power2(index+1,n);\n }\n}", + "title": "231. Power of Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:true\nExplanation:20= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 16\nOutput:true\nExplanation:24= 16", + "image": null + }, + { + "text": "Example 3: Input:n = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n \n if n == 0: return False\n \n k = n\n while k != 1:\n if k % 2 != 0:\n return False\n k = k // 2\n \n \n return True\n\n count = 0\n for i in range(33):\n mask = 1 << i\n \n if mask & n:\n count += 1\n \n if count > 1:\n return False\n \n if count == 1:\n return True\n return False\n\t\t\n", + "title": "231. Power of Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given three integers x , y , and bound , return a list of all the powerful integers that have a value less than or equal to bound . An integer is powerful if it can be represented as x i + y j for some integers i >= 0 and j >= 0 . You may return the answer in any order . In your answer, each value should occur at most once .", + "description_images": [], + "constraints": [ + "1 <= x, y <= 100", + "0 <= bound <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2, y = 3, bound = 10\nOutput:[2,3,4,5,7,9,10]\nExplanation:2 = 20+ 303 = 21+ 304 = 20+ 315 = 21+ 317 = 22+ 319 = 23+ 3010 = 20+ 32", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 5, bound = 15\nOutput:[2,4,6,8,10,14]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 39.15%) | Memory: 41.9 MB (Top 60.38%)\nclass Solution {\n public List powerfulIntegers(int x, int y, int bound) {\n HashSet set = new HashSet<>();\n for(int i = 1; i(set);\n }\n}", + "title": "970. Powerful Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given three integers x , y , and bound , return a list of all the powerful integers that have a value less than or equal to bound . An integer is powerful if it can be represented as x i + y j for some integers i >= 0 and j >= 0 . You may return the answer in any order . In your answer, each value should occur at most once .", + "description_images": [], + "constraints": [ + "1 <= x, y <= 100", + "0 <= bound <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2, y = 3, bound = 10\nOutput:[2,3,4,5,7,9,10]\nExplanation:2 = 20+ 303 = 21+ 304 = 20+ 315 = 21+ 317 = 22+ 319 = 23+ 3010 = 20+ 32", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 5, bound = 15\nOutput:[2,4,6,8,10,14]", + "image": null + } + ], + "follow_up": null, + "solution": "from math import log\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n if bound == 0:\n return []\n maxi = int(log(bound,max(x,2))) +1\n maxj = int(log(bound,max(y,2))) +1\n L = set()\n for i in range(maxi):\n for j in range(maxj):\n if (t:=x**i +y**j) <= bound:\n L.add(t)\n else:\n break\n return list(L)\n", + "title": "970. Powerful Integers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums . Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0 . At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1] ) which reduces the size of the array by 1 . The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true . You may assume that both players are playing optimally.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 20", + "0 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,2]\nOutput:false\nExplanation:Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,233,7]\nOutput:true\nExplanation:Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean PredictTheWinner(int[] nums) {\n return predictTheWinner(nums, 0, nums.length-1,true,0, 0);\n }\n private boolean predictTheWinner(int[] nums, int start,int end, boolean isP1Turn, long p1Score, long p2Score){\n if(start > end){\n return p1Score >= p2Score;\n }\n\n boolean firstTry;\n boolean secondTry;\n if(isP1Turn){\n firstTry = predictTheWinner(nums, start +1 , end, false, p1Score + nums[start], p2Score);\n secondTry = predictTheWinner(nums, start, end-1, false, p1Score + nums[end], p2Score);\n\n }else{\n firstTry = predictTheWinner(nums, start +1 , end, true, p1Score, p2Score + nums[start]);\n secondTry = predictTheWinner(nums, start, end-1, true, p1Score , p2Score + nums[end]);\n\n }\n return isP1Turn ? (firstTry || secondTry) : (firstTry && secondTry);\n }\n}\n", + "title": "486. Predict the Winner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0 . At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1] ) which reduces the size of the array by 1 . The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true . You may assume that both players are playing optimally.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 20", + "0 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,2]\nOutput:false\nExplanation:Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,233,7]\nOutput:true\nExplanation:Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n dp = [[-1] * len(nums) for _ in nums]\n def get_score(i: int, j: int) -> int:\n if i == j: \n dp[i][j] = 0\n return dp[i][j]\n if i == j - 1:\n dp[i][j] = nums[j] if nums[i] > nums[j] else nums[i]\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n\n y1 = get_score(i + 1, j - 1)\n y2 = get_score(i + 2, j)\n y3 = get_score(i, j - 2)\n res_y1 = y1 + nums[j] if y1 + nums[j] > y2 + nums[i+1] else y2 + nums[i+1]\n res_y2 = y1 + nums[i] if y1 + nums[i] > y3 + nums[j-1] else y3 + nums[j-1]\n\n dp[i][j] = min(res_y1, res_y2)\n return dp[i][j] \n \n y = get_score(0, len(nums) - 1)\n x = sum(nums) - y\n\n return 0 if y > x else 1\n", + "title": "486. Predict the Winner", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class:", + "description_images": [], + "constraints": [ + "WordFilter(string[] words) Initializes the object with the words in the dictionary.", + "f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff . If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"WordFilter\", \"f\"]\n[[[\"apple\"]], [\"a\", \"e\"]]Output[null, 0]ExplanationWordFilter wordFilter = new WordFilter([\"apple\"]);\nwordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = \"e\".", + "image": null + } + ], + "follow_up": null, + "solution": "class WordFilter:\n def __init__(self, words: List[str]):\n self.words = words\n \n def f(self, prefix: str, suffix: str) -> int:\n idx = -1\n for i,w in enumerate(self.words):\n if w.startswith(prefix) and w.endswith(suffix):\n idx = i\n \n return idx\n\n", + "title": "745. Prefix and Suffix Search", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Let f(x) be the number of zeroes at the end of x! . Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1 . Given an integer k , return the number of non-negative integers x have the property that f(x) = k .", + "description_images": [], + "constraints": [ + "For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end." + ], + "examples": [ + { + "text": "Example 1: Input:k = 0\nOutput:5\nExplanation:0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.", + "image": null + }, + { + "text": "Example 2: Input:k = 5\nOutput:0\nExplanation:There is no x such that x! ends in k = 5 zeroes.", + "image": null + }, + { + "text": "Example 3: Input:k = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int preimageSizeFZF(int k) {\n long n = 4L * k;\n int resp = 0;\n while (true) {\n int t = zeros(n);\n if (t > k) return 0;\n if (t == k) return 5;\n n++;\n }\n \n }\n \n private int zeros(long n) {\n int resp = 0;\n while (n > 0) {\n resp += (int)(n / 5);\n n /= 5;\n }\n return resp;\n }\n}\n", + "title": "793. Preimage Size of Factorial Zeroes Function", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Let f(x) be the number of zeroes at the end of x! . Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1 . Given an integer k , return the number of non-negative integers x have the property that f(x) = k .", + "description_images": [], + "constraints": [ + "For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end." + ], + "examples": [ + { + "text": "Example 1: Input:k = 0\nOutput:5\nExplanation:0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.", + "image": null + }, + { + "text": "Example 2: Input:k = 5\nOutput:0\nExplanation:There is no x such that x! ends in k = 5 zeroes.", + "image": null + }, + { + "text": "Example 3: Input:k = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 30 ms (Top 93.33%) | Memory: 16.50 MB (Top 82.96%)\n\nclass Solution:\n def preimageSizeFZF(self, k: int) -> int: \n\n def atMost_k(k: int)-> int:\n\n left, right = 0, 5*k + 4\n\n while left <= right:\n mid = (left+right)//2\n count, n = 0, mid\n\n while n:\n n//= 5\n count+= n\n\n if count <= k: left = mid + 1\n else: right = mid - 1\n\n return right\n\n \n return atMost_k(k) - atMost_k(k-1)\n", + "title": "793. Preimage Size of Factorial Zeroes Function", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr , that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j] ). If it cannot be done, then return the same array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,1]\nOutput:[3,1,2]\nExplanation:Swapping 2 and 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,5]\nOutput:[1,1,5]\nExplanation:This is already the smallest permutation.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,9,4,6,7]\nOutput:[1,7,4,6,9]\nExplanation:Swapping 9 and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] prevPermOpt1(int[] arr) {\n int n=arr.length;\n int small=arr[n-1];\n int prev=arr[n-1];\n for(int i=n-2;i>=0;i--){\n if(arr[i]<=prev){\n prev=arr[i];\n }\n else{\n int indte=i;\n int te=0;\n for(int j=i+1;jte){\n te=arr[j];\n indte=j;\n }\n }\n int tem=arr[indte];\n arr[indte]=arr[i];\n arr[i]=tem;\n return arr;\n }\n }\n return arr;\n }\n}\n", + "title": "1053. Previous Permutation With One Swap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr , that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j] ). If it cannot be done, then return the same array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,1]\nOutput:[3,1,2]\nExplanation:Swapping 2 and 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,5]\nOutput:[1,1,5]\nExplanation:This is already the smallest permutation.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,9,4,6,7]\nOutput:[1,7,4,6,9]\nExplanation:Swapping 9 and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 486 ms (Top 14.08%) | Memory: 15.3 MB (Top 47.61%)\nclass Solution:\n\n def find_max(self, i, a, n):\n maxs = i+1\n for j in range(n-1, i, -1):\n # if only j is greater than max and smaller than first descending element\n if(a[maxs] <= a[j] and a[j] < a[i]):\n maxs = j\n # Swap\n a[i], a[maxs] = a[maxs], a[i]\n return a\n\n def prevPermOpt1(self, arr):\n n = len(arr)\n for i in range(n-1, 0, -1):\n if(arr[i] < arr[i-1]):\n # sending the first descending element from right to max_function\n arr = self.find_max(i-1, arr, n)\n break\n return arr", + "title": "1053. Previous Permutation With One Swap", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5\nOutput:12\nExplanation:For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:682289015", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n long mod = (long)(1e9+7);\n public int numPrimeArrangements(int n) {\n if(n==1){\n return 1;\n }\n \n boolean[] arr = new boolean[n+1];\n Arrays.fill(arr,true);\n arr[0]=false;\n arr[1]=false;\n \n for(int i=2;i<=Math.sqrt(n);i++){\n \n for(int j=i*i;j<=n;j+=i){\n if(arr[i]==false){\n continue;\n }\n arr[j]=false;\n }\n \n }\n long prime = 0;\n long notPrime=0;\n for(int k=1;k int:\n primes = set()\n for i in range(2,n+1):\n if all(i%p != 0 for p in primes):\n primes.add(i)\n M = 10**9 + 7\n def fact(k):\n res = 1\n for i in range(2,k+1):\n res = (res*i)%M\n return res\n return fact(len(primes))*fact(n-len(primes))%M", + "title": "1175. Prime Arrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right , return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation . Recall that the number of set bits an integer has is the number of 1 's present when written in binary.", + "description_images": [], + "constraints": [ + "For example, 21 written in binary is 10101 , which has 3 set bits." + ], + "examples": [ + { + "text": "Example 1: Input:left = 6, right = 10\nOutput:4\nExplanation:6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.", + "image": null + }, + { + "text": "Example 2: Input:left = 10, right = 15\nOutput:5\nExplanation:10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 161 ms (Top 18.27%) | Memory: 63.5 MB (Top 16.98%)\nclass Solution {\n public int calculateSetBits(String s){\n int count=0;\n for (int i = 0; i < s.length(); i++) {\n if(s.charAt(i)=='1') count++;\n }\n return count;\n }\n\n public boolean isPrime(int n){\n if (n==0 || n==1) return false;\n for (int i = 2; i <= n/2; i++) {\n if(n%i ==0 ) return false;\n }\n// System.out.println(n+\" - \");\n return true;\n }\n\n public int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;i++){\n String b= Integer.toBinaryString(i);\n\n int n=calculateSetBits(b);\n\n if(isPrime(n)) count++;\n }\n return count;\n }\n}", + "title": "762. Prime Number of Set Bits in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integers left and right , return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation . Recall that the number of set bits an integer has is the number of 1 's present when written in binary.", + "description_images": [], + "constraints": [ + "For example, 21 written in binary is 10101 , which has 3 set bits." + ], + "examples": [ + { + "text": "Example 1: Input:left = 6, right = 10\nOutput:4\nExplanation:6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.", + "image": null + }, + { + "text": "Example 2: Input:left = 10, right = 15\nOutput:5\nExplanation:10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n return sum(bin(n).count('1') in primes for n in range(left, right + 1))", + "title": "762. Prime Number of Set Bits in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n, return the smallest prime palindrome greater than or equal to n . An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8 ] .", + "description_images": [], + "constraints": [ + "For example, 2 , 3 , 5 , 7 , 11 , and 13 are all primes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6\nOutput:7", + "image": null + }, + { + "text": "Example 2: Input:n = 8\nOutput:11", + "image": null + }, + { + "text": "Example 3: Input:n = 13\nOutput:101", + "image": null + } + ], + "follow_up": null, + "solution": "// Prime Palindrome\n// Leetcode problem: https://leetcode.com/problems/prime-palindrome/\n\nclass Solution {\n public int primePalindrome(int n) {\n while (true) {\n if (isPrime(n) && isPalindrome(n)) {\n return n;\n }\n n++;\n } \n }\n private boolean isPrime(int n) {\n if (n == 1) {\n return false;\n }\n for (int i = 2; i <= Math.sqrt(n); i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n private boolean isPalindrome(int n) {\n String s = String.valueOf(n);\n int i = 0;\n int j = s.length() - 1;\n while (i < j) {\n if (s.charAt(i) != s.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n}\n", + "title": "866. Prime Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n, return the smallest prime palindrome greater than or equal to n . An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8 ] .", + "description_images": [], + "constraints": [ + "For example, 2 , 3 , 5 , 7 , 11 , and 13 are all primes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6\nOutput:7", + "image": null + }, + { + "text": "Example 2: Input:n = 8\nOutput:11", + "image": null + }, + { + "text": "Example 3: Input:n = 13\nOutput:101", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 99.21%) | Memory: 17.20 MB (Top 18.9%)\n\nclass Solution:\n def isPrime(self, num):\n from math import sqrt\n if num < 2 or num % 2 == 0:\n return num == 2\n for i in range(3, int(sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True\n\n def primePalindrome(self, n: int) -> int:\n if 8 <= n <= 11:\n return 11\n if len(str(n)) % 2 == 0:\n limit = pow(10, len(str(n)) // 2)\n else:\n n_string = str(n)\n limit = n_string[:len(str(n)) // 2 + 1]\n for i in range(int(limit), 20000):\n y = int(str(i) + str(i)[:-1][::-1])\n if y >= n and self.isPrime(y):\n return y\n", + "title": "866. Prime Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: Return the constructed matrix res .", + "description_images": [], + "constraints": [ + "The height of the tree is height and the number of rows m should be equal to height + 1 .", + "The number of columns n should be equal to 2 height+1 - 1 .", + "Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2] ).", + "For each node that has been placed in the matrix at position res[r][c] , place its left child at res[r+1][c-2 height-r-1 ] and its right child at res[r+1][c+2 height-r-1 ] .", + "Continue this process until all the nodes in the tree have been placed.", + "Any empty cells should contain the empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2]\nOutput:[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]\nOutput:[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 43.8 MB (Top 78.96%)\nclass Solution {\n public List> printTree(TreeNode root) {\n List> res = new ArrayList();\n\n int height = getHeight(root);\n int row = height + 1;\n int column = (int) Math.pow(2, height+1) - 1;\n\n for(int k=0; k list = new ArrayList();\n for(int i=0; i> res, int left, int right, int level, TreeNode root){\n if(root == null) return;\n int mid = left+(right-left)/2;\n res.get(level).set(mid, String.valueOf(root.val));\n\n print(res, left, mid-1, level+1, root.left);\n print(res, mid+1, right, level+1, root.right);\n }\n public int getHeight(TreeNode root){\n if (root==null) return -1;\n int left = getHeight(root.left);\n int right = getHeight(root.right);\n\n return Math.max(left, right)+1;\n }\n}", + "title": "655. Print Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: Return the constructed matrix res .", + "description_images": [], + "constraints": [ + "The height of the tree is height and the number of rows m should be equal to height + 1 .", + "The number of columns n should be equal to 2 height+1 - 1 .", + "Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2] ).", + "For each node that has been placed in the matrix at position res[r][c] , place its left child at res[r+1][c-2 height-r-1 ] and its right child at res[r+1][c+2 height-r-1 ] .", + "Continue this process until all the nodes in the tree have been placed.", + "Any empty cells should contain the empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2]\nOutput:[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]\nOutput:[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 97.8%) | Memory: 17.40 MB (Top 11.72%)\n\nclass Solution:\n def printTree(self, root: TreeNode) -> List[List[str]]:\n height = 0\n def dfs(node, h): # Find height\n nonlocal height\n height = max(height, h)\n if node.left:\n dfs(node.left, h+1)\n if node.right: \n dfs(node.right, h+1)\n dfs(root, 0)\n n = 2 ** (height + 1) - 1 # Get `n`\n offset = (n - 1) // 2 # Column for root node\n ans = [[''] * n for _ in range(height + 1)]\n q = [(root, 0, offset)]\n for i in range(height+1): # BFS\n tmp_q = []\n while q:\n cur, r, c = q.pop()\n ans[r][c] = str(cur.val)\n if cur.left:\n tmp_q.append((cur.left, r+1, c-2 ** (height - r - 1)))\n if cur.right: \n tmp_q.append((cur.right, r+1, c+2 ** (height - r - 1)))\n q = tmp_q\n return ans\n", + "title": "655. Print Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s . Return all the words vertically in the same order in which they appear in s . Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 200", + "s contains only upper case English letters.", + "It's guaranteed that there is only one space between 2 words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"HOW ARE YOU\"\nOutput:[\"HAY\",\"ORO\",\"WEU\"]\nExplanation:Each word is printed vertically. \n \"HAY\"\n \"ORO\"\n \"WEU\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"TO BE OR NOT TO BE\"\nOutput:[\"TBONTB\",\"OEROOE\",\" T\"]\nExplanation:Trailing spaces is not allowed. \n\"TBONTB\"\n\"OEROOE\"\n\" T\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"CONTEST IS COMING\"\nOutput:[\"CIC\",\"OSO\",\"N M\",\"T I\",\"E N\",\"S G\",\"T\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 20.22%) | Memory: 42.9 MB (Top 20.22%)\nclass Solution {\n public List printVertically(String s) {\n s = s.replace(\" \",\",\");\n String str=\"\";\n List a=new ArrayList<>();\n\n int max=0;\n for(int i =0;i();\n for(int i=0;i List[str]:\n words = s.split()\n max_len = self.getMaxLen(words)\n \n res = list()\n for i in range(max_len):\n s = \"\"\n for word in words:\n if i < len(word):\n s += word[i]\n else:\n s += \" \"\n s = s.rstrip()\n res.append(s)\n return res\n \n \n \n\t\t\n", + "title": "1324. Print Words Vertically", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the i th cell is occupied and cells[i] == 0 if the i th cell is vacant, and you are given an integer n . Return the state of the prison after n days (i.e., n such changes described above).", + "description_images": [], + "constraints": [ + "If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.", + "Otherwise, it becomes vacant." + ], + "examples": [ + { + "text": "Example 1: Input:cells = [0,1,0,1,1,0,0,1], n = 7\nOutput:[0,0,1,1,0,0,0,0]\nExplanation:The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]", + "image": null + }, + { + "text": "Example 2: Input:cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput:[0,0,1,1,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.57%) | Memory: 42.40 MB (Top 48.82%)\n\nclass Solution {\n public int[] prisonAfterNDays(int[] cells, int N) {\n if(N==0) return cells;\n int[][] mem=new int[14][8]; // Repeat pattern after day 14, so Day 1 and Day 15 is equal\n mem[0][0]=0;\n mem[0][7]=0;\n for(int i=1;i<7;i++){ // calculating Day 1 and insert at 0th position in mem\n if(cells[i-1]==cells[i+1])\n mem[0][i]=1;\n else\n mem[0][i]=0;\n }\n \n for(int j=1;j<14;j++){ // calculating Day 2 to 14 and inserting at position 1 to 13 in mem.\n for(int i=1;i<7;i++){\n if(mem[j-1][i-1]==mem[j-1][i+1])\n mem[j][i]=1;\n else\n mem[j][i]=0;\n }\n }\n return mem[(N-1)%14]; //return the day modulo 14\n }\n}\n", + "title": "957. Prison Cells After N Days", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the i th cell is occupied and cells[i] == 0 if the i th cell is vacant, and you are given an integer n . Return the state of the prison after n days (i.e., n such changes described above).", + "description_images": [], + "constraints": [ + "If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.", + "Otherwise, it becomes vacant." + ], + "examples": [ + { + "text": "Example 1: Input:cells = [0,1,0,1,1,0,0,1], n = 7\nOutput:[0,0,1,1,0,0,0,0]\nExplanation:The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]", + "image": null + }, + { + "text": "Example 2: Input:cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput:[0,0,1,1,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 85 ms (Top 14.83%) | Memory: 14 MB (Top 28.83%)\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n patternMatch=defaultdict(int) # pattern match\n totalPrisons=8 # totalPrisons\n cells= [ str(c) for c in (cells)] # into char type\n for d in range(1,n+1):\n tempCell=[]\n tempCell.append('0') # left corner case\n for c in range(1,totalPrisons-1):\n if (cells[c-1]=='1' and cells[c+1]=='1') or (cells[c-1]=='0' and cells[c+1]=='0'):\n tempCell.append('1') # insert 1 if first condition met\n else:\n tempCell.append('0') # otherwise 0\n tempCell.append('0') # right corner case\n cells=tempCell # update cells\n pattern= ''.join(tempCell) # insert pattern in hashtable\n if pattern in patternMatch: # if there is a match\n day=patternMatch[pattern]\n remainder= (n%(d-1))-1 # take modulo\n match= list(patternMatch.keys())[remainder] # find key\n return [ int(m) for m in match] # return\n patternMatch[pattern]=d # assign day\n return [ int(c) for c in (cells)] # return", + "title": "957. Prison Cells After N Days", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i . All the balls will be shuffled uniformly at random , then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b , and two boxes [] and () , then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10 -5 of the actual value will be accepted as correct.", + "description_images": [], + "constraints": [ + "1 <= balls.length <= 8", + "1 <= balls[i] <= 6", + "sum(balls) is even." + ], + "examples": [ + { + "text": "Example 1: Input:balls = [1,1]\nOutput:1.00000\nExplanation:Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1", + "image": null + }, + { + "text": "Example 2: Input:balls = [2,1,1]\nOutput:0.66667\nExplanation:We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667", + "image": null + }, + { + "text": "Example 3: Input:balls = [1,2,1,2]\nOutput:0.60000\nExplanation:The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 48.15%) | Memory: 41.6 MB (Top 50.00%)\nclass Solution {\n double all = 0;\n public double getProbability(int[] balls) {\n double[] fact = new double[25];\n fact[0]=1;\n for (int i = 1; i <= 24; i++){\n fact[i]=i*fact[i-1];\n }\n int need = Arrays.stream(balls).sum()/2;\n return solve(0, 0, need, new int[balls.length], balls, fact)/all;\n }\n\n private double solve(int idx, int got, int need, int[] cur, int[] balls, double[] fact){\n if (need == got){\n int colors=0;\n double a = fact[need];\n double b = fact[need];\n for (int i = 0;ineed){\n return 0;\n }\n double ans = 0;\n for (int i = 0; i <=balls[idx];i++){ // for this level of ball, try to take 0 to balls[idx]\n cur[idx]+=i;\n ans += solve(idx+1,got+i,need,cur,balls,fact);\n cur[idx]-=i;\n }\n return ans;\n }\n}", + "title": "1467. Probability of a Two Boxes Having The Same Number of Distinct Balls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i . All the balls will be shuffled uniformly at random , then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b , and two boxes [] and () , then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10 -5 of the actual value will be accepted as correct.", + "description_images": [], + "constraints": [ + "1 <= balls.length <= 8", + "1 <= balls[i] <= 6", + "sum(balls) is even." + ], + "examples": [ + { + "text": "Example 1: Input:balls = [1,1]\nOutput:1.00000\nExplanation:Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1", + "image": null + }, + { + "text": "Example 2: Input:balls = [2,1,1]\nOutput:0.66667\nExplanation:We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667", + "image": null + }, + { + "text": "Example 3: Input:balls = [1,2,1,2]\nOutput:0.60000\nExplanation:The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 90.74%) | Memory: 14.1 MB (Top 53.70%)\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n m = len(balls)\n N = sum(balls)\n n = N // 2\n\n prefix = [0] * m\n for i in range(m):\n prefix[i] = prefix[i-1] + balls[i]\n\n # STEP 1: Compute the number of ways to pick j balls from i total, i.e. C(i, j)\n choose = [[0] * (N + 1) for i in range(N + 1)]\n choose[0][0] = 1\n for i in range(1, N + 1):\n for pick in range(N + 1):\n # DECISION 1: don't pick the ith ball\n choose[i][pick] += choose[i - 1][pick]\n # DECISION 2: pick the ith ball\n choose[i][pick] += choose[i - 1][pick - 1]\n\n # STEP 2: From first i ball types, compute ways to:\n # - pick c1 balls in box1\n # - such that the difference in unique ball count between box1 and box2 is d\n ways = [[defaultdict(int) for k in range(n + 1)] for i in range(m + 1)]\n ways[0][0][0] = 1\n\n for i in range(m):\n b = balls[i]\n if i == 0:\n prev_total = 0\n else:\n prev_total = prefix[i - 1]\n for c1 in range(n + 1):\n c2 = prev_total - c1\n if c2 < 0:\n continue\n for d in ways[i][c1]:\n for add1 in range(b + 1):\n add2 = b - add1\n if c1 + add1 > n:\n continue\n if c2 + add2 > n:\n continue\n if add1 == b:\n delta = 1\n elif add2 == b:\n delta = -1\n else:\n delta = 0\n ways_to_add = choose[b][add1] * ways[i][c1][d]\n ways[i + 1][c1 + add1][d + delta] += ways_to_add\n\n # compute the actual probability\n return ways[m][n][0] / choose[N][n]", + "title": "1467. Probability of a Two Boxes Having The Same Number of Distinct Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1 . You are also given a 0-indexed 2D integer array restrictions , where restrictions[i] = [x i , y i ] means that person x i and person y i cannot become friends , either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests , where requests[j] = [u j , v j ] is a friend request between person u j and person v j . A friend request is successful if u j and v j can be friends . Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1] ), and upon a successful request, u j and v j become direct friends for all future friend requests. Return a boolean array result , where each result[j] is true if the j th friend request is successful or false if it is not . Note: If u j and v j are already direct friends, the request is still successful .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "0 <= restrictions.length <= 1000", + "restrictions[i].length == 2", + "0 <= x i , y i <= n - 1", + "x i != y i", + "1 <= requests.length <= 1000", + "requests[j].length == 2", + "0 <= u j , v j <= n - 1", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput:[true,false]\nExplanation:Request 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).", + "image": null + }, + { + "text": "Example 2: Input:n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput:[true,false]\nExplanation:Request 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).", + "image": null + }, + { + "text": "Example 3: Input:n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput:[true,false,true,false]\nExplanation:Request 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n boolean[] result;\n \n public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n parent = new int[n];\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n result = new boolean[requests.length];\n \n for (int i = 0; i < requests.length; i++) {\n // personA and personB can become friends if for all restrictions\n // person x_i and person y_i are not in the same set as personA and personB\n // and vice versa\n int personA = requests[i][0];\n int personB = requests[i][1];\n int personASetRepresentative = find(personA);\n int personBSetRepresentative = find(personB);\n boolean flag = true;\n for (int[] restriction : restrictions) {\n int blackListPersonARepresentative = find(restriction[0]);\n int blackListPersonBRepresentative = find(restriction[1]);\n if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) {\n flag = false;\n }\n if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) {\n flag = false;\n }\n }\n if (flag) {\n union(personA, personB);\n }\n result[i] = flag;\n }\n return result;\n }\n \n private int find(int node) {\n int root = node;\n while (parent[root] != root) {\n root = parent[root];\n }\n \n //path compression\n int curr = node;\n while (parent[curr] != root) {\n int next = parent[curr];\n parent[curr] = root;\n curr = next;\n }\n return root;\n }\n \n private boolean union(int node1, int node2) {\n int root1 = find(node1);\n int root2 = find(node2);\n if (root1 == root2) {\n return false;\n }\n parent[root2] = root1;\n return true;\n }\n}\n", + "title": "2076. Process Restricted Friend Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1 . You are also given a 0-indexed 2D integer array restrictions , where restrictions[i] = [x i , y i ] means that person x i and person y i cannot become friends , either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests , where requests[j] = [u j , v j ] is a friend request between person u j and person v j . A friend request is successful if u j and v j can be friends . Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1] ), and upon a successful request, u j and v j become direct friends for all future friend requests. Return a boolean array result , where each result[j] is true if the j th friend request is successful or false if it is not . Note: If u j and v j are already direct friends, the request is still successful .", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "0 <= restrictions.length <= 1000", + "restrictions[i].length == 2", + "0 <= x i , y i <= n - 1", + "x i != y i", + "1 <= requests.length <= 1000", + "requests[j].length == 2", + "0 <= u j , v j <= n - 1", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput:[true,false]\nExplanation:Request 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).", + "image": null + }, + { + "text": "Example 2: Input:n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput:[true,false]\nExplanation:Request 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).", + "image": null + }, + { + "text": "Example 3: Input:n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput:[true,false,true,false]\nExplanation:Request 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).", + "image": null + } + ], + "follow_up": null, + "solution": "class UnionFindSet(object):\n def __init__(self, n):\n self.data = range(n)\n\n def find(self, x):\n while x <> self.data[x]:\n x = self.data[x]\n return x\n\n def union(self, x, y):\n self.data[self.find(x)] = self.find(y)\n\n def speedup(self):\n for i in range(len(self.data)):\n self.data[i] = self.find(i)\n\n\nclass Solution(object):\n def friendRequests(self, n, restrictions, requests):\n uf = UnionFindSet(n)\n ret = [True] * len(requests)\n for k, [x, y] in enumerate(requests): # Process Requests Sequentially\n xh = uf.find(x) # backup the head of x for undo\n uf.union(x, y) # link [x, y] and verify if any restriction triggers\n for [i, j] in restrictions:\n if uf.find(i) == uf.find(j):\n ret[k] = False\n break\n if not ret[k]: # if any restriction triggers, undo\n uf.data[xh] = xh\n else:\n uf.speedup()\n return ret\n", + "title": "2076. Process Restricted Friend Requests", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n ​​​​​​ and m ​​​​​​ respectively. servers[i] is the weight of the i ​​​​​​th ​​​​ server, and tasks[j] is the time needed to process the j ​​​​​​th ​​​​ task in seconds . Tasks are assigned to the servers using a task queue . Initially, all servers are free, and the queue is empty . At second j , the j th task is inserted into the queue (starting with the 0 th task being inserted at second 0 ). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight , and in case of a tie, it is assigned to a free server with the smallest index . If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j] . Build an array ans ​​​​ of length m , where ans[j] is the index of the server the j ​​​​​​th task will be assigned to. Return the array ans ​​​​.", + "description_images": [], + "constraints": [ + "servers.length == n", + "tasks.length == m", + "1 <= n, m <= 2 * 10^5", + "1 <= servers[i], tasks[j] <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput:[2,2,0,2,1,2]\nExplanation:Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "image": null + }, + { + "text": "Example 2: Input:servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput:[1,4,1,4,1,3,2]\nExplanation:Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 421 ms (Top 69.74%) | Memory: 172.7 MB (Top 82.56%)\nclass Solution {\n public int[] assignTasks(int[] servers, int[] tasks) {\n\n PriorityQueue availableServer = new PriorityQueue((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0])));\n for(int i = 0; i < servers.length; i++){\n availableServer.add(new int[]{i, servers[i]});\n }\n\n //int[[] arr,\n //arr[0] - server index\n //arr[1] - server weight\n //arr[2] - free time\n PriorityQueue processingServer = new PriorityQueue(\n (a, b) ->\n\n (\n a[2] != b[2] ? a[2] - b[2] : // try to sort increasing order of free time\n a[1] != b[1] ? a[1] - b[1] : // try to sort increasing order of server weight\n a[0] - b[0] // sort increasing order of server index\n )\n );\n\n int[] result = new int[tasks.length];\n\n for(int i = 0; i < tasks.length; i++){\n\n while(!processingServer.isEmpty() && processingServer.peek()[2] <= i){\n int serverIndex = processingServer.remove()[0];\n availableServer.add(new int[]{serverIndex, servers[serverIndex]});\n }\n\n int currentTaskTimeRequired = tasks[i];\n\n int[] server;\n\n //when current task will free the server done\n int freeTime = currentTaskTimeRequired;\n\n if(!availableServer.isEmpty()){\n server = availableServer.remove();\n freeTime += i;\n }else{\n server = processingServer.remove();\n //append previous time\n freeTime += server[2];\n }\n\n int serverIndex = server[0];\n processingServer.add(new int[]{serverIndex, servers[serverIndex] ,freeTime});\n\n //assign this server to current task\n result[i] = serverIndex;\n }\n\n return result;\n\n }\n}", + "title": "1882. Process Tasks Using Servers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n ​​​​​​ and m ​​​​​​ respectively. servers[i] is the weight of the i ​​​​​​th ​​​​ server, and tasks[j] is the time needed to process the j ​​​​​​th ​​​​ task in seconds . Tasks are assigned to the servers using a task queue . Initially, all servers are free, and the queue is empty . At second j , the j th task is inserted into the queue (starting with the 0 th task being inserted at second 0 ). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight , and in case of a tie, it is assigned to a free server with the smallest index . If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j] . Build an array ans ​​​​ of length m , where ans[j] is the index of the server the j ​​​​​​th task will be assigned to. Return the array ans ​​​​.", + "description_images": [], + "constraints": [ + "servers.length == n", + "tasks.length == m", + "1 <= n, m <= 2 * 10^5", + "1 <= servers[i], tasks[j] <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput:[2,2,0,2,1,2]\nExplanation:Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "image": null + }, + { + "text": "Example 2: Input:servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput:[1,4,1,4,1,3,2]\nExplanation:Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n servers_available = [(w, i) for i,w in enumerate(servers)]\n heapify(servers_available)\n tasks_in_progress = []\n res = []\n time = 0\n for j,task in enumerate(tasks):\n time = max(time, j)\n if not servers_available:\n time = tasks_in_progress[0][0]\n while tasks_in_progress and tasks_in_progress[0][0] <= time:\n heappush(servers_available, heappop(tasks_in_progress)[1])\n res.append(servers_available[0][1])\n heappush(tasks_in_progress, (time + task, heappop(servers_available)))\n return res\n", + "title": "1882. Process Tasks Using Servers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "-30 <= nums[i] <= 30", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]\nOutput:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 62.8%) | Memory: 54.05 MB (Top 10.0%)\n\nclass Solution {\n public int[] productExceptSelf(int[] nums) {\n int n = nums.length;\n int pre[] = new int[n];\n int suff[] = new int[n];\n pre[0] = 1;\n suff[n - 1] = 1;\n \n for(int i = 1; i < n; i++) {\n pre[i] = pre[i - 1] * nums[i - 1];\n }\n for(int i = n - 2; i >= 0; i--) {\n suff[i] = suff[i + 1] * nums[i + 1];\n }\n \n int ans[] = new int[n];\n for(int i = 0; i < n; i++) {\n ans[i] = pre[i] * suff[i];\n }\n return ans;\n }\n}", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "-30 <= nums[i] <= 30", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]\nOutput:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 477 ms (Top 13.75%) | Memory: 22.5 MB (Top 18.46%)\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n pre = [1]* (len(nums)+1)\n back = [1]*(len(nums)+1)\n\n for i in range(len(nums)):\n pre[i+1] = pre[i]*nums[i]\n\n for i in range(len(nums)-1,-1,-1):\n back[i-1] = back[i]*nums[i]\n for i in range(len(pre)-1):\n nums[i]=pre[i]*back[i]\n\n return nums", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Example:", + "description_images": [], + "constraints": [ + "ProductOfNumbers() Initializes the object with an empty stream.", + "void add(int num) Appends the integer num to the stream.", + "int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers." + ], + "examples": [ + { + "text": "Example: Input[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]Output[null,null,null,null,null,null,20,40,0,null,32]ExplanationProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32", + "image": null + } + ], + "follow_up": null, + "solution": "class ProductOfNumbers {\n List prefix;\n public ProductOfNumbers() {\n prefix = new ArrayList<>();\n prefix.add(1);\n }\n \n public void add(int num) {\n if(num==0){\n prefix.clear();\n prefix.add(1);\n }\n else prefix.add(num*prefix.get(prefix.size()-1));\n }\n public int getProduct(int k) {\n if(k>=prefix.size()) return 0;\n return prefix.get(prefix.size()-1)/prefix.get(prefix.size()-k-1);\n }\n}\n", + "title": "1352. Product of the Last K Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Example:", + "description_images": [], + "constraints": [ + "ProductOfNumbers() Initializes the object with an empty stream.", + "void add(int num) Appends the integer num to the stream.", + "int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers." + ], + "examples": [ + { + "text": "Example: Input[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]Output[null,null,null,null,null,null,20,40,0,null,32]ExplanationProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 732 ms (Top 6.90%) | Memory: 163.2 MB (Top 5.18%)\nclass ProductOfNumbers:\n def __init__(self):\n self.prods = [1]\n self.max = 0\n\n def add(self, num: int) -> None:\n if num == 0:\n num = 1\n self.max = len(self.prods)\n self.prods.append(self.prods[-1] * num)\n\n def getProduct(self, k: int) -> int:\n if k >= len(self.prods) - self.max:\n return 0\n return self.prods[-1] // self.prods[-k-1]", + "title": "1352. Product of the Last K Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a group of n members, and a list of various crimes they could commit. The i th crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n . Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "0 <= minProfit <= 100", + "1 <= group.length <= 100", + "1 <= group[i] <= 100", + "profit.length == group.length", + "0 <= profit[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, minProfit = 3, group = [2,2], profit = [2,3]\nOutput:2\nExplanation:To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\nOutput:7\nExplanation:To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def profitableSchemes(self, n, minProfit, group, profit):\n \n k = len(group)\n arr = [[[0 for _ in range(k+1)] for _ in range(minProfit+1)] for _ in range(n+1)]\n \n for i in range(n+1):\n arr[i][0][k] = 1\n \n for j in range(k-1,-1,-1):\n for i in range(n,-1,-1):\n for x in range(minProfit,-1,-1):\n\n arr[i][x][j] = arr[i][x][j+1]\n if i>=group[j]:\n arr[i][x][j] += arr[i-group[j]][max(x-profit[j],0)][j+1]\n \n return arr[n][minProfit][0] % (10**9 + 7)\n\n", + "title": "879. Profitable Schemes", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x , y , and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j) . We view the projection of these cubes onto the xy , yz , and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]\nOutput:17\nExplanation:Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png" + }, + { + "text": "Example 2: Input:grid = [[2]]\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0],[0,2]]\nOutput:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int projectionArea(int[][] grid) {\n int totalArea = 0;\n \n \n for(int[] row : grid){\n int max = row[0];\n for(int c : row){\n if(max < c){\n max = c;\n }if(c != 0){\n totalArea += 1;\n }\n \n }\n totalArea += max;\n }\n \n for(int c = 0; c < grid[0].length; c++){\n int max = grid[0][c];\n for(int row = 0; row < grid.length; row++){\n if(max < grid[row][c]){\n \n max = grid[row][c];\n }\n }\n totalArea += max;\n }\n return totalArea;\n }\n}\n", + "title": "883. Projection Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x , y , and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j) . We view the projection of these cubes onto the xy , yz , and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]\nOutput:17\nExplanation:Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png" + }, + { + "text": "Example 2: Input:grid = [[2]]\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0],[0,2]]\nOutput:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n total = 0\n\t\t\n # top\n total += sum([1 for i in grid for j in i if j > 0])\n \n\t\t# front\n total += sum([max(col) for col in zip(*grid)])\n \n\t\t# side\n total += sum([max(row) for row in grid])\n \n\t\treturn total\n", + "title": "883. Projection Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png", + "https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^5 ] .", + "1 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,3,1,3,1,null,1]\nOutput:2\nExplanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 2: Input:root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput:1\nExplanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 3: Input:root = [9]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int pseudoPalindromicPaths (TreeNode root) {\n return helper(root, 0);\n }\n \n public int helper(TreeNode node, int freq) {\n if (node == null) return 0;\n \n freq = freq ^ (1 << node.val);\n if (node.left == null && node.right == null) {\n return (freq & (freq - 1)) == 0 ? 1 : 0;\n // return Integer.bitCount(freq) <= 1 ? 1 : 0;\n }\n return helper(node.left, freq) + helper(node.right, freq);\n }\n}\n", + "title": "1457. Pseudo-Palindromic Paths in a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png", + "https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^5 ] .", + "1 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,3,1,3,1,null,1]\nOutput:2\nExplanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 2: Input:root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput:1\nExplanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 3: Input:root = [9]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def dfs(self, node, path):\n if not node:\n return\n \n if not node.left and not node.right:\n path += [node.val]\n d = {}\n for i in path.copy():\n if i in d:\n del d[i]\n else:\n d[i] = 1\n #print(d.items())\n self.ans += 1 if len(d) <= 1 else 0\n return\n \n self.dfs(node.left, path+[node.val])\n self.dfs(node.right, path+[node.val])\n \n def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:\n self.ans = 0\n self.dfs(root, [])\n return self.ans", + "title": "1457. Pseudo-Palindromic Paths in a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: Return a string representing the final state .", + "description_images": [], + "constraints": [ + "dominoes[i] = 'L' , if the i th domino has been pushed to the left,", + "dominoes[i] = 'R' , if the i th domino has been pushed to the right, and", + "dominoes[i] = '.' , if the i th domino has not been pushed." + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = \"RR.L\"\nOutput:\"RR.L\"\nExplanation:The first domino expends no additional force on the second domino.", + "image": null + }, + { + "text": "Example 2: Input:dominoes = \".L.R...LR..L..\"\nOutput:\"LL.RR.LLRRLL..\"", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/05/18/domino.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 100.00%) | Memory: 43.4 MB (Top 96.04%)\n// Time complexity: O(N)\n// Space complexity: O(N), where N is the length of input string\nclass Solution {\n public String pushDominoes(String dominoes) {\n // ask whether dominoes could be null\n final int N = dominoes.length();\n if (N <= 1) return dominoes;\n char[] res = dominoes.toCharArray();\n int i = 0;\n while (i < N) {\n if (res[i] == '.') {\n i++;\n } else if (res[i] == 'L') { // push left\n int j = i-1;\n while (j >= 0 && res[j] == '.') {\n res[j--] = 'L';\n }\n i++;\n } else { // res[i] == 'R'\n int j = i+1;\n while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side\n j++;\n }\n if (j < N && res[j] == 'L') { // if found 'L', push left and right\n for (int l = i+1, r = j-1; l < r; l++, r--) {\n res[l] = 'R';\n res[r] = 'L';\n }\n i = j + 1;\n } else { // if no 'L', push right\n while (i < j) {\n res[i++] = 'R';\n }\n }\n }\n }\n return String.valueOf(res);\n }\n}", + "title": "838. Push Dominoes", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: Return a string representing the final state .", + "description_images": [], + "constraints": [ + "dominoes[i] = 'L' , if the i th domino has been pushed to the left,", + "dominoes[i] = 'R' , if the i th domino has been pushed to the right, and", + "dominoes[i] = '.' , if the i th domino has not been pushed." + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = \"RR.L\"\nOutput:\"RR.L\"\nExplanation:The first domino expends no additional force on the second domino.", + "image": null + }, + { + "text": "Example 2: Input:dominoes = \".L.R...LR..L..\"\nOutput:\"LL.RR.LLRRLL..\"", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/05/18/domino.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def pushDominoes(self, dom: str) -> str:\n from collections import deque\n n = len(dom)\n d = set()\n q = deque()\n arr = [0 for i in range(n)]\n for i in range(n):\n if dom[i] == \"L\":\n arr[i] = -1\n d.add(i)\n q.append((i,\"L\"))\n if dom[i] == \"R\":\n arr[i] = 1\n d.add(i)\n q.append((i,\"R\"))\n while q:\n t1 = set()\n for _ in range(len(q)):\n t = q.popleft()\n if t[1] == \"L\":\n if t[0]-1 >= 0 and t[0]-1 not in d:\n t1.add(t[0]-1)\n arr[t[0]-1] -= 1\n else:\n if t[0]+1 < n and t[0]+1 not in d:\n t1.add(t[0]+1)\n arr[t[0]+1] += 1\n for val in t1:\n d.add(val)\n if arr[val] > 0:\n q.append((val,\"R\"))\n elif arr[val]<0:\n q.append((val,\"L\"))\n ans = \"\"\n for val in arr:\n if val<0:\n ans += \"L\"\n elif val>0:\n ans += \"R\"\n else:\n ans += \".\"\n return ans\n", + "title": "838. Push Dominoes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks . The patterns are given as a list of three-letter strings allowed , where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom , given as a single string, that you must use as the base of the pyramid. Given bottom and allowed , return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed , or false otherwise .", + "description_images": [], + "constraints": [ + "For example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput:true\nExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid1-grid.jpg" + }, + { + "text": "Example 2: Input:bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput:false\nExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap> map = new HashMap<>();\n HashMap dp = new HashMap<>();\n \n public boolean pyramidTransition(String bottom, List allowed) {\n for(String s:allowed){\n String sub = s.substring(0,2);\n \n char c = s.charAt(2);\n \n if(!map.containsKey(sub))\n map.put(sub, new ArrayList<>());\n \n map.get(sub).add(c);\n }\n \n return dfs(bottom, \"\", 0);\n }\n \n boolean dfs(String currBottom, String newBottom, int index){\n \n if(currBottom.length()==1)\n return true;\n if(index+1>=currBottom.length())\n return false;\n \n String sub = currBottom.substring(index,index+2);\n \n String state = currBottom+\" \"+newBottom+\" \"+index;\n \n if(dp.containsKey(state))\n return dp.get(state);\n \n if(map.containsKey(sub)){\n List letters = map.get(sub);\n \n for(char c:letters){\n if(index==currBottom.length()-2){\n if(dfs(newBottom+c, \"\", 0))\n {\n dp.put(state, true);\n return true;\n }\n }\n else if(dfs(currBottom, newBottom+c, index+1))\n {\n dp.put(state, true);\n return true;\n }\n }\n }\n \n dp.put(state, false);\n return false;\n }\n}\n", + "title": "756. Pyramid Transition Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks . The patterns are given as a list of three-letter strings allowed , where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom , given as a single string, that you must use as the base of the pyramid. Given bottom and allowed , return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed , or false otherwise .", + "description_images": [], + "constraints": [ + "For example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput:true\nExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid1-grid.jpg" + }, + { + "text": "Example 2: Input:bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput:false\nExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool \n \"\"\"\n dic = defaultdict(list)\n for i in allowed:\n dic[(i[0], i[1])].append(i[2])\n \n res = []\n \n def dfs(arr, nxt):\n #base case second floor and check top exists\n if len(arr) == 2 and dic[(arr[0], arr[1])]:\n return True\n \n #go to the next row now\n if len(arr) == len(nxt) + 1:\n return dfs(nxt, [])\n\n #keep iterating the same row\n if dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n for val in dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n if dfs(arr, nxt + [val]):\n return True\n return False\n \n return dfs(bottom, [])\n", + "title": "756. Pyramid Transition Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-2.jpg" + ], + "constraints": [ + "1 <= queens.length <= 63", + "queens[i].length == 2", + "0 <= queens[i][j] < 8", + "king.length == 2", + "0 <= king[0], king[1] < 8", + "At most one piece is allowed in a cell." + ], + "examples": [ + { + "text": "Example 1: Input:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput:[[0,1],[1,0],[3,3]]\nExplanation:The queen at [0,1] can attack the king cause they're in the same row. \nThe queen at [1,0] can attack the king cause they're in the same column. \nThe queen at [3,3] can attack the king cause they're in the same diagnal. \nThe queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. \nThe queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. \nThe queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.", + "image": null + }, + { + "text": "Example 2: Input:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput:[[2,2],[3,4],[4,4]]", + "image": null + }, + { + "text": "Example 3: Input:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]\nOutput:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 56.88%) | Memory: 44 MB (Top 9.63%)\nclass Solution {\n public List> queensAttacktheKing(int[][] queens, int[] king) {\n List> res = new ArrayList<>();\n int r=king[0];\n int l=king[1];\n int [][]board =new int[8][8];\n int n=8;\n\n// 8 cases;\n// moving upward\n// moving downward\n// moving right\n// moving left\n// moving upper right diagonal\n// moving upper left diagonal'\n// moving lower left diagonal\n// moving lower right diagonal\n\n int i,j;\n for(i=0;i(Arrays.asList(r, j)));\n break;\n }\n }\n for(i=r;i(Arrays.asList(i, l)));\n break;\n }\n }\n for(i=r;i>=0;i--)\n {\n if(board[i][l]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, l)));\n break;\n\n }\n }\n for(j=l;j>=0;j--)\n {\n if(board[r][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(r, j)));\n break;\n\n }\n }\n for(i=r,j=l;i>=0 && j>=0;j--,i--)\n {\n if(board[i][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;j=0;j++,i--)\n {\n if(board[i][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;i(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;j>=0 && i(Arrays.asList(i, j)));\n break;\n }\n }\n return res;\n }\n}", + "title": "1222. Queens That Can Attack the King", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-2.jpg" + ], + "constraints": [ + "1 <= queens.length <= 63", + "queens[i].length == 2", + "0 <= queens[i][j] < 8", + "king.length == 2", + "0 <= king[0], king[1] < 8", + "At most one piece is allowed in a cell." + ], + "examples": [ + { + "text": "Example 1: Input:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput:[[0,1],[1,0],[3,3]]\nExplanation:The queen at [0,1] can attack the king cause they're in the same row. \nThe queen at [1,0] can attack the king cause they're in the same column. \nThe queen at [3,3] can attack the king cause they're in the same diagnal. \nThe queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. \nThe queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. \nThe queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.", + "image": null + }, + { + "text": "Example 2: Input:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput:[[2,2],[3,4],[4,4]]", + "image": null + }, + { + "text": "Example 3: Input:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]\nOutput:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = []\n d = {(i[0],i[1]) : True for i in queens}\n def goUp(r,c):\n while r >=0:\n if (r,c) in d:\n ans.append([r,c])\n break\n r -= 1\n def goDown(r,c):\n while r < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n def goLeft(r,c):\n while c >= 0:\n if (r,c) in d:\n ans.append([r,c])\n break\n c -= 1\n def goRight(r,c):\n while c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n c += 1\n def goD1(r,c):\n while r >=0 and c >= 0:\n if (r,c) in d:\n ans.append([r,c])\n break\n r -= 1\n c -= 1\n def goD2(r,c):\n while r < 8 and c >= 0:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n c -= 1\n def goD3(r,c):\n while r < 8 and c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n c += 1\n def goD4(r,c):\n while r >= 0 and c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r -= 1\n c += 1\n\n goUp(king[0],king[1])\n goDown(king[0],king[1])\n goLeft(king[0],king[1])\n goRight(king[0],king[1])\n goD1(king[0],king[1])\n goD2(king[0],king[1])\n goD3(king[0],king[1])\n goD4(king[0],king[1])\n\n return ans\n", + "title": "1222. Queens That Can Attack the King", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array queries of positive integers between 1 and m , you have to process all queries[i] (from i=0 to i=queries.length-1 ) according to the following rules: Return an array containing the result for the given queries .", + "description_images": [], + "constraints": [ + "In the beginning, you have the permutation P=[1,2,3,...,m] .", + "For the current i , find the position of queries[i] in the permutation P ( indexing from 0 ) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [3,1,2,1], m = 5\nOutput:[2,1,2,1]\nExplanation:The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].", + "image": null + }, + { + "text": "Example 2: Input:queries = [4,1,2,2], m = 4\nOutput:[3,1,2,0]", + "image": null + }, + { + "text": "Example 3: Input:queries = [7,5,5,8,3], m = 8\nOutput:[6,5,0,7,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 39.19%) | Memory: 43.3 MB (Top 49.82%)\nclass Solution {\n public int[] processQueries(int[] queries, int m) {\n int[] results = new int[queries.length];\n ArrayList permutations = new ArrayList();\n\n // Filling the permuations array with numbers.\n for (int i = 0; i < m; i++)\n permutations.add(i+1);\n\n // Looping on the queries & checking their index in the permuations\n for (int i = 0; i < queries.length; i++) {\n int query = queries[i];\n for (int j = 0; j < permutations.size(); j++)\n if (permutations.get(j) == query) {\n results[i] = j;\n int temp = permutations.get(j);\n permutations.remove(j);\n permutations.add(0, temp);\n break;\n }\n }\n\n return results;\n\n }\n}", + "title": "1409. Queries on a Permutation With Key", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array queries of positive integers between 1 and m , you have to process all queries[i] (from i=0 to i=queries.length-1 ) according to the following rules: Return an array containing the result for the given queries .", + "description_images": [], + "constraints": [ + "In the beginning, you have the permutation P=[1,2,3,...,m] .", + "For the current i , find the position of queries[i] in the permutation P ( indexing from 0 ) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [3,1,2,1], m = 5\nOutput:[2,1,2,1]\nExplanation:The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].", + "image": null + }, + { + "text": "Example 2: Input:queries = [4,1,2,2], m = 4\nOutput:[3,1,2,0]", + "image": null + }, + { + "text": "Example 3: Input:queries = [7,5,5,8,3], m = 8\nOutput:[6,5,0,7,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n perm=[i for i in range(1,m+1)]\n res=[]\n for i in queries:\n ind=perm.index(i)\n res.append(ind)\n perm=[perm.pop(ind)]+perm\n return res\n", + "title": "1409. Queries on a Permutation With Key", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array points where points[i] = [x i , y i ] is the coordinates of the i th point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [x j , y j , r j ] describes a circle centered at (x j , y j ) with a radius of r j . For each query queries[j] , compute the number of points inside the j th circle. Points on the border of the circle are considered inside . Return an array answer , where answer[j] is the answer to the j th query .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 500", + "points[i].length == 2", + "0 <= x ​​​​​​i , y ​​​​​​i <= 500", + "1 <= queries.length <= 500", + "queries[j].length == 3", + "0 <= x j , y j <= 500", + "1 <= r j <= 500", + "All coordinates are integers." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\nOutput:[3,2,2]\nExplanation:The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-34-16.png" + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\nOutput:[2,3,2,4]\nExplanation:The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-42-07.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 100.00%) | Memory: 42.8 MB (Top 96.08%)\n\nclass Solution {\n public int[] countPoints(int[][] points, int[][] queries) {\n int len = queries.length;\n int[] ans = new int[len];\n\n for(int i=0;i List[int]:\n\t\tcircle = []\n\t\tfor x2, y2, radius in queries:\n\t\t\tcount = 0\n\t\t\tfor x1, y1 in points:\n\t\t\t\tdis = ((x2-x1)**2+(y2-y1)**2)**0.5 # Use the Distance Formula...\n\t\t\t\tif dis <= radius:\n\t\t\t\t\tcount += 1\n\t\t\tcircle.append(count)\n\t\treturn circle", + "title": "1828. Queries on Number of Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array of strings nums , where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [k i , trim i ] . For each queries[i] , you need to: Return an array answer of the same length as queries , where answer[i] is the answer to the i th query. Note :", + "description_images": [], + "constraints": [ + "Trim each number in nums to its rightmost trim i digits.", + "Determine the index of the k i th smallest trimmed number in nums . If two trimmed numbers are equal, the number with the lower index is considered to be smaller.", + "Reset each number in nums to its original length." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]\nOutput:[2,2,1,0]\nExplanation:1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2ndsmallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4thsmallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n Note that the trimmed number \"02\" is evaluated as 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]\nOutput:[3,0]\nExplanation:1. Trimmed to the last digit, nums = [\"4\",\"7\",\"6\",\"4\"]. The 2ndsmallest number is 4 at index 3.\n There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2ndsmallest number is 24.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 526 ms (Top 46.46%) | Memory: 54.8 MB (Top 85.59%)\nclass Solution {\n public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {\n\n if (nums.length == 0)\n return new int[0];\n\n int[] result = new int[queries.length];\n int strLen = nums[0].length();\n int[] index = new int[1];\n\n PriorityQueue queue = new PriorityQueue<>((a, b) -> {\n for (int i = index[0]; i < strLen; i++) {\n if (nums[a].charAt(i) != nums[b].charAt(i))\n return nums[b].charAt(i) - nums[a].charAt(i);\n }\n\n return b - a;\n });\n\n for (int i = 0; i < queries.length; i++) {\n index[0] = strLen - queries[i][1];\n queue.clear();\n\n for (int j = 0; j < nums.length; j++) {\n queue.add(j);\n if (queue.size() > queries[i][0])\n queue.poll();\n }\n\n result[i] = queue.poll();\n }\n\n return result;\n }\n}", + "title": "2343. Query Kth Smallest Trimmed Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of strings nums , where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [k i , trim i ] . For each queries[i] , you need to: Return an array answer of the same length as queries , where answer[i] is the answer to the i th query. Note :", + "description_images": [], + "constraints": [ + "Trim each number in nums to its rightmost trim i digits.", + "Determine the index of the k i th smallest trimmed number in nums . If two trimmed numbers are equal, the number with the lower index is considered to be smaller.", + "Reset each number in nums to its original length." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]\nOutput:[2,2,1,0]\nExplanation:1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2ndsmallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4thsmallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n Note that the trimmed number \"02\" is evaluated as 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]\nOutput:[3,0]\nExplanation:1. Trimmed to the last digit, nums = [\"4\",\"7\",\"6\",\"4\"]. The 2ndsmallest number is 4 at index 3.\n There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2ndsmallest number is 24.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1276 ms (Top 58.39%) | Memory: 15.2 MB (Top 22.81%)\nfrom collections import defaultdict\n\nclass Solution:\n def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:\n sl = len(nums[0])\n len_to_sorted = defaultdict(list)\n ans = [0] * len(queries)\n\n for i, (k_smallest, trim_len) in enumerate(queries):\n if trim_len not in len_to_sorted:\n # have to trim\n for ni, num in enumerate(nums):\n len_to_sorted[trim_len].append( (int(num[sl - trim_len:]), ni) )\n\n len_to_sorted[trim_len] = sorted(len_to_sorted[trim_len])\n ans[i] = len_to_sorted[trim_len][k_smallest -1][1]\n\n return ans", + "title": "2343. Query Kth Smallest Trimmed Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of people, people , which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h i , k i ] represents the i th person of height h i with exactly k i other people in front who have a height greater than or equal to h i . Reconstruct and return the queue that is represented by the input array people . The returned queue should be formatted as an array queue , where queue[j] = [h j , k j ] is the attributes of the j th person in the queue ( queue[0] is the person at the front of the queue).", + "description_images": [], + "constraints": [ + "1 <= people.length <= 2000", + "0 <= h i <= 10^6", + "0 <= k i < people.length", + "It is guaranteed that the queue can be reconstructed." + ], + "examples": [ + { + "text": "Example 1: Input:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.", + "image": null + }, + { + "text": "Example 2: Input:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 81.09%) | Memory: 53.8 MB (Top 84.02%)\nclass Solution {\n public int[][] reconstructQueue(int[][] people) {\n List result = new ArrayList<>(); //return value\n\n Arrays.sort(people, (a, b) -> {\n int x = Integer.compare(b[0], a[0]);\n if(x == 0) return Integer.compare(a[1], b[1]);\n else return x; });\n\n for(int[] p: people)\n result.add(p[1], p);\n\n return result.toArray(new int[people.length][2]);\n }\n}", + "title": "406. Queue Reconstruction by Height", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of people, people , which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h i , k i ] represents the i th person of height h i with exactly k i other people in front who have a height greater than or equal to h i . Reconstruct and return the queue that is represented by the input array people . The returned queue should be formatted as an array queue , where queue[j] = [h j , k j ] is the attributes of the j th person in the queue ( queue[0] is the person at the front of the queue).", + "description_images": [], + "constraints": [ + "1 <= people.length <= 2000", + "0 <= h i <= 10^6", + "0 <= k i < people.length", + "It is guaranteed that the queue can be reconstructed." + ], + "examples": [ + { + "text": "Example 1: Input:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.", + "image": null + }, + { + "text": "Example 2: Input:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n\t\tn = len(people)\n\t\tpeople.sort()\n\t\tans = [[]]*n\n\t\ti = 0\n\t\twhile people:\n\t\t\th,p = people.pop(0)\n\t\t\tcount= p\n\t\t\tfor i in range(n):\n\t\t\t\tif count== 0 and ans[i] == []:\n\t\t\t\t\tans[i] = [h,p]\n\t\t\t\t\tbreak\n\n\t\t\t\telif not ans[i] or (ans[i] and ans[i][0] >= h ):\n\t\t\t\t\tcount -= 1\n\t\treturn ans", + "title": "406. Queue Reconstruction by Height", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the i th rabbit. Given the array answers , return the minimum number of rabbits that could be in the forest .", + "description_images": [], + "constraints": [ + "1 <= answers.length <= 1000", + "0 <= answers[i] < 1000" + ], + "examples": [ + { + "text": "Example 1: Input:answers = [1,1,2]\nOutput:5\nExplanation:The two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.", + "image": null + }, + { + "text": "Example 2: Input:answers = [10,10,10]\nOutput:11", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numRabbits(int[] answers) {\n HashMap map = new HashMap<>();\n int count = 0;\n \n for(int ele : answers) {\n \n if(!map.containsKey(ele+1)) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else if(map.get(ele+1) == ele+1) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else {\n int freq = map.get(ele+1);\n map.put(ele+1, freq+1);\n }\n }\n \n return count;\n }\n}\n", + "title": "781. Rabbits in Forest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the i th rabbit. Given the array answers , return the minimum number of rabbits that could be in the forest .", + "description_images": [], + "constraints": [ + "1 <= answers.length <= 1000", + "0 <= answers[i] < 1000" + ], + "examples": [ + { + "text": "Example 1: Input:answers = [1,1,2]\nOutput:5\nExplanation:The two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.", + "image": null + }, + { + "text": "Example 2: Input:answers = [10,10,10]\nOutput:11", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 35.1%) | Memory: 16.38 MB (Top 76.8%)\n\nclass Solution:\n def numRabbits(self, answers: List[int]) -> int:\n counts = {}\n count = 0\n\n for answer in answers:\n if answer == 0:\n # This must be the only rabbit of its color.\n count += 1\n elif answer not in counts or counts[answer] == 0:\n # This is the first time the color appears.\n counts[answer] = 1\n # Add all rabbits having this new color.\n count += answer + 1\n else:\n # Add one to how many times answer occurred.\n counts[answer] += 1\n if counts[answer] > answer:\n # If n+1 rabbits have said n,\n # this color group is complete.\n counts[answer] = 0\n \n return count", + "title": "781. Rabbits in Forest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): For example, after commands \"AAR\" , your car goes to positions 0 --> 1 --> 3 --> 3 , and your speed goes to 1 --> 2 --> 4 --> -1 . Given a target position target , return the length of the shortest sequence of instructions to get there .", + "description_images": [], + "constraints": [ + "When you get an instruction 'A' , your car does the following: position += speed speed *= 2", + "position += speed", + "speed *= 2", + "When you get an instruction 'R' , your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same.", + "If your speed is positive then speed = -1", + "otherwise speed = 1" + ], + "examples": [ + { + "text": "Example 1: Input:target = 3\nOutput:2\nExplanation:The shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 6\nOutput:5\nExplanation:The shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 86.11%) | Memory: 41.5 MB (Top 82.95%)\nclass Solution {\n public int racecar(int target) {\n Queue queue = new LinkedList<>();\n queue.add(new int[]{0, 1, 0});\n Set visited = new HashSet<>();\n\n while(!queue.isEmpty()){\n int[] item = queue.poll();\n int currPos = item[0];\n int currSpeed = item[1];\n int distance = item[2];\n\n if(currPos == target)\n return distance;\n\n // Choosing A\n int nextPos = currPos + currSpeed;\n int nextSpeed = currSpeed * 2;\n String posSpeed = new StringBuilder().append(nextPos).append(\",\").append(nextSpeed).toString();\n\n // If the particular state (position & speed) is not encountered earlier then we explore that state\n // And we also check if the nextPos is not beyond twice the size of target, then there is no point in exploring that route\n if(!visited.contains(posSpeed) && Math.abs(nextPos) < 2 * target){\n visited.add(posSpeed);\n queue.add(new int[]{nextPos, nextSpeed, distance + 1});\n }\n\n // Choosing R\n // We go in reverse only when we are moving away from the target in the positive or in the negative direction\n if((currPos + currSpeed > target && currSpeed > 0) || (currPos + currSpeed < target && currSpeed < 0)) {\n nextSpeed = currSpeed > 0 ? -1 : 1;\n posSpeed = new StringBuilder().append(currPos).append(\",\").append(nextSpeed).toString();\n\n if(!visited.contains(posSpeed) && Math.abs(currPos) < 2 * target){\n visited.add(posSpeed);\n queue.add(new int[]{currPos, nextSpeed, distance + 1});\n }\n }\n }\n return -1;\n }\n}", + "title": "818. Race Car", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): For example, after commands \"AAR\" , your car goes to positions 0 --> 1 --> 3 --> 3 , and your speed goes to 1 --> 2 --> 4 --> -1 . Given a target position target , return the length of the shortest sequence of instructions to get there .", + "description_images": [], + "constraints": [ + "When you get an instruction 'A' , your car does the following: position += speed speed *= 2", + "position += speed", + "speed *= 2", + "When you get an instruction 'R' , your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same.", + "If your speed is positive then speed = -1", + "otherwise speed = 1" + ], + "examples": [ + { + "text": "Example 1: Input:target = 3\nOutput:2\nExplanation:The shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 6\nOutput:5\nExplanation:The shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 46.38%) | Memory: 14.3 MB (Top 75.93%)\nclass Solution:\n def racecar(self, target: int) -> int:\n q = [(0, 1)]\n steps = 0\n\n while q:\n num = len(q)\n for i in range(num):\n pos, speed = q.pop(0)\n if pos == target:\n return steps\n q.append((pos+speed, speed*2))\n rev_speed = -1 if speed > 0 else 1\n if (pos+speed) < target and speed < 0 or (pos+speed) > target and speed > 0:\n q.append((pos, rev_speed))\n steps += 1", + "title": "818. Race Car", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1 . All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int m, int n) Initializes the object with the size of the binary matrix m and n .", + "int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1 .", + "void reset() Resets all the values of the matrix to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n[[3, 1], [], [], [], [], []]Output[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]ExplanationSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 62.26%) | Memory: 50.7 MB (Top 63.21%)\n// Swap Tail Element Solution\n// 1. Get a random number between [0, size-1]\n// 2. size - 1\n// 3. Get the index in map by the random map\n// 4. Update the flipped element with the tail element.\n// Time complexity: O(1) to init, flip, and reset\n// Space complexity: O(K), where K is the times of flip calls.\nclass Solution {\n private final int M, N, CAPACITY;\n private int size;\n private Random random;\n private Map map;\n\n public Solution(int m, int n) {\n M = m;\n N = n;\n CAPACITY = m * n;\n size = CAPACITY;\n random = new Random();\n map = new HashMap<>();\n }\n\n public int[] flip() {\n if (size <= 0) return new int[]{-1, -1}; // or throw exception.\n Integer rand = random.nextInt(size);\n size--;\n int idx = map.getOrDefault(rand, rand);\n Integer tail = map.getOrDefault(size, size);\n map.put(rand, tail);\n return new int[]{idx / N, idx % N};\n }\n\n public void reset() {\n map = new HashMap();\n size = CAPACITY;\n }\n}\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(m, n);\n * int[] param_1 = obj.flip();\n * obj.reset();\n */", + "title": "519. Random Flip Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1 . All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int m, int n) Initializes the object with the size of the binary matrix m and n .", + "int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1 .", + "void reset() Resets all the values of the matrix to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n[[3, 1], [], [], [], [], []]Output[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]ExplanationSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "from random import randint\n\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m = m\n self.n = n\n self.ones = set()\n\n def flip(self) -> List[int]:\n i, j = randint(0, self.m - 1), randint(0, self.n - 1)\n while (i, j) in self.ones:\n i, j = randint(0, self.m - 1), randint(0, self.n - 1)\n self.ones.add((i, j))\n return [i, j]\n\n def reset(self) -> None:\n self.ones.clear()\n", + "title": "519. Random Flip Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums with possible duplicates , randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the array nums .", + "int pick(int target) Picks a random index i from nums where nums[i] == target . If there are multiple valid i's, then each index should have an equal probability of returning." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]Output[null, 4, 0, 2]ExplanationSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 42.59%) | Memory: 55.80 MB (Top 31.28%)\n\nclass Solution {\n Random random;\n int[] origin;\n \n public Solution(int[] nums) {\n random = new Random();\n origin = nums;\n }\n \n public int pick(int target) {\n \n while(true){\n int idx = random.nextInt(origin.length);\n if(origin[idx] == target){\n return idx;\n }\n }\n }\n}\n", + "title": "398. Random Pick Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums with possible duplicates , randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the array nums .", + "int pick(int target) Picks a random index i from nums where nums[i] == target . If there are multiple valid i's, then each index should have an equal probability of returning." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]Output[null, 4, 0, 2]ExplanationSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def __init__(self, nums: List[int]):\n #self.nums = nums\n #create a hash of values with their list of indices\n self.map = defaultdict(list)\n for i,v in enumerate(nums):\n self.map[v].append(i)\n \n\n def pick(self, target: int) -> int:\n return random.sample(self.map[target],1)[0]\n '''\n reservoir = 0\n count = 0\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n count+=1\n if random.random() < 1/count:\n reservoir = i\n return reservoir\n\n \n samp = []\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n samp.append(i)\n return (random.sample(samp,1))[0]\n '''\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(nums)\n# param_1 = obj.pick(target)", + "title": "398. Random Pick Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n and an array of unique integers blacklist . Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist . Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist .", + "int pick() Returns a random integer in the range [0, n - 1] and not in blacklist ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]Output[null, 0, 4, 1, 6, 1, 0, 4]ExplanationSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 841 ms (Top 10.38%) | Memory: 24.8 MB (Top 56.73%)\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n self.hashmap={}\n for b in blacklist:\n self.hashmap[b]=-1\n self.length=n-len(blacklist)\n flag=n-1\n for b in blacklist:\n if b int:\n seed=random.randrange(self.length)\n return self.hashmap.get(seed,seed)\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(n, blacklist)\n# param_1 = obj.pick()", + "title": "710. Random Pick with Blacklist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the i th index. You need to implement the function pickIndex() , which randomly picks an index in the range [0, w.length - 1] ( inclusive ) and returns it. The probability of picking an index i is w[i] / sum(w) .", + "description_images": [], + "constraints": [ + "For example, if w = [1, 3] , the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25% ), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75% )." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\",\"pickIndex\"]\n[[[1]],[]]Output[null,0]ExplanationSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.", + "image": null + }, + { + "text": "Example 2: Input[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]Output[null,1,1,1,1,0]ExplanationSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 42.43%) | Memory: 56.3 MB (Top 78.21%)\nclass Solution {\n\n private int[] prefixSum;\n private Random random;\n\n public Solution(int[] w) {\n for (int i = 1; i < w.length; i++)\n w[i] += w[i - 1];\n prefixSum = w;\n random = new Random();\n }\n\n public int pickIndex() {\n int num = 1 + random.nextInt(prefixSum[prefixSum.length - 1]); // Generate random number between 1 and total sum of weights\n int left = 0;\n int right = prefixSum.length - 1;\n\n while (left < right) {\n int mid = (left + right) / 2;\n if (num == prefixSum[mid])\n return mid;\n else if (num < prefixSum[mid])\n right = mid;\n else\n left = mid + 1;\n }\n return left;\n }\n}", + "title": "528. Random Pick with Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the i th index. You need to implement the function pickIndex() , which randomly picks an index in the range [0, w.length - 1] ( inclusive ) and returns it. The probability of picking an index i is w[i] / sum(w) .", + "description_images": [], + "constraints": [ + "For example, if w = [1, 3] , the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25% ), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75% )." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\",\"pickIndex\"]\n[[[1]],[]]Output[null,0]ExplanationSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.", + "image": null + }, + { + "text": "Example 2: Input[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]Output[null,1,1,1,1,0]ExplanationSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n\tdef __init__(self, w):\n\t\t\"\"\"\n\t\t:type w: List[int]\n\t\t\"\"\"\n\t\t#Cumulative sum\n\t\tself.list = [0] * len(w)\n\n\t\ts = 0\n\t\tfor i, n in enumerate(w):\n\t\t\ts += n\n\t\t\tself.list[i] = s\n\n\n\tdef pickIndex(self):\n\t\t\"\"\"\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n", + "title": "528. Random Pick with Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [a i , b i , x i , y i ] indicates that (a i , b i ) is the bottom-left corner point of the i th rectangle and (x i , y i ) is the top-right corner point of the i th rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int[][] rects) Initializes the object with the given rectangles rects .", + "int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]Output[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]ExplanationSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n int[][] rects;\n TreeMap weightedRectIndex = new TreeMap<>();\n int nPoints = 0;\n \n Random rng = new Random();\n\n public Solution(int[][] rects) {\n this.rects = rects;\n int index = 0;\n for (int[] rect : rects) {\n\t\t // inserts cumulative weight key pointing to rectangle index\n weightedRectIndex.put(nPoints, index++);\n nPoints += width(rect) * height(rect);\n }\n }\n \n public int[] pick() {\n\t // generates random point within total weight\n int point = rng.nextInt(nPoints);\n\t\t// finds appropriate rectangle\n var entry = weightedRectIndex.floorEntry(point);\n\t\t// find point within the current rectangle\n int rectPoint = point - entry.getKey();\n int[] rect = rects[entry.getValue()];\n return new int[]{\n rect[0] + rectPoint % width(rect), \n rect[1] + rectPoint / width(rect)};\n }\n \n private int width(int[] rect) {\n return rect[2] - rect[0] + 1;\n }\n \n private int height(int[] rect) {\n return rect[3] - rect[1] + 1;\n }\n}\n", + "title": "497. Random Point in Non-overlapping Rectangles", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [a i , b i , x i , y i ] indicates that (a i , b i ) is the bottom-left corner point of the i th rectangle and (x i , y i ) is the top-right corner point of the i th rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int[][] rects) Initializes the object with the given rectangles rects .", + "int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]Output[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]ExplanationSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n 1 <= rects.length <= 100\n rects[i].length == 4\n -10^9 <= ai < xi <= 10^9\n -10^9 <= bi < yi <= 10^9\n xi - ai <= 2000\n yi - bi <= 2000\n All the rectangles do not overlap.\n At most 10^4 calls will be made to pick.\n \"\"\"\n\n def __init__(self, rects: List[List[int]]):\n self.rects = rects\n self.n_range = list(range(len(self.rects)))\n self.weights = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]\n\n def pick(self) -> List[int]:\n rect = self.rects[choices(self.n_range, self.weights, k=1)[0]]\n return [randint(rect[0], rect[2]), randint(rect[1], rect[3])]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(rects)\n# param_1 = obj.pick()\n", + "title": "497. Random Point in Non-overlapping Rectangles", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n matrix M initialized with all 0 's and an array of operations ops , where ops[i] = [a i , b i ] means M[x][y] should be incremented by one for all 0 <= x < a i and 0 <= y < b i . Count and return the number of maximum integers in the matrix after performing all the operations .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 4 * 10^4", + "0 <= ops.length <= 10^4", + "ops[i].length == 2", + "1 <= a i <= m", + "1 <= b i <= n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, ops = [[2,2],[3,3]]\nOutput:4\nExplanation:The maximum integer in M is 2, and there are four of it in M. So return 4.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg" + }, + { + "text": "Example 2: Input:m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:m = 3, n = 3, ops = []\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 12.57%) | Memory: 45.3 MB (Top 7.43%)\nclass Solution {\n public int maxCount(int m, int n, int[][] ops) {\n int minRow=m,minCol=n;\n for(int[] op:ops){\n minRow=Math.min(minRow,op[0]);\n minCol=Math.min(minCol,op[1]);\n }\n return minRow*minCol;\n }\n}", + "title": "598. Range Addition II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n matrix M initialized with all 0 's and an array of operations ops , where ops[i] = [a i , b i ] means M[x][y] should be incremented by one for all 0 <= x < a i and 0 <= y < b i . Count and return the number of maximum integers in the matrix after performing all the operations .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 4 * 10^4", + "0 <= ops.length <= 10^4", + "ops[i].length == 2", + "1 <= a i <= m", + "1 <= b i <= n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, ops = [[2,2],[3,3]]\nOutput:4\nExplanation:The maximum integer in M is 2, and there are four of it in M. So return 4.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg" + }, + { + "text": "Example 2: Input:m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:m = 3, n = 3, ops = []\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n if not ops:\n return m*n\n else:\n x,y = zip(*ops)\n return min(x) * min(y)\n", + "title": "598. Range Addition II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ).", + "description_images": [], + "constraints": [ + "RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr .", + "int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]Output[null, 1, 2]ExplanationRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.", + "image": null + } + ], + "follow_up": null, + "solution": "class RangeFreqQuery {\n //Use map's key to store arr's value, map's value to keep \n HashMap> map;\n public RangeFreqQuery(int[] arr) {\n //O(nlog(n))\n map = new HashMap<>();\n for(int i = 0; i < arr.length; i++){\n map.putIfAbsent(arr[i], new TreeMap<>());\n TreeMap tree = map.get(arr[i]);\n //i = value's location\n //tree.size() = cummulative arr's value count - 1\n tree.put(i, tree.size());\n }\n }\n \n public int query(int left, int right, int value) {\n //O(log(n))\n \n //check if value exist in map\n if(!map.containsKey(value)){\n return 0;\n }\n TreeMap tree = map.get(value);\n \n //check if there exist position >= left and position <= right\n //if not, return 0\n if(tree.ceilingKey(left) == null || tree.floorKey(right) == null){\n return 0;\n }\n //get leftMost position's cummulative count\n int leftMost = tree.get(tree.ceilingKey(left));\n //get rightMost position's cummulative count\n int rightMost = tree.get(tree.floorKey(right));\n \n return rightMost - leftMost + 1;\n }\n}\n\n/**\n * Your RangeFreqQuery object will be instantiated and called as such:\n * RangeFreqQuery obj = new RangeFreqQuery(arr);\n * int param_1 = obj.query(left,right,value);\n */\n", + "title": "2080. Range Frequency Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ).", + "description_images": [], + "constraints": [ + "RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr .", + "int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]Output[null, 1, 2]ExplanationRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3295 ms (Top 30.98%) | Memory: 53.7 MB (Top 24.88%)\nclass RangeFreqQuery:\n def __init__(self, arr: List[int]):\n self.l = [[] for _ in range(10001)]\n for i, v in enumerate(arr):\n self.l[v].append(i)\n def query(self, left: int, right: int, v: int) -> int:\n return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)", + "title": "2080. Range Frequency Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right . Implement the RangeModule class:", + "description_images": [], + "constraints": [ + "RangeModule() Initializes the object of the data structure.", + "void addRange(int left, int right) Adds the half-open interval [left, right) , tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.", + "boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.", + "void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]Output[null, null, null, true, false, true]ExplanationRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 31.23%) | Memory: 73.2 MB (Top 20.97%)\nclass RangeModule {\n TreeMap map;\n\n public RangeModule() {\n map = new TreeMap<>();\n }\n\n public void addRange(int left, int right) {\n // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of right. Like this:\n // [left, right)\n // [l1, r1) [l2, r2)\n // Note: l2 could be the same as l1, so they are either both null or both non-null\n Integer l1 = map.floorKey(left);\n Integer l2 = map.floorKey(right);\n\n // try to visualize each case, and what to do based on r1\n if (l1 == null && l2 == null) {\n map.put(left, right);\n }\n else if (l1 != null && map.get(l1) >= left) {\n map.put(l1, Math.max(right, map.get(l2))); // r2 will always be greater than r1, so no need to check r1\n }\n else {\n map.put(left, Math.max(right, map.get(l2)));\n }\n\n // we don't want to remove the range starts at left, so left should be exclusive.\n // but we want to remove the one starts at right, so right should be inclusive.\n map.subMap(left, false, right, true).clear();\n }\n\n public boolean queryRange(int left, int right) {\n Integer l = map.floorKey(left);\n if (l != null && map.get(l) >= right) {\n return true;\n }\n return false;\n }\n\n public void removeRange(int left, int right) {\n Integer l1 = map.lowerKey(left); // I used lowerKey here, since we don't care about the range starting at left, as it should be removed\n Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right\n\n // do this first, in case l1 == l2, the later one will change r1(or r2 in this case)\n if (l2 != null && map.get(l2) > right) {\n map.put(right, map.get(l2));\n }\n\n if (l1 != null && map.get(l1) > left) {\n map.put(l1, left);\n }\n\n // range that starts at left should be removed, so left is inclusive\n // range that starts at right should be kept, so right is exclusive\n map.subMap(left, true, right, false).clear();\n }\n}", + "title": "715. Range Module", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right . Implement the RangeModule class:", + "description_images": [], + "constraints": [ + "RangeModule() Initializes the object of the data structure.", + "void addRange(int left, int right) Adds the half-open interval [left, right) , tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.", + "boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.", + "void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]Output[null, null, null, true, false, true]ExplanationRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_left as bl, bisect_right as br\nclass RangeModule:\n\n def __init__(self):\n self._X = []\n\n def addRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) or idx(right) is odd, it's in a interval. So don't add it. \n # If idx(left) or idx(right) is even, it's not in any interval. So add it as new interval \n # Slice array[idx(left) : idx(right)]\n # 1) both odd: Nothing is added. Merge all middle intervals. \n # 2) both even: Add new intervals. Merge all middle intervals\n # 3) idx(left) is even: update start point of next interval with left\n # 4) idx(right) is even: update end point of previous interval with right\n # Bisect_left vs. Bisect_right\n # left need to proceed all interval closing at left, so use Bisect_left\n # right need to go after all interval openning at right, so use Bisect_right\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0)\n \n\n def queryRange(self, left: int, right: int) -> bool:\n # Main logic \n # If idx of left/right is odd, it's in a interval. Else it's not. \n # If idx of left&right is the same, they're in the same interval\n # Bisect_left vs. Bisect_right\n # [start, end). Start is included. End is not. \n # so use bisect_right for left \n # so use bisect_left for right \n i, j = br(self._X, left), bl(self._X, right)\n return i == j and i % 2 == 1\n \n\n def removeRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) is odd, the interval that contains left need to change end point to left \n # If idx(right) is odd, the interval that contains right need to change start point to right\n # Else, everything from idx(left) to idx(right) is removed. Nothing is changed. \n # Bisect_left vs. Bisect_right\n # Same as addRange\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)\n\n", + "title": "715. Range Module", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root node of a binary search tree and two integers low and high , return the sum of values of all nodes with a value in the inclusive range [low, high] .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 * 10^4 ] .", + "1 <= Node.val <= 10^5", + "1 <= low <= high <= 10^5", + "All Node.val are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput:32\nExplanation:Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput:23\nExplanation:Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private int sum = 0;\n public int rangeSumBST(TreeNode root, int low, int high) {\n dfs(root, low, high);\n return sum;\n }\n \n public void dfs(TreeNode root, int low, int high){\n if(root == null) return;\n \n if(root.val < low) dfs(root.right, low, high);\n else if(root.val > high) dfs(root.left, low, high);\n \n if(root.val >= low && root.val <= high) {\n sum += root.val;\n dfs(root.left, low, high);\n dfs(root.right, low, high);\n }\n \n }\n}\n", + "title": "938. Range Sum of BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root node of a binary search tree and two integers low and high , return the sum of values of all nodes with a value in the inclusive range [low, high] .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 * 10^4 ] .", + "1 <= Node.val <= 10^5", + "1 <= low <= high <= 10^5", + "All Node.val are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput:32\nExplanation:Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput:23\nExplanation:Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 106 ms (Top 94.04%) | Memory: 24.40 MB (Top 92.45%)\n\nclass Solution:\n def rangeSumBST(self, root, L, R):\n if not root:\n return 0\n \n if L <= root.val <= R:\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n else:\n return self.rangeSumBST(root.left, L, R)\n\n\n\n", + "title": "938. Range Sum of BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right ( indexed from 1 ) , inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 100", + "1 <= left <= right <= n * (n + 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput:13\nExplanation:All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput:6\nExplanation:The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput:50", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static int mod=(int)1e9+7;\n public int rangeSum(int[] nums, int n, int left, int right) {\n \n PriorityQueue pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]);\n \n for(int i=0;i=left){\n ans=(ans+k[1])%mod;\n }\n if(k[0]+1 int:\n return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]\n", + "title": "303. Range Sum Query - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray {\n SegmentTree s;\n public NumArray(int[] nums) {\n s = new SegmentTree(nums);\n s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built\n }\n \n public void update(int index, int val) {\n int oldvalue = s.arr[index];//Find old value with traditional array, which is O(1) time complexity\n s.arr[index] = val;//Set our array so that there will be no contradictions if we ever rebuild.\n //If we are going use build function only once, then we don't need to update our traditional array. \n s.update(s.root, val, index, oldvalue);//Call class' function\n }\n \n public int sumRange(int left, int right) {\n return s.rangeSum(s.root, left, right);\n }\n}\n\nclass Node {\n int s;//inclusive label\n int e;//inclusive label\n int val;\n Node left;\n Node right;\n}\n\nclass SegmentTree {\n Node root;\n int[] arr;\n\n SegmentTree(int [] arr) {\n this.arr = arr;\n }\n\n public Node build(int start, int end, int[] arr) {\n //Start and End integers have nothing to do with building of our SegmentTree, you may ignore them for now\n //They are needed for querying and updating, so that we can use binary search.\n Node temp = new Node();\n if (arr.length == 1) {//which means we are setting a node equal to an element of arr\n temp.val = arr[0];\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n } else if (arr.length == 0 || start > end || start < 0 || end < 0) {\n return new Node();// may be better\n } else {\n //left = build(start, mid but add 1 if array's length is not divisible by 2, left half of the passed array)\n temp.left = build(start, (start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), Arrays.copyOfRange(arr, 0, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0)));\n //right = build(start, mid but add 1 if array's length is not divisible by 2, right half of the passed array)\n temp.right = build((start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), end, Arrays.copyOfRange(arr, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0), arr.length));\n temp.val = temp.left.val + temp.right.val;\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n }\n return temp;//return this Node to one upper call so that this can be a child of it's parent\n }\n \n public int rangeSum(Node node, int l, int r) {\n if(node == null)\n {\n //Range is completely outside given range\n return 0;\n }\n if(l <= node.s && node.e <= r)\n {\n //Range is completely inside given range\n return node.val;\n }\n //Range is partially inside and partially outside the given range\n int mid = (node.s + node.e) / 2;\n int left = 0;\n int right = 0;\n if (l <= mid) {\n //For example let's say root's borders are 0:3, l,r=1:2\n //Then mid will be 1, then we will go into both directions because 1<=1, and 2>=1\n //Our next calls will be rS(root.left(which is 0:1), 1, 2) and rS(root.right(which is 2:3), 1, 2)\n //Left call's mid will be mid = (0+1)/2 = 0\n //Then 1<=0 ? No it's not, this is why left call's variable named left will be 0\n //Then 2>=0 ? Yes, we will call rS(root.left.right(which is 1:1), 1, 2)\n //Our left call's right call:\n //1:1 is completely inside 1:2, return the value it holds(equals to arr[1] if our arr is up to date)\n //Our original call's left will be arr[1]\n //Let's calculate our first right function\n //With same reasoning, our right function will go to left and be root.right.left(which is 2:2)\n //Our original call's right will be arr[2]\n //Our original/first function will return left + right, which is in fact [1:2] inclusive\n left = rangeSum(node.left, l, r);\n } \n if (r >= mid) {\n right = rangeSum(node.right, l, r);\n }\n return (left + right);\n }\n //What we are doing is, going downwards in our tree while we update the values we touch upon\n //We need to update root always, since it is sum of every element\n //After that we find mid which is mid value of our current node's start and end(inclusive)\n //At first call this will be (0+arr.length)/2 => mid\n //If given idx is bigger than mid, then we need to keep searching at right branch\n //That is why we call the function with root.right as our new root\n //If given idx is smaller and equals to mid, then we search at left branch\n //Why did we include equality too? Because I built my tree this way.(where equal things go left)\n //If idx is between our root's borders then we will decrease by the old value, increase by the new value.\n //If root equals null, we won't do anything\n //We update our traditional array at above.\n public void update(Node root, int value, int idx, int oldvalue) {\n if (root == null) {\n return;\n }\n int mid = (root.e + root.s) / 2;\n if (idx <= root.e && idx >= root.s) {\n root.val -= oldvalue;\n root.val += value;\n } if (idx > mid) {\n update(root.right, value, idx, oldvalue);\n } else if (idx <= mid) {\n update(root.left, value, idx, oldvalue);\n }\n }\n}\n", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray:\n nums = []\n s = 0\n l = 0\n \n def __init__(self, nums: List[int]):\n self.nums = nums\n self.s = sum(nums)\n self.l = len(nums)\n\n def update(self, index: int, val: int) -> None:\n self.s -= self.nums[index]\n self.nums[index] = val\n self.s += self.nums[index]\n\n def sumRange(self, left: int, right: int) -> int:\n if right - left > self.l // 2:\n ans = sum(self.nums[:left]) + sum(self.nums[right + 1:])\n return self.s - ans\n else:\n return sum(self.nums[left: right + 1])\n", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D matrix matrix , handle multiple queries of the following type: Implement the NumMatrix class: You must design an algorithm where sumRegion works on O(1) time complexity.", + "description_images": [], + "constraints": [ + "Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]Output[null, 8, 11, 12]ExplanationNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)", + "image": "https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" + } + ], + "follow_up": null, + "solution": "class NumMatrix {\n\n int mat[][];\n public NumMatrix(int[][] matrix) {\n mat = matrix;\n int rows = mat.length;\n int cols = mat[0].length;\n \n for(int i = 0; i< rows; i++)\n {\n for(int j = 0; j < cols; j++) \n {\n if(i > 0) mat[i][j] += mat[i-1][j];\n if(j > 0) mat[i][j] += mat[i][j-1];\n if(i>0 && j > 0) mat[i][j] -= mat[i-1][j-1];\n }\n }\n \n }\n \n public int sumRegion(int row1, int col1, int row2, int col2) {\n int res = mat[row2][col2];\n if(row1 > 0) res -= mat[row1-1][col2];\n if(col1 > 0) res -= mat[row2][col1-1];\n if(row1> 0 && col1 > 0) res += mat[row1-1][col1-1];\n \n return res;\n }\n}\n", + "title": "304. Range Sum Query 2D - Immutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D matrix matrix , handle multiple queries of the following type: Implement the NumMatrix class: You must design an algorithm where sumRegion works on O(1) time complexity.", + "description_images": [], + "constraints": [ + "Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]Output[null, 8, 11, 12]ExplanationNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)", + "image": "https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 3180 ms (Top 18.96%) | Memory: 24.7 MB (Top 69.46%)\n\nclass NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n m, n = len(matrix), len(matrix[0])\n # Understand why we need to create a new matrix with extra one row/column\n self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)]\n for r in range(1, m + 1):\n for c in range(1, n + 1):\n self.sum[r][c] = self.sum[r - 1][c] + self.sum[r][c - 1] - self.sum[r - 1][c - 1] + matrix[r - 1][c - 1]\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n r1, c1, r2, c2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1\n return self.sum[r2][c2] - self.sum[r1 - 1][c2] - self.sum[r2][c1 - 1] + self.sum[r1 - 1][c1 - 1]\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)", + "title": "304. Range Sum Query 2D - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system.", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput:\"ACB\"\nExplanation:Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.\nTeam B was ranked second by 2 voters and was ranked third by 3 voters.\nTeam C was ranked second by 3 voters and was ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]\nOutput:\"XWYZ\"\nExplanation:X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation:Only one voter so his votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 71.24%) | Memory: 43.7 MB (Top 79.83%)\nclass Solution {\n public String rankTeams(String[] votes) {\n int n = votes.length;\n int teams = votes[0].length();\n Map map = new HashMap<>();\n List chars = new ArrayList<>();\n\n for(int i = 0 ; i < teams ; i++) {\n char team = votes[0].charAt(i);\n map.put(team, new int[teams]);\n chars.add(team);\n }\n\n for(int i = 0 ; i < n ; i++) {\n String round = votes[i];\n for(int j = 0 ; j < round.length() ; j++) {\n map.get(round.charAt(j))[j]+=1;\n }\n }\n\n chars.sort((a,b) -> {\n int[] l1 = map.get(a);\n int[] l2 = map.get(b);\n for(int i = 0 ; i < l1.length; i++) {\n if(l1[i] < l2[i]) {\n return 1;\n }\n else if(l1[i] > l2[i]) {\n return -1;\n }\n }\n return a.compareTo(b);\n });\n\n StringBuilder sb = new StringBuilder();\n for(char c : chars) {\n sb.append(c);\n }\n return sb.toString();\n }\n}", + "title": "1366. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system.", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput:\"ACB\"\nExplanation:Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.\nTeam B was ranked second by 2 voters and was ranked third by 3 voters.\nTeam C was ranked second by 3 voters and was ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]\nOutput:\"XWYZ\"\nExplanation:X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation:Only one voter so his votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "#[\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\n#d = {\n# \"A\": [5, 0, 0],\n# \"B\": [0, 2, 3],\n# \"C\": [0, 3, 2]\n#}\n#keys represent the candidates\n#index of array in dict represent the rank\n#value of array item represent number of votes casted\n#ref: https://www.programiz.com/python-programming/methods/built-in/sorted\nclass Solution:\n #T=O(mn + mlgm), S=O(mn)\n\t#n=number of votes\n\t#m=number of candidates and m(number of ranks) is constant(26)\n def rankTeams(self, votes: List[str]) -> str:\n d = {}\n #build the dict\n #T=O(mn), S=O(mn)\n\t\t#n=number of votes, m=number of candidates(26)\n for vote in votes:\n for i, c in enumerate(vote):\n #if key not in dict\n if c not in d:\n #d[char] = [0, 0, 0]\n d[c] = [0]*len(vote)\n #increment the count of votes for each rank\n #d[\"A\"][0] = 1\n d[c][i] += 1\n #sort the dict keys in ascending order because if there is a tie we return in ascending order\n\t\t#sorted uses a stable sorting algorithm\n #T=O(mlgm), S=O(m)\n vote_names = sorted(d.keys()) #d.keys()=[\"A\", \"B\", \"C\"]\n #sort the dict keys based on votes for each rank in descending order\n #T=O(mlgm), S=O(m)\n #sorted() always returns a list\n vote_rank = sorted(vote_names, reverse=True, key= lambda x: d[x])\n #join the list\n return \"\".join(vote_rank)\n", + "title": "1366. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix , return a new matrix answer where answer[row][col] is the rank of matrix[row][col] . The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The test cases are generated so that answer is unique under the given rules.", + "description_images": [], + "constraints": [ + "The rank is an integer starting from 1 .", + "If two elements p and q are in the same row or column , then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q)", + "If p < q then rank(p) < rank(q)", + "If p == q then rank(p) == rank(q)", + "If p > q then rank(p) > rank(q)", + "The rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2],[3,4]]\nOutput:[[1,2],[2,3]]\nExplanation:The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[7,7],[7,7]]\nOutput:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" + }, + { + "text": "Example 3: Input:matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\nOutput:[[4,2,3],[1,3,4],[5,1,6],[1,3,4]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 209 ms (Top 84.06%) | Memory: 75.6 MB (Top 97.21%)\nclass Solution {\n int[] parent;\n public int[][] matrixRankTransform(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] answer = new int[m][n];\n\n // GROUP BY MATRIX VAL -> {X,Y}\n TreeMap> map = new TreeMap<>();\n for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n int[] xy = {i,j};\n int val = matrix[i][j];\n if(map.get(val) == null)\n map.put(val, new ArrayList<>());\n map.get(val).add(xy);\n }\n }\n\n // INITIALIZE MIN-RANK ARRAY FOR EVERY COL/ROW\n int[] minX = new int[m];\n int[] minY = new int[n];\n\n for(Integer key : map.keySet()){\n List list = map.get(key);\n\n // SPLIT TO GROUPS USING UNION FIND FOR VALs IN SAME COL/ROW\n int lSize = list.size();\n parent = new int[lSize];\n for(int i = 0; i < lSize; i++)\n parent[i] = i;\n\n // Group the xy by col and row then union by row & by col\n HashMap> xMap = new HashMap<>();\n HashMap> yMap = new HashMap<>();\n for(int i = 0; i < lSize; i++){\n int[] xy = list.get(i);\n int x = xy[0];\n int y = xy[1];\n\n if(xMap.get(x) == null)\n xMap.put(x, new ArrayList<>());\n if(yMap.get(y) == null)\n yMap.put(y, new ArrayList<>());\n xMap.get(x).add(i);\n yMap.get(y).add(i);\n }\n\n // union by X\n for(Integer xKey : xMap.keySet()){\n List xList = xMap.get(xKey);\n for(int i = 1; i < xList.size(); i++){\n union(xList.get(i-1), xList.get(i));\n }\n }\n\n // union by Y\n for(Integer yKey : yMap.keySet()){\n List yList = yMap.get(yKey);\n for(int i = 1; i < yList.size(); i++){\n union(yList.get(i-1), yList.get(i));\n }\n }\n\n HashMap> group = new HashMap<>();\n for(int i = 0; i < lSize; i++){\n int grp = find(i);\n if(group.get(grp) == null)\n group.put(grp, new ArrayList<>());\n group.get(grp).add(list.get(i));\n }\n\n // SET ANSWER FOR EACH GROUP\n for(Integer grpKey : group.keySet()){\n int max = 1;\n List sublist = group.get(grpKey);\n\n // FIND MAX-RANK FOR THIS GROUP\n for(int[] xy : sublist){\n int x = xy[0];\n int y = xy[1];\n\n max = Math.max(max, Math.max(minX[x], minY[y]));\n }\n\n // UPDATE ANSWER = MAX-RANK AND SET NEW MIN-RANK FOR ROW/COL = MAX-RANK+1\n for(int[] xy : sublist){\n int x = xy[0];\n int y = xy[1];\n answer[x][y] = max;\n minX[x] = max+1;\n minY[y] = max+1;\n }\n }\n }\n return answer;\n }\n\n // UNION FIND IMPL\n void union(int a, int b){\n int pa = find(a);\n int pb = find(b);\n parent[pb] = pa;\n }\n\n int find(int a){\n int pa = parent[a];\n if(pa != a){\n parent[a] = find(pa);\n return parent[a];\n } else\n return a;\n }\n}", + "title": "1632. Rank Transform of a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix , return a new matrix answer where answer[row][col] is the rank of matrix[row][col] . The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The test cases are generated so that answer is unique under the given rules.", + "description_images": [], + "constraints": [ + "The rank is an integer starting from 1 .", + "If two elements p and q are in the same row or column , then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q)", + "If p < q then rank(p) < rank(q)", + "If p == q then rank(p) == rank(q)", + "If p > q then rank(p) > rank(q)", + "The rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2],[3,4]]\nOutput:[[1,2],[2,3]]\nExplanation:The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[7,7],[7,7]]\nOutput:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" + }, + { + "text": "Example 3: Input:matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\nOutput:[[4,2,3],[1,3,4],[5,1,6],[1,3,4]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 3042 ms (Top 71.65%) | Memory: 50.4 MB (Top 92.27%)\nclass Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n m, n = len(matrix), len(matrix[0])\n rank = [0]*(m + n)\n d = defaultdict(list)\n for i in range(m):\n for j in range(n):\n d[matrix[i][j]].append((i,j))\n def find(i):\n if p[i] != i:\n p[i] = find(p[i])\n return p[i]\n def union(i,j):\n pi, pj = find(i), find(j)\n p[pi] = pj\n newrank[pj] = max(newrank[pi], newrank[pj])\n for e in sorted(d):\n p = list(range(m+n))\n newrank = rank[:]\n for i, j in d[e]:\n union(i,m+j)\n for i, j in d[e]:\n rank[i] = rank[m+j] = matrix[i][j] = newrank[find(i)] + 1\n return matrix", + "title": "1632. Rank Transform of a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , replace each element with its rank. The rank represents how large the element is. The rank has the following rules:", + "description_images": [], + "constraints": [ + "Rank is an integer starting from 1.", + "The larger the element, the larger the rank. If two elements are equal, their rank must be the same.", + "Rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [40,10,20,30]\nOutput:[4,1,2,3]\nExplanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,100,100]\nOutput:[1,1,1]\nExplanation: Same elements share the same rank.", + "image": null + }, + { + "text": "Example 3: Input:arr = [37,12,28,9,100,56,80,5,12]\nOutput:[5,3,4,2,8,6,7,1,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 325 ms (Top 99.70%) | Memory: 33.7 MB (Top 29.42%)\nclass Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n arr_set = list(sorted(set(arr)))\n rank = {}\n for i, e in enumerate(arr_set):\n rank[e] = i+1\n return [ rank[e] for e in arr]", + "title": "1331. Rank Transform of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote .", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 19.48%) | Memory: 44.60 MB (Top 8.88%)\n\nclass Solution {\n public boolean canConstruct(String ransomNote, String magazine) {\n char[] rs = ransomNote.toCharArray();\n char[] ms = magazine.toCharArray();\n \n HashMap rm = new HashMap<>();\n HashMap mz = new HashMap<>();\n \n for (char c : rs) {\n if (rm.containsKey(c)) {\n rm.put(c, rm.get(c) + 1);\n } else {\n rm.put(c, 1);\n }\n }\n\n for (char c : ms) {\n if (mz.containsKey(c)) {\n mz.put(c, mz.get(c) + 1);\n } else {\n mz.put(c, 1);\n }\n }\n\n for (char c : rm.keySet()) {\n if (!mz.containsKey(c) || mz.get(c) < rm.get(c)) {\n return false;\n }\n }\n return true; \n }\n}\n", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote .", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nclass Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n \n ransomNote_count = dict(Counter(ransomNote))\n magazine_count = dict(Counter(magazine))\n \n for key , value in ransomNote_count.items():\n \n if key in magazine_count:\n if value <= magazine_count[key]:\n continue\n else:\n return False\n \n return False\n \n return True\n", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are standing at position 0 on an infinite number line. There is a destination at position target . You can make some number of moves numMoves so that: Given the integer target , return the minimum number of moves required (i.e., the minimum numMoves ) to reach the destination .", + "description_images": [], + "constraints": [ + "On each move, you can either go left or right.", + "During the i th move (starting from i == 1 to i == numMoves ), you take i steps in the chosen direction." + ], + "examples": [ + { + "text": "Example 1: Input:target = 2\nOutput:3\nExplanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to -1 (2 steps).\nOn the 3rdmove, we step from -1 to 2 (3 steps).", + "image": null + }, + { + "text": "Example 2: Input:target = 3\nOutput:2\nExplanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to 3 (2 steps).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reachNumber(int target) {\n int sum =0 ,steps = 0;\n if(target ==0) return 0;\n target = Math.abs(target);\n while(sum< target){\n sum+=steps;\n steps++;\n }\n \n while(((sum-target)%2!=0)){\n sum+=steps;\n steps++;\n }\n return steps-1;\n\n }\n}\n", + "title": "754. Reach a Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are standing at position 0 on an infinite number line. There is a destination at position target . You can make some number of moves numMoves so that: Given the integer target , return the minimum number of moves required (i.e., the minimum numMoves ) to reach the destination .", + "description_images": [], + "constraints": [ + "On each move, you can either go left or right.", + "During the i th move (starting from i == 1 to i == numMoves ), you take i steps in the chosen direction." + ], + "examples": [ + { + "text": "Example 1: Input:target = 2\nOutput:3\nExplanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to -1 (2 steps).\nOn the 3rdmove, we step from -1 to 2 (3 steps).", + "image": null + }, + { + "text": "Example 2: Input:target = 3\nOutput:2\nExplanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to 3 (2 steps).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def reachNumber(self,target):\n jumpCount = 1 \n sum = 0 \n while sum heap = new PriorityQueue<>( (a, b) -> b[1]-a[1] );\n int ans = 0;\n boolean[] vis = new boolean[n];\n heap.offer(new int[]{0, maxMoves});\n while ( !heap.isEmpty() ) {\n int[] info = heap.poll();\n int nearestNodeId = info[0];\n int maxMovesRemaining = info[1];\n if ( vis[nearestNodeId] ) {\n continue;\n }\n // visiting the current node\n vis[nearestNodeId] = true;\n // since we visited this node we increment our counter\n ans++;\n for ( int i=0; i=graph[nearestNodeId][i]+1 ) {\n heap.offer( new int[] {i, maxMovesRemaining-graph[nearestNodeId][i]-1} );\n }\n int movesTaken = Math.min(maxMovesRemaining, graph[nearestNodeId][i]);\n graph[nearestNodeId][i] -= movesTaken;\n graph[i][nearestNodeId] -= movesTaken;\n ans += movesTaken;\n }\n }\n }\n return ans;\n }\n}", + "title": "882. Reachable Nodes In Subdivided Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an undirected graph (the \"original graph\" ) with n nodes labeled from 0 to n - 1 . You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [u i , v i , cnt i ] indicates that there is an edge between nodes u i and v i in the original graph, and cnt i is the total number of new nodes that you will subdivide the edge into. Note that cnt i == 0 means you will not subdivide the edge. To subdivide the edge [u i , v i ] , replace it with (cnt i + 1) new edges and cnt i new nodes. The new nodes are x 1 , x 2 , ..., x cnt i , and the new edges are [u i , x 1 ] , [x 1 , x 2 ] , [x 2 , x 3 ] , ..., [x cnt i -1 , x cnt i ] , [x cnt i , v i ] . In this new graph , you want to know how many nodes are reachable from the node 0 , where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves , return the number of nodes that are reachable from node 0 in the new graph .", + "description_images": [], + "constraints": [ + "0 <= edges.length <= min(n * (n - 1) / 2, 10^4 )", + "edges[i].length == 3", + "0 <= u i < v i < n", + "There are no multiple edges in the graph.", + "0 <= cnt i <= 10^4", + "0 <= maxMoves <= 10^9", + "1 <= n <= 3000" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\nOutput:13\nExplanation:The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/01/origfinal.png" + }, + { + "text": "Example 2: Input:edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\nOutput:23", + "image": null + }, + { + "text": "Example 3: Input:edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\nOutput:1\nExplanation:Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1218 ms (Top 16.46%) | Memory: 23.7 MB (Top 8.86%)\nclass Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n m = defaultdict(list)\n for a, b, p in edges:\n m[a].append((p, b))\n m[b].append((p, a))\n\n vis = set()\n queue = []\n heappush(queue, (0, 0))\n edgevis = set()\n edgeofl = defaultdict(lambda: 0)\n ans = 0\n while queue:\n # print(queue)\n cost, cur = heappop(queue)\n vis.add(cur)\n for p, nxt in m[cur]:\n if p < maxMoves - cost:\n if (cur, nxt) not in edgevis and (nxt, cur) not in edgevis:\n ans += p\n # if nxt in vis:\n # ans -= 1\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n if nxt not in vis:\n heappush(queue, (cost + p + 1, nxt))\n else:\n bal = maxMoves - cost\n if (cur, nxt) in edgevis:\n continue\n if bal <= edgeofl[(cur, nxt)]:\n continue\n if bal + edgeofl[(nxt, cur)] < p:\n ans += bal - edgeofl[(cur, nxt)]\n edgeofl[(cur, nxt)] = bal\n else:\n ans += p - edgeofl[(nxt, cur)] - edgeofl[(cur, nxt)]\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n return ans + len(vis)", + "title": "882. Reachable Nodes In Subdivided Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "edges represents a valid tree.", + "1 <= restricted.length < n", + "1 <= restricted[i] < n", + "All the values of restricted are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput:4\nExplanation:The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput:3\nExplanation:The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int count=0;\n ArrayList> adj=new ArrayList<>();\n public int reachableNodes(int n, int[][] edges, int[] restricted) {\n boolean[] vis=new boolean[n];\n for(int i:restricted){\n vis[i]=true;\n }\n for(int i=0;i());\n }\n for(int[] ii:edges){\n adj.get(ii[0]).add(ii[1]);\n adj.get(ii[1]).add(ii[0]);\n }\n dfs(0,vis);\n return count;\n }\n private void dfs(int node,boolean[] vis){\n vis[node]=true;\n count++;\n for(int it:adj.get(node)){\n if(vis[it]==false){\n dfs(it,vis);\n }\n }\n }\n}\n", + "title": "2368. Reachable Nodes With Restrictions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node.", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "edges represents a valid tree.", + "1 <= restricted.length < n", + "1 <= restricted[i] < n", + "All the values of restricted are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput:4\nExplanation:The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput:3\nExplanation:The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n # ignore restricted node\n # bfs from 0\n \n # O(E), EDITED: the time complexity here is wrong, plz see my comment\n adj_dict = collections.defaultdict(list)\n for u, v in edges:\n if u in restricted or v in restricted: # EDITED: not O(1)\n continue\n adj_dict[u].append(v)\n adj_dict[v].append(u)\n \n # O(V + E)\n queue = collections.deque([0])\n visited = {0}\n while queue:\n cur = queue.popleft()\n for neighbor in adj_dict[cur]:\n if neighbor in visited:\n continue\n visited.add(neighbor)\n queue.append(neighbor)\n\n return len(visited)\n", + "title": "2368. Reachable Nodes With Restrictions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given four integers sx , sy , tx , and ty , return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations , or false otherwise . The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y) .", + "description_images": [], + "constraints": [ + "1 <= sx, sy, tx, ty <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:sx = 1, sy = 1, tx = 3, ty = 5\nOutput:true\nExplanation:One series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)", + "image": null + }, + { + "text": "Example 2: Input:sx = 1, sy = 1, tx = 2, ty = 2\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:sx = 1, sy = 1, tx = 1, ty = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 55.54%) | Memory: 41.4 MB (Top 26.41%)\nclass Solution {\n public boolean reachingPoints(int sx, int sy, int tx, int ty) {\n if (sx==tx && sy==ty){\n return true;\n }\n if (tx < sx || ty < sy){\n return false;\n }\n return tx (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)", + "image": null + }, + { + "text": "Example 2: Input:sx = 1, sy = 1, tx = 2, ty = 2\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:sx = 1, sy = 1, tx = 1, ty = 1\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\nclass Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n def nextNum(ta,tb,s):\n if ta % tb == s % tb:\n return min(ta, s)\n return ta % tb\n visited = defaultdict(bool)\n while tx >= sx and ty >= sy and (sx != tx or sy != ty):\n if tx > ty:\n tx, ty = nextNum(tx, ty, sx), ty\n else:\n tx, ty = tx, nextNum(ty, tx, sy)\n if visited[(tx,ty)]:\n break\n visited[(tx,ty)] = True\n return (sx == tx) and (sy == ty)\n", + "title": "780. Reaching Points", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Return the modified array after rearranging the elements to satisfy the aforementioned conditions .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^5", + "nums.length is even", + "1 <= |nums[i]| <= 10^5", + "nums consists of equal number of positive and negative integers." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,-2,-5,2,-4]\nOutput:[3,-2,1,-5,2,-4]\nExplanation:The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1]\nOutput:[1,-1]\nExplanation:1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 29.67%) | Memory: 225.1 MB (Top 38.94%)\nclass Solution {\n public int[] rearrangeArray(int[] nums) {\n int[] res = new int[nums.length];\n int resIdx = 0;\n int posIdx = -1;\n int minusIdx = -1;\n\n for(int i=0;i 0 )minusIdx++;\n res[resIdx++] = nums[minusIdx];\n }\n }\n\n return res;\n }\n}", + "title": "2149. Rearrange Array Elements by Sign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Return the modified array after rearranging the elements to satisfy the aforementioned conditions .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^5", + "nums.length is even", + "1 <= |nums[i]| <= 10^5", + "nums consists of equal number of positive and negative integers." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,-2,-5,2,-4]\nOutput:[3,-2,1,-5,2,-4]\nExplanation:The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1]\nOutput:[1,-1]\nExplanation:1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]\n", + "title": "2149. Rearrange Array Elements by Sign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed strings s and target . You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "1 <= target.length <= 10", + "s and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ilovecodingonleetcode\", target = \"code\"\nOutput:2\nExplanation:For the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcba\", target = \"abc\"\nOutput:1\nExplanation:We can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abbaccaddaeea\", target = \"aaaaa\"\nOutput:1\nExplanation:We can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.04 MB (Top 6.2%)\n\nclass Solution\n{\n public int rearrangeCharacters(String s, String target)\n {\n int[] freq = new int[26], freq2 = new int[26];\n for(char ch : s.toCharArray())\n freq[ch-'a']++;\n for(char ch : target.toCharArray())\n freq2[ch-'a']++;\n\n int min = Integer.MAX_VALUE;\n for(char ch : target.toCharArray())\n min = Math.min(min,freq[ch-'a']/freq2[ch-'a']);\n \n return min;\n }\n}", + "title": "2287. Rearrange Characters to Make Target String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed strings s and target . You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "1 <= target.length <= 10", + "s and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ilovecodingonleetcode\", target = \"code\"\nOutput:2\nExplanation:For the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcba\", target = \"abc\"\nOutput:1\nExplanation:We can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abbaccaddaeea\", target = \"aaaaa\"\nOutput:1\nExplanation:We can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 55 ms (Top 32.02%) | Memory: 13.9 MB (Top 67.72%)\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n counter_s = Counter(s)\n return min(counter_s[c] // count for c,count in Counter(target).items())", + "title": "2287. Rearrange Characters to Make Target String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word . Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized . If you cannot redistribute all the spaces equally, place the extra spaces at the end , meaning the returned string should be the same length as text . Return the string after rearranging the spaces .", + "description_images": [], + "constraints": [ + "1 <= text.length <= 100", + "text consists of lowercase English letters and ' ' .", + "text contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:text = \" this is a sentence \"\nOutput:\"this is a sentence\"\nExplanation:There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.", + "image": null + }, + { + "text": "Example 2: Input:text = \" practice makes perfect\"\nOutput:\"practice makes perfect \"\nExplanation:There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 61.66%) | Memory: 40.5 MB (Top 92.33%)\nclass Solution {\n public String reorderSpaces(String text) {\n int spaces = 0;\n\n //count the spacex\n for(char c: text.toCharArray()){\n if(c==' ')\n spaces++;\n }\n\n //form word array\n String[] words = text.trim().split(\"\\\\s+\");\n int nWords = words.length;\n\n StringBuilder sb = new StringBuilder();\n int spacesToApply=0,extraSpaces=0;\n\n //if there is only 1 word, then all spaces will be at the end\n if(nWords == 1){\n extraSpaces=spaces;\n }\n\n //if there are multiple words, find the spaces to apply between words and also any extra space\n else{\n spacesToApply = spaces / (nWords-1);\n extraSpaces = spaces % (nWords-1);\n }\n\n //append every word and then apply spaces\n for(int i=0;i 1:\n q, r = spaces//(words-1), spaces%(words-1)\n return (\" \" * q).join(word_list) + \" \" * r\n else:\n return \"\".join(word_list) + \" \" * spaces\n", + "title": "1592. Rearrange Spaces Between Words", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sentence text (A sentence is a string of space-separated words) in the following format: Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above.", + "description_images": [], + "constraints": [ + "First letter is in upper case.", + "Each word in text are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"Leetcode is cool\"\nOutput:\"Is cool leetcode\"\nExplanation:There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.", + "image": null + }, + { + "text": "Example 2: Input:text = \"Keep calm and code on\"\nOutput:\"On and keep calm code\"\nExplanation:Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.", + "image": null + }, + { + "text": "Example 3: Input:text = \"To be or not to be\"\nOutput:\"To be or to be not\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 72.47%) | Memory: 45.70 MB (Top 34.84%)\n\nclass Solution {\n public String arrangeWords(String text) {\n text = text.replace(text.charAt(0)+\"\", (char)(text.charAt(0)+32)+\"\");\n\n String[] arr = text.split(\" \");\n Arrays.sort(arr, new Comparator(){\n public int compare(String s1, String s2){\n return Integer.compare(s1.length(), s2.length());\n }\n });\n\n StringBuilder str = new StringBuilder(arr[0]);\n\n for(int i = 1; i < arr.length; i++)\n str.append(\" \"+arr[i]);\n\n text = (char)(str.charAt(0)-32)+str.substring(1, str.length());\n\n return text;\n }\n}\n// UP-VOTE IF HELPFUL\n", + "title": "1451. Rearrange Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sentence text (A sentence is a string of space-separated words) in the following format: Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above.", + "description_images": [], + "constraints": [ + "First letter is in upper case.", + "Each word in text are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"Leetcode is cool\"\nOutput:\"Is cool leetcode\"\nExplanation:There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.", + "image": null + }, + { + "text": "Example 2: Input:text = \"Keep calm and code on\"\nOutput:\"On and keep calm code\"\nExplanation:Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.", + "image": null + }, + { + "text": "Example 3: Input:text = \"To be or not to be\"\nOutput:\"To be or to be not\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 89.61%) | Memory: 19.60 MB (Top 55.06%)\n\nclass Solution:\n def arrangeWords(self, text: str) -> str:\n a = []\n for x in text.split(\" \"):\n a.append(x.lower())\n return \" \".join(sorted(a, key=len)).capitalize()\n", + "title": "1451. Rearrange Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the following details of a matrix with n columns and 2 rows : Your task is to reconstruct the matrix with upper , lower and colsum . Return it as a 2-D integer array. If there are more than one valid solution, any of them will be accepted. If no valid solution exists, return an empty 2-D array.", + "description_images": [], + "constraints": [ + "The matrix is a binary matrix, which means each element in the matrix can be 0 or 1 .", + "The sum of elements of the 0-th(upper) row is given as upper .", + "The sum of elements of the 1-st(lower) row is given as lower .", + "The sum of elements in the i-th column(0-indexed) is colsum[i] , where colsum is given as an integer array with length n ." + ], + "examples": [ + { + "text": "Example 1: Input:upper = 2, lower = 1, colsum = [1,1,1]\nOutput:[[1,1,0],[0,0,1]]\nExplanation:[[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.", + "image": null + }, + { + "text": "Example 2: Input:upper = 2, lower = 3, colsum = [2,2,1,1]\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]\nOutput:[[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2054 ms (Top 5.33%) | Memory: 24.4 MB (Top 72.78%)\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n n = len(colsum)\n matrix = [[0 for i in range(n)] for j in range(2)]\n for col,summ in enumerate(colsum):\n if summ == 0:\n continue\n if summ == 2:\n matrix[0][col] = matrix[1][col] = 1\n upper -= 1\n lower -= 1\n else:\n if upper > lower:\n matrix[0][col] = 1\n upper -= 1\n else:\n matrix[1][col] = 1\n lower -= 1\n if upper < 0 or lower < 0: break\n\n return matrix if upper == lower == 0 else []", + "title": "1253. Reconstruct a 2-Row Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.", + "description_images": [], + "constraints": [ + "For example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nOutput:[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg" + }, + { + "text": "Example 2: Input:tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nOutput:[\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\nExplanation:Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 90.17%) | Memory: 50.3 MB (Top 42.47%)\nclass Solution {\n LinkedList res = new LinkedList<>();\n\n public List findItinerary(List> tickets) {\n HashMap> map= new HashMap<>();\n for(int i=0;i temp = new PriorityQueue();\n map.put(a,temp);\n }\n map.get(a).add(b);\n }\n\n dfs(\"JFK\",map);\n return res;\n\n }\n private void dfs(String departure,HashMap> map){\n PriorityQueue arrivals= map.get(departure);\n while(arrivals!=null &&!arrivals.isEmpty()){\n dfs(arrivals.poll(),map);\n }\n res.addFirst(departure);\n }\n}", + "title": "332. Reconstruct Itinerary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.", + "description_images": [], + "constraints": [ + "For example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nOutput:[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg" + }, + { + "text": "Example 2: Input:tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nOutput:[\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\nExplanation:Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution: \n def findTicketsAdjList(self, tickets):\n ticket = {}\n for src,dest in tickets:\n if src in ticket:\n ticket[src].append(dest)\n else:\n ticket[src] = [dest]\n\n for src,dest in ticket.items():\n if len(dest)>1:\n ticket[src] = sorted(ticket[src], reverse=True)\n \n return ticket\n \n def reconstructItinerary(self, source, tickets, itinerary):\n if source in tickets:\n while tickets[source]: \n destination = tickets[source].pop()\n self.reconstructItinerary(destination, tickets, itinerary)\n itinerary.append(source)\n return itinerary\n \n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n if len(tickets)==1:\n if \"JFK\" not in tickets[0]:\n return []\n \n ticketsAdj = self.findTicketsAdjList(tickets)\n if \"JFK\" not in ticketsAdj:\n return []\n itinerary = []\n itinerary = self.reconstructItinerary(\"JFK\", ticketsAdj, itinerary)\n \n return itinerary[::-1]\n \n", + "title": "332. Reconstruct Itinerary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing an out-of-order English representation of digits 0-9 , return the digits in ascending order .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"] .", + "s is guaranteed to be valid." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"owoztneoer\"\nOutput:\"012\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"fviefuro\"\nOutput:\"45\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n // First letter is unique after previous entries have been handled:\n static final String[] UNIQUES = new String[] {\n \"zero\", \"wto\", \"geiht\", \"xsi\", \"htree\",\n \"seven\", \"rfou\", \"one\", \"vfie\", \"inne\"\n };\n\n // Values corresponding to order of uniqueness checks:\n static final int[] VALS = new int[] { 0, 2, 8, 6, 3, 7, 4, 1, 5, 9 };\n \n\t// Maps for checking uniqueness more conveniently:\n static final Map> ORDERED_FREQ_MAP;\n static final Map ORDERED_DIGIT_MAP;\n \n static {\n\t // Initialize our ordered frequency map: 0-25 key to 0-25 values finishing the word:\n final LinkedHashMap> orderedFreqMap = new LinkedHashMap<>();\n\t\t// Also initialize a digit lookup map, e.g. 'g' becomes 6 maps to 8 for ei[g]ht:\n final LinkedHashMap orderedDigitMap = new LinkedHashMap<>();\n for (int i = 0; i < 10; ++i) {\n final char unique = UNIQUES[i].charAt(0);\n final int ui = convert(unique);\n orderedFreqMap.put(ui, converting(UNIQUES[i].substring(1).toCharArray()));\n orderedDigitMap.put(ui, VALS[i]);\n }\n\t\t// Let's make sure we aren't tempted to modify these since they're static.\n ORDERED_FREQ_MAP = Collections.unmodifiableMap(orderedFreqMap);\n ORDERED_DIGIT_MAP = Collections.unmodifiableMap(orderedDigitMap);\n }\n\n public String originalDigits(String s) {\n\t // count frequencies of each letter in s:\n final int[] freqs = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n freqs[convert(s.charAt(i))]++;\n }\n\t\t// Crate an array to store digit strings in order, e.g. '00000', '11, '2222222', etc.\n final String[] strings = new String[10];\n\t\t// Iterate through uniqueness checks in order:\n for (Map.Entry> entry : ORDERED_FREQ_MAP.entrySet()) {\n final int index = entry.getKey(); // unique letter in 0-25 form\n final int value = ORDERED_DIGIT_MAP.get(index); // corresponding digit, e.g. 8 for 'g', 0 for 'z', etc.\n final int count = freqs[index]; // frequency of unique letter = frequency of corresponding digit\n if (count > 0) {\n\t\t\t // update frequencies to remove the digit's word count times:\n freqs[index] -= count;\n for (int idx : entry.getValue()) {\n freqs[idx] -= count;\n }\n\t\t\t\t// now create the digit string for the unique digit: the digit count times:\n strings[value] = String.valueOf(value).repeat(count);\n } else {\n\t\t\t // count 0 - empty strring for this digit\n strings[value] = \"\";\n }\n }\n\t\t// append the digit strings in order\n final StringBuilder sb = new StringBuilder();\n for (String str : strings) {\n sb.append(str);\n }\n\t\t// and we are done!\n return sb.toString();\n }\n\n // Converts a character array into a list of 0-25 frequency values.\n private static final List converting(char... carr) {\n final List list = new ArrayList<>();\n for (char ch : carr) {\n list.add(convert(ch)); // converts each to 0-25\n }\n return Collections.unmodifiableList(list);\n }\n\n // Converts a-z to 0-26. Bitwise AND with 31 gives a=1, z=26, so then subtract one.\n private static final Integer convert(char ch) {\n return (ch & 0x1f) - 1; // a->0, z->25\n }\n\n}\n", + "title": "423. Reconstruct Original Digits from English", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s containing an out-of-order English representation of digits 0-9 , return the digits in ascending order .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"] .", + "s is guaranteed to be valid." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"owoztneoer\"\nOutput:\"012\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"fviefuro\"\nOutput:\"45\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def originalDigits(self, s: str) -> str:\n c = dict()\n \n c[0] = s.count(\"z\")\n c[2] = s.count(\"w\")\n c[4] = s.count(\"u\")\n c[6] = s.count(\"x\")\n c[8] = s.count(\"g\")\n \n c[3] = s.count(\"h\") - c[8]\n c[5] = s.count(\"f\") - c[4]\n c[7] = s.count(\"s\") - c[6]\n \n c[9] = s.count(\"i\") - (c[8] + c[5] + c[6])\n c[1] = s.count(\"o\") - (c[0] + c[2] + c[4])\n \n c = sorted(c.items(), key = lambda x: x[0])\n ans = \"\"\n for k, v in c:\n ans += (str(k) * v)\n return ans", + "title": "423. Reconstruct Original Digits from English", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the original tree is in the range [1, 1000] .", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:traversal = \"1-2--3--4-5--6--7\"\nOutput:[1,2,5,3,4,6,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/08/recover-a-tree-from-preorder-traversal.png" + }, + { + "text": "Example 2: Input:traversal = \"1-2--3---4-5--6---7\"\nOutput:[1,2,5,3,null,6,null,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114101-pm.png" + }, + { + "text": "Example 3: Input:traversal = \"1-401--349---90--88\"\nOutput:[1,401,null,349,88,90]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114955-pm.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode recoverFromPreorder(String traversal) {\n if(!traversal.contains(\"-\"))\n return new TreeNode(Integer.parseInt(traversal));\n String number = \"\";\n int i = 0;\n while(traversal.charAt(i)!='-'){\n number+=traversal.charAt(i);\n i++;\n }\n //System.out.print(\"root = \" + number + \" \" + i + \" \");\n TreeNode root = new TreeNode(Integer.parseInt(number));\n StringBuilder str = new StringBuilder();\n int bk = 0;\n for(int j = i; i < traversal.length(); i++){\n if(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-' && traversal.charAt(i+1) != '-')\n bk = str.toString().length();\n else if(!(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-'))\n str.append(traversal.charAt(i));\n }\n String divide = str.toString();\n \n TreeNode left = (bk==0)?recoverFromPreorder(divide):recoverFromPreorder(divide.substring(0,bk));\n TreeNode right = (bk==0)?null:recoverFromPreorder(divide.substring(bk,divide.length()));\n root.left = left;\n root.right = right;\n \n \n return root;\n }\n}\n", + "title": "1028. Recover a Tree From Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the original tree is in the range [1, 1000] .", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:traversal = \"1-2--3--4-5--6--7\"\nOutput:[1,2,5,3,4,6,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/08/recover-a-tree-from-preorder-traversal.png" + }, + { + "text": "Example 2: Input:traversal = \"1-2--3---4-5--6---7\"\nOutput:[1,2,5,3,null,6,null,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114101-pm.png" + }, + { + "text": "Example 3: Input:traversal = \"1-401--349---90--88\"\nOutput:[1,401,null,349,88,90]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114955-pm.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 138 ms (Top 42.81%) | Memory: 14.7 MB (Top 52.51%)\nclass Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n i = 0\n dummy_head = TreeNode()\n depth = 0\n while i < len(traversal):\n if traversal[i].isdigit():\n value, i = get_value(traversal, i)\n insert_node(dummy_head, depth, value)\n\n else:\n depth, i = get_depth(traversal, i)\n\n return dummy_head.left\n\n# Returns the next value from the string traversal, and returns the position following the last digit of the current value.\ndef get_value(traversal, i):\n value = 0\n while i < len(traversal) and traversal[i].isdigit():\n value *= 10\n value += int(traversal[i])\n i += 1\n\n return value, i\n\n# Insertes a node of the given `value` at the given `depth` of the subtree whose root is the given `root`.\ndef insert_node(root, depth, value):\n for _ in range(depth):\n if root.right:\n root = root.right\n else:\n root = root.left\n\n new_node = TreeNode(value)\n if root.left:\n root.right = new_node\n else:\n root.left = new_node\n\n# Gets the next depth from the string traversal, and returns the position following the last dash of the current depth.\ndef get_depth(traversal, i):\n depth = 0\n while i < len(traversal) and traversal[i] == \"-\":\n depth += 1\n i += 1\n\n return depth, i", + "title": "1028. Recover a Tree From Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 1000] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,3,null,null,2]\nOutput:[3,1,null,null,2]\nExplanation:3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.", + "image": "https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg" + }, + { + "text": "Example 2: Input:root = [3,1,4,null,null,2]\nOutput:[2,1,4,null,null,3]\nExplanation:2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.", + "image": "https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 95.6%) | Memory: 16.68 MB (Top 75.1%)\n\nclass Solution:\n \n \"\"\"\n Brute force kind of thing\n -> Inorder Traversal returns sorted array\n -> find a swap btwn numbers to make sorted\n Make single swap to make array sorted\n [1, 2, 3, 4, 10, 6, 9, 5, 10, 12]\n x, x, x, x, x, No\n prev number is mismatch -> 10 is cause\n now go frm right to left\n [1, 2, 3, 4, 10, 6, 9, 5, 11, 12]\n No x x x\n mismatch with next number -> 5 is the cause\n swap 10, 5\n \n Eg: 2\n [3, 2, 1]\n x No -> 3 is the cause\n [3, 2, 1]\n x No -> 1 is the cause\n swap values -> 1, 3\n \"\"\"\n \n def inorder(self, root, li):\n if root is None:\n return li\n li = self.inorder(root.left, li)\n li.append(root)\n li = self.inorder(root.right, li)\n return li\n \n def recoverTree(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n li = self.inorder(root, [])\n n = len(li)\n i, j = 1, n-2\n a = li[0]\n for i in range(1, n):\n if li[i].val < li[i-1].val:\n a = li[i-1]\n break\n b = li[-1]\n for i in range(n-2, -1, -1):\n if li[i].val > li[i+1].val:\n b = li[i+1]\n break\n\n a.val,b.val = b.val, a.val\n", + "title": "99. Recover Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr .", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]\nOutput:[3,7,11]\nExplanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]\nOutput:[2,2]\nExplanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]\nOutput:[220]\nExplanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 910 ms (Top 16.67%) | Memory: 44.70 MB (Top 72.22%)\n\nclass Solution {\n public int[] recoverArray(int[] nums) {\n \n \tint i,n=nums.length;\n \tint ans[]=new int[n/2];\n \tArrays.sort(nums);\n \tPriorityQueue pq=new PriorityQueue<>();\n \tfor(i=0;i pq1=new PriorityQueue<>(pq);\n \t\tint p=0;\n \t\tif((nums[0]+nums[i])%2==0)\n \t\t{\n \t\t\tint k=(nums[0]+nums[i])/2-nums[0];\n \t\t\tif(k==0)\n \t\t\t\tcontinue;\n \t\t\tint curr=pq1.poll();\n \t\t\twhile(pq1.contains((curr+k+k))) {\n \t\t\t\n \t\t\t\tpq1.remove(curr+k+k); \n\t\t\t\t\tans[p++]=curr+k;\n\t\t\t\t\tif(p==n/2)\n\t\t\t\t\t\tbreak;\n \t\t\t\tcurr=pq1.poll();\n \t\t\t}\n \t\t\tif(p==n/2)\n \t\t\t\tbreak;\n \t\t}\n \t}\n \treturn ans;\n }\n}\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr .", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]\nOutput:[3,7,11]\nExplanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]\nOutput:[2,2]\nExplanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]\nOutput:[220]\nExplanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] recoverArray(int[] nums) {\n int N = nums.length;\n Arrays.sort(nums);\n List diffList = new ArrayList<>();\n for (int i = 1; i < N; i++) {\n int diff = Math.abs(nums[i] - nums[0]);\n if (diff % 2 == 0 && diff > 0) diffList.add(diff / 2);\n }\n Map map1 = new HashMap<>();\n for (int i = 0; i < N; i++)\n map1.put(nums[i], map1.getOrDefault(nums[i], 0) + 1);\n for (int diff : diffList) {\n Map map = new HashMap<>(map1);\n List tmp = new ArrayList<>();\n for (int i = 0; i < N; i++) {\n\t\t\t if (tmp.size() == N / 2) break;\n int low = nums[i];\n int high = low + 2 * diff;\n if (map.containsKey(low) && map.containsKey(high)) {\n tmp.add(low + diff);\n map.put(low, map.get(low) - 1); \n map.put(high, map.get(high) - 1);\n if (map.get(low) == 0) map.remove(low);\n if (map.get(high) == 0) map.remove(high);\n }\n }\n if (tmp.size() == N / 2) return tmp.stream().mapToInt(i -> i).toArray();\n }\n return null;\n }\n}\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr .", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]\nOutput:[3,7,11]\nExplanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]\nOutput:[2,2]\nExplanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]\nOutput:[220]\nExplanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def recoverArray(self, nums):\n nums.sort()\n mid = len(nums) // 2\n # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k.\n # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k.\n # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but\n # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough.\n # The conclusion is j <= mid.\n\t\t# If you think it’s not easy to understand why mid is enough, len(nums) can also work well\n\t\t# for j in range(1, len(nums)): \n for j in range(1, mid + 1): # O(N)\n if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive.\n k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), []\n # For each number in lower, we try to find the corresponding number from higher list.\n # Because nums is sorted, current n is always the current lowest num which can only come from lower\n # list, so we search the corresponding number of n which equals to n + 2 * k in the left\n # if it can not be found, change another k and continue to try.\n for n in nums: # check if n + 2 * k available as corresponding number in higher list of n\n if counter[n] == 0: # removed by previous num as its corresponding number in higher list\n continue\n if counter[n + 2 * k] == 0: # not found corresponding number in higher list\n break\n ans.append(n + k)\n counter[n] -= 1 # remove n\n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list\n if len(ans) == mid:\n return ans\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles . The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2) . The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2) .", + "description_images": [], + "constraints": [ + "-10^4 <= ax1 <= ax2 <= 10^4", + "-10^4 <= ay1 <= ay2 <= 10^4", + "-10^4 <= bx1 <= bx2 <= 10^4", + "-10^4 <= by1 <= by2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput:45", + "image": "https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" + }, + { + "text": "Example 2: Input:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 35.02%) | Memory: 42.9 MB (Top 64.28%)\nclass Solution {\n public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int x1 = Math.max(ax1,bx1);\n int y1 = Math.max(ay1,by1);\n int x2 = Math.min(ax2,bx2);\n int y2 = Math.min(ay2,by2);\n\n int area = 0;\n int R1 = (ax2-ax1)*(ay2-ay1);\n int R2 = (bx2-bx1)*(by2-by1);\n area = R1 + R2;\n\n if(x2 > x1 && y2 > y1){\n int overlap = (x2-x1)*(y2-y1);\n area = area - overlap;\n }\n\n return area;\n }\n}", + "title": "223. Rectangle Area", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles . The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2) . The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2) .", + "description_images": [], + "constraints": [ + "-10^4 <= ax1 <= ax2 <= 10^4", + "-10^4 <= ay1 <= ay2 <= 10^4", + "-10^4 <= bx1 <= bx2 <= 10^4", + "-10^4 <= by1 <= by2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput:45", + "image": "https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" + }, + { + "text": "Example 2: Input:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 48.63%) | Memory: 14 MB (Top 27.24%)\nclass Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n def segment(ax1,ax2,bx1,bx2):\n return min(ax2,bx2) - max(ax1, bx1) if max(ax1, bx1) < min(ax2, bx2) else 0\n return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - segment(ax1,ax2,bx1,bx2)*segment(ay1,ay2,by1,by2)", + "title": "223. Rectangle Area", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D array of axis-aligned rectangles . Each rectangle[i] = [x i1 , y i1 , x i2 , y i2 ] denotes the i th rectangle where (x i1 , y i1 ) are the coordinates of the bottom-left corner , and (x i2 , y i2 ) are the coordinates of the top-right corner . Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once . Return the total area . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 200", + "rectanges[i].length == 4", + "0 <= x i1 , y i1 , x i2 , y i2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput:6\nExplanation:A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/06/rectangle_area_ii_pic.png" + }, + { + "text": "Example 2: Input:rectangles = [[0,0,1000000000,1000000000]]\nOutput:49\nExplanation:The answer is 1018modulo (109+ 7), which is 49.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 17.31%) | Memory: 42.3 MB (Top 86.54%)\nclass Solution {\n public int rectangleArea(int[][] rectangles) {\n int n = rectangles.length;\n Set coorx = new HashSet<>();\n Set coory = new HashSet<>();\n for (int[] rec : rectangles) {\n coorx.add(rec[0]); coorx.add(rec[2]);\n coory.add(rec[1]); coory.add(rec[3]);\n }\n\n Integer[] compressx = coorx.toArray(new Integer[0]);\n Arrays.sort(compressx);\n Integer[] compressy = coory.toArray(new Integer[0]);\n Arrays.sort(compressy);\n\n Map mapx = new HashMap<>();\n for(int i = 0; i < compressx.length; i++) {\n mapx.put(compressx[i], i);\n }\n Map mapy = new HashMap<>();\n for(int i = 0; i < compressy.length; i++) {\n mapy.put(compressy[i], i);\n }\n\n boolean[][] grid = new boolean[compressx.length][compressy.length];\n for (int[] rec: rectangles) {\n for (int x = mapx.get(rec[0]); x < mapx.get(rec[2]); x++) {\n for (int y = mapy.get(rec[1]); y < mapy.get(rec[3]); y++) {\n grid[x][y] = true;\n }\n }\n }\n\n long res = 0L;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j]) {\n res += (long)(compressx[i + 1] - compressx[i]) * (compressy[j + 1] - compressy[j]);\n }\n }\n }\n res %= 1000000007;\n return (int)res;\n }\n }", + "title": "850. Rectangle Area II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D array of axis-aligned rectangles . Each rectangle[i] = [x i1 , y i1 , x i2 , y i2 ] denotes the i th rectangle where (x i1 , y i1 ) are the coordinates of the bottom-left corner , and (x i2 , y i2 ) are the coordinates of the top-right corner . Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once . Return the total area . Since the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 200", + "rectanges[i].length == 4", + "0 <= x i1 , y i1 , x i2 , y i2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput:6\nExplanation:A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/06/rectangle_area_ii_pic.png" + }, + { + "text": "Example 2: Input:rectangles = [[0,0,1000000000,1000000000]]\nOutput:49\nExplanation:The answer is 1018modulo (109+ 7), which is 49.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 133 ms (Top 41.78%) | Memory: 13.9 MB (Top 70.89%)\nclass SegmentTree:\n def __init__(self, xs):\n #cnts[v] means that the node's interval is active\n self.cnts = defaultdict(int)\n #total[v] length of active intervals that are contained the node's interval\n self.total = defaultdict(int)\n self.xs = xs\n\n def update(self, v, tl, tr, l, r, h):\n #node interval [tl,tr] does not overlap with query interval [l,r]\n if r < tl or tr < l: return\n #node interval is included in the query interval\n if l <= tl and tr <= r:\n self.cnts[v] += h\n else:\n tm = (tl + tr)//2\n self.update(v*2, tl, tm, l, r, h)\n self.update(v*2+1, tm+1, tr, l, r, h)\n #node interval is included in the active interval\n if self.cnts[v] > 0:\n self.total[v] = self.xs[tr + 1] - self.xs[tl]\n else:\n self.total[v] = self.total[v*2] + self.total[v*2+1]\n return self.total[v]\n\nclass Solution:\n def rectangleArea(self, rectangles):\n #index i means the interval from xs[i] to xs[i+1]\n xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))\n xs_i = {x:i for i, x in enumerate(xs)}\n st = SegmentTree(xs)\n L = []\n for x1, y1, x2, y2 in rectangles:\n L.append([y1, 1, x1, x2])\n L.append([y2, -1, x1, x2])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for y, open_close, x1, x2 in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n #one index corresponds to one interval, that's why we use xs_i[x2]-1 instead of xs_i[x2]\n st.update(1, 0, len(xs) - 1, xs_i[x1], xs_i[x2]-1, open_close)\n cur_x_sum = st.total[1]\n\n return area % (10 ** 9 + 7)", + "title": "850. Rectangle Area II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2] , where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive . To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2 , return true if they overlap, otherwise return false .", + "description_images": [], + "constraints": [ + "rec1.length == 4", + "rec2.length == 4", + "-10^9 <= rec1[i], rec2[i] <= 10^9", + "rec1 and rec2 represent a valid rectangle with a non-zero area." + ], + "examples": [ + { + "text": "Example 1: Input:rec1 = [0,0,2,2], rec2 = [1,1,3,3]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:rec1 = [0,0,1,1], rec2 = [1,0,2,1]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:rec1 = [0,0,1,1], rec2 = [2,2,3,3]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Rectangle Overlap\n// https://leetcode.com/problems/rectangle-overlap/\n\nclass Solution {\n public boolean isRectangleOverlap(int[] rec1, int[] rec2) {\n int x1 = rec1[0];\n int y1 = rec1[1];\n int x2 = rec1[2];\n int y2 = rec1[3];\n int x3 = rec2[0];\n int y3 = rec2[1];\n int x4 = rec2[2];\n int y4 = rec2[3];\n if (x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3) {\n return false;\n }\n return true; \n }\n}\n", + "title": "836. Rectangle Overlap", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2] , where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive . To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2 , return true if they overlap, otherwise return false .", + "description_images": [], + "constraints": [ + "rec1.length == 4", + "rec2.length == 4", + "-10^9 <= rec1[i], rec2[i] <= 10^9", + "rec1 and rec2 represent a valid rectangle with a non-zero area." + ], + "examples": [ + { + "text": "Example 1: Input:rec1 = [0,0,2,2], rec2 = [1,1,3,3]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:rec1 = [0,0,1,1], rec2 = [1,0,2,1]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:rec1 = [0,0,1,1], rec2 = [2,2,3,3]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n if (rec2[1]>=rec1[3] or rec2[0]>=rec1[2] or rec2[3]<=rec1[1] or rec1[0]>=rec2[2]) :\n \n return False\n else:\n return True\n", + "title": "836. Rectangle Overlap", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of strings words ( 0-indexed ). In one operation, pick two distinct indices i and j , where words[i] is a non-empty string, and move any character from words[i] to any position in words[j] . Return true if you can make every string in words equal using any number of operations , and false otherwise .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"aabc\",\"bc\"]\nOutput:true\nExplanation:Move the first 'a' inwords[1] to the front of words[2],\nto makewords[1]= \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so returntrue.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"a\"]\nOutput:false\nExplanation:It is impossible to make all the strings equal using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean makeEqual(String[] words) {\n \n HashMap map = new HashMap<>();\n \n for(String str : words){\n \n for(int i=0; i bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map_.items():\n if (v%n) != 0:\n return False\n return True\n", + "title": "1897. Redistribute Characters to Make All Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr . You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "arr.length is even.", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,3,3,3,5,5,5,2,2,7]\nOutput:2\nExplanation:Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,7,7,7,7,7]\nOutput:1\nExplanation:The only possible set you can choose is {7}. This will make the new array empty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSetSize(int[] arr) {\n int size=arr.length;\n int deletedSize=0;\n int countIteration=0;\n Map hashMap=new HashMap<>();\n Queue> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());\n \n for(int i=0;i entry:hashMap.entrySet())\n {\n queue.add(entry);\n }\n \n while(!queue.isEmpty())\n {\n int totalOccurence=queue.poll().getValue();\n deletedSize+=totalOccurence; \n countIteration++;\n if(deletedSize>=size/2)\n return countIteration;\n \n }\n return countIteration;\n }\n}\n", + "title": "1338. Reduce Array Size to The Half", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array arr . You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed .", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "arr.length is even.", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,3,3,3,5,5,5,2,2,7]\nOutput:2\nExplanation:Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,7,7,7,7,7]\nOutput:1\nExplanation:The only possible set you can choose is {7}. This will make the new array empty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n n = len(arr)\n half = n // 2\n \n c = Counter(arr)\n s = 0\n ans = 0\n \n for num, occurances in c.most_common():\n s += occurances\n ans += 1\n if s >= half:\n return ans\n return ans\n", + "title": "1338. Reduce Array Size to The Half", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i] . Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation . Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.", + "description_images": [], + "constraints": [ + "n == satisfaction.length", + "1 <= n <= 500", + "-1000 <= satisfaction[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:satisfaction = [-1,-8,0,5,-9]\nOutput:14\nExplanation:After Removing the second and last dish, the maximum totallike-time coefficientwill be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.", + "image": null + }, + { + "text": "Example 2: Input:satisfaction = [4,3,2]\nOutput:20\nExplanation:Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)", + "image": null + }, + { + "text": "Example 3: Input:satisfaction = [-1,-4,-5]\nOutput:0\nExplanation:People do not like the dishes. No dish is prepared.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 80.60%) | Memory: 41.7 MB (Top 87.57%)\nclass Solution {\n public int maxSatisfaction(int[] satisfaction) {\n Arrays.sort(satisfaction);\n if(satisfaction[satisfaction.length-1] <= 0){\n return 0;\n }\n\n int res = 0;\n int beforeSum = 0;\n for(int i = satisfaction.length-1; i>=0; i--){\n int currNum = satisfaction[i];\n beforeSum += currNum;\n if(beforeSum >= 0){\n res += beforeSum;\n }else{\n return res;\n }\n }\n\n return res;\n }\n}", + "title": "1402. Reducing Dishes", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i] . Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation . Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.", + "description_images": [], + "constraints": [ + "n == satisfaction.length", + "1 <= n <= 500", + "-1000 <= satisfaction[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:satisfaction = [-1,-8,0,5,-9]\nOutput:14\nExplanation:After Removing the second and last dish, the maximum totallike-time coefficientwill be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.", + "image": null + }, + { + "text": "Example 2: Input:satisfaction = [4,3,2]\nOutput:20\nExplanation:Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)", + "image": null + }, + { + "text": "Example 3: Input:satisfaction = [-1,-4,-5]\nOutput:0\nExplanation:People do not like the dishes. No dish is prepared.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort(reverse=True)\n maxSatisfaction = dishSum = 0\n\n for dish in satisfaction:\n dishSum += dish\n if dishSum <= 0:\n break\n maxSatisfaction += dishSum\n \n return maxSatisfaction", + "title": "1402. Reducing Dishes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,1,3]\nOutput:3\nExplanation:It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:0\nExplanation:All elements in nums are already equal.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2,3]\nOutput:4\nExplanation:It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reductionOperations(int[] nums) {\n Map valMap = new TreeMap<>(Collections.reverseOrder());\n\n for (int i=0; i entry : valMap.entrySet()) {\n opsCount += entry.getValue() * (--mapSize);\n }\n return opsCount;\n }\n}\n", + "title": "1887. Reduction Operations to Make the Array Elements Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,1,3]\nOutput:3\nExplanation:It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:0\nExplanation:All elements in nums are already equal.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2,3]\nOutput:4\nExplanation:It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 717 ms (Top 99.99%) | Memory: 24.60 MB (Top 36.15%)\n\nclass Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n ans = val = 0\n nums.sort()\n for i in range(1, len(nums)): \n if nums[i-1] < nums[i]: val += 1\n ans += val\n return ans \n", + "title": "1887. Reduction Operations to Make the Array Elements Equal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput:[1,4]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.63%) | Memory: 43.5 MB (Top 75.35%)\nclass Solution {\n public int[] findRedundantConnection(int[][] edges) {\n UnionFind uf = new UnionFind(edges.length);\n for (int[] edge : edges) {\n if (!uf.union(edge[0], edge[1])) {\n return new int[]{edge[0], edge[1]};\n }\n }\n return null;\n }\n\n private class UnionFind {\n int[] rank;\n int[] root;\n\n UnionFind(int n) {\n rank = new int[n + 1];\n root = new int[n + 1];\n for (int i = 1; i <= n; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n int find(int x) {\n if (x == root[x]) {\n return x;\n }\n return root[x] = find(root[x]);\n }\n\n boolean union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = root[rootX];\n } else if (rank[rootY] > rank[rootX]) {\n root[rootX] = root[rootY];\n } else {\n root[rootY] = root[rootX];\n rank[rootX]++;\n }\n return true;\n }\n return false;\n }\n }\n}", + "title": "684. Redundant Connection", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput:[1,4]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class UnionFind:\n \n def __init__(self, size):\n \n self.parent = [-1 for _ in range(size)]\n self.rank = [-1 for _ in range(size)]\n \n def find(self, i):\n \n if self.parent[i] == -1:\n return i\n \n k = self.find(self.parent[i])\n self.parent[i] = k\n return k\n \n def union(self, x, y):\n \n x = self.find(x)\n y = self.find(y)\n \n if x == y:\n return -1\n else:\n \n if self.rank[x] > self.rank[y]:\n self.parent[y] = x\n \n elif self.rank[x] < self.rank[y]:\n self.parent[x] = y\n \n else:\n self.rank[x] += 1\n self.parent[y] = x\n\nclass Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n \n vertex_set = set()\n \n for edge in edges:\n vertex_set.add(edge[0])\n vertex_set.add(edge[1])\n \n \n union_find = UnionFind(len(vertex_set))\n \n for edge in edges:\n \n new_edge = [edge[0]-1, edge[1]-1]\n \n if union_find.union(new_edge[0], new_edge[1]) == -1:\n return edge\n \n return []\n\n", + "title": "684. Redundant Connection", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n ), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n , and was not an edge that already existed. The resulting graph is given as a 2D-array of edges . Each element of edges is a pair [u i , v i ] that represents a directed edge connecting nodes u i and v i , where u i is a parent of child v i . Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes . If there are multiple answers, return the answer that occurs last in the given 2D-array.", + "description_images": [], + "constraints": [ + "n == edges.length", + "3 <= n <= 1000", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "u i != v i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\nOutput:[4,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 24.18%) | Memory: 44.9 MB (Top 16.79%)\nclass Solution {\n int[] dsu;\n public int[] findRedundantDirectedConnection(int[][] edges) {\n int n=edges.length;\n int[] parent=new int[n+1];\n Arrays.fill(parent,-1);\n\n int[] e2=null;\n int[] e1=null;\n boolean twopt=false;\n\n for(int[] edge: edges){\n\n int from=edge[0];\n int to=edge[1];\n\n if(parent[to]==-1){\n parent[to]=from;\n }else{\n twopt=true;\n e2=edge;\n e1=new int[]{parent[to],to};\n break;\n }\n }\n\n dsu=new int[edges.length+1];\n for(int i=0;i<=edges.length;i++){\n dsu[i]=i;\n }\n if(twopt==false){\n int[] res=null;\n\n for(int[] edge: edges){\n int from=edge[0];\n int to=edge[1];\n\n int fromlead=find(from);\n if(fromlead==to){\n res=edge;\n break;\n }else{\n dsu[to]=fromlead;\n }\n }\n return res;\n }else{\n boolean iscycle=false;\n for(int[] edge: edges){\n if(edge==e2) continue;\n int from =edge[0];\n int to=edge[1];\n\n int fromlead=find(from);\n\n if(fromlead==to){\n iscycle=true;\n break;\n }else{\n dsu[to]=fromlead;\n }\n }\n if(iscycle==true){\n return e1;\n }else{\n return e2;\n }\n }\n\n }\n public int find(int x){\n if(dsu[x]==x) return x;\n return dsu[x]=find(dsu[x]);\n }\n}", + "title": "685. Redundant Connection II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n ), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n , and was not an edge that already existed. The resulting graph is given as a 2D-array of edges . Each element of edges is a pair [u i , v i ] that represents a directed edge connecting nodes u i and v i , where u i is a parent of child v i . Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes . If there are multiple answers, return the answer that occurs last in the given 2D-array.", + "description_images": [], + "constraints": [ + "n == edges.length", + "3 <= n <= 1000", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "u i != v i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\nOutput:[4,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 118 ms (Top 30.98%) | Memory: 14.6 MB (Top 46.10%)\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n # THREE DIFFERENT TYPES OF REDUNDANT TREES CAN EXISIT IDENTIFY THOSE (CYCLE,NOCYCLE,INDEGREE2)\n # CAN BE SOLVED USING DSU OR DFS\n class DSU:\n def __init__(self,n):\n self.parent = [i for i in range(1005)]\n def find(self,node):\n if self.parent[node] == node:\n return node\n self.parent[node] = self.find(self.parent[node])\n return self.parent[node]\n def union(self,node1,node2):\n p1 = self.find(node1)\n p2 = self.find(node2)\n if p1 != p2:\n self.parent[p1] = p2\n def isConnected(self,node1,node2):\n return self.find(node1) == self.find(node2)\n def isValidTree(edges,edge,n):\n d = DSU(n)\n for e in edges:\n if e == edge:\n continue\n d.union(e[0],e[1])\n return d.isConnected(edge[0],edge[1])\n\n indegree = []\n count = defaultdict(int)\n for i,j in edges:\n count[j] = count.get(j,0)+1\n n = len(edges)\n for i in range(n):\n if count[edges[i][1]] == 2:\n indegree += [i]\n if len(indegree) != 0:\n if isValidTree(edges,edges[indegree[-1]],n):\n return edges[indegree[-1]]\n return edges[indegree[0]]\n else:\n d2 = DSU(n)\n for e in edges:\n if d2.isConnected(e[0],e[1]):\n return e\n d2.union(e[0],e[1])\n\n# def dfs(node):\n# if node in seen:\n# return False\n# seen.add(node)\n# for nb in g[node]:\n# if not dfs(nb):\n# return False\n# return True\n# g = defaultdict(list)\n# v = defaultdict(int)\n# total = set()\n# for i,j in edges:\n# g[i] = g.get(i,[]) + [j]\n# v[j] = v.get(j,0) + 1\n# total.add(i)\n# total.add(j)\n# for e in edges[::-1]:\n# g[e[0]].remove(e[1])\n# v[e[1]] -= 1\n# for root in total:\n# seen = set()\n# if v[root] == 0 and dfs(root) and len(seen) == len(total):\n# return e\n\n# v[e[1]] += 1\n# g[e[0]].append(e[1])\n# return [-1,-1]", + "title": "685. Redundant Connection II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a date string in the form Day Month Year , where: Convert the date string to the format YYYY-MM-DD , where:", + "description_images": [], + "constraints": [ + "Day is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"} .", + "Month is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"} .", + "Year is in the range [1900, 2100] ." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"20th Oct 2052\"\nOutput:\"2052-10-20\"", + "image": null + }, + { + "text": "Example 2: Input:date = \"6th Jun 1933\"\nOutput:\"1933-06-06\"", + "image": null + }, + { + "text": "Example 3: Input:date = \"26th May 1960\"\nOutput:\"1960-05-26\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reformatDate(String date) {\n int len = date.length();\n \n String[] monthArray = {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"};\n \n String year = date.substring(len - 4);\n int month = Arrays.asList(monthArray).indexOf(date.substring(len - 8, len - 5)) + 1;\n String day = date.substring(0, len - 11);\n \n StringBuffer sb = new StringBuffer();\n \n sb.append(year + \"-\");\n \n if(month < 10)\n sb.append(\"0\" + month + \"-\");\n else\n sb.append(month + \"-\");\n \n if(day.length() == 1) \n sb.append(\"0\" + day);\n else\n sb.append(day);\n \n return sb.toString();\n }\n}\n", + "title": "1507. Reformat Date", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a date string in the form Day Month Year , where: Convert the date string to the format YYYY-MM-DD , where:", + "description_images": [], + "constraints": [ + "Day is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"} .", + "Month is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"} .", + "Year is in the range [1900, 2100] ." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"20th Oct 2052\"\nOutput:\"2052-10-20\"", + "image": null + }, + { + "text": "Example 2: Input:date = \"6th Jun 1933\"\nOutput:\"1933-06-06\"", + "image": null + }, + { + "text": "Example 3: Input:date = \"26th May 1960\"\nOutput:\"1960-05-26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 31 ms (Top 93.30%) | Memory: 13.8 MB (Top 98.50%)\nclass Solution:\n def reformatDate(self, date: str) -> str:\n\n m_dict_={\"Jan\":\"01\", \"Feb\":\"02\", \"Mar\":\"03\", \"Apr\":\"04\", \"May\":\"05\", \"Jun\":\"06\", \"Jul\":\"07\", \"Aug\":\"08\", \"Sep\":\"09\", \"Oct\":\"10\", \"Nov\":\"11\", \"Dec\":\"12\"}\n\n day=date[:-11]\n\n if len(day)==1:\n day=\"0\"+day\n\n return(date[-4:] + \"-\" + m_dict_[date[-8:-5]] + \"-\" + day)", + "title": "1507. Reformat Date", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a phone number as a string number . number consists of digits, spaces ' ' , and/or dashes '-' . You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting.", + "description_images": [], + "constraints": [ + "2 digits: A single block of length 2.", + "3 digits: A single block of length 3.", + "4 digits: Two blocks of length 2 each." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"1-23-45 6\"\nOutput:\"123-456\"\nExplanation:The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"123 4-567\"\nOutput:\"123-45-67\"\nExplanation:The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"123 4-5678\"\nOutput:\"123-456-78\"\nExplanation:The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 38.91%) | Memory: 42.8 MB (Top 36.01%)\nclass Solution {\n String modifiedNumber=\"\";\n public String reformatNumber(String number) {\n modifiedNumber=number.replace(\" \",\"\");\n modifiedNumber=modifiedNumber.replace(\"-\",\"\");\n int l=modifiedNumber.length();\n if(l<=3){\n return modifiedNumber;\n } else if(l==4){\n return modifiedNumber.substring(0,2)+\"-\"+ modifiedNumber.substring(2,4);\n } else {\n modifiedNumber=modifiedNumber.substring(0,3)+\"-\"+reformatNumber(modifiedNumber.substring(3,l));\n }\n return modifiedNumber;\n }\n}", + "title": "1694. Reformat Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a phone number as a string number . number consists of digits, spaces ' ' , and/or dashes '-' . You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting.", + "description_images": [], + "constraints": [ + "2 digits: A single block of length 2.", + "3 digits: A single block of length 3.", + "4 digits: Two blocks of length 2 each." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"1-23-45 6\"\nOutput:\"123-456\"\nExplanation:The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"123 4-567\"\nOutput:\"123-45-67\"\nExplanation:The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"123 4-5678\"\nOutput:\"123-456-78\"\nExplanation:The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reformatNumber(self, number: str) -> str:\n s = number.replace(\" \", \"\").replace(\"-\", \"\")\n pieces = list()\n while s:\n if len(s) == 2:\n pieces.append(s)\n break\n elif len(s) == 4:\n pieces.append(s[:2])\n pieces.append(s[2:])\n break\n else:\n pieces.append(s[:3])\n s = s[3:]\n return \"-\".join(pieces)\n", + "title": "1694. Reformat Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an alphanumeric string s . ( Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a0b1c2\"\nOutput:\"0a1b2c\"\nExplanation:No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"\"\nExplanation:\"leetcode\" has only characters so we cannot separate them by digits.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1229857369\"\nOutput:\"\"\nExplanation:\"1229857369\" has only digits so we cannot separate them by characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reformat(String s) {\n \n List ch = new ArrayList<>();\n List d = new ArrayList<>();\n \n for(char c : s.toCharArray()){\n if(c >= 'a' && c <= 'z')ch.add(c);\n else d.add(c);\n }\n \n if(Math.abs(d.size() - ch.size()) > 1) return \"\";\n \n StringBuilder str = new StringBuilder();\n \n for(int i = 0; i < s.length(); i++){\n \n if(!ch.isEmpty() || !d.isEmpty()){\n if(ch.size() > d.size())\n str.append(appender(ch,d));\n else \n str.append(appender(d,ch));\n }\n else{\n break;\n }\n }\n \n return new String(str);\n \n }\n \n public String appender(List first,List second){\n \n StringBuilder str = new StringBuilder();\n \n if(!first.isEmpty()){\n str.append(first.get(0));\n first.remove(0);\n }\n if(!second.isEmpty()){\n str.append(second.get(0));\n second.remove(0);\n }\n \n return new String(str);\n }\n}\n", + "title": "1417. Reformat The String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an alphanumeric string s . ( Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a0b1c2\"\nOutput:\"0a1b2c\"\nExplanation:No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"\"\nExplanation:\"leetcode\" has only characters so we cannot separate them by digits.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1229857369\"\nOutput:\"\"\nExplanation:\"1229857369\" has only digits so we cannot separate them by characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reformat(self, s: str) -> str:\n # Store the alphabets and the numerics from the string in a seperat arrays\n alpha = []\n num = []\n # Initiate a res variable to store the resultant string\n res = ''\n \n for i in s:\n if i.isalpha():\n alpha.append(i)\n else:\n num.append(i)\n \n # It's not possible to create a permutation if the absolute difference b/w len(alpha) and len(num) > 1.\n if abs(len(alpha)-len(num)) > 1: return ''\n \n # Use Zip to create list of tuples.\n # For ex:- if alpha = ['a','b'] and num = ['1', '2'] then,\n # zip(alpha, num) = [('a', '1'), ('b', '2')]\n for ch, n in zip(alpha, num):\n res += (ch+n)\n \n if len(alpha) > len(num):\n res += alpha[-1]\n if len(num) > len(alpha):\n res = num[-1] + res\n \n return res\n", + "title": "1417. Reformat The String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/' , '\\' , or blank space ' ' . These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions . Note that backslash characters are escaped, so a '\\' is represented as '\\\\' .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 30", + "grid[i][j] is either '/' , '\\' , or ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\" /\",\"/ \"]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2018/12/15/1.png" + }, + { + "text": "Example 2: Input:grid = [\" /\",\" \"]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2018/12/15/2.png" + }, + { + "text": "Example 3: Input:grid = [\"/\\\\\",\"\\\\/\"]\nOutput:5\nExplanation:Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/4.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n int[] rank;\n \n public int regionsBySlashes(String[] grid) {\n parent = new int[4*grid.length*grid.length];\n rank = new int[4*grid.length*grid.length];\n \n for(int i=0;i 0){\n int obno = (i-1) * grid.length + j;\n unionHelper(4*bno + 0 , 4*obno + 2);\n }\n \n if(j > 0){\n int obno = i * grid.length + (j-1);\n unionHelper(4*bno + 3 , 4*obno + 1);\n }\n \n }\n }\n \n int count = 0;\n \n for(int i=0;i int:\n n=len(grid)\n dots=n+1\n par=[0]*(dots*dots)\n rank=[0]*(dots*dots)\n self.count=1\n\n def find(x):\n if par[x]==x:\n return x\n temp=find(par[x])\n par[x]=temp\n return temp\n def union(x,y):\n lx=find(x)\n ly=find(y)\n if lx!=ly:\n if rank[lx]>rank[ly]:\n par[ly]=lx\n elif rank[lx] 1:\n dp[0][c] = dp[0][c-2]\n for r in range(1,n+1):\n for c in range(1,m+1):\n if p[c-1] == s[r-1] or p[c-1] == '.':\n dp[r][c] = dp[r-1][c-1]\n elif c > 1 and p[c-1] == '*':\n if p[c-2] =='.' or s[r-1]==p[c-2]:\n dp[r][c] =dp[r][c-2] or dp[r-1][c]\n else:\n dp[r][c] = dp[r][c-2]\n return dp[n][m]\n", + "title": "10. Regular Expression Matching", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array score of size n , where score[i] is the score of the i th athlete in a competition. All the scores are guaranteed to be unique . The athletes are placed based on their scores, where the 1 st place athlete has the highest score, the 2 nd place athlete has the 2 nd highest score, and so on. The placement of each athlete determines their rank: Return an array answer of size n where answer[i] is the rank of the i th athlete.", + "description_images": [], + "constraints": [ + "The 1 st place athlete's rank is \"Gold Medal\" .", + "The 2 nd place athlete's rank is \"Silver Medal\" .", + "The 3 rd place athlete's rank is \"Bronze Medal\" .", + "For the 4 th place to the n th place athlete, their rank is their placement number (i.e., the x th place athlete's rank is \"x\" )." + ], + "examples": [ + { + "text": "Example 1: Input:score = [5,4,3,2,1]\nOutput:[\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\nExplanation:The placements are [1st, 2nd, 3rd, 4th, 5th].", + "image": null + }, + { + "text": "Example 2: Input:score = [10,3,8,9,4]\nOutput:[\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\nExplanation:The placements are [1st, 5th, 3rd, 2nd, 4th].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String[] findRelativeRanks(int[] score) {\n String[] res = new String[score.length];\n TreeMap map = new TreeMap<>();\n for(int i = 0; i < score.length; i++) map.put(score[i], i);\n int rank = score.length;\n for(Map.Entry p: map.entrySet()){\n if(rank == 1) res[p.getValue()] = \"Gold Medal\";\n else if(rank == 2) res[p.getValue()] = \"Silver Medal\";\n else if(rank == 3) res[p.getValue()] = \"Bronze Medal\";\n else res[p.getValue()] = String.valueOf(rank);\n rank--;\n }\n return res;\n }\n}\n", + "title": "506. Relative Ranks", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array score of size n , where score[i] is the score of the i th athlete in a competition. All the scores are guaranteed to be unique . The athletes are placed based on their scores, where the 1 st place athlete has the highest score, the 2 nd place athlete has the 2 nd highest score, and so on. The placement of each athlete determines their rank: Return an array answer of size n where answer[i] is the rank of the i th athlete.", + "description_images": [], + "constraints": [ + "The 1 st place athlete's rank is \"Gold Medal\" .", + "The 2 nd place athlete's rank is \"Silver Medal\" .", + "The 3 rd place athlete's rank is \"Bronze Medal\" .", + "For the 4 th place to the n th place athlete, their rank is their placement number (i.e., the x th place athlete's rank is \"x\" )." + ], + "examples": [ + { + "text": "Example 1: Input:score = [5,4,3,2,1]\nOutput:[\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\nExplanation:The placements are [1st, 2nd, 3rd, 4th, 5th].", + "image": null + }, + { + "text": "Example 2: Input:score = [10,3,8,9,4]\nOutput:[\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\nExplanation:The placements are [1st, 5th, 3rd, 2nd, 4th].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 162 ms (Top 33.91%) | Memory: 15.3 MB (Top 22.09%)\nclass Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n scores_ids = []\n for i in range(len(score)):\n scores_ids.append((score[i], i))\n scores_ids.sort(reverse=True)\n\n ans = [0] * len(scores_ids)\n for i in range(len(scores_ids)):\n ans[scores_ids[i][1]] = str(i+1)\n\n try:\n ans[scores_ids[0][1]] = \"Gold Medal\"\n ans[scores_ids[1][1]] = \"Silver Medal\"\n ans[scores_ids[2][1]] = \"Bronze Medal\"\n except:\n pass\n\n return ans\n", + "title": "506. Relative Ranks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2 . Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 1000", + "0 <= arr1[i], arr2[i] <= 1000", + "All the elements of arr2 are distinct .", + "Each arr2[i] is in arr1 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\nOutput:[2,2,2,1,4,3,3,9,6,7,19]", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\nOutput:[22,28,8,6,17,44]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 28.58%) | Memory: 43 MB (Top 43.79%)\nclass Solution {\n public int[] relativeSortArray(int[] arr1, int[] arr2) {\n Map map = new TreeMap();\n for(int i = 0; i List[int]:\n\t\t# initialise a dictionary since we're going to want to count the occurences of each element in arr1\n dic = {}\n\t\t# this loop populates the dictionary with the number of occurences for each element\n for elem in arr1:\n if dic.get(elem) is None:\n dic[elem] = 1\n else:\n dic[elem] = dic[elem] + 1\n\t\t# initialise a new list to store the values which exist in both arr2 and arr1\n output = []\n\t\t# populate output with the elements multiplied by their occurences (e.g. [1]*2 = [1, 1])\n for elem in arr2:\n output += [elem]*dic[elem]\n\t\t# initialise a new list to store the elements which are in arr1 but not arr2\n extra_output = []\n\t\t# populate extra_output with these elements multiplied by their occurences. \n\t\t# Note: set(arr1)-set(arr2) provides us with the set of numbers which exist in arr1 but not in arr2\n for elem in set(arr1)-set(arr2):\n extra_output += [elem]*dic[elem]\n\t\t# return the first list and the sorted second list\n return output + sorted(extra_output)\n", + "title": "1122. Relative Sort Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It can be proven that the answer is unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbaca\"\nOutput:\"ca\"\nExplanation:For example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"azxxzy\"\nOutput:\"ay\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 46.58%) | Memory: 54.8 MB (Top 52.34%)\nclass Solution {\n public String removeDuplicates(String s) {\n Stack st=new Stack<>();\n int i=s.length()-1;\n while(i>=0)\n {\n char ch=s.charAt(i);\n if(st.size()>0 && ch==st.peek())\n {\n st.pop();\n }\n else\n {\n st.push(ch);\n }\n i--;\n }\n StringBuilder ans=new StringBuilder(\"\");\n while(!st.isEmpty())\n {\n ans.append(st.pop());\n }\n return ans.toString();\n }\n}", + "title": "1047. Remove All Adjacent Duplicates In String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It can be proven that the answer is unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbaca\"\nOutput:\"ca\"\nExplanation:For example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"azxxzy\"\nOutput:\"ay\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 69 ms (Top 68.51%) | Memory: 18.40 MB (Top 6.96%)\n\nclass Solution:\n def removeDuplicates(self, S: str) -> str:\n stack = []\n for char in S:\n if stack and stack[-1] == char:\n stack.pop()\n else:\n stack.append(char)\n \n return ''.join(stack)\n", + "title": "1047. Remove All Adjacent Duplicates In String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and an integer k , a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It is guaranteed that the answer is unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "2 <= k <= 10^4", + "s only contains lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", k = 2\nOutput:\"abcd\"\nExplanation:There's nothing to delete.", + "image": null + }, + { + "text": "Example 2: Input:s = \"deeedbbcccbdaa\", k = 3\nOutput:\"aa\"\nExplanation:First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"pbbcggttciiippooaais\", k = 2\nOutput:\"ps\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 71 ms (Top 53.30%) | Memory: 48.3 MB (Top 81.34%)\nclass Solution\n{\n public String removeDuplicates(String s, int k)\n {\n int i = 0 ;\n StringBuilder newString = new StringBuilder(s) ;\n int[] count = new int[newString.length()] ;\n while( i < newString.length() )\n {\n if( i == 0 || newString.charAt(i) != newString.charAt( i - 1 ) )\n {\n count[i] = 1 ;\n }\n else\n {\n count[i] = count[ i - 1 ] + 1 ;\n if( count[i] == k )\n {\n newString.delete( i - k + 1 , i + 1 ) ;\n i = i - k ;\n }\n }\n i++ ;\n }\n return newString.toString() ;\n }\n}", + "title": "1209. Remove All Adjacent Duplicates in String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s and an integer k , a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It is guaranteed that the answer is unique .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "2 <= k <= 10^4", + "s only contains lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", k = 2\nOutput:\"abcd\"\nExplanation:There's nothing to delete.", + "image": null + }, + { + "text": "Example 2: Input:s = \"deeedbbcccbdaa\", k = 3\nOutput:\"aa\"\nExplanation:First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"pbbcggttciiippooaais\", k = 2\nOutput:\"ps\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 309 ms (Top 14.94%) | Memory: 18.7 MB (Top 36.81%)\nclass Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n stack=[]\n res=''\n for i in range(len(s)):\n if len(stack)==0:\n stack.append([s[i],1])\n elif stack[-1][0]==s[i]:\n stack[-1][1]=stack[-1][1]+1\n else:\n stack.append([s[i],1])\n if stack[-1][1]==k:\n stack.pop()\n for i in range(len(stack)):\n res+=stack[i][0]*stack[i][1]\n return res", + "title": "1209. Remove All Adjacent Duplicates in String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and part , perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "Find the leftmost occurrence of the substring part and remove it from s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"daabcbaabcbc\", part = \"abc\"\nOutput:\"dab\"\nExplanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"axxxxyyyyb\", part = \"xy\"\nOutput:\"ab\"\nExplanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 38.9%) | Memory: 43.67 MB (Top 34.2%)\n\nclass Solution {\n public String removeOccurrences(String s, String part) {\n // s.replace(part,\"\");\n // System.out.println(s);\n \n while(s.contains(part))\n {\n s=s.replaceFirst(part,\"\");\n }\n return s;\n }\n}", + "title": "1910. Remove All Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and part , perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part . A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "Find the leftmost occurrence of the substring part and remove it from s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"daabcbaabcbc\", part = \"abc\"\nOutput:\"dab\"\nExplanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"axxxxyyyyb\", part = \"xy\"\nOutput:\"ab\"\nExplanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n n=len(part)\n while part in s:\n i=s.index(part)\n s=s[:i]+s[i+n:]\n return s\n", + "title": "1910. Remove All Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1 ), remove them and get k * k points. Return the maximum points you can get .", + "description_images": [], + "constraints": [ + "1 <= boxes.length <= 100", + "1 <= boxes[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [1,3,2,2,2,3,4,3,1]\nOutput:23\nExplanation:[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)", + "image": null + }, + { + "text": "Example 2: Input:boxes = [1,1,1]\nOutput:9", + "image": null + }, + { + "text": "Example 3: Input:boxes = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeBoxes(int[] boxes) {\n int n = boxes.length;\n int[][][] dp = new int[n][n][n];\n for (int i = n-1; i >= 0; i--){\n for (int j = i; j < n; j++){\n for (int k = 0; k < n; k++){\n for (int m = i; m <= j; m++){\n if (boxes[m] == boxes[i]){\n dp[i][j][k]=Math.max(dp[i][j][k], (m-1= 1 ), remove them and get k * k points. Return the maximum points you can get .", + "description_images": [], + "constraints": [ + "1 <= boxes.length <= 100", + "1 <= boxes[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [1,3,2,2,2,3,4,3,1]\nOutput:23\nExplanation:[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)", + "image": null + }, + { + "text": "Example 2: Input:boxes = [1,1,1]\nOutput:9", + "image": null + }, + { + "text": "Example 3: Input:boxes = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeBoxes(self, B):\n \n @lru_cache(None)\n def dp(i, j, k):\n if i > j: return 0\n indx = [m for m in range(i+1, j+1) if B[m] == B[i]]\n ans = (k+1)**2 + dp(i+1, j, 0)\n return max([ans] + [dp(i+1, m-1, 0) + dp(m, j, k+1) for m in indx]) \n \n return dp(0, len(B)-1, 0)", + "title": "546. Remove Boxes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B' . You are given a string colors of length n where colors[i] is the color of the i th piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first . Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins .", + "description_images": [], + "constraints": [ + "Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A' . She is not allowed to remove pieces that are colored 'B' .", + "Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B' . He is not allowed to remove pieces that are colored 'A' .", + "Alice and Bob cannot remove pieces from the edge of the line.", + "If a player cannot make a move on their turn, that player loses and the other player wins ." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"AAABABB\"\nOutput:true\nExplanation:AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.", + "image": null + }, + { + "text": "Example 2: Input:colors = \"AA\"\nOutput:false\nExplanation:Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.", + "image": null + }, + { + "text": "Example 3: Input:colors = \"ABBBBBBBAAA\"\nOutput:false\nExplanation:ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 5.50%) | Memory: 52.8 MB (Top 84.58%)\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int cntA=0,cntB=0;\n for(int i=1;icntB;\n }\n}", + "title": "2038. Remove Colored Pieces if Both Neighbors are the Same Color", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B' . You are given a string colors of length n where colors[i] is the color of the i th piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first . Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins .", + "description_images": [], + "constraints": [ + "Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A' . She is not allowed to remove pieces that are colored 'B' .", + "Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B' . He is not allowed to remove pieces that are colored 'A' .", + "Alice and Bob cannot remove pieces from the edge of the line.", + "If a player cannot make a move on their turn, that player loses and the other player wins ." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"AAABABB\"\nOutput:true\nExplanation:AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.", + "image": null + }, + { + "text": "Example 2: Input:colors = \"AA\"\nOutput:false\nExplanation:Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.", + "image": null + }, + { + "text": "Example 3: Input:colors = \"ABBBBBBBAAA\"\nOutput:false\nExplanation:ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def winnerOfGame(self, s: str) -> bool:\n \n a = b = 0\n \n for i in range(1,len(s)-1):\n if s[i-1] == s[i] == s[i+1]:\n if s[i] == 'A':\n a += 1\n else:\n b += 1\n \n return a>b\n", + "title": "2038. Remove Colored Pieces if Both Neighbors are the Same Color", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the i th line of the source code. This represents the result of splitting the original source code string by the newline character '\\n' . In C++, there are two types of comments, line comments, and block comments. The first effective comment takes precedence over others. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format .", + "description_images": [], + "constraints": [ + "The string \"//\" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.", + "The string \"/*\" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of \"*/\" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string \"/*/\" does not yet end the block comment, as the ending would be overlapping the beginning." + ], + "examples": [ + { + "text": "Example 1: Input:source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\nOutput:[\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]\nExplanation:The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n // variable declaration \nint a, b, c;\n/* This is a test\n multiline \n comment for \n testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n \nint a, b, c;\na = b + c;\n}", + "image": null + }, + { + "text": "Example 2: Input:source = [\"a/*comment\", \"line\", \"more_comment*/b\"]\nOutput:[\"ab\"]\nExplanation:The original source string is \"a/*comment\\nline\\nmore_comment*/b\", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string \"ab\", which when delimited by newline characters becomes [\"ab\"].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.99 MB (Top 67.1%)\n\nclass Solution {\n public List removeComments(String[] source) {\n boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. \n\t\t//It is initally set to false since we haven't read anything until now. \n\n\n List result = new ArrayList();\n StringBuilder builder = new StringBuilder();\n \n //Read every line from the source input. \n \n for(String line: source){\n// Each time we move on to reading a new line, we check if it is a part of a block comment. \n//If it is already part of a block comment, it means we should skip the implicit newline characters as mentioned in the problem description. \n//For example if Line 1 was \"int a /*Block comment Started\" and Line 2 was \"Block comment ends here */ b;\", and Line 3 was \"int c;\" \n//we want our output to be \"int ab\", \"int c\" instead of \"int a\", \"b;\", \"int c;\" \n if(!blockActive){ \n builder = new StringBuilder();\n }\n for(int i=0; i List[str]:\n ans, inComment = [], False\n new_str = \"\"\n for c in source:\n if not inComment: new_str = \"\"\n i, n = 0, len(c)\n # inComment, we find */\n while i < n:\n if inComment:\n if c[i:i + 2] == '*/' and i + 1 < n:\n i += 2\n inComment = False\n continue\n i += 1\n # not in Comment, we find /* // and common character\n else:\n if c[i:i + 2] == '/*' and i + 1 < n:\n i += 2\n inComment = True\n continue\n if c[i:i + 2] == '//' and i + 1 < n:\n break\n new_str += c[i]\n i += 1\n if new_str and not inComment:\n ans.append(new_str)\n \n\n return ans", + "title": "722. Remove Comments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array intervals where intervals[i] = [l i , r i ] represent the interval [l i , r i ) , remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d . Return the number of remaining intervals .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 1000", + "intervals[i].length == 2", + "0 <= l i < r i <= 10^5", + "All the given intervals are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,4],[3,6],[2,8]]\nOutput:2\nExplanation:Interval [3,6] is covered by [2,8], therefore it is removed.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[2,3]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeCoveredIntervals(int[][] intervals) {\n if(intervals == null || intervals.length == 0) return 0;\n Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0]));\n int c = intervals[0][0], d = intervals[0][1];\n int ans = intervals.length;\n for(int i=1;i int:\n\n intervals.sort(key = lambda x: (x[0], -x[1]))\n current, count = intervals[0], 1\n for i in range(1, len(intervals)):\n if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]:\n continue\n current = intervals[i]\n count += 1\n return count\n\n# time and space complexity\n# time: O(nlog(n))\n# space: O(1)", + "title": "1288. Remove Covered Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string number representing a positive integer and a character digit . Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized . The test cases are generated such that digit occurs at least once in number .", + "description_images": [], + "constraints": [ + "2 <= number.length <= 100", + "number consists of digits from '1' to '9' .", + "digit is a digit from '1' to '9' .", + "digit occurs at least once in number ." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"123\", digit = \"3\"\nOutput:\"12\"\nExplanation:There is only one '3' in \"123\". After removing '3', the result is \"12\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"1231\", digit = \"1\"\nOutput:\"231\"\nExplanation:We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"551\", digit = \"5\"\nOutput:\"51\"\nExplanation:We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 37.58%) | Memory: 43 MB (Top 24.40%)\nclass Solution {\n public String removeDigit(String number, char digit) {\n List digits = new ArrayList<>();\n for (int i = 0; i < number.length(); i++) {\n if (number.charAt(i) == digit) {\n String stringWithoutDigit = number.substring(0, i) + number.substring(i + 1);\n digits.add(stringWithoutDigit);\n }\n }\n Collections.sort(digits);\n return digits.get(digits.size() - 1);\n }\n}", + "title": "2259. Remove Digit From Number to Maximize Result", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string number representing a positive integer and a character digit . Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized . The test cases are generated such that digit occurs at least once in number .", + "description_images": [], + "constraints": [ + "2 <= number.length <= 100", + "number consists of digits from '1' to '9' .", + "digit is a digit from '1' to '9' .", + "digit occurs at least once in number ." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"123\", digit = \"3\"\nOutput:\"12\"\nExplanation:There is only one '3' in \"123\". After removing '3', the result is \"12\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"1231\", digit = \"1\"\nOutput:\"231\"\nExplanation:We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"551\", digit = \"5\"\nOutput:\"51\"\nExplanation:We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n \n # Initializing the last index as zero\n last_index = 0\n \n #iterating each number to find the occurences, \\\n # and to find if the number is greater than the next element \\ \n\n for num in range(1, len(number)):\n \n # Handling [case 1] and [case 2]\n if number[num-1] == digit:\n if int(number[num]) > int(number[num-1]):\n return number[:num-1] + number[num:]\n else:\n last_index = num - 1\n \n # If digit is the last number (last occurence) in the string [case 3]\n if number[-1] == digit:\n last_index = len(number) - 1\n\n return number[:last_index] + number[last_index + 1:]\n", + "title": "2259. Remove Digit From Number to Maximize Result", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"\nOutput:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"\nOutput:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String removeDuplicateLetters(String s) {\n int[] lastIndex = new int[26];\n for (int i = 0; i < s.length(); i++){\n lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence\n }\n \n boolean[] seen = new boolean[26]; // keep track seen\n Stack st = new Stack();\n \n for (int i = 0; i < s.length(); i++) {\n int curr = s.charAt(i) - 'a';\n if (seen[curr]) continue; // if seen continue as we need to pick one char only\n while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){\n seen[st.pop()] = false; // pop out and mark unseen\n }\n st.push(curr); // add into stack\n seen[curr] = true; // mark seen\n }\n\n StringBuilder sb = new StringBuilder();\n while (!st.isEmpty())\n sb.append((char) (st.pop() + 'a'));\n return sb.reverse().toString();\n }\n}\n", + "title": "316. Remove Duplicate Letters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"\nOutput:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"\nOutput:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n \n\t\tlast_occ = {}\n\t\tstack = []\n\t\tvisited = set()\n\n\t\tfor i in range(len(s)):\n\t\t\tlast_occ[s[i]] = i\n\n\t\tfor i in range(len(s)):\n\n\t\t\tif s[i] not in visited:\n\t\t\t\twhile (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):\n\t\t\t\t\tvisited.remove(stack.pop())\n\n\t\t\t\tstack.append(s[i])\n\t\t\t\tvisited.add(s[i])\n\n\t\treturn ''.join(stack)\n", + "title": "316. Remove Duplicate Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove the duplicates in-place such that each unique element appears only once . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-100 <= nums[i] <= 100", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]\nOutput:2, nums = [1,2,_]\nExplanation:Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,2,2,3,3,4]\nOutput:5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation:Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.72 MB (Top 69.8%)\n\nclass Solution {\n public int removeDuplicates(int[] arr) {\n int i=0;\n for(int j=1;j int:\n i = 1\n for index in range(1, len(nums)):\n if(nums[index] != nums[index-1]):\n nums[i] = nums[index]\n i += 1\n return i\n", + "title": "26. Remove Duplicates from Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove some duplicates in-place such that each unique element appears at most twice . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3]\nOutput:5, nums = [1,1,2,2,3,_]\nExplanation:Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,1,2,3,3]\nOutput:7, nums = [0,0,1,1,2,3,3,_,_]\nExplanation:Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.37 MB (Top 93.9%)\n\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int index = 1;\n int count = 0;\n for(int i = 1;i Optional[ListNode]:\n if head is None:\n return head\n cur=head.next\n prev=head\n while cur is not None:\n if cur.val==prev.val:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head\n", + "title": "83. Remove Duplicates from Sorted List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]\nOutput:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 8.62%) | Memory: 43.1 MB (Top 83.93%)\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n if (head == null) return head;\n ListNode temp = head;\n int last = -1;\n int[]array = new int[201];\n // zero == index 100\n // one == index 101;\n // -100 == index 0;\n\n while (temp != null){\n array[temp.val + 100]++;\n temp = temp.next;\n }\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n last = i;\n }\n }\n if (last == -1) return null;\n temp = head;\n\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n temp.val = i - 100;\n if (i == last){\n temp.next = null;\n break;\n }\n temp=temp.next;\n }\n }\n temp.next = null;\n\n return head;\n }\n}```", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]\nOutput:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if (not head):\n return None\n\n result = tail = ListNode(-1)\n\n while(head):\n curr = head\n head = head.next\n hasDup = False\n while(head) and (curr.val == head.val):\n hasDup = True\n headNext = head.next\n head = None\n head = headNext\n\n if (hasDup == False):\n tail.next = curr\n tail = tail.next\n tail.next = None\n\n return result.next\n\n", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer val , remove all occurrences of val in nums in-place . The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 100", + "0 <= nums[i] <= 50", + "0 <= val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,2,3], val = 3\nOutput:2, nums = [2,2,_,_]\nExplanation:Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2,2,3,0,4,2], val = 2\nOutput:5, nums = [0,1,4,0,3,_,_,_]\nExplanation:Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.4 MB (Top 71.77%)\n\nclass Solution {\n public int removeElement(int[] nums, int val) {\n int ind = 0;\n for(int i=0; i removeInvalidParentheses(String s) {\n List ans=new ArrayList<>();\n HashSet set=new HashSet();\n \n int minBracket=removeBracket(s);\n getAns(s, minBracket,set,ans);\n \n return ans;\n }\n \n public void getAns(String s, int minBracket, HashSet set, List ans){\n if(set.contains(s)) return;\n \n set.add(s);\n \n if(minBracket==0){\n int remove=removeBracket(s); \n if(remove==0) ans.add(s);\n return;\n }\n \n for(int i=0;i stack=new Stack<>();\n \n for(int i=0;i List[str]:\n ## RC ##\n ## APPROACH : BACK-TRACKING ##\n ## Similar to Leetcode 32. Longest Valid Parentheses ##\n ## LOGIC ##\n # 1. use stack to find invalid left and right braces.\n # 2. if its close brace at index i , you can remove it directly to make it valid and also you can also remove any of the close braces before that i.e in the range [0,i-1]\n # 3. similarly for open brace, left over at index i, you can remove it or any other open brace after that i.e [i+1, end]\n # 4. if left over braces are more than 1 say 2 close braces here, you need to make combinations of all 2 braces before that index and find valid parentheses.\n # 5. so, we count left and right invalid braces and do backtracking removing them\n \n\t\t## TIME COMPLEXITY : O(2^N) ## (each brace has 2 options: exits or to be removed)\n\t\t## SPACE COMPLEXITY : O(N) ##\n\n def isValid(s):\n stack = []\n for i in range(len(s)):\n if( s[i] == '(' ):\n stack.append( (i,'(') )\n elif( s[i] == ')' ):\n if(stack and stack[-1][1] == '('):\n stack.pop()\n else:\n stack.append( (i,')') ) # pushing invalid close braces also\n return len(stack) == 0, stack\n \n \n def dfs( s, left, right):\n visited.add(s)\n if left == 0 and right == 0 and isValid(s)[0]: res.append(s)\n for i, ch in enumerate(s):\n if ch != '(' and ch != ')': continue # if it is any other char ignore.\n if (ch == '(' and left == 0) or (ch == ')' and right == 0): continue # if left == 0 then removing '(' will only cause imbalance. Hence, skip.\n if s[:i] + s[i+1:] not in visited:\n dfs( s[:i] + s[i+1:], left - (ch == '('), right - (ch == ')') )\n \n stack = isValid(s)[1]\n lc = sum([1 for val in stack if val[1] == \"(\"]) # num of left braces\n rc = len(stack) - lc\n \n res, visited = [], set()\n dfs(s, lc, rc)\n return res", + "title": "301. Remove Invalid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given string num representing a non-negative integer num , and an integer k , return the smallest possible integer after removing k digits from num .", + "description_images": [], + "constraints": [ + "1 <= k <= num.length <= 10^5", + "num consists of only digits.", + "num does not have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1432219\", k = 3\nOutput:\"1219\"\nExplanation:Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:num = \"10200\", k = 1\nOutput:\"200\"\nExplanation:Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.", + "image": null + }, + { + "text": "Example 3: Input:num = \"10\", k = 2\nOutput:\"0\"\nExplanation:Remove all the digits from the number and it is left with nothing which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 69.83%) | Memory: 55 MB (Top 18.30%)\nclass Solution {\n public String removeKdigits(String num, int k) {\n int n = num.length();\n if(n == k){\n return \"0\";\n }\n Deque dq = new ArrayDeque<>();\n for(char ch : num.toCharArray()){\n while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){\n dq.pollLast();\n k--;\n }\n dq.addLast(ch);\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty() && dq.peekFirst() == '0'){\n dq.pollFirst();\n }\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n if(k >= sb.length()){\n return \"0\";\n }\n return sb.length() == 0 ? \"0\" : sb.toString().substring(0,sb.length()-k);\n }\n}", + "title": "402. Remove K Digits", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given string num representing a non-negative integer num , and an integer k , return the smallest possible integer after removing k digits from num .", + "description_images": [], + "constraints": [ + "1 <= k <= num.length <= 10^5", + "num consists of only digits.", + "num does not have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1432219\", k = 3\nOutput:\"1219\"\nExplanation:Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:num = \"10200\", k = 1\nOutput:\"200\"\nExplanation:Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.", + "image": null + }, + { + "text": "Example 3: Input:num = \"10\", k = 2\nOutput:\"0\"\nExplanation:Remove all the digits from the number and it is left with nothing which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict.\n#as soon as len(delete) == k delete those indexes from the initial string and thats the answer.\n#if len(delete) < k remove k-len(delete) chars from right and thats the answer\nclass Solution:\n def removeKdigits(self, s: str, k: int) -> str:\n if len(s) == k:\n return '0'\n stack = []\n delete = {}\n for i in range(len(s)):\n\n while stack and s[i] < stack[-1][0]:\n delete[stack.pop()[1]] = 1\n if len(delete) == k:\n break\n if len(delete) == k:\n return self.deleteindexes(s, delete, k)\n stack.append([s[i], i])\n s1 = self.deleteindexes(s, delete, k)\n\n return str(int(s1[:len(s1)-k +len(delete)]))\n\n\n def deleteindexes(self, s, delete, k):\n if not delete:\n return s\n if len(delete) == k:\n return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete])))\n else:\n return ''.join([c for ind, c in enumerate(s) if ind not in delete])\n\n\n", + "title": "402. Remove K Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6\nOutput:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode removeElements(ListNode head, int val) {\n if (head == null) {\n return head;\n }\n ListNode result = head;\n while (head.next != null) {\n if (head.next.val == val) {\n head.next = head.next.next;\n } else {\n head = head.next;\n }\n }\n if (result.val == val) {\n result = result.next;\n }\n return result;\n }\n}\n", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6\nOutput:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 151 ms (Top 10.13%) | Memory: 17.7 MB (Top 81.63%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:\n prev=head\n cur=head\n while cur is not None:\n if cur.val==val:\n if cur==head:\n head=head.next\n prev=head\n else:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob have an undirected graph of n nodes and three types of edges: Given an array edges where edges[i] = [type i , u i , v i ] represents a bidirectional edge of type type i between nodes u i and v i , find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/19/ex1.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex2.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex3.png" + ], + "constraints": [ + "Type 1: Can be traversed by Alice only.", + "Type 2: Can be traversed by Bob only.", + "Type 3: Can be traversed by both Alice and Bob." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput:2\nExplanation:If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput:0\nExplanation:Notice that removing any edge will not make the graph fully traversable by Alice and Bob.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput:-1\nExplanation:In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 44.9%) | Memory: 82.52 MB (Top 97.7%)\n\nclass Solution {\n public int maxNumEdgesToRemove(int n, int[][] edges) \n {\n Arrays.sort(edges, (a, b)->{\n return b[0]-a[0];\n });//giving the priority to third type of edge or the edge which Bob and Alice both can access\n \n //1-based indexing of nodes \n int []parentAlice= new int[n+1];//Graph 1 for Alice connectedness\n int []parentBob= new int[n+1];//Graph 2 for Bob connectedness\n \n for(int i= 0; i< n+1; i++){//every node is pointing to itself, at first no connection is considered all sets are independent(no dependency) \n parentAlice[i]= i;\n parentBob[i]= i;\n }\n \n //number of merged unique node for Alice and Bob that are required to maintain the connectedness of Alice and Bob graph nodes//intialised with one because merging happens in pair \n int mergeAlice= 1;\n int mergeBob= 1;\n \n //number of cyclic or the non dependent node, that are not required for the connectedness of Alice and Bob nodes \n int removeEdge= 0;\n \n for(int []edge: edges)\n {\n int cat= edge[0];//category of edge 1)edge Alice can only access 2)edge Bob can only access 3)edge both Alice and Bob can access\n int u= edge[1];\n int v= edge[2];\n \n if(cat == 3){//edge both Alice and Bob an access\n \n //creating dependency of nodes in graph 1 and 2 \n boolean tempAlice= union(u, v, parentAlice);\n boolean tempBob= union(u, v, parentBob);\n \n if(tempAlice == true)\n mergeAlice+= 1;\n \n if(tempBob == true)\n mergeBob+= 1;\n \n if(tempAlice == false && tempBob == false)//retundant or the cyclic non-dependent edge//both Alice and Bob don't rquire it connection is already there between these pair of nodes\n removeEdge+= 1;\n }\n else if(cat == 2){//edge Bob can only access \n \n //creating dependency of nodes in graph 2\n boolean tempBob= union(u, v, parentBob);\n \n if(tempBob == true)\n mergeBob+= 1;\n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n else{//edge Alice can only access \n \n //creating dependency of nodes in graph 1\n boolean tempAlice= union(u, v, parentAlice);\n \n if(tempAlice == true)\n mergeAlice+= 1; \n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n }\n if(mergeAlice != n || mergeBob != n)//all node are not connected, connectedness is not maintained \n return -1;\n return removeEdge;//number of edge removed by maintaining the connectedness \n }\n \n public int find(int x, int[] parent)\n {\n if(parent[x] == x)//when we found the absolute root or the leader of the set \n return x;\n \n int temp= find(parent[x], parent);\n \n parent[x]= temp;//Path Compression//child pointing to the absolute root or the leader of the set, while backtracking\n \n return temp;//returning the absolute root \n }\n \n public boolean union(int x, int y, int[] parent)\n {\n int lx= find(x, parent);//leader of set x or the absolute root\n int ly= find(y, parent);//leader of set y or the absolute root\n \n if(lx != ly){//belong to different set merging \n \n //Rank Compression is not done, but you can do it \n parent[lx]= ly;\n \n return true;//union done, dependency created\n }\n else\n return false;//no union done cycle is due to this edge \n }//Please do Upvote, it helps a lot \n}", + "title": "1579. Remove Max Number of Edges to Keep Graph Fully Traversable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob have an undirected graph of n nodes and three types of edges: Given an array edges where edges[i] = [type i , u i , v i ] represents a bidirectional edge of type type i between nodes u i and v i , find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/19/ex1.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex2.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex3.png" + ], + "constraints": [ + "Type 1: Can be traversed by Alice only.", + "Type 2: Can be traversed by Bob only.", + "Type 3: Can be traversed by both Alice and Bob." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput:2\nExplanation:If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput:0\nExplanation:Notice that removing any edge will not make the graph fully traversable by Alice and Bob.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput:-1\nExplanation:In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.", + "image": null + } + ], + "follow_up": null, + "solution": "class DSUF:\n def __init__(self, n):\n self.arr = [-1] * n\n def find(self, node):\n p = self.arr[node]\n if p == -1:\n return node\n self.arr[node] = self.find(p)\n return self.arr[node]\n def union(self, a, b):\n aP = self.find(a)\n bP = self.find(b)\n if aP == bP:\n return 0\n self.arr[aP] = bP\n return 1\n def countParents(self):\n count = 0\n for i in self.arr:\n if i == -1:\n count += 1\n return count\n\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n # Solution - DSU\n # Time - O(ElogV)\n # Space - O(V)\n \n aliceSet = DSUF(n)\n bobSet = DSUF(n)\n \n bothEdges = []\n bobEdges = []\n aliceEdges= []\n for i in range(len(edges)):\n if edges[i][0] == 3:\n bothEdges.append(edges[i])\n elif edges[i][0] == 1:\n aliceEdges.append(edges[i])\n else:\n bobEdges.append(edges[i])\n \n usedEdgeCount = 0\n \n # connect both edges\n for edge in bothEdges:\n aReq = aliceSet.union(edge[1]-1, edge[2]-1)\n bReq = bobSet.union(edge[1]-1, edge[2]-1)\n if aReq and bReq:\n usedEdgeCount += 1\n \n # connect individual edges\n for edge in aliceEdges:\n usedEdgeCount += aliceSet.union(edge[1]-1, edge[2]-1)\n \n for edge in bobEdges:\n usedEdgeCount += bobSet.union(edge[1]-1, edge[2]-1)\n \n if aliceSet.countParents() == 1 and bobSet.countParents() == 1:\n return len(edges) - usedEdgeCount\n \n return -1\n", + "title": "1579. Remove Max Number of Edges to Keep Graph Fully Traversable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2\nOutput:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 72.17%) | Memory: 42.2 MB (Top 52.18%)\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode temp = head;\n int len=0;\n\n if(head==null || head.next==null)\n return null;\n\n while(temp!=null){\n temp=temp.next;\n len++;\n }\n\n if(len==n)\n return head.next;\n\n int frontlen = len-n-1;\n\n ListNode first=head.next;\n ListNode second = head;\n\n int count=0;\n\n while(first!=null){\n if(count==frontlen){\n second.next=first.next;\n break;\n }else{\n first=first.next;\n second=second.next;\n count++;\n }\n }\n\n return head;\n }\n}", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2\nOutput:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 20.14%) | Memory: 13.9 MB (Top 70.35%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if head == None:\n return None\n slow = head\n fast = head\n for i in range(n):\n fast = fast.next\n if fast == None:\n return head.next\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next\n slow.next = slow.next.next\n return head", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true . The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,10,5,7]\nOutput:true\nExplanation:By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,2]\nOutput:false\nExplanation:[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]\nOutput:false\nExplanation:The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 78.74%) | Memory: 42.8 MB (Top 79.54%)\nclass Solution {\n public boolean canBeIncreasing(int[] nums) {\n int count=0;\n int p=0;\n for(int i=0;inums[i+1] || nums[i]==nums[i+1]) {\n count++;\n p=i;\n }\n }\n if(count>1) return false;\n else if(count==1){\n if(p==0 || p== nums.length-2) return true;\n if(nums[p+1]>nums[p-1] || nums[p+2]>nums[p]) return true;\n else return false;\n }\n return true;\n }\n}", + "title": "1909. Remove One Element to Make the Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums , return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true . The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,10,5,7]\nOutput:true\nExplanation:By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,2]\nOutput:false\nExplanation:[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]\nOutput:false\nExplanation:The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n indx = -1\n count = 0\n n = len(nums)\n \n # count the number of non-increasing elements\n for i in range(n-1):\n if nums[i] >= nums[i+1]:\n indx = i\n count += 1\n \n #the cases explained above\n if count==0:\n return True\n \n if count == 1:\n if indx == 0 or indx == n-2:\n return True\n if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]):\n return True\n \n return False\n", + "title": "1909. Remove One Element to Make the Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A valid parentheses string is either empty \"\" , \"(\" + A + \")\" , or A + B , where A and B are valid parentheses strings, and + represents string concatenation. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B , with A and B nonempty valid parentheses strings. Given a valid parentheses string s , consider its primitive decomposition: s = P 1 + P 2 + ... + P k , where P i are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s .", + "description_images": [], + "constraints": [ + "For example, \"\" , \"()\" , \"(())()\" , and \"(()(()))\" are all valid parentheses strings." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()())(())\"\nOutput:\"()()()\"\nExplanation:The input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"(()())(())(()(()))\"\nOutput:\"()()()()(())\"\nExplanation:The input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"\nOutput:\"\"\nExplanation:The input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 58.51%) | Memory: 43 MB (Top 43.86%)\nclass Solution {\n public String removeOuterParentheses(String s) {\n // if '(' check stack size > 0 add ans else not add ans\n // if ')' check stack size > 0 add ans else not add ans\n Stack st = new Stack<>();\n StringBuilder sb = new StringBuilder();\n for(int i=0;i 0){\n sb.append(ch);\n }\n st.push(ch);\n }\n\n else{\n st.pop();\n if(st.size() > 0){\n sb.append(ch);\n }\n }\n }\n return sb.toString();\n }\n}", + "title": "1021. Remove Outermost Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A valid parentheses string is either empty \"\" , \"(\" + A + \")\" , or A + B , where A and B are valid parentheses strings, and + represents string concatenation. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B , with A and B nonempty valid parentheses strings. Given a valid parentheses string s , consider its primitive decomposition: s = P 1 + P 2 + ... + P k , where P i are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s .", + "description_images": [], + "constraints": [ + "For example, \"\" , \"()\" , \"(())()\" , and \"(()(()))\" are all valid parentheses strings." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()())(())\"\nOutput:\"()()()\"\nExplanation:The input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"(()())(())(()(()))\"\nOutput:\"()()()()(())\"\nExplanation:The input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"\nOutput:\"\"\nExplanation:The input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n c=0\n res=''\n for i in s:\n if i==')' and c==1:\n c=c-1\n elif i=='(' and c==0:\n c=c+1\n elif i=='(':\n res=res+'('\n c=c+1\n elif i==')':\n res=res+')'\n c=c-1\n return res\n", + "title": "1021. Remove Outermost Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of letters 'a' and 'b' . In a single step you can remove one palindromic subsequence from s . Return the minimum number of steps to make the given string empty . A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababa\"\nOutput:1\nExplanation:s is already a palindrome, so its entirety can be removed in a single step.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abb\"\nOutput:2\nExplanation:\"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"baabb\"\nOutput:2\nExplanation:\"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.3 MB (Top 19.55%)\nclass Solution\n{\n public int removePalindromeSub(String s)\n {\n int left = 0 , right = s.length() - 1 ;\n while( left < right )\n {\n if( s.charAt(left++) != s.charAt(right--) )\n {\n return 2 ;\n }\n }\n return 1 ;\n }\n}", + "title": "1332. Remove Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting only of letters 'a' and 'b' . In a single step you can remove one palindromic subsequence from s . Return the minimum number of steps to make the given string empty . A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababa\"\nOutput:1\nExplanation:s is already a palindrome, so its entirety can be removed in a single step.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abb\"\nOutput:2\nExplanation:\"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"baabb\"\nOutput:2\nExplanation:\"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n return 1 if s[::-1] == s else 2\n ", + "title": "1332. Remove Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array piles , where piles[i] represents the number of stones in the i th pile, and an integer k . You should apply the following operation exactly k times: Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations . floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).", + "description_images": [], + "constraints": [ + "Choose any piles[i] and remove floor(piles[i] / 2) stones from it." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,4,9], k = 2\nOutput:12\nExplanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.", + "image": null + }, + { + "text": "Example 2: Input:piles = [4,3,6,7], k = 3\nOutput:12\nExplanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 304 ms (Top 95.0%) | Memory: 58.55 MB (Top 23.6%)\n\nclass Solution {\n public int minStoneSum(int[] A, int k) {\n PriorityQueue pq = new PriorityQueue<>((a, b)->b - a);\n int res = 0;\n for (int a : A) {\n pq.add(a);\n res += a;\n }\n while (k-- > 0) {\n int a = pq.poll();\n pq.add(a - a / 2);\n res -= a / 2;\n }\n return res;\n }\n}", + "title": "1962. Remove Stones to Minimize the Total", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array piles , where piles[i] represents the number of stones in the i th pile, and an integer k . You should apply the following operation exactly k times: Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations . floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).", + "description_images": [], + "constraints": [ + "Choose any piles[i] and remove floor(piles[i] / 2) stones from it." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,4,9], k = 2\nOutput:12\nExplanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.", + "image": null + }, + { + "text": "Example 2: Input:piles = [4,3,6,7], k = 3\nOutput:12\nExplanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n heap = [-p for p in piles]\n heapq.heapify(heap)\n for _ in range(k):\n cur = -heapq.heappop(heap)\n heapq.heappush(heap, -(cur-cur//2))\n return -sum(heap) \n", + "title": "1962. Remove Stones to Minimize the Total", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of folders folder , return the folders after removing all sub-folders in those folders . You may return the answer in any order . If a folder[i] is located within another folder[j] , it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.", + "description_images": [], + "constraints": [ + "For example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not." + ], + "examples": [ + { + "text": "Example 1: Input:folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput:[\"/a\",\"/c/d\",\"/c/f\"]\nExplanation:Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.", + "image": null + }, + { + "text": "Example 2: Input:folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput:[\"/a\"]\nExplanation:Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".", + "image": null + }, + { + "text": "Example 3: Input:folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput:[\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n TrieNode root;\n public List removeSubfolders(String[] folder) {\n List res = new ArrayList<>();\n Arrays.sort(folder, (a, b) -> (a.length() - b.length()));\n root = new TrieNode();\n for (String f : folder) {\n if (insert(f)) {\n res.add(f);\n }\n }\n return res;\n }\n \n private boolean insert(String folder) {\n TrieNode node = root;\n char[] chs = folder.toCharArray();\n for (int i = 0; i < chs.length; i++) {\n char ch = chs[i];\n node.children.putIfAbsent(ch, new TrieNode());\n node = node.children.get(ch);\n if (node.isFolder && (i+1 < chs.length && chs[i+1] == '/')) {\n return false;\n }\n }\n node.isFolder = true;\n return true;\n }\n}\n\nclass TrieNode {\n Map children = new HashMap<>();\n boolean isFolder;\n}\n", + "title": "1233. Remove Sub-Folders from the Filesystem", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list of folders folder , return the folders after removing all sub-folders in those folders . You may return the answer in any order . If a folder[i] is located within another folder[j] , it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.", + "description_images": [], + "constraints": [ + "For example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not." + ], + "examples": [ + { + "text": "Example 1: Input:folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput:[\"/a\",\"/c/d\",\"/c/f\"]\nExplanation:Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.", + "image": null + }, + { + "text": "Example 2: Input:folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput:[\"/a\"]\nExplanation:Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".", + "image": null + }, + { + "text": "Example 3: Input:folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput:[\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# a TrieNode class for creating new node\nclass TrieNode():\n def __init__(self):\n self.children = {}\n self.main = False\n \n# the main class\nclass Solution(object):\n def removeSubfolders(self, folder): \n node = TrieNode()\n res = []\n # sort the list to prevent adding the subfolder to the Trie first\n folder.sort()\n for dir in folder:\n name = dir.split(\"/\")\n if self.addTrie(name,node):\n res.append(dir)\n return res\n\n # usign the same addTrie template and modify the else part\n def addTrie(self,name,node): \n trie = node\n for c in name:\n if c not in trie.children:\n trie.children[c] = TrieNode()\n # if char is in trie,\n else:\n # check if it's the last sub folder. \n if trie.children[c].main == True:\n return False\n trie = trie.children[c]\n trie.main = True\n return True\n", + "title": "1233. Remove Sub-Folders from the Filesystem", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.)", + "description_images": [], + "constraints": [ + "The given linked list will contain between 1 and 1000 nodes.", + "Each node in the linked list has -1000 <= node.val <= 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,-3,3,1]\nOutput:[3,1]Note:The answer [1,2,1] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,2,3,-3,4]\nOutput:[1,2,4]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2,3,-3,-2]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 92.2%) | Memory: 43.00 MB (Top 67.8%)\n\nclass Solution {\n public ListNode removeZeroSumSublists(ListNode head) {\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n \n int prefix = 0;\n ListNode curr = dummy;\n Map seen = new HashMap<>();\n seen.put(prefix, dummy);\n \n while (curr != null) {\n prefix += curr.val;\n seen.put(prefix, curr);\n curr = curr.next;\n }\n \n prefix = 0;\n curr = dummy;\n while (curr != null) {\n prefix += curr.val;\n curr.next = seen.get(prefix).next;\n curr = curr.next;\n }\n \n return dummy.next;\n }\n}", + "title": "1171. Remove Zero Sum Consecutive Nodes from Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.)", + "description_images": [], + "constraints": [ + "The given linked list will contain between 1 and 1000 nodes.", + "Each node in the linked list has -1000 <= node.val <= 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,-3,3,1]\nOutput:[3,1]Note:The answer [1,2,1] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,2,3,-3,4]\nOutput:[1,2,4]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2,3,-3,-2]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 77.27%) | Memory: 14.3 MB (Top 57.10%)\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n root = ListNode(0,head)\n summ , d , node = 0 , {} , root\n while node:\n summ += node.val\n if summ in d:\n prev = d[summ]\n tmp = prev.next\n tmp_sum = summ\n while tmp != node:\n tmp_sum += tmp.val\n if tmp_sum in d and d[tmp_sum] == tmp :d.pop(tmp_sum)\n tmp = tmp.next\n prev.next = node.next\n node = prev\n else:\n d[summ] = node\n node = node.next\n\n return root.next", + "title": "1171. Remove Zero Sum Consecutive Nodes from Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of distinct integers nums . There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "The integers in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,7,5,4,1,8,6]\nOutput:5\nExplanation:The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,-4,19,1,8,-2,-3,5]\nOutput:3\nExplanation:The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 3: Input:nums = [101]\nOutput:1\nExplanation:There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumDeletions(int[] nums) {\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n int minInd = 0;\n int maxInd = 0;\n int n = nums.length;\n \n //First Find out the max and min element index\n for(int i=0;imax){\n max = nums[i];\n maxInd = i;\n }\n \n if(nums[i]minInd){\n int count = Math.min(maxInd+1,n-minInd); // min of all the elements till max element and all the elements to the right of min element\n int count1 = minInd+1+(n-maxInd); // all elements to the left of min and right of max\n return Math.min(count,count1); // min of both\n }\n // min element is right side of the max element\n else{\n int count = Math.min(minInd+1,n-maxInd);\n int count1 = maxInd+1+(n-minInd);\n return Math.min(count,count1);\n }\n \n }\n}", + "title": "2091. Removing Minimum and Maximum From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of distinct integers nums . There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "The integers in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,7,5,4,1,8,6]\nOutput:5\nExplanation:The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,-4,19,1,8,-2,-3,5]\nOutput:3\nExplanation:The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 3: Input:nums = [101]\nOutput:1\nExplanation:There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n minFromFront = nums.index(min(nums))\n maxFromFront = nums.index(max(nums))\n \n minFromBack = len(nums) - minFromFront - 1\n maxFromBack = len(nums) - maxFromFront - 1 \n \n return min(max(minFromFront, maxFromFront) + 1, # Case 1\n max(minFromBack, maxFromBack) + 1, # Case 2\n minFromBack + maxFromFront + 2, # Case 3 \n minFromFront + maxFromBack + 2) # Case 4\n", + "title": "2091. Removing Minimum and Maximum From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of positive integers beans , where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans ( possibly none ) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal . Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove .", + "description_images": [], + "constraints": [ + "1 <= beans.length <= 10^5", + "1 <= beans[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:beans = [4,1,6,5]\nOutput:4\nExplanation:- We remove 1 bean from the bag with only 1 bean.\n This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer.", + "image": null + }, + { + "text": "Example 2: Input:beans = [2,10,3,2]\nOutput:7\nExplanation:- We remove 2 beans from one of the bags with 2 beans.\n This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumRemoval(int[] beans) {\n Arrays.parallelSort(beans);\n long sum=0,min=Long.MAX_VALUE;\n int n=beans.length;\n for(int i:beans)\n sum+=i;\n for(int i=0;i int:\n return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))\n", + "title": "2171. Removing Minimum Number of Magic Beans", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of logs . Each log is a space-delimited string of words, where the first word is the identifier . There are two types of logs: Reorder these logs so that: Return the final order of the logs .", + "description_images": [], + "constraints": [ + "Letter-logs : All words (except the identifier) consist of lowercase English letters.", + "Digit-logs : All words (except the identifier) consist of digits." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]\nOutput:[\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]\nExplanation:The letter-log contents are all different, so their ordering is \"art can\", \"art zero\", \"own kit dig\".\nThe digit-logs have a relative order of \"dig1 8 1 5 1\", \"dig2 3 6\".", + "image": null + }, + { + "text": "Example 2: Input:logs = [\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\"]\nOutput:[\"g1 act car\",\"a8 act zoo\",\"ab1 off key dog\",\"a1 9 2 3 1\",\"zo4 4 7\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n self._seq=0\n def _sortBy(log):\n a=log.split(' ')\n logType,self._seq=('A',self._seq) if a[1].isalpha() else ('B',self._seq+1)\n return (logType,\" \".join(a[1:]),a[0]) if logType=='A' else (logType,self._seq)\n return sorted(logs,key=_sortBy)\n", + "title": "937. Reorder Data in Log Files", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a singly linked-list. The list can be represented as: Reorder the list to be on the following form: You may not modify the values in the list's nodes. Only nodes themselves may be changed.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5 * 10^4 ] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]\nOutput:[1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5]\nOutput:[1,5,2,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" + }, + { + "text": "L0→ L1→ … → Ln - 1→ Ln", + "image": null + }, + { + "text": "L0→ Ln→ L1→ Ln - 1→ L2→ Ln - 2→ …", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void reorderList(ListNode head) {\n if (head == null) return;\n\t\t\n\t\t// Find start of second list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\t\t\n ListNode list1 = head;\n ListNode list2 = reverseList(slow.next); // slow.next is start of list2\n \n // Break first list from second list!\n slow.next = null; \n \n\t\t// Merge list1 and list2\n while (list2 != null) {\n ListNode l1Next = list1.next;\n ListNode l2Next = list2.next;\n list2.next = list1.next;\n list1.next = list2;\n list1 = l1Next;\n list2 = l2Next;\n }\n }\n \n private ListNode reverseList(ListNode node) {\n if (node == null) return node;\n ListNode newHead = null, currNode = node;\n while (currNode != null) {\n ListNode backup = currNode.next;\n currNode.next = newHead;\n newHead = currNode;\n currNode = backup;\n }\n return newHead;\n }\n}\n", + "title": "143. Reorder List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the head of a singly linked-list. The list can be represented as: Reorder the list to be on the following form: You may not modify the values in the list's nodes. Only nodes themselves may be changed.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5 * 10^4 ] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]\nOutput:[1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5]\nOutput:[1,5,2,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" + }, + { + "text": "L0→ L1→ … → Ln - 1→ Ln", + "image": null + }, + { + "text": "L0→ Ln→ L1→ Ln - 1→ L2→ Ln - 2→ …", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverse(self , head):\n prev = None\n after = None\n curr = head\n while(curr):\n after = curr.next\n curr.next = prev\n prev = curr\n curr = after\n return prev\n \n def find_middle(self , head):\n slow = head\n fast = head\n while(fast and fast.next):\n fast = fast.next.next\n slow = slow.next\n return slow\n \n def reorderList(self, head: Optional[ListNode]) -> None:\n mid = self.find_middle(head)\n rev = self.reverse(mid)\n first = head\n second = rev\n \n while(second.next):\n temp = first.next\n first.next = second\n first = temp\n \n temp = second.next\n second.next = first\n second = temp\n \n", + "title": "143. Reorder List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput:3\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput:2\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 76.3%) | Memory: 72.93 MB (Top 48.8%)\n\nclass Solution {\n int dfs(List> al, boolean[] visited, int from) {\n int change = 0;\n visited[from] = true;\n for (var to : al.get(from))\n if (!visited[Math.abs(to)])\n change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);\n return change; \n }\n public int minReorder(int n, int[][] connections) {\n List> al = new ArrayList<>();\n for(int i = 0; i < n; ++i) \n al.add(new ArrayList<>());\n for (var c : connections) {\n al.get(c[0]).add(c[1]);\n al.get(c[1]).add(-c[0]);\n }\n return dfs(al, new boolean[n], 0);\n }\n}", + "title": "1466. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput:3\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput:2\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n count, stack, visited = 0, [ 0 ], set() #Add root node to stack\n neighbours = defaultdict(list) #To store neighbours\n\t\tadjacency = defaultdict(list) #To store adjacency\n for i, j in connections:\n adjacency[i].append(j)\n neighbours[i].append(j)\n neighbours[j].append(i)\n while stack:\n current = stack.pop()\n if current in visited:\n continue\n else:\n visited.add(current)\n for i in neighbours[current]:\n if i in visited:\n continue\n if current not in adjacency[i]:\n count += 1\n stack.append(i)\n return count\n", + "title": "1466. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:\"aba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 11.69%) | Memory: 42.5 MB (Top 40.28%)\nclass Solution {\n public String reorganizeString(String s) {\n StringBuilder ans=new StringBuilder(\"\");\n char[] charArray=new char[s.length()];\n Map hashMap=new HashMap<>();\n Queue queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence);\n\n charArray=s.toCharArray();\n\n for(int i=0;inew CharOccurence(e.getKey(),e.getValue()))\n .collect(Collectors.toList()));\n while(!queue.isEmpty())\n {\n Queue tmpQueue=new LinkedList<>();\n int sizeQueue=queue.size();\n int stringLength=ans.length();\n int startSub=(stringLength-1<0)?0:stringLength-1;\n int endSub=stringLength;\n String lastLetter=ans.substring(startSub,endSub);\n boolean letterAdded=false;\n for(int i=0;i0)\n tmpQueue.add(letter);\n letterAdded=true;\n break;\n }\n else\n {\n tmpQueue.add(letter);\n }\n }\n if(!letterAdded)\n return \"\";\n queue.addAll(tmpQueue);\n }\n return ans.toString();\n\n }\n class CharOccurence{\n public Character letter;\n public int occurence;\n public CharOccurence(Character letter, int occurence)\n {\n this.letter=letter;\n this.occurence=occurence;\n }\n }\n}", + "title": "767. Reorganize String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:\"aba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef reorganizeString(self, s: str) -> str:\n\t\tc = Counter(s) # for counting the distinct element \n\t\tpq = []\n\t\tfor k,v in c.items(): heapq.heappush(pq,(-v,k)) #multipy by -1 to make max heap \n\t\tans = ''\n\t\twhile pq :\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif ans and ans[-1] == ch: \n\t\t\t\tif not pq: return '' // if heap is empty we cant make the ans return empty string\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\t\treturn ans", + "title": "767. Reorganize String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A' , 'C' , 'G' , and 'T' . When studying DNA , it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence , return all the 10 -letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, \"ACGAATTCCG\" is a DNA sequence ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput:[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"AAAAAAAAAAAAA\"\nOutput:[\"AAAAAAAAAA\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 6.21%) | Memory: 61.2 MB (Top 61.48%)\nclass Solution {\n public List findRepeatedDnaSequences(String s) {\n HashMap map =new HashMap();\n int i=0;\n int j=0;\n int k=10;\n StringBuilder sb=new StringBuilder(\"\");\n\n while(j list=new ArrayList();\n for(Map.Entry mapElement:map.entrySet()){\n if(mapElement.getValue()>1){\n list.add(mapElement.getKey());\n }\n }\n return list;\n }\n}", + "title": "187. Repeated DNA Sequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A' , 'C' , 'G' , and 'T' . When studying DNA , it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence , return all the 10 -letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, \"ACGAATTCCG\" is a DNA sequence ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput:[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"AAAAAAAAAAAAA\"\nOutput:[\"AAAAAAAAAA\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 147 ms (Top 16.98%) | Memory: 27.7 MB (Top 15.14%)\nclass Solution(object):\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n seqs = {}\n i = 0\n while i+10 <= len(s):\n curr = s[i:i+10]\n if curr in seqs:\n seqs[curr] = seqs[curr] + 1\n else:\n seqs[curr] = 1\n i += 1\n\n repeats = []\n for seq in list(seqs.keys()):\n if seqs[seq] > 1:\n repeats.append(seq)\n\n return repeats", + "title": "187. Repeated DNA Sequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings a and b , return the minimum number of times you should repeat string a so that string b is a substring of it . If it is impossible for b ​​​​​​ to be a substring of a after repeating it, return -1 . Notice: string \"abc\" repeated 0 times is \"\" , repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\" .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"abcd\", b = \"cdabcdab\"\nOutput:3\nExplanation:We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.", + "image": null + }, + { + "text": "Example 2: Input:a = \"a\", b = \"aa\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 305 ms (Top 62.11%) | Memory: 113.5 MB (Top 30.98%)\nclass Solution {\n public int repeatedStringMatch(String a, String b) {\n String copyA = a;\n int count =1;\n int repeat = b.length()/a.length();\n for(int i=0;i int:\n if len(A) >= len(B):\n if B in A: return 1\n elif B in A*2: return 2\n else: return -1\n prefix = max(0, B.find(A)) #prefix -- length of A1\n repeat, postfix = divmod(len(B)-prefix, len(A)) #postfix -- length of A2\n repeat += bool(prefix) + bool(postfix)\n if B in A * repeat: return repeat\n else: return -1 \n", + "title": "686. Repeated String Match", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"\nOutput:true\nExplanation:It is the substring \"ab\" twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcabcabcabc\"\nOutput:true\nExplanation:It is the substring \"abc\" four times or the substring \"abcabc\" twice.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 17.74%) | Memory: 165.9 MB (Top 16.84%)\nclass Solution {\n\n public boolean repeatedSubstringPattern(String s) {\n String temp=\"\";\n for(int i=0 ;i bool:\n for i in range(1, len(s)//2+1):\n if s[:i] * (len(s)//i) == s:\n return True\n return False", + "title": "459. Repeated Substring Pattern", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x) , where c is a character and x is a digit, that returns the x th character after c . For every odd index i , you want to replace the digit s[i] with shift(s[i-1], s[i]) . Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z' .", + "description_images": [], + "constraints": [ + "For example, shift('a', 5) = 'f' and shift('x', 0) = 'x' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a1c1e1\"\nOutput:\"abcdef\"\nExplanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "image": null + }, + { + "text": "Example 2: Input:s = \"a1b2c3d4e\"\nOutput:\"abbdcfdhe\"\nExplanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.86%) | Memory: 42.6 MB (Top 27.39%)\nclass Solution {\n public String replaceDigits(String s) {\n char[] str = s.toCharArray();\n\n for(int i=0;i shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "image": null + }, + { + "text": "Example 2: Input:s = \"a1b2c3d4e\"\nOutput:\"abbdcfdhe\"\nExplanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 73 ms (Top 5.29%) | Memory: 13.8 MB (Top 58.42%)\nclass Solution(object):\n def replaceDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n res = []\n\n for i in range(len(s)):\n if i % 2 == 0:\n res.append(s[i])\n if i % 2 == 1:\n res.append( chr(ord(s[i-1]) + int(s[i])) )\n\n return ''.join(res)", + "title": "1844. Replace All Digits with Characters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the i th operation you replace the number operations[i][0] with operations[i][1] . It is guaranteed that in the i th operation: Return the array obtained after applying all the operations .", + "description_images": [], + "constraints": [ + "operations[i][0] exists in nums .", + "operations[i][1] does not exist in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\nOutput:[3,2,7,1]\nExplanation:We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], operations = [[1,3],[2,1],[3,2]]\nOutput:[2,1]\nExplanation:We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 124 ms (Top 26.09%) | Memory: 164.1 MB (Top 72.68%)\nclass Solution {\n public int[] arrayChange(int[] nums, int[][] operations) {\n Map map = new HashMap<>();\n for(int i=0;i List[int]:\n replacements = {}\n for x, y in reversed(operations):\n replacements[x] = replacements.get(y, y)\n for idx, val in enumerate(nums):\n if val in replacements:\n nums[idx] = replacements[val]\n return nums\n", + "title": "2295. Replace Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr , replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1 . After doing so, return the array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [17,18,5,4,6,1]\nOutput:[18,6,6,6,1,-1]\nExplanation:- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [400]\nOutput:[-1]\nExplanation:There are no elements to the right of index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 67.33%) | Memory: 55.1 MB (Top 5.58%)\nclass Solution {\n public int[] replaceElements(int[] arr) {\n int greatElement = -1;\n for(int i = arr.length-1; i >= 0; i--) {\n int temp = arr[i];\n arr[i] = greatElement;\n greatElement = Math.max(temp, greatElement);\n }\n return arr;\n }\n}", + "title": "1299. Replace Elements with Greatest Element on Right Side", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array arr , replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1 . After doing so, return the array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [17,18,5,4,6,1]\nOutput:[18,6,6,6,1,-1]\nExplanation:- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [400]\nOutput:[-1]\nExplanation:There are no elements to the right of index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n maxright = arr[-1]\n for i in range(len(arr) -1,-1,-1):\n temp = arr[i]\n arr[i] = maxright\n if temp > maxright:\n maxright = temp\n arr[-1] = -1\n \n return arr\n", + "title": "1299. Replace Elements with Greatest Element on Right Side", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers nums . Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 10^8 . Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "The test cases are generated such that the values in the final array are less than or equal to 10^8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,4,3,2,7,6,2]\nOutput:[12,7,6]\nExplanation:- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,3,3,3]\nOutput:[2,1,1,3]\nExplanation:- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic List replaceNonCoprimes(int[] nums) \n\t{\n\t\tList al=new ArrayList<>();\n\t\tlong n1=nums[0];\n\t\tint idx=1;\n\n\t\twhile(idx 1 where GCD(x, y) is the Greatest Common Divisor of x and y .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "The test cases are generated such that the values in the final array are less than or equal to 10^8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,4,3,2,7,6,2]\nOutput:[12,7,6]\nExplanation:- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,3,3,3]\nOutput:[2,1,1,3]\nExplanation:- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n res = []\n for num in nums:\n while res and gcd(res[-1], num) > 1:\n num = lcm(res[-1], num)\n res.pop()\n res.append(num)\n return res\n", + "title": "2197. Replace Non-Coprime Numbers in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of length n containing only four kinds of characters: 'Q' , 'W' , 'E' , and 'R' . A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced . If s is already balanced , return 0 .", + "description_images": [], + "constraints": [ + "n == s.length", + "4 <= n <= 10^5", + "n is a multiple of 4 .", + "s contains only 'Q' , 'W' , 'E' , and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"QWER\"\nOutput:0\nExplanation:s is already balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"QQWE\"\nOutput:1\nExplanation:We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"QQQW\"\nOutput:2\nExplanation:We can replace the first \"QQ\" to \"ER\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int balancedString(String s) {\n int n = s.length(), ans = n, excess = 0;\n int[] cnt = new int[128];\n cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4;\n for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be removed.\n if (excess == 0) return 0;\n for (int i = 0, j = 0; i < n; i++){//i = window right end, j = window left end\n if (--cnt[s.charAt(i)] == 0) excess--; //remove letter at index i\n while (excess == 0){ //if no more excess, then \n if (++cnt[s.charAt(j)] == 1) excess++; //we put letter at index j back\n ans = Math.min(i - j + 1, ans);; //and update ans accordingly\n j++;\n }\n }\n\n return ans;\n }\n}\n", + "title": "1234. Replace the Substring for Balanced String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of length n containing only four kinds of characters: 'Q' , 'W' , 'E' , and 'R' . A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced . If s is already balanced , return 0 .", + "description_images": [], + "constraints": [ + "n == s.length", + "4 <= n <= 10^5", + "n is a multiple of 4 .", + "s contains only 'Q' , 'W' , 'E' , and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"QWER\"\nOutput:0\nExplanation:s is already balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"QQWE\"\nOutput:1\nExplanation:We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"QQQW\"\nOutput:2\nExplanation:We can replace the first \"QQ\" to \"ER\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 450 ms (Top 49.65%) | Memory: 14.6 MB (Top 82.17%)\nclass Solution:\n def balancedString(self, s):\n count = collections.Counter(s)\n res = n = len(s)\n if all(n/4==count[char] for char in 'QWER'):\n return 0\n left = 0\n for right, char in enumerate(s):\n # replace char whose index==right to check if it is balanced\n count[char] -= 1\n # if it is balanced, window shrinks to get the smallest length of window\n while left <= right and all(n / 4 >= count[char] for char in 'QWER'):\n res = min(res, right - left + 1)\n count[s[left]] =count[s[left]]+ 1\n left += 1\n return res", + "title": "1234. Replace the Substring for Balanced String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In English, we have a concept called root , which can be followed by some other word to form another longer word - let's call this word successor . For example, when the root \"an\" is followed by the successor word \"other\" , we can form a new word \"another\" . Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root , replace it with the root that has the shortest length . Return the sentence after the replacement.", + "description_images": [], + "constraints": [ + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 100", + "dictionary[i] consists of only lower-case letters.", + "1 <= sentence.length <= 10^6", + "sentence consists of only lower-case letters and spaces.", + "The number of words in sentence is in the range [1, 1000]", + "The length of each word in sentence is in the range [1, 1000]", + "Every two consecutive words in sentence will be separated by exactly one space.", + "sentence does not have leading or trailing spaces." + ], + "examples": [ + { + "text": "Example 1: Input:dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput:\"the cat was rat by the bat\"", + "image": null + }, + { + "text": "Example 2: Input:dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput:\"a a b c\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};\n\n", + "title": "648. Replace Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In English, we have a concept called root , which can be followed by some other word to form another longer word - let's call this word successor . For example, when the root \"an\" is followed by the successor word \"other\" , we can form a new word \"another\" . Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root , replace it with the root that has the shortest length . Return the sentence after the replacement.", + "description_images": [], + "constraints": [ + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 100", + "dictionary[i] consists of only lower-case letters.", + "1 <= sentence.length <= 10^6", + "sentence consists of only lower-case letters and spaces.", + "The number of words in sentence is in the range [1, 1000]", + "The length of each word in sentence is in the range [1, 1000]", + "Every two consecutive words in sentence will be separated by exactly one space.", + "sentence does not have leading or trailing spaces." + ], + "examples": [ + { + "text": "Example 1: Input:dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput:\"the cat was rat by the bat\"", + "image": null + }, + { + "text": "Example 2: Input:dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput:\"a a b c\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};\n\n", + "title": "648. Replace Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "-1000 <= mat[i][j] <= 1000", + "1 <= r, c <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2],[3,4]], r = 1, c = 4\nOutput:[[1,2,3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]], r = 2, c = 4\nOutput:[[1,2],[3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.50%) | Memory: 50.7 MB (Top 48.08%)\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n\n if (r * c != mat.length * mat[0].length) {\n return mat;\n }\n\n int[][] ans = new int[r][c];\n\n int i = 0;\n int j = 0;\n\n for(int k = 0; k < mat.length; k++) {\n for(int l = 0; l < mat[0].length; l++) {\n if (j == c) {\n i++;\n j = 0;\n }\n ans[i][j++] = mat[k][l];\n }\n }\n return ans;\n }\n}", + "title": "566. Reshape the Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "-1000 <= mat[i][j] <= 1000", + "1 <= r, c <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2],[3,4]], r = 1, c = 4\nOutput:[[1,2,3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]], r = 2, c = 4\nOutput:[[1,2],[3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg" + } + ], + "follow_up": null, + "solution": "import numpy\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat", + "title": "566. Reshape the Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 ( inclusive ) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s . You are not allowed to reorder or remove any digits in s . You may return the valid IP addresses in any order.", + "description_images": [], + "constraints": [ + "For example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\" , \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"25525511135\"\nOutput:[\"255.255.11.135\",\"255.255.111.35\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"0000\"\nOutput:[\"0.0.0.0\"]", + "image": null + }, + { + "text": "Example 3: Input:s = \"101023\"\nOutput:[\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 19.20%) | Memory: 43.5 MB (Top 45.49%)\n\nclass Solution {\n public List restoreIpAddresses(String s) {\n List ans = new ArrayList<>();\n\n int len = s.length();\n for(int i = 1; i < 4 && i < len-2 ; i++ ){\n for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){\n for(int k = j+1 ; k < j + 4 && k < len ; k++){\n String s1 = s.substring(0,i);\n String s2 = s.substring(i,j);\n String s3 = s.substring(j,k);\n String s4 = s.substring(k,len);\n if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))\n ans.add(s1+\".\"+s2+\".\"+s3+\".\"+s4);\n }\n }\n }\n return ans;\n }\n boolean isValid(String s){\n if(s.length() > 3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s) > 255)\n return false;\n return true;\n }\n}", + "title": "93. Restore IP Addresses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 ( inclusive ) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s . You are not allowed to reorder or remove any digits in s . You may return the valid IP addresses in any order.", + "description_images": [], + "constraints": [ + "For example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\" , \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"25525511135\"\nOutput:[\"255.255.11.135\",\"255.255.111.35\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"0000\"\nOutput:[\"0.0.0.0\"]", + "image": null + }, + { + "text": "Example 3: Input:s = \"101023\"\nOutput:[\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def restoreIpAddresses(self, s: str):\n def isValid(st):\n if(len(st)!=len(str(int(st)))):\n return False\n st = int(st)\n if(st>255 or st<0):\n return False\n return True\n \n validIps = []\n for i in range(1,4):\n s1 = s[:i]\n if(not isValid(s1)):\n continue\n for j in range(i+1, min(len(s), i+4)):\n s2 = s[i:j]\n if(not isValid(s2)):\n continue\n for k in range(j+1,min(len(s), j+4)):\n s3 = s[j:k]\n if(not isValid(s3)):\n continue\n s4 = s[k:]\n if(not isValid(s4)):\n continue\n currentIp = s1+\".\"+s2+\".\"+s3+\".\"+s4\n validIps.append(currentIp)\n return validIps\n", + "title": "93. Restore IP Addresses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k , return the number of the possible arrays that can be printed as s using the mentioned program . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only digits and does not contain leading zeros.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1000\", k = 10000\nOutput:1\nExplanation:The only possible array is [1000]", + "image": null + }, + { + "text": "Example 2: Input:s = \"1000\", k = 10\nOutput:0\nExplanation:There cannot be an array that was printed this way and has all integer >= 1 and <= 10.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1317\", k = 2000\nOutput:8\nExplanation:Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 126 ms (Top 51.52%) | Memory: 71.7 MB (Top 43.43%)\nclass Solution {\n static long mod;\n private long solve(int idx,String s,int k,long[] dp){\n if(idx==s.length())\n return 1;\n if(dp[idx]!=-1)\n return dp[idx];\n long max=0,number=0;\n for(int i=idx;i=1 && number<=k){\n max=(max+solve(i+1,s,k,dp))%mod;\n }else\n break;\n }\n return dp[idx]=max;\n }\n public int numberOfArrays(String s, int k) {\n mod = (int)1e9+7;\n long[] dp=new long[s.length()+1];\n Arrays.fill(dp,-1);\n return (int)solve(0,s,k,dp);\n }\n}", + "title": "1416. Restore The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k , return the number of the possible arrays that can be printed as s using the mentioned program . Since the answer may be very large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only digits and does not contain leading zeros.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1000\", k = 10000\nOutput:1\nExplanation:The only possible array is [1000]", + "image": null + }, + { + "text": "Example 2: Input:s = \"1000\", k = 10\nOutput:0\nExplanation:There cannot be an array that was printed this way and has all integer >= 1 and <= 10.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1317\", k = 2000\nOutput:8\nExplanation:Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n \"1317\"\n[1, 3, 1, 7] -> [1] * nums(317, k)\n[1, 3, 17] \n[1, 31, 7]\n[1, 317] \n[13, 1, 7] -> [13] * nums(17, k)\n[13, 17]\n[131, 7]\n[1317]\n\n\n \"2020\" k = 30\n[2000] x\n[2, 020] x\n[20, 20]\n\n \"67890\" k = 90\n\n[6, 7890] x\n[6, 7, 8, 9, 0] x\n[6, 7, 8, 90] OK\n[6, 78, 90] OK\n[67, 8, 90] OK\n[67, 89, 0] x\n[678, 90] x\nbreak because 678 > k (90), so neither 678, 6789 would be possible numbers\n\n\"\"\"\n\n\n\nclass Solution:\n def num_arrays(self, s, k, memo):\n if not s:\n return 0\n memo_ans = memo.get(s)\n if memo_ans is not None:\n return memo_ans\n \n num = int(s)\n if num <= k:\n counter = 1\n else:\n counter = 0\n \n for i in range(len(s) - 1):\n # Stop when the number to the right side of the array is greater than k\n if int(s[:i + 1]) > k:\n break\n # Don't count leading zeros\n if s[i + 1] == \"0\":\n continue\n counter += self.num_arrays(s[i + 1:], k, memo)\n ans = counter % (10 ** 9 + 7)\n memo[s] = ans\n return ans\n \n def numberOfArrays(self, s: str, k: int) -> int:\n memo = {}\n return self.num_arrays(s, k, memo)\n", + "title": "1416. Restore The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums . You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [u i , v i ] indicates that the elements u i and v i are adjacent in nums . It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs , either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]] . The pairs can appear in any order . Return the original array nums . If there are multiple solutions, return any of them .", + "description_images": [], + "constraints": [ + "nums.length == n", + "adjacentPairs.length == n - 1", + "adjacentPairs[i].length == 2", + "2 <= n <= 10^5", + "-10^5 <= nums[i], u i , v i <= 10^5", + "There exists some nums that has adjacentPairs as its pairs." + ], + "examples": [ + { + "text": "Example 1: Input:adjacentPairs = [[2,1],[3,4],[3,2]]\nOutput:[1,2,3,4]\nExplanation:This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.", + "image": null + }, + { + "text": "Example 2: Input:adjacentPairs = [[4,-2],[1,4],[-3,1]]\nOutput:[-2,4,1,-3]\nExplanation:There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.", + "image": null + }, + { + "text": "Example 3: Input:adjacentPairs = [[100000,-100000]]\nOutput:[100000,-100000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 122 ms (Top 96.49%) | Memory: 87.3 MB (Top 95.99%)\n\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n // Build an adjacency list graph.\n Map> iToPairs = new HashMap<>();\n for (int[] pair : adjacentPairs) {\n iToPairs.computeIfAbsent(pair[0], k -> new ArrayDeque<>()).add(pair[1]);\n iToPairs.computeIfAbsent(pair[1], k -> new ArrayDeque<>()).add(pair[0]);\n }\n\n // Find an item that has only one neighbour.\n int start = -1;\n for (int i : iToPairs.keySet()) {\n if (iToPairs.get(i).size() == 1) {\n start = i;\n break;\n }\n }\n\n // Traverse the graph in a linked-list fashion.\n int n = iToPairs.size();\n int writeIdx = 0;\n int[] restored = new int[n];\n restored[writeIdx++] = start;\n while (writeIdx < n) {\n int next = iToPairs.get(start).remove();\n iToPairs.remove(start);\n iToPairs.get(next).remove(start); // Remove the loop back to the current start.\n restored[writeIdx++] = next;\n start = next;\n }\n\n return restored;\n }\n}", + "title": "1743. Restore the Array From Adjacent Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums . You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [u i , v i ] indicates that the elements u i and v i are adjacent in nums . It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs , either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]] . The pairs can appear in any order . Return the original array nums . If there are multiple solutions, return any of them .", + "description_images": [], + "constraints": [ + "nums.length == n", + "adjacentPairs.length == n - 1", + "adjacentPairs[i].length == 2", + "2 <= n <= 10^5", + "-10^5 <= nums[i], u i , v i <= 10^5", + "There exists some nums that has adjacentPairs as its pairs." + ], + "examples": [ + { + "text": "Example 1: Input:adjacentPairs = [[2,1],[3,4],[3,2]]\nOutput:[1,2,3,4]\nExplanation:This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.", + "image": null + }, + { + "text": "Example 2: Input:adjacentPairs = [[4,-2],[1,4],[-3,1]]\nOutput:[-2,4,1,-3]\nExplanation:There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.", + "image": null + }, + { + "text": "Example 3: Input:adjacentPairs = [[100000,-100000]]\nOutput:[100000,-100000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2248 ms (Top 15.65%) | Memory: 166 MB (Top 35.87%)\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n # create the map\n adj = collections.defaultdict(list)\n for a, b in adjacentPairs:\n adj[a].append(b)\n adj[b].append(a)\n\n # find the start num\n start = adjacentPairs[0][0]\n for k, v in adj.items():\n if len(v) ==1:\n start = k\n break\n\n # dfs to connect the graph\n nums=[]\n seen = set()\n def dfs(num):\n seen.add(num)\n for next_num in adj[num]:\n if next_num in seen: continue\n dfs(next_num)\n nums.append(num)\n dfs(start)\n return nums\n", + "title": "1743. Restore the Array From Adjacent Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array deck . There is a deck of cards where every card has a unique integer. The integer on the i th card is deck[i] . You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: Return an ordering of the deck that would reveal the cards in increasing order . Note that the first entry in the answer is considered to be the top of the deck.", + "description_images": [], + "constraints": [ + "1 <= deck.length <= 1000", + "1 <= deck[i] <= 10^6", + "All the values of deck are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [17,13,11,2,3,5,7]\nOutput:[2,13,3,11,5,17,7]\nExplanation:We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1000]\nOutput:[1,1000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 59.29%) | Memory: 44.5 MB (Top 28.33%)\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) { // deck=[ 17,13,11,2,3,5,7 ]\n Queue ql = new LinkedList();\n for(int i=0;i List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n i += 1\n return ans\n ans = reveal(len(deck))\n ans = sorted([v, i] for i, v in enumerate(ans))\n deck.sort()\n return (deck[j] for i,j in ans)", + "title": "950. Reveal Cards In Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Reverse bits of a given 32 bits unsigned integer. Note:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825 ." + ], + "examples": [ + { + "text": "Example 2 Input:n = 00000010100101000001111010011100\nOutput:964176192 (00111001011110000010100101000000)\nExplanation:The input binary string00000010100101000001111010011100represents the unsigned integer 43261596, so return 964176192 which its binary representation is00111001011110000010100101000000.", + "image": null + }, + { + "text": "Example 2: Input:n = 11111111111111111111111111111101\nOutput:3221225471 (10111111111111111111111111111111)\nExplanation:The input binary string11111111111111111111111111111101represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is10111111111111111111111111111111.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need treat n as an unsigned value\n public int reverseBits(int n) {\n int mask = 0;\n int smask = 0;\n int j = 0;\n int rev = 0;\n \n // basically we are checking that the number is set bit or not \n // if the number is set bit then we are appending that to our main answer i.e, rev\n for(int i=31 ; i>=0 ; i--){\n mask = 1<>i)&1\n res=res|bit<<(31-i)\n return res\n", + "title": "190. Reverse Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123\nOutput:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123\nOutput:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120\nOutput:21", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.59%) | Memory: 39.60 MB (Top 71.8%)\n\nclass Solution {\n public int reverse(int x) {\n long reverse = 0;\n while (x != 0) {\n int digit = x % 10;\n reverse = reverse * 10 + digit;\n x = x / 10;\n }\n if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0;\n return (int) reverse;\n }\n}\n\n", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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).", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123\nOutput:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123\nOutput:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120\nOutput:21", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass Solution:\n def reverse(self, x: int) -> int:\n\n flag = 0\n if x<0:\n x = abs(x)\n flag = 1\n \n l = [i for i in str(x)]\n l.reverse()\n \n ret = ''.join(l)\n ret = int(ret)\n \n if flag == 1:\n ret = ret*-1\n \n if ((ret >= (-(2**31))) and (ret<=((2**31)-1))):\n return ret\n else:\n return 0\n", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]\nOutput:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.5 MB (Top 99.13%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n\n if(head == null || head.next == null) return head;\n\n ListNode curr = head;\n ListNode temp = null, next = curr.next;\n curr.next = null;\n\n while(curr !=null && next !=null)\n {\n // before cutting off link between next & its next, save next.next\n temp = next.next;\n // let next point to curr\n next.next = curr;\n\n curr = next;\n next = temp;\n\n }\n\n return curr;\n\n }\n}", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]\nOutput:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 71 ms (Top 18.71%) | Memory: 15.5 MB (Top 28.33%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head==None or head.next==None:\n return head\n p = None\n while(head != None):\n temp = head.next\n head.next = p\n p = head\n head = temp\n return p\n", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list and two integers left and right where left <= right , reverse the nodes of the list from position left to position right , and return the reversed list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 500", + "-500 <= Node.val <= 500", + "1 <= left <= right <= n" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], left = 2, right = 4\nOutput:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg" + }, + { + "text": "Example 2: Input:head = [5], left = 1, right = 1\nOutput:[5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if(left==right) return head;\n ListNode last = null;\n ListNode present = head;\n \n for(int i=0; present != null && i Optional[ListNode]:\n # revrese api\n def reverse(start, end):\n prev = None\n cur = start\n while prev != end:\n nextNode = cur.next\n cur.next = prev\n prev = cur\n cur = nextNode\n return prev\n \n if not head or not head.next or right <= left:\n return head\n \n start, end = head, head\n node, afterRight = 0, 0\n \n # At the begining\n if left == 1:\n # start index \n inc = left-1\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n reverse(start, end)\n head = end\n else: # Left other then begining\n # start index \n inc = left-2\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n begin = start # node before left\n start = start.next\n reverse(start, end)\n begin.next = end\n \n # If their's ll chain left agter right chain it to the updated ll\n if afterRight:\n start.next = afterRight\n\n return head\n \n\"\"\"\nTC : O(n)\nSc : O(1)\n\n\"\"\"\n", + "title": "92. Reverse Linked List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers ( 1, 2, 3, 4, ... ). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group . Reverse the nodes in each group with an even length, and return the head of the modified linked list .", + "description_images": [], + "constraints": [ + "The 1 st node is assigned to the first group.", + "The 2 nd and the 3 rd nodes are assigned to the second group.", + "The 4 th , 5 th , and 6 th nodes are assigned to the third group, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,2,6,3,9,1,7,3,8,4]\nOutput:[5,6,2,3,9,1,4,8,3,7]\nExplanation:- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg1.png" + }, + { + "text": "Example 2: Input:head = [1,1,0,6]\nOutput:[1,0,1,6]\nExplanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg2.png" + }, + { + "text": "Example 3: Input:head = [1,1,0,6,5]\nOutput:[1,0,1,5,6]\nExplanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/11/17/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 20.66%) | Memory: 252.2 MB (Top 80.33%)\n// This Question can be solved easily using two standard methods of LinkedList\n// 1) addFirst (it adds node in front of the LinkedList)\n// 2) addLast (it adds node in end of the LinkedList)\n\nclass Solution {\n\n static ListNode oh;\n static ListNode ot;\n static ListNode th;\n static ListNode tt;\n\n public ListNode reverseEvenLengthGroups(ListNode head) {\n\n oh = null;\n ot = null;\n th = null;\n tt = null;\n\n if(head == null || head.next == null)\n return head;\n\n int size = length(head);\n int idx = 1;\n ListNode curr = head;\n int group = 1;\n\n while(curr!=null)\n {\n int temp = size - idx + 1;\n if((temp>=group && group%2 == 0) || (temp0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addFirst(curr);\n curr = t;\n idx++;\n }\n }\n else\n {\n int k = group;\n while(k-->0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addLast(curr);\n curr = t;\n idx++;\n }\n }\n\n if(oh==null && ot==null)\n {\n oh = th;\n ot = tt;\n }\n else\n {\n ot.next = th;\n ot = tt;\n }\n\n th = null;\n tt = null;\n group++;\n }\n\n return oh;\n }\n\n public int length (ListNode head)\n {\n if(head==null) return 0;\n ListNode curr = head;\n int k = 0;\n while(curr!=null)\n {\n k++;\n curr = curr.next;\n }\n return k;\n }\n\n public void addFirst(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n head.next = th;\n th = head;\n }\n }\n\n public void addLast(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n tt.next = head;\n tt = head;\n }\n }\n}", + "title": "2074. Reverse Nodes in Even Length Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers ( 1, 2, 3, 4, ... ). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group . Reverse the nodes in each group with an even length, and return the head of the modified linked list .", + "description_images": [], + "constraints": [ + "The 1 st node is assigned to the first group.", + "The 2 nd and the 3 rd nodes are assigned to the second group.", + "The 4 th , 5 th , and 6 th nodes are assigned to the third group, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,2,6,3,9,1,7,3,8,4]\nOutput:[5,6,2,3,9,1,4,8,3,7]\nExplanation:- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg1.png" + }, + { + "text": "Example 2: Input:head = [1,1,0,6]\nOutput:[1,0,1,6]\nExplanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg2.png" + }, + { + "text": "Example 3: Input:head = [1,1,0,6,5]\nOutput:[1,0,1,5,6]\nExplanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/11/17/ex3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3864 ms (Top 51.07%) | Memory: 53.5 MB (Top 68.62%)\nclass Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n group = 2\n tail = head # tail of previous group\n while tail and tail.next:\n cnt = 1 # actual size of the current group\n cur = tail.next # first node of the current group\n while cur.next and cnt < group:\n cur = cur.next\n cnt += 1\n pre, cur = tail, tail.next\n if cnt % 2 == 0: # if group size is even\n while cnt and cur:\n nxt = cur.next\n cur.next = pre\n pre = cur\n cur = nxt\n cnt -= 1\n first = tail.next # first node of the original group\n first.next = cur\n tail.next = pre\n tail = first\n else:\n while cnt and cur:\n pre, cur = cur, cur.next\n cnt -= 1\n tail = pre\n group += 1\n return head", + "title": "2074. Reverse Nodes in Even Length Groups", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3\nOutput:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n int numOfNodes = count(head);\n ListNode ptr = null;\n List start = new ArrayList<>(), end = new ArrayList<>();\n ListNode f = null;\n while (head != null) {\n if (numOfNodes >= k) {\n start.add(head);\n int count = 0;\n while (count < k) {\n ListNode temp = head.next;\n head.next = ptr;\n ptr = head;\n head = temp;\n count++;\n }\n end.add(ptr);\n ptr = null;\n numOfNodes -= count;\n }\n else {\n f = head;\n break;\n }\n }\n int n = start.size();\n for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);\n start.get(n - 1).next = f;\n return end.get(0);\n }\n public int count(ListNode head) {\n ListNode temp = head;\n int count = 0;\n while (temp != null) {\n count++;\n temp = temp.next;\n }\n return count;\n }\n}\n", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3\nOutput:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n\n # Intialize the result and the current node to the head\n res = node = head\n\n # Initialize the index of the current node to 0\n i = 0\n\n # Initialize the head and tail of the reversed nodes group to None\n reversedHead, reversedTail = None, None\n\n # Initialize the tail of the previous group to None\n previousTail = None\n\n # Iterate through all nodes\n while node:\n\n # When we reach the first node in a group\n if i % k == 0:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have less than k nodes left\n if previousTail:\n previousTail.next = node\n\n # Initialize the head and tail of the reversed nodes group\n reversedHead = reversedTail = ListNode(node.val)\n\n # Continue to reverse subsequent nodes\n else:\n reversedHead = ListNode(node.val, reversedHead)\n\n # If we are able to reach the last node in a reversed nodes group\n if i % k == k - 1:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have k nodes and thus, we should reverse this group\n if previousTail:\n previousTail.next = reversedHead\n\n # Set the tail of the previous group to the tail of the reversed nodes group\n previousTail = reversedTail\n\n # Set the head of the first reversed nodes group as the result\n if i == k - 1:\n res = reversedHead\n\n # Continue to the next node\n i, node = i + 1, node.next\n\n return res\n", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse the string according to the following rules: Return s after reversing it .", + "description_images": [], + "constraints": [ + "All the characters that are not English letters remain in the same position.", + "All the English letters (lowercase or uppercase) should be reversed." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab-cd\"\nOutput:\"dc-ba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"a-bC-dEf-ghIj\"\nOutput:\"j-Ih-gfE-dCba\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"Test1ng-Leet=code-Q!\"\nOutput:\"Qedo1ct-eeLg=ntse-T!\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.35%) | Memory: 40.8 MB (Top 87.29%)\nclass Solution {\n public String reverseOnlyLetters(String s) {\n // converting the string to the charArray...\n char[] ch = s.toCharArray();\n\n int start = 0;\n int end = s.length()-1;\n\n // Storing all the english alphabets in a hashmap so that the searching becomes easy...\n HashMap hash = new HashMap<>();\n for(int i=0 ; i<26 ;i++){\n hash.put((char)(97+i) , 1);\n }\n for(int i=0 ; i<26 ; i++){\n hash.put((char)(65+i) , 1);\n }\n\n // using two while loops ..since the constraints are too less thats why we can prefer nested loops approach..\n while(startstart&&!hash.containsKey(ch[end])){\n end--;\n }\n\n // swapping the array elements..\n char temp = ch[start];\n ch[start] = ch[end];\n ch[end] = temp;\n\n start++;\n end--;\n }\n\n // converting the charArray to the string again..\n String ans = new String(ch);\n return ans;\n\n // Time Complexity : O(N) (since the loops will run only till the number of charcters in the string..)\n // Space Complexity : O(N) since we used hashmap..\n }\n}", + "title": "917. Reverse Only Letters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , reverse the string according to the following rules: Return s after reversing it .", + "description_images": [], + "constraints": [ + "All the characters that are not English letters remain in the same position.", + "All the English letters (lowercase or uppercase) should be reversed." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab-cd\"\nOutput:\"dc-ba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"a-bC-dEf-ghIj\"\nOutput:\"j-Ih-gfE-dCba\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"Test1ng-Leet=code-Q!\"\nOutput:\"Qedo1ct-eeLg=ntse-T!\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n st,sp=[],[]\n for i,ch in enumerate(s):\n if ch.isalpha():\n st.append(ch)\n else:\n sp.append([i,ch])\n st=st[::-1]\n for i in sp:\n st.insert(i[0],i[1])\n return (''.join(st))", + "title": "917. Reverse Only Letters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the number of reverse pairs in the array . A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,3,1]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,5,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 354 ms (Top 5.04%) | Memory: 75.8 MB (Top 46.03%)\nclass Solution {\n int cnt;\n public int reversePairs(int[] nums) {\n int n = nums.length;\n cnt = 0;\n sort(0 , n - 1 , nums);\n return cnt;\n }\n void sort(int l , int r , int nums[]){\n if(l == r){\n return;\n }\n int mid = l + (r - l) / 2;\n sort(l , mid , nums);\n sort(mid + 1 , r , nums);\n merge(l , mid , r , nums);\n }\n void merge(int l , int mid , int r , int nums[]){\n int n1 = mid - l + 1;\n int n2 = r - mid;\n int a[] = new int[n1];\n int b[] = new int[n2];\n for(int i = 0; i < n1; i++){\n a[i] = nums[l + i];\n }\n for(int j = 0; j < n2; j++){\n b[j] = nums[mid + 1 + j];\n int idx = upperBound(a , 0 , n1 - 1 , 2L * (long)b[j]);\n if(idx <= n1) {\n cnt += n1 - idx;\n }\n }\n int i = 0;\n int j = 0;\n int k = l;\n while(i < n1 && j < n2){\n if(b[j] <= a[i]){\n nums[k++] = b[j++];\n }\n else{\n nums[k++] = a[i++];\n }\n }\n while(i < n1){\n nums[k++] = a[i++];\n }\n while(j < n2){\n nums[k++] = b[j++];\n }\n }\n int upperBound(int a[] , int l , int r , long x){\n int ans = r + 1;\n while(l <= r){\n int mid = l + (r - l) / 2;\n if((long)a[mid] > x){\n ans = mid;\n r = mid - 1;\n }\n else{\n l = mid + 1;\n }\n }\n return ans;\n }\n}", + "title": "493. Reverse Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of reverse pairs in the array . A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,3,1]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,5,1]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\nclass Solution:\n \"\"\"\n For each sub array nums[0, i]\n We sum the reverse pairs count\n of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1 \n Using a BST(sortedList) to get logN insert and lookup time.\n Time: O(NlogN)\n Space: O(N)\n \"\"\"\n def reversePairs(self, nums: List[int]) -> int:\n res = 0\n bst = SortedList()\n for e in nums:\n res += len(bst) - bst.bisect_left(2 * e + 1) # the count is the N - index\n bst.add(e) # add the the bst\n return res\n", + "title": "493. Reverse Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed string word and a character ch , reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch ( inclusive ). If the character ch does not exist in word , do nothing. Return the resulting string .", + "description_images": [], + "constraints": [ + "For example, if word = \"abcdefd\" and ch = \"d\" , then you should reverse the segment that starts at 0 and ends at 3 ( inclusive ). The resulting string will be \" dcba efd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abcdefd\", ch = \"d\"\nOutput:\"dcbaefd\"\nExplanation:The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".", + "image": null + }, + { + "text": "Example 2: Input:word = \"xyxzxe\", ch = \"z\"\nOutput:\"zxyxxe\"\nExplanation:The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".", + "image": null + }, + { + "text": "Example 3: Input:word = \"abcd\", ch = \"z\"\nOutput:\"abcd\"\nExplanation:\"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.37%) | Memory: 42 MB (Top 72.03%)\nclass Solution {\n public String reversePrefix(String word, char ch) {\n char[] c = word.toCharArray();\n int locate = 0;\n for (int i = 0; i < word.length(); i++) { //first occurrence of ch\n if (ch == c[i]) {\n locate = i;\n break;\n }\n }\n char[] res = new char[word.length()];\n for (int i = 0; i <= locate; i++) {\n res[i] = c[locate - i];\n }\n for (int i = locate + 1; i < word.length(); i++) {\n res[i] = c[i];\n }\n return String.valueOf(res);\n }\n}", + "title": "2000. Reverse Prefix of Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 0-indexed string word and a character ch , reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch ( inclusive ). If the character ch does not exist in word , do nothing. Return the resulting string .", + "description_images": [], + "constraints": [ + "For example, if word = \"abcdefd\" and ch = \"d\" , then you should reverse the segment that starts at 0 and ends at 3 ( inclusive ). The resulting string will be \" dcba efd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abcdefd\", ch = \"d\"\nOutput:\"dcbaefd\"\nExplanation:The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".", + "image": null + }, + { + "text": "Example 2: Input:word = \"xyxzxe\", ch = \"z\"\nOutput:\"zxyxxe\"\nExplanation:The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".", + "image": null + }, + { + "text": "Example 3: Input:word = \"abcd\", ch = \"z\"\nOutput:\"abcd\"\nExplanation:\"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 84.42%) | Memory: 16.40 MB (Top 68.29%)\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n \"\"\"\n #method 1:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word\"\"\"\n #method 2:\n l=0\n r=word.find(ch)\n word=list(word)\n while l=s.length()){\n sb.append(s);\n sb.reverse();\n return sb.toString();\n }\n for(i=0;i str:\n a=list(s)\n for i in range(0,len(a),2*k):\n a[i:i+k]=a[i:i+k][::-1]\n print(a)\n return(\"\".join(a))", + "title": "541. Reverse String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1 . You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once . Find maximum possible value of the final array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,5,4]\nOutput:10\nExplanation:By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,9,24,2,1,10]\nOutput:68", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private int getAbsoluteDifference(int a, int b){\n return Math.abs(a - b);\n }\n public int maxValueAfterReverse(int[] nums) {\n int n = nums.length;\n int result = 0;\n for (int i = 0; i < n - 1; i++)\n result += getAbsoluteDifference(nums[i], nums[i+1]);\n \n int minLine = Integer.MIN_VALUE;\n int maxLine = Integer.MAX_VALUE;\n for (int i = 0; i < n - 1; i++) {\n minLine = Math.max(minLine, Math.min(nums[i], nums[i + 1]));\n maxLine = Math.min(maxLine, Math.max(nums[i], nums[i + 1]));\n }\n int diff = Math.max(0, (minLine - maxLine) * 2);\n for (int i = 1; i < n - 1; i++)\n diff = Math.max(diff, getAbsoluteDifference(nums[0], nums[i+1]) - getAbsoluteDifference(nums[i], nums[i+1]));\n \n for (int i = 0; i < n - 1; i++)\n diff = Math.max(diff, getAbsoluteDifference(nums[n-1], nums[i]) - getAbsoluteDifference(nums[i+1], nums[i]));\n return result + diff;\n }\n}\n", + "title": "1330. Reverse Subarray To Maximize Array Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1 . You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once . Find maximum possible value of the final array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,5,4]\nOutput:10\nExplanation:By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,9,24,2,1,10]\nOutput:68", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxValueAfterReverse(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # basic idea without fancy stuff \n # 1. https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489929/O(n)-time-O(1)-space.-In-depth-Explanation\n # 2. https://code.dennyzhang.com/reverse-subarray-to-maximize-array-value\n \n # This can be done in three steps each step taking O(N) time\n \n res, n = 0, len(nums)\n \n # Step 1: Assume that no subarray is reversed and so the sum would just accumulate over all the abs differences\n for index in range(1, n):\n res += abs(nums[index] - nums[index - 1])\n \n # Step 2: Reversing the left or the right half so basically this idea stems from prefix array type question where in which we have the sum upto ith index but then to get at a specific index we substract extra sum, following from that idea. Or refer to the reference 1\n \n diff = 0\n for index in range(n):\n \n # reversing from 0th index to current\n if index + 1 < n:\n diff = max(diff, abs(nums[index + 1] - nums[0]) - abs(nums[index + 1] - nums[index])) # diff between 0 and curr - diff curr and curr + 1\n \n # reversing from current to last index n - 1\n if index > 0:\n diff = max(diff, abs(nums[index - 1] - nums[n - 1]) - abs(nums[index - 1] - nums[index]))\n \n \n # Step 3: We still need to check the middle reverse part, we can do this using the min max trick\n low_number, high_number = float(\"inf\"), float(\"-inf\")\n \n for index in range(n - 1):\n \n low_number = min(low_number, max(nums[index], nums[index + 1])) # min of low and the max of the current and next number\n high_number = max(high_number, min(nums[index], nums[index + 1]))\n \n\t\t\tdiff = max(diff, 2 * (high_number - low_number)) # This is explained in ref 1\n \n return res + diff\n \n \n", + "title": "1330. Reverse Subarray To Maximize Array Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s only contains lower case English characters and parentheses.", + "It is guaranteed that all parentheses are balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(abcd)\"\nOutput:\"dcba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"(u(love)i)\"\nOutput:\"iloveu\"\nExplanation:The substring \"love\" is reversed first, then the whole string is reversed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(ed(et(oc))el)\"\nOutput:\"leetcode\"\nExplanation:First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 52.91%) | Memory: 42.5 MB (Top 42.22%)\nclass Solution {\n public String reverseParentheses(String s) {\n Stack stack = new Stack<>();\n\n int j = 0;\n while(j < s.length()){\n /*\n We need to keep on adding whatever comes\n as long as it is not a ')'.\n */\n if(s.charAt(j) != ')')\n stack.push(s.charAt(j)+\"\");\n\n /*\n Now that we have encountered an ')', its time\n to start popping from top of stack unless we find an opening\n parenthesis\n\n then we just need to reverse the string formed by popping\n and put it back on stack.\n\n Try dry running and it will all make sense\n */\n else{\n StringBuilder sb = new StringBuilder();\n while(!stack.isEmpty() && !stack.peek().equals(\"(\")){\n sb.append(stack.pop());\n }\n\n stack.pop();\n stack.push(sb.reverse().toString());\n }\n j++;\n }\n\n /*\n We have our result string in the stack now,\n we just need to pop it and return the reverse of it.\n */\n StringBuilder res = new StringBuilder();\n while(!stack.isEmpty())\n res.append(stack.pop());\n\n return res.reverse().toString();\n }\n}", + "title": "1190. Reverse Substrings Between Each Pair of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s only contains lower case English characters and parentheses.", + "It is guaranteed that all parentheses are balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(abcd)\"\nOutput:\"dcba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"(u(love)i)\"\nOutput:\"iloveu\"\nExplanation:The substring \"love\" is reversed first, then the whole string is reversed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(ed(et(oc))el)\"\nOutput:\"leetcode\"\nExplanation:First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = []\n ans = \"\"\n res = deque([])\n s = list(s)\n for i in s:\n if i==\")\":\n while stack[-1] != \"(\":\n res.append(stack.pop())\n stack.pop()\n while res:\n stack.append(res.popleft())\n else:\n stack.append(i)\n return \"\".join(stack)", + "title": "1190. Reverse Substrings Between Each Pair of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both cases.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"hello\"\nOutput:\"holle\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"leotcede\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reverseVowels(String s) {\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n \n StringBuilder str = new StringBuilder(s);\n int left = 0, right = str.length() - 1;\n while (left < right) {\n if (!set.contains(str.charAt(left))) {\n left++;\n }\n if (!set.contains(str.charAt(right))) {\n right--;\n }\n if (set.contains(str.charAt(left)) && set.contains(s.charAt(right))) {\n char temp = str.charAt(left);\n str.setCharAt(left++, str.charAt(right));\n str.setCharAt(right--, temp);\n }\n }\n return str.toString();\n }\n}\n", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both cases.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"hello\"\nOutput:\"holle\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"\nOutput:\"leotcede\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseVowels(self, s: str) -> str:\n s=list(s)\n vow=[]\n for i,val in enumerate(s):\n if val in ('a','e','i','o','u','A','E','I','O','U'):\n vow.append(val)\n s[i]='_'\n \n vow=vow[::-1]\n c=0\n print(vow)\n for i,val in enumerate(s):\n if val =='_':\n s[i]=vow[c]\n c+=1\n return \"\".join(s)\n", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string s , reverse the order of the words . A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s contains English letters (upper-case and lower-case), digits, and spaces ' ' .", + "There is at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"the sky is blue\"\nOutput:\"blue is sky the\"", + "image": null + }, + { + "text": "Example 2: Input:s = \" hello world \"\nOutput:\"world hello\"\nExplanation:Your reversed string should not contain leading or trailing spaces.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a good example\"\nOutput:\"example good a\"\nExplanation:You need to reduce multiple spaces between two words to a single space in the reversed string.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public String reverseWords(String s) {\n String[] arr = s.replaceAll(\"\\\\s{2,}\", \" \").split(\" \"); \n // splitting based on while spaces by replaceing spaces by single gap \n int n = arr.length;\n String temp = \"\";\n for(int i =0;i List[str]:\n start, end = 0, 0\n\n res = []\n for ch in s:\n if ch == delimiter:\n if start == end:\n start += 1\n else:\n res.append(s[start:end])\n start = end + 1\n \n end += 1\n \n if start != end:\n res.append(s[start:end])\n\n return res\n\n def reverse_list(self, ll: List[str]) -> List[str]:\n l, r = 0, len(ll) - 1\n\n while l < r:\n ll[l], ll[r] = ll[r], ll[l]\n l += 1\n r -= 1\n \n return ll\n\n def reverseWords(self, s: str) -> str:\n\n # split first\n splitted_str_list = self.split(s)\n\n # reverse splitted list\n reversed_str_list = self.reverse_list(splitted_str_list)\n\n # join an return\n return \" \".join(reversed_str_list)", + "title": "151. Reverse Words in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s contains printable ASCII characters.", + "s does not contain any leading or trailing spaces.", + "There is at least one word in s .", + "All the words in s are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Let's take LeetCode contest\"\nOutput:\"s'teL ekat edoCteeL tsetnoc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"God Ding\"\nOutput:\"doG gniD\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 36.48%) | Memory: 50.7 MB (Top 54.16%)\nclass Solution {\n public String reverseWords(String s) {\n if(s == null || s.trim().equals(\"\")){\n return null;\n }\n String [] words = s.split(\" \");\n StringBuilder resultBuilder = new StringBuilder();\n for(String word: words){\n for(int i = word.length() - 1; i>=0; i --){\n resultBuilder.append(word.charAt(i));\n }\n resultBuilder.append(\" \");\n }\n return resultBuilder.toString().trim();\n }\n}", + "title": "557. Reverse Words in a String III", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s contains printable ASCII characters.", + "s does not contain any leading or trailing spaces.", + "There is at least one word in s .", + "All the words in s are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Let's take LeetCode contest\"\nOutput:\"s'teL ekat edoCteeL tsetnoc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"God Ding\"\nOutput:\"doG gniD\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseWords(self, s: str) -> str:\n s = s + ' '\n l = len(s)\n t = ''\n w = ''\n for i in range(l):\n if s[i]!=' ':\n t = s[i] + t # t stores the word in reverse order\n else:\n\t\t\t\t# w stores the reversed word in the same order\n w = w + t + ' ' # could have used .join() function and not write .strip()\n t = \"\" # value of t is null so that it won't affect upcoming words\n return w.strip() # removes extra whitespace\n", + "title": "557. Reverse Words in a String III", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​ ​​​​​​th ​​​​ customer has in the j​​​​​ ​​​​​​th ​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth .", + "description_images": [], + "constraints": [ + "m == accounts.length", + "n == accounts[i].length", + "1 <= m, n <= 50", + "1 <= accounts[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[1,2,3],[3,2,1]]\nOutput:6\nExplanation:1st customer has wealth = 1 + 2 + 3 = 62nd customer has wealth = 3 + 2 + 1 = 6Both customers are considered the richest with a wealth of 6 each, so return 6.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[1,5],[7,3],[3,5]]\nOutput:10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.", + "image": null + }, + { + "text": "Example 3: Input:accounts = [[2,8,7],[7,1,3],[1,9,5]]\nOutput:17", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 56.03%) | Memory: 43.3 MB (Top 46.87%)\nclass Solution {\n public int maximumWealth(int[][] accounts) {\n int res = 0;\n for(int i =0;i int:\n return max(map(sum, accounts))", + "title": "1672. Richest Customer Wealth", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9 . You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them.", + "description_images": [], + "constraints": [ + "The first character of the i th pair denotes the i th ring's color ( 'R' , 'G' , 'B' ).", + "The second character of the i th pair denotes the rod that the i th ring is placed on ( '0' to '9' )." + ], + "examples": [ + { + "text": "Example 1: Input:rings = \"B0B6G0R6R0R6G9\"\nOutput:1\nExplanation:- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex1final.png" + }, + { + "text": "Example 2: Input:rings = \"B0R0G0R9R0B0G0\"\nOutput:1\nExplanation:- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex2final.png" + }, + { + "text": "Example 3: Input:rings = \"G4\"\nOutput:0\nExplanation:Only one ring is given. Thus, no rods have all three colors.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.71%) | Memory: 40.70 MB (Top 25.29%)\n\nclass Solution {\n public int countPoints(String rings) {\n Map> m=new HashMap<>();\n for(int i=0;i x=m.get(index);\n x.add(c);\n m.put(index,x);\n }else{\n Set x=new HashSet<>();\n x.add(c);\n m.put(index,x);\n }\n }\n int count=0;\n for(Set k : m.values()){\n if(k.size()==3) count++;\n }\n return count;\n }\n}\n", + "title": "2103. Rings and Rods", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9 . You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them.", + "description_images": [], + "constraints": [ + "The first character of the i th pair denotes the i th ring's color ( 'R' , 'G' , 'B' ).", + "The second character of the i th pair denotes the rod that the i th ring is placed on ( '0' to '9' )." + ], + "examples": [ + { + "text": "Example 1: Input:rings = \"B0B6G0R6R0R6G9\"\nOutput:1\nExplanation:- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex1final.png" + }, + { + "text": "Example 2: Input:rings = \"B0R0G0R9R0B0G0\"\nOutput:1\nExplanation:- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex2final.png" + }, + { + "text": "Example 3: Input:rings = \"G4\"\nOutput:0\nExplanation:Only one ring is given. Thus, no rods have all three colors.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 56 ms (Top 27.28%) | Memory: 13.8 MB (Top 63.52%)\nclass Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if 'R'+i in r and 'G'+i in r and 'B'+i in r:\n ans += 1\n return ans", + "title": "2103. Rings and Rods", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We can use run-length encoding (i.e., RLE ) to encode a sequence of integers. In a run-length encoded array of even length encoding ( 0-indexed ), for all even i , encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. Given a run-length encoded array, design an iterator that iterates through it. Implement the RLEIterator class:", + "description_images": [], + "constraints": [ + "For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5] . encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]Output[null, 8, 8, 5, -1]ExplanationRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class RLEIterator {\n \n long[] prefixEncoded;\n long processed = 0;\n int l = 0;\n\n public RLEIterator(int[] encoding) {\n int encodeLen = encoding.length;\n this.prefixEncoded = new long[encodeLen];\n for(int i=0;i 0) {\n prevPrefixSum = this.prefixEncoded[i-2];\n }\n this.prefixEncoded[i] = encoding[i] + prevPrefixSum;\n this.prefixEncoded[i+1] = encoding[i+1];\n }\n }\n\n public int next(int n) {\n int r = this.prefixEncoded.length-2;\n \n processed += n;\n \n if(l >= this.prefixEncoded.length || processed > this.prefixEncoded[this.prefixEncoded.length - 2]) {\n return -1;\n }\n \n while(l < r) {\n int m = (l + ((r-l)/2));\n if(m % 2 != 0) {\n m = m - 1;\n }\n if(this.prefixEncoded[m] >= processed) {\n r = m;\n } else {\n l = m + 2;\n }\n }\n return l >= this.prefixEncoded.length ? -1: (int) this.prefixEncoded[l + 1];\n } \n}\n", + "title": "900. RLE Iterator", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We can use run-length encoding (i.e., RLE ) to encode a sequence of integers. In a run-length encoded array of even length encoding ( 0-indexed ), for all even i , encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. Given a run-length encoded array, design an iterator that iterates through it. Implement the RLEIterator class:", + "description_images": [], + "constraints": [ + "For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5] . encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]Output[null, 8, 8, 5, -1]ExplanationRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 64 ms (Top 41.88%) | Memory: 14.5 MB (Top 71.25%)\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n\n def next(self, n: int) -> int:\n\n if self.encoding:\n\n count = self.encoding[0]\n\n if count >= n:\n # Partially exhaust and return the current value.\n self.encoding[0] -= n\n return self.encoding[1]\n\n # Exhaust all of current value and continue.\n self.encoding = self.encoding[2:]\n return self.next(n - count)\n\n return -1", + "title": "900. RLE Iterator", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The robot can receive one of three instructions: The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.", + "description_images": [], + "constraints": [ + "The north direction is the positive direction of the y-axis.", + "The south direction is the negative direction of the y-axis.", + "The east direction is the positive direction of the x-axis.", + "The west direction is the negative direction of the x-axis." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = \"GGLLGG\"\nOutput:true\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.", + "image": null + }, + { + "text": "Example 2: Input:instructions = \"GG\"\nOutput:false\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.", + "image": null + }, + { + "text": "Example 3: Input:instructions = \"GL\"\nOutput:true\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 16.85%) | Memory: 41.9 MB (Top 53.99%)\nclass Solution {\n public boolean isRobotBounded(String instructions) {\n if (instructions.length() == 0) {\n return true;\n }\n\n Robot bender = new Robot();\n int[] start = new int[]{0, 0};\n\n // 4 represents the max 90 degree turns that can restart initial orientation.\n for (int i = 0; i < 4; i++) {\n boolean orientationChanged = bender.performSet(instructions);\n\n int[] location = bender.location;\n if (location[0] == start[0] && location[1] == start[1]) {\n return true;\n }\n\n // If robot never turns and the first instruction isn't at start, exit.\n else if (!orientationChanged) {\n return false;\n }\n }\n\n return false;\n }\n}\n\nclass Robot {\n int[] location;\n int[] orientation;\n int[][] orientations;\n int orientationPos;\n boolean orientationChangeCheck;\n\n Robot() {\n // Start in center\n location = new int[]{0, 0};\n\n // N, E, S, W\n orientations = new int[][]{{1,0}, {0, 1}, {-1, 0}, {0, -1}};\n\n // Start pointing north\n orientationPos = 0;\n orientation = orientations[orientationPos];\n\n // Track if robot has turned\n orientationChangeCheck = false;\n }\n\n public boolean performSet(String orders) {\n this.orientationChangeCheck = false;\n\n for (int i = 0; i < orders.length(); i++) {\n this.perform(orders.charAt(i));\n }\n\n return this.orientationChangeCheck;\n }\n\n public void perform(char order) {\n if (order == 'G') {\n this.go();\n } else if (order == 'L' || order == 'R') {\n this.turn(order);\n } else {\n // do nothing\n }\n }\n\n public void turn(char direction) {\n if (direction == 'L') {\n this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;\n } else if (direction == 'R') {\n this.orientationPos = (this.orientationPos + 1) % 4;\n }\n\n this.orientation = this.orientations[this.orientationPos];\n this.orientationChangeCheck = true;\n }\n\n public int[] go() {\n this.location[0] += this.orientation[0];\n this.location[1] += this.orientation[1];\n return this.location;\n }\n}", + "title": "1041. Robot Bounded In Circle", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The robot can receive one of three instructions: The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.", + "description_images": [], + "constraints": [ + "The north direction is the positive direction of the y-axis.", + "The south direction is the negative direction of the y-axis.", + "The east direction is the positive direction of the x-axis.", + "The west direction is the negative direction of the x-axis." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = \"GGLLGG\"\nOutput:true\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.", + "image": null + }, + { + "text": "Example 2: Input:instructions = \"GG\"\nOutput:false\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.", + "image": null + }, + { + "text": "Example 3: Input:instructions = \"GL\"\nOutput:true\nExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 34 ms (Top 89.04%) | Memory: 14 MB (Top 22.71%)\n\nclass Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n pos, d = [0,0], \"N\"\n def move(d, pos, instructions):\n for i in instructions:\n if i == \"G\":\n if d == \"N\": pos[1] += 1\n elif d == \"S\": pos[1] -= 1\n elif d == \"W\": pos[0] -= 1\n else: pos[0] += 1\n elif i == \"L\":\n if d == \"N\": d = \"W\"\n elif d == \"W\": d = \"S\"\n elif d == \"S\": d = \"E\"\n else: d = \"N\"\n else:\n if d == \"N\": d = \"E\"\n elif d == \"W\": d = \"N\"\n elif d == \"S\": d = \"W\"\n else: d = \"S\"\n return (d, pos)\n for i in range(4):\n d, pos = (move(d, pos, instructions))\n return True if pos == [0,0] else False", + "title": "1041. Robot Bounded In Circle", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a robot starting at the position (0, 0) , the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. You are given a string moves that represents the move sequence of the robot where moves[i] represents its i th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise . Note : The way that the robot is \"facing\" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.", + "description_images": [], + "constraints": [ + "1 <= moves.length <= 2 * 10^4", + "moves only contains the characters 'U' , 'D' , 'L' and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:moves = \"UD\"\nOutput:true\nExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:moves = \"LL\"\nOutput:false\nExplanation: The robot moves left twice. It ends up two \"moves\" to the left of the origin. We return false because it is not at the origin at the end of its moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean judgeCircle(String moves) {\n int up=0;\n int rt=0;\n for(int i=0;i bool:\n x=Counter(moves)\n flag=False\n if(x['U']==x['D'] and x['L']==x['R']):\n flag=True\n return flag", + "title": "657. Robot Return to Origin", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"III\"\nOutput:3\nExplanation:III = 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"LVIII\"\nOutput:58\nExplanation:L = 50, V= 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:s = \"MCMXCIV\"\nOutput:1994\nExplanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 63.45%) | Memory: 44.6 MB (Top 83.79%)\nclass Solution {\n public int romanToInt(String s) {\n int res=0;\n // Let s = \"IV\" after traversing string res will be 6\n // Let s= \"IX\" after traversing string res will be 11\n for(int i=0;i int:\n roman = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n\n sum = 0;\n for i in range(0, len(s) - 1):\n curr = roman[s[i]]\n nxt = roman[s[i + 1]]\n if curr < nxt:\n sum -= curr\n else:\n sum += curr\n sum += roman[s[-1]]\n return sum", + "title": "13. Roman to Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise .", + "description_images": [], + "constraints": [ + "The tree consists only of the root, its left child, and its right child.", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,4,6]\nOutput:true\nExplanation:The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png" + }, + { + "text": "Example 2: Input:root = [5,3,1]\nOutput:false\nExplanation:The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 77.34%) | Memory: 41.9 MB (Top 35.55%)\nclass Solution\n{\n public boolean checkTree(TreeNode root)\n {\n return root.val == root.left.val + root.right.val; // O(1)\n }\n}", + "title": "2236. Root Equals Sum of Children", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise .", + "description_images": [], + "constraints": [ + "The tree consists only of the root, its left child, and its right child.", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,4,6]\nOutput:true\nExplanation:The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png" + }, + { + "text": "Example 2: Input:root = [5,3,1]\nOutput:false\nExplanation:The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)", + "title": "2236. Root Equals Sum of Children", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array, rotate the array to the right by k steps, where k is non-negative.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7], k = 3\nOutput:[5,6,7,1,2,3,4]\nExplanation:rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-100,3,99], k = 2\nOutput:[3,99,-1,-100]\nExplanation:rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[] nums, int k) {\n reverse(nums , 0 , nums.length-1);\n reverse(nums , 0 , k-1);\n reverse(nums , k , nums.length -1);\n }\n \n public static void reverse(int[] arr , int start , int end){\n while(start None:\n length = len(nums)\n k = k % length\n l, r = 0, length - 1\n nums = self.reverse(nums,l,r)\n l, r = 0, k - 1\n nums = self.reverse(nums,l,r)\n l, r = k, length - 1\n nums = self.reverse(nums,l,r)\n return nums", + "title": "189. Rotate Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n . Assume arr k to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: Return the maximum value of F(0), F(1), ..., F(n-1) . The test cases are generated so that the answer fits in a 32-bit integer.", + "description_images": [], + "constraints": [ + "F(k) = 0 * arr k [0] + 1 * arr k [1] + ... + (n - 1) * arr k [n - 1]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,6]\nOutput:26\nExplanation:F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.", + "image": null + }, + { + "text": "Example 2: Input:nums = [100]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 100.00%) | Memory: 54.3 MB (Top 98.33%)\nclass Solution {\n public int maxRotateFunction(int[] nums) {\n int sum1 =0,sum2 = 0;\n for(int i=0;i int:\n preSum, cur = 0, 0\n for i in range(len(nums)):\n cur += i * nums[i]\n preSum += nums[i]\n ans = cur\n for i in range(1, len(nums)):\n cur -= len(nums) * nums[len(nums) - i]\n cur += preSum\n ans = max(ans, cur)\n return ans", + "title": "396. Rotate Function", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.7 MB (Top 54.90%)\nclass Solution {\n public void swap(int[][] matrix, int n1, int m1, int n2, int m2) {\n int a = matrix[n1][m1];\n int temp = matrix[n2][m2];\n matrix[n2][m2] = a;\n matrix[n1][m1] = temp;\n }\n public void rotate(int[][] matrix) {\n int n = matrix.length;\n for (int i = 0; i < n/2; i++) {\n for (int j = 0; j < n; j++) {\n swap(matrix, i,j, n-i-1, j);\n }\n }\n for (int i = n-1; i >= 0; i--) {\n for (int j = 0; j < i; j++) {\n swap(matrix, i,j, j, i);\n }\n }\n }\n}", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n # transpose \n size = len(matrix)\n for i in range(size):\n for j in range(i+1, size):\n matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]\n \n print(matrix)\n \n # reverse row\n for row in range(len(matrix)):\n matrix[row] = matrix[row][::-1]\n \n print(matrix)\n", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the head of a linked list, rotate the list to the right by k places.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4\nOutput:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode rotateRight(ListNode head, int k) {\n if(k<=0 || head==null || head.next==null){\n return head;\n }\n \n int length=1;\n ListNode first=head;\n ListNode curr=head;\n ListNode node=head; \n while(node.next!=null){\n length++;\n node=node.next;\n }\n \n if(k==length){\n return head;\n }\n \n int n=length-(k%length);\n for(int i=0; i1\n head=curr.next;\n curr.next=null;\n \n return head;\n }\n}\n", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, rotate the list to the right by k places.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4\nOutput:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if k==0 or head is None or head.next is None:\n return head\n cur=head\n n=0\n while cur is not None:\n cur=cur.next\n n+=1\n k=n-k%n\n if k==n:\n return head\n cur=head\n prev=None\n while k>0 and cur is not None:\n prev=cur\n cur=cur.next\n k-=1\n prev.next=None\n prev=cur\n while cur.next is not None:\n cur=cur.next\n cur.next=head\n return prev\n \n", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s . A shift on s consists of moving the leftmost character of s to the rightmost position.", + "description_images": [], + "constraints": [ + "For example, if s = \"abcde\" , then it will be \"bcdea\" after one shift." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", goal = \"cdeab\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\", goal = \"abced\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.5 MB (Top 17.04%)\nclass Solution {\n public boolean rotateString(String s, String goal) {\n int n = s.length(), m = goal.length();\n if (m != n) return false;\n\n for (int offset = 0; offset < n; offset++) {\n if (isMatch(s, goal, offset)) return true;\n }\n return false;\n }\n\n private boolean isMatch(String s, String g, int offset) {\n int n = s.length();\n for (int si = 0; si < n; si++) {\n int gi = (si + offset) % n;\n if (s.charAt(si) != g.charAt(gi)) return false;\n }\n return true;\n }\n}", + "title": "796. Rotate String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s . A shift on s consists of moving the leftmost character of s to the rightmost position.", + "description_images": [], + "constraints": [ + "For example, if s = \"abcde\" , then it will be \"bcdea\" after one shift." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", goal = \"cdeab\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\", goal = \"abced\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 33 ms, faster than 90.10% of Python3 online submissions for Rotate String.\n# Memory Usage: 13.8 MB, less than 97.64% of Python3 online submissions for Rotate String.\n\nclass Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n for x in range(len(s)):\n s = s[-1] + s[:-1]\n if (goal == s):\n return True\n return False\n", + "title": "796. Rotate String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x . Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: Given an integer n , return the number of good integers in the range [1, n] .", + "description_images": [], + "constraints": [ + "0 , 1 , and 8 rotate to themselves,", + "2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),", + "6 and 9 rotate to each other, and", + "the rest of the numbers do not rotate to any other number and become invalid." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:4\nExplanation:There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 82.34%) | Memory: 39.1 MB (Top 97.40%)\nclass Solution {\n public int rotatedDigits(int n) {\n int ans=0;\n for(int i=1; i<=n; i++){\n int k = i;\n boolean bool1=true; boolean bool2=false;\n while(k>0){\n int m=k%10;\n if(m==3 || m==4 || m==7){ bool1=false; break; }\n else if(m==2 || m==5 || m==6 || m==9){ bool2=true; }\n k/=10;\n }\n if(bool1 && bool2){ ans++; }\n }\n return ans;\n }\n}", + "title": "788. Rotated Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x . Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: Given an integer n , return the number of good integers in the range [1, n] .", + "description_images": [], + "constraints": [ + "0 , 1 , and 8 rotate to themselves,", + "2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),", + "6 and 9 rotate to each other, and", + "the rest of the numbers do not rotate to any other number and become invalid." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:4\nExplanation:There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:n = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 226 ms (Top 14.46%) | Memory: 13.9 MB (Top 71.45%)\nclass Solution:\n def rotatedDigits(self, n: int) -> int:\n d={\n 0:0,\n 1:1,\n 2:5,\n 3:None,\n 4: None,\n 5:2,\n 6:9,\n 7:None,\n 8:8,\n 9:6\n }\n res=0\n for i in range(n+1):\n t=i\n pos=0\n temp=0\n status=True\n while t>0:\n r=d[t%10] #Every Digit Rotation Is Must, We Don't Have Choice To Leave It Without Rotating\n if r is None:\n status=False\n break\n\n temp+=((10**pos)*r)\n pos+=1\n t=t//10\n\n if temp!=i and status:\n res+=1\n return res", + "title": "788. Rotated Digits", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise , causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcodewithstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode2withstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode3withstone.png" + ], + "constraints": [ + "A stone '#'", + "A stationary obstacle '*'", + "Empty '.'" + ], + "examples": [ + { + "text": "Example 1: Input:box = [[\"#\",\".\",\"#\"]]\nOutput:[[\".\"],\n  [\"#\"],\n  [\"#\"]]", + "image": null + }, + { + "text": "Example 2: Input:box = [[\"#\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"*\",\".\"]]\nOutput:[[\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\"*\",\"*\"],\n  [\".\",\".\"]]", + "image": null + }, + { + "text": "Example 3: Input:box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n  [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\nOutput:[[\".\",\"#\",\"#\"],\n  [\".\",\"#\",\"#\"],\n  [\"#\",\"#\",\"*\"],\n  [\"#\",\"*\",\".\"],\n  [\"#\",\".\",\"*\"],\n  [\"#\",\".\",\".\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 22.29%) | Memory: 144.4 MB (Top 28.51%)\n class Solution {\n public char[][] rotateTheBox(char[][] box) {\n int row = box.length, col = box[0].length;\n char[][] res = new char[col][row];\n // rotate first, then drop\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n res[j][i] = box[row-1-i][j];\n }\n }\n\n for (int i = col - 1; i >= 0; i--) {\n for (int j = 0; j < row; j++) {\n if (res[i][j] == '#') {\n int curRow = i;\n while (curRow+1 < col && res[curRow+1][j] == '.') {\n curRow++;\n }\n if (curRow != i) {\n res[curRow][j] = '#';\n res[i][j] = '.';\n }\n }\n }\n }\n return res;\n }\n }", + "title": "1861. Rotating the Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise , causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcodewithstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode2withstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode3withstone.png" + ], + "constraints": [ + "A stone '#'", + "A stationary obstacle '*'", + "Empty '.'" + ], + "examples": [ + { + "text": "Example 1: Input:box = [[\"#\",\".\",\"#\"]]\nOutput:[[\".\"],\n  [\"#\"],\n  [\"#\"]]", + "image": null + }, + { + "text": "Example 2: Input:box = [[\"#\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"*\",\".\"]]\nOutput:[[\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\"*\",\"*\"],\n  [\".\",\".\"]]", + "image": null + }, + { + "text": "Example 3: Input:box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n  [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\nOutput:[[\".\",\"#\",\"#\"],\n  [\".\",\"#\",\"#\"],\n  [\"#\",\"#\",\"*\"],\n  [\"#\",\"*\",\".\"],\n  [\"#\",\".\",\"*\"],\n  [\"#\",\".\",\".\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n # move stones to right, row by row\n for i in range(len(box)):\n stone = 0\n for j in range(len(box[0])):\n if box[i][j] == '#': # if a stone\n stone += 1\n box[i][j] = '.'\n elif box[i][j] == '*': # if a obstacle\n for m in range(stone):\n box[i][j-m-1] = '#'\n stone = 0\n # if reaches the end of j, but still have stone\n if stone != 0:\n for m in range(stone):\n box[i][j-m] = '#'\n \n # rotate box, same as leetcode #48\n box[:] = zip(*box[::-1])\n \n return box\n", + "title": "1861. Rotating the Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n grid where each cell can have one of three values: 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 .", + "description_images": [], + "constraints": [ + "0 representing an empty cell,", + "1 representing a fresh orange, or", + "2 representing a rotten orange." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2019/02/16/oranges.png" + }, + { + "text": "Example 2: Input:grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput:-1\nExplanation:The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[0,2]]\nOutput:0\nExplanation:Since there are already no fresh oranges at minute 0, the answer is just 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Pair{\n int i;\n int j;\n int t;\n \n public Pair(int i,int j,int t){\n this.i = i;\n this.j = j;\n this.t = t;\n }\n }\n int ans = 0;\n final int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};\n public int orangesRotting(int[][] grid) {\n int countFresh = 0;\n Queue q = new LinkedList<>();\n for(int i=0;i= 0 && c >= 0 && r int:\n visited = set()\n res = 0\n def bfs(grid):\n que = collections.deque()\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 2:\n que.append((i,j))\n que.append(None)\n count = 0 \n while len(que)>0:\n left , right = 0,0\n\t\t\t\t# This other while loop is to make sure that we traverse from all the rotten oranges in one turn.\n while que[0] != None:\n r,c = que.popleft()\n for Cols in [-1,1]:\n if c+Cols>=0 and c+Cols=0 and r+Rows0:\n\t\t\t\t '''\n\t\t\t\t This is required to terminate the loop and prevent infinite loop.\n\t\t\t\t This only appends a None if there is still some values in the que, \n\t\t\t\t else we have completed our traversal and we can stop going any futher.\n\t\t\t\t '''\n que.append(None)\n return count\n res = bfs(grid)\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n return -1\n return res\n", + "title": "994. Rotting Oranges", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array nums . We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]) . Return the running sum of nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^6 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[1,3,6,10]\nExplanation:Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1,1]\nOutput:[1,2,3,4,5]\nExplanation:Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,1,2,10,1]\nOutput:[3,4,6,16,17]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 85.2%) | Memory: 16.70 MB (Top 56.78%)\n\nclass Solution:\n def runningSum(self, nums: List[int]) -> List[int]:\n # The variable that will have the running sum\n tot = 0\n # The array that will hold the running su,\n ans = []\n # For loop\n for ele in nums:\n # Adding the element\n tot += ele\n # Appending this running sum to ans\n ans.append(tot)\n # Return ans\n return ans\n", + "title": "1480. Running Sum of 1d Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D array of integers envelopes where envelopes[i] = [w i , h i ] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other) . Note: You cannot rotate an envelope.", + "description_images": [], + "constraints": [ + "1 <= envelopes.length <= 10^5", + "envelopes[i].length == 2", + "1 <= w i , h i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput:3\nExplanation:The maximum number of envelopes you can Russian doll is3([2,3] => [5,4] => [6,7]).", + "image": null + }, + { + "text": "Example 2: Input:envelopes = [[1,1],[1,1],[1,1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxEnvelopes(int[][] envelopes) {\n\t\t//sort the envelopes considering only width\n Arrays.sort(envelopes, new sortEnvelopes());\n\t\t\n\t\t//Now this is a Longest Increasing Subsequence problem on heights\n\t\t//tempList to store the temporary elements, size of this list will be the length of LIS \n ArrayList tempList = new ArrayList<>();\n tempList.add(envelopes[0][1]);\n\t\t\n for(int i=1; itempList.get(tempList.size()-1)){\n tempList.add(envelopes[i][1]);\n } else{\n\t\t\t//if the element is smaller than the largest(last because it is sorted) element of tempList, replace the largest smaller element of tempList with it..\n\t\t\t//ex->(assume if envelopes[i][1] is 4), then >>[1,7,8] will become [1,4,8]<<\n int index = lowerBound(tempList, envelopes[i][1]);\n tempList.set(index, envelopes[i][1]);\n }\n }\n return tempList.size();\n }\n \n\t//finding the index of greatest smaller element \n public int lowerBound(ArrayList list, int search){\n int start = 0;\n int end = list.size()-1;\n while(start {\n public int compare(int[] a, int[] b){\n if(a[0] == b[0]){\n\t\t//to ignore the duplicates, we are sorting such that, for same width-> element with \n\t\t//largest height would be considered first, in this way all the other smaller heights would\n\t\t//be ignored\n return b[1] - a[1];\n } else{\n return a[0] - b[0];\n }\n }\n}\n", + "title": "354. Russian Doll Envelopes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D array of integers envelopes where envelopes[i] = [w i , h i ] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other) . Note: You cannot rotate an envelope.", + "description_images": [], + "constraints": [ + "1 <= envelopes.length <= 10^5", + "envelopes[i].length == 2", + "1 <= w i , h i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput:3\nExplanation:The maximum number of envelopes you can Russian doll is3([2,3] => [5,4] => [6,7]).", + "image": null + }, + { + "text": "Example 2: Input:envelopes = [[1,1],[1,1],[1,1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1587 ms (Top 72.81%) | Memory: 61.7 MB (Top 65.15%)\n\nfrom bisect import bisect_left\nclass Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n envelopes = sorted(envelopes, key= lambda x:(x[0],-x[1]))\n rst = []\n for _,h in envelopes:\n i = bisect_left(rst,h)\n if i == len(rst):\n rst.append(h)\n else:\n rst[i] = h\n return len(rst)", + "title": "354. Russian Doll Envelopes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.66 MB (Top 84.7%)\n\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Base case: if both trees are null, they are identical\n if (p == null && q == null) {\n return true;\n }\n // If only one tree is null or the values are different, they are not identical\n if (p == null || q == null || p.val != q.val) {\n return false;\n }\n // Recursively check if the left and right subtrees are identical\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}\n", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 21.7%) | Memory: 17.30 MB (Top 8.84%)\n\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n stack = [[p,q]]\n while stack:\n p,q = stack.pop()\n if not p and not q:\t\t\t\t\t#(1)\n continue\n elif p and q and p.val == q.val:\t#(2)\n stack.append([p.left, q.left])\n stack.append([p.right, q.right])\n else:\t\t\t\t\t\t\t\t#(3)\n return False\n return True\n", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"x i ==y i \" or \"x i !=y i \" .Here, x i and y i are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 500", + "equations[i].length == 4", + "equations[i][0] is a lowercase letter.", + "equations[i][1] is either '=' or '!' .", + "equations[i][2] is '=' .", + "equations[i][3] is a lowercase letter." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [\"a==b\",\"b!=a\"]\nOutput:false\nExplanation:If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.", + "image": null + }, + { + "text": "Example 2: Input:equations = [\"b==a\",\"a==b\"]\nOutput:true\nExplanation:We could assign a = 1 and b = 1 to satisfy both equations.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.0%) | Memory: 40.98 MB (Top 47.4%)\n\nclass Solution {\n static int par[];\n\n public static int findPar(int u) {\n return par[u] == u ? u : (par[u] = findPar(par[u]));\n }\n\n public boolean equationsPossible(String[] equations) {\n par = new int[26];\n for (int i = 0; i < 26; i++) {\n par[i] = i;\n }\n\n /*First perform all the merging operation*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '=') {\n if (p1 != p2) {\n if (p1 < p2) {\n par[p2] = p1;\n } else {\n par[p1] = p2;\n }\n }\n } \n }\n\n /*Now traverse on the whole string and search for any != operation and check if there parents are same*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '!') {\n if (p1 == p2) {\n return false;\n }\n }\n }\n return true;\n }\n}", + "title": "990. Satisfiability of Equality Equations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"x i ==y i \" or \"x i !=y i \" .Here, x i and y i are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 500", + "equations[i].length == 4", + "equations[i][0] is a lowercase letter.", + "equations[i][1] is either '=' or '!' .", + "equations[i][2] is '=' .", + "equations[i][3] is a lowercase letter." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [\"a==b\",\"b!=a\"]\nOutput:false\nExplanation:If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.", + "image": null + }, + { + "text": "Example 2: Input:equations = [\"b==a\",\"a==b\"]\nOutput:true\nExplanation:We could assign a = 1 and b = 1 to satisfy both equations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n from collections import defaultdict\n g = defaultdict(list)\n for e in equations:\n if e[1] == '=':\n x = e[0]\n y = e[3]\n g[x].append(y)\n g[y].append(x)\n \n # marked the connected components as 0,1,2,...,25\n ccs = defaultdict(lambda: -1) # -1 means unmarked or unseen\n\n def dfs(node, cc):\n if node not in ccs:\n ccs[node] = cc\n for neighbour in g[node]:\n dfs(neighbour, cc)\n \n for i in range(26):\n dfs(chr(i+97), i)\n \n for e in equations:\n if e[1] == '!':\n x = e[0]\n y = e[3]\n if ccs[x] == ccs[y]:\n return False\n return True", + "title": "990. Satisfiability of Equality Equations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n binary matrix grid . A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0 's to 1 's, and all 1 's to 0 's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves) .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 20", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\nOutput:39\nExplanation:0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-toogle1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 17.33%) | Memory: 42.9 MB (Top 9.03%)\nclass Solution {\n public int matrixScore(int[][] grid) {\n ArrayList arr=new ArrayList();\n for(int i=0;ione)\n {\n arr.add(i);\n }\n }\n for(int i:arr)\n {\n for(int j=0;j int:\n self.grid = grid\n self.height = len(grid)\n self.width = len(grid[0])\n \n for r in range(self.height):\n if not self.grid[r][0]:\n if not self.grid[r][0]:\n self.flipRow(r)\n \n for c in range(1, self.width):\n colSum = self.colSum(c)\n \n if colSum < ceil(self.height/2):\n self.flipCol(c)\n \n return self.calcScore()\n \n", + "title": "861. Score After Flipping Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a balanced parentheses string s , return the score of the string . The score of a balanced parentheses string is based on the following rule:", + "description_images": [], + "constraints": [ + "\"()\" has score 1 .", + "AB has score A + B , where A and B are balanced parentheses strings.", + "(A) has score 2 * A , where A is a balanced parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(())\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 25.38%)\n\nclass Solution {\n public int scoreOfParentheses(String s) {\n Stack st = new Stack<>();\n int score = 0;\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(ch == '('){\n st.push(score);\n score = 0;\n }\n else {\n score = st.pop() + Math.max(2 * score, 1);\n }\n }\n return score;\n }\n}\n", + "title": "856. Score of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a balanced parentheses string s , return the score of the string . The score of a balanced parentheses string is based on the following rule:", + "description_images": [], + "constraints": [ + "\"()\" has score 1 .", + "AB has score A + B , where A and B are balanced parentheses strings.", + "(A) has score 2 * A , where A is a balanced parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(())\"\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n \n level = 0\n result = 0\n prev = \"\"\n \n for c in s: \n if c == \"(\":\n level += 1\n if c == \")\":\n if prev == \"(\":\n result += 2 ** (level - 1)\n level -= 1 \n prev = c\n \n return result\n", + "title": "856. Score of Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length , return true if s2 is a scrambled string of s1 , otherwise, return false .", + "description_images": [], + "constraints": [ + "Split the string into two non-empty substrings at a random index, i.e., if the string is s , divide it to x and y where s = x + y .", + "Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x .", + "Apply step 1 recursively on each of the two substrings x and y ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"great\", s2 = \"rgeat\"\nOutput:true\nExplanation:One possible scenario applied on s1 is:\n\"great\" --> \"gr/eat\" // divide at random index.\n\"gr/eat\" --> \"gr/eat\" // random decision is not to swap the two substrings and keep them in order.\n\"gr/eat\" --> \"g/r / e/at\" // apply the same algorithm recursively on both substrings. divide at random index each of them.\n\"g/r / e/at\" --> \"r/g / e/at\" // random decision was to swap the first substring and to keep the second substring in the same order.\n\"r/g / e/at\" --> \"r/g / e/ a/t\" // again apply the algorithm recursively, divide \"at\" to \"a/t\".\n\"r/g / e/ a/t\" --> \"r/g / e/ a/t\" // random decision is to keep both substrings in the same order.\nThe algorithm stops now, and the result string is \"rgeat\" which is s2.\nAs one possible scenario led s1 to be scrambled to s2, we return true.", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abcde\", s2 = \"caebd\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a\", s2 = \"a\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isScramble(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n if s1 == s2:\n return True\n if len(s1) != len(s2):\n return False\n \n # Check both strings have same count of letters\n count1 = collections.defaultdict(int)\n count2 = collections.defaultdict(int)\n for c1, c2 in zip(s1, s2):\n count1[c1] += 1\n count2[c2] += 1\n if count1 != count2: return False\n \n # Iterate through letters and check if it results in a partition of \n # string 1 where the collection of letters are the same\n # on the left (non-swapped) or right (swapped) sides of string 2\n # Then we recursively check these partitioned strings to see if they are scrambled\n lcount1 = collections.defaultdict(int) # s1 count from left\n lcount2 = collections.defaultdict(int) # s2 count from left\n rcount2 = collections.defaultdict(int) # s2 count from right\n for i in xrange(len(s1) - 1):\n lcount1[s1[i]] += 1 \n lcount2[s2[i]] += 1\n rcount2[s2[len(s1) - 1 - i]] += 1\n if lcount1 == lcount2: # Left sides of both strings have same letters\n if self.isScramble(s1[:i + 1], s2[:i + 1]) and \\\n self.isScramble(s1[i + 1:], s2[i + 1:]):\n return True\n elif lcount1 == rcount2: # Left side of s1 has same letters as right side of s2\n if self.isScramble(s1[:i + 1], s2[-(i + 1):]) and \\\n self.isScramble(s1[i + 1:], s2[:-(i + 1)]):\n return True\n return False\n", + "title": "87. Scramble String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted from left to right.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n if (target < matrix[0][0]) {\n return false;\n }\n for (int i = 0; i < matrix.length; i++) {\n if (matrix[i][0] > target | i == matrix.length - 1) {\n if (matrix[i][0] > target) {\n i--;\n }\n for (int j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] == target) {\n return true;\n }\n }\n return false;\n }\n }\n return false;\n }\n}\n", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted from left to right.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 96.94%) | Memory: 17.90 MB (Top 11.07%)\n\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n n = len(matrix[0])\n def get(idx: int) -> int:\n r, c = divmod(idx, n)\n return matrix[r][c]\n return get(bisect_left(range(len(matrix)*n-1), target, key=get)) == target\n", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 30.54%) | Memory: 57.2 MB (Top 69.94%)\nclass Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n int lo = 0, hi = rows;\n while(lo + 1 < hi) {\n int mid = lo + (hi - lo) / 2;\n if (matrix[mid][0] <= target) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n int[] prospect;\n for (int i = 0; i <= lo; i++) {\n prospect = matrix[i];\n int l = 0;\n int h = cols;\n while (l + 1 < h) {\n int mid = l + (h - l) / 2;\n if (prospect[mid] <= target) {\n l = mid;\n } else {\n h = mid;\n }\n }\n if (prospect[l] == target) {\n return true;\n }\n }\n return false;\n }\n}", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 121 ms (Top 76.1%) | Memory: 19.55 MB (Top 13.9%)\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n found=False\n for X in matrix:\n for M in X:\n if M==target:\n found=True\n return found", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2\nOutput:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 51.2 MB (Top 70.33%)\nclass Solution {\n public TreeNode searchBST(TreeNode root, int val) {\n if (root == null) return root;\n if (root.val == val) {\n return root;\n } else {\n return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);\n }\n }\n}", + "title": "700. Search in a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2\nOutput:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 85.77%) | Memory: 16.7 MB (Top 24.56%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n def search(root):\n if not root:return None\n if root.val==val:\n return root\n elif root.valarr[mid+1]){\n return mid;\n }\n if(mid>start && arr[mid-1]>arr[mid]){\n return mid-1;\n }\n if(arr[mid]<=arr[start]){\n end = mid-1;\n }else{\n start = mid+1;\n }\n }\n return -1;\n }\n \n public int binarySearch(int[] arr, int target, int start, int end){\n \n while(start<=end){\n int mid = start+ (end-start)/2;\n \n \n if(targetarr[mid]){\n start = mid+1;\n }else{\n return mid;\n }\n \n \n }\n return -1;\n }\n \n}\n", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot 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 rotated at pivot index 3 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.", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,6,7,0,1,2], target = 0\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2], target = 3\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], target = 0\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n \n while l<=r:\n mid = (l+r)//2\n if target == nums[mid]:\n return mid\n \n if nums[l]<=nums[mid]:\n if target > nums[mid] or target nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n \n return -1\n", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k ( 0 <= 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,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4] . Given the array nums after the rotation and an integer target , return true if target is in nums , or false if it is not in nums . You must decrease the overall operation steps as much as possible.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "-10^4 <= nums[i] <= 10^4", + "nums is guaranteed to be rotated at some pivot.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,0,0,1,2], target = 0\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,5,6,0,0,1,2], target = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean search(int[] nums, int target) {\n if (nums == null || nums.length == 0) return false;\n \n int left = 0, right = nums.length-1;\n int start = 0;\n\n//1. find index of the smallest element\n while(left < right) {\n while (left < right && nums[left] == nums[left + 1])\n ++left;\n while (left < right && nums[right] == nums[right - 1])\n --right;\n int mid = left + (right-left)/2;\n if (nums[mid] > nums[right]) {\n left = mid +1;\n } else right = mid;\n }\n \n//2. figure out in which side our target lies\n start = left;\n left = 0;\n right = nums.length-1;\n if (target >= nums[start] && target <= nums[right])\n left = start;\n else right = start;\n \n//3. Run normal binary search in sorted half.\n while(left <= right) {\n int mid = left + (right - left)/2;\n if (nums[mid] == target) return true;\n \n if (nums[mid] > target) right = mid-1;\n else left = mid + 1;\n }\n \n return false;\n}\n}\n", + "title": "81. Search in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k ( 0 <= 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,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4] . Given the array nums after the rotation and an integer target , return true if target is in nums , or false if it is not in nums . You must decrease the overall operation steps as much as possible.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "-10^4 <= nums[i] <= 10^4", + "nums is guaranteed to be rotated at some pivot.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,0,0,1,2], target = 0\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,5,6,0,0,1,2], target = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def search(self, nums: List[int], target: int) -> bool:\n nums.sort()\n low=0\n high=len(nums)-1\n while low<=high:\n mid=(low+high)//2\n if nums[mid]==target:\n return True\n elif nums[mid]>target:\n high=mid-1\n else:\n low=mid+1\n return False\n", + "title": "81. Search in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.90 MB (Top 78.78%)\n\nclass Solution {\n public int searchInsert(int[] nums, int target) {\n int start = 0;\n int end = nums.length-1;\n\n while (start <= end) {\n int mid = start + (end-start)/2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] > target) end = mid-1;\n else start = mid+1;\n }\n\n return start;\n }\n}\n", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def searchInsert(self, nums, target):\n for i, num in enumerate(nums):\n if num >= target:\n return i\n return len(nums)", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed .", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput:[\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\nExplanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"\nOutput:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]", + "image": null + }, + { + "text": "Example 3: Input:products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\nOutput:[[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 48.70%) | Memory: 45.5 MB (Top 96.95%)\nclass Solution\n{\n public List> suggestedProducts(String[] products, String searchWord)\n {\n PriorityQueue pq= new PriorityQueue();\n List> res= new LinkedList>();\n List segment= new LinkedList();\n for(int i=0;i();\n pq= reduce(pq,searchWord.substring(0,j+1));\n PriorityQueue pri= new PriorityQueue<>(pq);\n int p=0;\n while(p reduce(PriorityQueue pr, String filter)\n {\n PriorityQueue p= new PriorityQueue<>();\n String s=\"\";\n while(!pr.isEmpty())\n {\n s=pr.poll();\n if(s.startsWith(filter))\n p.add(s);\n }\n return p;\n }\n}", + "title": "1268. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed .", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput:[\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\nExplanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"\nOutput:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]", + "image": null + }, + { + "text": "Example 3: Input:products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\nOutput:[[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 77.93%) | Memory: 19.60 MB (Top 79.27%)\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n list_ = []\n products.sort()\n for i, c in enumerate(searchWord):\n products = [ p for p in products if len(p) > i and p[i] == c ]\n list_.append(products[:3])\n return list_\n", + "title": "1268. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a system that manages the reservation state of n seats that are numbered from 1 to n . Implement the SeatManager class:", + "description_images": [], + "constraints": [ + "SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n . All seats are initially available.", + "int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.", + "void unreserve(int seatNumber) Unreserves the seat with the given seatNumber ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]Output[null, 1, 2, null, 2, 3, 4, 5, null]ExplanationSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 88 ms (Top 72.91%) | Memory: 105 MB (Top 67.49%)\nclass SeatManager {\n PriorityQueue pq;\n int count;\n public SeatManager(int n) {\n count = 1;\n pq = new PriorityQueue();\n }\n\n public int reserve() {\n if(pq.size()==0)\n return count++;\n\n return pq.poll();\n }\n\n public void unreserve(int seatNumber) {\n pq.add(seatNumber);\n }\n}", + "title": "1845. Seat Reservation Manager", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a system that manages the reservation state of n seats that are numbered from 1 to n . Implement the SeatManager class:", + "description_images": [], + "constraints": [ + "SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n . All seats are initially available.", + "int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.", + "void unreserve(int seatNumber) Unreserves the seat with the given seatNumber ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]Output[null, 1, 2, null, 2, 3, 4, 5, null]ExplanationSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].", + "image": null + } + ], + "follow_up": null, + "solution": "class SeatManager:\n def __init__(self, n: int):\n self.lis = list(range(1,n+1))\n def reserve(self) -> int:\n mini = min(self.lis)\n self.lis.remove(mini)\n return mini\n\n def unreserve(self, seatNumber: int) -> None:\n self.lis.append(seatNumber)\n", + "title": "1845. Seat Reservation Manager", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an alphanumeric string s , return the second largest numerical digit that appears in s , or -1 if it does not exist . An alphanumeric string is a string consisting of lowercase English letters and digits.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dfa12321afd\"\nOutput:2\nExplanation:The digits that appear in s are [1, 2, 3]. The second largest digit is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc1111\"\nOutput:-1\nExplanation:The digits that appear in s are [1]. There is no second largest digit.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 72.70%) | Memory: 42.6 MB (Top 56.41%)\nclass Solution {\n public int secondHighest(String s) {\n int[] arr = new int[10];\n for(int i = 0;i=0){\n arr[s.charAt(i)-'0']++;\n }\n }\n boolean first = false;\n for(int i = 9;i>=0;i--){\n if(arr[i] !=0){\n if(first)\n return i;\n else first = true;\n }\n }\n\n return -1;\n }\n}", + "title": "1796. Second Largest Digit in a String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an alphanumeric string s , return the second largest numerical digit that appears in s , or -1 if it does not exist . An alphanumeric string is a string consisting of lowercase English letters and digits.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dfa12321afd\"\nOutput:2\nExplanation:The digits that appear in s are [1, 2, 3]. The second largest digit is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc1111\"\nOutput:-1\nExplanation:The digits that appear in s are [1]. There is no second largest digit.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 80 ms (Top 5.3%) | Memory: 16.30 MB (Top 72.1%)\n\nclass Solution:\n def secondHighest(self, s: str) -> int:\n nums = []\n for char in s:\n if char.isdigit():\n nums.append(int(char))\n nums = [num for num in nums if num != max(nums)]\n if len(nums) >= 1: return max(nums)\n else: return -1", + "title": "1796. Second Largest Digit in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 25] .", + "1 <= Node.val <= 2 31 - 1", + "root.val == min(root.left.val, root.right.val) for each internal node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,2,5,null,null,5,7]\nOutput:5\nExplanation:The smallest value is 2, the second smallest value is 5.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" + }, + { + "text": "Example 2: Input:root = [2,2,2]\nOutput:-1\nExplanation:The smallest value is 2, but there isn't any second smallest value.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 20.63%)\nclass Solution {\n int ans = Integer.MAX_VALUE;\n boolean x = true;\n\n public int findSecondMinimumValue(TreeNode root) {\n go(root);\n return x ? -1 : ans;\n }\n\n private void go(TreeNode root) {\n if (root == null) return;\n if (root.left != null) {\n if (root.left.val == root.val) go(root.left);\n else {\n x = false;\n ans = Math.min(ans, root.left.val);\n }\n }\n if (root.right != null) {\n if (root.right.val == root.val) go(root.right);\n else {\n x = false;\n ans = Math.min(ans, root.right.val);\n }\n }\n }\n}", + "title": "671. Second Minimum Node In a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 25] .", + "1 <= Node.val <= 2 31 - 1", + "root.val == min(root.left.val, root.right.val) for each internal node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,2,5,null,null,5,7]\nOutput:5\nExplanation:The smallest value is 2, the second smallest value is 5.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" + }, + { + "text": "Example 2: Input:root = [2,2,2]\nOutput:-1\nExplanation:The smallest value is 2, but there isn't any second smallest value.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n temp1=temp2=float(inf)\n from collections import deque\n a=deque([root])\n while a:\n node=a.popleft()\n if node.valtemp1:\n if node.val", + "title": "671. Second Minimum Node In a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time . You can enter a vertex at any time , but can leave a vertex only when the signal is green . You cannot wait at a vertex if the signal is green . The second minimum value is defined as the smallest value strictly larger than the minimum value. Given n , edges , time , and change , return the second minimum time it will take to go from vertex 1 to vertex n . Notes:", + "description_images": [], + "constraints": [ + "For example the second minimum value of [2, 3, 4] is 3 , and the second minimum value of [2, 2, 4] is 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5\nOutput:13\nExplanation:The figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/e2.png" + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]], time = 3, change = 2\nOutput:11\nExplanation:The minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/eg2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 254 ms (Top 50.50%) | Memory: 51.9 MB (Top 97.03%)\nclass Solution {\n public int secondMinimum(int n, int[][] edges, int time, int change) {\n Map> g = new HashMap();\n for(int[] e : edges) {\n int u = e[0], v = e[1];\n g.computeIfAbsent(u, x -> new ArrayList()).add(v);\n g.computeIfAbsent(v, x -> new ArrayList()).add(u);\n }\n PriorityQueue q = new PriorityQueue<>((a,b) -> a[1] - b[1]);\n q.offer(new int[]{1, 0});\n int[] uniqueVisit = new int[n+1]; // uniqueVisit limit to 2 <==> relax twice at most\n int[] dis = new int[n+1];\n Arrays.fill(dis, -1);\n while(!q.isEmpty()) {\n int size = q.size();\n int[] cur = q.poll();\n int node = cur[0], t = cur[1]; // arriving time\n if(dis[node] == t || uniqueVisit[node] >= 2) continue; // skip if it's same value or has been relaxed twice already\n uniqueVisit[node]++;\n dis[node] = t;\n if(node == n && uniqueVisit[node] == 2) return dis[node];\n // generate leaving time (waiting the green light)\n if((t / change) % 2 != 0) t = (t/change + 1) * change;\n for(int nei : g.getOrDefault(node, new ArrayList<>())) {\n q.offer(new int[]{nei, t + time});\n }\n }\n return -1;\n }\n}", + "title": "2045. Second Minimum Time to Reach Destination", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time . You can enter a vertex at any time , but can leave a vertex only when the signal is green . You cannot wait at a vertex if the signal is green . The second minimum value is defined as the smallest value strictly larger than the minimum value. Given n , edges , time , and change , return the second minimum time it will take to go from vertex 1 to vertex n . Notes:", + "description_images": [], + "constraints": [ + "For example the second minimum value of [2, 3, 4] is 3 , and the second minimum value of [2, 2, 4] is 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5\nOutput:13\nExplanation:The figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/e2.png" + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]], time = 3, change = 2\nOutput:11\nExplanation:The minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/eg2.png" + } + ], + "follow_up": null, + "solution": "from heapq import heappop,heappush\nfrom collections import defaultdict\n\nclass Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n G = defaultdict(list)\n dist = defaultdict(set)\n for v, w in edges:\n G[v].append(w)\n G[w].append(v)\n h = [(0, 1)]\n res = []\n while h:\n d, v = heappop(h)\n if len(dist[v]) > 1:\n continue\n if d in dist[v]:\n continue\n dist[v].add(d)\n q, r = divmod(d, change)\n if q%2 == 1:\n d += change - r\n for w in G[v]:\n if w == n:\n if res:\n if d+time not in res:\n return d+time\n else:\n res.append(d+time)\n if len(dist[w]) < 2:\n heappush(h, (d+time,w))\n", + "title": "2045. Second Minimum Time to Reach Destination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers distance . You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not.", + "description_images": [], + "constraints": [ + "1 <= distance.length <= 10^5", + "1 <= distance[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [2,1,1,2]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg" + }, + { + "text": "Example 2: Input:distance = [1,2,3,4]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg" + }, + { + "text": "Example 3: Input:distance = [1,1,1,1]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b) return true; // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true; // cross [i - 4]\n\nif (x[i] < a) arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}", + "title": "335. Self Crossing", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of integers distance . You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not.", + "description_images": [], + "constraints": [ + "1 <= distance.length <= 10^5", + "1 <= distance[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [2,1,1,2]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg" + }, + { + "text": "Example 2: Input:distance = [1,2,3,4]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg" + }, + { + "text": "Example 3: Input:distance = [1,1,1,1]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSelfCrossing(self, x):\n n = len(x)\n if n < 4: return False\n for i in range(3, n):\n if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True\n if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True\n if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] and 0<=x[i-3]-x[i-1]<=x[i-5]: return True\n return False\n \n", + "title": "335. Self Crossing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right , return a list of all the self-dividing numbers in the range [left, right] .", + "description_images": [], + "constraints": [ + "For example, 128 is a self-dividing number because 128 % 1 == 0 , 128 % 2 == 0 , and 128 % 8 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 22\nOutput:[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "image": null + }, + { + "text": "Example 2: Input:left = 47, right = 85\nOutput:[48,55,66,77]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List selfDividingNumbers(int left, int right) {\n List ans= new ArrayList<>();\n while(left<=right){\n if(fun(left))\n ans.add(left); \n left++;\n }\n return ans;\n }\n boolean fun(int x){\n int k=x;\n while(k>0)\n {\n int y=k%10;\n k=k/10;\n if(y==0||x%y!=0)\n return false;\n }\n return true;\n }\n}\n", + "title": "728. Self Dividing Numbers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right , return a list of all the self-dividing numbers in the range [left, right] .", + "description_images": [], + "constraints": [ + "For example, 128 is a self-dividing number because 128 % 1 == 0 , 128 % 2 == 0 , and 128 % 8 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 22\nOutput:[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "image": null + }, + { + "text": "Example 2: Input:left = 47, right = 85\nOutput:[48,55,66,77]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 99 ms (Top 32.60%) | Memory: 13.9 MB (Top 25.64%)\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n res = []\n for num in range(left, right + 1):\n num_str = str(num)\n if '0' in num_str:\n continue\n elif all([num % int(digit_str) == 0 for digit_str in num_str]):\n res.append(num)\n return res", + "title": "728. Self Dividing Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory . For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory , where inventory[i] represents the number of balls of the i th color that you initially own. You are also given an integer orders , which represents the total number of balls that the customer wants. You can sell the balls in any order . Return the maximum total value that you can attain after selling orders colored balls . As the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= inventory.length <= 10^5", + "1 <= inventory[i] <= 10^9", + "1 <= orders <= min(sum(inventory[i]), 10^9 )" + ], + "examples": [ + { + "text": "Example 1: Input:inventory = [2,5], orders = 4\nOutput:14\nExplanation:Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/jj.gif" + }, + { + "text": "Example 2: Input:inventory = [3,5], orders = 6\nOutput:19\nExplanation:Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private long mod = 1000000007L;\n public int maxProfit(int[] inventory, int orders) {\n\t\t// we use pq to find the most balls\n PriorityQueue pq = new PriorityQueue<>((x, y) -> Long.compare(y, x));\n pq.offer(0L);\n\t\t\n // we use map to count the balls\n Map map = new HashMap<>();\n map.put(0L, 0L);\n \n for (int j : inventory) {\n long i = (long)j;\n if (map.containsKey(i)) {\n map.put(i, map.get(i) + 1);\n }\n else {\n pq.offer(i);\n map.put(i, 1L);\n }\n }\n \n long res = 0;\n while (orders > 0) {\n long ball = pq.poll(), nextBall = pq.peek();\n long times = map.get(ball);\n long diff = Math.min(ball - nextBall, orders / times);\n if (diff == 0) {\n res = (res + orders * ball) % mod;\n break;\n }\n long sum = (ball * 2 + 1 - diff) * diff / 2 * times;\n res = (res + sum) % mod;\n orders -= diff * times;\n if (!map.containsKey(ball - diff)) {\n map.put(ball - diff, map.get(ball));\n pq.offer(ball - diff);\n }\n else {\n map.put(ball - diff, map.get(ball - diff) + map.get(ball));\n }\n map.remove(ball);\n }\n return (int) res;\n }\n}\n", + "title": "1648. Sell Diminishing-Valued Colored Balls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory . For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory , where inventory[i] represents the number of balls of the i th color that you initially own. You are also given an integer orders , which represents the total number of balls that the customer wants. You can sell the balls in any order . Return the maximum total value that you can attain after selling orders colored balls . As the answer may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= inventory.length <= 10^5", + "1 <= inventory[i] <= 10^9", + "1 <= orders <= min(sum(inventory[i]), 10^9 )" + ], + "examples": [ + { + "text": "Example 1: Input:inventory = [2,5], orders = 4\nOutput:14\nExplanation:Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/jj.gif" + }, + { + "text": "Example 2: Input:inventory = [3,5], orders = 6\nOutput:19\nExplanation:Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True) \n inventory += [0]\n res = 0\n k = 1\n \n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i]-inventory[i+1]) < orders:\n diff = inventory[i]-inventory[i+1]\n res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2\n orders -= k*diff\n else: \n q, r = divmod(orders, k)\n res += k*(inventory[i]+(inventory[i]-q+1))*q//2\n res += r*(inventory[i]-q)\n return res%(10**9+7)\n k += 1\n", + "title": "1648. Sell Diminishing-Valued Colored Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices , where prices[i] = [h i , w i , price i ] indicates you can sell a rectangular piece of wood of height h i and width w i for price i dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices . You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood . Note that you can cut the piece of wood as many times as you want.", + "description_images": [], + "constraints": [ + "1 <= m, n <= 200", + "1 <= prices.length <= 2 * 10^4", + "prices[i].length == 3", + "1 <= h i <= m", + "1 <= w i <= n", + "1 <= price i <= 10^6", + "All the shapes of wood (h i , w i ) are pairwise distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\nOutput:19\nExplanation:The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex1.png" + }, + { + "text": "Example 2: Input:m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\nOutput:32\nExplanation:The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex2new.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public long sellingWood(int m, int n, int[][] prices) {\n long[][] dp = new long[m+1][n+1];\n for (int[] price : prices) {\n dp[price[0]][price[1]] = price[2];\n }\n for (int i = 1; i < m+1; i++) {\n for (int j = 1; j < n+1; j++) {\n // all horizontal\n for (int k = 1; k <= i/2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[i-k][j] + dp[k][j]);\n }\n // all vertical\n for (int k = 1; k <= j/2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[i][j-k] + dp[i][k]);\n }\n }\n }\n \n return dp[m][n];\n }\n}\n", + "title": "2312. Selling Pieces of Wood", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices , where prices[i] = [h i , w i , price i ] indicates you can sell a rectangular piece of wood of height h i and width w i for price i dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices . You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood . Note that you can cut the piece of wood as many times as you want.", + "description_images": [], + "constraints": [ + "1 <= m, n <= 200", + "1 <= prices.length <= 2 * 10^4", + "prices[i].length == 3", + "1 <= h i <= m", + "1 <= w i <= n", + "1 <= price i <= 10^6", + "All the shapes of wood (h i , w i ) are pairwise distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\nOutput:19\nExplanation:The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex1.png" + }, + { + "text": "Example 2: Input:m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\nOutput:32\nExplanation:The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex2new.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n price = {(dimension_price[0], dimension_price[1]): dimension_price[2] for dimension_price in prices}\n DP = [[-1 for _ in range(n + 1)] for _ in range(m + 1)]\n \n def solve(h: int, v: int) -> int:\n if DP[h][v] != -1:\n return DP[i][j]\n \n ans = price.get((h, v), 0)\n \n for i in range(1, 1 + h // 2):\n ans = max(ans, (DP[i][v] if DP[i][v] != -1 else solve(i, v)) + (DP[h - i][v] if DP[h - i][v] != -1 else solve(h - i, v)))\n \n for j in range(1, 1 + v // 2):\n ans = max(ans, (DP[h][j] if DP[h][j] != -1 else solve(h, j)) + (DP[h][v - j] if DP[h][v - j] != -1 else solve(h, v - j)))\n \n DP[h][v] = ans\n \n return ans\n \n return solve(m, n)\n", + "title": "2312. Selling Pieces of Wood", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i] . A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count . If there is more than one sender with the largest word count, return the one with the lexicographically largest name . Note:", + "description_images": [], + "constraints": [ + "Uppercase letters come before lowercase letters in lexicographical order.", + "\"Alice\" and \"alice\" are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]\nOutput:\"Alice\"\nExplanation:Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return \"Alice\".", + "image": null + }, + { + "text": "Example 2: Input:messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]\nOutput:\"Charlie\"\nExplanation:Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 92.47%) | Memory: 48.80 MB (Top 99.46%)\n\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) \n {\n HashMap map = new HashMap<>();\n String res = \"\";int max =0;\n \n for(int i=0; i max)\n {\n res = s;\n max = map.get(s);\n }\n \n if(map.get(s) == max && res.compareTo(s) < 0)\n res = s;\n }\n return res;\n }\n \n private int get_count(String s)\n {\n int spaces = 0;\n \n for(int i=0; i str:\n d={}\n l=[]\n for i in range(len(messages)):\n if senders[i] not in d:\n d[senders[i]]=len(messages[i].split())\n else:\n d[senders[i]]+=len(messages[i].split())\n x=max(d.values())\n for k,v in d.items():\n if v==x :\n l.append(k)\n if len(l)==1:\n return l[0]\n else:\n l=sorted(l)[::-1] #Lexigograhical sorting of list\n return l[0]\n", + "title": "2284. Sender With Largest Word Count", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, \"Hello World\" , \"HELLO\" , \"hello world hello world\" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2 . Given two sentences sentence1 and sentence2 , return true if sentence1 and sentence2 are similar. Otherwise, return false .", + "description_images": [], + "constraints": [ + "1 <= sentence1.length, sentence2.length <= 100", + "sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.", + "The words in sentence1 and sentence2 are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"\nOutput:true\nExplanation:sentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".", + "image": null + }, + { + "text": "Example 2: Input:sentence1 = \"of\", sentence2 = \"A lot of words\"\nOutput:false\nExplanation:No single sentence can be inserted inside one of the sentences to make it equal to the other.", + "image": null + }, + { + "text": "Example 3: Input:sentence1 = \"Eating right now\", sentence2 = \"Eating\"\nOutput:true\nExplanation:sentence2 can be turned to sentence1 by inserting \"right now\" at the end of the sentence.", + "image": null + } + ], + "follow_up": null, + "solution": "2", + "title": "1813. Sentence Similarity III", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.", + "description_images": [], + "constraints": [ + "10 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 100, high = 300\nOutput:[123,234]", + "image": null + }, + { + "text": "Example 2: Input:low = 1000, high = 13000\nOutput:[1234,2345,3456,4567,5678,6789,12345]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 53.25%)\nclass Solution {\n public List sequentialDigits(int low, int high) {\n int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length();\n List output = new ArrayList<>();\n\n for(int size=lowSize; size<=highSize; size++) {\n int seedNumber = getSeedNumber(size);\n int increment = getIncrement(size);\n int limit = (int)Math.pow(10,size);\n // System.out.println(seedNumber+\":\"+increment+\":\"+limit);\n while(true){\n if(seedNumber>=low && seedNumber<=high)\n output.add(seedNumber);\n if(seedNumber%10==9 || seedNumber>high) break;\n seedNumber+=increment;\n }\n }\n return output;\n }\n\n private int getSeedNumber(int size) {\n int seed = 1;\n for(int i=2;i<=size;i++)\n seed=10*seed + i;\n return seed;\n }\n\n private int getIncrement(int size) {\n int increment = 1;\n for(int i=2;i<=size;i++)\n increment=10*increment + 1;\n return increment;\n }\n}", + "title": "1291. Sequential Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.", + "description_images": [], + "constraints": [ + "10 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 100, high = 300\nOutput:[123,234]", + "image": null + }, + { + "text": "Example 2: Input:low = 1000, high = 13000\nOutput:[1234,2345,3456,4567,5678,6789,12345]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 41 ms (Top 43.2%) | Memory: 16.29 MB (Top 65.6%)\n\nclass Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n l = len(str(low))\n h = len(str(high))\n ans = []\n for i in range(l,h+1):\n for j in range(1,11-i):\n t = str(j)\n for k in range(i-1):\n t+=str(int(t[-1])+1)\n if int(t)<=high and int(t)>=low:\n ans.append(int(t))\n ans.sort()\n return ans\n", + "title": "1291. Sequential Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A scenic location is represented by its name and attractiveness score , where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time , the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class:", + "description_images": [], + "constraints": [ + "Adding scenic locations, one at a time .", + "Querying the i th best location of all locations already added , where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added.", + "For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added." + ], + "examples": [ + { + "text": "Example 1: Input[\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n[[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]Output[null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]ExplanationSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\ntracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\ntracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to itshigher score(3 > 2).\n // This is the 1sttime get() is called, so return the best location: \"branford\".\ntracker.add(\"alps\", 2); // Add location with name=\"alps\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because \"alps\" islexicographically smallerthan \"bradford\".\n // Return the 2ndbest location \"alps\", as it is the 2ndtime get() is called.\ntracker.add(\"orland\", 2); // Add location with name=\"orland\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return \"bradford\", as it is the 3rdtime get() is called.\ntracker.add(\"orlando\", 3); // Add location with name=\"orlando\" and score=3 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return \"bradford\".\ntracker.add(\"alpine\", 2); // Add location with name=\"alpine\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"bradford\".\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"orland\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 996 ms (Top 5.13%) | Memory: 131.3 MB (Top 81.29%)\nclass SORTracker {\n\n private TreeMap> map;\n private int queryNum;\n\n // Find suitable position for name in the list\n private int getIndex(String name, List list) {\n int l = 0, r = list.size() - 1, m = 0;\n while (l < r) {\n m = l + (r - l) / 2;\n if(name.compareTo(list.get(m)) > 0) {\n l = m + 1;\n } else {\n r = m;\n }\n }\n return name.compareTo(list.get(l)) > 0 ? l+1 : l;\n }\n\n public SORTracker() {\n map = new TreeMap<>((a,b) -> (b-a));\n queryNum = 0;\n }\n\n public void add(String name, int score) {\n List list = map.getOrDefault(score, new ArrayList<>());\n int index = (list.size() == 0) ? 0 : getIndex(name, list);\n list.add(index, name);\n map.put(score, list);\n }\n\n public String get() {\n int index = queryNum;\n for (int score: map.keySet()) {\n if (index < map.get(score).size()) {\n queryNum++;\n return map.get(score).get(index);\n }\n index -= map.get(score).size();\n }\n return \"\";\n }\n}", + "title": "2102. Sequentially Ordinal Rank Tracker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A scenic location is represented by its name and attractiveness score , where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time , the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class:", + "description_images": [], + "constraints": [ + "Adding scenic locations, one at a time .", + "Querying the i th best location of all locations already added , where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added.", + "For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added." + ], + "examples": [ + { + "text": "Example 1: Input[\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n[[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]Output[null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]ExplanationSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\ntracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\ntracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to itshigher score(3 > 2).\n // This is the 1sttime get() is called, so return the best location: \"branford\".\ntracker.add(\"alps\", 2); // Add location with name=\"alps\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because \"alps\" islexicographically smallerthan \"bradford\".\n // Return the 2ndbest location \"alps\", as it is the 2ndtime get() is called.\ntracker.add(\"orland\", 2); // Add location with name=\"orland\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return \"bradford\", as it is the 3rdtime get() is called.\ntracker.add(\"orlando\", 3); // Add location with name=\"orlando\" and score=3 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return \"bradford\".\ntracker.add(\"alpine\", 2); // Add location with name=\"alpine\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"bradford\".\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"orland\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 675 ms (Top 95.65%) | Memory: 40.70 MB (Top 63.04%)\n\nfrom sortedcontainers import SortedList\nclass SORTracker:\n\n def __init__(self):\n self.arr=SortedList()\n self.index=-1\n def add(self, name: str, score: int) -> None:\n self.arr.add([-score,name])\n \n def get(self) -> str:\n \n self.index+=1\n return self.arr[self.index][1]\n\n\n# Your SORTracker object will be instantiated and called as such:\n# obj = SORTracker()\n# obj.add(name,score)\n# param_2 = obj.get()\n", + "title": "2102. Sequentially Ordinal Rank Tracker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,null,4,5]\nOutput:[1,2,3,null,null,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "public class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n String data=\"\";\n Queue q=new LinkedList<>();\n if(root!=null)\n q.add(root);\n else\n return \"\";\n data=Integer.toString(root.val)+\"e\";\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i q=new LinkedList<>();\n q.add(root);\n while(i root.val){\n if(root.right != null)\n insert(digit, root.right);\n else\n root.right = new TreeNode(digit);\n } else {\n if(root.left != null)\n insert(digit, root.left);\n else\n root.left = new TreeNode(digit);\n }\n\n }\n}", + "title": "449. Serialize and Deserialize BST", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Serialization is 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 search tree . There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The input tree is guaranteed to be a binary search tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:[2,1,3]", + "image": null + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n \"\"\"Encodes a tree to a single string.\n \"\"\"\n if not root:\n return \"\"\n res = []\n def dfs(node):\n res.append(str(node.val))\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n dfs(root)\n return ','.join(res)\n def deserialize(self, data: str) -> Optional[TreeNode]:\n \"\"\"Decodes your encoded data to tree.\n \"\"\"\n if len(data) == 0:\n return []\n splitdata = data.split(\",\") \n preorder = []\n for item in splitdata:\n preorder.append(int(item)) \n inorder = sorted(preorder)\n hash_map = {} \n for i in range(len(inorder)):\n hash_map[inorder[i]] = i\n def helper(preorder, pstart, pend, inorder, istart, iend):\n if pstart > pend:\n return None\n elif pstart == pend:\n return TreeNode(preorder[pstart])\n\n root = TreeNode(preorder[pstart])\n \n rootindex = hash_map[preorder[pstart]]\n \n numleft = rootindex - istart\n \n root.left = helper(preorder, pstart+1, pstart + numleft, inorder, istart,rootindex-1 )\n root.right = helper(preorder, pstart + numleft +1, pend, inorder, rootindex +1, iend)\n \n return root\n \n return (helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1))\n", + "title": "449. Serialize and Deserialize BST", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer interval [a, b] (for integers a < b ) is a set of all consecutive integers from a to b , including a and b . Find the minimum size of a set S such that for every integer interval A in intervals , the intersection of S with A has a size of at least two.", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 3000", + "intervals[i].length == 2", + "0 <= a i < b i <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput:3\nExplanation:Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\nAlso, there isn't a smaller size set that fulfills the above condition.\nThus, we output the size of this set, which is 3.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput:5\nExplanation:An example of a minimum sized set is {1, 2, 3, 4, 5}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 28.66%) | Memory: 53.2 MB (Top 21.64%)\n//Time Complexity O(Nlog(N)) - N is the number of intervals\n//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed\nclass Solution {\n public int intersectionSizeTwo(int[][] intervals) {\n //corner case: can intervals be null or empty? No\n\n //First, sort the intervals by end, then by reverse order start\n Arrays.sort(intervals, new Comparator() {\n @Override\n public int compare(int[] a, int[] b) {\n if (a[1] == b[1]) {\n return b[0] - a[0];\n }\n return a[1] - b[1];\n }\n });\n\n //Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request\n List list = new ArrayList<>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition\n\n //add last two nums within the range\n list.add(intervals[0][1] - 1);\n list.add(intervals[0][1]);\n\n for (int i = 1; i < intervals.length; i++) {\n int lastOne = list.get(list.size() - 1);\n int lastTwo = list.get(list.size() - 2);\n\n int[] interval = intervals[i];\n int start = interval[0];\n int end = interval[1];\n\n //if overlaps at least 2\n if (lastOne >= start && lastTwo >= start) {\n continue;\n } else if (lastOne >= start) { //if overlaps 1\n list.add(end);\n } else { //if not overlapping\n list.add(end - 1);\n list.add(end);\n }\n }\n\n return list.size();\n }\n}", + "title": "757. Set Intersection Size At Least Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer interval [a, b] (for integers a < b ) is a set of all consecutive integers from a to b , including a and b . Find the minimum size of a set S such that for every integer interval A in intervals , the intersection of S with A has a size of at least two.", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 3000", + "intervals[i].length == 2", + "0 <= a i < b i <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput:3\nExplanation:Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\nAlso, there isn't a smaller size set that fulfills the above condition.\nThus, we output the size of this set, which is 3.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput:5\nExplanation:An example of a minimum sized set is {1, 2, 3, 4, 5}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)", + "title": "757. Set Intersection Size At Least Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 25.0%) | Memory: 44.70 MB (Top 37.39%)\n\nclass Solution {\n public void setZeroes(int[][] matrix) {\n Set row = new HashSet<>();\n Set col = new HashSet<>();\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] == 0){\n row.add(i);\n col.add(j);\n }\n }\n }\n for(int r : row){\n for(int i = 0; i < matrix[0].length; i++){\n matrix[r][i] = 0;\n }\n }\n for(int c : col){\n for(int i = 0; i < matrix.length; i++){\n matrix[i][c] = 0;\n }\n }\n }\n}\n", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void setZeroes(int[][] matrix) { \n\t\tif (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n\t\t\treturn;\n\n\t\tint row = matrix.length;\n\t\tint col = matrix[0].length;\n\n\t\tboolean firstColumnZero = false;\n\t\tboolean firstRowZero = false;\n\n\t\t// Check if first column should be made zero\n\t\tfor (int i = 0; i < row; i++) {\n\t\t\tif (matrix[i][0] == 0) {\n\t\t\t\tfirstColumnZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Check if first row should be made zero\n\t\tfor (int i = 0; i < col; i++) {\n\t\t\tif (matrix[0][i] == 0) {\n\t\t\t\tfirstRowZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse the matrix excluding first row and column\n\t\t// If zero is found, update the same in first row and column\n\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][j] == 0) {\n\t\t\t\t\tmatrix[i][0] = 0;\n\t\t\t\t\tmatrix[0][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Now traverse again and update\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][0] == 0 || matrix[0][j] == 0) {\n\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first column\n\t\tif (firstColumnZero) {\n\t\t\tfor (int i = 0; i < row; i++) {\n\t\t\t\tmatrix[i][0] = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first row\n\t\tif (firstRowZero) {\n\t\t\tfor (int j = 0; j < col; j++) {\n\t\t\t\tmatrix[0][j] = 0;\n\t\t\t}\n\t\t}\n\n\t\n }\n}\n", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n rows = len(matrix)\n cols = len(matrix[0])\n visited=set()\n for r in range(rows):\n for c in range(cols):\n \n if matrix[r][c]==0 and (r,c) not in visited :\n for t in range(cols):\n if matrix[r][t]!=0:\n matrix[r][t]=0\n visited.add((r,t))\n for h in range(rows):\n if matrix[h][c]!=0:\n matrix[h][c]=0\n visited.add((h,c))\n ##Time Complexity :- O(m*n)\n ##Space Complexity:- O(m+n)\n\t\t\n\t\t```", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a set of integers s , which originally contains all the numbers from 1 to n . Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,4]\nOutput:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.57%) | Memory: 45.20 MB (Top 54.78%)\n\nclass Solution {\n public int[] findErrorNums(int[] nums) {\n int N = nums.length, sum = N * (N + 1) / 2;\n int[] ans = new int[2];\n boolean[] seen = new boolean[N+1];\n for (int num : nums) {\n sum -= num;\n if (seen[num]) ans[0] = num;\n seen[num] = true;\n }\n ans[1] = sum + ans[0];\n return ans;\n }\n}\n", + "title": "645. Set Mismatch", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a set of integers s , which originally contains all the numbers from 1 to n . Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,4]\nOutput:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 93.95%) | Memory: 18.00 MB (Top 86.53%)\n\nclass Solution:\n def findErrorNums(self, nums):\n n = len(nums)\n v = [0] * (n + 1)\n missing, duplicate = 0, 0\n\n for num in nums:\n v[num] += 1\n\n for i in range(1, len(v)):\n if v[i] == 2:\n duplicate = i\n if v[i] == 0:\n missing = i\n\n return [duplicate, missing]\n\n\n", + "title": "645. Set Mismatch", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 2D grid of size m x n and an integer k . You need to shift the grid k times. In one shift operation: Return the 2D grid after applying shift operation k times.", + "description_images": [], + "constraints": [ + "Element at grid[i][j] moves to grid[i][j + 1] .", + "Element at grid[i][n - 1] moves to grid[i + 1][0] .", + "Element at grid[m - 1][n - 1] moves to grid[0][0] ." + ], + "examples": [ + { + "text": "Example 1: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput:[[9,1,2],[3,4,5],[6,7,8]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e1.png" + }, + { + "text": "Example 2: Input:grid= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e2.png" + }, + { + "text": "Example 3: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput:[[1,2,3],[4,5,6],[7,8,9]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> shiftGrid(int[][] grid, int k) {\n // just bruteforce??? O(i*j*k)\n // instead we calculate the final position at once!\n \n int m = grid.length; // row\n int n = grid[0].length; // column\n \n int[][] arr = new int[m][n];\n \n // Since moving m*n times will result in same matrix, we do this:\n k = k % (m*n);\n \n // Then we move each element\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // for calculating column, it back to the original position\n // every n steps\n int column = (j + k) % n;\n \n // for calculating row, we move to the next row each time\n // it exceed the last element on the current row.\n // For example when 2 moves k=5 steps it turns to the (+2) row.\n // Thus it's original row + ((original column + steps) / n)\n // But if 2 moves k=8 steps it turns to the (0,0),\n // and row + ((original column + steps) / n) gives 0+(9/3)=3 (out of bounds)\n // so we'll need to % number of rows to get 0. (circle back)\n int row = (i + ((j + k) / n)) % m;\n arr[row][column] = grid[i][j];\n }\n }\n return (List) Arrays.asList(arr);\n }\n}\n", + "title": "1260. Shift 2D Grid", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid of size m x n and an integer k . You need to shift the grid k times. In one shift operation: Return the 2D grid after applying shift operation k times.", + "description_images": [], + "constraints": [ + "Element at grid[i][j] moves to grid[i][j + 1] .", + "Element at grid[i][n - 1] moves to grid[i + 1][0] .", + "Element at grid[m - 1][n - 1] moves to grid[0][0] ." + ], + "examples": [ + { + "text": "Example 1: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput:[[9,1,2],[3,4,5],[6,7,8]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e1.png" + }, + { + "text": "Example 2: Input:grid= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e2.png" + }, + { + "text": "Example 3: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput:[[1,2,3],[4,5,6],[7,8,9]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0])\n cache = []\n for i in range(m):\n for j in range(n):\n cache.append(grid[i][j])\n \n k %= len(cache)\n new_vals = cache[-k:] + cache[:-k]\n \n cur = 0\n for i in range(m):\n for j in range(n):\n grid[i][j] = new_vals[cur]\n cur += 1\n \n return grid\n", + "title": "1260. Shift 2D Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a' ). Now for each shifts[i] = x , we want to shift the first i + 1 letters of s , x times. Return the final string after all such shifts to s are applied .", + "description_images": [], + "constraints": [ + "For example, shift('a') = 'b' , shift('t') = 'u' , and shift('z') = 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", shifts = [3,5,9]\nOutput:\"rpl\"\nExplanation:We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\", shifts = [1,2,3]\nOutput:\"gfd\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 23.48%) | Memory: 82.1 MB (Top 8.82%)\nclass Solution {\n public String shiftingLetters(String s, int[] shifts) {\n char[] arr = s.toCharArray();\n int[] arr1 = new int[shifts.length];\n arr1[arr1.length-1] = (shifts[shifts.length-1])%26;\n for(int i =shifts.length -2 ;i>=0 ;i--){\n arr1[i] = (shifts[i] + arr1[i+1])%26;\n }\n for(int i =0; i122){\n int m = arr1[i] -(122-c);\n n = m+96;\n }\n char ch = (char)n;\n arr[i] = ch;\n\n }\n String string = new String(arr);\n return string;\n\n }\n}", + "title": "848. Shifting Letters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a' ). Now for each shifts[i] = x , we want to shift the first i + 1 letters of s , x times. Return the final string after all such shifts to s are applied .", + "description_images": [], + "constraints": [ + "For example, shift('a') = 'b' , shift('t') = 'u' , and shift('z') = 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", shifts = [3,5,9]\nOutput:\"rpl\"\nExplanation:We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\", shifts = [1,2,3]\nOutput:\"gfd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n n = len(s)\n nums = []\n sums = 0\n for i in shifts[::-1]:\n sums = (sums+i)%26\n nums.append(sums)\n nums = nums[::-1]\n \n res = ''\n for i, ch in enumerate(s):\n val = ord(s[i]) + nums[i]\n while val > 122:\n val -= 26\n res += chr(val)\n \n return res", + "title": "848. Shifting Letters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the i th item, and an integer array needs where needs[i] is the number of pieces of the i th item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the j th item in the i th offer and special[i][n] (i.e., the last integer in the array) is the price of the i th offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers . You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.", + "description_images": [], + "constraints": [ + "n == price.length == needs.length", + "1 <= n <= 6", + "0 <= price[i], needs[i] <= 10", + "1 <= special.length <= 100", + "special[i].length == n + 1", + "0 <= special[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput:14\nExplanation:There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.", + "image": null + }, + { + "text": "Example 2: Input:price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput:11\nExplanation:The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 549 ms (Top 11.6%) | Memory: 43.58 MB (Top 33.0%)\n\nclass Solution {\n public static int fun(int index,List price,List> special, List needs){\n // Base \n if(index < 0){\n int addAmount = 0;\n for(int i=0;i(needs));\n\n // Take Offer \n int takeOffer = 1000000000;\n if(canTakeOffer(special.get(index),new ArrayList<>(needs))){\n List current_special = special.get(index);\n for(int i=0;i(needs));\n }\n return Math.min(notTakeOffer,takeOffer);\n }\n\n public static boolean canTakeOffer(List current_special, List needs){\n boolean canTake = true;\n for(int i=0;i price, List> special, List needs) {\n int items = price.size();\n int offers = special.size();\n return fun(offers-1,price,special,needs);\n }\n}", + "title": "638. Shopping Offers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the i th item, and an integer array needs where needs[i] is the number of pieces of the i th item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the j th item in the i th offer and special[i][n] (i.e., the last integer in the array) is the price of the i th offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers . You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.", + "description_images": [], + "constraints": [ + "n == price.length == needs.length", + "1 <= n <= 6", + "0 <= price[i], needs[i] <= 10", + "1 <= special.length <= 100", + "special[i].length == n + 1", + "0 <= special[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput:14\nExplanation:There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.", + "image": null + }, + { + "text": "Example 2: Input:price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput:11\nExplanation:The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 164 ms (Top 43.73%) | Memory: 14 MB (Top 84.10%)\nclass Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n def dfs(price, special, needs, memo = {}):\n if tuple(needs) in memo:\n return memo[tuple(needs)]\n res = [sum([p * need for p, need in zip(price, needs)])] # don't use any offer\n for offer in special:\n # check if can apply the offer\n new_needs = []\n for offer_items, need in zip(offer[:-1], needs):\n new_needs.append(need - offer_items)\n if min(new_needs) < 0:\n continue\n # Check if without the offer is better\n value = 0\n for p, offer_items in zip(price, offer[:-1]):\n value += p * offer_items\n if value < offer[-1]:\n continue\n # Valid Case\n res.append(dfs(price, special, new_needs, memo) + offer[-1])\n memo[tuple(needs)] = min(res)\n return min(res)\n return dfs(price, special, needs)", + "title": "638. Shopping Offers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A valid encoding of an array of words is any reference string s and array of indices indices such that: Given an array of words , return the length of the shortest reference string s possible of any valid encoding of words .", + "description_images": [], + "constraints": [ + "words.length == indices.length", + "The reference string s ends with the '#' character.", + "For each index indices[i] , the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"time\", \"me\", \"bell\"]\nOutput:10\nExplanation:A valid encoding would be s =\"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"", + "image": null + }, + { + "text": "Example 2: Input:words = [\"t\"]\nOutput:2\nExplanation:A valid encoding would be s = \"t#\" and indices = [0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 85.71%) | Memory: 59.1 MB (Top 35.19%)\nclass Node {\n private boolean flag;\n private Node[] children;\n\n public Node () {\n flag = false;\n children = new Node[26];\n Arrays.fill (children, null);\n }\n\n public boolean getFlag () {\n return flag;\n }\n\n public Node getChild (int index) {\n return children[index];\n }\n\n public boolean hasChild (int index) {\n return children[index] != null;\n }\n\n public void setFlag (boolean flag) {\n this.flag = flag;\n }\n\n public void makeChild (int index) {\n children[index] = new Node();\n }\n}\n\nclass Trie {\n private Node root;\n\n public Trie () {\n root = new Node();\n }\n\n public int addWord (String word) {\n\n boolean flag = true;\n Node node = root;\n int count = 0;\n\n for (int i = word.length () - 1; i >= 0; --i) {\n int index = (int) word.charAt(i) - 97;\n\n if (!node.hasChild (index)) {\n flag = false;\n node.makeChild (index);\n }\n\n node = node.getChild (index);\n if (node.getFlag()) {\n node.setFlag (false);\n count -= word.length() - i + 1;\n\n if (i == 0)\n flag = false;\n }\n }\n\n if (!flag)\n node.setFlag (true);\n\n return flag? count: count + 1 + word.length();\n }\n}\n\nclass Solution {\n public int minimumLengthEncoding(String[] words) {\n Trie trie = new Trie ();\n int size = 0;\n\n for (String word: words) {\n size += trie.addWord (word);\n }\n\n return size;\n }\n}", + "title": "820. Short Encoding of Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A valid encoding of an array of words is any reference string s and array of indices indices such that: Given an array of words , return the length of the shortest reference string s possible of any valid encoding of words .", + "description_images": [], + "constraints": [ + "words.length == indices.length", + "The reference string s ends with the '#' character.", + "For each index indices[i] , the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"time\", \"me\", \"bell\"]\nOutput:10\nExplanation:A valid encoding would be s =\"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"", + "image": null + }, + { + "text": "Example 2: Input:words = [\"t\"]\nOutput:2\nExplanation:A valid encoding would be s = \"t#\" and indices = [0].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumLengthEncoding(self, words):\n \n \n # root of suffix trie\n trie_root = dict()\n \n # helper function to judge leaf node\n isLeafNode = lambda node: len(node) == 0\n \n # collection of tail nodes\n tail_nodes = []\n \n # set of unique words\n unique_words = set(words)\n \n # scan each word\n for word in unique_words:\n \n # build suffix trie from root node\n cur = trie_root\n \n # scan each character in reversed order\n for char in reversed(word):\n \n # update trie\n cur[char] = cur.get(char, dict() )\n \n # go to next level\n cur = cur[char]\n \n # save tail nodes with corresponding word length, +1 is for '#' symbol\n tail_nodes.append( (cur, len(word)+1) )\n\n # summation of the length with all tail node which is also a leaf node\n return sum( suffix_length for node, suffix_length in tail_nodes if isLeafNode(node) )", + "title": "820. Short Encoding of Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1 's not connected to any other 1 's. There are exactly two islands in grid . You may change 0 's to 1 's to connect the two islands to form one island . Return the smallest number of 0 's you must flip to connect the two islands .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "2 <= n <= 100", + "grid[i][j] is either 0 or 1 .", + "There are exactly two islands in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 59.97%) | Memory: 53.7 MB (Top 81.02%)\n\nclass Solution {\n private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}};\n public int shortestBridge(int[][] grid) {\n boolean[][] visited=new boolean[grid.length][grid[0].length];\n LinkedList queue=new LinkedList();\n boolean found=false;\n for(int i=0;i0){\n int size=queue.size();\n while(size-- >0){\n Pair pair=queue.poll();\n for(int k=0;k<4;k++){\n int rowDash=pair.row+dirs[k][0];\n int colDash=pair.col+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true )continue;\n if(grid[rowDash][colDash]==1) return level;\n queue.add(new Pair(rowDash,colDash));\n visited[rowDash][colDash]=true;\n }\n }\n level++;\n }\n return -1;\n }\n private void dfs(int[][] grid,int i,int j,LinkedList queue,boolean[][] visited){\n visited[i][j]=true;\n queue.add(new Pair(i,j));\n for(int k=0;k<4;k++){\n int rowDash=i+dirs[k][0];\n int colDash=j+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true || grid[rowDash][colDash]==0)continue;\n dfs(grid,rowDash,colDash,queue,visited);\n }\n }\n static class Pair{\n int row;\n int col;\n public Pair(int row,int col){\n this.row=row;\n this.col=col;\n }\n }\n}", + "title": "934. Shortest Bridge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1 's not connected to any other 1 's. There are exactly two islands in grid . You may change 0 's to 1 's to connect the two islands to form one island . Return the smallest number of 0 's you must flip to connect the two islands .", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "2 <= n <= 100", + "grid[i][j] is either 0 or 1 .", + "There are exactly two islands in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput:2", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 329 ms (Top 84.2%) | Memory: 17.67 MB (Top 84.2%)\n\nclass Solution:\n def shortestBridge(self, grid):\n m, n = len(grid), len(grid[0])\n start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n \n stack = [(start_i, start_j)]\n visited = set(stack)\n while stack:\n i, j = stack.pop()\n visited.add((i, j)) \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n stack.append((ii, jj))\n visited.add((ii, jj))\n \n \n ans = 0\n queue = list(visited)\n while queue:\n new_queue = []\n for i, j in queue:\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n if grid[ii][jj] == 1:\n return ans\n new_queue.append((ii, jj))\n visited.add((ii, jj))\n queue = new_queue\n ans += 1\n", + "title": "934. Shortest Bridge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings str1 and str2 , return the shortest string that has both str1 and str2 as subsequences . If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0 ) results in the string s .", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"abac\", str2 = \"cab\"\nOutput:\"cabac\"\nExplanation:str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput:\"aaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String shortestCommonSupersequence(String str1, String str2) {\n int m=str1.length();\n int n=str2.length();\n int[][] dp=new int[m+1][n+1];\n for(int i=1;i0 && j>0){\n if(str1.charAt(i-1)==str2.charAt(j-1)){\n res=str1.charAt(i-1)+res;\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]){\n res=str1.charAt(i-1)+res;\n i--;\n }else{\n res=str2.charAt(j-1)+res;\n j--;\n }\n }\n while(i>0){\n res=str1.charAt(i-1)+res;\n i--;\n }\n while(j>0){\n res=str2.charAt(j-1)+res;\n j--;\n }\n return res;\n }\n}\n", + "title": "1092. Shortest Common Supersequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings str1 and str2 , return the shortest string that has both str1 and str2 as subsequences . If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0 ) results in the string s .", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"abac\", str2 = \"cab\"\nOutput:\"cabac\"\nExplanation:str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput:\"aaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestCommonSupersequence(self, A, B):\n n, m = len(A), len(B)\n dp = [B[:i] for i in range(m + 1)]\n for i in range(n):\n prev = A[:i]\n dp[0] = A[:i + 1]\n for j in range(m):\n if A[i] == B[j]:\n prev, dp[j + 1] = dp[j + 1], prev + A[i]\n else:\n prev, dp[j + 1] = dp[j + 1], min(dp[j] + B[j], dp[j + 1] + A[i], key = len)\n return dp[-1]\n", + "title": "1092. Shortest Common Supersequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string licensePlate and an array of strings words , find the shortest completing word in words . A completing word is a word that contains all the letters in licensePlate . Ignore numbers and spaces in licensePlate , and treat letters as case insensitive . If a letter appears more than once in licensePlate , then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\" , then it contains letters 'a' , 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\" , \"caaacab\" , and \"cbca\" . Return the shortest completing word in words . It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words .", + "description_images": [], + "constraints": [ + "1 <= licensePlate.length <= 7", + "licensePlate contains digits, letters (uppercase or lowercase), or space ' ' .", + "1 <= words.length <= 1000", + "1 <= words[i].length <= 15", + "words[i] consists of lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput:\"steps\"\nExplanation:licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.", + "image": null + }, + { + "text": "Example 2: Input:licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput:\"pest\"\nExplanation:licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 66.6%) | Memory: 43.77 MB (Top 64.6%)\n\nclass Solution {\n public String shortestCompletingWord(String licensePlate, String[] words) {\n //Store count of letters in LicensePlate\n int[] licensePlateCount = new int[26];\n \n //To store all words which meet the criteria\n ArrayList res = new ArrayList<>();\n //To find min length word that meets the criteria\n int min = Integer.MAX_VALUE;\n \n //Add char count for each char in LicensePlate\n for(Character c:licensePlate.toCharArray()) {\n if(isChar(c)) {\n licensePlateCount[Character.toLowerCase(c) - 'a']++;\n }\n }\n \n //Add char count for each word in words\n for(String word : words) {\n int[] wordCharCount = new int[26];\n boolean flag = true;\n \n for(Character c:word.toCharArray()) {\n wordCharCount[Character.toLowerCase(c) - 'a']++;\n }\n \n //Eliminate words that don't satisfy the criteria\n for(int i = 0; i<26;i++) {\n if(licensePlateCount[i] > wordCharCount[i]) flag = false;\n }\n \n //Add words satisfying criteria to res and calculate min word length\n if(flag) {\n res.add(word);\n if(word.length() < min) min = word.length();\n }\n }\n \n //Return 1st word in array meeting all criteria\n for(int i = 0; i < res.size();i++) {\n if(res.get(i).length() == min) return res.get(i);\n }\n \n //If not found, return -1 (or whatever interviewer expects)\n return \"-1\";\n }\n \n private boolean isChar(Character c) {\n if((c >='a' && c <='z') ||\n (c>='A' && c<='Z')) return true;\n \n return false;\n }\n}", + "title": "748. Shortest Completing Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string licensePlate and an array of strings words , find the shortest completing word in words . A completing word is a word that contains all the letters in licensePlate . Ignore numbers and spaces in licensePlate , and treat letters as case insensitive . If a letter appears more than once in licensePlate , then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\" , then it contains letters 'a' , 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\" , \"caaacab\" , and \"cbca\" . Return the shortest completing word in words . It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words .", + "description_images": [], + "constraints": [ + "1 <= licensePlate.length <= 7", + "licensePlate contains digits, letters (uppercase or lowercase), or space ' ' .", + "1 <= words.length <= 1000", + "1 <= words[i].length <= 15", + "words[i] consists of lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput:\"steps\"\nExplanation:licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.", + "image": null + }, + { + "text": "Example 2: Input:licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput:\"pest\"\nExplanation:licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n newPlate = '' # modify the licensePlate\n for i in licensePlate:\n if i.isalpha():\n newPlate += i.lower()\n \n c = Counter(newPlate)\n l1 = [] # store (word,len,index)\n for idx,word in enumerate(words):\n if Counter(word) >= c:\n l1.append((word,len(word),idx))\n l1.sort(key = lambda x:(x[1],idx))\n return l1[0][0]\n", + "title": "748. Shortest Completing Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and a character c that occurs in s , return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s . The distance between two indices i and j is abs(i - j) , where abs is the absolute value function.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] and c are lowercase English letters.", + "It is guaranteed that c occurs at least once in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"loveleetcode\", c = \"e\"\nOutput:[3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation:The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\", c = \"b\"\nOutput:[3,2,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 72.97%) | Memory: 43.3 MB (Top 45.95%)\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int index = -1;\n int[] ans = new int[n];\n // Starting from index 0 and storing the distance from the next c;\n for(int i=0;i=0;i--){\n if(s.charAt(i)==c) index = i;//to store the index of the nearest next c\n\n if(index!=-1) ans[i] = Math.min(ans[i],index-i);\n }\n return ans;\n }\n}", + "title": "821. Shortest Distance to a Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and a character c that occurs in s , return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s . The distance between two indices i and j is abs(i - j) , where abs is the absolute value function.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] and c are lowercase English letters.", + "It is guaranteed that c occurs at least once in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"loveleetcode\", c = \"e\"\nOutput:[3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation:The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\", c = \"b\"\nOutput:[3,2,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n res = []\n ch= []\n for i in range(len(s)):\n if s[i] == c:\n ch.append(i)\n min_d = len(s)\n for i in range(len(s)):\n for j in range(len(ch)):\n min_d = min(min_d, abs(i-ch[j]))\n res.append(min_d)\n min_d = len(s)\n return res\n", + "title": "821. Shortest Distance to a Character", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array rolls of length n and an integer k . You roll a k sided dice numbered from 1 to k , n times, where the result of the i th roll is rolls[i] . Return the length of the shortest sequence of rolls that cannot be taken from rolls . A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order.", + "description_images": [], + "constraints": [ + "n == rolls.length", + "1 <= n <= 10^5", + "1 <= rolls[i] <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [4,2,1,2,3,3,2,4,1], k = 4\nOutput:3\nExplanation:Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,1,2,2], k = 2\nOutput:2\nExplanation:Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,1,3,2,2,2,3,3], k = 4\nOutput:1\nExplanation:The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestSequence(int[] rolls, int k) {\n int len = 0;\n Set set = new HashSet<>();\n for(int i:rolls)\n {\n set.add(i);\n if(set.size()==k)\n {\n set = new HashSet<>();\n len++;\n }\n }\n return len+1;\n }\n}\n", + "title": "2350. Shortest Impossible Sequence of Rolls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array rolls of length n and an integer k . You roll a k sided dice numbered from 1 to k , n times, where the result of the i th roll is rolls[i] . Return the length of the shortest sequence of rolls that cannot be taken from rolls . A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order.", + "description_images": [], + "constraints": [ + "n == rolls.length", + "1 <= n <= 10^5", + "1 <= rolls[i] <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [4,2,1,2,3,3,2,4,1], k = 4\nOutput:3\nExplanation:Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,1,2,2], k = 2\nOutput:2\nExplanation:Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,1,3,2,2,2,3,3], k = 4\nOutput:1\nExplanation:The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 966 ms (Top 94.20%) | Memory: 28.2 MB (Top 71.33%)\nclass Solution:\n def shortestSequence(self, rolls: List[int], k: int) -> int:\n ans = 1\n data = set()\n\n for roll in rolls:\n data.add(roll)\n\n if len(data) == k:\n ans += 1\n data.clear()\n\n return ans", + "title": "2350. Shortest Impossible Sequence of Rolls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacecaaa\"\nOutput:\"aaacecaaa\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"\nOutput:\"dcbabcd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String shortestPalindrome(String s) {\n for(int i=s.length()-1; i >= 0; i--){\n if(isPalindrome(s, 0, i)){\n String toAppend = s.substring(i+1);\n String result = new StringBuilder(toAppend).reverse().append(s).toString();\n return result;\n }\n }\n String result = new StringBuilder(s).reverse().append(s).toString();\n return result; \n }\n \n boolean isPalindrome(String s, int left, int right){\n while(left < right){\n if(s.charAt(left) != s.charAt(right))\n return false;\n left++;\n right--;\n }\n return true;\n }\n}\n", + "title": "214. Shortest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s . You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacecaaa\"\nOutput:\"aaacecaaa\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"\nOutput:\"dcbabcd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPalindrome(self, s: str) -> str:\n \n end = 0\n \n # if the string itself is a palindrome return it\n if(s == s[::-1]):\n return s\n \n # Otherwise find the end index of the longest palindrome that starts\n # from the first character of the string\n \n for i in range(len(s)+1):\n if(s[:i]==s[:i][::-1]):\n end=i-1\n \n # return the string with the remaining characters other than\n # the palindrome reversed and added at the beginning\n \n return (s[end+1:][::-1])+s\n", + "title": "214. Shortest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step . Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles . If it is not possible to find such walk return -1 .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 40", + "1 <= k <= m * n", + "grid[i][j] is either 0 or 1 .", + "grid[0][0] == grid[m - 1][n - 1] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput:6\nExplanation:The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) ->(3,2)-> (4,2).", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput:-1\nExplanation:We need to eliminate at least two obstacles to find such a walk.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 735 ms (Top 5.01%) | Memory: 122.2 MB (Top 5.01%)\nclass Solution {\n int rowLen = 0;\n int colLen = 0;\n int MAXVAL = 0;\n public int shortestPath(int[][] grid, int k) {\n rowLen = grid.length;\n colLen = grid[0].length;\n MAXVAL = rowLen * colLen + 1;\n int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k+1][4]);\n return path == MAXVAL ? -1 : path;\n }\n\n /* Direction\n 0 - Up\n 1 - Down\n 2 - Left\n 3 - Right\n */\n\n // For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we consider the direction as well\n int shortest(int[][] grid, int k, int row, int col, int direction, boolean[][] visited, Integer[][][][] dp){\n // Reached end of the matrix\n if(row == rowLen - 1 && col == colLen - 1 && k >= 0)\n return 0;\n\n // Couldn't find a valid path\n if(k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen)\n return MAXVAL;\n\n if(dp[row][col][k][direction] != null)\n return dp[row][col][k][direction];\n\n // 4 options to choose a direction\n // Go right\n int op1 = MAXVAL;\n if(col + 1 < colLen && !visited[row][col+1]) {\n visited[row][col+1] = true;\n if(grid[row][col+1] == 0)\n op1 = shortest(grid, k, row, col+1, 3, visited, dp) + 1;\n else\n op1 = shortest(grid, k-1, row, col+1, 3, visited, dp) + 1;\n visited[row][col+1] = false;\n }\n\n // Go left\n int op2 = MAXVAL;\n if(col - 1 >= 0 && !visited[row][col-1]) {\n visited[row][col-1] = true;\n if(grid[row][col-1] == 0)\n op2 = shortest(grid, k, row, col-1, 2, visited, dp) + 1;\n else\n op2 = shortest(grid, k-1, row, col-1, 2, visited, dp) + 1;\n visited[row][col-1] = false;\n }\n\n // Go up\n int op3 = MAXVAL;\n if(row - 1 >= 0 && !visited[row-1][col]) {\n visited[row-1][col] = true;\n if(grid[row-1][col] == 0)\n op3 = shortest(grid, k, row-1, col, 0, visited, dp) + 1;\n else\n op3 = shortest(grid, k-1, row-1, col, 0, visited, dp) + 1;\n visited[row-1][col] = false;\n }\n\n // Go down\n int op4 = MAXVAL;\n if(row + 1 < rowLen && !visited[row+1][col]) {\n visited[row+1][col] = true;\n if(grid[row+1][col] == 0)\n op4 = shortest(grid, k, row+1, col, 1, visited, dp) + 1;\n else\n op4 = shortest(grid, k-1, row+1, col, 1, visited, dp) + 1;\n visited[row+1][col] = false;\n }\n\n dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4));\n return dp[row][col][k][direction];\n }\n}", + "title": "1293. Shortest Path in a Grid with Obstacles Elimination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step . Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles . If it is not possible to find such walk return -1 .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 40", + "1 <= k <= m * n", + "grid[i][j] is either 0 or 1 .", + "grid[0][0] == grid[m - 1][n - 1] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput:6\nExplanation:The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) ->(3,2)-> (4,2).", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput:-1\nExplanation:We need to eliminate at least two obstacles to find such a walk.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n Q = [[0, 0, k]] # m, n, remaining elimination quota \n rows, cols = len(grid), len(grid[0])\n V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited\n \n while Q: \n frontier = []\n for m, n, rem in Q: \n if m == rows - 1 and n == cols - 1: \n return counter \n for dm, dn in [[1, 0], [-1, 0], [0, 1], [0, -1]]: \n if 0 <= m+dm < rows and 0 <= n+dn < cols: # check inbound \n if grid[m+dm][n+dn] == 0: \n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem])\n V[(m+dm, n+dn)] = rem\n elif rem > 0: # I see a wall and I can still eliminate\n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem - 1: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem-1])\n V[(m+dm, n+dn)] = rem - 1\n Q = frontier \n counter += 1\n \n return -1\n\t```", + "title": "1293. Shortest Path in a Grid with Obstacles Elimination", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n x n binary matrix grid , return the length of the shortest clear path in the matrix . If there is no clear path, return -1 . A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0) ) to the bottom-right cell (i.e., (n - 1, n - 1) ) such that: The length of a clear path is the number of visited cells of this path.", + "description_images": [], + "constraints": [ + "All the visited cells of the path are 0 .", + "All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner)." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example1_1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example2_1.png" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestPathBinaryMatrix(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n \n boolean [][] visited = new boolean [m][n];\n \n int [] up = {0, 0, 1, -1, 1, 1, -1, -1};\n int [] down = {-1, 1, 0, 0, -1, 1, -1, 1};\n \n /*\n if top-left is 1 or bottom-right is 1\n we will return -1\n */\n if(grid[0][0] == 1 || grid[m-1][n-1] == 1)\n return -1;\n \n ArrayDeque q = new ArrayDeque<>();\n /*\n we will add top-left to the deque\n ans steps as 1\n */\n q.add(new int[]{0,0,1}); \n \n while(q.size() > 0){\n int [] tmp = q.removeFirst();\n int x = tmp[0];\n int y = tmp[1];\n int steps = tmp[2];\n visited[x][y] = true;\n \n if(x == m-1 && y == n-1)\n return steps;\n \n for(int i = 0; i < 8; i++){\n int x_new = x + up[i];\n int y_new = y + down[i];\n /*\n we will traverse level wise using bfs\n and those which can be directly reach via\n current level will be considered as the same\n level and we will return the level of \n bottom-right as result\n */\n if(x_new >= 0 && x_new < m && y_new >= 0 && y_new < n){\n if(visited[x_new][y_new] == false && grid[x_new][y_new] == 0){\n q.add(new int[]{x_new,y_new,steps+1});\n visited[x_new][y_new] = true;\n }\n }\n }\n }\n \n return -1;\n }\n}\n", + "title": "1091. Shortest Path in Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n binary matrix grid , return the length of the shortest clear path in the matrix . If there is no clear path, return -1 . A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0) ) to the bottom-right cell (i.e., (n - 1, n - 1) ) such that: The length of a clear path is the number of visited cells of this path.", + "description_images": [], + "constraints": [ + "All the visited cells of the path are 0 .", + "All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner)." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example1_1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example2_1.png" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nfrom collections import deque\nclass Solution:\n\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\t\tL=len(grid)\n\t\tdef generate_next_state(i,j):\n\t\t\treturn [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]\n\t\tdef valid_state(states):\n\t\t\tres=[]\n\t\t\tfor (i,j) in states:\n\t\t\t\tif i>L-1:continue\n\t\t\t\tif i<0:continue\n\t\t\t\tif j<0:continue\n\t\t\t\tif j>L-1:continue\n\t\t\t\tif grid[i][j]==0:\n\t\t\t\t\tres.append((i,j))\n\t\t\treturn res\n\t\tqueue=deque([(0,0)])\n\t\tres=1\n\t\twhile queue:\n\t\t\tfor _ in range(len(queue)):\n\t\t\t\ti,j=queue.popleft()\n\t\t\t\tval=grid[i][j]\n\t\t\t\tgrid[i][j]=1\n\t\t\t\tif not val:\n\t\t\t\t\tif i==L-1 and j==L-1:\n\t\t\t\t\t\treturn res\n\n\t\t\t\t\tnext_state=valid_state(generate_next_state(i,j))\n\t\t\t\t\tfor (ki,kj) in next_state:\n\t\t\t\t\t\tqueue.append((ki,kj))\n\t\t\tres+=1\n\t\treturn -1\n \n \n \n \n'''", + "title": "1091. Shortest Path in Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n grid grid where: You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6 , there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys . If it is impossible, return -1 .", + "description_images": [], + "constraints": [ + "'.' is an empty cell.", + "'#' is a wall.", + "'@' is the starting point.", + "Lowercase letters represent keys.", + "Uppercase letters represent locks." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput:8\nExplanation:Note that the goal is to obtain all the keys not to open all the locks.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg" + }, + { + "text": "Example 2: Input:grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg" + }, + { + "text": "Example 3: Input:grid = [\"@Aa\"]\nOutput:-1", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[][] DIRS = new int[][]{ \n {1,0}, {-1,0}, {0,1}, {0,-1}\n };\n \n public int shortestPathAllKeys(String[] grid) {\n int m = grid.length, n = grid[0].length();\n int numKeys = 0, startRow = -1, startCol = -1;\n \n for(int i=0; i queue = new LinkedList();\n Set visited = new HashSet(); \n int steps = 0;\n \n queue.offer(start);\n visited.add(start);\n \n while( !queue.isEmpty() ) {\n int size = queue.size();\n \n while( size-- > 0 ) {\n int i = queue.peek().i;\n int j = queue.peek().j;\n int keys = queue.peek().keys;\n queue.poll();\n \n if( keys == keyMask )\n return steps;\n \n for(int[] dir : DIRS) {\n int di = i + dir[0];\n int dj = j + dir[1];\n int newKeys = keys;\n\n if( di < 0 || dj < 0 || di == m || dj == n )\n continue;\n\n char c = grid[di].charAt(dj);\n\n if( isWall(c) ) continue;\n \n if( isLock(c) && !isKeyPresent(keys, c) )\n continue;\n\n if( isKey(c) ) \n newKeys |= (1 << (c - 'a'));\n \n State newState = new State(di, dj, newKeys);\n \n if( visited.add(newState) ) \n queue.offer(newState);\n }\n }\n steps++;\n }\n return -1;\n }\n \n private boolean isLock(char c) {\n return c >= 'A' && c <= 'Z';\n }\n private boolean isKey(char c) {\n return c >= 'a' && c <= 'z';\n }\n private boolean isWall(char c) {\n return c == '#';\n }\n private boolean isStart(char c) {\n return c == '@';\n }\n private boolean isKeyPresent(int keys, char lock) {\n return (keys & (1 << (lock-'A'))) != 0;\n }\n}\nclass State {\n public int i, j, keys;\n \n public State(int i, int j, int keys) {\n this.i = i;\n this.j = j;\n this.keys = keys;\n }\n \n @Override\n public boolean equals(Object obj) {\n if( !(obj instanceof State) ) return false;\n State that = (State)obj;\n return i == that.i && j == that.j && keys == that.keys;\n }\n \n @Override\n public int hashCode() {\n int prime = 31;\n int hash = 1;\n hash = hash * prime + i;\n hash = hash * prime + j;\n hash = hash * prime + keys;\n return hash;\n }\n}\n", + "title": "864. Shortest Path to Get All Keys", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n grid grid where: You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6 , there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys . If it is impossible, return -1 .", + "description_images": [], + "constraints": [ + "'.' is an empty cell.", + "'#' is a wall.", + "'@' is the starting point.", + "Lowercase letters represent keys.", + "Uppercase letters represent locks." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput:8\nExplanation:Note that the goal is to obtain all the keys not to open all the locks.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg" + }, + { + "text": "Example 2: Input:grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg" + }, + { + "text": "Example 3: Input:grid = [\"@Aa\"]\nOutput:-1", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n \n m=len(grid)\n n=len(grid[0])\n visited=set()\n \n steps=0\n q=deque([])\n keyCt=0\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"@\":\n q.append((i,j,''))\n elif grid[i][j].islower():\n keyCt+=1\n \n while q:\n for _ in range(len(q)):\n curr_x,curr_y,keys = q.popleft()\n if (curr_x,curr_y,keys) in visited:\n continue\n \n visited.add((curr_x,curr_y,keys))\n \n if len(keys)==keyCt:\n return steps\n \n for x,y in ((0,1),(1,0),(-1,0),(0,-1)):\n nx=curr_x+x\n ny=curr_y+y\n if nx<0 or ny<0 or nx>=m or ny>=n or grid[nx][ny]=='#' or (nx,ny,keys) in visited:\n continue\n \n curr=grid[nx][ny] \n if curr in 'abcdef' and curr not in keys:\n q.append((nx,ny,keys+curr)) \n elif curr.isupper() and curr.lower() not in keys:\n continue\n else:\n q.append((nx,ny,keys))\n steps+=1\n \n return -1", + "title": "864. Shortest Path to Get All Keys", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1 . You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node . You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.", + "description_images": [], + "constraints": [ + "n == graph.length", + "1 <= n <= 12", + "0 <= graph[i].length < n", + "graph[i] does not contain i .", + "If graph[a] contains b , then graph[b] contains a .", + "The input graph is always connected." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2,3],[0],[0],[0]]\nOutput:4\nExplanation:One possible path is [1,0,2,0,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg" + }, + { + "text": "Example 2: Input:graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput:4\nExplanation:One possible path is [0,1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 78.04%) | Memory: 46.7 MB (Top 69.44%)\nclass Solution {\n class Pair {\n int i;\n int path;\n public Pair(int i, int path) {\n this.i = i;\n this.path = path;\n }\n }\n public int shortestPathLength(int[][] graph) {\n /*\n For each node currentNode, steps as key, visited as value\n boolean[currentNode][steps]\n */\n int n = graph.length;\n\n // 111....1, 1<< n - 1\n int allVisited = (1 << n) - 1;\n\n boolean[][] visited = new boolean[n][1 << n];\n Queue q = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (1 << i == allVisited) return 0;\n visited[i][1 << i] = true;\n q.offer(new Pair(i, 1 << i));\n }\n int step = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n Pair p = q.poll();\n int[] edges = graph[p.i];\n\n for(int t: edges) {\n int path = p.path | (1 << t);\n if (path == allVisited) return step + 1;\n if (!visited[t][path]) {\n visited[t][path] = true;\n q.offer(new Pair(t, path));\n }\n }\n }\n step++;\n }\n return step;\n }\n}", + "title": "847. Shortest Path Visiting All Nodes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1 . You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node . You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.", + "description_images": [], + "constraints": [ + "n == graph.length", + "1 <= n <= 12", + "0 <= graph[i].length < n", + "graph[i] does not contain i .", + "If graph[a] contains b , then graph[b] contains a .", + "The input graph is always connected." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2,3],[0],[0],[0]]\nOutput:4\nExplanation:One possible path is [1,0,2,0,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg" + }, + { + "text": "Example 2: Input:graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput:4\nExplanation:One possible path is [0,1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n = len(graph)\n dist = [[inf]*n for _ in range(n)]\n \n for i, x in enumerate(graph): \n dist[i][i] = 0\n for ii in x: dist[i][ii] = 1\n \n # floyd-warshall \n for k in range(n): \n for i in range(n): \n for j in range(n): \n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n \n @cache \n def fn(x, mask): \n if mask == 0: return 0 \n ans = inf \n for i in range(n): \n if mask & (1 << i): \n ans = min(ans, dist[x][i] + fn(i, mask ^ (1< graph with red edges\n // g2-> graph with blue edges\n List g1[], g2[];\n int[] dist1, dist2, ans;\n int MX = (int) 2e9;\n\n public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {\n dist1 = new int[n];\n dist2 = new int[n];\n g1=new ArrayList[n];\n g2=new ArrayList[n];\n ans=new int[n];\n for (int i=0;i();\n g2[i]=new ArrayList<>();\n dist1[i]=MX;\n dist2[i]=MX;\n ans[i]=MX;\n }\n for (int i=0;idist2[u]+1){\n dist1[v]=dist2[u]+1;\n dfs(v,!flag);\n }\n }\n } else {\n for (int v: g2[u]) {\n if (dist2[v]>dist1[u]+1){\n dist2[v]=dist1[u]+1;\n dfs(v,!flag);\n }\n }\n }\n }\n}", + "title": "1129. Shortest Path with Alternating Colors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n , the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1 . Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: Return an array answer of length n , where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.", + "description_images": [], + "constraints": [ + "redEdges[i] = [a i , b i ] indicates that there is a directed red edge from node a i to node b i in the graph, and", + "blueEdges[j] = [u j , v j ] indicates that there is a directed blue edge from node u j to node v j in the graph." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, redEdges = [[0,1],[1,2]], blueEdges = []\nOutput:[0,1,-1]", + "image": null + }, + { + "text": "Example 2: Input:n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]\nOutput:[0,1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n g = [[[] for _ in range(2)] for _ in range(n)]\n \n for i,j in redEdges:\n g[i][0] += [j]\n for i,j in blueEdges:\n g[i][1] += [j]\n distance = [float(\"inf\") for _ in range(n)]\n distance[0] = 0\n q = queue.Queue()\n q.put((0,0,False))\n q.put((0,0,True))\n \n redS = set([0])\n blueS = set([0])\n while not q.empty():\n node,dist,red = q.get()\n if red:\n neighbours = g[node][0]\n redS.add(node)\n curr = blueS\n else:\n neighbours = g[node][1]\n blueS.add(node)\n curr = redS\n for neighbour in neighbours:\n if dist + 1 < distance[neighbour]:\n distance[neighbour] = dist + 1\n q.put((neighbour,dist + 1,not red))\n if not (neighbour in curr):\n q.put((neighbour,dist + 1,not red))\n for i in range(n):\n if distance[i] == float(\"inf\"):\n distance[i] = -1\n return distance\n \n", + "title": "1129. Shortest Path with Alternating Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr , remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing . Return the length of the shortest subarray to remove . A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "0 <= arr[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,10,4,2,3,5]\nOutput:3\nExplanation:The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,4,3,2,1]\nOutput:4\nExplanation:Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3]\nOutput:0\nExplanation:The array is already non-decreasing. We do not need to remove any elements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findLengthOfShortestSubarray(int[] arr) {\n int firstLast=0,lastFirst=arr.length-1;\n for(;firstLastarr[firstLast+1]) break;\n }\n\t\t//Base case for a non-decreasing sequence\n if(firstLast==arr.length-1) return 0;\n for( ;lastFirst>0;lastFirst--){\n if(arr[lastFirst]=0;firstLast--){\n for(int i=lastFirst;iarr[i]) continue;\n minLength = Math.min(minLength,i-firstLast-1);\n break;\n }\n }\n return minLength;\n }\n}\n", + "title": "1574. Shortest Subarray to be Removed to Make Array Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing . Return the length of the shortest subarray to remove . A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "0 <= arr[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,10,4,2,3,5]\nOutput:3\nExplanation:The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,4,3,2,1]\nOutput:4\nExplanation:Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3]\nOutput:0\nExplanation:The array is already non-decreasing. We do not need to remove any elements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n n = len(arr)\n i = 0\n while i < n-1 and arr[i+1] >= arr[i]:\n i += 1\n \n if i == n-1:\n return 0\n \n j = n-1\n while j >= 0 and arr[j-1] <= arr[j]:\n j -= 1\n \n ans = min(n, n-i-1, j)\n \n for l in range(i+1):\n r = j\n while r < n and arr[r] < arr[l]:\n r += 1\n ans = min(ans, r-l-1)\n \n return ans", + "title": "1574. Shortest Subarray to be Removed to Make Array Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return the length of the shortest non-empty subarray of nums with a sum of at least k . If there is no such subarray , return -1 . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 1\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], k = 4\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,2], k = 3\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestSubarray(int[] nums, int k) {\n \n TreeMap maps = new TreeMap<>();\n long sum = 0l;\n int min = nums.length + 1;\n\t\t \n maps.put(0l, -1);\n \n for(int i = 0; i < nums.length; i++) {\n sum += nums[i];ntry(sum - k) != null) \n\t\t\t min = Math.min(min, i - maps.floorEntry(sum - k).getValue()); \n while(!maps.isEmpty() && maps.lastEntry().getKey() >= sum) \n\t\t\t maps.remove(maps.lastEntry().getKey());\n \n maps.put(sum, i);\n }\n \n return min == (nums.length + 1) ? -1 : min;\n }\n}\n", + "title": "862. Shortest Subarray with Sum at Least K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and an integer k , return the length of the shortest non-empty subarray of nums with a sum of at least k . If there is no such subarray , return -1 . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 1\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], k = 4\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,2], k = 3\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "# 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative, \n# the numbers in sliding window are not always incrementing\n# ex [8,-4,3,1,6], 10\n\n# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.\n# 3. monotonic queue is used to keep the prefix sums are in the incrementing order\n# 4. If the diffenence between the cur and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n prefixsum = [0]\n monoq = deque()\n minLen = float('inf')\n # to calculate prefix sum\n for n in nums:\n prefixsum.append(n+prefixsum[-1])\n for idx, cur in enumerate(prefixsum):\n while monoq and prefixsum[monoq[-1]] >= cur: monoq.pop() # to maintain monotonic queue\n\n # If the diffenence between the head and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n while monoq and cur-prefixsum[monoq[0]]>=k: \n minLen = min(minLen, idx-monoq.popleft())\n monoq.append(idx)\n return -1 if minLen == float('inf') else minLen\n", + "title": "862. Shortest Subarray with Sum at Least K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,6,4,8,10,9,15]\nOutput:5\nExplanation:You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 47.11%) | Memory: 43.4 MB (Top 88.72%)\nclass Solution {\n public int findUnsortedSubarray(int[] nums) {\n int[] numsClone = nums.clone();\n Arrays.sort(nums);\n\n int s = Integer.MAX_VALUE;\n int e = Integer.MIN_VALUE;\n\n for(int i = 0; i int:\n stack = []\n min_index = len(nums)\n max_index = 0\n max_pop = float('-inf')\n for i in range(len(nums)):\n while stack and nums[i] < stack[-1][0]:\n\n p = stack.pop()\n if p[0] > max_pop:\n max_pop = p[0]\n if p[1] < min_index:\n min_index = p[1]\n if p[1] > max_index:\n max_index = p[1]\n stack.append([nums[i], i])\n max_r = max_index\n for st in stack:\n if st[0] < max_pop:\n max_r = st[1]\n if min_index == len(nums):\n return 0\n return max_r - min_index +1\n", + "title": "581. Shortest Unsorted Continuous Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the integer array nums .", + "int[] reset() Resets the array to its original configuration and returns it.", + "int[] shuffle() Returns a random shuffling of the array." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n[[[1, 2, 3]], [], [], []]Output[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle(); // Shuffle the array [1,2,3] and return its result.\n // Any permutation of [1,2,3] must be equally likely to be returned.\n // Example: return [3, 1, 2]\nsolution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 16.02%) | Memory: 64.6 MB (Top 78.83%)\nclass Solution {\n\n int a[];\n int b[];\n public Solution(int[] nums) {\n a=nums.clone();\n b=nums.clone();\n }\n\n public int[] reset() {\n a=b.clone();\n return a;\n }\n\n public int[] shuffle() {\n\n for(int i=0;i List[int]: \n return self.nums\n\n def shuffle(self) -> List[int]:\n shuffled_array = self.nums.copy()\n # randomly generates the idx of the element that'll be the ith element of the array \n for i in range(len(self.nums) - 1, 0, -1):\n idx = random.randint(0, i)\n shuffled_array[i], shuffled_array[idx] = shuffled_array[idx], shuffled_array[i]\n return shuffled_array", + "title": "384. Shuffle an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and an integer array indices of the same length . The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string. Return the shuffled string .", + "description_images": [], + "constraints": [ + "s.length == indices.length == n", + "1 <= n <= 100", + "s consists of only lowercase English letters.", + "0 <= indices[i] < n", + "All values of indices are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"codeleet\",indices= [4,5,6,7,0,2,1,3]\nOutput:\"leetcode\"\nExplanation:As shown, \"codeleet\" becomes \"leetcode\" after shuffling.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/q1.jpg" + }, + { + "text": "Example 2: Input:s = \"abc\",indices= [0,1,2]\nOutput:\"abc\"\nExplanation:After shuffling, each character remains in its position.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.6 MB (Top 92.75%)\nclass Solution {\n public String restoreString(String s, int[] indices) {\n char[] ch = new char[s.length()];\n for(int i = 0 ; i< s.length() ; i ++){\n ch[indices[i]]=s.charAt(i);\n }\n return new String (ch);\n }\n}", + "title": "1528. Shuffle String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s and an integer array indices of the same length . The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string. Return the shuffled string .", + "description_images": [], + "constraints": [ + "s.length == indices.length == n", + "1 <= n <= 100", + "s consists of only lowercase English letters.", + "0 <= indices[i] < n", + "All values of indices are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"codeleet\",indices= [4,5,6,7,0,2,1,3]\nOutput:\"leetcode\"\nExplanation:As shown, \"codeleet\" becomes \"leetcode\" after shuffling.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/q1.jpg" + }, + { + "text": "Example 2: Input:s = \"abc\",indices= [0,1,2]\nOutput:\"abc\"\nExplanation:After shuffling, each character remains in its position.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 68.03%) | Memory: 13.9 MB (Top 63.45%)\nclass Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n dec = {}\n c = 0\n res=''\n for i in indices:\n dec[i] = s[c]\n c += 1\n # dec = {\"4\":\"c\",\"5\":\"o\",\"6\":\"d\",\"7\":\"e\",\"0\":\"l\",\"2\":\"e\",\"1\":\"e\",\"3\":\"t\"}\n for x in range(len(indices)):\n res += dec[x]\n # x in range 0, 1, 2,....... len *indices or s*\n return res", + "title": "1528. Shuffle String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the array nums consisting of 2n elements in the form [x 1 ,x 2 ,...,x n ,y 1 ,y 2 ,...,y n ] . Return the array in the form [x 1 ,y 1 ,x 2 ,y 2 ,...,x n ,y n ] .", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "nums.length == 2n", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,1,3,4,7], n = 3\nOutput:[2,3,5,4,1,7]\nExplanation:Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,4,3,2,1], n = 4\nOutput:[1,4,2,3,3,2,4,1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], n = 2\nOutput:[1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.71%) | Memory: 45.8 MB (Top 46.61%)\nclass Solution {\n public int[] shuffle(int[] nums, int n)\n {\n int[] arr = new int[2*n];\n int j = 0;\n int k = n;\n for(int i =0; i<2*n; i++)\n {\n if(i%2==0)\n {\n arr[i] = nums[j];\n j++;\n }\n else\n {\n arr[i] = nums[k];\n k++;\n }\n }\n return arr;\n }\n}", + "title": "1470. Shuffle the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array nums consisting of 2n elements in the form [x 1 ,x 2 ,...,x n ,y 1 ,y 2 ,...,y n ] . Return the array in the form [x 1 ,y 1 ,x 2 ,y 2 ,...,x n ,y n ] .", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "nums.length == 2n", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,1,3,4,7], n = 3\nOutput:[2,3,5,4,1,7]\nExplanation:Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,4,3,2,1], n = 4\nOutput:[1,4,2,3,3,2,4,1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], n = 2\nOutput:[1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nFirst of all, I'm making a few tuples using zip function.\nThen extracting every created tuple. (for tup in zip())\nAfter that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup)\n'''\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n return [number for tup in zip(nums[:n], nums[n:]) for number in tup]\n", + "title": "1470. Shuffle the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a function signFunc(x) that returns: You are given an integer array nums . Let product be the product of all values in the array nums . Return signFunc(product) .", + "description_images": [], + "constraints": [ + "1 if x is positive.", + "-1 if x is negative.", + "0 if x is equal to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,-2,-3,-4,3,2,1]\nOutput:1\nExplanation:The product of all values in the array is 144, and signFunc(144) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,0,2,-3]\nOutput:0\nExplanation:The product of all values in the array is 0, and signFunc(0) = 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-1,1,-1]\nOutput:-1\nExplanation:The product of all values in the array is -1, and signFunc(-1) = -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int arraySign(int[] nums) {\n int prod=1;\n for(int i=0;i0) return 1;\n return 0;\n }\n}\n", + "title": "1822. Sign of the Product of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a function signFunc(x) that returns: You are given an integer array nums . Let product be the product of all values in the array nums . Return signFunc(product) .", + "description_images": [], + "constraints": [ + "1 if x is positive.", + "-1 if x is negative.", + "0 if x is equal to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,-2,-3,-4,3,2,1]\nOutput:1\nExplanation:The product of all values in the array is 144, and signFunc(144) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,0,2,-3]\nOutput:0\nExplanation:The product of all values in the array is 0, and signFunc(0) = 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-1,1,-1]\nOutput:-1\nExplanation:The product of all values in the array is -1, and signFunc(-1) = -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arraySign(self, nums: List[int]) -> int:\n\t\treturn 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1\n", + "title": "1822. Sign of the Product of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings X and Y are similar if we can swap two letters (in different positions) of X , so that it equals Y . Also two strings X and Y are similar if they are equal. For example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2 ), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\" , \"rats\" , or \"arts\" . Together, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"} .  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs . How many groups are there?", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 300", + "1 <= strs[i].length <= 300", + "strs[i] consists of lowercase letters only.", + "All words in strs have the same length and are anagrams of each other." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"tars\",\"rats\",\"arts\",\"star\"]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"omv\",\"ovm\"]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSimilarGroups(String[] strs) {\n boolean[] visited = new boolean[strs.length]; // record the word that we checked\n int res = 0;\n for (int i = 0; i < strs.length; i++) {\n if (!visited[i]) {\n res++;\n dfs(strs, visited, i);\n }\n }\n return res;\n }\n \n void dfs(String[] strs, boolean[] visited, int index) { // explore all similar words we can explore\n visited[index] = true;\n String curr = strs[index];\n for (int i = 0; i < strs.length; i++) {\n if (!visited[i] && isSimilar(curr, strs[i])) {\n dfs(strs, visited, i);\n } \n }\n }\n \n boolean isSimilar(String a, String b) {\n int diff = 0;\n for (int i = 0; i < a.length(); i++) {\n if (a.charAt(i) != b.charAt(i)) {\n diff++;\n if (diff > 2) return false;\n }\n }\n return true;\n }\n}\n", + "title": "839. Similar String Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Two strings X and Y are similar if we can swap two letters (in different positions) of X , so that it equals Y . Also two strings X and Y are similar if they are equal. For example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2 ), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\" , \"rats\" , or \"arts\" . Together, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"} .  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs . How many groups are there?", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 300", + "1 <= strs[i].length <= 300", + "strs[i] consists of lowercase letters only.", + "All words in strs have the same length and are anagrams of each other." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"tars\",\"rats\",\"arts\",\"star\"]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"omv\",\"ovm\"]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5068 ms (Top 15.23%) | Memory: 14.3 MB (Top 64.62%)\nclass Solution: #839. Similar String Groups\n def numSimilarGroups(self, strs: List[str]) -> int:\n #memo\n visited = set()\n count = 0\n for i in range(len(strs)):\n if i not in visited:\n #dfs\n self.dfs(strs, i, visited)\n #add a new connected area\n count += 1\n return count\n\n #dfs to search the similar string from 0 to n-1\n def dfs(self, strs, i, visited):\n #add current string to memo\n visited.add(i)\n for j in range(len(strs)):\n if self.isSimilar(strs[i], strs[j]) and j not in visited:\n self.dfs(strs, j , visited)\n\n # calculate the similarity of two strings\n def isSimilar(self, str1, str2):\n diff_count = 0\n for i in range(len(str1)):\n if str1[i] != str2[i]:\n diff_count += 1\n return diff_count <= 2", + "title": "839. Similar String Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n . The initial balance of each account is stored in a 0-indexed integer array balance , with the (i + 1) th account having an initial balance of balance[i] . Execute all the valid transactions. A transaction is valid if: Implement the Bank class:", + "description_images": [], + "constraints": [ + "The given account number(s) are between 1 and n , and", + "The amount of money withdrawn or transferred from is less than or equal to the balance of the account." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]Output[null, true, true, true, false, false]ExplanationBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 265 ms (Top 12.10%) | Memory: 117.3 MB (Top 39.86%)\nclass Bank {\n\n int N;\n long[] balance;\n public Bank(long[] balance) {\n this.N = balance.length;\n this.balance = balance;\n }\n\n public boolean transfer(int account1, int account2, long money) {\n if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < money)\n return false;\n balance[account1 - 1] -= money;\n balance[account2 - 1] += money;\n return true;\n }\n\n public boolean deposit(int account, long money) {\n if(account < 1 || account > N)\n return false;\n balance[account - 1] += money;\n return true;\n }\n\n public boolean withdraw(int account, long money) {\n if(account < 1 || account > N || balance[account - 1] < money)\n return false;\n balance[account - 1] -= money;\n return true;\n }\n}", + "title": "2043. Simple Bank System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n . The initial balance of each account is stored in a 0-indexed integer array balance , with the (i + 1) th account having an initial balance of balance[i] . Execute all the valid transactions. A transaction is valid if: Implement the Bank class:", + "description_images": [], + "constraints": [ + "The given account number(s) are between 1 and n , and", + "The amount of money withdrawn or transferred from is less than or equal to the balance of the account." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]Output[null, true, true, true, false, false]ExplanationBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1834 ms (Top 5.30%) | Memory: 43.9 MB (Top 45.70%)\nclass Bank:\n\n def __init__(self, bal: List[int]):\n self.store = bal # storage list\n\n def transfer(self, a1: int, a2: int, money: int) -> bool:\n try:\n # checking if both accounts exist. and if the transaction would be valid\n if self.store[a1 - 1] >= money and self.store[a2 - 1] >= 0:\n # performing the transaction\n self.store[a1 - 1] -= money\n self.store[a2 - 1] += money\n return True\n else:\n # retrning false on invalid transaction\n return False\n except:\n # returning false when accounts don't exist\n return False\n\n def deposit(self, ac: int, mn: int) -> bool:\n try:\n # if account exists performing transaction\n self.store[ac - 1] += mn\n return True\n except:\n # returning false when account doesn't exist\n return False\n\n def withdraw(self, ac: int, mn: int) -> bool:\n try:\n # checking if transaction is valid\n if self.store[ac - 1] >= mn:\n # performing the transaction\n self.store[ac - 1] -= mn\n return True\n else:\n # returning false in case on invalid transaction\n return False\n except:\n # returning false when account doesn't exist\n return False", + "title": "2043. Simple Bank System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[\"1/2\"]\nExplanation:\"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:[\"1/2\",\"1/3\",\"2/3\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:[\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation:\"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 52.04%) | Memory: 73.5 MB (Top 36.20%)\nclass Solution {\n public List simplifiedFractions(int n) {\n List list = new ArrayList<>() ;\n\n for(int numerator = 1; numerator< n ; numerator++) {\n for(int denominator = numerator+1; denominator<=n; denominator++) {\n if(gcd(numerator,denominator) == 1) {\n list.add(numerator+\"/\"+denominator);\n// System.out.println(numerator+\"/\"+denominator);\n }\n }\n }\n return list ;\n }\n\n static int gcd(int a, int b)\n {\n// euclidean algo\n\n if(a==0) {\n return b ;\n }\n return gcd(b%a,a);\n }\n}", + "title": "1447. Simplified Fractions", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[\"1/2\"]\nExplanation:\"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:[\"1/2\",\"1/3\",\"2/3\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:[\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation:\"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n \n collect = {}\n for b in range(2, n+1):\n for a in range(1, b):\n if a/b not in collect:\n collect[a/b] = f\"{a}/{b}\" \n return list(collect.values())\n", + "title": "1447. Simplified Fractions", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string path , which is an absolute path (starting with a slash '/' ) to a file or directory in a Unix-style file system, convert it to the simplified canonical path . In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//' ) are treated as a single slash '/' . For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path .", + "description_images": [], + "constraints": [ + "The path starts with a single slash '/' .", + "Any two directories are separated by a single slash '/' .", + "The path does not end with a trailing '/' .", + "The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..' )" + ], + "examples": [ + { + "text": "Example 1: Input:path = \"/home/\"\nOutput:\"/home\"\nExplanation:Note that there is no trailing slash after the last directory name.", + "image": null + }, + { + "text": "Example 2: Input:path = \"/../\"\nOutput:\"/\"\nExplanation:Going one level up from the root directory is a no-op, as the root level is the highest level you can go.", + "image": null + }, + { + "text": "Example 3: Input:path = \"/home//foo/\"\nOutput:\"/home/foo\"\nExplanation:In the canonical path, multiple consecutive slashes are replaced by a single one.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 86.82%) | Memory: 43.20 MB (Top 75.26%)\n\nclass Solution {\n public String simplifyPath(String path) {\n Deque dirOrFiles = new ArrayDeque<>();\n for (String dirOrFile : path.split(\"/\")) {\n if (!dirOrFiles.isEmpty() && dirOrFile.equals(\"..\")) {\n dirOrFiles.removeLast();\n } else if (!dirOrFile.equals(\".\") && !dirOrFile.equals(\"\") && !dirOrFile.equals(\"..\")) {\n dirOrFiles.addLast(dirOrFile);\n }\n }\n StringBuilder simplified_path = new StringBuilder();\n for (String dirOrFile : dirOrFiles) {\n simplified_path.append(\"/\").append(dirOrFile);\n }\n return simplified_path.length() == 0 ? \"/\" : simplified_path.toString();\n }\n}\n", + "title": "71. Simplify Path", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string path , which is an absolute path (starting with a slash '/' ) to a file or directory in a Unix-style file system, convert it to the simplified canonical path . In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//' ) are treated as a single slash '/' . For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path .", + "description_images": [], + "constraints": [ + "The path starts with a single slash '/' .", + "Any two directories are separated by a single slash '/' .", + "The path does not end with a trailing '/' .", + "The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..' )" + ], + "examples": [ + { + "text": "Example 1: Input:path = \"/home/\"\nOutput:\"/home\"\nExplanation:Note that there is no trailing slash after the last directory name.", + "image": null + }, + { + "text": "Example 2: Input:path = \"/../\"\nOutput:\"/\"\nExplanation:Going one level up from the root directory is a no-op, as the root level is the highest level you can go.", + "image": null + }, + { + "text": "Example 3: Input:path = \"/home//foo/\"\nOutput:\"/home/foo\"\nExplanation:In the canonical path, multiple consecutive slashes are replaced by a single one.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def simplifyPath(self, path: str) -> str:\n \tstack = []\n \t\n \ti = 0\n while i < len(path):\n if path[i] == '/':\n i += 1\n continue\n\n else:\n cur = ''\n while i < len(path) and path[i] != '/':\n cur += path[i]\n i += 1\n\n if cur == '..':\n if stack:\n stack.pop()\n elif cur == '.' or cur == '':\n i += 1\n continue\n else:\n stack.append(cur)\n\n return '/' + '/'.join(stack)\n", + "title": "71. Simplify Path", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once . Your solution must run in O(log n) time and O(1) space.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,3,3,4,4,8,8]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,7,7,10,11,11]\nOutput:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 49.90 MB (Top 64.7%)\n\nclass Solution {\n public int singleNonDuplicate(int[] nums) {\n if(nums.length==1) return nums[0];\n int l = 0;\n int h = nums.length-1;\n \n while(l int:\n return self.b_search(nums)[0]\n \n def b_search(self, nums):\n if len(nums) == 1:\n return nums\n mid = len(nums)//2\n a = nums[:mid]\n b = nums[mid:]\n\t\t\n\t\t# check if last & first element of the two sub lists are same\n if a[-1] == b[0]:\n a = a[:-1]\n b = b[1:]\n\t\t\n\t\t# ignore the sub list with even number of elements\n if len(a)%2:\n return self.b_search(a)\n else:\n return self.b_search(b)\n", + "title": "540. Single Element in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,2,1,2]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 30.48%) | Memory: 52.1 MB (Top 26.29%)\nclass Solution {\n public int singleNumber(int[] nums) {\n Stack numStack = new Stack();\n Arrays.sort(nums);\n for (var i = 0; i < nums.length; ++i) {\n numStack.push(nums[i]);\n if (i < nums.length - 1 && nums[++i] != (int) numStack.peek()) break;\n }\n return (int) numStack.pop();\n }\n}", + "title": "136. Single Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,2,1,2]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 301 ms (Top 20.49%) | Memory: 16.1 MB (Top 98.97%)\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n nums.sort()\n i=0\n while i List[int]:\n x = Counter(nums)\n return([y for y in x if x[y] == 1])\n", + "title": "260. Single Number III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given n ​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks , where tasks[i] = [enqueueTime i , processingTime i ] means that the i ​​​​​​th ​​​​ task will be available to process at enqueueTime i and will take processingTime i to finish processing. You have a single-threaded CPU that can process at most one task at a time and will act in the following way: Return the order in which the CPU will process the tasks.", + "description_images": [], + "constraints": [ + "If the CPU is idle and there are no available tasks to process, the CPU remains idle.", + "If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time . If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.", + "Once a task is started, the CPU will process the entire task without stopping.", + "The CPU can finish a task then start a new one instantly." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [[1,2],[2,4],[3,2],[4,1]]\nOutput:[0,2,3,1]\nExplanation:The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\nOutput:[4,3,2,0,1]\nExplanation:The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getOrder(self, tasks: List[List[int]]) -> List[int]:\n # For better readability\n Task = namedtuple('Task', ['etime', 'ptime', 'index'])\n \n # Sort the tasks by enqueue time, shortest processing time and index\n stasks = sorted([Task(task[0], task[1], i) for i, task in enumerate(tasks)])\n # t: current CPU clock; i: current task index\n t = i = 0\n heap, result = [], []\n \n while len(result) < len(stasks):\n # Push all the tasks available at current CPU clock\n while i < len(stasks) and stasks[i].etime <= t:\n heappush(heap, (stasks[i].ptime, stasks[i].index))\n i += 1\n if heap:\n ptime, index = heappop(heap)\n result.append(index)\n t += ptime\n else:\n # Jump to the next available task\n t = stasks[i].etime\n return result\n", + "title": "1834. Single-Threaded CPU", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an 2 x 3 board, there are five tiles labeled from 1 to 5 , and an empty square represented by 0 . A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]] . Given the puzzle board board , return the least number of moves required so that the state of the board is solved . If it is impossible for the state of the board to be solved, return -1 .", + "description_images": [], + "constraints": [ + "board.length == 2", + "board[i].length == 3", + "0 <= board[i][j] <= 5", + "Each value board[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[1,2,3],[4,0,5]]\nOutput:1\nExplanation:Swap the 0 and the 5 in one move.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[1,2,3],[5,4,0]]\nOutput:-1\nExplanation:No number of moves will make the board solved.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[4,1,2],[5,0,3]]\nOutput:5\nExplanation:5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide3-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 35.42%) | Memory: 44.4 MB (Top 46.82%)\nclass Solution {\n int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}};\n public int slidingPuzzle(int[][] board) {\n\n String tar=\"123450\";\n\n String src=\"\";\n\n for(int i =0;i visited=new HashSet<>();\n\n visited.add(src);\n int level=0;\n ArrayDeque q=new ArrayDeque<>();\n q.add(src);\n while(q.size()!=0){\n int t=q.size();\n\n while(t-->0){\n String rem=q.remove();\n\n if(rem.equals(tar)){\n return level;\n }\n\n int idx=-1;\n\n for(int i=0;i int:\n def findNei(board):\n directs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n boards = []\n for i in range(2):\n for j in range(3):\n if board[i][j] == 0:\n for dr, dc in directs:\n tmp = [row.copy() for row in board]\n r, c = i + dr, j + dc\n if r in range(2) and c in range(3):\n tmp[r][c], tmp[i][j] = tmp[i][j], tmp[r][c]\n boards.append(tmp)\n return boards\n\n visited = set()\n target = [[1, 2, 3], [4, 5, 0]]\n if board == target:\n return 0\n rows, cols = len(board), len(board[0])\n q = collections.deque()\n step = 1\n\n for row in range(rows):\n for col in range(cols):\n if board[row][col] == 0:\n boards = findNei(board)\n for b in boards:\n if b == target:\n return step\n visited.add(tuple([tuple(row) for row in b]))\n q.append(b)\n break\n\n while q:\n step += 1\n for _ in range(len(q)):\n b = q.popleft()\n boards = findNei(b)\n for b in boards:\n if b == target:\n return step\n t = tuple([tuple(row) for row in b])\n if t not in visited:\n visited.add(t)\n q.append(b)\n\n return -1", + "title": "773. Sliding Puzzle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput:[3,3,5,5,6,7]\nExplanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSlidingWindow(int[] nums, int k) {\n Deque queue = new LinkedList<>();\n int l = 0, r = 0;\n int[] res = new int[nums.length - k + 1];\n int index = 0;\n while (r < nums.length) {\n int n = nums[r++];\n while (!queue.isEmpty() && n > queue.peekLast()) {\n queue.pollLast();\n }\n queue.offer(n);\n while (r - l > k) {\n int m = nums[l++];\n if (m == queue.peekFirst()) {\n queue.pollFirst();\n }\n }\n if (r - l == k) {\n res[index++] = queue.peekFirst();\n }\n }\n return res;\n }\n}\n", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput:[3,3,5,5,6,7]\nExplanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4951 ms (Top 7.51%) | Memory: 39.4 MB (Top 5.02%)\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n ans = []\n pq = []\n\n for i in range(k): heapq.heappush(pq,(-nums[i],i))\n\n ans.append(-pq[0][0])\n\n for i in range(k,len(nums)):\n heapq.heappush(pq,(-nums[i],i))\n while pq and pq[0][1] < i-k+1 : heapq.heappop(pq)\n ans.append(-pq[0][0])\n\n return ans", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k . 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 median array for each window in the original array . Answers within 10 -5 of the actual value will be accepted.", + "description_images": [], + "constraints": [ + "For examples, if arr = [2, 3 ,4] , the median is 3 .", + "For examples, if arr = [1, 2,3 ,4] , the median is (2 + 3) / 2 = 2.5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput:[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\nExplanation:Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,2,3,1,4,2], k = 3\nOutput:[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 176 ms (Top 24.15%) | Memory: 56.2 MB (Top 31.72%)\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n Queue minHeap = new PriorityQueue<>();\n Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n double[] res = new double[nums.length - k + 1];\n for(int i = 0; i< nums.length; i++){\n if(i >= k){\n if(!minHeap.remove(nums[i-k]))\n maxHeap.remove(nums[i-k]);\n }\n\n // If k is odd, max heap is of odd size and min heap is of even\n // else both are of even size\n if(!maxHeap.isEmpty() && nums[i] <= maxHeap.peek()) {\n maxHeap.add(nums[i]);\n if(((k&1) == 1 && maxHeap.size() > k/2+1) || ((k&1) == 0 && maxHeap.size() > k/2)){\n minHeap.offer(maxHeap.poll());\n }\n }else{\n minHeap.add(nums[i]);\n if(minHeap.size() > k/2){\n maxHeap.offer(minHeap.poll());\n }\n }\n while(!minHeap.isEmpty() && !maxHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){\n int temp1 = maxHeap.poll();\n int temp2 = minHeap.poll();\n maxHeap.add(temp2);\n minHeap.add(temp1);\n }\n if(minHeap.size() + maxHeap.size() == k){\n if((k&1)==1){\n res[i-k+1] = maxHeap.peek();\n }else{\n res[i-k+1] = ((long)minHeap.peek()+ (long)maxHeap.peek())/2.0;\n }\n }\n }\n return res;\n }\n}", + "title": "480. Sliding Window Median", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k . 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 median array for each window in the original array . Answers within 10 -5 of the actual value will be accepted.", + "description_images": [], + "constraints": [ + "For examples, if arr = [2, 3 ,4] , the median is 3 .", + "For examples, if arr = [1, 2,3 ,4] , the median is (2 + 3) / 2 = 2.5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput:[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\nExplanation:Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,2,3,1,4,2], k = 3\nOutput:[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 447 ms (Top 43.48%) | Memory: 30.40 MB (Top 31.32%)\n\nimport heapq\nfrom collections import defaultdict\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n if not nums or not k:\n return []\n lo = [] # max heap\n hi = [] # min heap\n for i in range(k):\n if len(lo) == len(hi):\n heapq.heappush(hi, -heapq.heappushpop(lo, -nums[i]))\n else:\n heapq.heappush(lo, -heapq.heappushpop(hi, nums[i]))\n ans = [float(hi[0])] if k & 1 else [(hi[0] - lo[0]) / 2.0]\n to_remove = defaultdict(int)\n for i in range(k, len(nums)): # right bound of window\n heapq.heappush(lo, -heapq.heappushpop(hi, nums[i])) # always push to lo\n out_num = nums[i-k]\n if out_num > -lo[0]:\n heapq.heappush(hi, -heapq.heappop(lo))\n to_remove[out_num] += 1\n while lo and to_remove[-lo[0]]:\n to_remove[-lo[0]] -= 1\n heapq.heappop(lo)\n while to_remove[hi[0]]:\n to_remove[hi[0]] -= 1\n heapq.heappop(hi)\n if k % 2:\n ans.append(float(hi[0]))\n else:\n ans.append((hi[0] - lo[0]) / 2.0)\n return ans\n", + "title": "480. Sliding Window Median", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n , where keysPressed[i] was the i th key pressed in the testing sequence, and a sorted list releaseTimes , where releaseTimes[i] was the time the i th key was released. Both arrays are 0-indexed . The 0 th key was pressed at the time 0 , and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration . The i th keypress had a duration of releaseTimes[i] - releaseTimes[i - 1] , and the 0 th keypress had a duration of releaseTimes[0] . Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration . Return the key of the keypress that had the longest duration . If there are multiple such keypresses, return the lexicographically largest key of the keypresses.", + "description_images": [], + "constraints": [ + "releaseTimes.length == n", + "keysPressed.length == n", + "2 <= n <= 1000", + "1 <= releaseTimes[i] <= 10^9", + "releaseTimes[i] < releaseTimes[i+1]", + "keysPressed contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\nOutput:\"c\"\nExplanation:The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.", + "image": null + }, + { + "text": "Example 2: Input:releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\nOutput:\"a\"\nExplanation:The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public char slowestKey(int[] releaseTimes, String keysPressed) {\n int max = releaseTimes[0];\n char ch = keysPressed.charAt(0);\n for(int i=1;i= max){\n if(diff>max)\n ch = keysPressed.charAt(i);\n else if(diff== max)\n ch = (char)Math.max((int) ch, (int) keysPressed.charAt(i));\n max = diff;\n } \n }\n return ch; \n } \n}\n", + "title": "1629. Slowest Key", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n , where keysPressed[i] was the i th key pressed in the testing sequence, and a sorted list releaseTimes , where releaseTimes[i] was the time the i th key was released. Both arrays are 0-indexed . The 0 th key was pressed at the time 0 , and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration . The i th keypress had a duration of releaseTimes[i] - releaseTimes[i - 1] , and the 0 th keypress had a duration of releaseTimes[0] . Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration . Return the key of the keypress that had the longest duration . If there are multiple such keypresses, return the lexicographically largest key of the keypresses.", + "description_images": [], + "constraints": [ + "releaseTimes.length == n", + "keysPressed.length == n", + "2 <= n <= 1000", + "1 <= releaseTimes[i] <= 10^9", + "releaseTimes[i] < releaseTimes[i+1]", + "keysPressed contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\nOutput:\"c\"\nExplanation:The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.", + "image": null + }, + { + "text": "Example 2: Input:releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\nOutput:\"a\"\nExplanation:The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 111 ms (Top 25.49%) | Memory: 14.1 MB (Top 45.43%)\nclass Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n max_dur = releaseTimes[0]\n max_key = keysPressed[0]\n\n for i in range(1, len(releaseTimes)):\n if releaseTimes[i] - releaseTimes[i-1] > max_dur:\n max_dur = releaseTimes[i] - releaseTimes[i-1]\n max_key = keysPressed[i]\n elif releaseTimes[i] - releaseTimes[i-1] == max_dur and max_key < keysPressed[i]:\n max_key = keysPressed[i]\n\n return max_key", + "title": "1629. Slowest Key", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer n represented as a string, return the smallest good base of n . We call k >= 2 a good base of n , if all digits of n base k are 1 's.", + "description_images": [], + "constraints": [ + "n is an integer in the range [3, 10^18 ] .", + "n does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"13\"\nOutput:\"3\"\nExplanation:13 base 3 is 111.", + "image": null + }, + { + "text": "Example 2: Input:n = \"4681\"\nOutput:\"8\"\nExplanation:4681 base 8 is 11111.", + "image": null + }, + { + "text": "Example 3: Input:n = \"1000000000000000000\"\nOutput:\"999999999999999999\"\nExplanation:1000000000000000000 base 999999999999999999 is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestGoodBase(self, n: str) -> str:\n import math\n n = int(n)\n max_m = math.floor(math.log(n, 2))\n ans = 0\n for m in range(max_m, 0, -1):\n k = int(n ** (1 / m))\n if (k ** (m + 1) - 1) // (k - 1) == n:\n return str(k)\n return str(n - 1)\n", + "title": "483. Smallest Good Base", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums , return the smallest index i of nums such that i mod 10 == nums[i] , or -1 if such index does not exist . x mod y denotes the remainder when x is divided by y .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2]\nOutput:0\nExplanation:i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,2,1]\nOutput:2\nExplanation:i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9,0]\nOutput:-1\nExplanation:No index satisfies i mod 10 == nums[i].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.3 MB (Top 94.74%)\nclass Solution {\n public int smallestEqual(int[] nums) {\n int index = 0;\n for (int i = 0 ; i < nums.length; i++) {\n if (index == nums[i]) {\n return i;\n }\n if (++index== 10) {\n index = 0;\n }\n }\n return -1;\n }\n}", + "title": "2057. Smallest Index With Equal Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums , return the smallest index i of nums such that i mod 10 == nums[i] , or -1 if such index does not exist . x mod y denotes the remainder when x is divided by y .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2]\nOutput:0\nExplanation:i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,2,1]\nOutput:2\nExplanation:i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9,0]\nOutput:-1\nExplanation:No index satisfies i mod 10 == nums[i].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestEqual(self, nums: List[int]) -> int:\n for idx, n in enumerate(nums):\n if idx%10==n:\n return idx\n return -1 ", + "title": "2057. Smallest Index With Equal Value", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer k , you need to find the length of the smallest positive integer n such that n is divisible by k , and n only contains the digit 1 . Return the length of n . If there is no such n , return -1. Note: n may not fit in a 64-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1\nOutput:1\nExplanation:The smallest answer is n = 1, which has length 1.", + "image": null + }, + { + "text": "Example 2: Input:k = 2\nOutput:-1\nExplanation:There is no such positive integer n divisible by 2.", + "image": null + }, + { + "text": "Example 3: Input:k = 3\nOutput:3\nExplanation:The smallest answer is n = 111, which has length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int smallestRepunitDivByK(int k) {\n // if (k % 2 == 0 || k % 5 == 0) return -1; // this trick may save a little time\n boolean[] hit = new boolean[k];\n int n = 0, ans = 0;\n while (true) { // at most k times, because 0 <= remainder < k\n ++ ans;\n n = (n * 10 + 1) % k; // we only focus on whether to divide, so we only need to keep the remainder.\n if (n == 0) return ans; // can be divisible\n if (hit[n]) return -1; // the remainder of the division repeats, so it starts to loop that means it cannot be divisible.\n hit[n] = true;\n }\n }\n}\n", + "title": "1015. Smallest Integer Divisible by K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer k , you need to find the length of the smallest positive integer n such that n is divisible by k , and n only contains the digit 1 . Return the length of n . If there is no such n , return -1. Note: n may not fit in a 64-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1\nOutput:1\nExplanation:The smallest answer is n = 1, which has length 1.", + "image": null + }, + { + "text": "Example 2: Input:k = 2\nOutput:-1\nExplanation:There is no such positive integer n divisible by 2.", + "image": null + }, + { + "text": "Example 3: Input:k = 3\nOutput:3\nExplanation:The smallest answer is n = 111, which has length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n if k % 2 == 0: return -1\n n = 1\n leng = 1\n mapp = {}\n while True:\n rem = n % k\n if rem == 0: return leng\n if rem in mapp : return -1\n mapp[rem] = True\n n = n*10 + 1\n leng += 1\n \n", + "title": "1015. Smallest Integer Divisible by K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , an integer k , a letter letter , and an integer repetition . Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times . The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b .", + "description_images": [], + "constraints": [ + "1 <= repetition <= k <= s.length <= 5 * 10^4", + "s consists of lowercase English letters.", + "letter is a lowercase English letter, and appears in s at least repetition times." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet\", k = 3, letter = \"e\", repetition = 1\nOutput:\"eet\"\nExplanation:There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- \"lee\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"eet\" (from \"leet\")\nThe lexicographically smallest subsequence among them is \"eet\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 4, letter = \"e\", repetition = 2\nOutput:\"ecde\"\nExplanation:\"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.", + "image": "https://assets.leetcode.com/uploads/2021/09/13/smallest-k-length-subsequence.png" + }, + { + "text": "Example 3: Input:s = \"bb\", k = 2, letter = \"b\", repetition = 2\nOutput:\"bb\"\nExplanation:\"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, r: int) -> str:\n n_letters = len([c for c in s if c == letter])\n stack = []\n \n for i, c in enumerate(s):\n while stack and stack[-1] > c and (len(s) - i + len(stack) > k) and (stack[-1] != letter or n_letters > r):\n d = stack.pop()\n if d == letter:\n r += 1\n \n if len(stack) < k:\n if c == letter:\n stack.append(c)\n r -= 1\n elif k - len(stack) > r:\n stack.append(c)\n \n if c == letter:\n n_letters -= 1\n \n return ''.join(stack)\n", + "title": "2030. Smallest K-Length Subsequence With Occurrences of a Letter", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , an integer k , a letter letter , and an integer repetition . Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times . The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b .", + "description_images": [], + "constraints": [ + "1 <= repetition <= k <= s.length <= 5 * 10^4", + "s consists of lowercase English letters.", + "letter is a lowercase English letter, and appears in s at least repetition times." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet\", k = 3, letter = \"e\", repetition = 1\nOutput:\"eet\"\nExplanation:There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- \"lee\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"eet\" (from \"leet\")\nThe lexicographically smallest subsequence among them is \"eet\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 4, letter = \"e\", repetition = 2\nOutput:\"ecde\"\nExplanation:\"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.", + "image": "https://assets.leetcode.com/uploads/2021/09/13/smallest-k-length-subsequence.png" + }, + { + "text": "Example 3: Input:s = \"bb\", k = 2, letter = \"b\", repetition = 2\nOutput:\"bb\"\nExplanation:\"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n s = list(s)\n stack = []\n countAll = s.count(letter)\n count = 0\n for ind, i in enumerate(s):\n while stack and stack[-1] > i:\n if stack[-1] == letter and i != letter:\n if countAll+count-1 < repetition:\n break\n if len(stack)+len(s)-ind-1 < k:\n break\n if stack[-1] == letter:\n count-=1\n stack.pop()\n stack.append(i)\n if i == letter:\n count+=1\n countAll-=1\n temp = 0\n while len(stack)+temp > k:\n if stack[-1] == letter and count <= repetition:\n temp+=1\n if stack[-1] == letter:\n count-=1\n stack.pop()\n return \"\".join(stack)+temp*letter", + "title": "2030. Smallest K-Length Subsequence With Occurrences of a Letter", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1 . You are given a 0-indexed integer array parents , where parents[i] is the parent for node i . Since node 0 is the root , parents[0] == -1 . There are 10^5 genetic values, each represented by an integer in the inclusive range [1, 10^5 ] . You are given a 0-indexed integer array nums , where nums[i] is a distinct genetic value for node i . Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i . The subtree rooted at a node x contains node x and all of its descendant nodes.", + "description_images": [], + "constraints": [ + "n == parents.length == nums.length", + "2 <= n <= 10^5", + "0 <= parents[i] <= n - 1 for i != 0", + "parents[0] == -1", + "parents represents a valid tree.", + "1 <= nums[i] <= 10^5", + "Each nums[i] is distinct." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput:[5,1,1,1]\nExplanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput:[7,1,1,4,2,1]\nExplanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-2.png" + }, + { + "text": "Example 3: Input:parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput:[1,1,1,1,1,1,1]\nExplanation:The value 1 is missing from all the subtrees.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n int n = parents.length;\n int[] res = new int[n];\n for (int i = 0; i < n; i++) {\n res[i] = 1;\n }\n \n int oneIndex = -1;\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) {\n oneIndex = i;\n break;\n }\n }\n \n // 1 not found\n if (oneIndex == -1) {\n return res;\n }\n \n Map> graph = new HashMap<>();\n for (int i = 1; i < n; i++) {\n Set children = graph.getOrDefault(parents[i], new HashSet());\n children.add(i);\n graph.put(parents[i], children);\n }\n \n Set visited = new HashSet();\n \n int parentIter = oneIndex;\n int miss = 1;\n while (parentIter >= 0) {\n dfs(parentIter, graph, visited, nums);\n while (visited.contains(miss)) {\n miss++;\n }\n res[parentIter] = miss;\n parentIter = parents[parentIter];\n }\n return res;\n }\n \n public void dfs(int ind, Map> graph, Set visited, int []nums) {\n if (!visited.contains(nums[ind])) {\n Set children = graph.getOrDefault(ind, new HashSet());\n \n for (int p : children) {\n dfs(p, graph, visited, nums);\n }\n visited.add(nums[ind]);\n }\n }\n}\n", + "title": "2003. Smallest Missing Genetic Value in Each Subtree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1 . You are given a 0-indexed integer array parents , where parents[i] is the parent for node i . Since node 0 is the root , parents[0] == -1 . There are 10^5 genetic values, each represented by an integer in the inclusive range [1, 10^5 ] . You are given a 0-indexed integer array nums , where nums[i] is a distinct genetic value for node i . Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i . The subtree rooted at a node x contains node x and all of its descendant nodes.", + "description_images": [], + "constraints": [ + "n == parents.length == nums.length", + "2 <= n <= 10^5", + "0 <= parents[i] <= n - 1 for i != 0", + "parents[0] == -1", + "parents represents a valid tree.", + "1 <= nums[i] <= 10^5", + "Each nums[i] is distinct." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput:[5,1,1,1]\nExplanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput:[7,1,1,4,2,1]\nExplanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-2.png" + }, + { + "text": "Example 3: Input:parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput:[1,1,1,1,1,1,1]\nExplanation:The value 1 is missing from all the subtrees.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3421 ms (Top 39.22%) | Memory: 51.8 MB (Top 96.08%)\nclass Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n ans = [1] * len(parents)\n if 1 in nums:\n tree = {}\n for i, x in enumerate(parents):\n tree.setdefault(x, []).append(i)\n\n k = nums.index(1)\n val = 1\n seen = set()\n\n while k != -1:\n stack = [k]\n while stack:\n x = stack.pop()\n seen.add(nums[x])\n for xx in tree.get(x, []):\n if nums[xx] not in seen:\n stack.append(xx)\n seen.add(nums[xx])\n while val in seen: val += 1\n ans[k] = val\n k = parents[k]\n return ans", + "title": "2003. Smallest Missing Genetic Value in Each Subtree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet {\n private PriorityQueue q;\n private int index;\n public SmallestInfiniteSet() {\n q = new PriorityQueue();\n index = 1;\n }\n \n public int popSmallest() {\n if (q.size()>0){\n return q.poll();\n }\n return index++;\n }\n \n private boolean is_in_q(int num){\n for(int i : q){\n if (i == num){\n return true;\n }\n }\n return false;\n }\n \n public void addBack(int num) {\n if( num < index && !is_in_q(num)){\n q.add(num);\n }\n }\n}\n", + "title": "2336. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet:\n\n def __init__(self):\n self.index = 1\n self.heap = []\n\n def popSmallest(self) -> int:\n if self.heap:\n return heapq.heappop(self.heap)\n self.index += 1\n return self.index-1\n\n def addBack(self, num: int) -> None:\n if self.index > num and num not in self.heap:\n heapq.heappush(self.heap,num)\n", + "title": "2336. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have k lists of sorted integers in non-decreasing order . Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c .", + "description_images": [], + "constraints": [ + "nums.length == k", + "1 <= k <= 3500", + "1 <= nums[i].length <= 50", + "-10^5 <= nums[i][j] <= 10^5", + "nums[i] is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput:[20,24]\nExplanation:List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 89.13%) | Memory: 48.60 MB (Top 83.44%)\n\nclass Solution {\n public int[] smallestRange(List> nums) {\n int[] res = {-100000 , 100000};\n PriorityQueuepq = new PriorityQueue<>((a , b) -> a[0] - b[0]);\n int max = Integer.MIN_VALUE;\n int k = nums.size();\n\n for(int i = 0; i < k; i++){\n int minElem = nums.get(i).get(0);\n int[] arr = {minElem , 0 , i};\n\n max = Math.max(max , minElem);\n pq.add(arr);\n\n }\n while(true){\n int min[] = pq.poll();\n if(res[1] - res[0] > max - min[0]){\n res[1] = max;\n res[0] = min[0];\n }\n min[1]++;\n\n Listcur = nums.get(min[2]);\n\n if(min[1] == cur.size()){\n break;\n }\n else{\n min[0] = cur.get(min[1]);\n max = Math.max(max , cur.get(min[1]));\n pq.add(min);\n }\n }\n return res;\n }\n}\n", + "title": "632. Smallest Range Covering Elements from K Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have k lists of sorted integers in non-decreasing order . Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c .", + "description_images": [], + "constraints": [ + "nums.length == k", + "1 <= k <= 3500", + "1 <= nums[i].length <= 50", + "-10^5 <= nums[i][j] <= 10^5", + "nums[i] is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput:[20,24]\nExplanation:List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 188 ms (Top 86.16%) | Memory: 23.30 MB (Top 59.07%)\n\nfrom typing import List\nimport heapq\n\n\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n heap = [(row[0], i, 0) for i, row in enumerate(nums)]\n heapq.heapify(heap)\n ans = [-10**9, 10**9]\n right = max(row[0] for row in nums)\n while heap:\n left, row, col = heapq.heappop(heap)\n if right - left < ans[1] - ans[0]:\n ans = [left, right]\n if col + 1 == len(nums[row]):\n return ans\n right = max(right, nums[row][col + 1])\n heapq.heappush(heap, (nums[row][col + 1], row, col + 1))\n\n# Tests:\nif __name__ == '__main__':\n s = Solution()\n # test case 1\n output1 = s.smallestRange([[4,10,15,24,26],[0,9,12,20],[5,18,22,30]])\n expected_output1 = [20,24]\n assert output1 == expected_output1, f\"Expected {expected_output1}, but got {output1}\"\n # test case 2\n output2 = s.smallestRange([[1,2,3],[1,2,3],[1,2,3]])\n expected_output2 = [1,1]\n assert output2 == expected_output2, f\"Expected {expected_output2}, but got {output2}\"\n print(\"All tests passed!\")\n", + "title": "632. Smallest Range Covering Elements from K Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k] . You can apply this operation at most once for each index i . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after applying the mentioned operation at most once for each index in it .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0\nOutput:0\nExplanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2\nOutput:6\nExplanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3\nOutput:0\nExplanation:Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 41.38%) | Memory: 50.1 MB (Top 6.90%)\n\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n if (nums.length == 1)\n return 0;\n\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n\n for (int num: nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n int diff = max - min;\n\n return Math.max(0, diff - 2*k);\n }\n}", + "title": "908. Smallest Range I", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k] . You can apply this operation at most once for each index i . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after applying the mentioned operation at most once for each index in it .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0\nOutput:0\nExplanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2\nOutput:6\nExplanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3\nOutput:0\nExplanation:Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 156 ms (Top 5.06%) | Memory: 18.40 MB (Top 7.47%)\n\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n maxi = max(A)\n mini = min(A)\n return max(0, maxi-K-mini-K)\n", + "title": "908. Smallest Range I", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums and an integer k . For each index i where 0 <= i < nums.length , change nums[i] to be either nums[i] + k or nums[i] - k . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after changing the values at each index .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0\nOutput:0\nExplanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2\nOutput:6\nExplanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3\nOutput:3\nExplanation:Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 5.74%) | Memory: 50.2 MB (Top 6.63%)\nclass Solution {\n public int smallestRangeII(int[] nums, int k) {\n int n = nums.length;\n if (n==1)\n return 0; // Max and min are the same\n\n Arrays.sort(nums);\n\n // score = minimum(max-min)\n // To minimize the score, need to add k to small numbers (Initial part of array)\n // and need to subtract k from large numbers (End part of array)\n\n // It might happen that when we add k to a number\n // And subtract k from another number\n // The minimum and maximum can change\n\n // If k>=nums[n-1]-nums[0] the score will always increase if we add k to some\n // numbers and subtract k from some numbers\n // Hence, the minimum score is the current score\n\n if (k >= nums[n-1]-nums[0]) {\n return nums[n-1]-nums[0];\n }\n\n // Now k < nums[n-1]-nums[0]\n // Add k to first p numbers and subtract k from remaining numbers\n // LEFT SEGMENT: First p numbers where we add k\n // RIGHT SEGMENT: Remaining numbers where we subtract k\n\n // LEFT SEGMENT: (nums[0]+k,nums[1]+k,......,nums[p-1]+k)\n // RIGHT SEGMENT: (nums[p]-k,nums[p+1]-k,.......nums[n-1]-k)\n\n // Question: Where is p?\n // Answer: We try all possible values for p and min score everytime\n\n // After subtracting and adding k to numbers,\n // the new minimum and maximum will be\n // minimum = min (nums[0]+k , nums[p]-k)\n // maximum = max (nums[p-1]+k, nums[n-1]-k)\n\n int minScore = nums[n-1]-nums[0];\n for (int p=1;p int:\n nums.sort()\n ans = nums[-1] - nums[0]\n\n for i in range(0, len(nums) - 1):\n ans = min(ans, max(nums[i] + k, nums[-1] -\n k) - min(nums[i+1] - k, nums[0] + k))\n\n return ans\n", + "title": "910. Smallest Range II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums . You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] . Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it . If there are multiple answers, return the smallest such index k .", + "description_images": [], + "constraints": [ + "For example, if we have nums = [2,4,1,3,0] , and we rotate by k = 2 , it becomes [1,3,0,2,4] . This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,4,0]\nOutput:3\nExplanation:Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,0,2,4]\nOutput:0\nExplanation:nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 100.0%) | Memory: 61.60 MB (Top 46.55%)\n\nclass Solution {\n public int bestRotation(int[] nums) {\n final int size = nums.length;\n int[] rsc = new int[size];\n for(int i = 0; i < size - 1; i++) {\n int value = nums[i];\n int downPos = (i + 1 + size - value) % size;\n rsc[downPos]--;\n }\n int value = nums[size-1];\n if( value != 0 ) rsc[size - value]--;\n int bestk = 0;\n int bestscore = rsc[0];\n int score = rsc[0];\n for(int i = 1; i < nums.length; i++) {\n score += rsc[i] + 1;\n if( score > bestscore ) {\n bestk = i;\n bestscore = score;\n }\n }\n return bestk;\n }\n}\n", + "title": "798. Smallest Rotation with Highest Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums . You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] . Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it . If there are multiple answers, return the smallest such index k .", + "description_images": [], + "constraints": [ + "For example, if we have nums = [2,4,1,3,0] , and we rotate by k = 2 , it becomes [1,3,0,2,4] . This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,4,0]\nOutput:3\nExplanation:Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,0,2,4]\nOutput:0\nExplanation:nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bestRotation(self, nums: List[int]) -> int:\n diff = [i - nums[i] for i in range(len(nums))]\n \n target = 0\n qualified = []\n for d in diff:\n if d >= target:\n heappush(qualified, d)\n smallest_rotate = 0\n highest_score = len(qualified)\n \n \n for rotate in range(1, len(nums)):\n target += 1\n while qualified and qualified[0] < target:\n heappop(qualified)\n modified = diff[rotate-1] + len(diff)\n heappush(qualified, modified)\n score = len(qualified)\n if score > highest_score:\n smallest_rotate = rotate\n highest_score = score\n \n return smallest_rotate\n\n", + "title": "798. Smallest Rotation with Highest Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z' . Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root . As a reminder, any shorter prefix of a string is lexicographically smaller . A leaf of a node is a node that has no children.", + "description_images": [], + "constraints": [ + "For example, \"ab\" is lexicographically smaller than \"aba\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,1,2,3,4,3,4]\nOutput:\"dba\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree1.png" + }, + { + "text": "Example 2: Input:root = [25,1,3,1,3,0,2]\nOutput:\"adz\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree2.png" + }, + { + "text": "Example 3: Input:root = [2,2,1,null,1,0,null,0]\nOutput:\"abc\"", + "image": "https://assets.leetcode.com/uploads/2019/02/01/tree3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 58.14%) | Memory: 45.5 MB (Top 29.64%)\nclass Solution {\n String result = null;\n public String smallestFromLeaf(TreeNode root) {\n build(root, new StringBuilder());\n return result;\n }\n\n public void build(TreeNode root, StringBuilder str) {\n if (root == null) return;\n\n StringBuilder sb = new StringBuilder(str).insert(0, String.valueOf(intToChar(root.val)));\n\n if (root.left == null && root.right == null) { // we are on a leaf node\n result = result == null || sb.toString().compareTo(result) < 0 ? sb.toString() : result;\n return;\n }\n build(root.left, sb); // build left child\n build(root.right, sb); // build right child\n }\n\n // turns an int (0-25) into a Character ex: 0 -> a, 1 -> b, 2 -> c\n public Character intToChar(int i) {\n return (char) (i + 'a');\n }\n}", + "title": "988. Smallest String Starting From Leaf", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z' . Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root . As a reminder, any shorter prefix of a string is lexicographically smaller . A leaf of a node is a node that has no children.", + "description_images": [], + "constraints": [ + "For example, \"ab\" is lexicographically smaller than \"aba\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,1,2,3,4,3,4]\nOutput:\"dba\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree1.png" + }, + { + "text": "Example 2: Input:root = [25,1,3,1,3,0,2]\nOutput:\"adz\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree2.png" + }, + { + "text": "Example 3: Input:root = [2,2,1,null,1,0,null,0]\nOutput:\"abc\"", + "image": "https://assets.leetcode.com/uploads/2019/02/01/tree3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, \"\")\n return self.res", + "title": "988. Smallest String Starting From Leaf", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1 , the numeric value of b is 2 , the numeric value of c is 3 , and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8 . You are given two integers n and k . Return the lexicographically smallest string with length equal to n and numeric value equal to k . Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "n <= k <= 26 * n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 27\nOutput:\"aay\"\nExplanation:The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 73\nOutput:\"aaszz\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 80.31%) | Memory: 63.1 MB (Top 85.85%)\nclass Solution {\n public String getSmallestString(int n, int k) {\n char[] ch = new char[n];\n for(int i=0;i0) {\n currChar=Math.min(25,k);\n ch[--n]+=currChar;\n k-=currChar;\n }\n return String.valueOf(ch);\n }\n}", + "title": "1663. Smallest String With A Given Numeric Value", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1 , the numeric value of b is 2 , the numeric value of c is 3 , and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8 . You are given two integers n and k . Return the lexicographically smallest string with length equal to n and numeric value equal to k . Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "n <= k <= 26 * n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 27\nOutput:\"aay\"\nExplanation:The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 73\nOutput:\"aaszz\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1870 ms (Top 22.43%) | Memory: 15.5 MB (Top 41.47%)\nclass Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n ans = ['a']*n # Initialize the answer to be 'aaa'.. length n\n val = n #Value would be length as all are 'a'\n\n for i in range(n-1, -1, -1):\n if val == k: # if value has reached k, we have created our lexicographically smallest string\n break\n val -= 1 # reduce value by one as we are removing 'a' and replacing by a suitable character\n ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or 'z'\n val += ord(ans[i]) - 96 # add the value of newly appended character to value\n\n return ''.join(ans) # return the ans string in the by concatenating the list", + "title": "1663. Smallest String With A Given Numeric Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times . Return the lexicographically smallest string that s can be changed to after using the swaps.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "0 <= pairs.length <= 10^5", + "0 <= pairs[i][0], pairs[i][1] < s.length", + "s only contains lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dcab\", pairs = [[0,3],[1,2]]\nOutput:\"bacd\"Explaination:Swap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\nOutput:\"abcd\"Explaination:Swap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"cba\", pairs = [[0,1],[1,2]]\nOutput:\"abc\"Explaination:Swap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[]parent;\n int[]rank;\n public String smallestStringWithSwaps(String s, List> pairs) {\n parent = new int[s.length()];\n rank = new int[s.length()];\n for(int i=0;i l : pairs){\n int i = l.get(0);\n int j = l.get(1);\n \n int il = find(i);\n int jl = find(j);\n if(il != jl){\n union(il,jl);\n }\n }\n \n //To get the Character in sorted order\n PriorityQueue[]pq = new PriorityQueue[s.length()];\n for(int i=0;i();\n }\n \n for(int i=0;ir2:\n self.parentof[p2] = p1\n else:\n self.parentof[p1]=p2\n if r1==r2: self.rankof[p2]+=1\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n dsu = DSU()\n nodes = set()\n smallest = [s[i] for i in range(len(s))]\n\n for i,j in pairs:\n dsu.unify(i,j)\n nodes.add(i)\n nodes.add(j)\n\n groups = {}\n for node in nodes:\n par = dsu.find(node)\n if par not in groups:\n groups[par] = [node]\n else:\n groups[par].append(node)\n \n for group in groups.values():\n letters,k = sorted([s[i] for i in group]),0\n \n for i in group:\n smallest[i] = letters[k]\n k+=1\n\n return \"\".join(smallest)\n", + "title": "1202. Smallest String With Swaps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"\nOutput:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"\nOutput:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 87.48%) | Memory: 42.2 MB (Top 54.57%)\n\nclass Solution {\n public String smallestSubsequence(String s) {\n boolean[] inStack = new boolean [26];\n int[] lastIdx = new int [26];\n Arrays.fill(lastIdx,-1);\n for(int i = 0; i < s.length(); i++){\n lastIdx[s.charAt(i)-'a'] = i;\n }\n Deque dq = new ArrayDeque<>();\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(inStack[ch-'a']){\n continue;\n }\n while(!dq.isEmpty() && dq.peekLast() > ch && lastIdx[dq.peekLast()-'a'] > i){\n inStack[dq.pollLast()-'a'] = false;\n }\n dq.addLast(ch);\n inStack[ch-'a'] = true;\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n return sb.toString();\n }\n}", + "title": "1081. Smallest Subsequence of Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"\nOutput:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"\nOutput:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str) -> str:\n # calculate the last occurence of each characters in s\n last_occurence = {c: i for i, c in enumerate(s)}\n \n stack = []\n # check if element is in stack\n instack = set()\n for i, c in enumerate(s):\n if c not in instack:\n # check if stack already have char larger then current char\n # and if char in stack will occur later again, remove that from stack\n while stack and stack[-1] > c and last_occurence[stack[-1]] > i:\n instack.remove(stack[-1])\n stack.pop()\n \n instack.add(c) \n stack.append(c)\n \n return \"\".join(stack)\n", + "title": "1081. Smallest Subsequence of Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root . Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 500] .", + "0 <= Node.val <= 500", + "The values of the nodes in the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput:[2,7,4]\nExplanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[1]\nExplanation:The root is the deepest node in the tree.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]\nOutput:[2]\nExplanation:The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode subtreeWithAllDeepest(TreeNode root) {\n\t\tif (root.left == null && root.right == null) return root;\n int depth = findDepth(root);\n Queue q = new LinkedList<>();\n q.offer(root);\n int count = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n count++;\n if (count == depth) {\n break;\n }\n for (int i = 0; i < size; i++) {\n TreeNode cur = q.poll();\n if (cur.left != null) q.offer(cur.left);\n if (cur.right != null) q.offer(cur.right);\n }\n }\n Set set = new HashSet<>();\n while (!q.isEmpty()) {\n set.add(q.poll().val);\n }\n return find(root, set);\n }\n \n public int findDepth(TreeNode root) {\n if (root == null) return 0;\n int left = findDepth(root.left);\n int right = findDepth(root.right);\n return 1 + Math.max(left, right);\n }\n \n public TreeNode find(TreeNode root, Set set) {\n if (root == null) return root;\n if (set.contains(root.val)) return root;\n TreeNode left = find(root.left, set);\n TreeNode right = find(root.right, set);\n if (left != null && right != null) return root;\n else if (left != null) return left;\n else if (right != null) return right;\n else return null;\n }\n}\n", + "title": "865. Smallest Subtree with all the Deepest Nodes", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root . Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 500] .", + "0 <= Node.val <= 500", + "The values of the nodes in the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput:[2,7,4]\nExplanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[1]\nExplanation:The root is the deepest node in the tree.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]\nOutput:[2]\nExplanation:The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n\n # find a set of deepest nodes first\n deepest_nodes = [0]\n self.find_deepest(root, 0, deepest_nodes)\n \n # extract the depth and also make a set out of the values\n targets = set(deepest_nodes[1:])\n\n # get the subtree\n return self.find_merge(root, targets)[0]\n\n def find_deepest(self, node, current_depth, deepest_nodes):\n\n # make a check\n if not node:\n return\n \n # make a check if we are a deep node\n if current_depth > deepest_nodes[0]:\n deepest_nodes.clear()\n deepest_nodes.append(current_depth)\n deepest_nodes.append(node.val)\n elif current_depth == deepest_nodes[0]:\n deepest_nodes.append(node.val)\n \n # go deeper\n self.find_deepest(node.left, current_depth+1, deepest_nodes)\n self.find_deepest(node.right, current_depth+1, deepest_nodes)\n \n def find_merge(self, node, targets):\n\n # make a check\n if not node:\n return None, set()\n\n # check whether we are a target\n found = set()\n if node.val in targets:\n found.add(node.val)\n\n # go deeper and get result nodes\n nleft, left = self.find_merge(node.left, targets)\n if nleft is not None:\n return nleft, set()\n nright, right = self.find_merge(node.right, targets)\n if nright is not None:\n return nright, set()\n\n # merge the found set\n found = found | left | right\n\n # check whether we found all\n if not (targets - found):\n return node, set()\n else:\n return None, found", + "title": "865. Smallest Subtree with all the Deepest Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a project, you have a list of required skills req_skills , and a list of people. The i th person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills , there is at least one person in the team who has that skill. We can represent these teams by the index of each person. Return any sufficient team of the smallest possible size, represented by the index of each person . You may return the answer in any order . It is guaranteed an answer exists.", + "description_images": [], + "constraints": [ + "For example, team = [0, 1, 3] represents the people with skills people[0] , people[1] , and people[3] ." + ], + "examples": [ + { + "text": "Example 1: Input:req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput:[0,2]", + "image": null + }, + { + "text": "Example 2: Input:req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] smallestSufficientTeam(String[] req_skills, List> people) {\n int N = 1 << req_skills.length, INF = (int)1e9;\n int[] parent = new int[N];\n int[] who = new int[N];\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0] = 0;\n for (int i = 0; i < N; i++){\n if (dp[i]!=INF){ // valid state \n for (int k = 0; k < people.size(); k++){\n int cur = i;\n for (int j = 0; j < req_skills.length; j++){\n for (String skill : people.get(k)){\n if (req_skills[j].equals(skill)){\n cur |= 1<dp[i]+1){ // replace if better\n dp[cur]=dp[i]+1;\n parent[cur]=i;\n who[cur]=k;\n }\n }\n }\n }\n int[] ans = new int[dp[N-1]];\n for (int i = 0,cur=N-1; i < ans.length; i++){\n ans[i]=who[cur];\n cur=parent[cur];\n }\n return ans;\n }\n}\n", + "title": "1125. Smallest Sufficient Team", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a project, you have a list of required skills req_skills , and a list of people. The i th person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills , there is at least one person in the team who has that skill. We can represent these teams by the index of each person. Return any sufficient team of the smallest possible size, represented by the index of each person . You may return the answer in any order . It is guaranteed an answer exists.", + "description_images": [], + "constraints": [ + "For example, team = [0, 1, 3] represents the people with skills people[0] , people[1] , and people[3] ." + ], + "examples": [ + { + "text": "Example 1: Input:req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput:[0,2]", + "image": null + }, + { + "text": "Example 2: Input:req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2036 ms (Top 22.82%) | Memory: 203 MB (Top 6.04%)\nfrom collections import defaultdict\nfrom functools import lru_cache\n\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n N = len(req_skills)\n skills = {skill: i for i, skill in enumerate(req_skills)}\n people_mask = defaultdict(int)\n for i, cur_skills in enumerate(people):\n mask = 0\n for skill in cur_skills:\n mask |= 1<= self.res:\n return\n dfs(i+1, l, mask)\n self.path.append(i)\n if mask & people_mask[i] != people_mask[i]: dfs(i+1, l+1, mask | people_mask[i])\n self.path.pop()\n dfs(0,0,0)\n return self.respath", + "title": "1125. Smallest Sufficient Team", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value . Note that the sign of the number does not change after rearranging the digits.", + "description_images": [], + "constraints": [ + "-10^15 <= num <=10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 310\nOutput:103\nExplanation:The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.", + "image": null + }, + { + "text": "Example 2: Input:num = -7605\nOutput:-7650\nExplanation:Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long smallestNumber(long num) {\n if(num == 0){\n return 0;\n }\n boolean isNegative = num < 0;\n num = num < 0 ? num * -1 : num;\n \n char[] c = String.valueOf(num).toCharArray();\n Arrays.sort(c);\n String str;\n if(!isNegative){\n int non = 0;\n\t\t\t//if not negative we need to find out the first non-leading zero then swap with first zero\n for(; non < c.length; non++){\n if(c[non] != '0'){\n break;\n }\n }\n char temp = c[non];\n c[non] = c[0];\n c[0] = temp;\n str = new String(c);\n }else{\n str = new String(c);\n StringBuilder sb = new StringBuilder(str);\n str = \"-\".concat(sb.reverse().toString());\n }\n return Long.valueOf(str);\n }\n}\n", + "title": "2165. Smallest Value of the Rearranged Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value . Note that the sign of the number does not change after rearranging the digits.", + "description_images": [], + "constraints": [ + "-10^15 <= num <= 10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 310\nOutput:103\nExplanation:The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.", + "image": null + }, + { + "text": "Example 2: Input:num = -7605\nOutput:-7650\nExplanation:Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 17.05%) | Memory: 13.9 MB (Top 69.77%)\nclass Solution:\n def smallestNumber(self, num: int) -> int:\n lst=[i for i in str(num)]\n if num<0:\n return ''.join(['-'] + sorted(lst[1:],reverse=True))\n lst=sorted(lst)\n if '0' in lst:\n itr=0\n while itr map,int si,int ei){\n //if si==ei just directly return \n if(si==ei) return new int [] {0,0,0};\n LinkedList que = new LinkedList<>();\n que.addLast(new int[] {si,0,0});\n int level = 0;\n //to stop visiting cells again\n boolean [] vis = new boolean [ei+1];\n vis[si]=true;\n //starting bfs\n while(que.size()!=0){\n int size=que.size();\n while(size-->0){\n int [] rem = que.removeFirst();\n int idx= rem[0];\n int lad = rem[1];\n int sna = rem[2];\n for(int i=1;i<=dice;i++){\n int x =i+rem[0]; //checking all the steps\n if(x<=ei){ //valid points\n if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder\n if(map.containsKey(x)){\n int val = map.get(x); \n if(val==ei) return new int[] {level+1,lad+1,sna};\n if(!vis[val]){\n vis[val]=true;\n //if val>x this means we have a ladder and if less, then it is a snake\n que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});\n }\n }\n }\n else{\n //if it is not present in map, then it is a normal cell, so just insert it directly\n if(x==ei) return new int [] {level+1,lad,sna};\n if(!vis[x]){\n vis[x]=true;\n que.addLast(new int [] {x,lad,sna});\n }\n }\n }\n }\n }\n level++;\n }\n return new int [] {-1,0,0};\n }\n public int snakesAndLadders(int[][] board) {\n HashMap map = new HashMap<>();\n int count = 1;\n int n = board.length;\n boolean flag = true;\n //traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)\n for(int i=n-1;i>=0;i--){\n //traversing in the order of the board\n if(flag){\n for(int j=0;j=0;j--){\n if(board[i][j]!=-1){\n map.put(count,board[i][j]);\n }\n flag=true;\n count++;\n }\n }\n }\n //if snake on destination then just return -1;\n if(board[0][0]!=-1) return -1;\n //we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used} \n int [] ans = getans(6,map,1,n*n);;\n return ans[0];\n \n }\n}", + "title": "909. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n integer matrix board where the cells are labeled from 1 to n 2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0] ) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr , do the following: A board square on row r and column c has a snake or ladder if board[r][c] != -1 . The destination of that snake or ladder is board[r][c] . Squares 1 and n 2 do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. Return the least number of moves required to reach the square n 2 . If it is not possible to reach the square, return -1 .", + "description_images": [], + "constraints": [ + "Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n 2 )] . This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next .", + "The game ends when you reach the square n 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput:4\nExplanation:In the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.", + "image": "https://assets.leetcode.com/uploads/2018/09/23/snakes.png" + }, + { + "text": "Example 2: Input:board = [[-1,-1],[-1,3]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 228 ms (Top 5.16%) | Memory: 17.50 MB (Top 5.8%)\n\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n moves = 0\n q = collections.deque([1])\n visited = [[False for _ in range(n)] for _ in range(n)]\n visited[n-1][0] = True\n while q:\n size = len(q)\n for i in range(size):\n currBoardVal = q.popleft()\n if currBoardVal == n*n:\n return moves\n for diceVal in range(1, 7):\n if currBoardVal + diceVal > n*n:\n break\n pos = self.findCoordinates(currBoardVal + diceVal, n)\n row, col = pos\n if not visited[row][col]:\n visited[row][col] = True\n if board[row][col] == -1:\n q.append(currBoardVal + diceVal)\n else:\n q.append(board[row][col])\n moves += 1\n return -1\n \n def findCoordinates(self, curr: int, n: int) -> Tuple[int, int]:\n row = n - (curr - 1) // n - 1\n col = (curr - 1) % n\n if row % 2 == n % 2:\n return (row, n - 1 - col)\n else:\n return (row, col)\n\n", + "title": "909. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement a SnapshotArray that supports the following interface:", + "description_images": [], + "constraints": [ + "SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0 .", + "void set(index, val) sets the element at the given index to be equal to val .", + "int snap() takes a snapshot of the array and returns the snap_id : the total number of times we called snap() minus 1 .", + "int get(index, snap_id) returns the value at the given index , at the time we took the snapshot with the given snap_id" + ], + "examples": [ + { + "text": "Example 1: Input:[\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n[[3],[0,5],[],[0,6],[0,0]]\nOutput:[null,null,0,null,5]\nExplanation:SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\nsnapshotArr.set(0,5); // Set array[0] = 5\nsnapshotArr.snap(); // Take a snapshot, return snap_id = 0\nsnapshotArr.set(0,6);\nsnapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 90.65%) | Memory: 81.4 MB (Top 44.17%)\nclass SnapshotArray {\n\n TreeMap[] snapshotArray;\n int currSnapId;\n\n public SnapshotArray(int length) {\n snapshotArray = new TreeMap[length];\n for(int i=0;i None:\n self.history[self.snap_id][index] = val\n\n def snap(self) -> int:\n self.snap_id += 1\n return self.snap_id-1\n\n def get(self, index: int, snap_id: int) -> int:\n for i in range(snap_id,-1,-1):\n if index in self.history[i]:\n return self.history[i][index]\n return 0 # default value in case it wasn't set earlier", + "title": "1146. Snapshot Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\" . The equation contains only '+' , '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.", + "description_images": [], + "constraints": [ + "3 <= equation.length <= 1000", + "equation has exactly one '=' .", + "equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x' ." + ], + "examples": [ + { + "text": "Example 1: Input:equation = \"x+5-3+x=6+x-2\"\nOutput:\"x=2\"", + "image": null + }, + { + "text": "Example 2: Input:equation = \"x=x\"\nOutput:\"Infinite solutions\"", + "image": null + }, + { + "text": "Example 3: Input:equation = \"2x=x\"\nOutput:\"x=0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] simplifyEqn(String eqn){\n int prevSign = 1;\n int sumX = 0;\n int sumNums = 0;\n for(int i=0;i str:\n \"\"\" O(N)TS \"\"\"\n x, y, p = 0, 0, 1\n for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n g = i.group()\n if g == '=':\n p = -1\n elif g[-1] == 'x':\n x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n else:\n y += -p * int(g)\n\n if x == 0 == y:\n return 'Infinite solutions'\n elif x == 0:\n return \"No solution\"\n return f'x={y // x}'", + "title": "640. Solve the Equation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array questions where questions[i] = [points i , brainpower i ] . The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0 ) and make a decision whether to solve or skip each question. Solving question i will earn you points i points but you will be unable to solve each of the next brainpower i questions. If you skip question i , you get to make the decision on the next question. Return the maximum points you can earn for the exam .", + "description_images": [], + "constraints": [ + "For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]] : If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2 . If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3 .", + "If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2 .", + "If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:questions = [[3,2],[4,3],[4,4],[2,5]]\nOutput:5\nExplanation:The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.", + "image": null + }, + { + "text": "Example 2: Input:questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput:7\nExplanation:The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mostPoints(self, q: List[List[int]]) -> int:\n @cache\n def dfs(i: int) -> int:\n return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1]))\n return dfs(0)\n", + "title": "2140. Solving Questions With Brainpower", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , sort the array in ascending order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-5 * 10^4 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,3,1]\nOutput:[1,2,3,5]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1,2,0,0]\nOutput:[0,0,1,1,2,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 28.44%) | Memory: 75.6 MB (Top 11.81%)\nclass Solution {\n\n public void downHeapify(int[] nums, int startIndex, int lastIndex){\n\n int parentIndex = startIndex;\n int leftChildIndex = 2*parentIndex + 1;\n int rightChildIndex = 2*parentIndex + 2;\n\n while(leftChildIndex <= lastIndex){\n int maxIndex = parentIndex;\n if(nums[leftChildIndex] > nums[maxIndex]){\n maxIndex = leftChildIndex;\n }\n if(rightChildIndex <= lastIndex && nums[rightChildIndex] > nums[maxIndex]){\n maxIndex = rightChildIndex;\n }\n if(maxIndex == parentIndex){\n return;\n }\n int temp = nums[maxIndex];\n nums[maxIndex] = nums[parentIndex];\n nums[parentIndex] = temp;\n parentIndex = maxIndex;\n leftChildIndex = 2*parentIndex + 1;\n rightChildIndex = 2*parentIndex + 2;\n }\n return;\n }\n\n public int[] sortArray(int[] nums) {\n int len = nums.length;\n //building a heap - O(n) time\n for(int i=(len/2)-1;i>=0;i--){\n downHeapify(nums,i,len-1);\n }\n //sorting element - nlogn(n) time\n for(int i=len -1 ;i>0;i--){\n int temp = nums[i];\n nums[i] = nums[0];\n nums[0] = temp;\n downHeapify(nums,0,i-1);\n }\n return nums;\n\n }\n}", + "title": "912. Sort an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums , sort the array in ascending order.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-5 * 10^4 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,3,1]\nOutput:[1,2,3,5]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1,2,0,0]\nOutput:[0,0,1,1,2,5]", + "image": null + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n \n h = {}\n for i in nums:\n if i in h:\n h[i]+=1\n else:\n h[i]=1\n \n heap = []\n for i in h:\n heap.append([i,h[i]])\n \n heapq.heapify(heap)\n ans = []\n \n while heap:\n x = heapq.heappop(heap)\n ans.append(x[0])\n if x[1]>1:\n heapq.heappush(heap,[x[0],x[1]-1])\n \n return ans\n", + "title": "912. Sort an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums , sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,2,2,3]\nOutput:[3,1,1,2,2,2]\nExplanation:'3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,3,2]\nOutput:[1,3,3,2,2]\nExplanation:'2' and '3' both have a frequency of 2, so they are sorted in decreasing order.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-6,4,5,-6,1,4,1]\nOutput:[5,-1,4,4,-6,-6,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \n r = Counter(nums).most_common()\n r.sort(key = lambda x: x[0], reverse=True)\n r.sort(key = lambda x: x[1])\n \n t = []\n for i in r:\n a, b = i\n t.extend([a]*b)\n \n return t\n", + "title": "1636. Sort Array by Increasing Frequency", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "0 <= nums[i] <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,4]\nOutput:[2,4,3,1]\nExplanation:The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 48.1 MB (Top 66.96%)\nclass Solution {\n\n public int[] sortArrayByParity(int[] nums) {\n int i = 0;\n int j = 0;\n\n while(i < nums.length){\n if(nums[i] % 2 == 1){\n i++;\n }else{\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n\n i++;\n j++;\n }\n }\n\n return nums;\n }\n}", + "title": "905. Sort Array By Parity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "0 <= nums[i] <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,4]\nOutput:[2,4,3,1]\nExplanation:The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 84 ms (Top 42.8%) | Memory: 17.10 MB (Top 53.6%)\n\nclass Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n i, j = 0, len(A) - 1\n while i < j:\n \tif A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i]\n \ti, j = i + 1 - A[i] % 2, j - A[j] % 2\n return A", + "title": "905. Sort Array By Parity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , half of the integers in nums are odd , and the other half are even . Sort the array so that whenever nums[i] is odd, i is odd , and whenever nums[i] is even, i is even . Return any answer array that satisfies this condition .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^4", + "nums.length is even.", + "Half of the integers in nums are even.", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,7]\nOutput:[4,5,2,7]\nExplanation:[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3]\nOutput:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 44.53%) | Memory: 47.70 MB (Top 5.52%)\n\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n int i = 0, j = 1, n = A.length;\n while (i < n && j < n) {\n while (i < n && A[i] % 2 == 0) {\n i += 2;\n }\n while (j < n && A[j] % 2 == 1) {\n j += 2;\n }\n if (i < n && j < n) {\n swap(A, i, j);\n }\n }\n return A;\n }\n private void swap(int[] A, int i, int j) {\n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n }\n}\n\n", + "title": "922. Sort Array By Parity II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums , half of the integers in nums are odd , and the other half are even . Sort the array so that whenever nums[i] is odd, i is odd , and whenever nums[i] is even, i is even . Return any answer array that satisfies this condition .", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^4", + "nums.length is even.", + "Half of the integers in nums are even.", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,7]\nOutput:[4,5,2,7]\nExplanation:[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3]\nOutput:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 148 ms (Top 91.55%) | Memory: 19.90 MB (Top 17.18%)\n\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in range(len(nums)):\n if nums[i]%2 == 0:\n even.append(nums[i])\n else:\n odd.append(nums[i])\n for i in range(len(even)):\n lst.append(even[i])\n lst.append(odd[i])\n return lst\n", + "title": "922. Sort Array By Parity II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string . If there are multiple answers, return any of them .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s consists of uppercase and lowercase English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"tree\"\nOutput:\"eert\"\nExplanation:'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cccaaa\"\nOutput:\"aaaccc\"\nExplanation:Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Aabb\"\nOutput:\"bbAa\"\nExplanation:\"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 83.68%) | Memory: 45.80 MB (Top 20.05%)\n\nclass Solution {\n public String frequencySort(String s) {\n int len = s.length();\n HashMap> map = new HashMap(); \n HashMap freqMap = new HashMap();\n \n for(int idx = 0;idx set = map.getOrDefault(freqMap.get(ch),new HashSet());\n set.add(ch);\n map.put(freqMap.get(ch),set);\n maxFreq = Math.max(maxFreq , freqMap.get(ch));\n minFreq = Math.min(minFreq,freqMap.get(ch));\n }\n \n StringBuilder ansStr = new StringBuilder();\n \n for(int freq = maxFreq;freq>=minFreq;freq--){\n if(map.containsKey(freq)){\n HashSet set = map.get(freq);\n for(char ch : set){\n int temp = freq;\n while(temp>0){\n ansStr.append(ch);\n temp--;\n }\n }\n }\n }\n \n return ansStr.toString();\n }\n}\n", + "title": "451. Sort Characters By Frequency", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string . If there are multiple answers, return any of them .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s consists of uppercase and lowercase English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"tree\"\nOutput:\"eert\"\nExplanation:'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cccaaa\"\nOutput:\"aaaccc\"\nExplanation:Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Aabb\"\nOutput:\"bbAa\"\nExplanation:\"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def frequencySort(self, s: str) -> str:\n di = Counter(s)\n #it wont strike immediately that this is a heap kind of question.\n heap = []\n heapq.heapify(heap)\n for key,val in di.items():\n heapq.heappush(heap,(-1*val,key))\n # n = len(s)\n res = \"\"\n # print(heap)\n while(len(heap)):\n val,ch = heapq.heappop(heap)\n res+=(ch*(-1*val))\n return res\n", + "title": "451. Sort Characters By Frequency", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]\nOutput:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]\nOutput:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public void sortColors(int[] nums) {\n\n int zeroIndex = 0, twoIndex = nums.length - 1, i = 0;\n while (i <= twoIndex) {\n if (nums[i] == 0)\n swap(nums, zeroIndex++, i++);\n else if (nums[i] == 2)\n swap(nums, twoIndex--, i);\n else\n i++;\n }\n }\n\n public void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]\nOutput:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]\nOutput:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 8.88%) | Memory: 16.20 MB (Top 55.73%)\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n\n red, white, blue = 0, 0, len(nums) - 1\n\n while white <= blue:\n if nums[white] == 0:\n nums[white], nums[red] = nums[red], nums[white]\n red += 1\n white += 1\n elif nums[white] == 1:\n white += 1\n else:\n nums[white], nums[blue] = nums[blue], nums[white]\n blue -= 1\n", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums .", + "description_images": [], + "constraints": [ + "For example, if nums = [4, 1 ,2, 3 ] before this step, it becomes [4, 3 ,2, 1 ] after. The values at odd indices 1 and 3 are sorted in non-increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,2,3]\nOutput:[2,3,4,1]\nExplanation:First, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1]\nOutput:[2,1]\nExplanation:Since there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 98.20%) | Memory: 44.5 MB (Top 79.13%)\n\nclass Solution {\n public int[] sortEvenOdd(int[] nums) {\n int[] even = new int[101];\n int[] odd = new int[101];\n int length = nums.length;\n for (int i = 0; i < length; ++i) {\n if (i % 2 == 0) {\n even[nums[i]]++;\n } else {\n odd[nums[i]]++;\n }\n }\n int e = 0;\n int o = 100;\n for (int i = 0; i < length; ++i) {\n if (i % 2 == 0) {\n // check even\n while (even[e] == 0) {\n ++e;\n }\n nums[i] = e;\n even[e]--;\n } else {\n while(odd[o] == 0) {\n --o;\n }\n nums[i] = o;\n odd[o]--;\n }\n }\n return nums;\n }\n}", + "title": "2164. Sort Even and Odd Indices Independently", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums .", + "description_images": [], + "constraints": [ + "For example, if nums = [4, 1 ,2, 3 ] before this step, it becomes [4, 3 ,2, 1 ] after. The values at odd indices 1 and 3 are sorted in non-increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,2,3]\nOutput:[2,3,4,1]\nExplanation:First, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1]\nOutput:[2,1]\nExplanation:Since there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 63 ms (Top 80.35%) | Memory: 13.8 MB (Top 69.47%)\n\nclass Solution(object):\n def sortEvenOdd(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n nums[::2], nums[1::2] = sorted(nums[::2]), sorted(nums[1::2], reverse=True)\n return nums", + "title": "2164. Sort Even and Odd Indices Independently", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr . Sort the integers in the array in ascending order by the number of 1 's in their binary representation and in case of two or more integers have the same number of 1 's you have to sort them in ascending order. Return the array after sorting it .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,2,3,4,5,6,7,8]\nOutput:[0,1,2,4,8,3,5,6,7]Explantion:[0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput:[1,2,4,8,16,32,64,128,256,512,1024]Explantion:All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 70.77%) | Memory: 42.3 MB (Top 96.77%)\nclass Solution {\n public int[] sortByBits(int[] arr) {\n\n Integer[] arrInt = new Integer[arr.length];\n\n for(int i=0;i() {\n @Override\n public int compare(Integer a, Integer b) {\n int aBits=numOfBits(a);\n int bBits=numOfBits(b);\n if(aBits==bBits) {\n return a-b;\n }\n return aBits-bBits;\n }\n });\n\n for(int i=0;i>>1;\n }\n\n return bits;\n }\n}", + "title": "1356. Sort Integers by The Number of 1 Bits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array arr . Sort the integers in the array in ascending order by the number of 1 's in their binary representation and in case of two or more integers have the same number of 1 's you have to sort them in ascending order. Return the array after sorting it .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,2,3,4,5,6,7,8]\nOutput:[0,1,2,4,8,3,5,6,7]Explantion:[0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput:[1,2,4,8,16,32,64,128,256,512,1024]Explantion:All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n binary = []\n final = []\n arr.sort()\n for i in arr:\n binary.append(bin(i).count(\"1\"))\n for i,j in zip(arr,binary):\n final.append((i,j))\n z = sorted(final, key=lambda x:x[1])\n \n ls = []\n for k in z:\n ls.append(k[0])\n \n return ls\n", + "title": "1356. Sort Integers by The Number of 1 Bits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 ( 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1 ). Given three integers lo , hi and k . The task is to sort all integers in the interval [lo, hi] by the power value in ascending order , if two or more integers have the same power value sort them by ascending order . Return the k th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "if x is even then x = x / 2", + "if x is odd then x = 3 * x + 1" + ], + "examples": [ + { + "text": "Example 1: Input:lo = 12, hi = 15, k = 2\nOutput:13\nExplanation:The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.", + "image": null + }, + { + "text": "Example 2: Input:lo = 7, hi = 11, k = 4\nOutput:7\nExplanation:The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getKth(int lo, int hi, int k) {\n\n int p = 0;\n int[][] powerArr = new int[hi - lo + 1][2];\n\n Map memo = new HashMap<>();\n for (int i = lo; i <= hi; i++)\n powerArr[p++] = new int[]{i, getPower(i, memo)};\n\n Arrays.sort(powerArr, (a1, a2) -> a1[1] - a2[1] == 0 ? a1[0] - a2[0] : a1[1] - a2[1]);\n\n return powerArr[k - 1][0];\n }\n\n private int getPower(int i, Map memo) {\n if (memo.containsKey(i)) return memo.get(i);\n\n if (i == 1) return 0;\n\n int power = 1 + (i % 2 == 0 ? getPower(i / 2, memo) : getPower(i * 3 + 1, memo));\n\n memo.put(i, power);\n return power;\n }\n}\n", + "title": "1387. Sort Integers by The Power Value", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 ( 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1 ). Given three integers lo , hi and k . The task is to sort all integers in the interval [lo, hi] by the power value in ascending order , if two or more integers have the same power value sort them by ascending order . Return the k th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "if x is even then x = x / 2", + "if x is odd then x = 3 * x + 1" + ], + "examples": [ + { + "text": "Example 1: Input:lo = 12, hi = 15, k = 2\nOutput:13\nExplanation:The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.", + "image": null + }, + { + "text": "Example 2: Input:lo = 7, hi = 11, k = 4\nOutput:7\nExplanation:The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 156 ms (Top 74.13%) | Memory: 16.70 MB (Top 42.43%)\n\nimport heapq\nclass Solution:\n def power(self,n):\n if n in self.dic:\n return self.dic[n]\n if n % 2:\n self.dic[n] = self.power(3 * n + 1) + 1\n else:\n self.dic[n] = self.power(n // 2) + 1\n return self.dic[n] \n def getKth(self, lo: int, hi: int, k: int) -> int:\n self.dic = {1:0}\n for i in range(lo,hi+1):\n self.power(i)\n \n lst = [(self.dic[i],i) for i in range(lo,hi+1)]\n heapq.heapify(lst)\n \n for i in range(k):\n ans = heapq.heappop(lst)\n \n return ans[1] \n", + "title": "1387. Sort Integers by The Power Value", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n items each belonging to zero or one of m groups where group[i] is the group that the i -th item belongs to and it's equal to -1 if the i -th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: Return any solution if there is more than one solution and return an empty list if there is no solution.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/11/1359_ex1.png" + ], + "constraints": [ + "The items that belong to the same group are next to each other in the sorted list.", + "There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i -th item in the sorted array (to the left of the i -th item)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\nOutput:[6,3,4,1,5,2,0,7]", + "image": null + }, + { + "text": "Example 2: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\nOutput:[]\nExplanation:This is the same as example 1 except that 4 needs to be before 6 in the sorted list.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 104 ms (Top 36.60%) | Memory: 71.6 MB (Top 49.67%)\nclass Solution {\n // topological sort group first, then node within the group\n private List[] groups;\n private List[] graph;\n // indegrees of node\n private int[] indegrees;\n // indegrees of group\n private int[] indegreeGroups;\n public int[] sortItems(int n, int m, int[] group, List> beforeItems) {\n buildGroups(n, group);\n buildGraph(n, beforeItems, group);\n int[] result = new int[n];\n int top = -1;\n Queue queue = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (indegreeGroups[i] == 0) {\n queue.offer(i);\n }\n }\n while (!queue.isEmpty()) {\n Integer groupId = queue.poll();\n List groupItems = groups[groupId];\n if (groupItems == null) continue;\n Queue itemQueue = new LinkedList<>();\n for (var item: groupItems) {\n if (indegrees[item] == 0) {\n itemQueue.offer(item);\n }\n }\n while (!itemQueue.isEmpty()) {\n Integer item = itemQueue.poll();\n result[++top] = item;\n if (graph[item] == null) continue;\n for (var neighbor: graph[item]) {\n indegrees[neighbor]--;\n if (group[neighbor] != groupId) {\n if (--indegreeGroups[group[neighbor]] == 0) {\n queue.offer(group[neighbor]);\n }\n } else if (indegrees[neighbor] == 0) {\n itemQueue.offer(neighbor);\n }\n }\n }\n }\n if (top < n - 1) return new int[] {};\n return result;\n }\n private void buildGroups(int n, int[] group) {\n // build groups;\n groups = new List[n];\n int index = n - 1;\n for (int i = 0; i < n; i++) {\n if (group[i] == -1) {\n // virtual group\n group[i] = index--;\n }\n if (groups[group[i]] == null) {\n groups[group[i]] = new ArrayList<>();\n }\n groups[group[i]].add(i);\n }\n }\n private void buildGraph(int n, List> beforeItems, int[] group) {\n graph = new List[n];\n indegrees = new int[n];\n indegreeGroups = new int[n];\n for (int i = 0; i < n; i++) {\n for (int j: beforeItems.get(i)) {\n if (graph[j] == null) {\n graph[j] = new ArrayList<>();\n }\n graph[j].add(i);\n indegrees[i]++;\n if (group[i] != group[j]) {\n indegreeGroups[group[i]]++;\n }\n }\n }\n }\n}", + "title": "1203. Sort Items by Groups Respecting Dependencies", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n items each belonging to zero or one of m groups where group[i] is the group that the i -th item belongs to and it's equal to -1 if the i -th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: Return any solution if there is more than one solution and return an empty list if there is no solution.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/11/1359_ex1.png" + ], + "constraints": [ + "The items that belong to the same group are next to each other in the sorted list.", + "There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i -th item in the sorted array (to the left of the i -th item)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\nOutput:[6,3,4,1,5,2,0,7]", + "image": null + }, + { + "text": "Example 2: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\nOutput:[]\nExplanation:This is the same as example 1 except that 4 needs to be before 6 in the sorted list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n before = {i:set() for i in range(n)}\n after = {i:set() for i in range(n)}\n beforeG = {i:set() for i in range(m)}\n afterG = {i:set() for i in range(m)}\n groups = {i:set() for i in range(m)}\n qg = collections.deque()\n lazy = collections.deque()\n for i in range(n):\n if group[i] != -1:\n groups[group[i]].add(i)\n for x in beforeItems[i]:\n before[i].add(x)\n after[x].add(i)\n if group[x] != group[i] and group[x] != -1 and group[i] != -1:\n beforeG[group[i]].add(group[x])\n afterG[group[x]].add(group[i])\n for i in range(n):\n if group[i] == -1 and not before[i]:\n lazy.append(i)\n\n for i in range(m):\n if not beforeG[i]:\n qg.append(i)\n ans = []\n while qg:\n while lazy:\n i = lazy.popleft()\n ans.append(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j] and group[j] == -1:\n lazy.append(j)\n g = qg.popleft()\n q = collections.deque()\n for member in groups[g]:\n if not before[member]:\n q.append(member)\n while q:\n i = q.popleft()\n ans.append(i)\n groups[g].remove(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j]:\n if group[j] == g:\n q.append(j)\n if group[j] == -1:\n lazy.append(j) \n if groups[g]:\n return []\n for p in afterG[g]:\n beforeG[p].remove(g)\n if not beforeG[p]:\n qg.append(p)\n while lazy:\n i = lazy.popleft()\n ans.append(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j] and group[j] == -1:\n lazy.append(j)\n return ans if len(ans) == n else []", + "title": "1203. Sort Items by Groups Respecting Dependencies", + "topic": "Database" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list, return the list after sorting it in ascending order .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]\nOutput:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]\nOutput:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 51.11%) | Memory: 78.2 MB (Top 48.67%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode sortList(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n\n ListNode mid = middle(head);\n\n ListNode left = sortList(head);\n ListNode right = sortList(mid);\n\n return mergeTwoLists(left, right);\n }\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode head = new ListNode();\n ListNode tail = head;\n while (list1 != null && list2 != null) {\n if (list1.val < list2.val) {\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n } else {\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n }\n }\n\n tail.next = (list1 != null) ? list1 : list2;\n\n return head.next;\n }\n\n public ListNode middle(ListNode head) {\n ListNode midprev = null;\n while (head != null && head.next != null) {\n midprev = (midprev == null) ? head : midprev.next;\n head = head.next.next;\n }\n ListNode mid = midprev.next;\n midprev.next = null;\n return mid;\n }\n}", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the head of a linked list, return the list after sorting it in ascending order .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]\nOutput:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]\nOutput:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n store = []\n curr = head\n while curr:\n store.append(curr.val)\n curr = curr.next\n store.sort()\n dummyNode = ListNode(0)\n temp = dummyNode\n \n for i in store:\n x = ListNode(val = i)\n temp.next = x\n temp = x\n return dummyNode.next", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9 . You are also given another integer array nums . Return the array nums sorted in non-decreasing order based on the mapped values of its elements. Notes:", + "description_images": [], + "constraints": [ + "Elements with the same mapped values should appear in the same relative order as in the input.", + "The elements of nums should only be sorted based on their mapped values and not be replaced by them." + ], + "examples": [ + { + "text": "Example 1: Input:mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\nOutput:[338,38,991]\nExplanation:Map the number 991 as follows:\n1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.\n2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.\nTherefore, the mapped value of 991 is 669.\n338 maps to 007, or 7 after removing the leading zeros.\n38 maps to 07, which is also 7 after removing leading zeros.\nSince 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.\nThus, the sorted array is [338,38,991].", + "image": null + }, + { + "text": "Example 2: Input:mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]\nOutput:[123,456,789]\nExplanation:789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n \n return sorted(nums, key = lambda x: int(\"\".join([str(mapping[int(digit)]) for digit in str(x)])))\n", + "title": "2191. Sort the Jumbled Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0] , where mat is a 6 x 3 matrix, includes cells mat[2][0] , mat[3][1] , and mat[4][2] . Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput:[[1,1,1,1],[1,2,2,2],[1,2,3,3]]", + "image": "https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png" + }, + { + "text": "Example 2: Input:mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput:[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] diagonalSort(int[][] mat) {\n int n = mat.length; \n int m = mat[0].length;\n for(int i=0;i List[List[int]]:\n n, m, d = len(A), len(A[0]), defaultdict(list)\n any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m))\n any(d[sum_].sort(reverse=1) for sum_ in d)\n return [[d[i-j].pop() for j in range(m)] for i in range(n)]", + "title": "1329. Sort the Matrix Diagonally", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence .", + "description_images": [], + "constraints": [ + "For example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"is2 sentence4 This1 a3\"\nOutput:\"This is a sentence\"\nExplanation:Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Myself2 Me1 I4 and3\"\nOutput:\"Me Myself and I\"\nExplanation:Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 59.85%) | Memory: 42 MB (Top 63.26%)\nclass Solution {\n public String sortSentence(String s) {\n String []res=new String[s.split(\" \").length];\n for(String st:s.split(\" \")){\n res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1);\n }\n return String.join(\" \",res);\n }\n}", + "title": "1859. Sorting the Sentence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence .", + "description_images": [], + "constraints": [ + "For example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"is2 sentence4 This1 a3\"\nOutput:\"This is a sentence\"\nExplanation:Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Myself2 Me1 I4 and3\"\nOutput:\"Me Myself and I\"\nExplanation:Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 5.88%) | Memory: 13.7 MB (Top 96.86%)\nclass Solution:\n def sortSentence(self, s: str) -> str:\n\n x = s.split()\n dic = {}\n for i in x :\n dic[i[-1]] = i[:-1]\n return ' '.join([dic[j] for j in sorted(dic)])", + "title": "1859. Sorting the Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are two types of soup: type A and type B . Initially, we have n ml of each type of soup. There are four kinds of operations: When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25 . If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 50\nOutput:0.62500\nExplanation:If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:0.71875", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.5%) | Memory: 39.56 MB (Top 93.7%)\n\nclass Solution {\n public double soupServings(int n) {\n if(n>4800) return 1;\n n=(int)Math.ceil(n*1.0/25);\n double dp[][]= new double[n+1][n+1];\n return helper(n,n,dp);\n }\n double helper(int a,int b,double dp[][]){\n if(a<=0 && b<=0) return 0.5;\n if(b<=0) return 0;\n if(a<=0) return 1;\n if(dp[a][b]>0) return dp[a][b];\n return dp[a][b]=0.25*(helper(a-4,b,dp)+helper(a-3,b-1,dp)+helper(a-2,b-2,dp)+helper(a-1,b-3,dp));\n }\n}\n// Upvote please !!", + "title": "808. Soup Servings", + "topic": "Stack" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are two types of soup: type A and type B . Initially, we have n ml of each type of soup. There are four kinds of operations: When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25 . If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 50\nOutput:0.62500\nExplanation:If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.", + "image": null + }, + { + "text": "Example 2: Input:n = 100\nOutput:0.71875", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 34.5%) | Memory: 18.09 MB (Top 39.7%)\n\nclass Solution:\n def soupServings(self, n: int) -> float:\n if n > 4451: \n return 1.0\n n = (n + 24) // 25\n memo = dict()\n \n def dp(i, j):\n if (i, j) in memo:\n return memo[(i, j)]\n if i <= 0 and j <= 0: \n return 0.5\n if i <= 0: \n return 1.0\n if j <= 0: \n return 0.0\n memo[(i, j)] = 0.25 * (dp(i - 4, j) + dp(i - 3, j - 1) + dp(i - 2, j - 2) + dp(i - 1, j - 3))\n return memo[(i, j)]\n \n return dp(n, n)", + "title": "808. Soup Servings", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x . Notice that x does not have to be an element in nums . Return x if the array is special , otherwise, return -1 . It can be proven that if nums is special, the value for x is unique .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5]\nOutput:2\nExplanation:There are 2 values (3 and 5) that are greater than or equal to 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0]\nOutput:-1\nExplanation:No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,4,3,0,4]\nOutput:3\nExplanation:There are 3 values that are greater than or equal to 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.84%) | Memory: 42.3 MB (Top 22.19%)\nclass Solution {\n public int specialArray(int[] nums) {\n int x = nums.length;\n int[] counts = new int[x+1];\n\n for(int elem : nums)\n if(elem >= x)\n counts[x]++;\n else\n counts[elem]++;\n\n int res = 0;\n for(int i = counts.length-1; i > 0; i--) {\n res += counts[i];\n if(res == i)\n return i;\n }\n\n return -1;\n }\n}", + "title": "1608. Special Array With X Elements Greater Than or Equal X", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x . Notice that x does not have to be an element in nums . Return x if the array is special , otherwise, return -1 . It can be proven that if nums is special, the value for x is unique .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5]\nOutput:2\nExplanation:There are 2 values (3 and 5) that are greater than or equal to 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0]\nOutput:-1\nExplanation:No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,4,3,0,4]\nOutput:3\nExplanation:There are 3 values that are greater than or equal to 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 23.2%) | Memory: 16.30 MB (Top 28.6%)\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(max(nums)+1):\n y=len(nums)-bisect.bisect_left(nums,i)\n if y==i:\n return i\n return -1\n\n \n ", + "title": "1608. Special Array With X Elements Greater Than or Equal X", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Special binary strings are binary strings with the following two properties: You are given a special binary string s . A move consists of choosing two consecutive, non-empty, special substrings of s , and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return the lexicographically largest resulting string possible after applying the mentioned operations on the string .", + "description_images": [], + "constraints": [ + "The number of 0 's is equal to the number of 1 's.", + "Every prefix of the binary string has at least as many 1 's as 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11011000\"\nOutput:\"11100100\"\nExplanation:The strings \"10\" [occuring at s[1]] and \"1100\" [at s[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"\nOutput:\"10\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]=='1' else -1\n if balance==0:\n sublist.append(\"1\" + self.makeLargestSpecial(s[l+1:r])+ \"0\")\n l = r+1\n \n sublist.sort(reverse=True)\n return ''.join(sublist)", + "title": "761. Special Binary String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the number of special positions in mat . A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed ).", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,0],[0,0,1],[1,0,0]]\nOutput:1\nExplanation:(1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/special1.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,0,0],[0,1,0],[0,0,1]]\nOutput:3\nExplanation:(0, 0), (1, 1) and (2, 2) are special positions.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/special-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSpecial(int[][] mat) {\n int count=0;\n for(int i=0;i int:\n def get_column_sum(col_idx):\n return sum(row[col_idx] for row in mat)\n\n special = 0\n for row in mat:\n if sum(row) == 1:\n col_idx = row.index(1)\n special += get_column_sum(col_idx) == 1\n\n return special\n", + "title": "1582. Special Positions in a Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nOutput:[1,2,3,4,8,12,11,10,9,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List spiralOrder(int[][] matrix) {\n List ans = new ArrayList<>();\n int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;\n\n while (top <= bottom && left <= right) \n {\n for (int i = left; i <= right; i++)\n ans.add(matrix[top][i]);\n top++;\n\n for (int i = top; i <= bottom; i++)\n ans.add(matrix[i][right]);\n right--;\n\n if (top <= bottom) {\n for (int i = right; i >= left; i--)\n ans.add(matrix[bottom][i]);\n bottom--;\n }\n\n if (left <= right) {\n for (int i = bottom; i >= top; i--)\n ans.add(matrix[i][left]);\n left++;\n }\n }\n return ans;\n }\n}", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nOutput:[1,2,3,4,8,12,11,10,9,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n col, row = len(matrix[0]), len(matrix)\n l, t, r, b = 0, 0, col - 1, row - 1\n res = []\n while l <= r and t <= b:\n for i in range(l, r):\n res.append(matrix[t][i])\n for i in range(t, b):\n res.append(matrix[i][r])\n \n\t\t\t# Append the orphan left by the open interval\n if t == b:\n res.append(matrix[t][r])\n else:\n # From right to left at the bottom\n for i in range(r, l, -1):\n res.append(matrix[b][i])\n \n\t\t\t# Avoid duplicated appending if it is a square\n if l == r and t != b:\n res.append(matrix[b][r])\n else:\n # From bottom to top at the left\n for i in range(b, t, -1):\n res.append(matrix[i][l])\n l += 1\n t += 1\n r -= 1\n b -= 1\n\n return res\n", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , generate an n x n matrix filled with elements from 1 to n 2 in spiral order.", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[[1,2,3],[8,9,4],[7,6,5]]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 69.11%)\nclass Solution {\n public int[][] generateMatrix(int n) {\n int startingRow = 0;\n int endingRow = n-1;\n int startingCol = 0;\n int endingCol = n-1;\n\n int total = n*n;\n int element = 1;\n int[][] matrix = new int[n][n];\n\n while(element<=total){\n\n for(int i = startingCol; element<=total && i<=endingCol; i++){\n matrix[startingRow][i] = element;\n element++;\n }\n startingRow++;\n\n for(int i = startingRow; element<=total && i<=endingRow; i++){\n matrix[i][endingCol] = element;\n element++;\n }\n endingCol--;\n\n for(int i = endingCol; element<=total && i>=startingCol; i--){\n matrix[endingRow][i] = element;\n element++;\n }\n endingRow--;\n\n for(int i = endingRow; element<=total && i>=startingRow; i--){\n matrix[i][startingCol] = element;\n element++;\n }\n startingCol++;\n\n }\n\n return matrix;\n }\n}", + "title": "59. Spiral Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , generate an n x n matrix filled with elements from 1 to n 2 in spiral order.", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[[1,2,3],[8,9,4],[7,6,5]]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 84.25%) | Memory: 16.50 MB (Top 59.83%)\n\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n if not n:\n return []\n matrix = [[0 for _ in range(n)] for _ in range(n)]\n left, right, top, bottom, num = 0, n-1, 0, n-1, 1\n while left <= right and top <= bottom:\n for i in range(left, right+1):\n matrix[top][i] = num \n num += 1\n top += 1\n for i in range(top, bottom+1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left-1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top-1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n\n", + "title": "59. Spiral Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them .", + "description_images": [], + "constraints": [ + "1 <= rows, cols <= 100", + "0 <= rStart < rows", + "0 <= cStart < cols" + ], + "examples": [ + { + "text": "Example 1: Input:rows = 1, cols = 4, rStart = 0, cStart = 0\nOutput:[[0,0],[0,1],[0,2],[0,3]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_1.png" + }, + { + "text": "Example 2: Input:rows = 5, cols = 6, rStart = 1, cStart = 4\nOutput:[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n ans = [[rStart, cStart]]\n val = 1\n i, j = rStart, cStart\n def is_valid(i, j):\n if 0 <= i < rows and 0 <= j < cols:\n return True\n return False\n \n while True:\n if len(ans) == rows * cols:\n return ans\n \n # go right val times\n for _ in range(val):\n j+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go bottom val times\n for _ in range(val):\n i+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go left val+1 times\n for _ in range(val+1):\n j-=1\n if is_valid(i,j):\n ans.append([i,j])\n # go up val+1 times\n for _ in range(val+1):\n i-=1\n if is_valid(i,j):\n ans.append([i,j])\n val+=2\n", + "title": "885. Spiral Matrix III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput:[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation:The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/09/ex1new.jpg" + }, + { + "text": "Example 2: Input:m = 1, n = 4, head = [0,1,2]\nOutput:[[0,1,2,-1]]\nExplanation:The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/11/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] spiralMatrix(int m, int n, ListNode head) {\n int[][] ans=new int[m][n];\n for(int[] arr:ans){\n Arrays.fill(arr,-1);\n }\n \n int rowBegin=0;\n int rowEnd=m-1;\n int columnBegin=0;\n int columnEnd=n-1;\n ListNode cur=head;\n \n \n while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){\n \n for(int i=columnBegin;i<=columnEnd && cur!=null;i++){\n if(cur!=null){\n ans[rowBegin][i]=cur.val;\n }\n \n cur=cur.next;\n \n \n }\n rowBegin++;\n for(int i=rowBegin;i<=rowEnd && cur!=null;i++){\n if(cur!=null){\n ans[i][columnEnd]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n columnEnd--;\n if(rowBegin<=rowEnd){\n for(int i=columnEnd;i>=columnBegin && cur!=null;i--){\n if(cur!=null){\n ans[rowEnd][i]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n rowEnd--;\n if(columnBegin<=columnEnd){\n for(int i=rowEnd;i>=rowBegin && cur!=null;i--){\n if(cur!=null){\n ans[i][columnBegin]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n columnBegin++;\n \n }\n return ans;\n \n }\n}\n", + "title": "2326. Spiral Matrix IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput:[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation:The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/09/ex1new.jpg" + }, + { + "text": "Example 2: Input:m = 1, n = 4, head = [0,1,2]\nOutput:[[0,1,2,-1]]\nExplanation:The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/11/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2522 ms (Top 39.98%) | Memory: 66.3 MB (Top 18.63%)\nclass Solution:\n def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n num = m * n\n res = [[-1 for j in range(n)] for i in range(m)]\n x, y = 0, 0\n dx, dy = 1, 0\n while head:\n res[y][x] = head.val\n if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m or res[y+dy][x+dx] != -1:\n dx, dy = -dy, dx\n x = x + dx\n y = y + dy\n head = head.next\n return res", + "title": "2326. Spiral Matrix IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s , split it into some number of substrings such that: Return the maximum number of balanced strings you can obtain.", + "description_images": [], + "constraints": [ + "Each substring is balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"RLRRLLRLRL\"\nOutput:4\nExplanation:s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"RLRRRLLRLL\"\nOutput:2\nExplanation:s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2ndand 5thsubstrings are not balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LLLLRRRR\"\nOutput:1\nExplanation:s can be split into \"LLLLRRRR\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int balancedStringSplit(String s) {\n int nl = 0;\n int nr = 0;\n int count = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.substring(i,i+1).equals(\"L\")) ++nl;\n else ++nr;\n if (nr == nl) {\n ++count;\n }\n }\n return count;\n }\n}\n", + "title": "1221. Split a String in Balanced Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s , split it into some number of substrings such that: Return the maximum number of balanced strings you can obtain.", + "description_images": [], + "constraints": [ + "Each substring is balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"RLRRLLRLRL\"\nOutput:4\nExplanation:s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"RLRRRLLRLL\"\nOutput:2\nExplanation:s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2ndand 5thsubstrings are not balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LLLLRRRR\"\nOutput:1\nExplanation:s can be split into \"LLLLRRRR\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n r_count=l_count=t_count=0\n for i in s:\n if i=='R':\n r_count+=1\n elif i=='L':\n l_count+=1\n if r_count==l_count:\n t_count+=1\n r_count=0\n l_count=0\n continue\n return t_count\n", + "title": "1221. Split a String in Balanced Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the maximum number of unique substrings that the given string can be split into . You can split string s into any list of non-empty substrings , where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababccc\"\nOutput:5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:2\nExplanation: One way to split maximally is ['a', 'ba'].", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\"\nOutput:1\nExplanation: It is impossible to split the string any further.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int max = 0;\n public int maxUniqueSplit(String s) {\n int n = s.length();\n backtrack(s, 0, new HashSet());\n return max;\n }\n public void backtrack(String s, int start, Set h) {\n if(start == s.length()) {\n max = Math.max(max, h.size());\n }\n String res = \"\";\n \n for(int i = start;i < s.length();i++) {\n res += s.charAt(i);\n if(h.contains(res)) continue;\n h.add(res);\n backtrack(s, i+1, h);\n h.remove(res);\n }\n }\n}\n", + "title": "1593. Split a String Into the Max Number of Unique Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return the maximum number of unique substrings that the given string can be split into . You can split string s into any list of non-empty substrings , where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababccc\"\nOutput:5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:2\nExplanation: One way to split maximally is ['a', 'ba'].", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\"\nOutput:1\nExplanation: It is impossible to split the string any further.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ans, n = 0, len(s)\n def dfs(i, cnt, visited):\n nonlocal ans, n\n if i == n: ans = max(ans, cnt); return # stop condition\n for j in range(i+1, n+1): \n if s[i:j] in visited: continue # avoid re-visit/duplicates\n visited.add(s[i:j]) # update visited set\n dfs(j, cnt+1, visited) # backtracking\n visited.remove(s[i:j]) # recover visited set for next possibility\n dfs(0, 0, set()) # function call\n return ans\n", + "title": "1593. Split a String Into the Max Number of Unique Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums that is sorted in non-decreasing order . Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Return true if you can split nums according to the above conditions, or false otherwise . A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [ 1 ,2, 3 ,4, 5 ] while [1,3,2] is not).", + "description_images": [], + "constraints": [ + "Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).", + "All subsequences have a length of 3 or more ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,5]\nOutput:true\nExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3,4,4,5,5]\nOutput:true\nExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4,5]\nOutput:false\nExplanation:It is impossible to split nums into consecutive increasing subsequences of length 3 or more.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 12.39%) | Memory: 45.60 MB (Top 38.5%)\n\nclass Solution {\n public boolean isPossible(int[] nums) {\n Map possibility = new HashMap<>();\n Map counts = new HashMap<>();\n for(int num:nums){\n counts.put(num,counts.getOrDefault(num,0)+1);\n }\n for(int num:nums){\n if(counts.get(num)==0)continue;\n if(possibility.getOrDefault(num,0)>0){\n possibility.put(num,possibility.getOrDefault(num,0)-1);\n possibility.put(num+1,possibility.getOrDefault(num+1,0)+1);\n }\n else if( counts.getOrDefault(num+1,0)>0 && counts.getOrDefault(num+2,0)>0 ){\n possibility.put(num+3,possibility.getOrDefault(num+3,0)+1);\n counts.put(num+1,counts.getOrDefault(num+1,0)-1);\n counts.put(num+2,counts.getOrDefault(num+2,0)-1);\n }\n else{\n return false;\n }\n counts.put(num,counts.get(num)-1);\n }\n return true;\n }\n}\n", + "title": "659. Split Array into Consecutive Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums that is sorted in non-decreasing order . Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Return true if you can split nums according to the above conditions, or false otherwise . A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [ 1 ,2, 3 ,4, 5 ] while [1,3,2] is not).", + "description_images": [], + "constraints": [ + "Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).", + "All subsequences have a length of 3 or more ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,5]\nOutput:true\nExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3,4,4,5,5]\nOutput:true\nExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4,5]\nOutput:false\nExplanation:It is impossible to split nums into consecutive increasing subsequences of length 3 or more.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n from collections import defaultdict\n\n def isPossible(self, nums):\n # If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.\n if len(nums) < 3:\n return False\n\n # 'count' dictionary stores the frequency of each number in the input array.\n count = defaultdict(int)\n\n # 'tails' dictionary stores the number of subsequences that end at a certain number.\n tails = defaultdict(int)\n\n # Populate the 'count' dictionary with the frequency of each number.\n for num in nums:\n count[num] += 1\n\n # Iterate through the input array.\n for num in nums:\n # If the count of the current number is 0, it means this number has already been used in a subsequence.\n if count[num] == 0:\n continue\n # If there is a subsequence that ends with the current number minus 1,\n # it means we can extend that subsequence by adding the current number.\n elif tails[num - 1] > 0:\n tails[num - 1] -= 1 # Decrease the count of the tails that end with the current number minus 1.\n tails[num] += 1 # Increase the count of the tails that end with the current number.\n # If there are enough numbers after the current number to form a subsequence,\n # create a new subsequence starting with the current number.\n elif count[num + 1] > 0 and count[num + 2] > 0:\n count[num + 1] -= 1 # Decrease the count of the next number.\n count[num + 2] -= 1 # Decrease the count of the number after the next number.\n tails[num + 2] += 1 # Increase the count of the tails that end with the number after the next number.\n else:\n # If we can't extend an existing subsequence or start a new one, return False.\n return False\n\n # Decrease the count of the current number since it's used in a subsequence.\n count[num] -= 1\n\n # If the function successfully iterates through the entire array, return True.\n return True\n", + "title": "659. Split Array into Consecutive Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string of digits num , such as \"123456579\" . We can split it into a Fibonacci-like sequence [123, 456, 579] . Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num , or return [] if it cannot be done.", + "description_images": [], + "constraints": [ + "0 <= f[i] < 2 31 , (that is, each integer fits in a 32-bit signed integer type),", + "f.length >= 3 , and", + "f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1101111\"\nOutput:[11,0,11,11]\nExplanation:The output [110, 1, 111] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:num = \"112358130\"\nOutput:[]\nExplanation:The task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0123\"\nOutput:[]\nExplanation:Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.83%) | Memory: 41.60 MB (Top 63.04%)\n\nclass Solution {\n List list=new ArrayList<>();\n public List splitIntoFibonacci(String num) {\n \n if(backtrack(num,0)) return list;\n else return new ArrayList();\n \n }\n boolean backtrack(String num,int index){\n if(index==num.length()) return list.size()>2;\n \n int n=0;\n for(int i=index;i= 3 , and", + "f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1101111\"\nOutput:[11,0,11,11]\nExplanation:The output [110, 1, 111] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:num = \"112358130\"\nOutput:[]\nExplanation:The task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0123\"\nOutput:[]\nExplanation:Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "MAX=2**31\ndef consume_tail(current, s):\n # Following the definition of the fibonacci sequence\n # we know that the sum of the last two values in our \n # `current` list determines the next value in the sequence.\n # So that value, our \"target\", is what we're looking for next in\n # `s`.\n target = current[-1] + current[-2]\n \n if target > MAX:\n return False\n \n sTarget = str(target) \n # If the next value in the fibonacci sequence\n # is found at the beginning of s\n # we can continue to process the remaining \n # portion of the string.\n if s.find(sTarget) == 0:\n current.append(target)\n else:\n return False\n \n if sTarget != s:\n return consume_tail(current, s[len(sTarget):])\n \n return current\n \n\nclass Solution: \n def splitIntoFibonacci(self, num: str) -> List[int]:\n \n # Identify candidate for the first\n # number in fibonacci sequence\n for i in range(len(num)):\n if num[0] == \"0\" and i > 0:\n break\n \n first = num[0:i+1]\n \n # If our current candidate for the first number\n # of the sequence is already larger that our \n # maximum value in the spec, don't bother doing anymore work.\n if int(first) > MAX:\n return []\n \n tail = num[i+1:]\n \n # Identify candidate for the scond\n # number in fibonacci sequence\n for j in range(len(tail)):\n if tail[0] == \"0\" and j > 0:\n break\n \n second = tail[0:j+1]\n if int(second) > MAX:\n break\n \n # With our current candidates (first and second),\n # we can consume the remaining portion of the string (tail[j+1:])\n # to determine if it contains the correct values for a fibonacci sequence\n # beginning with [first, second]\n result = consume_tail([int(first), int(second)], tail[j+1:])\n if result:\n return result\n return []\n", + "title": "842. Split Array into Fibonacci Sequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array nums which consists of non-negative integers and an integer m , you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 10^6", + "1 <= m <= min(50, nums.length)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,2,5,10,8], m = 2\nOutput:18\nExplanation:There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8],\nwhere the largest sum among the two subarrays is only 18.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], m = 2\nOutput:9", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,4], m = 3\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] nums;\n public int splitArray(int[] nums, int m) {\n this.nums = nums;\n int low = 0, high = 0, min = Integer.MAX_VALUE;\n for(int i=0;i int:\n lo, hi = max(nums), sum(nums)\n while lo < hi:\n mid = (lo+hi)//2\n tot, cnt = 0, 1\n for num in nums:\n if tot+num<=mid: \n tot += num\n else:\n tot = num\n cnt += 1\n if cnt>m: lo = mid+1\n else: hi = mid\n return hi\n", + "title": "410. Split Array Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B) . Return true if it is possible to achieve that and false otherwise. Note that for an array arr , average(arr) is the sum of all the elements of arr over the length of arr .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 30", + "0 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7,8]\nOutput:true\nExplanation:We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean splitArraySameAverage(int[] nums) {\n int n = nums.length, sum = Arrays.stream(nums).sum();\n Set[] a = new HashSet[n/2+1];\n Set[] b = new HashSet[n/2+2];\n Arrays.setAll(a, o -> new HashSet<>());\n Arrays.setAll(b, o -> new HashSet<>());\n gen(0, n/2, 0, 0, nums, a);\n gen(n/2, n, 0, 0, nums, b);\n for (int i = 0; i < a.length; i++){ // i = num of elements selected from A\n for (int j = 0; j < b.length; j++){ // j = num of elements selected from B\n if (i+j>0 && i+j < n && sum*(i+j)%n == 0){\n for (int cur : a[i]){ // do Two Sum\n if (b[j].contains(sum*(i+j)/n-cur)){\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n \n private void gen(int cur, int n, int bits, int sum, int[] nums, Set[] set){\n set[bits].add(sum);\n if (cur < n){\n gen(cur+1, n, bits+1, sum+nums[cur], nums, set);\n gen(cur+1, n, bits, sum, nums, set);\n }\n }\n}\n", + "title": "805. Split Array With Same Average", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B) . Return true if it is possible to achieve that and false otherwise. Note that for an array arr , average(arr) is the sum of all the elements of arr over the length of arr .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 30", + "0 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7,8]\nOutput:true\nExplanation:We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def splitArraySameAverage(self, A: List[int]) -> bool:\n A.sort()\n DP=[set() for _ in range(len(A)//2+1)] #DP[i] stores the all available sum with i items in a bracket\n all_sum=sum(A)\n DP[0]=set([0])\n for item in A: #iterate over items in the list\n for count in range(len(DP)-2,-1,-1): # iterate backwards w.r.t. the bracket size\n if len(DP[count])>0: # if DP[i] is not empty, then update DP[i+1] by adding the current item into all sums in DP[i]\n for a in DP[count]:\n DP[count+1].add(a+item)\n for size in range(1,len(DP)):\n if all_sum*size/len(A) in DP[size]:\n return True\n return False", + "title": "805. Split Array With Same Average", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5\nOutput:[[1],[2],[3],[],[]]\nExplanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput:[[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 69.17%) | Memory: 43.9 MB (Top 66.95%)\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n ListNode[] arr=new ListNode[k];\n\n if(k<2 || head==null || head.next==null){\n arr[0]=head;\n return arr;\n }\n\n ListNode temp=head;\n int len=1;\n while(temp.next!=null){\n len++;\n temp=temp.next;\n }\n\n int partition= len/k; //no of part 3\n int extra=len%k; //extra node 1 0\n\n ListNode curr=head;\n ListNode prev=null;\n int index=0;\n while(head!=null){\n arr[index++]=curr;\n for(int i=0; i0){\n prev=curr;\n curr=curr.next;\n extra--;\n }\n head=curr;\n prev.next=null;\n\n }\n return arr;\n }\n}", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5\nOutput:[[1],[2],[3],[],[]]\nExplanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput:[[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 81.38%) | Memory: 14.5 MB (Top 12.03%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n length = 0\n cur = head\n while cur:\n length += 1\n cur = cur.next\n # DON'T do following since this makes head become null\n # while head:\n # length += 1\n # head = head.next\n\n # calculate the base size and the number of parts contain extra number\n size, extra = length // k, length % k\n\n # create empty list to store split parts\n res = [[] for _ in range(k)]\n\n # use two ptrs to split parts\n prev, cur = None, head\n\n for i in range(k):\n res[i] = cur\n # if this part contains extra number, it has (size+1) number\n for j in range(size + (1 if extra > 0 else 0)):\n prev, cur = cur, cur.next\n if prev: prev.next = None\n extra -= 1\n\n return res", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index , splitting a into two strings: a prefix and a suffix where a = a prefix + a suffix , and splitting b into two strings: b prefix and b suffix where b = b prefix + b suffix . Check if a prefix + b suffix or b prefix + a suffix forms a palindrome. When you split a string s into s prefix and s suffix , either s suffix or s prefix is allowed to be empty. For example, if s = \"abc\" , then \"\" + \"abc\" , \"a\" + \"bc\" , \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false . Notice that x + y denotes the concatenation of strings x and y .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^5", + "a.length == b.length", + "a and b consist of lowercase English letters" + ], + "examples": [ + { + "text": "Example 1: Input:a = \"x\", b = \"y\"\nOutput:trueExplaination:If either a or b are palindromes the answer is true since you can split in the following way:\naprefix= \"\", asuffix= \"x\"\nbprefix= \"\", bsuffix= \"y\"\nThen, aprefix+ bsuffix= \"\" + \"y\" = \"y\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:a = \"xbdef\", b = \"xecab\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:a = \"ulacfd\", b = \"jizalu\"\nOutput:trueExplaination:Split them at index 3:\naprefix= \"ula\", asuffix= \"cfd\"\nbprefix= \"jiz\", bsuffix= \"alu\"\nThen, aprefix+ bsuffix= \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 100.0%) | Memory: 45.60 MB (Top 14.69%)\n\nclass Solution {\n public boolean checkPalindromeFormation(String a, String b) {\n // either way of split should give us a palindrome\n return cut(a, b) || cut(b, a);\n }\n\n // method to match letters from both ends\n private boolean cut(String a, String b) {\n int i = 0, j = a.length() - 1;\n // converge from both ends till we have same letters\n while (i < j && a.charAt(i) == b.charAt(j)) {\n i++; j--;\n }\n\n // the case when we surpassed the mid point from both ends\n if (i >= j) return true;\n // the case when there is still a substring left in between\n // or say we didn't reach the mid point\n // we will check if that substring is a palindrome or not\n return isPalindrome(a, i, j) || isPalindrome(b, i, j);\n }\n\n // method to check if a string is palindrome\n private boolean isPalindrome(String s, int i, int j) {\n while (i < j) {\n if (s.charAt(i++) != s.charAt(j--)) {\n return false;\n }\n }\n\n return true;\n }\n}\n", + "title": "1616. Split Two Strings to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index , splitting a into two strings: a prefix and a suffix where a = a prefix + a suffix , and splitting b into two strings: b prefix and b suffix where b = b prefix + b suffix . Check if a prefix + b suffix or b prefix + a suffix forms a palindrome. When you split a string s into s prefix and s suffix , either s suffix or s prefix is allowed to be empty. For example, if s = \"abc\" , then \"\" + \"abc\" , \"a\" + \"bc\" , \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false . Notice that x + y denotes the concatenation of strings x and y .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^5", + "a.length == b.length", + "a and b consist of lowercase English letters" + ], + "examples": [ + { + "text": "Example 1: Input:a = \"x\", b = \"y\"\nOutput:trueExplaination:If either a or b are palindromes the answer is true since you can split in the following way:\naprefix= \"\", asuffix= \"x\"\nbprefix= \"\", bsuffix= \"y\"\nThen, aprefix+ bsuffix= \"\" + \"y\" = \"y\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:a = \"xbdef\", b = \"xecab\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:a = \"ulacfd\", b = \"jizalu\"\nOutput:trueExplaination:Split them at index 3:\naprefix= \"ula\", asuffix= \"cfd\"\nbprefix= \"jiz\", bsuffix= \"alu\"\nThen, aprefix+ bsuffix= \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 271 ms (Top 15.83%) | Memory: 15.4 MB (Top 41.73%)\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n def pal(x):\n return x == x[::-1]\n if pal(a) or pal(b): return True\n # either grow from inside to outside, or vice versa\n ina = len(a)-1\n inb = 0\n outa = 0\n outb = len(b)-1\n\n while a[ina] == b[inb]:\n ina -= 1\n inb += 1\n if ina <= inb:\n return True # short circuit found break point\n # jump into each string now!?\n # is a or b a palindrome in this portion from inb to ina\n if pal(a[inb:ina+1]) or pal(b[inb:ina+1]):\n return True # either one is breakpoint, so check remainder is palindrome\n\n while a[outa] == b[outb]:\n outa += 1\n outb -= 1\n if outa >= outb:\n return True\n if pal(a[outa:outb+1]) or pal(b[outa:outb+1]):\n return True # either one is breakpoint, so check remainder\n\n return False", + "title": "1616. Split Two Strings to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1 . Return true if it is possible to split s ​​​​​​ as described above , or false otherwise. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89] . The values are in descending order and adjacent values differ by 1 , so this way is valid.", + "Another example, the string s = \"001\" can be split into [\"0\", \"01\"] , [\"00\", \"1\"] , or [\"0\", \"0\", \"1\"] . However all the ways are invalid because they have numerical values [0,1] , [0,1] , and [0,0,1] respectively, all of which are not in descending order." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1234\"\nOutput:false\nExplanation:There is no valid way to split s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"050043\"\nOutput:true\nExplanation:s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"9080701\"\nOutput:false\nExplanation:There is no valid way to split s.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean splitString(String s) {\n return isRemainingValid(s, null);\n }\n private boolean isRemainingValid(String s, Long previous) {\n long current =0;\n for(int i=0;i= 10000000000L) return false; // Avoid overflow\n if(previous == null) {\n if (isRemainingValid(s.substring(i+1), current)) \n return true;\n } else if(current == previous - 1 && (i==s.length()-1 || isRemainingValid(s.substring(i+1), current)))\n return true;\n }\n return false;\n }\n}\n", + "title": "1849. Splitting a String Into Descending Consecutive Values", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1 . Return true if it is possible to split s ​​​​​​ as described above , or false otherwise. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "For example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89] . The values are in descending order and adjacent values differ by 1 , so this way is valid.", + "Another example, the string s = \"001\" can be split into [\"0\", \"01\"] , [\"00\", \"1\"] , or [\"0\", \"0\", \"1\"] . However all the ways are invalid because they have numerical values [0,1] , [0,1] , and [0,0,1] respectively, all of which are not in descending order." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1234\"\nOutput:false\nExplanation:There is no valid way to split s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"050043\"\nOutput:true\nExplanation:s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"9080701\"\nOutput:false\nExplanation:There is no valid way to split s.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 66 ms (Top 24.00%) | Memory: 13.8 MB (Top 70.18%)\nclass Solution:\n def splitString(self, s: str, last_val: int = None) -> bool:\n # Base case, remaining string is a valid solution\n if last_val and int(s) == last_val - 1:\n return True\n\n # Iterate through increasingly larger slices of s\n for i in range(1, len(s)):\n cur = int(s[:i])\n # If current slice is equal to last_val - 1, make\n # recursive call with remaining string and updated last_val\n if last_val is None or cur == last_val - 1:\n if self.splitString(s[i:], cur):\n return True\n\n return False", + "title": "1849. Splitting a String Into Descending Consecutive Values", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-negative integer x , compute and return the square root of x . Since the return type is an integer, the decimal digits are truncated , and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5 .", + "description_images": [], + "constraints": [ + "0 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 4\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:x = 8\nOutput:2\nExplanation:The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 10.30%) | Memory: 41.3 MB (Top 62.51%)\n\nclass Solution {\n public int mySqrt(int x) {\n long answer = 0;\n while (answer * answer <= x) {\n answer += 1;\n }\n return (int)answer - 1;\n }\n}", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a non-negative integer x , compute and return the square root of x . Since the return type is an integer, the decimal digits are truncated , and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5 .", + "description_images": [], + "constraints": [ + "0 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 4\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:x = 8\nOutput:2\nExplanation:The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mySqrt(self, x: int) -> int:\n beg =0\n end =x\n while beg <=end:\n mid = (beg+end)//2\n sqr = mid*mid\n if sqr == x:\n return mid\n elif sqr < x:\n beg = mid+1\n else:\n end = mid-1\n return end\n \n", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-4,-1,0,3,10]\nOutput:[0,1,9,16,100]\nExplanation:After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-7,-3,2,3,11]\nOutput:[4,9,9,49,121]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 87.02%) | Memory: 54.8 MB (Top 82.69%)\nclass Solution {\n public int[] sortedSquares(int[] nums) {\n int s=0;\n int e=nums.length-1;\n int p=nums.length-1;\n int[] a=new int[nums.length];\n while(s<=e){\n if(nums[s]*nums[s]>nums[e]*nums[e]){\n a[p--]=nums[s]*nums[s];\n s++;\n }\n else{\n a[p--]=nums[e]*nums[e];\n e--;\n }\n }\n return a;\n }\n}", + "title": "977. Squares of a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-4,-1,0,3,10]\nOutput:[0,1,9,16,100]\nExplanation:After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-7,-3,2,3,11]\nOutput:[4,9,9,49,121]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n l,r = 0, len(nums)-1\n pointer = 0\n arr = [0] *len(nums)\n pointer = r\n while l<=r:\n if abs(nums[r]) > abs(nums[l]):\n arr[pointer] = nums[r] **2\n r-=1\n pointer-=1\n else:\n arr[pointer] = nums[l] **2\n l+=1\n pointer-=1\n \n \n return arr\n \n \n \n", + "title": "977. Squares of a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth . We want to fit the stamps such that they follow the given restrictions and requirements : Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false .", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[r].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 2 * 10^5", + "grid[r][c] is either 0 or 1 .", + "1 <= stampHeight, stampWidth <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3\nOutput:true\nExplanation:We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/ex1.png" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2\nOutput:false\nExplanation:There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]:\n ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))]\n \n for row in range(len(grid)):\n for col in range(1, len(grid[0])):\n ps[row][col] = ps[row][col-1] + grid[row][col]\n \n for row in range(1, len(grid)):\n for col in range(len(grid[0])):\n ps[row][col] = ps[row-1][col] + ps[row][col]\n \n return ps\n\t\t\t\n def sumRegion(self, ps, row1: int, col1: int, row2: int, col2: int) -> int:\n ans = 0\n if row1 == 0 and col1 == 0:\n ans = ps[row2][col2]\n elif row1 == 0:\n ans = ps[row2][col2] - ps[row2][col1-1]\n elif col1 == 0:\n ans = ps[row2][col2] - ps[row1-1][col2]\n else:\n ans = ps[row2][col2] - ps[row1-1][col2] - ps[row2][col1-1] + ps[row1-1][col1-1]\n return ans\n\n def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:\n diff = [[0 for col in range(len(grid[0])+1)]for row in range(len(grid)+1)]\n \n ps = self.prefix_sum(grid)\n cover = 0\n \n for row in range(len(grid)-(stampHeight-1)):\n for col in range(len(grid[0])-(stampWidth-1)):\n sub_sum = self.sumRegion(ps, row, col, row+stampHeight-1, col+stampWidth-1)\n if sub_sum == 0:\n diff[row][col] += 1\n diff[row][col+stampWidth] -= 1\n diff[row+stampHeight][col] -= 1\n diff[row+stampHeight][col+stampWidth] = 1\n pref_diff = self.prefix_sum(diff)\n m, n = len(grid), len(grid[0])\n \n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 0 and pref_diff[row][col] == 0: return False \n \n return True\n", + "title": "2132. Stamping the Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings stamp and target . Initially, there is a string s of length target.length with all s[i] == '?' . In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp . We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn . If we cannot obtain target from s within 10 * target.length turns, return an empty array.", + "description_images": [], + "constraints": [ + "For example, if stamp = \"abc\" and target = \"abcba\" , then s is \"?????\" initially. In one turn you can: place stamp at index 0 of s to obtain \"abc??\" , place stamp at index 1 of s to obtain \"?abc?\" , or place stamp at index 2 of s to obtain \"??abc\" . Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s ).", + "place stamp at index 0 of s to obtain \"abc??\" ,", + "place stamp at index 1 of s to obtain \"?abc?\" , or", + "place stamp at index 2 of s to obtain \"??abc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:stamp = \"abc\", target = \"ababc\"\nOutput:[0,2]\nExplanation:Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.", + "image": null + }, + { + "text": "Example 2: Input:stamp = \"abca\", target = \"aabcaca\"\nOutput:[3,0,1]\nExplanation:Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] movesToStamp(String stamp, String target) {\n \n /*\n * Intitution:\n * Instead of creating target string from intial state,\n * create the intial state from the target string.\n * - take a window of stamp length\n * - reverse that window to the intail state \n * current state -> abcdefgh, window = def, \n * next state -> abc???gh \n *\n */\n \n int sLen = stamp.length();\n int tLen = target.length();\n \n //it save the index of reversed charcacter\n Queue reversedCharIndices= new LinkedList();\n \n //it mark Character of target, as reversed\n boolean[] isReversedCharOfThisIndex = new boolean[tLen];\n \n Stack stack = new Stack();\n \n List widowList = new ArrayList();\n \n for(int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++){\n \n Set matched = new HashSet();\n Set notMatched = new HashSet();\n \n for(int j = 0; j < sLen; j++){\n \n //char index of current window of the target\n int charIndex = windowStartIndex + j;\n \n if(stamp.charAt(j) == target.charAt(charIndex)){\n matched.add(charIndex);\n } else {\n notMatched.add(charIndex);\n }\n }\n \n //add the window\n widowList.add(new Window(matched, notMatched));\n \n //when all char of current window is matched with \n if(notMatched.isEmpty()){\n stack.push(windowStartIndex);\n \n for(int index : matched){\n if(!isReversedCharOfThisIndex[index]){\n \n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n \n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n \n }\n }\n \n \n \n //get all char index, one by once\n //see the impact of reverse char of this index, in ano\n while(!reversedCharIndices.isEmpty()){\n int reversedCharIndex = reversedCharIndices.remove();\n \n int start = Math.max(0, reversedCharIndex - sLen + 1);\n int end = Math.min(reversedCharIndex, tLen - sLen);\n \n for(int windowIndex = start; windowIndex <= end; windowIndex++){\n \n if(widowList.get(windowIndex).notMatched.contains(reversedCharIndex)){\n \n \n //as this char is reversed in another window\n //remove this char index from current window, \n widowList.get(windowIndex).notMatched.remove(reversedCharIndex);\n \n if(widowList.get(windowIndex).notMatched.isEmpty()){\n \n //as all of charcater reversed of current window\n //now add current window index\n stack.push(windowIndex);\n \n for(int index : widowList.get(windowIndex).matched){\n \n if(!isReversedCharOfThisIndex[index]){\n\n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n\n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n }\n }\n \n }\n }\n \n \n for(boolean reversed : isReversedCharOfThisIndex){\n if(!reversed){\n return new int[0];\n }\n }\n \n int i = 0;\n int[] result = new int[stack.size()];\n while(!stack.empty()){\n result[i++] = stack.pop();\n }\n \n \n return result;\n \n }\n}\n\nclass Window {\n Set matched;\n Set notMatched;\n \n public Window(Set matched, Set notMatched){\n this.matched = matched;\n this.notMatched = notMatched;\n }\n}\n", + "title": "936. Stamping The Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings stamp and target . Initially, there is a string s of length target.length with all s[i] == '?' . In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp . We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn . If we cannot obtain target from s within 10 * target.length turns, return an empty array.", + "description_images": [], + "constraints": [ + "For example, if stamp = \"abc\" and target = \"abcba\" , then s is \"?????\" initially. In one turn you can: place stamp at index 0 of s to obtain \"abc??\" , place stamp at index 1 of s to obtain \"?abc?\" , or place stamp at index 2 of s to obtain \"??abc\" . Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s ).", + "place stamp at index 0 of s to obtain \"abc??\" ,", + "place stamp at index 1 of s to obtain \"?abc?\" , or", + "place stamp at index 2 of s to obtain \"??abc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:stamp = \"abc\", target = \"ababc\"\nOutput:[0,2]\nExplanation:Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.", + "image": null + }, + { + "text": "Example 2: Input:stamp = \"abca\", target = \"aabcaca\"\nOutput:[3,0,1]\nExplanation:Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def movesToStamp(self, S: str, T: str) -> List[int]:\n if S == T: return [0]\n S, T = list(S), list(T)\n slen, tlen = len(S), len(T) - len(S) + 1\n ans, tdiff, sdiff = [], True, True\n while tdiff:\n tdiff = False\n for i in range(tlen):\n sdiff = False\n for j in range(slen):\n if T[i+j] == \"*\": continue\n if T[i+j] != S[j]: break\n sdiff = True\n else: \n if sdiff:\n tdiff = True\n for j in range(i, i + slen): T[j] = \"*\"\n ans.append(i)\n for i in range(len(T)):\n if T[i] != \"*\": return []\n return reversed(ans)\n", + "title": "936. Stamping The Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a large sample of integers in the range [0, 255] . Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample. Calculate the following statistics: Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode] . Answers within 10 -5 of the actual answer will be accepted.", + "description_images": [], + "constraints": [ + "minimum : The minimum element in the sample.", + "maximum : The maximum element in the sample.", + "mean : The average of the sample, calculated as the total sum of all elements divided by the total number of elements.", + "median : If the sample has an odd number of elements, then the median is the middle element once the sample is sorted. If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.", + "If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.", + "If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.", + "mode : The number that appears the most in the sample. It is guaranteed to be unique ." + ], + "examples": [ + { + "text": "Example 1: Input:count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput:[1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation:The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.", + "image": null + }, + { + "text": "Example 2: Input:count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput:[1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation:The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double[] sampleStats(int[] count) {\n double[]ans=new double[5];\n ans[0]=-1;\n ans[1]=-1;\n int place=0;\n while(ans[0]==-1){\n if(count[place]>0)\n ans[0]=place;\n place++;\n }\n place=count.length-1;\n while(ans[1]==-1){\n if(count[place]>0)\n ans[1]=place;\n place--;\n }\n int countEl=count[0];\n int max=count[0];\n for(int i=1;imax){\n max=count[i];\n ans[4]=i;\n }\n }\n for(int i=0;i0){\n double tmp=count[i];\n tmp/=countEl;\n ans[2]+=tmp*i;\n }\n }\n place=0;\n int whereToStop=0;\n while(whereToStopmodev:modev,mode=n,i\n acc,cnt=acc+n*i,cnt+n\n \n midCnt,cc,midv,prei=cnt//2,0,0,i\n for i,n in enumerate(count):\n if n==0:continue\n if cc+n<=midCnt:\n cc,prei=cc+n,i\n continue\n if cnt%2==1:midv=i\n else:midv=(prei+i)/2.0 if cc==midCnt else i\n break\n return (minv,maxv,acc/cnt,midv,mode) \n", + "title": "1093. Statistics from a Large Sample", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n . You are also given an integer startValue representing the value of the start node s , and a different integer destValue representing the value of the destination node t . Find the shortest path starting from node s and ending at node t . Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L' , 'R' , and 'U' . Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t .", + "description_images": [], + "constraints": [ + "'L' means to go from a node to its left child node.", + "'R' means to go from a node to its right child node.", + "'U' means to go from a node to its parent node." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput:\"UURL\"\nExplanation:The shortest path is: 3 → 1 → 5 → 2 → 6.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg1.png" + }, + { + "text": "Example 2: Input:root = [2,1], startValue = 2, destValue = 1\nOutput:\"L\"\nExplanation:The shortest path is: 2 → 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) {\n if(currNode == null) return false;\n if(currNode.val == destVal) return true;\n if(DFS(currNode.left, path, destVal)) path.append(\"L\");\n else if(DFS(currNode.right, path, destVal)) path.append(\"R\");\n return path.length() > 0;\n }\n \n public String getDirections(TreeNode root, int startValue, int destValue) {\n StringBuilder startToRoot = new StringBuilder();\n StringBuilder endToRoot = new StringBuilder();\n \n DFS(root, startToRoot, startValue);\n DFS(root, endToRoot, destValue);\n \n int i = startToRoot.length(), j = endToRoot.length();\n int cnt = 0;\n while(i > 0 && j > 0 && startToRoot.charAt(i-1) == endToRoot.charAt(j-1)) {\n cnt++; i--; j--;\n }\n \n String sPath = \"U\".repeat(startToRoot.length() - cnt);\n String ePath = endToRoot.reverse().toString().substring(cnt, endToRoot.length());\n \n return sPath + ePath;\n }\n}\n", + "title": "2096. Step-By-Step Directions From a Binary Tree Node to Another", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n . You are also given an integer startValue representing the value of the start node s , and a different integer destValue representing the value of the destination node t . Find the shortest path starting from node s and ending at node t . Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L' , 'R' , and 'U' . Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t .", + "description_images": [], + "constraints": [ + "'L' means to go from a node to its left child node.", + "'R' means to go from a node to its right child node.", + "'U' means to go from a node to its parent node." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput:\"UURL\"\nExplanation:The shortest path is: 3 → 1 → 5 → 2 → 6.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg1.png" + }, + { + "text": "Example 2: Input:root = [2,1], startValue = 2, destValue = 1\nOutput:\"L\"\nExplanation:The shortest path is: 2 → 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n def find(n: TreeNode, val: int, path: List[str]) -> bool:\n if n.val == val:\n return True\n if n.left and find(n.left, val, path):\n path += \"L\"\n elif n.right and find(n.right, val, path):\n path += \"R\"\n return path\n s, d = [], []\n find(root, startValue, s)\n find(root, destValue, d)\n while len(s) and len(d) and s[-1] == d[-1]:\n s.pop()\n d.pop()\n return \"\".join(\"U\" * len(s)) + \"\".join(reversed(d))\n", + "title": "2096. Step-By-Step Directions From a Binary Tree Node to Another", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length . Return the number of steps performed until nums becomes a non-decreasing array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,4,4,7,3,6,11,8,5,11]\nOutput:3\nExplanation:The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,7,7,13]\nOutput:0\nExplanation:nums is already a non-decreasing array. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n \n public int totalSteps(int[] nums) {\n \n int n = nums.length;\n int ans = 0;\n \n Stack> st = new Stack();\n \n st.push(new Pair(nums[n-1],0));\n \n \n for(int i=n-2;i>=0;i--)\n {\n int count = 0;\n \n while(!st.isEmpty() && nums[i] > st.peek().getKey())\n {\n count = Math.max(count+1 , st.peek().getValue() );\n st.pop();\n }\n \n ans = Math.max(ans , count);\n st.push(new Pair(nums[i],count));\n }\n \n return ans;\n \n }\n}\n", + "title": "2289. Steps to Make Array Non-decreasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length . Return the number of steps performed until nums becomes a non-decreasing array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,4,4,7,3,6,11,8,5,11]\nOutput:3\nExplanation:The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,7,7,13]\nOutput:0\nExplanation:nums is already a non-decreasing array. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalSteps(self, nums: List[int]) -> int:\n st = []\n ans = 0\n for i in nums:\n t = 0\n while st and st[-1][0] <= i:\n t = max(t, st.pop()[1])\n x = 0 \n if st: \n x = t+1 \n st.append([i, x])\n ans = max(ans, x)\n return ans\n", + "title": "2289. Steps to Make Array Non-decreasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given n different types of stickers . Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target . If the task is impossible, return -1 . Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.", + "description_images": [], + "constraints": [ + "n == stickers.length", + "1 <= n <= 50", + "1 <= stickers[i].length <= 10", + "1 <= target.length <= 15", + "stickers[i] and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput:3\nExplanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.", + "image": null + }, + { + "text": "Example 2: Input:stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput:-1\n\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap>map;\n public int minStickers(String[] stickers, String target) {\n map = new HashMap<>();\n for(String sticker:stickers){\n HashMap temp = new HashMap<>();\n for(char ch:sticker.toCharArray())\n temp.put(ch,temp.getOrDefault(ch,0)+1);\n map.put(sticker,temp);\n }\n int count = memoization(target,new HashMap<>());\n return count<1||count>=Integer.MAX_VALUE?-1:count;\n }\n public int memoization(String target, HashMapdpmap){\n if(target.length()==0)return 0;\n if(dpmap.containsKey(target)) return dpmap.get(target);\n int count = Integer.MAX_VALUE;\n for(String str: map.keySet()){\n HashMap xd = new HashMap(map.get(str));\n String temp = target;\n char ch = temp.charAt(0);\n if(xd.containsKey(ch)){\n for(int i =0;i0){\n xd.put(ch,xd.get(ch)-1);\n temp = temp.substring(0,i)+temp.substring(i+1);\n i--;\n }\n }\n if(temp.length()!=target.length()){\n count = Math.min(count,1+memoization(temp,dpmap));\n dpmap.put(target,count); \n }\n }\n }\n return count;\n }\n}\n", + "title": "691. Stickers to Spell Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We are given n different types of stickers . Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target . If the task is impossible, return -1 . Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.", + "description_images": [], + "constraints": [ + "n == stickers.length", + "1 <= n <= 50", + "1 <= stickers[i].length <= 10", + "1 <= target.length <= 15", + "stickers[i] and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput:3\nExplanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.", + "image": null + }, + { + "text": "Example 2: Input:stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput:-1\n\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nfrom collections import Counter\nclass Solution(object):\n def minStickers(self, stickers, target):\n counter = [Counter(sticker) for sticker in stickers] \n n = len(counter)\n @lru_cache(None)\n def dfs(target):\n if not target: return 0\n targ_counter = Counter(target)\n res = float('inf')\n #using sticker[i] if it contains the first letter of target\n for i in range(n):\n if counter[i][target[0]] == 0:\n continue\n s = ''\n for j in 'abcdefghijklmnopqrstuvwxyz':\n s += j*max(targ_counter[j] - counter[i][j], 0) \n res = min(res, 1 + dfs(s)) if dfs(s) != -1 else res\n return -1 if res == float('inf') else res\n return dfs(target)", + "title": "691. Stickers to Spell Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Implement the StockPrice class:", + "description_images": [], + "constraints": [ + "Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.", + "Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.", + "Finds the maximum price the stock has been based on the current records.", + "Finds the minimum price the stock has been based on the current records." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]Output[null, null, null, 5, 10, null, 5, null, 2]ExplanationStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class StockRecord {\n int timestamp;\n int price;\n \n public StockRecord(){}\n \n public StockRecord(int t, int p) {\n timestamp = t;\n price = p;\n }\n}\n\nclass StockPrice {\n \n PriorityQueue max = new PriorityQueue<>((sr1, sr2) -> (sr2.price - sr1.price));\n PriorityQueue min = new PriorityQueue<>((sr1, sr2) -> (sr1.price - sr2.price));\n StockRecord current_record;\n Map map = new HashMap<>();\n\n \n public StockPrice() {\n current_record = new StockRecord();\n }\n \n public void update(int timestamp, int price) {\n if(timestamp >= current_record.timestamp) {\n current_record.timestamp = timestamp;\n current_record.price = price;\n }\n \n StockRecord sr = new StockRecord(timestamp, price);\n max.add(sr);\n min.add(sr);\n map.put(timestamp, price);\n }\n \n public int current() {\n return current_record.price;\n }\n \n public int maximum() {\n StockRecord sp = max.peek();\n while(true) {\n sp = max.peek();\n if(sp.price != map.get(sp.timestamp))\n max.poll();\n else break;\n }\n return sp.price;\n }\n \n public int minimum() {\n StockRecord sp = min.peek();\n while(true) {\n sp = min.peek();\n if(sp.price != map.get(sp.timestamp))\n min.poll();\n else break;\n }\n return sp.price;\n }\n}\n", + "title": "2034. Stock Price Fluctuation", + "topic": "Algorithms" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Implement the StockPrice class:", + "description_images": [], + "constraints": [ + "Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.", + "Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.", + "Finds the maximum price the stock has been based on the current records.", + "Finds the minimum price the stock has been based on the current records." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]Output[null, null, null, 5, 10, null, 5, null, 2]ExplanationStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class StockPrice:\n\n def __init__(self):\n self.timestamps = {}\n self.highestTimestamp = 0\n self.minHeap = []\n self.maxHeap = []\n\n def update(self, timestamp: int, price: int) -> None:\n\t #Keep track of current prices\n self.timestamps[timestamp] = price\n self.highestTimestamp = max(self.highestTimestamp, timestamp)\n \n\t\t#For maximum/minimum\n heappush(self.minHeap, (price, timestamp))\n heappush(self.maxHeap, (-price, timestamp))\n\n def current(self) -> int:\n\t #Just return the highest timestamp in O(1)\n return self.timestamps[self.highestTimestamp]\n\n def maximum(self) -> int:\n currPrice, timestamp = heappop(self.maxHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n while -currPrice != self.timestamps[timestamp]:\n currPrice, timestamp = heappop(self.maxHeap)\n \n heappush(self.maxHeap, (currPrice, timestamp))\n return -currPrice\n\n def minimum(self) -> int:\n currPrice, timestamp = heappop(self.minHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n while currPrice != self.timestamps[timestamp]:\n currPrice, timestamp = heappop(self.minHeap)\n \n heappush(self.minHeap, (currPrice, timestamp))\n return currPrice\n", + "title": "2034. Stock Price Fluctuation", + "topic": "Algorithms" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i] . The objective of the game is to end with the most stones. The total number of stones across all the piles is odd , so there are no ties. Alice and Bob take turns, with Alice starting first . Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins . Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins .", + "description_images": [], + "constraints": [ + "2 <= piles.length <= 500", + "piles.length is even .", + "1 <= piles[i] <= 500", + "sum(piles[i]) is odd ." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,3,4,5]\nOutput:true\nExplanation:Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:piles = [3,7,2,3]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n //This is the Easy One..\n //The main Thing is We(Alice) have to take win\n \n //alice going to check the even sum and the odd sum if even sum> odd sum alice start with 0 else start with n-1.\n public boolean stoneGame(int[] piles) {\n return true;\n }\n}\n", + "title": "877. Stone Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i] . The objective of the game is to end with the most stones. The total number of stones across all the piles is odd , so there are no ties. Alice and Bob take turns, with Alice starting first . Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins . Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins .", + "description_images": [], + "constraints": [ + "2 <= piles.length <= 500", + "piles.length is even .", + "1 <= piles[i] <= 500", + "sum(piles[i]) is odd ." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,3,4,5]\nOutput:true\nExplanation:Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:piles = [3,7,2,3]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n", + "title": "877. Stone Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row , and each pile has a positive integer number of stones piles[i] .  The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first.  Initially, M = 1 . On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M .  Then, we set M = max(M, X) . The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 100", + "1 <= piles[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [2,7,9,4,4]\nOutput:10\nExplanation:If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.", + "image": null + }, + { + "text": "Example 2: Input:piles = [1,2,3,4,5,100]\nOutput:104", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 884 ms (Top 5.06%) | Memory: 117.5 MB (Top 5.06%)\nclass Solution {\n public int stoneGameII(int[] piles) {\n Map memo = new HashMap<>();\n int diff = stoneGame(piles,1,0,0,memo);\n int totalSum = 0;\n for(int ele: piles)\n totalSum+=ele;\n return (diff+totalSum)/2;\n }\n\n public int stoneGame(int[] piles, int M, int index, int turn,Map memo )\n {\n if(index >= piles.length)\n return 0;\n if(memo.containsKey(index+\"-\"+M+\"-\"+turn))\n return memo.get(index+\"-\"+M+\"-\"+turn);\n int score=0,maxScore=Integer.MIN_VALUE;\n // Alice's turn\n if(turn == 0)\n {\n for(int X=1;X<=2*M && index+X-1 int:\n n = len(piles)\n dp = {} \n def recursion(index,M):\n # if we reached to the end we cannot score any value\n if index == n:\n return 0\n # we search if we have solved the same case earlier\n if (index,M) in dp:\n return dp[(index,M)] \n # total remaining score is the sum of array from index to the end\n total = sum(piles[index:]) \n # if we can take the complete array it is the best choice\n if index + 2*M >= n :return total\n # my_score is the score we are getting as the player who is playing\n my_score = 0\n for x in range(index,index+2*M):\n # opponent score will be calculated by next recursion\n opponent_score = recursion(x+1,max(M,x-index+1))\n # my_score is the remaining value of total - opponent_score\n my_score = max(my_score,total - opponent_score) \n # this is memoization part\n dp[(index,M)] = my_score\n # return the score\n return my_score\n \n return recursion(0,1)\n", + "title": "1140. Stone Game II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1 , 2 , or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally . Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score .", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 5 * 10^4", + "-1000 <= stoneValue[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3,7]\nOutput:\"Bob\"\nExplanation:Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2,3,-9]\nOutput:\"Alice\"\nExplanation:Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.", + "image": null + }, + { + "text": "Example 3: Input:values = [1,2,3,6]\nOutput:\"Tie\"\nExplanation:Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tInteger[] dp;\n\n\tpublic String stoneGameIII(int[] stoneValue) {\n\t\tdp = new Integer[stoneValue.length + 1];\n\t\n\t\t\tArrays.fill(dp, null);\n\t\t\n\t\tint ans = stoneGameIII(0, stoneValue);\n\t\tif (ans == 0)\n\t\t\treturn \"Tie\";\n\t\telse if (ans > 0)\n\t\t\treturn \"Alice\";\n\t\telse\n\t\t\treturn \"Bob\";\n\t}\n\n\tpublic int stoneGameIII(int l, int[] s) {\n\t\tif (l >= s.length)\n\t\t\treturn 0;\n\t\tif (dp[l] != null)\n\t\t\treturn dp[l];\n\t\tint ans;\n\t\t\tans = Integer.MIN_VALUE;\n\t\t\tif (l < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] - stoneGameIII(l + 1, s));\n\t\t\t}\n\t\t\tif (l + 1 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] -stoneGameIII(l + 2, s));\n\t\t\t}\n\t\t\tif (l + 2 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] +s[l + 2] -stoneGameIII(l + 3, s));\n\t\t\t}\n\t\t \n\t\treturn dp[l] = ans;\n\t}\n}\n", + "title": "1406. Stone Game III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1 , 2 , or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally . Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score .", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 5 * 10^4", + "-1000 <= stoneValue[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3,7]\nOutput:\"Bob\"\nExplanation:Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2,3,-9]\nOutput:\"Alice\"\nExplanation:Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.", + "image": null + }, + { + "text": "Example 3: Input:values = [1,2,3,6]\nOutput:\"Tie\"\nExplanation:Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def stoneGameIII(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: str\n \"\"\"\n n = len(stoneValue)\n suffixSum = [0 for _ in range(n+1)]\n dp = [0 for _ in range(n+1)]\n for i in range(n-1, -1, -1):\n suffixSum[i] = suffixSum[i+1] + stoneValue[i]\n for i in range(n-1, -1, -1):\n dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1]\n for k in range(i+1, min(n, i+3)):\n dp[i] = max(dp[i], suffixSum[i] - dp[k+1])\n if dp[0]*2 == suffixSum[0]:\n return \"Tie\"\n elif dp[0]*2 > suffixSum[0]:\n return \"Alice\"\n else:\n return \"Bob\"\n", + "title": "1406. Stone Game III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n , return true if and only if Alice wins the game otherwise return false , assuming both players play optimally.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:true\nExplanation:Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:false\nExplanation:Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:true\nExplanation:n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1188 ms (Top 5.04%) | Memory: 258.9 MB (Top 5.04%)\nclass Solution {\n // idea: Alice wins a game with n stones if and only if there exists\n // some perfect square p <= n such that Alice wins a game with\n // n - p stones... i.e., Bob DOES NOT win a game with n - p stones\n public boolean winnerSquareGame(int n) {\n // this bit would be better with just an array of booleans, but this\n // is how i thought of it at the time, so leaving it this way...\n // maybe it will be \"more explicit\" and help someone better understand dp?\n HashMap memo = new HashMap<>();\n memo.put(1, true); // if there is one stone in the pile to begin the game, the next player to go wins\n memo.put(0, false); // if there are zero stones in the pile to begin the game, the next player to go loses\n List perfectSquares = new ArrayList<>();\n int i = 1;\n while (i * i <= n) {\n perfectSquares.add(i * i);\n i++;\n }\n // if there are some perfect square number of stones in the pile to begin the game, the next player to go wins\n perfectSquares.forEach(p -> memo.put(p, true));\n // Alice goes first...\n return this.playerWins(n, perfectSquares, memo);\n }\n\n private boolean playerWins(int n, List P, HashMap m) {\n if (m.containsKey(n)) { return m.get(n); } // if we already computed the answer for n, just return it\n m.put(n, false); // otherwise, assume it's false to begin...\n for (Integer p : P) { // check every perfect square p...\n if (p <= n && !playerWins(n - p, P, m)) {\n // if p <= n AND the player who goes next (e.g., Bob) does not win a game that begins with\n // n - p stones, then we know that the player whose turn it is right now (e.g., Alice) wins\n // a game that begins with n stones, so record this discovery in the memo and then break out\n // of the loop because there's no more work to do...\n m.put(n, true);\n break;\n } // else p >= n OR taking p stones would not result in a win for the player whose turn it is right now...\n }\n // we put false in before the loop; if we never found a reason to change it to true,\n // then false is the correct result...\n return m.get(n);\n }\n\n}", + "title": "1510. Stone Game IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n , return true if and only if Alice wins the game otherwise return false , assuming both players play optimally.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:true\nExplanation:Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:false\nExplanation:Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "image": null + }, + { + "text": "Example 3: Input:n = 4\nOutput:true\nExplanation:n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 189 ms (Top 93.6%) | Memory: 21.09 MB (Top 49.0%)\n\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n \n @cache\n def can_win(n: int) -> bool:\n return n and not all(can_win(n - s) for s in squares(n))\n \n return can_win(n)\n\n", + "title": "1510. Stone Game IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones , where stones[i] is the value of the i th stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones . The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3 . Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally , return true if Alice wins and false if Bob wins .", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 10^5", + "1 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,1]\nOutput:true\nExplanation:The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [2]\nOutput:false\nExplanation:Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.", + "image": null + }, + { + "text": "Example 3: Input:stones = [5,1,2,4,3]\nOutput:false\nExplanation:Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean stoneGameIX(int[] stones) {\n Map div3 = new HashMap<>();\n div3.put(0, 0);\n div3.put(1, 0);\n div3.put(2, 0);\n \n for(int stone : stones){\n div3.put(stone%3, div3.get(stone%3)+1);\n }\n\t\t// the count of 3's don't matter, only whether it is even or odd\n div3.put(0, div3.get(0)%2);\n \n \n if(div3.get(1) == 0 && div3.get(2) == 0){\n return false;\n }\n \n int smaller = Math.min(div3.get(1), div3.get(2));\n int larger = Math.max(div3.get(2), div3.get(1));\n\t\t// the combinations of 1's and 2's will work with each other in a complementary way. \n\t\t// A pair of 1 and 2 makes modulo 3 to be 0\n\t\t// Three counts of 1 or 2 makes modulo 3 to be 0\n\t\t// so, we need only relative counts\n \n // if there are even 3's, then bob can't reverse alice's win\n // so, if all three digits chosen are the same then bob wins, but if there is another option then alice wins\n // [1,2,2,2] -> alice picks 1 and wins\n // [1,3,3,2] -> alice picks 1 or two and wins\n // [2,2,2] -> alice has to pick the third 2 and loses\n\n if(div3.get(0) == 0){\n return smaller != 0;\n }\n \n // all cases now have odd number of 3's, so result can be reversed\n \n // [1,1,1,1,3] -> 1,1,3,1 picked or 1,3,1,1 picked means alice wins\n // similar for 2 because the other number doesn't exist to make a %3 pair\n \n // if the difference of number counts is more than 2 then alice can always force bob\n // [3,1,2,2,2] -> \n\t\t// [3,1,2,2,2,2] ->\n if(larger > smaller + 2){\n return true;\n }\n \n return false;\n }\n}\n", + "title": "2029. Stone Game IX", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones , where stones[i] is the value of the i th stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones . The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3 . Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally , return true if Alice wins and false if Bob wins .", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 10^5", + "1 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,1]\nOutput:true\nExplanation:The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [2]\nOutput:false\nExplanation:Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.", + "image": null + }, + { + "text": "Example 3: Input:stones = [5,1,2,4,3]\nOutput:false\nExplanation:Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2982 ms (Top 22.53%) | Memory: 27.5 MB (Top 95.77%)\nclass Solution:\n def stoneGameIX(self, stones: List[int]) -> bool:\n u, d, t = 0, 0, 0\n for stone in stones:\n if stone % 3 == 1:\n u += 1\n elif stone % 3 == 2:\n d += 1\n else:\n t += 1\n if not u and d <= 2 or u <= 2 and not d: #situation 1 part 2\n return False\n if not u and d > 2 or u > 2 and not d: #situation 1 part 1\n if not t % 2:\n return False\n else:\n return True\n if u == d or abs(u - d) <= 2: #situation 2 and situation 3\n if t % 2:\n return False\n else:\n return True\n return True #default situation", + "title": "2029. Stone Game IX", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining . Alice's is initially zero . Return the maximum score that Alice can obtain .", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 500", + "1 <= stoneValue[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:stoneValue = [6,2,3,4,5,5]\nOutput:18\nExplanation:In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.", + "image": null + }, + { + "text": "Example 2: Input:stoneValue = [7,7,7,7,7,7,7]\nOutput:28", + "image": null + }, + { + "text": "Example 3: Input:stoneValue = [4]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 299 ms (Top 83.10%) | Memory: 42.5 MB (Top 97.18%)\nclass Solution {\n int dp[][];\n public int fnc(int a[], int i, int j, int sum){\n //System.out.println(i+\" \"+j);\n int n=a.length;\n if(i>j)\n return 0;\n if(j>n)\n return 0;\n if(i==j){\n dp[i][j]=-1;\n return 0;\n }\n if(dp[i][j]!=0)\n return dp[i][j];\n\n int temp=0;\n int ans=Integer.MIN_VALUE;\n\n for(int index=i;index<=j;index++){\n temp+=a[index];\n if(temp>sum-temp){\n ans=Math.max(ans,((sum-temp)+fnc(a,index+1,j,sum-temp)));\n }\n else if(temp int:\n n = len(stoneValue)\n dp = [[0]*n for _ in range(n)]\n left = [[0]*n for _ in range(n)]\n prefix = list(accumulate(stoneValue))\n prefix = [0]+prefix+[prefix[-1]]\n\n def sum(i,j):\n return prefix[j+1]-prefix[i]\n\n row_idx = [i for i in range(n)]\n for i in range(n):\n left[i][i] = stoneValue[i]\n for d in range(1,n):\n for i in range(n-d):\n j = i+d\n while sum(i,row_idx[i]) < sum(row_idx[i]+1,j):\n row_idx[i] +=1\n if sum(i, row_idx[i]) == sum(row_idx[i]+1,j):\n dp[i][j] = max(left[i][row_idx[i]], left[j][row_idx[i]+1])\n else:\n if row_idx[i] == i:\n dp[i][j] = left[j][i+1]\n elif row_idx[i] == j:\n dp[i][j] = left[i][j-1]\n else:\n dp[i][j] = max(left[i][row_idx[i]-1], left[j][row_idx[i]+1])\n left[j][i] = max(left[j][i+1],sum(i,j)+dp[i][j])\n left[i][j] = max(left[i][j-1],sum(i,j)+dp[i][j])\n return dp[0][n-1]", + "title": "1563. Stone Game V", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently . You are given two integer arrays of length n , aliceValues and bobValues . Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the i th stone. The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally . Both players know the other's values. Determine the result of the game, and:", + "description_images": [], + "constraints": [ + "If Alice wins, return 1 .", + "If Bob wins, return -1 .", + "If the game results in a draw, return 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:aliceValues = [1,3], bobValues = [2,1]\nOutput:1\nExplanation:If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.", + "image": null + }, + { + "text": "Example 2: Input:aliceValues = [1,2], bobValues = [3,1]\nOutput:0\nExplanation:If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.", + "image": null + }, + { + "text": "Example 3: Input:aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput:-1\nExplanation:Regardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\nstatic class Pair\n{\n int sum=0;\n int alice=0;\n int bob=0;\n public Pair(int sum,int alice, int bob)\n{\n this.sum=sum;\n\tthis.alice = alice;\n\tthis.bob = bob;\n}\n}\n\n// class to define user defined conparator\nstatic class Compare {\n\t\n\tstatic void compare(Pair arr[], int n)\n\t{\n\t\t// Comparator to sort the pair according to second element\n\t\tArrays.sort(arr, new Comparator() {\n\t\t\t@Override public int compare(Pair p1, Pair p2)\n\t\t\t{\n\t\t\t\treturn p2.sum - p1.sum;\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t}\n}\n public int stoneGameVI(int[] aliceValues, int[] bobValues)\n {\n int n=aliceValues.length;\n Pair[] a=new Pair[n];\n for(int i=0;i0 else ( -1 if d<0 else 0 )", + "title": "1686. Stone Game VI", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference . Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the i th stone from the left , return the difference in Alice and Bob's score if they both play optimally .", + "description_images": [], + "constraints": [ + "n == stones.length", + "2 <= n <= 1000", + "1 <= stones[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [5,3,1,4,2]\nOutput:6\nExplanation:- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6.", + "image": null + }, + { + "text": "Example 2: Input:stones = [7,90,5,1,100,10,10,2]\nOutput:122", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6869 ms (Top 56.16%) | Memory: 13.9 MB (Top 96.15%)\nclass Solution:\n def stoneGameVII(self, S: List[int]) -> int:\n N, dp = len(S), [0] * len(S)\n for i in range(N - 2, -1, -1):\n total = S[i]\n for j in range(i + 1, N):\n total += S[j]\n dp[j] = max(total - S[i] - dp[j], total - S[j] - dp[j-1])\n return dp[-1]", + "title": "1690. Stone Game VII", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . There are n stones arranged in a row. On each player's turn, while the number of stones is more than one , they will do the following: The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score) . Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the i th stone from the left , return the score difference between Alice and Bob if they both play optimally .", + "description_images": [], + "constraints": [ + "n == stones.length", + "2 <= n <= 10^5", + "-10^4 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [-1,2,-3,4,-5]\nOutput:5\nExplanation:- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\n value 2 on the left. stones = [2,-5].\n- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\n the left. stones = [-3].\nThe difference between their scores is 2 - (-3) = 5.", + "image": null + }, + { + "text": "Example 2: Input:stones = [7,-6,5,10,5,-2,-6]\nOutput:13\nExplanation:- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\n stone of value 13 on the left. stones = [13].\nThe difference between their scores is 13 - 0 = 13.", + "image": null + }, + { + "text": "Example 3: Input:stones = [-10,-12]\nOutput:-22\nExplanation:- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\n score and places a stone of value -22 on the left. stones = [-22].\nThe difference between their scores is (-22) - 0 = -22.", + "image": null + } + ], + "follow_up": null, + "solution": "# OJ: https://leetcode.com/problems/stone-game-viii/\n# Author: github.com/lzl124631x\nclass Solution:\n def stoneGameVIII(self, A: List[int]) -> int:\n return reduce(lambda memo, cur : max(memo, cur - memo), list(accumulate(A))[::-1][:-1])\n", + "title": "1872. Stone Game VIII", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a strange printer with the following two special properties: Given a string s , return the minimum number of turns the printer needed to print it .", + "description_images": [], + "constraints": [ + "The printer can only print a sequence of the same character each time.", + "At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"\nOutput:2\nExplanation:Print \"aaa\" first and then print \"bbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:2\nExplanation:Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic int strangePrinter(String s) {\n if (s.equals(\"\")) return 0;\n int len = s.length();\n int[][] dp = new int[len][len];\n for (int i = 0; i < len; i++)\n dp[i][i] = 1;\n for (int l = 2; l <= len; l++) {\n for (int i = 0; i < len && l + i - 1 < len; i++) {\n int j = l + i - 1;\n dp[i][j] = dp[i][j - 1] + (s.charAt(i) == s.charAt(j) ? 0 : 1);\n for (int k = i + 1; k < j; k++) {\n if (s.charAt(k) == s.charAt(j)) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k][j - 1]);\n }\n }\n }\n }\n return dp[0][len - 1];\n}\n}", + "title": "664. Strange Printer", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a strange printer with the following two special properties: Given a string s , return the minimum number of turns the printer needed to print it .", + "description_images": [], + "constraints": [ + "The printer can only print a sequence of the same character each time.", + "At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"\nOutput:2\nExplanation:Print \"aaa\" first and then print \"bbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"\nOutput:2\nExplanation:Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 878 ms (Top 47.91%) | Memory: 16.1 MB (Top 47.44%)\nclass Solution(object):\n def strangePrinter(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # remove duplicate letters from s.\n tmp = []\n for c in s:\n if len(tmp) == 0 or tmp[-1] != c:\n tmp.append(c)\n s = \"\".join(tmp)\n\n _m = {}\n def _dp(i, j, background):\n if j < i:\n return 0\n elif i == j:\n return 1 if background != s[i] else 0\n elif (i, j, background) in _m:\n return _m[(i, j, background)]\n\n ans = len(s)\n\n # shrink s[i:j+1] to s[i_:j_+1] according to the background letter\n i_ = i + 1 if s[i] == background else i\n j_ = j - 1 if s[j] == background else j\n\n if s[i_] == s[j_]:\n # case \"AxxxA\" => best strategy is printing A first\n ans = _dp(i_ + 1, j_ - 1, s[i_]) + 1\n else:\n # otherwise, print first letter, try every possible print length\n for p in range(i_, j_ + 1):\n # searching is needed only if s[p] == s[i_]\n # e.g. s=\"ABCDEA\"print 'A' on s[0:1] is equivalent to s[0:5]\n if s[p] != s[i_]:\n continue\n l = _dp(i_, p, s[i_])\n r = _dp(p + 1, j_, background)\n ans = min(ans, l + r + 1)\n _m[(i, j, background)] = ans\n return ans\n\n return _dp(0, len(s) - 1, '')", + "title": "664. Strange Printer", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a strange printer with the following two special requirements: You are given a m x n matrix targetGrid , where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid , otherwise, return false .", + "description_images": [], + "constraints": [ + "On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.", + "Once the printer has used a color for the above operation, the same color cannot be used again ." + ], + "examples": [ + { + "text": "Example 1: Input:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print1.jpg" + }, + { + "text": "Example 2: Input:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print2.jpg" + }, + { + "text": "Example 3: Input:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\nOutput:false\nExplanation:It is impossible to form targetGrid because it is not allowed to print the same color in different turns.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 41.74%) | Memory: 54.3 MB (Top 53.04%)\nclass Solution {\n // store each color's left, top, right, bottom\n private Set[] graph;\n private int[] indegrees;\n private int[][] ranges;\n private boolean[] exists;\n private int m;\n private int n;\n private int maxColor = 60;\n public boolean isPrintable(int[][] targetGrid) {\n this.m = targetGrid.length;\n this.n = targetGrid[0].length;\n buildRanges(targetGrid);\n buildGraph(targetGrid);\n int count = 0;\n int totalCount = 0;\n Queue queue = new LinkedList<>();\n for (int i = 1; i <= maxColor; i++) {\n if (exists[i]) {\n if (indegrees[i] == 0) {\n queue.offer(i);\n }\n totalCount++;\n }\n }\n while (!queue.isEmpty()) {\n count++;\n Integer current = queue.poll();\n for (Integer neighbor: graph[current]) {\n if (--indegrees[neighbor] == 0) {\n queue.offer(neighbor);\n }\n }\n }\n return count == totalCount;\n }\n private void buildRanges(int[][] targetGrid) {\n this.ranges = new int[maxColor + 1][4];\n for (int i = 1; i <= maxColor; i++) {\n ranges[i][0] = ranges[i][1] = Integer.MAX_VALUE;\n ranges[i][2] = ranges[i][3] = Integer.MIN_VALUE;\n }\n exists = new boolean[maxColor + 1];\n int max = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int color = targetGrid[i][j];\n exists[color] = true;\n max = Math.max(max, color);\n ranges[color][0] = Math.min(ranges[color][0], j);\n ranges[color][1] = Math.min(ranges[color][1], i);\n ranges[color][2] = Math.max(ranges[color][2], j);\n ranges[color][3] = Math.max(ranges[color][3], i);\n }\n }\n maxColor = max;\n }\n // TC O(n^3) to build graph\n private void buildGraph(int[][] targetGrid) {\n graph = new Set[maxColor + 1];\n indegrees = new int[maxColor + 1];\n for (int c = 1; c <= maxColor; c++) {\n if (exists[c]) {\n graph[c] = new HashSet<>();\n for (int i = ranges[c][1]; i <= ranges[c][3]; i++) {\n for (int j = ranges[c][0]; j <= ranges[c][2]; j++) {\n int other = targetGrid[i][j];\n if (other != c && !graph[c].contains(other)) {\n graph[c].add(other);\n indegrees[other]++;\n }\n }\n }\n }\n }\n }\n}", + "title": "1591. Strange Printer II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a strange printer with the following two special requirements: You are given a m x n matrix targetGrid , where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid , otherwise, return false .", + "description_images": [], + "constraints": [ + "On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.", + "Once the printer has used a color for the above operation, the same color cannot be used again ." + ], + "examples": [ + { + "text": "Example 1: Input:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print1.jpg" + }, + { + "text": "Example 2: Input:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print2.jpg" + }, + { + "text": "Example 3: Input:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\nOutput:false\nExplanation:It is impossible to form targetGrid because it is not allowed to print the same color in different turns.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 514 ms (Top 80.64%) | Memory: 14.5 MB (Top 44.35%)\nfrom graphlib import TopologicalSorter, CycleError\n\nColor = int\nCorner = Tuple[int, int]\nRect = Tuple[Corner, Corner] # [upper-left, lower-right (non-inclusive)]\nLayer = Tuple[Color, Rect]\n\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n # Runtime is the summation of several steps but is dominated by the second step\n # O(M*N + C*C*M*N + (O(C*C) + O(M*N)) + M*N) -> O(C*C*M*N)\n def compare(a:Layer, b:Layer) -> int:\n \"\"\"\n Determine if two rectangles overlap.\n\n Return:\n -1 if b is over a\n 0 if there is no overlap or an order cannot be determined (the overlap contains no elements of a or b)\n 1 if a is over b\n \"\"\"\n val_a, (a_ul, a_lr) = a\n val_b, (b_ul, b_lr) = b\n\n # Get overlap rectangle\n ul, lr = (\n (max(a_ul[0], b_ul[0]), max(a_ul[1], b_ul[1])),\n (min(a_lr[0], b_lr[0]), min(a_lr[1], b_lr[1])),\n )\n\n # If either dimension is non-positive, there is no overlap\n if lr[0] - ul[0] <= 0 or lr[1] - ul[1] <= 0:\n return 0\n\n # Find the first element matching a or b in the overlap rectangle.\n # We'll consider that the \"over\" value.\n for r in range(ul[0], lr[0]):\n for c in range(ul[1], lr[1]):\n if targetGrid[r][c] == val_b:\n return -1\n elif targetGrid[r][c] == val_a:\n return 1\n # We could find no values from a or b in the overlap.\n # The result is indeterminate.\n return 0\n\n # Generate the enclosing rectangles for each visible color (ie. layers).\n # O(M*N)\n rects:Dict[Color, Rect] = defaultdict(lambda: ([100, 100], [0, 0]))\n for r, row in enumerate(targetGrid):\n for c, val in enumerate(row):\n ul, lr = rects[val]\n rects[val] = (\n (min(ul[0], r), min(ul[1], c)),\n (max(lr[0], r + 1), max(lr[1], c + 1))\n )\n\n # Compare every pair of layers.\n # If overlap is detected, record that the \"upper\" rectangle depends on the \"lower\" one.\n # O(C*C*M*N) # Number of colors\n layers:List[Layer] = list(rects.items())\n graph:Dict[Layer, Set[Layer]] = {layer: set() for layer in layers}\n for i, a in enumerate(layers):\n for b in layers[i + 1 :]:\n if (cmp := compare(a, b)) < 0:\n graph[b].add(a)\n elif cmp > 0:\n graph[a].add(b)\n\n # Use topological sort on the graph to reproduce the printing order (in the absence\n # of cycles) and print our own grid.\n # O(C*C) + O(M*N) // O(C*C) is derived from topological sort O(V+E)\n try:\n grid = [[0] * len(targetGrid[0]) for _ in targetGrid]\n for color, (ul, lr) in TopologicalSorter(graph).static_order():\n for r in range(ul[0], lr[0]):\n for c in range(ul[1], lr[1]):\n grid[r][c] = color\n except CycleError:\n return False\n\n # Compare the grids\n # O(M*N)\n return grid == targetGrid", + "title": "1591. Strange Printer II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words . For example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a' , 'x' , 'y' , and 'z' , your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words . Implement the StreamChecker class:", + "description_images": [], + "constraints": [ + "StreamChecker(String[] words) Initializes the object with the strings array words .", + "boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]Output[null, false, false, false, true, false, true, false, false, false, false, false, true]ExplanationStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist", + "image": null + } + ], + "follow_up": null, + "solution": "class StreamChecker {\n \n class TrieNode {\n boolean isWord;\n TrieNode[] next = new TrieNode[26];\n }\n \n TrieNode root = new TrieNode();\n StringBuilder sb = new StringBuilder();\n \n public StreamChecker(String[] words) {\n createTrie(words);\n }\n \n public boolean query(char letter){\n sb.append(letter);\n TrieNode node = root;\n for(int i=sb.length()-1; i>=0 && node!=null; i--){\n char ch = sb.charAt(i);\n node = node.next[ch - 'a'];\n if(node != null && node.isWord){\n return true;\n }\n }\n return false;\n }\n \n private void createTrie(String words[]){\n for(String s : words){\n TrieNode node = root;\n int len = s.length();\n for(int i = len-1; i>=0; i--){\n char ch = s.charAt(i);\n if(node.next[ch-'a'] == null){\n node.next[ch - 'a'] = new TrieNode();\n }\n node = node.next[ch - 'a'];\n }\n node.isWord = true;\n }\n }\n}\n", + "title": "1032. Stream of Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words . For example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a' , 'x' , 'y' , and 'z' , your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words . Implement the StreamChecker class:", + "description_images": [], + "constraints": [ + "StreamChecker(String[] words) Initializes the object with the strings array words .", + "boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]Output[null, false, false, false, true, false, true, false, false, false, false, false, true]ExplanationStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode:\n \n def __init__(self):\n self.children = {}\n self.endOfWord = False\n\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n self.root = TrieNode()\n self.qCur = self.root\n self.stream = collections.deque()\n cur = self.root\n for word in words:\n for i in range(len(word) - 1, -1, -1):\n ch = word[i]\n if ch not in cur.children:\n cur.children[ch] = TrieNode()\n cur = cur.children[ch]\n cur.endOfWord = True\n cur = self.root\n\n def query(self, letter: str) -> bool:\n self.stream.appendleft(letter)\n cur = self.root\n for ch in self.stream:\n if ch not in cur.children:\n return False\n else:\n cur = cur.children[ch]\n if cur.endOfWord:\n return True\n return False\n", + "title": "1032. Stream of Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space.", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]\nOutput:Return 1, and the first character of the input array should be: [\"a\"]\nExplanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compress(char[] chars) {\n int index = 0;\n int i = 0;\n\n while (i < chars.length) {\n int j = i;\n\n while (j < chars.length && chars[j] == chars[i]) {\n j++;\n }\n\n chars[index++] = chars[i];\n\n if (j - i > 1) {\n String count = j - i + \"\";\n\n for (char c : count.toCharArray()) {\n chars[index++] = c;\n }\n }\n\n i = j;\n }\n\n return index;\n }\n}\n\n// TC: O(n), SC: O(1)", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space.", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]\nOutput:Return 1, and the first character of the input array should be: [\"a\"]\nExplanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def compress(self, chars: List[str]) -> int:\n stri = ''\n stack = [chars.pop(0)]\n \n while chars:\n p = chars.pop(0)\n \n if p in stack:\n stack.append(p)\n else:\n stri = stri + stack[-1] + str(len(stack) if len(stack) > 1 else '')\n stack = [p] \n \n o = list(stri + stack[-1] + str(len(stack) if len(stack) > 1 else ''))\n \n for i in o:\n chars.append(i)\n", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\" . Thus the compressed string becomes \"a2bc3\" . Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k . You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "0 <= k <= s.length", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabcccd\", k = 2\nOutput:4\nExplanation:Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaa\", k = 2\nOutput:2\nExplanation:If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaaaaaaaaaa\", k = 0\nOutput:3\nExplanation:Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\t public int getLengthOfOptimalCompression(String s, int k) {\n Map memo = new HashMap<>();\n return recur(s, '\\u0000', 0, k, 0, memo);\n }\n\n private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map memo) {\n\n if (index == s.length()) {\n return 0;\n }\n String key = prevChar + \", \" + prevCharCount + \", \" + k + \", \" + index;\n Integer keyVal = memo.get(key);\n\n if (keyVal != null) {\n return keyVal;\n }\n char ch = s.charAt(index);\n int count = 1;\n int nextIndex = index + 1;\n\n for (int i = index + 1; i < s.length(); i++) {\n\n if (s.charAt(i) == ch) {\n count++;\n nextIndex = i + 1;\n } else {\n nextIndex = i;\n break;\n }\n }\n int totalCount = count;\n int prevCountRepresentation = 0;\n //if prev char is equal to current char that means we have removed middle element\n //So we have to subtract the previous representation length and add the new encoding\n //representation length\n if (ch == prevChar) {\n totalCount += prevCharCount;\n prevCountRepresentation = getLength(prevCharCount);\n }\n\n int representaionLength = getLength(totalCount);\n int ans = representaionLength + recur(s, ch, totalCount, k, nextIndex, memo) - prevCountRepresentation;\n\n if (k > 0) {\n\n for (int i = 1; i <= k && i <= count; i++) {\n int currentCount = totalCount - i;\n int length = getLength(currentCount);\n //checking if we have to send current char and current char count or previous char\n //and previous char count\n int holder = length + recur(s, currentCount == 0 ? prevChar : ch,\n currentCount == 0 ? prevCharCount : currentCount, k - i, nextIndex, memo) -\n prevCountRepresentation;\n ans = Math.min(ans, holder);\n }\n }\n memo.put(key, ans);\n return ans;\n }\n //Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc.\n private int getLength(int n) {\n\n if (n == 0) {\n return 0;\n } else if (n == 1) {\n return 1;\n } else if (n < 10) {\n return 2;\n } else if (n < 100) {\n return 3;\n } else {\n return 4;\n }\n }\n}\n", + "title": "1531. String Compression II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\" . Thus the compressed string becomes \"a2bc3\" . Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k . You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "0 <= k <= s.length", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabcccd\", k = 2\nOutput:4\nExplanation:Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaa\", k = 2\nOutput:2\nExplanation:If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaaaaaaaaaa\", k = 0\nOutput:3\nExplanation:Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1997 ms (Top 68.37%) | Memory: 360.00 MB (Top 27.55%)\n\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n # We define f(i, curr_run_ch, run_length, nb_dels_remain) to return \n # the minimum, additional, number of characters it will cost to run-length \n # compress the substring s[i..n-1].\n # `curr_run_ch` is the character we have in the current \"run\", or the same\n # contiguous block of characters. \n # `run_length` is the length of the current \"run\", or the length of the\n # contiguous block of identical characters.\n\t\t# e.g. if we just encoded \"aaaaa\", `curr_run_ch` is \"a\" and `run_length` = 5\n # `nb_dels_remain` is the number of delete operations we have available to us,\n # should we choose to use them\n memo = {}\n def f(i, curr_run_ch, run_length, nb_dels_remain):\n if i == len(s):\n return 0\n \n key = (i, curr_run_ch, run_length, nb_dels_remain)\n if key in memo:\n return memo[key]\n \n # At character i, we have two possible options, we could choose to either\n # delete this character or keep this character. Each choice we make will\n # incurr some additional run-length encoding length for s[i..n-1]. We return\n # the minimum of the two.\n \n # Delete s[i]\n del_ch_cost = float('inf')\n if nb_dels_remain > 0:\n # Deleting s[i] means the latest character we kept stays the same AND\n # the current run-length of characters stays the same as well\n del_ch_cost = f(i + 1, curr_run_ch, run_length, nb_dels_remain - 1)\n \n # Keep s[i]\n keep_ch_cost = 0\n if s[i] == curr_run_ch:\n\t\t\t # The new character at s[i] we are about to encode is the same as the character in the\n\t\t\t\t# current \"run\", we could choose to include it into the current run of course.\n # Be careful that if we started with run-length of 1, 9, 99, 999 and etc, encoding another\n # character same as `curr_run_ch` into the same \"run\" will require an extra digit.\n # e.g. 'a' => '2a' '9a' => '10a', '99a' => '100a'\n extra_digit_cost = 0\n if run_length == 1 or len(str(run_length + 1)) > len(str(run_length)):\n extra_digit_cost = 1\n keep_ch_cost = extra_digit_cost + f(i + 1, curr_run_ch, run_length + 1, nb_dels_remain)\n else:\n # s[i] != curr_run_ch, we are going to need to run-length encode at least\n # one instance of s[i] which would cost 1, plus whatever the cost to encode\n # the rest. Of course that also means the current \"run\" will \"reset\" and start anew with\n\t\t\t\t# a single character s[i]\n keep_ch_cost = 1 + f(i + 1, s[i], 1, nb_dels_remain)\n \n memo[key] = min(keep_ch_cost, del_ch_cost)\n return memo[key]\n \n return f(0, '', 0, k)\n", + "title": "1531. String Compression II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of string words . Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j] , if can be obtained removing some characters to left and/or right side of words[j] .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 30", + "words[i] contains only lowercase English letters.", + "It's guaranteed that words[i] will be unique." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput:[\"as\",\"hero\"]\nExplanation:\"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"et\",\"code\"]\nOutput:[\"et\",\"code\"]\nExplanation:\"et\", \"code\" are substring of \"leetcode\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"blue\",\"green\",\"bu\"]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List stringMatching(String[] words) {\n Listans = new ArrayList<>();\n for(int i=0; i= 0){\n ans.add(s);\n break;\n }\n }\n }\n return ans;\n }\n}\n", + "title": "1408. String Matching in an Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of string words . Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j] , if can be obtained removing some characters to left and/or right side of words[j] .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 30", + "words[i] contains only lowercase English letters.", + "It's guaranteed that words[i] will be unique." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput:[\"as\",\"hero\"]\nExplanation:\"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"et\",\"code\"]\nOutput:[\"et\",\"code\"]\nExplanation:\"et\", \"code\" are substring of \"leetcode\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"blue\",\"green\",\"bu\"]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def stringMatching(self, words: List[str]) -> List[str]:\n ans=set()\n l=len(words)\n for i in range(l):\n for j in range(l):\n if (words[i] in words[j]) & (i!=j):\n ans.add(words[i])\n return ans\n", + "title": "1408. String Matching in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note:", + "description_images": [], + "constraints": [ + "Only the space character ' ' is considered a whitespace character.", + "Do not ignore any characters other than the leading whitespace or the rest of the string after the digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"42\"\nOutput:42\nExplanation:The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231- 1], the final result is 42.", + "image": null + }, + { + "text": "Example 2: Input:s = \" -42\"\nOutput:-42\nExplanation:Step 1: \"-42\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-42\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -42\" (\"42\" is read in)\n ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231- 1], the final result is -42.", + "image": null + }, + { + "text": "Example 3: Input:s = \"4193 with words\"\nOutput:4193\nExplanation:Step 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"4193with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231- 1], the final result is 4193.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int myAtoi(String s) {\n long n=0;\n int i=0,a=0;\n s=s.trim();\n if(s.length()==0)\n return 0;\n if(s.charAt(i)=='+' || s.charAt(i)=='-')\n a=1;\n while(a='0' && s.charAt(i)<='9')\n n=n*10+(int)(s.charAt(i)-'0');\n else\n break;\n }\n if(s.charAt(0)=='-')\n n=-n;\n if(n>2147483647)\n n=2147483647;\n if(n<-2147483648)\n n=-2147483648;\n return (int)n;\n }\n}\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note:", + "description_images": [], + "constraints": [ + "Only the space character ' ' is considered a whitespace character.", + "Do not ignore any characters other than the leading whitespace or the rest of the string after the digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"42\"\nOutput:42\nExplanation:The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231- 1], the final result is 42.", + "image": null + }, + { + "text": "Example 2: Input:s = \" -42\"\nOutput:-42\nExplanation:Step 1: \"-42\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-42\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -42\" (\"42\" is read in)\n ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231- 1], the final result is -42.", + "image": null + }, + { + "text": "Example 3: Input:s = \"4193 with words\"\nOutput:4193\nExplanation:Step 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"4193with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231- 1], the final result is 4193.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 69 ms (Top 20.00%) | Memory: 13.9 MB (Top 79.88%)\n\nclass Solution:\n\n def assign_sign(self, sign):\n # verify that we haven't already got a sign\n # \"+42-\" -> we don't want to return -42; hence check\n if not self.is_neg and not self.is_pos:\n # no sign has been set yet\n if sign==\"+\":\n self.is_pos = True\n elif sign==\"-\":\n self.is_neg = True\n return\n\n def add_to_int(self, num):\n if not self.num:\n self.num = num\n else:\n self.num = (self.num*10) + num\n\n def myAtoi(self, s: str) -> int:\n # remove the leading and trailing spaces\n self.is_neg = False\n self.is_pos = False\n self.num = None\n s=s.strip()\n for i in s:\n # ignore the rest of the string if a non digit character is read\n if i in (\"+\",\"-\"):\n # only read the first symbol; break if second symbol is read\n if self.is_pos or self.is_neg or isinstance(self.num, int):\n # one of the two symbols is read or a number is read\n break\n self.assign_sign(i)\n continue\n try:\n i = int(i)\n self.add_to_int(i)\n except ValueError:\n # it's neither a sign, nor a number; terminate\n break\n\n # outside the loop; compile the result\n if not self.num:\n return 0\n upper_limit = 2**31 - 1\n if self.is_pos or (not self.is_pos and not self.is_neg):\n if self.num > upper_limit:\n self.num = upper_limit\n elif self.is_neg:\n if self.num > upper_limit+1:\n self.num = upper_limit+1\n self.num = -1 * self.num\n return self.num\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two integers a and b , return any string s such that:", + "description_images": [], + "constraints": [ + "s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,", + "The substring 'aaa' does not occur in s , and", + "The substring 'bbb' does not occur in s ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2\nOutput:\"abb\"\nExplanation:\"abb\", \"bab\" and \"bba\" are all correct answers.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 1\nOutput:\"aabaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.03%) | Memory: 41.4 MB (Top 67.52%)\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb = new StringBuilder();\n int x = Math.min(a, Math.min(b, Math.abs(a - b))); // TAKE THE MIN OF (a, b, abs(a - b))\n if (a > b){\n sb.append(\"aab\".repeat(x));\n b -= x;\n a -= 2 * x;\n }\n if (a < b){\n sb.append(\"bba\".repeat(x));\n b -= 2 * x;\n a -= x;\n }\n if (a == b){\n sb.append(\"ab\".repeat(a));\n }\n if (a == 0){\n sb.append(\"b\".repeat(b));\n }\n if (b == 0){\n sb.append(\"a\".repeat(a));\n }\n return sb.toString();\n }\n}", + "title": "984. String Without AAA or BBB", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers a and b , return any string s such that:", + "description_images": [], + "constraints": [ + "s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,", + "The substring 'aaa' does not occur in s , and", + "The substring 'bbb' does not occur in s ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2\nOutput:\"abb\"\nExplanation:\"abb\", \"bab\" and \"bba\" are all correct answers.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 1\nOutput:\"aabaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if a<3 and b<3:\n return 'a'*a+'b'*b\n s=''\n if a>=b:\n k=a//b\n \n if a//b!=a/b:\n \n k+=1\n if k>=3:\n k=2\n while a>0 or b>0:\n \n if a>k:\n s+='a'*k \n else:\n s+='a'*a\n a-=k\n if b>0:\n s+='b'\n b-=1\n if a==b:\n k=1\n if a=3:\n k=2\n while b>0 or a>0:\n \n if b>k:\n s+='b'*k \n else:\n s+='b'*b\n b-=k\n if a>0:\n s+='a'\n a-=1\n if a==b:\n k=1\n return s\n", + "title": "984. String Without AAA or BBB", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A password is considered strong if the below conditions are all met: Given a string password , return the minimum number of steps required to make password strong. if password is already strong, return 0 . In one step, you can:", + "description_images": [], + "constraints": [ + "It has at least 6 characters and at most 20 characters.", + "It contains at least one lowercase letter, at least one uppercase letter, and at least one digit .", + "It does not contain three repeating characters in a row (i.e., \"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"a\"\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:password = \"aA1\"\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:password = \"1337C0d3\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int MIN_LENGTH = 6;\n private static final int MAX_LENGTH = 20;\n\n public int strongPasswordChecker(String password) {\n int numMissingComponents = getNumberOfMissingComponents(password);\n int n = password.length();\n\n if (n < MIN_LENGTH) {\n return Math.max(numMissingComponents, MIN_LENGTH - n);\n }\n\n List repeats = buildRepeatList(password);\n\n int over = Math.max(0, n - MAX_LENGTH);\n int numRemoval = over;\n\n // use overage for repeat % 3 == 0 case. One removal would reduce one replacement\n for (int i = 0; i < repeats.size() && over > 0; i++) {\n int repeat = repeats.get(i);\n if (repeat >= 3 && repeat % 3 == 0) {\n repeats.set(i, repeat - 1);\n over--;\n }\n }\n // use overage for repeat % 3 == 1 case. Two removal would reduce one replacement\n for (int i = 0; i < repeats.size() && over > 0; i++) {\n int repeat = repeats.get(i);\n if (repeat >= 3 && repeat % 3 == 1) {\n repeats.set(i, repeat - Math.min(over, 2));\n over -= Math.min(over, 2);\n }\n }\n\n int numReplace = 0;\n for (int repeat : repeats) {\n if (over > 0 && repeat >= 3) {\n int reduce = Math.min(over, repeat - 2);\n over -= reduce;\n repeat -= reduce;\n }\n if (repeat >= 3) {\n numReplace += repeat / 3;\n }\n }\n\n return Math.max(numReplace, numMissingComponents) + numRemoval;\n }\n\n private List buildRepeatList(String password) {\n List repeats = new ArrayList<>();\n for (int i = 0; i < password.length(); i++) {\n if (i == 0 || password.charAt(i) != password.charAt(i - 1)) {\n repeats.add(1);\n } else {\n int last = repeats.size() - 1;\n repeats.set(last, repeats.get(last) + 1);\n }\n }\n return repeats;\n }\n\n private int getNumberOfMissingComponents(String password) {\n int digit = 1;\n int upper = 1;\n int lower = 1;\n for (char c: password.toCharArray()) {\n if (Character.isDigit(c)) {\n digit = 0;\n }\n if (Character.isLowerCase(c)) {\n lower = 0;\n }\n if (Character.isUpperCase(c)) {\n upper = 0;\n }\n }\n return digit + upper + lower;\n }\n}\n", + "title": "420. Strong Password Checker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A password is considered strong if the below conditions are all met: Given a string password , return the minimum number of steps required to make password strong. if password is already strong, return 0 . In one step, you can:", + "description_images": [], + "constraints": [ + "It has at least 6 characters and at most 20 characters.", + "It contains at least one lowercase letter, at least one uppercase letter, and at least one digit .", + "It does not contain three repeating characters in a row (i.e., \"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"a\"\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:password = \"aA1\"\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:password = \"1337C0d3\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def strongPasswordChecker(self, password: str) -> int:\n #vimla_kushwaha\n s = password\n missing_type = 3\n if any('a' <= c <= 'z' for c in s): missing_type -= 1\n if any('A' <= c <= 'Z' for c in s): missing_type -= 1\n if any(c.isdigit() for c in s): missing_type -= 1\n\n change = 0\n one = two = 0\n p = 2\n while p < len(s):\n if s[p] == s[p-1] == s[p-2]:\n length = 2\n while p < len(s) and s[p] == s[p-1]:\n length += 1\n p += 1\n \n change += length // 3\n if length % 3 == 0: one += 1\n elif length % 3 == 1: two += 1\n else:\n p += 1\n \n if len(s) < 6:\n return max(missing_type, 6 - len(s))\n elif len(s) <= 20:\n return max(missing_type, change)\n else:\n delete = len(s) - 20\n \n change -= min(delete, one)\n change -= min(max(delete - one, 0), two * 2) // 2\n change -= max(delete - one - 2 * two, 0) // 3\n \n return int(delete + max(missing_type, change))\n", + "title": "420. Strong Password Checker", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A password is said to be strong if it satisfies all the following criteria: Given a string password , return true if it is a strong password . Otherwise, return false .", + "description_images": [], + "constraints": [ + "It has at least 8 characters.", + "It contains at least one lowercase letter.", + "It contains at least one uppercase letter.", + "It contains at least one digit .", + "It contains at least one special character . The special characters are the characters in the following string: \"!@#$%^&*()-+\" .", + "It does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"IloveLe3tcode!\"\nOutput:true\nExplanation:The password meets all the requirements. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:password = \"Me+You--IsMyDream\"\nOutput:false\nExplanation:The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.", + "image": null + }, + { + "text": "Example 3: Input:password = \"1aB!\"\nOutput:false\nExplanation:The password does not meet the length requirement. Therefore, we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean strongPasswordCheckerII(String password) {\n HashSet intAscii = new HashSet<>();\n String specialCharacters = \"!@#$%^&*()-+\";\n for (int i = 0; i < specialCharacters.length(); i++) {\n int ascii = specialCharacters.charAt(i);\n intAscii.add(ascii);\n }\n \n if(password.length() < 8){\n return false;\n }\n boolean small = false;\n boolean large = false;\n boolean numbers = false;\n boolean specialChars = false;\n for(int i = 0 ; i < password.length() ; i++){\n int ascii = (int)(password.charAt(i));\n if(ascii <= 90 && ascii>=65){\n large = true;\n }\n if(ascii <= 122 && ascii>=97){\n small = true;\n }\n if(ascii <=57 && ascii >=48){\n numbers = true;\n }\n if(intAscii.contains(ascii)){\n specialChars = true;\n }\n if(i> 0 && password.charAt(i)== password.charAt(i-1)){\n return false;\n }\n }\n if(large == false || small == false || numbers == false || specialChars ==false){\n return false;\n }\n return true;\n }\n}\n", + "title": "2299. Strong Password Checker II", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A password is said to be strong if it satisfies all the following criteria: Given a string password , return true if it is a strong password . Otherwise, return false .", + "description_images": [], + "constraints": [ + "It has at least 8 characters.", + "It contains at least one lowercase letter.", + "It contains at least one uppercase letter.", + "It contains at least one digit .", + "It contains at least one special character . The special characters are the characters in the following string: \"!@#$%^&*()-+\" .", + "It does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"IloveLe3tcode!\"\nOutput:true\nExplanation:The password meets all the requirements. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:password = \"Me+You--IsMyDream\"\nOutput:false\nExplanation:The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.", + "image": null + }, + { + "text": "Example 3: Input:password = \"1aB!\"\nOutput:false\nExplanation:The password does not meet the length requirement. Therefore, we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 11.66%) | Memory: 13.9 MB (Top 19.37%)\n\nclass Solution:\n def strongPasswordCheckerII(self, pwd: str) -> bool:\n return (\n len(pwd) > 7\n and max(len(list(p[1])) for p in groupby(pwd)) == 1\n and reduce(\n lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0\n ) == 15\n )", + "title": "2299. Strong Password Checker II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: The student is eligible for an attendance award if they meet both of the following criteria: Return true if the student is eligible for an attendance award, or false otherwise .", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PPALLP\"\nOutput:true\nExplanation:The student has fewer than 2 absences and was never late 3 or more consecutive days.", + "image": null + }, + { + "text": "Example 2: Input:s = \"PPALLL\"\nOutput:false\nExplanation:The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkRecord(String s) {\n\n int size=s.length();\n if(s.replace(\"A\",\"\").length()<=size-2||s.indexOf(\"LLL\")!=-1)return false;\n\n return true;\n\n }\n}", + "title": "551. Student Attendance Record I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: The student is eligible for an attendance award if they meet both of the following criteria: Return true if the student is eligible for an attendance award, or false otherwise .", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PPALLP\"\nOutput:true\nExplanation:The student has fewer than 2 absences and was never late 3 or more consecutive days.", + "image": null + }, + { + "text": "Example 2: Input:s = \"PPALLL\"\nOutput:false\nExplanation:The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 76 ms (Top 5.14%) | Memory: 13.9 MB (Top 11.51%)\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n eligible = True\n\n for i in range(0, len(s)-2):\n if s[i:i+3] == \"LLL\":\n eligible = False\n absent = 0\n for i in range(len(s)):\n if s[i] == \"A\":\n absent +=1\n\n if absent>=2:\n eligible = False\n\n return(eligible)", + "title": "551. Student Attendance Record I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: Any student is eligible for an attendance award if they meet both of the following criteria: Given an integer n , return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:8\nExplanation:There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:n = 10101\nOutput:183236316", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 343 ms (Top 29.4%) | Memory: 78.58 MB (Top 12.2%)\n\nclass Solution {\n int mod=1000000000+7;\n public int checkRecord(int n) {\n int[][][] cache=new int[n+1][2][3];\n for(int i=0; i<=n; i++){\n for(int j=0; j<2; j++){\n for(int k=0; k<3; k++)cache[i][j][k]=-1;\n }\n }\n return populate(n, 0, 1, 2, cache);\n }\n public int populate(int n, int ptr, int aCount, int lCount, int[][][] cache){\n if(ptr>=n)return 1;\n if(cache[ptr][aCount][lCount]!=-1)return cache[ptr][aCount][lCount];\n long count=0;\n // Late\n if(lCount>0){\n count=populate(n, ptr+1, aCount, lCount-1, cache)%mod;\n }\n // Present\n count=(count+populate(n, ptr+1, aCount, 2, cache))%mod;\n // Absent\n if(aCount==1)count=(count+populate(n, ptr+1, aCount-1, 2, cache))%mod;\n cache[ptr][aCount][lCount]=(int)(count%mod);\n return cache[ptr][aCount][lCount];\n }\n}", + "title": "552. Student Attendance Record II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: Any student is eligible for an attendance award if they meet both of the following criteria: Given an integer n , return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:8\nExplanation:There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:n = 10101\nOutput:183236316", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 228 ms (Top 90.78%) | Memory: 35.80 MB (Top 36.89%)\n\nimport numpy as np\n\nclass Solution:\n \n def checkRecord(self, n: int) -> int:\n MODULUS = 10**9 + 7\n\n initial_counts = np.array(\n [1, 0, 0, 0, 0, 0], \n dtype=np.int64\n )\n\n adjacency_matrix = np.array([\n [1, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n ], dtype=np.int64)\n\n def power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n for bit in reversed(bin(exp)[2:]):\n if bit == '1':\n B = B @ A\n B %= MODULUS\n A = A @ A\n A %= MODULUS\n return B\n\n final_counts = power(adjacency_matrix, n) @ initial_counts\n\n return sum(final_counts) % MODULUS\n", + "title": "552. Student Attendance Record II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "1 <= nums[i] <= 1000", + "0 <= k <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,5,2,6], k = 100\nOutput:8\nExplanation:The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 19.32%) | Memory: 47.80 MB (Top 5.49%)\n\nclass Solution {\n public int numSubarrayProductLessThanK(int[] nums, int k) {\n int n = nums.length;\n long p = 1l;\n int i = 0;\n int j = 0;\n int total = 0;\n while(j < n){\n p *= nums[j];\n while(i <= j&&p >= k){\n p /= nums[i];\n i++;\n }\n total += (j - i + 1);\n j++;\n }\n return total;\n }\n}", + "title": "713. Subarray Product Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "1 <= nums[i] <= 1000", + "0 <= k <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,5,2,6], k = 100\nOutput:8\nExplanation:The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n if k==0 or k==1:\n return 0\n p=1\n ini=0\n fin=0\n n=len(nums)\n c=0\n while fin=k :\n p=p//nums[ini]\n ini+=1\n\n n1=fin-ini+1\n c+=n1\n fin+=1\n return c\n", + "title": "713. Subarray Product Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the total number of subarrays whose sum equals to k . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-1000 <= nums[i] <= 1000", + "-10^7 <= k <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1], k = 2\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 3\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 80 ms (Top 15.87%) | Memory: 68.2 MB (Top 25.50%)\n/*\nRuntime: 21 ms, faster than 98.97% of Java online submissions for Subarray Sum Equals K.\nMemory Usage: 47.1 MB, less than 85.93% of Java online submissions for Subarray Sum Equals K.\n*/\nclass Solution {\n public int subarraySum(int[] nums, int k) {\n\n HashMap map = new HashMap<>();\n map.put(0,1);\n int count = 0;\n int sum = 0;\n\n for(int i=0; i int:\n\n\t\tans=0\n\t\tprefsum=0\n\t\td={0:1}\n\n\t\tfor num in nums:\n\t\t\tprefsum = prefsum + num\n\n\t\t\tif prefsum-k in d:\n\t\t\t\tans = ans + d[prefsum-k]\n\n\t\t\tif prefsum not in d:\n\t\t\t\td[prefsum] = 1\n\t\t\telse:\n\t\t\t\td[prefsum] = d[prefsum]+1\n\n\t\treturn ans\n", + "title": "560. Subarray Sum Equals K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of non-empty subarrays that have a sum divisible by k . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "2 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,0,-2,-3,1], k = 5\nOutput:7\nExplanation:There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 9\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int subarraysDivByK(int[] nums, int k) {\n HashMap map = new HashMap<>();\n int count = 0;\n int sum = 0;\n for(int i=0;i 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int validSubarraySize(int[] nums, int threshold) {\n int n = nums.length;\n int[] next_small = new int[n];\n int[] prev_small = new int[n];\n Stack stack = new Stack<>();\n stack.push(0);\n Arrays.fill(next_small, n);\n Arrays.fill(prev_small, -1);\n for(int i=1;i= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n prev_small[i] = stack.peek();\n }\n stack.push(i);\n }\n stack = new Stack<>();\n stack.push(n-1);\n for(int i=n-2;i>=0;i--){\n while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n next_small[i] = stack.peek();\n }\n stack.push(i);\n }\n for(int i=0;i 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3127 ms (Top 12.36%) | Memory: 28.8 MB (Top 64.23%)\nclass Solution:\n def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n nums = [0] + nums + [0]\n stack = [0]\n for i in range(1,len(nums)):\n while nums[i] < nums[stack[-1]]:\n tmp = nums[stack.pop()]\n if tmp > threshold / (i - stack[-1] - 1):\n return i - stack[-1] - 1\n stack.append(i)\n return -1", + "title": "2334. Subarray With Elements Greater Than Varying Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of good subarrays of nums . A good array is an array where the number of different integers in that array is exactly k . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "For example, [1,2,3,1,2] has 3 different integers: 1 , 2 , and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,3], k = 2\nOutput:7\nExplanation:Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,4], k = 3\nOutput:3\nExplanation:Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 139 ms (Top 8.32%) | Memory: 69.1 MB (Top 62.69%)\n\nclass Solution {\n public int subarraysWithKDistinct(int[] nums, int k) {\n return count(nums, k) - count(nums, k - 1);\n }\n\n public int count(int[] nums, int k){\n HashMap hm = new HashMap<>();\n\n int left = 0, right = 0, ans = 0;\n\n while(right < nums.length){\n hm.put(nums[right] , hm.getOrDefault(nums[right], 0) + 1);\n\n while(hm.size() == k + 1){\n hm.put(nums[left], hm.get(nums[left]) - 1);\n if(hm.get(nums[left]) == 0)\n hm.remove(nums[left]);\n left++;\n }\n ans += right - left + 1;\n right++;\n }\n return ans;\n\n }\n}", + "title": "992. Subarrays with K Different Integers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return the number of good subarrays of nums . A good array is an array where the number of different integers in that array is exactly k . A subarray is a contiguous part of an array.", + "description_images": [], + "constraints": [ + "For example, [1,2,3,1,2] has 3 different integers: 1 , 2 , and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,3], k = 2\nOutput:7\nExplanation:Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,4], k = 3\nOutput:3\nExplanation:Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n return self.lengthOfLongestSubstringKDistinct(nums, k) - self.lengthOfLongestSubstringKDistinct(nums, k-1)\n \n def lengthOfLongestSubstringKDistinct(self, s, k):\n n = len(s)\n if n * k == 0:\n return 0\n left = 0\n\n hashmap = collections.OrderedDict()\n\n subarray = 0\n for right in range(n):\n if s[right] in hashmap:\n del hashmap[s[right]]\n hashmap[s[right]] = right\n\n if len(hashmap) == k + 1:\n _, del_idx = hashmap.popitem(last = False)\n left = del_idx + 1\n subarray += right - left + 1\n\n return subarray\n \n \n \n", + "title": "992. Subarrays with K Different Integers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\" , at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\" . When we visit a domain like \"discuss.leetcode.com\" , we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains , return an array of the count-paired domains of each subdomain in the input . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times." + ], + "examples": [ + { + "text": "Example 1: Input:cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput:[\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation:We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.", + "image": null + }, + { + "text": "Example 2: Input:cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput:[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation:We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List subdomainVisits(String[] cpdomains) {\n List result = new LinkedList<>();\n HashMap hmap = new HashMap<>();\n \n for(int i = 0; i < cpdomains.length; i++){\n String[] stringData = cpdomains[i].split(\" \");\n String[] str = stringData[1].split(\"\\\\.\");\n String subDomains = \"\";\n \n for(int j = str.length-1; j >= 0; j--){\n subDomains = str[j] + subDomains;\n \n if(!hmap.containsKey(subDomains))\n hmap.put(subDomains, Integer.parseInt(stringData[0]));\n else\n hmap.put(subDomains, hmap.get(subDomains) + Integer.parseInt(stringData[0]));\n subDomains = \".\" + subDomains;\n }\n \n }\n \n for(Map.Entry entry: hmap.entrySet()){\n result.add(entry.getValue() + \" \" + entry.getKey());\n }\n \n return result;\n }\n}\n", + "title": "811. Subdomain Visit Count", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\" , at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\" . When we visit a domain like \"discuss.leetcode.com\" , we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains , return an array of the count-paired domains of each subdomain in the input . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times." + ], + "examples": [ + { + "text": "Example 1: Input:cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput:[\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation:We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.", + "image": null + }, + { + "text": "Example 2: Input:cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput:[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation:We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n output, ans = {}, []\n for domain in cpdomains : \n number, domain = domain.split(' ')\n sub_domain = domain.split('.')\n pair = ''\n print(sub_domain)\n for i in reversed(range(len(sub_domain))) :\n if i == len(sub_domain)-1 : \n pair += sub_domain[i]\n else : \n pair = sub_domain[i] +'.'+ pair \n print(pair)\n \n # output.append(str(number) + ' '+pair)\n if pair not in output.keys() : \n output[pair] = int(number)\n else : \n output[pair] += int(number)\n \n for key in output.keys() : \n ans.append(str(output[key]) + ' '+key)\n \n return ans\n", + "title": "811. Subdomain Visit Count", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) 2. getValue(int row, int col)", + "description_images": [], + "constraints": [ + "Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]Output[null,1,null,5,5,null,10,5]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5", + "image": null + }, + { + "text": "Example 2: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]Output[null,1,null,100,100,null,20]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 20.07%) | Memory: 56.2 MB (Top 15.31%)\nclass SubrectangleQueries {\n int[][] rectangle;\n public SubrectangleQueries(int[][] rectangle) {\n this.rectangle = rectangle;\n }\n\n public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n for(int i=row1;i<=row2;i++){\n for(int j=col1;j<=col2;j++){\n rectangle[i][j] = newValue;\n }\n }\n }\n\n public int getValue(int row, int col) {\n return this.rectangle[row][col];\n }\n}\n\n/**\n * Your SubrectangleQueries object will be instantiated and called as such:\n * SubrectangleQueries obj = new SubrectangleQueries(rectangle);\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue);\n * int param_2 = obj.getValue(row,col);\n */", + "title": "1476. Subrectangle Queries", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) 2. getValue(int row, int col)", + "description_images": [], + "constraints": [ + "Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]Output[null,1,null,5,5,null,10,5]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5", + "image": null + }, + { + "text": "Example 2: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]Output[null,1,null,100,100,null,20]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "class SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.rectangle = rectangle\n\n def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n for i in range(row1,row2+1):\n for j in range(col1,col2+1):\n self.rectangle[i][j] = newValue\n \n def getValue(self, row: int, col: int) -> int:\n return self.rectangle[row][col]\n", + "title": "1476. Subrectangle Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static void solve(int[] nums, int i, List temp, List> subset){\n \n if(i == nums.length){\n subset.add(new ArrayList(temp));\n return;\n }\n \n temp.add(nums[i]);\n solve(nums, i + 1, temp, subset);\n \n temp.remove(temp.size() - 1);\n solve(nums, i + 1, temp, subset);\n }\n \n public List> subsets(int[] nums) {\n List> subset = new ArrayList();\n List temp = new ArrayList<>();\n \n if(nums.length == 0) return subset;\n\n int startInd = 0;\n \n solve(nums, startInd, temp, subset);\n \n return subset;\n }\n}\n", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 8.76%) | Memory: 14.1 MB (Top 82.26%)\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n self.final_list = []\n def subset(final_list,curr_list,listt,i):\n if i == len(listt):\n final_list.append(curr_list)\n return\n else:\n subset(final_list,curr_list,listt,i+1)\n subset(final_list,curr_list+[listt[i]],listt,i+1)\n subset(self.final_list,[],nums,0)\n return self.final_list", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]\nOutput:[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.9%) | Memory: 44.19 MB (Top 7.0%)\n\nclass Solution {\n public List> subsetsWithDup(int[] nums) {\n // Sort the input array to handle duplicates properly\n Arrays.sort(nums);\n // Start the recursion with an empty prefix list\n return subset(new ArrayList(), nums);\n }\n \n // Recursive function to generate subsets\n public List> subset(ArrayList prefix, int[] nums) {\n List> result = new ArrayList<>();\n \n // Base case: If there are no elements in nums, add the current prefix to result\n if (nums.length == 0) {\n result.add(new ArrayList<>(prefix));\n return result;\n }\n \n // Include the first element of nums in the prefix\n ArrayList withCurrent = new ArrayList<>(prefix);\n withCurrent.add(nums[0]);\n \n // Recursive call with the first element included\n List> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));\n \n List> right = new ArrayList<>();\n \n // Check for duplicates in the prefix and decide whether to include the first element again\n if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {\n // If the current element is a duplicate, don't include it in the prefix\n // This avoids generating duplicate subsets\n } else {\n // If the current element is not a duplicate, include it in the prefix\n right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));\n }\n \n // Combine the subsets with and without the current element\n left.addAll(right);\n return left;\n }\n}", + "title": "90. Subsets II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]\nOutput:[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n ans = []\n nums.sort()\n def subset(p, up):\n if len(up) == 0:\n if p not in ans:\n ans.append(p)\n return \n ch = up[0]\n subset(p+[ch], up[1:])\n subset(p, up[1:])\n subset([], nums)\n return ans", + "title": "90. Subsets II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated. Return the starting indices of all the concatenated substrings in s . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput:[0,9]\nExplanation:Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.", + "image": null + }, + { + "text": "Example 2: Input:s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\nOutput:[]\nExplanation:Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\nOutput:[6,9,12]\nExplanation:Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 73.46%) | Memory: 43.2 MB (Top 88.65%)\nclass Solution {\n public List findSubstring(String s, String[] words) {\n\n HashMap input = new HashMap<>();\n int ID = 1;\n HashMap count = new HashMap<>();\n for(String word: words) {\n if(!input.containsKey(word))\n input.put(word, ID++);\n int id = input.get(word);\n count.put(id,count.getOrDefault(id,0)+1);\n\n }\n int len = s.length();\n int wordLen = words[0].length();\n int numWords = words.length;\n int windowLen = wordLen*numWords;\n int lastIndex = s.length()-windowLen;\n\n int curWordId[] = new int[len];\n String cur = \" \"+s.substring(0,wordLen-1);\n\n //Change to int array\n for(int i = 0; i< (len-wordLen+1); i++) {\n cur = cur.substring(1, cur.length())+s.charAt(i+wordLen-1);\n if(input.containsKey(cur)){\n curWordId[i] = input.get(cur);\n } else {\n curWordId[i] = -1;\n }\n }\n List res = new ArrayList<>();\n\n //compare using int make it faster 30 times in each comparison\n for(int i = 0; i<= lastIndex; i++) {\n\n HashMap winMap = new HashMap<>();\n for(int j = 0; j < windowLen && curWordId[i] != -1; j+=wordLen) {\n\n int candidate = curWordId[j+i];\n\n if(!count.containsKey(candidate))\n break;\n else{\n winMap.put(candidate, winMap.getOrDefault(candidate, 0)+1);\n }\n if(winMap.get(candidate) > count.get(candidate))\n break;\n\n if(j == (windowLen - wordLen) && winMap.size() == count.size()){\n res.add(i);\n\n }\n\n }\n }\n\n return res;\n }\n}", + "title": "30. Substring with Concatenation of All Words", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated. Return the starting indices of all the concatenated substrings in s . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput:[0,9]\nExplanation:Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.", + "image": null + }, + { + "text": "Example 2: Input:s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\nOutput:[]\nExplanation:Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\nOutput:[6,9,12]\nExplanation:Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1522 ms (Top 17.46%) | Memory: 14.2 MB (Top 76.15%)\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n req={}\n for i in words:\n req[i]=1+req.get(i,0)\n l=0\n r=len(words)*len(words[0])\n ans=[]\n\n while r 0)\n maxVariance = Math.max(maxVariance, currBFreq - currAFreq);\n \n if(currBFreq < currAFreq && remainingA >= 1){\n currBFreq = 0;\n currAFreq = 0;\n }\n }\n }\n }\n \n return maxVariance;\n }\n}", + "title": "2272. Substring With Largest Variance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababbb\"\nOutput:3\nExplanation:All possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings \"a\", \"aa\", \"ab\", \"abab\", \"aababb\", \"ba\", \"b\", \"bb\", and \"bbb\".\n- Variance 1 for substrings \"aab\", \"aba\", \"abb\", \"aabab\", \"ababb\", \"aababbb\", and \"bab\".\n- Variance 2 for substrings \"aaba\", \"ababbb\", \"abbb\", and \"babb\".\n- Variance 3 for substring \"babbb\".\nSince the largest possible variance is 3, we return it.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\"\nOutput:0\nExplanation:No letter occurs more than once in s, so the variance of every substring is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n class Solution:\n def largestVariance(self, s: str) -> int:\n \n def maxSubArray(nums: List[int]):\n ans=-float('inf')\n runningSum=0\n seen=False\n for x in (nums):\n if x<0:\n seen=True\n runningSum+=x\n if seen:\n ans=max(ans,runningSum)\n else:\n ans=max(ans,runningSum-1)\n if runningSum<0:\n runningSum=0\n seen=False\n return ans\n \n f=set()\n a=''\n for x in s:\n if x not in f:\n a+=x\n f.add(x)\n \n n=len(s)\n res=0\n for j in range(len(a)-1):\n for k in range(j+1,len(a)):\n x=a[j]\n y=a[k]\n arr=[]\n for i in range(n):\n if s[i]!=x and s[i]!=y:\n continue\n elif s[i]==x:\n arr.append(1)\n else:\n arr.append(-1)\n \n res=max(res,maxSubArray(arr),maxSubArray([-x for x in arr]))\n \n return res\n \n \n \n \n\n", + "title": "2272. Substring With Largest Variance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is good if there are no repeated characters. Given a string s ​​​​​, return the number of good substrings of length three in s ​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s ​​​​​​ consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"xyzzaz\"\nOutput:1\nExplanation:There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \nThe only good substring of length 3 is \"xyz\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababcabc\"\nOutput:4\nExplanation:There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\nThe good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countGoodSubstrings(String s) {\n int res = 0;\n \n for(int i = 2 ; i< s.length();i++)\n if(s.charAt(i) != s.charAt(i-1) && s.charAt(i) != s.charAt(i-2) && s.charAt(i-1) != s.charAt(i-2))\n res++;\n return res;\n }\n}\n", + "title": "1876. Substrings of Size Three with Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 234\nOutput:15\nExplanation:Product of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15", + "image": null + }, + { + "text": "Example 2: Input:n = 4421\nOutput:21\nExplanation:Product of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.3 MB (Top 90.51%)\nclass Solution {\n public int subtractProductAndSum(int n) {\n int mul=1,sum=0;\n while(n!=0){\n sum=sum+n%10;\n mul=mul*(n%10);\n n=n/10;\n }\n return mul-sum;\n }\n}", + "title": "1281. Subtract the Product and Sum of Digits of an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 234\nOutput:15\nExplanation:Product of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15", + "image": null + }, + { + "text": "Example 2: Input:n = 4421\nOutput:21\nExplanation:Product of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subtractProductAndSum(self, n: int) -> int:\n n_to_list = list(str(n))\n \n sum_of_digits = 0 \n for num in n_to_list:\n sum_of_digits = sum_of_digits + int(num)\n \n product_of_digits = 1\n for num in n_to_list:\n product_of_digits = product_of_digits * int(num)\n \n answer = product_of_digits - sum_of_digits\n \n return answer\n", + "title": "1281. Subtract the Product and Sum of Digits of an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,4,5,1,2], subRoot = [4,1,2]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if subRoot == None:\n return True\n if root == None:\n return False\n \n sameTree = self.isSameTree(root, subRoot)\n subTreeOnLeft = self.isSubtree(root.left, subRoot)\n subTreeOnRight = self.isSubtree(root.right, subRoot)\n \n return subTreeOnLeft or subTreeOnRight or sameTree\n \n def isSameTree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if (root == None and subRoot == None):\n return True\n \n if (root == None or subRoot == None):\n return False\n \n if (root.val != subRoot.val):\n return False\n \n return self.isSameTree(root.left, subRoot.left) and self.isSameTree(root.right, subRoot.right)\n", + "title": "572. Subtree of Another Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput:[4,0,3]\nExplanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16\nOutput:[2,0,2]\nExplanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 80.4%) | Memory: 58.00 MB (Top 19.8%)\n\nclass Solution {\n public int[] successfulPairs(int[] spells, int[] potions, long success) {\n int n = spells.length;\n int m = potions.length;\n int[] pairs = new int[n];\n Arrays.sort(potions);\n for (int i = 0; i < n; i++) {\n int spell = spells[i];\n int left = 0;\n int right = m - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n long product = (long) spell * potions[mid];\n if (product >= success) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n pairs[i] = m - left;\n }\n return pairs;\n }\n}\n", + "title": "2300. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput:[4,0,3]\nExplanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16\nOutput:[2,0,2]\nExplanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3070 ms (Top 29.46%) | Memory: 37.4 MB (Top 40.00%)\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n result = self.function(spells,potions,success)\n return result\n\n def function(self,arr1,arr2,success):\n n2 = len(arr2)\n arr2.sort() #Sorting Enables Us To Do Binary Search\n ans = []\n for i in arr1:\n val = math.ceil(success/i) #Finding the Value Of Portion With Least Strength So That It Can Be Greater Than Success\n idx = bisect.bisect_left(arr2,val) #Finding The Left Most Index So That The Value Can Be Inserted\n res = n2-idx+1 #Calculating the remaining numbers after finding the suitable index\n ans.append(res-1)\n return ans", + "title": "2300. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules : The '.' character indicates empty cells.", + "description_images": [], + "constraints": [ + "board.length == 9", + "board[i].length == 9", + "board[i][j] is a digit or '.' .", + "It is guaranteed that the input board has only one solution." + ], + "examples": [ + { + "text": "Example 1: 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\"]]\nOutput:[[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]\nExplanation:The input board is shown above and the only valid solution is shown below:", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 30.53%) | Memory: 41.7 MB (Top 44.25%)\nclass Solution {\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n boolean solve(char board[][]){\n for(int i = 0; i None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n full = set('123456789')\n\t\t# lets keep rows, columns and boxes sets in hashmaps\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n boxes = [[set() for _ in range(3)] for _ in range(3)]\n\t\t# and remember empty cell to fill them in\n empty = set()\n\n for i in range(9):\n for j in range(9):\n if board[i][j] == '.':\n empty.add((i,j))\n continue\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n def options(i, j):\n\t\t\t\"\"\"returns possible options for i,j intersecting options from row, col and box\"\"\"\n return (\n (full - rows[i]) &\n (full - cols[j]) &\n (full - boxes[i//3][j//3])\n )\n\n psingle = True # did we have single option decisions in previos traverse\n while empty:\n single = False # for single option decisions in this traverse\n \n for i, j in deepcopy(empty):\n opts = options(i, j)\n if len(opts) == 0:\n\t\t\t\t\t# we've made a wrong assumption - sudoku is unsolvable\n return None, None\n elif len(opts) == 2 and not psingle: # we have no single-option decisions so have to take an assumption\n board1 = deepcopy(board)\n board1[i][j] = opts.pop()\n board1, empty1 = self.solveSudoku(board1)\n if board1 != None: # if solved - we're done\n empty = empty1\n for i, b1 in enumerate(board1):\n board[i] = b1 # have to modify initial list, not just replace the reference\n return board, empty\n if len(opts) == 1: # hey, we have a predetermined choice. nice\n single = True\n board[i][j] = opts.pop()\n empty.remove((i, j))\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n psingle = single\n\n return board, empty\n ```", + "title": "37. Sudoku Solver", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first . You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num : The game ends when there are no more '?' characters in num . For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal . Assuming Alice and Bob play optimally , return true if Alice will win and false if Bob will win .", + "description_images": [], + "constraints": [ + "For example, if the game ended with num = \"243801\" , then Bob wins because 2+4+3 = 8+0+1 . If the game ended with num = \"243803\" , then Alice wins because 2+4+3 != 8+0+3 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5023\"\nOutput:false\nExplanation:There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.", + "image": null + }, + { + "text": "Example 2: Input:num = \"25??\"\nOutput:true\nExplanation:Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.", + "image": null + }, + { + "text": "Example 3: Input:num = \"?3295???\"\nOutput:false\nExplanation:It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 22.45%) | Memory: 50.6 MB (Top 24.49%)\nclass Solution {\n public boolean sumGame(String num) {\n int q = 0, d = 0, n = num.length();\n for (int i = 0; i < n; i++){\n if (num.charAt(i) == '?'){\n q += 2* i < n? 1 : -1;\n }else{\n d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0');\n }\n }\n return (q & 1) > 0 || q * 9 + 2 * d != 0;\n }\n}", + "title": "1927. Sum Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num : The game ends when there are no more '?' characters in num . For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal . Assuming Alice and Bob play optimally , return true if Alice will win and false if Bob will win .", + "description_images": [], + "constraints": [ + "For example, if the game ended with num = \"243801\" , then Bob wins because 2+4+3 = 8+0+1 . If the game ended with num = \"243803\" , then Alice wins because 2+4+3 != 8+0+3 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5023\"\nOutput:false\nExplanation:There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.", + "image": null + }, + { + "text": "Example 2: Input:num = \"25??\"\nOutput:true\nExplanation:Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.", + "image": null + }, + { + "text": "Example 3: Input:num = \"?3295???\"\nOutput:false\nExplanation:It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 173 ms (Top 90.14%) | Memory: 14.9 MB (Top 69.01%)\nclass Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n q_cnt_1 = s1 = 0\n for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n if num[i] == '?':\n q_cnt_1 += 1\n else:\n s1 += int(num[i])\n q_cnt_2 = s2 = 0\n for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n if num[i] == '?':\n q_cnt_2 += 1\n else:\n s2 += int(num[i])\n s_diff = s1 - s2 # calculate sum difference and question mark difference\n q_diff = q_cnt_2 - q_cnt_1\n return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins", + "title": "1927. Sum Game", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i ( 0-indexed ).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= nums[i + 1] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,5]\nOutput:[4,3,5]\nExplanation:Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,6,8,10]\nOutput:[24,15,13,15,21]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 7.55%) | Memory: 110.7 MB (Top 79.24%)\nclass Solution {\n public int[] getSumAbsoluteDifferences(int[] nums) {\n int n = nums.length;\n int[] res = new int[n];\n int sumBelow = 0;\n int sumTotal = Arrays.stream(nums).sum();\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n sumTotal -= num;\n res[i] = sumTotal - (n - i - 1) * num + i * num - sumBelow;\n sumBelow += num;\n }\n return res;\n }\n}", + "title": "1685. Sum of Absolute Differences in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i ( 0-indexed ).", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= nums[i + 1] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,5]\nOutput:[4,3,5]\nExplanation:Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,6,8,10]\nOutput:[24,15,13,15,21]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 733 ms (Top 62.5%) | Memory: 31.64 MB (Top 85.1%)\n\nfrom itertools import accumulate \n\nclass Solution(object):\n def getSumAbsoluteDifferences(self, nums):\n total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)\n return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumerate(nums), list(accumulate(nums)))]\n ", + "title": "1685. Sum of Absolute Differences in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of positive integers arr , return the sum of all possible odd-length subarrays of arr . A subarray is a contiguous subsequence of the array.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 100", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,4,2,5,3]\nOutput:58\nExplanation:The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]\nOutput:3\nExplanation:There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [10,11,12]\nOutput:66", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumOddLengthSubarrays(int[] arr) {\n \n // Using two loops in this question...\n int sum = 0;\n for(int i=0 ; i int:\n \n length = len(arr)\n ans = 0\n \n for i in range(length) :\n ans += ((i+1)*(length-i)+1)//2 * arr[i]\n return ans;\n", + "title": "1588. Sum of All Odd Length Subarrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The XOR total of an array is defined as the bitwise XOR of all its elements , or 0 if the array is empty . Given an array nums , return the sum of all XOR totals for every subset of nums . Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b .", + "description_images": [], + "constraints": [ + "For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3]\nOutput:6\nExplanation:The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,6]\nOutput:28\nExplanation:The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,5,6,7,8]\nOutput:480\nExplanation:The sum of all XOR totals for every subset is 480.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.90 MB (Top 35.14%)\n\nclass Solution {\n int sum=0;\n public int subsetXORSum(int[] nums) {\n sum=0;\n return getAns(nums,0,0);\n }\n \n int getAns(int[] arr,int i,int cur){\n if(i==arr.length){\n return cur;\n }\n return getAns(arr,i+1,cur^arr[i]) + getAns(arr,i+1,cur);\n }\n}\n", + "title": "1863. Sum of All Subset XOR Totals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The XOR total of an array is defined as the bitwise XOR of all its elements , or 0 if the array is empty . Given an array nums , return the sum of all XOR totals for every subset of nums . Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b .", + "description_images": [], + "constraints": [ + "For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3]\nOutput:6\nExplanation:The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,6]\nOutput:28\nExplanation:The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,5,6,7,8]\nOutput:480\nExplanation:The sum of all XOR totals for every subset is 480.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 60 ms (Top 83.44%) | Memory: 13.8 MB (Top 70.65%)\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n def sums(term, idx):\n if idx == len(nums):\n return term\n return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)\n\n return sums(0, 0)", + "title": "1863. Sum of All Subset XOR Totals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . For each index i ( 1 <= i <= nums.length - 2 ) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2 .", + "description_images": [], + "constraints": [ + "2 , if nums[j] < nums[i] < nums[k] , for all 0 <= j < i and for all i < k <= nums.length - 1 .", + "1 , if nums[i - 1] < nums[i] < nums[i + 1] , and the previous condition is not satisfied.", + "0 , if none of the previous conditions holds." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:2\nExplanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6,4]\nOutput:1\nExplanation:For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]\nOutput:0\nExplanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 73.89%) | Memory: 94 MB (Top 67.52%)\nclass Solution {\n public int sumOfBeauties(int[] nums) {\n boolean[] left = new boolean[nums.length];\n boolean[] right = new boolean[nums.length];\n\n left[0] = true;\n int leftMax = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > leftMax) {\n left[i] = true;\n leftMax = nums[i];\n }\n }\n\n right[nums.length-1] = true;\n int rightMin = nums[nums.length-1];\n for(int i = nums.length-2; i >= 0; i--) {\n if(nums[i] < rightMin) {\n right[i] = true;\n rightMin = nums[i];\n }\n }\n\n int beautyCount = 0;\n for(int i = 1; i < nums.length-1; i++) {\n if(left[i] && right[i]) {\n beautyCount += 2;\n }\n\n else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) {\n beautyCount += 1;\n }\n\n }\n return beautyCount;\n }\n}", + "title": "2012. Sum of Beauty in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . For each index i ( 1 <= i <= nums.length - 2 ) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2 .", + "description_images": [], + "constraints": [ + "2 , if nums[j] < nums[i] < nums[k] , for all 0 <= j < i and for all i < k <= nums.length - 1 .", + "1 , if nums[i - 1] < nums[i] < nums[i + 1] , and the previous condition is not satisfied.", + "0 , if none of the previous conditions holds." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:2\nExplanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6,4]\nOutput:1\nExplanation:For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]\nOutput:0\nExplanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n n = len(nums)\n max_dp = [0] * n\n min_dp = [float(inf)] * n\n max_dp[0] = nums[0]\n min_dp[-1] = nums[-1]\n \n for i in range(1, n):\n max_dp[i] = max(nums[i], max_dp[i-1])\n \n for i in range(n-2, -1, -1):\n min_dp[i] = min(nums[i], min_dp[i+1])\n \n ans = 0\n for i in range(1, n-1):\n if max_dp[i-1] < max_dp[i] and nums[i] < min_dp[i+1]:\n ans += 2\n elif nums[i-1] < nums[i] < nums[i+1]:\n ans += 1\n return ans\n", + "title": "2012. Sum of Beauty in the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s , return the sum of beauty of all of its substrings.", + "description_images": [], + "constraints": [ + "For example, the beauty of \"abaacc\" is 3 - 1 = 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcb\"\nOutput:5\nExplanation:The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabcbaa\"\nOutput:17", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int getMinCount(int[] charCount) {\n int min = Integer.MAX_VALUE;\n\t\t\n for (int i = 0; i < charCount.length; ++i) {\n if (charCount[i] != 0) {\n min = Math.min(min, charCount[i]);\n }\n }\n\t\t\n return min;\n }\n \n private int getMaxCount(int[] charCount) {\n int max = 0;\n\t\t\n for (int i = 0; i < charCount.length; ++i) {\n max = Math.max(max, charCount[i]);\n }\n\t\t\n return max;\n }\n \n public int beautySum(String s) {\n int sum = 0;\n \n for (int i = 0; i < s.length(); ++i) {\n int[] charCount = new int[26]; // initialize charCount to all 0\n \n for (int j = i; j < s.length(); ++j) {\n ++charCount[s.charAt(j) - 'a'];\n\n\t\t\t\t// get beauty of substring from i to j\n\t\t\t\tint beauty = getMaxCount(charCount) - getMinCount(charCount);\n sum += beauty;\n }\n }\n \n return sum;\n }\n}\n", + "title": "1781. Sum of Beauty of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s , return the sum of beauty of all of its substrings.", + "description_images": [], + "constraints": [ + "For example, the beauty of \"abaacc\" is 3 - 1 = 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcb\"\nOutput:5\nExplanation:The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabcbaa\"\nOutput:17", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def beautySum(self, s: str) -> int:\n c, n, ans = Counter(s), len(s), 0\n for i in range(n-2):\n x=c.copy()\n for j in range(n-1,i+1,-1):\n ans+=max(x.values())-min(x.values())\n if x[s[j]]==1:\n del x[s[j]]\n else:\n x[s[j]]-=1\n if c[s[i]]==1:\n del c[s[i]]\n else:\n c[s[i]]-=1\n return ans\n", + "title": "1781. Sum of Beauty of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n (in base 10 ) and a base k , return the sum of the digits of n after converting n from base 10 to base k . After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10 .", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "2 <= k <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:n = 34, k = 6\nOutput:9\nExplanation:34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, k = 10\nOutput:1\nExplanation:n is already in base 10. 1 + 0 = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 20.16%)\nclass Solution {\n public int sumBase(int n, int k) {\n int res = 0;\n for (; n > 0; n /= k)\n res += n % k;\n return res;\n }\n}", + "title": "1837. Sum of Digits in Base K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n (in base 10 ) and a base k , return the sum of the digits of n after converting n from base 10 to base k . After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10 .", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "2 <= k <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:n = 34, k = 6\nOutput:9\nExplanation:34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, k = 10\nOutput:1\nExplanation:n is already in base 10. 1 + 0 = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 73.88%) | Memory: 13.8 MB (Top 97.86%)\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n cnt = 0\n while n:\n cnt += (n % k)\n n //= k\n print(cnt)\n return cnt", + "title": "1837. Sum of Digits in Base K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting of lowercase English letters, and an integer k . First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1 , 'b' with 2 , ..., 'z' with 26 ). Then, transform the integer by replacing it with the sum of its digits . Repeat the transform operation k times in total. For example, if s = \"zbax\" and k = 2 , then the resulting integer would be 8 by the following operations: Return the resulting integer after performing the operations described above .", + "description_images": [], + "constraints": [ + "Convert : \"zbax\" ➝ \"(26)(2)(1)(24)\" ➝ \"262124\" ➝ 262124", + "Transform #1 : 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17", + "Transform #2 : 17 ➝ 1 + 7 ➝ 8" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iiii\", k = 1\nOutput:36\nExplanation:The operations are as follows:\n- Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999\n- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36\nThus the resulting integer is 36.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 2\nOutput:6\nExplanation:The operations are as follows:\n- Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545\n- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33\n- Transform #2: 33 ➝ 3 + 3 ➝ 6\nThus the resulting integer is 6.", + "image": null + }, + { + "text": "Example 3: Input:s = \"zbax\", k = 2\nOutput:8", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int getLucky(String s, int k) {\n \n StringBuilder sb=new StringBuilder();\n\n for(int i=0;i0 && result.length()>1)\n { \n sum=0;\n for(int i=0;i int:\n nums = [str(ord(c) - ord('a') + 1) for c in s]\n for _ in range(k):\n nums = str(sum(int(digit) for num in nums for digit in num))\n return nums\n", + "title": "1945. Sum of Digits of String After Convert", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i th node in the tree and all other nodes.", + "description_images": [], + "constraints": [ + "1 <= n <= 3 * 10^4", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "The given input represents a valid tree." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput:[8,12,6,10,10,10]\nExplanation:The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" + }, + { + "text": "Example 2: Input:n = 1, edges = []\nOutput:[0]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" + }, + { + "text": "Example 3: Input:n = 2, edges = [[1,0]]\nOutput:[1,1]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private Map> getGraph(int[][] edges) {\n Map> graph = new HashMap<>();\n for(int[] edge: edges) {\n graph.putIfAbsent(edge[0], new LinkedList<>());\n graph.putIfAbsent(edge[1], new LinkedList<>());\n \n graph.get(edge[0]).add(edge[1]);\n graph.get(edge[1]).add(edge[0]); \n }\n \n return graph;\n }\n \n public int[] sumOfDistancesInTree(int n, int[][] edges) { \n if(n < 2 || edges == null) {\n return new int[]{0};\n }\n \n int[] countSubNodes = new int[n];\n Arrays.fill(countSubNodes, 1);\n int[] distances = new int[n];\n Map> graph = getGraph(edges);\n postOrderTraversal(0, -1, countSubNodes, distances, graph);\n preOrderTraversal(0, -1, countSubNodes, distances, graph, n);\n return distances;\n }\n \n private void postOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n postOrderTraversal(child, node, countSubNodes, distances, graph);\n countSubNodes[node] += countSubNodes[child];\n distances[node] += distances[child] + countSubNodes[child];\n }\n }\n }\n \n private void preOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph, int n) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n\t\t\t\tdistances[child] = distances[node] + (n - countSubNodes[child]) - countSubNodes[child];\n\t\t\t\tpreOrderTraversal(child, node, countSubNodes, distances, graph, n); \n }\n }\n }\n}``\n", + "title": "834. Sum of Distances in Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i th node in the tree and all other nodes.", + "description_images": [], + "constraints": [ + "1 <= n <= 3 * 10^4", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "The given input represents a valid tree." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput:[8,12,6,10,10,10]\nExplanation:The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" + }, + { + "text": "Example 2: Input:n = 1, edges = []\nOutput:[0]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" + }, + { + "text": "Example 3: Input:n = 2, edges = [[1,0]]\nOutput:[1,1]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1783 ms (Top 30.42%) | Memory: 59.4 MB (Top 95.18%)\nfrom typing import List\n\nROOT_PARENT = -1\n\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n @see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N)\n :param n:\n :param edges:\n :return:\n \"\"\"\n g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree\n\n root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)\n\n # considering \"root\" as starting node, we create a tree.\n # Now defining,\n # tree_nodes[i] = number of nodes in the tree rooted at node i\n # distances[i] = sum of distances of all nodes from ith node to all the\n # other nodes of the tree\n tree_nodes, distances = [0] * n, [0] * n\n\n def postorder(rt: int, parent: int):\n \"\"\"\n updating tree_nodes and distances from children of rt. To update them, we must know their\n values at children. And that is why post order traversal is used\n\n After the traversal is done,\n tree_nodes[rt] = all the nodes in tree rooted at rt\n distances[rt] = sum of distances from rt to all the nodes of tree rooted at rt\n\n :param rt:\n :param parent:\n \"\"\"\n tree_nodes[rt] = 1\n\n for c in g[rt]:\n if c != parent:\n postorder(c, rt)\n\n # adding number of nodes in subtree rooted at c to tree rooted at rt\n tree_nodes[rt] += tree_nodes[c]\n\n # moving to rt from c will increase distances by nodes in tree rooted at c\n distances[rt] += distances[c] + tree_nodes[c]\n\n def preorder(rt: int, parent: int):\n \"\"\"\n we start with \"root\" and update its children.\n distances[root] = sum of distances between root and all the other nodes in tree.\n\n In this function, we calculate distances[c] with the help of distances[root] and\n that is why preorder traversal is required.\n :param rt:\n :param parent:\n :return:\n \"\"\"\n for c in g[rt]:\n if c != parent:\n distances[c] = (\n (n - tree_nodes[c]) # rt -> c increase this much distance\n +\n (distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance\n )\n preorder(c, rt)\n\n postorder(root, ROOT_PARENT)\n preorder(root, ROOT_PARENT)\n\n return distances\n\n @staticmethod\n def create_undirected_graph(edges: List[List[int]], n: int):\n \"\"\"\n :param edges:\n :param n:\n :return: graph from edges. Note that this undirect graph is a tree. (Any node can be\n picked as root node)\n \"\"\"\n g = [[] for _ in range(n)]\n\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n\n return g", + "title": "834. Sum of Distances in Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an array queries where queries[i] = [val i , index i ] . For each query i , first, apply nums[index i ] = nums[index i ] + val i , then print the sum of the even values of nums . Return an integer array answer where answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "1 <= queries.length <= 10^4", + "-10^4 <= val i <= 10^4", + "0 <= index i < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput:[8,6,2,4]\nExplanation:At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], queries = [[4,0]]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 90.94%) | Memory: 68.3 MB (Top 82.52%)\nclass Solution {\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int sum = 0;\n for (int i : nums) {\n if ((i & 1) == 0) { // (i % 2 == 0)\n sum += i;\n }\n }\n int[] ans = new int[nums.length];\n int k = 0;\n for (int[] q : queries) {\n int idx = q[1];\n if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n sum -= nums[idx];\n }\n nums[idx] += q[0];\n if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n sum += nums[idx];\n }\n ans[k++] = sum;\n }\n return ans;\n }\n}", + "title": "985. Sum of Even Numbers After Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an array queries where queries[i] = [val i , index i ] . For each query i , first, apply nums[index i ] = nums[index i ] + val i , then print the sum of the even values of nums . Return an integer array answer where answer[i] is the answer to the i th query .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "1 <= queries.length <= 10^4", + "-10^4 <= val i <= 10^4", + "0 <= index i < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput:[8,6,2,4]\nExplanation:At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], queries = [[4,0]]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1565 ms (Top 5.26%) | Memory: 20.6 MB (Top 46.36%)\nclass Solution:\n# O(n) || O(1)\n# Runtime: 583ms 72.40% || memory: 20.5mb 37.69%\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n totalEvenNumSum = sum([num for num in nums if num % 2 == 0])\n result = []\n\n for val, idx in queries:\n oldVal = nums[idx]\n nums[idx] += val\n\n if oldVal % 2 == 0:\n totalEvenNumSum -= oldVal\n\n if nums[idx] % 2 == 0:\n totalEvenNumSum += nums[idx]\n\n result.append(totalEvenNumSum)\n\n return result\n", + "title": "985. Sum of Even Numbers After Queries", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7 . The floor() function returns the integer part of the division.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,9]\nOutput:10\nExplanation:floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7,7,7]\nOutput:49", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumOfFlooredPairs(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length;\n long cnt[]=new long[nums[n-1]+2];\n for(int num:nums){\n cnt[num+1]++;\n }\n for(int i=1;i int:\n \n incs, counter=[0]*(max(nums)+1), Counter(nums) # To store all the quotients increases; counter\n for num in counter: # Loop over all the divisors\n for j in range(num, len(incs), num): # Loop over all the possible dividends where the quotient increases\n incs[j] += counter[num] # Increment the increases in quotients\n quots=list(accumulate(incs)) # Accumulate the increases to get the sum of quotients\n return sum([quots[num] for num in nums]) % 1_000_000_007 # Sum up all the quotients for all the numbers in the list.\n", + "title": "1862. Sum of Floored Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n , return the sum of the n smallest k-mirror numbers .", + "description_images": [], + "constraints": [ + "For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.", + "On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100 , which does not read the same both forward and backward." + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, n = 5\nOutput:25\nExplanation:The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 7\nOutput:499\nExplanation:The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.", + "image": null + }, + { + "text": "Example 3: Input:k = 7, n = 17\nOutput:20379000\nExplanation:The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kMirror(self, k: int, n: int) -> int:\n\n def numberToBase(n, b):\n if n == 0:\n return [0]\n digits = []\n while n:\n digits.append(n % b)\n n //= b\n return digits[::-1]\n \n # not used\n def baseToNumber(arr, b):\n ans = 0\n for x in arr:\n ans = ans * b + int(x)\n return ans\n \n def is_mirror(s):\n l, r = 0, len(s)-1\n while l <= r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\n \n def gen():\n '''\n generate for value with different length\n when i == 0: num:[1, 10)\n size of num: 1, 2 -> 1 or 11\n when i == 1: [10, 100)\n size of num: 3, 4 -> 10 or 101\n when i == 2: [100, 1000)\n size of num: 5, 6 -> 10001 or 100001\n \n the num will be increasing\n '''\n for i in range(30):\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1][1:]\n yield int(s)\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1]\n yield int(s)\n \n ans = 0\n left = n\n for num in gen():\n base = numberToBase(num, k)\n\t\t\t# if is_mirror(base):\n if base == base[::-1]:\n ans += num\n left -= 1\n if left == 0:\n break\n\n return ans\n", + "title": "2081. Sum of k-Mirror Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:24\nExplanation:There are two left leaves in the binary tree, with values 9 and 15 respectively.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 57.76%)\nclass Solution {\n public int sumOfLeftLeaves(TreeNode root) {\n\n if(root==null)\n return 0;\n\n if(root.left!=null && root.left.left==null && root.left.right==null){\n return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }else{\n return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }\n\n }\n}", + "title": "404. Sum of Left Leaves", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:24\nExplanation:There are two left leaves in the binary tree, with values 9 and 15 respectively.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "def is_leaf(x):\n return x.left is None and x.right is None\n\nclass Solution:\n def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n if root is None:\n return 0\n if root.left and is_leaf(root.left):\n left = root.left.val\n else:\n left = self.sumOfLeftLeaves(root.left)\n return left + self.sumOfLeftLeaves(root.right)\n", + "title": "404. Sum of Left Leaves", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr and a target value target , return the integer value such that when we change all the integers larger than value in the given array to be equal to value , the sum of the array gets as close as possible (in absolute difference) to target . In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i], target <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,9,3], target = 10\nOutput:3\nExplanation:When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,5], target = 10\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:arr = [60864,25176,27249,21296,20204], target = 56803\nOutput:11361", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 6.67%) | Memory: 47.2 MB (Top 65.28%)\nclass Solution {\n int max = 0;\n int len;\n public int findBestValue(int[] arr, int target) {\n this.len = arr.length;\n\n for (int i = 0; i < len; i++)\n max = Math.max(max, arr[i]);\n\n int l = 0;\n int r = max;\n while(l < r){\n int mid = l + (r-l) / 2;\n\n if(check(arr, mid, target) <= check(arr, mid+1, target))\n r = mid;\n else\n l = mid + 1;\n }\n return l;\n }\n\n private int check(int[] arr, int value, int target){\n int sum = 0;\n for(int e : arr){\n if(e > value)\n sum += value;\n else\n sum += e;\n }\n\n return Math.abs(sum-target);\n }\n}", + "title": "1300. Sum of Mutated Array Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr and a target value target , return the integer value such that when we change all the integers larger than value in the given array to be equal to value , the sum of the array gets as close as possible (in absolute difference) to target . In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i], target <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,9,3], target = 10\nOutput:3\nExplanation:When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,5], target = 10\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:arr = [60864,25176,27249,21296,20204], target = 56803\nOutput:11361", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findBestValue(self, arr: List[int], t: int) -> int:\n def getsum(x):\n s = 0\n for i in range(n):\n if arr[i] > x:\n s += x*(n-i)\n break\n else:\n s += arr[i]\n return s\n\t\t\t\n\t\tarr.sort()\n n = len(arr)\n l, r = 0, max(arr)\n ans = [inf, inf]\n while l <= r:\n m = l+(r-l)//2\n if abs(getsum(m)-t) <= ans[0]:\n if abs(getsum(m)-t) == ans[0]:\n ans[1] = min(m, ans[1])\n else:\n ans = [abs(getsum(m)-t), m]\n if getsum(m) > t:\n r = m-1\n else:\n l = m+1\n \n return ans[1]\n", + "title": "1300. Sum of Mutated Array Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent . If there are no nodes with an even-valued grandparent , return 0 . A grandparent of a node is the parent of its parent if it exists.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput:18\nExplanation:The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int sum=0;\n public int sumEvenGrandparent(TreeNode root) {\n dfs(root,null,null);\n return sum;\n }\n void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) {\n if (current == null) return; // base case \n if (grandParent != null && grandParent.val % 2 == 0) {\n sum += current.val;\n }\n\t\t\t\t//cur->cur.left ||cur.right , parent=cur,grandPrarent=parent\n dfs(current.left, current, parent)\n dfs(current.right, current, parent);\n }\n }\n", + "title": "1315. Sum of Nodes with Even-Valued Grandparent", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent . If there are no nodes with an even-valued grandparent , return 0 . A grandparent of a node is the parent of its parent if it exists.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput:18\nExplanation:The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:0", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef sumEvenGrandparent(self, root: TreeNode) -> int:\n\n\t\tdef dfs(root, p, gp):\n\t\t\tif not root: return 0\n\t\t\tif gp and gp.val%2==0:\n\t\t\t\treturn root.val + dfs(root.left,root,p)+dfs(root.right,root,p)\n\t\t\treturn 0 + dfs(root.left,root,p)+dfs(root.right,root,p)\n\n\t\treturn dfs(root,None,None)", + "title": "1315. Sum of Nodes with Even-Valued Grandparent", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers num and k , consider a set of positive integers with the following properties: Return the minimum possible size of such a set, or -1 if no such set exists. Note:", + "description_images": [], + "constraints": [ + "The units digit of each integer is k .", + "The sum of the integers is num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 58, k = 9\nOutput:2\nExplanation:One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.", + "image": null + }, + { + "text": "Example 2: Input:num = 37, k = 2\nOutput:-1\nExplanation:It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.", + "image": null + }, + { + "text": "Example 3: Input:num = 0, k = 7\nOutput:0\nExplanation:The sum of an empty set is considered 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.88%) | Memory: 40.7 MB (Top 84.12%)\n\nclass Solution\n{\n public int minimumNumbers(int num, int k)\n {\n if(num == 0)\n return 0;\n if(k == 0)\n if(num % 10 == 0) //E.g. 20,1590,3000\n return 1;\n else\n return -1;\n for(int i = 1; i <= num/k; i++) // Start with set size 1 and look for set having unit's digit equal to that of num\n if(num % 10 == ((i*k)%10)) // Look for equal unit's digit\n return i;\n\n return -1;\n }\n}", + "title": "2310. Sum of Numbers With Units Digit K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integers num and k , consider a set of positive integers with the following properties: Return the minimum possible size of such a set, or -1 if no such set exists. Note:", + "description_images": [], + "constraints": [ + "The units digit of each integer is k .", + "The sum of the integers is num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 58, k = 9\nOutput:2\nExplanation:One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.", + "image": null + }, + { + "text": "Example 2: Input:num = 37, k = 2\nOutput:-1\nExplanation:It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.", + "image": null + }, + { + "text": "Example 3: Input:num = 0, k = 7\nOutput:0\nExplanation:The sum of an empty set is considered 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumNumbers(self, num: int, k: int) -> int:\n if num == 0:\n return 0\n \n if k == 0:\n return 1 if num % 10 == 0 else -1\n \n for n in range(1, min(num // k, 10) + 1):\n if (num - n * k) % 10 == 0:\n return n\n \n return -1\n", + "title": "2310. Sum of Numbers With Units Digit K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree where each node has a value 0 or 1 . Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers . The test cases are generated so that the answer fits in a 32-bits integer.", + "description_images": [], + "constraints": [ + "For example, if the path is 0 -> 1 -> 1 -> 0 -> 1 , then this could represent 01101 in binary, which is 13 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,1,0,1,0,1]\nOutput:22\nExplanation:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "image": "https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png" + }, + { + "text": "Example 2: Input:root = [0]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.80 MB (Top 51.65%)\n\nclass Solution {\n public int sumRootToLeaf(TreeNode root) {\n return sumRootToLeaf(root, 0);\n }\n public int sumRootToLeaf(TreeNode root, int sum){\n if(root == null) return 0;\n sum = (2 * sum) + root.val;\n if(root.left == null && root.right == null) return sum;\n return sumRootToLeaf(root.left, sum) + sumRootToLeaf(root.right, sum);\n }\n}\n", + "title": "1022. Sum of Root To Leaf Binary Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree where each node has a value 0 or 1 . Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers . The test cases are generated so that the answer fits in a 32-bits integer.", + "description_images": [], + "constraints": [ + "For example, if the path is 0 -> 1 -> 1 -> 0 -> 1 , then this could represent 01101 in binary, which is 13 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,1,0,1,0,1]\nOutput:22\nExplanation:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "image": "https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png" + }, + { + "text": "Example 2: Input:root = [0]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n def path(root,p,ans):\n p.append(str(root.val))\n if root.left==None and root.right==None:\n t = int(\"\".join(p),2)\n p.pop()\n return t+ans\n if root.left==None:\n t = path(root.right,p,ans)\n p.pop()\n return t\n if root.right==None:\n t = path(root.left,p,ans)\n p.pop()\n return t\n t = path(root.left,p,ans)+path(root.right,p,ans)\n p.pop()\n return t\n return path(root,[],0)\n", + "title": "1022. Sum of Root To Leaf Binary Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n , where the string with length i is labeled s i . The score of s i is the length of the longest common prefix between s i and s n (Note that s == s n ). Given the final string s , return the sum of the score of every s i .", + "description_images": [], + "constraints": [ + "For example, for s = \"abaca\" , s 1 == \"a\" , s 2 == \"ca\" , s 3 == \"aca\" , etc." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babab\"\nOutput:9\nExplanation:For s1== \"b\", the longest common prefix is \"b\" which has a score of 1.\nFor s2== \"ab\", there is no common prefix so the score is 0.\nFor s3== \"bab\", the longest common prefix is \"bab\" which has a score of 3.\nFor s4== \"abab\", there is no common prefix so the score is 0.\nFor s5== \"babab\", the longest common prefix is \"babab\" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"azbazbzaz\"\nOutput:14\nExplanation:For s2== \"az\", the longest common prefix is \"az\" which has a score of 2.\nFor s6== \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\nFor s9== \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long[] hsh, hsh2, pw, pw2;\n public int mod = (int) 1e9+7;\n public long sumScores(String s) {\n int n = s.length(), base = 131, base2 = 137;\n hsh = new long[n+1]; pw = new long[n+1];\n hsh2 = new long[n+1]; pw2 = new long[n+1];\n pw[0] = 1; pw2[0] = 1;\n for (int j = 1; j <= n; j++) {\n hsh[j] = (hsh[j-1]*base + s.charAt(j-1))%mod;\n pw[j] = pw[j-1]*base%mod;\n hsh2[j] = (hsh2[j-1]*base2 + s.charAt(j-1))%mod;\n pw2[j] = pw2[j-1]*base2%mod;\n }\n // binary search for score\n long ans = 0;\n for (int i = n; i >= 1; i--) {\n if (s.charAt(i-1)!=s.charAt(0)) continue;\n int lo = 0, hi = n-i+1, res = 0;\n while (lo<=hi) {\n int mid = (lo+hi)>>1;\n if (getSubstrHash(0, mid)==getSubstrHash(i-1, i+mid-1)) {\n lo = mid+1; res = mid;\n }\n else hi = mid-1;\n }\n ans+=res;\n }\n return ans;\n }\n public long getSubstrHash(int l, int r){\n long h1 = (hsh[r] - hsh[l] * pw[r-l] % mod + mod)%mod;\n long h2 = (hsh2[r] - hsh2[l] * pw2[r-l] % mod + mod)%mod;\n return (h1<<31) | h2;\n }\n}\n", + "title": "2223. Sum of Scores of Built Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n , where the string with length i is labeled s i . The score of s i is the length of the longest common prefix between s i and s n (Note that s == s n ). Given the final string s , return the sum of the score of every s i .", + "description_images": [], + "constraints": [ + "For example, for s = \"abaca\" , s 1 == \"a\" , s 2 == \"ca\" , s 3 == \"aca\" , etc." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babab\"\nOutput:9\nExplanation:For s1== \"b\", the longest common prefix is \"b\" which has a score of 1.\nFor s2== \"ab\", there is no common prefix so the score is 0.\nFor s3== \"bab\", the longest common prefix is \"bab\" which has a score of 3.\nFor s4== \"abab\", there is no common prefix so the score is 0.\nFor s5== \"babab\", the longest common prefix is \"babab\" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"azbazbzaz\"\nOutput:14\nExplanation:For s2== \"az\", the longest common prefix is \"az\" which has a score of 2.\nFor s6== \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\nFor s9== \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 200 ms (Top 85.96%) | Memory: 25.20 MB (Top 24.56%)\n\nclass Solution:\n def sumScores(self, s):\n n = len(s)\n\n dp, ans, j = [1]*n, [0]*n, 0 \n\n for i in range(1,n):\n while s[i] != s[j] and j > 0:\n j = ans[j-1]\n\n if s[i] == s[j]:\n dp[i] += dp[j]\n ans[i] = j+1\n j += 1 \n\n return sum(dp)\n\n\n\n\n\n\n\n \n", + "title": "2223. Sum of Scores of Built Strings", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c .", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5\nOutput:true\nExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 55.1%) | Memory: 39.57 MB (Top 27.7%)\n\nclass Solution {\n public boolean judgeSquareSum(int c) {\n long a = 0;\n long b = (long) Math.sqrt(c);\n\n while(a<=b){\n if(((a*a) + (b*b)) == c){\n return true;\n }\n else if((((a*a)+(b*b)) < c)){\n a++;\n }\n else{\n b--;\n }\n }\n return false;\n }\n}", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c .", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5\nOutput:true\nExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 669 ms (Top 21.17%) | Memory: 13.8 MB (Top 63.98%)\nimport math\n\nclass Solution:\n def judgeSquareSum(self, c: int) -> bool:\n\n a = 0\n\n while a ** 2 <= c:\n b = math.sqrt(c - a ** 2)\n\n if b.is_integer():\n return True\n\n a += 1\n\n return False", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr, find the sum of min(b) , where b ranges over every (contiguous) subarray of arr . Since the answer may be large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 3 * 10^4", + "1 <= arr[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,2,4]\nOutput:17\nExplanation:Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,81,94,43,3]\nOutput:444", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumSubarrayMins(int[] arr) {\n int n = arr.length;\n int ans1[] = nsl(arr);\n int ans2[] = nsr(arr);\n long sum=0;\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=arr.length-1;i>=0;i--){\n while(!s.isEmpty() && arr[s.peek()]>=arr[i]){\n s.pop();\n }\n if(s.isEmpty()){\n ans[i] = arr.length-i;\n s.push(i);\n }\n else{\n ans[i] = s.peek()-i;\n s.push(i);\n }\n }\n return ans;\n }\n}\n", + "title": "907. Sum of Subarray Minimums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr, find the sum of min(b) , where b ranges over every (contiguous) subarray of arr . Since the answer may be large, return the answer modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 3 * 10^4", + "1 <= arr[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,2,4]\nOutput:17\nExplanation:Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,81,94,43,3]\nOutput:444", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n n = len(arr)\n small_before = [-1]*n\n stack = []\n for i in range(n):\n while stack and arr[stack[-1]] >= arr[i]:\n stack.pop()\n if stack:small_before[i] = stack[-1]\n stack.append(i)\n best = [0]*(n+1)\n ans = 0\n for i in range(n):\n best[i] = best[small_before[i]] + (i - small_before[i])*arr[i]\n ans += best[i]\n return ans%1000000007", + "title": "907. Sum of Subarray Minimums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:4\nExplanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,3]\nOutput:4\nExplanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,-2,-3,4,1]\nOutput:59\nExplanation:The sum of all subarray ranges of nums is 59.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n class Node{\n long val, displace;\n Node(long val, long displace){\n this.val = val;\n this.displace = displace;\n }\n }\n public long subArrayRanges(int[] nums) {\n \n //lesser than current element\n Stack stack = new Stack<>();\n //from left\n long [] lesserLeft = new long[nums.length];\n for (int i = 0; i< nums.length; i++){\n long count = 1;\n while(stack.size()>0 && stack.peek().val<=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n lesserLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] lesserRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val0 && stack.peek().val>=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] greaterRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val>nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterRight[i] = count;\n } \n \n long ans = 0;\n //Now we subtract the count of minimum occurrences from the count of maximum occurrences\n \n for (int i = 0; i< nums.length; i++){\n ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i];\n }\n return ans;\n }\n}\n", + "title": "2104. Sum of Subarray Ranges", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:4\nExplanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,3]\nOutput:4\nExplanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,-2,-3,4,1]\nOutput:59\nExplanation:The sum of all subarray ranges of nums is 59.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n n = len(nums)\n \n # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n # so totalsum = maxsum - minsum\n # we calculate minsum and maxsum in two different loops\n minsum = maxsum = 0\n \n # first calculate sum{ Min(subarray) } over all subarrays\n # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1\n # where f(i) is number of subarrays where nums[i] is the minimum value\n # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i]\n # we can claculate these indices in linear time using a monotonically increasing stack.\n stack = []\n for next_smaller in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically increasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]):\n i = stack.pop()\n prev_smaller = stack[-1] if stack else -1\n minsum += nums[i] * (next_smaller - i) * (i - prev_smaller)\n stack.append(next_smaller)\n \n # then calculate sum{ Max(subarray) } over all subarrays\n # sum{ Max(subarray) } = sum(f'(i) * nums[i]) ; i=0..n-1\n # where f'(i) is number of subarrays where nums[i] is the maximum value\n # f'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i]\n # this time we use a monotonically decreasing stack.\n stack = []\n for next_larger in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically decreasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]):\n i = stack.pop()\n prev_larger = stack[-1] if stack else -1\n maxsum += nums[i] * (next_larger - i) * (i - prev_larger)\n stack.append(next_larger)\n \n return maxsum - minsum\n", + "title": "2104. Sum of Subarray Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums , return the sum of the widths of all the non-empty subsequences of nums . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:6\n\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 70.11%) | Memory: 74.1 MB (Top 69.83%)\nclass Solution {\n public int sumSubseqWidths(int[] nums) {\n int MOD = (int)1e9 + 7;\n Arrays.sort(nums);\n\n long ans = 0;\n long p = 1;\n for(int i = 0; i < nums.length; i++){\n ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD;\n p = (p * 2) % MOD;\n }\n return (int)ans;\n }\n}", + "title": "891. Sum of Subsequence Widths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums , return the sum of the widths of all the non-empty subsequences of nums . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:6\n\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n M = 10**9+7\n res = 0\n le = 1\n re = pow(2, n-1, M)\n #by Fermat's Little Thm\n #inverse of 2 modulo M\n inv = pow(2, M-2, M)\n for num in nums:\n res = (res + num * (le - re))%M\n le = (le * 2) % M\n re = (re * inv) % M\n return res", + "title": "891. Sum of Subsequence Widths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength , where strength[i] denotes the strength of the i th wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength ), the total strength is defined as the product of the following two values: Return the sum of the total strengths of all contiguous groups of wizards . Since the answer may be very large, return it modulo 10^9 + 7 . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "The strength of the weakest wizard in the group.", + "The total of all the individual strengths of the wizards in the group." + ], + "examples": [ + { + "text": "Example 1: Input:strength = [1,3,1,2]\nOutput:44\nExplanation:The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.", + "image": null + }, + { + "text": "Example 2: Input:strength = [5,4,6]\nOutput:213\nExplanation:The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 178 ms (Top 61.28%) | Memory: 109.5 MB (Top 34.27%)\nclass Solution {\n public int totalStrength(int[] strength) {\n int mod = 1000000007;\n\n int len = strength.length;\n\n long[] prefix = prefixSum(strength, len, mod);\n\n Deque stack = new ArrayDeque<>();\n stack.push(-1);\n\n long ans = 0;\n for(int i = 0; i < len; i++) {\n while(stack.peek() != -1 && strength[i] <= strength[stack.peek()]) {\n int mid = stack.pop();\n int left = stack.peek() + 1;\n int right = i - 1;\n\n int n = (mid - left);\n int t = (right - mid);\n\n long val = (1l * (1 + n) * (prefix[right + 2] - prefix[mid + 1]) + mod) % mod;\n val -= (1l * (1 + t) * (prefix[mid + 1] - prefix[left]) + mod) % mod;\n val *= strength[mid];\n\n ans += val;\n ans %= mod;\n }\n\n stack.push(i);\n }\n\n int right = len - 1;\n while(stack.peek() != -1) {\n int mid = stack.pop();\n int left = stack.peek() + 1;\n\n int n = (mid - left);\n int t = (right - mid);\n\n long val = (1l * (1 + n) * (prefix[right + 2] - prefix[mid + 1]) + mod) % mod;\n val -= (1l * (1 + t) * (prefix[mid + 1] - prefix[left]) + mod) % mod;\n val *= strength[mid];\n\n ans += val;\n ans %= mod;\n }\n\n return (int)((ans + mod) % mod);\n }\n\n private long[] prefixSum(int[] strength, int len, int mod) {\n long[] prefix = new long[len + 1];\n\n for(int i = 0; i < len; i++) {\n prefix[i + 1] = prefix[i] + strength[i];\n }\n\n long[] doublePrefix = new long[len + 2];\n for(int i = 0; i <= len; i++) {\n doublePrefix[i + 1] = (doublePrefix[i] + prefix[i]) % mod;\n }\n\n return doublePrefix;\n }\n}", + "title": "2281. Sum of Total Strength of Wizards", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength , where strength[i] denotes the strength of the i th wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength ), the total strength is defined as the product of the following two values: Return the sum of the total strengths of all contiguous groups of wizards . Since the answer may be very large, return it modulo 10^9 + 7 . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "The strength of the weakest wizard in the group.", + "The total of all the individual strengths of the wizards in the group." + ], + "examples": [ + { + "text": "Example 1: Input:strength = [1,3,1,2]\nOutput:44\nExplanation:The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.", + "image": null + }, + { + "text": "Example 2: Input:strength = [5,4,6]\nOutput:213\nExplanation:The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalStrength(self, stp: List[int]) -> int:\n st = []\n n = len(stp)\n m1 = defaultdict(lambda:-1)\n ps = [0]\n for i in range(n):\n while st and stp[st[-1]] >= stp[i]:\n st.pop()\n if st: m1[i] = st[-1]\n st.append(i)\n ps.append(ps[-1] + stp[i])\n pss = [0]\n for i in ps:\n pss.append(pss[-1] + i)\n st = []\n m2 = defaultdict(lambda:n)\n for i in range(n-1,-1,-1):\n while st and stp[st[-1]] > stp[i]:\n st.pop()\n if st: m2[i] = st[-1]\n st.append(i)\n\n ans = 0\n mod = 10**9 + 7\n for i in range(n):\n left = m1[i] + 1\n right = m2[i]\n p1 = (i+1-left)*(pss[right+1]-pss[i+1])\n p2 = (right-i)*(pss[i+1]- pss[left])\n ans = (ans + stp[i]*(p1 - p2)) % mod\n return ans\n", + "title": "2281. Sum of Total Strength of Wizards", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integers a and b , return the sum of the two integers without using the operators + and - .", + "description_images": [], + "constraints": [ + "-1000 <= a, b <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int getSum(int a, int b) {\n return Integer.sum(a, b);\n }\n}\n", + "title": "371. Sum of Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers a and b , return the sum of the two integers without using the operators + and - .", + "description_images": [], + "constraints": [ + "-1000 <= a, b <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = 3\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n sol=(a,b)\n return sum(sol)\n\t```", + "title": "371. Sum of Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,2]\nOutput:4\nExplanation:The unique elements are [1,3], and the sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1,1]\nOutput:0\nExplanation:There are no unique elements, and the sum is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]\nOutput:15\nExplanation:The unique elements are [1,2,3,4,5], and the sum is 15.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.10%) | Memory: 40.1 MB (Top 92.63%)\nclass Solution {\n public int sumOfUnique(int[] nums) {\n int res = 0;\n Map map = new HashMap<>();\n for(int i = 0;i int:\n hashmap = {}\n for i in nums:\n if i in hashmap.keys():\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n sum = 0\n for k, v in hashmap.items():\n if v == 1: sum += k\n return sum\n", + "title": "1748. Sum of Unique Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:25\nExplanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]\nOutput:1026\nExplanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int res;\n public int sumNumbers(TreeNode root) {\n res = 0;\n getSum(root, 0);\n \n return res;\n }\n \n public void getSum(TreeNode root, int sum){\n \n if(root.left == null && root.right == null) {\n res += (sum*10+root.val);\n }\n \n if(root.left != null)\n getSum(root.left, sum*10+root.val);\n \n \n if(root.right != null)\n getSum(root.right, sum*10+root.val);\n }\n}\n", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:25\nExplanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]\nOutput:1026\nExplanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sumNumbers(self, root: Optional[TreeNode]) -> int:\n \n int_list = []\n \n def traverse(node, input_string):\n \n nonlocal int_list\n \n if not node:\n return int_list\n \n input_string = input_string + str(node.val)\n\n if not (node.left or node.right):\n int_list.append(int(input_string))\n \n traverse(node.left, input_string)\n traverse(node.right, input_string)\n \n traverse(root, \"\")\n return sum(int_list)\n \n", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a sorted unique integer array nums . A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly . That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums . Each range [a,b] in the list should be output as:", + "description_images": [], + "constraints": [ + "\"a->b\" if a != b", + "\"a\" if a == b" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,4,5,7]\nOutput:[\"0->2\",\"4->5\",\"7\"]\nExplanation:The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,2,3,4,6,8,9]\nOutput:[\"0\",\"2->4\",\"6\",\"8->9\"]\nExplanation:The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 76.97%) | Memory: 13.8 MB (Top 98.42%)\n\nclass Solution(object):\n def summaryRanges(self, nums):\n\n if len(nums) == 0:\n return []\n\n l, r = 0, 0\n res = []\n\n while l<=r and r <= len(nums):\n\n if r == 0:\n r+=1\n\n while r < len(nums) and r>0 and nums[r-1] == nums[r]-1:\n r+=1\n\n if r-1 == l:\n res.append(str(nums[r-1]))\n else:\n res.append(str(nums[l]) + '->' + str(nums[r-1]))\n\n l=r\n r+=1\n\n return res", + "title": "228. Summary Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1, n = 2\nOutput:2\nExplanation:Drop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, n = 6\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:k = 3, n = 14\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 33.33%) | Memory: 54.3 MB (Top 43.02%)\nclass Solution {\n\n int [][]dp;\n public int superEggDrop(int k, int n) {\n dp=new int[k+1][n+1];\n\n for(int i=0;i<=k;i++){\n Arrays.fill(dp[i],-1);\n }\n\n return solve(k,n);\n\n }\n\n public int solve(int e, int f){\n if(f==0 || f==1){\n return f;\n }\n\n if(e==1){\n return f;\n }\n\n if(dp[e][f]!=-1){\n return dp[e][f];\n }\n\n int high=f;\n int low=1;\n int min=Integer.MAX_VALUE;\n\n while(low<=high){\n int k=low+(high-low)/2;\n\n int l=0;\n int r=0;\n\n if(dp[e-1][k-1]!=-1){\n l=dp[e-1][k-1];\n }else{\n l=solve(e-1,k-1);\n }\n\n if(dp[e][f-k]!=-1){\n r=dp[e][f-k];\n }else{\n r=solve(e,f-k);\n }\n\n if(l>r){\n high=k-1;\n }else{\n low=k+1;\n }\n\n int temp=Math.max(l,r)+1;\n min=Math.min(min,temp);\n }\n\n return dp[e][f]=min;\n }\n}\n\n//-------------------------TLE--------------------------\n\n// class Solution {\n// public int superEggDrop(int k, int n) {\n// int [][]dp=new int[k+1][n+1];\n\n// for(int i=1;i<=k;i++){\n// for(int j=1;j<=n;j++){\n// if(i==1){\n// dp[i][j]=j;\n// }else if(j==1){\n// dp[i][j]=1;\n// }else{\n// int min=Integer.MAX_VALUE;\n\n// for(int m=j-1,p=0;m>=0;m--,p++){\n// int max=Math.max(dp[i][m],dp[i-1][p]);\n\n// min=Math.min(min,max);\n// }\n\n// dp[i][j]=min+1;\n// }\n// }\n// }\n\n// return dp[k][n];\n// }\n// }", + "title": "887. Super Egg Drop", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1, n = 2\nOutput:2\nExplanation:Drop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, n = 6\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:k = 3, n = 14\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def superEggDrop(self, e: int, f: int) -> int:\n dp = [[-1 for _ in range(e+1)] for _ in range(f+1)]\n \n def solve(floors,eggs):\n \n if eggs==1:\n dp[floors][eggs] = floors\n return floors\n\n if floors==0:\n dp[floors][eggs] = 0\n return 0\n \n if dp[floors][eggs]==-1:\n \n ans = math.inf\n low = 1\n high = floors\n # Binary Search for the floor where to drop the egg\n while low<=high:\n mid = (low+high)//2\n left = solve(mid-1,eggs-1)\n right = solve(floors-mid,eggs)\n tmp = 1 + max(left,right)\n if left < right:\n low = mid+1\n else:\n high = mid-1\n ans = min(ans,tmp)\n \n dp[floors][eggs] = ans\n \n return dp[floors][eggs]\n \n return solve(f,e)\n\n", + "title": "887. Super Egg Drop", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right] .", + "description_images": [], + "constraints": [ + "1 <= left.length, right.length <= 18", + "left and right consist of only digits.", + "left and right cannot have leading zeros.", + "left and right represent integers in the range [1, 10^18 - 1] .", + "left is less than or equal to right ." + ], + "examples": [ + { + "text": "Example 1: Input:left = \"4\", right = \"1000\"\nOutput:4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:left = \"1\", right = \"2\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 92.59%) | Memory: 42.2 MB (Top 79.63%)\nclass Solution {\n public int superpalindromesInRange(String left, String right) {\n int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n\n for (int dig = 1; dig < 10; dig++) {\n boolean isOdd = dig % 2 > 0 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n char[] pal = new char[dig];\n Arrays.fill(pal, '0');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) {\n innerLim = 1;\n midLim = Math.min(midLim, 2);\n }\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n String innerStr = Integer.toString(inner, 2);\n while (innerStr.length() < innerLen)\n innerStr = \"0\" + innerStr;\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr.charAt(i);\n pal[dig-2-i] = innerStr.charAt(i);\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n String palin = new String(pal);\n long square = Long.parseLong(palin) * Long.parseLong(palin);\n if (square > Long.parseLong(right)) return ans;\n if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n\n private boolean isPal(String str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str.charAt(i) != str.charAt(j)) return false;\n return true;\n }\n}", + "title": "906. Super Palindromes", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right] .", + "description_images": [], + "constraints": [ + "1 <= left.length, right.length <= 18", + "left and right consist of only digits.", + "left and right cannot have leading zeros.", + "left and right represent integers in the range [1, 10^18 - 1] .", + "left is less than or equal to right ." + ], + "examples": [ + { + "text": "Example 1: Input:left = \"4\", right = \"1000\"\nOutput:4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:left = \"1\", right = \"2\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n min_num, max_num = int(left), int(right)\n count, limit = 0, 20001\n \n # odd pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[:-1][::-1]\n num_sqr = int(pal) ** 2\n\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n # even pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[::-1]\n num_sqr = int(pal) ** 2\n\n if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n return count ", + "title": "906. Super Palindromes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Your task is to calculate a b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.", + "description_images": [], + "constraints": [ + "1 <= a <= 2 31 - 1", + "1 <= b.length <= 2000", + "0 <= b[i] <= 9", + "b does not contain leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = [3]\nOutput:8", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = [1,0]\nOutput:1024", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = [4,3,3,8,5,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.BigInteger;\nclass Solution {\n public int superPow(int a, int[] b) {\n StringBuilder bigNum = new StringBuilder();\n Arrays.stream(b).forEach(i -> bigNum.append(i));\n \n return \n BigInteger.valueOf(a)\n .modPow(new BigInteger(bigNum.toString()), BigInteger.valueOf(1337))\n .intValue();\n }\n}\n", + "title": "372. Super Pow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your task is to calculate a b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.", + "description_images": [], + "constraints": [ + "1 <= a <= 2 31 - 1", + "1 <= b.length <= 2000", + "0 <= b[i] <= 9", + "b does not contain leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = [3]\nOutput:8", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = [1,0]\nOutput:1024", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = [4,3,3,8,5,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 260 ms (Top 32.64%) | Memory: 13.9 MB (Top 58.72%)\nclass Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n mod = 1337\n ans = 1\n\n for power in b:\n ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod\n\n return ans", + "title": "372. Super Pow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes . Given an integer n and an array of integers primes , return the n th super ugly number . The n th super ugly number is guaranteed to fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= primes.length <= 100", + "2 <= primes[i] <= 1000", + "primes[i] is guaranteed to be a prime number.", + "All the values of primes are unique and sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, primes = [2,7,13,19]\nOutput:32\nExplanation:[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].", + "image": null + }, + { + "text": "Example 2: Input:n = 1, primes = [2,3,5]\nOutput:1\nExplanation:1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].", + "image": null + } + ], + "follow_up": null, + "solution": "//---------------------O(nlogk)-------------------------\n\nclass Solution {\n public int nthSuperUglyNumber(int n, int[] primes) {\n int []dp=new int[n+1];\n dp[1]=1;\n \n PriorityQueue pq=new PriorityQueue<>();\n \n for(int i=0;i0){\n pq.add(new Pair(curr.prime, curr.ptr+1,newval));\n }\n }\n \n return dp[n];\n }\n}\n\nclass Pair implements Comparable{\n int prime;\n int ptr;\n int val;\n \n public Pair(int prime, int ptr, int val){\n this.prime=prime;\n this.ptr=ptr;\n this.val=val;\n }\n \n public int compareTo(Pair o){\n return this.val-o.val;\n }\n}\n\n//-----------------------O(nk)---------------------------\n\n// class Solution {\n// public int nthSuperUglyNumber(int n, int[] primes) {\n// int []dp=new int[n+1];\n// dp[1]=1;\n \n// int []ptr=new int[primes.length];\n \n// Arrays.fill(ptr,1);\n \n// for(int i=2;i<=n;i++){\n \n// int min=Integer.MAX_VALUE;\n \n// for(int j=0;j0){\n// min=Math.min(min,val);\n// }\n \n// }\n \n// dp[i]=min;\n \n// for(int j=0;j0 && min==val){\n// ptr[j]++;\n// }\n// }\n// }\n \n// return dp[n];\n// }\n// }\n", + "title": "313. Super Ugly Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes . Given an integer n and an array of integers primes , return the n th super ugly number . The n th super ugly number is guaranteed to fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= primes.length <= 100", + "2 <= primes[i] <= 1000", + "primes[i] is guaranteed to be a prime number.", + "All the values of primes are unique and sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, primes = [2,7,13,19]\nOutput:32\nExplanation:[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].", + "image": null + }, + { + "text": "Example 2: Input:n = 1, primes = [2,3,5]\nOutput:1\nExplanation:1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n prime_nums = len(primes)\n index = [1]*prime_nums\n ret = [1]*(n+1)\n for i in range(2,n+1):\n ret[i] = min(primes[j]*ret[index[j]] for j in range(prime_nums))\n for k in range(prime_nums):\n if ret[i] == primes[k]*ret[index[k]]:\n index[k]+= 1\n \n return ret[-1]\n", + "title": "313. Super Ugly Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m ( 1 <= m <= n ) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses . If it is not possible to do it, return -1 .", + "description_images": [], + "constraints": [ + "n == machines.length", + "1 <= n <= 10^4", + "0 <= machines[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:machines = [1,0,5]\nOutput:3\nExplanation:1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2", + "image": null + }, + { + "text": "Example 2: Input:machines = [0,3,0]\nOutput:2\nExplanation:1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1", + "image": null + }, + { + "text": "Example 3: Input:machines = [0,2,0]\nOutput:-1\nExplanation:It's impossible to make all three washing machines have the same number of dresses.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.60 MB (Top 13.21%)\n\nclass Solution {\n public int findMinMoves(int[] machines) {\n int avg = 0;\n\n for(int i = 0; i < machines.length; i++){\n avg += machines[i];\n \n }\n\n if(avg % machines.length != 0){\n return -1;\n }\n\n int res = 0, cnt = 0;\n avg = avg / machines.length;\n for (int m : machines) {\n cnt += m - avg;\n res = Math.max(res, Math.max(Math.abs(cnt), m - avg));\n }\n return res;\n }\n}\n", + "title": "517. Super Washing Machines", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m ( 1 <= m <= n ) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses . If it is not possible to do it, return -1 .", + "description_images": [], + "constraints": [ + "n == machines.length", + "1 <= n <= 10^4", + "0 <= machines[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:machines = [1,0,5]\nOutput:3\nExplanation:1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2", + "image": null + }, + { + "text": "Example 2: Input:machines = [0,3,0]\nOutput:2\nExplanation:1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1", + "image": null + }, + { + "text": "Example 3: Input:machines = [0,2,0]\nOutput:-1\nExplanation:It's impossible to make all three washing machines have the same number of dresses.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 170 ms (Top 20.15%) | Memory: 15 MB (Top 44.78%)\nfrom itertools import accumulate\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n n = len(machines)\n summation = sum(machines)\n if summation%n:\n return -1\n avg = summation//n\n left = list(accumulate(machines))\n result = 0\n for i in range(n):\n move_to_right = max(left[i] - (i+1)*avg, 0)\n move_to_left = max(left[-1]-(left[i-1] if i!=0 else 0) - (n-i)*avg, 0)\n result = max(result, move_to_right + move_to_left)\n return result\n", + "title": "517. Super Washing Machines", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j) . After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes . Note: The bottom face of each shape counts toward its surface area.", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]\nOutput:34", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid2.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:32", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid4.jpg" + }, + { + "text": "Example 3: Input:grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput:46", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid5.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 63.77%) | Memory: 44.7 MB (Top 34.78%)\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n int n = grid.length;\n for(int i=0; i int: \n m, n = len(grid), len(grid[0])\n \n area = 0\n for r in range(m): \n for c in range(n):\n if grid[r][c] != 0:\n area += 2\n \n if r == 0 or r == m - 1:\n area += grid[r][c] if m != 1 else 2*grid[r][c]\n if r != m - 1: \n area += abs(grid[r][c] - grid[r+1][c])\n \n if c == 0 or c == n - 1:\n area += grid[r][c] if n != 1 else 2*grid[r][c]\n if c != n - 1: \n area += abs(grid[r][c] - grid[r][c+1]) \n \n return area", + "title": "892. Surface Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix board containing 'X' and 'O' , capture all regions that are 4-directionally surrounded by 'X' . A region is captured by flipping all 'O' s into 'X' s in that surrounded region.", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is 'X' or 'O' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nOutput:[[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nExplanation:Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" + }, + { + "text": "Example 2: Input:board = [[\"X\"]]\nOutput:[[\"X\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 54.99%) | Memory: 51.8 MB (Top 39.25%)\nclass Solution {\n boolean isClosed = true;\n\n public void solve(char[][] board) {\n int m = board.length;\n int n = board[0].length;\n\n // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value\n for(int i=0; i= board.length || j>=board[0].length || board[i][j] != 'O') return;\n\n board[i][j] = 'T'; // to put a temperory mark/ to mark as visited\n\n dfs(board, i, j+1); // Top\n dfs(board, i, j-1); // Bottom\n dfs(board, i+1, j); // Right\n dfs(board, i-1, j); // Left\n }\n}", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix board containing 'X' and 'O' , capture all regions that are 4-directionally surrounded by 'X' . A region is captured by flipping all 'O' s into 'X' s in that surrounded region.", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is 'X' or 'O' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nOutput:[[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nExplanation:Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" + }, + { + "text": "Example 2: Input:board = [[\"X\"]]\nOutput:[[\"X\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "# The question is an awesome example of multi-source bfs.\n# The intuition is to add the boundary to a heap if it is 'O'.\n# Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start\n# convertin all these 'O's to 'E's. \n# The last step is to traverse the matrix and if the element is still 'O' turn it to 'X' if it is 'E' turn it to 'O' and we get our answer.\n# Pro-Tip -> Try to reduce the number of append operations in python. The lesser the append operations the better is the runtime!\nfrom collections import deque\nclass Solution:\n def solve(self, bb: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n heap = deque()\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n r, c = len(bb), len(bb[0])\n for i in range(r):\n if bb[i][0] == 'O': heap.append((i, 0))\n if bb[i][c - 1] == 'O': heap.append((i, c - 1))\n for i in range(1, c - 1):\n if bb[0][i] == 'O': heap.append((0, i))\n if bb[r - 1][i] == 'O': heap.append((r - 1, i))\n visited = set()\n def isValid(nr, nc):\n if 0 <= nr < r and 0 <= nc < c: return True\n else: return False\n while heap:\n ri, ci = heap.popleft()\n bb[ri][ci] = 'E'\n for i, j in directions:\n nr, nc = ri + i, ci + j\n if isValid(nr, nc) and (nr, nc) not in visited and bb[nr][nc] == 'O':\n heap.append((nr, nc))\n visited.add((nr, nc))\n for i in range(r):\n for j in range(c):\n if bb[i][j] == 'O':\n bb[i][j] = 'X'\n if bb[i][j] == 'E':\n bb[i][j] = 'O'\n \n", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a string composed of 'L' , 'R' , and 'X' characters, like \"RXXLRXRXL\" , a move consists of either replacing one occurrence of \"XL\" with \"LX\" , or replacing one occurrence of \"RX\" with \"XR\" . Given the starting string start and the ending string end , return True if and only if there exists a sequence of moves to transform one string to the other.", + "description_images": [], + "constraints": [ + "1 <= start.length <= 10^4", + "start.length == end.length", + "Both start and end will only consist of characters in 'L' , 'R' , and 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput:true\nExplanation:We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX", + "image": null + }, + { + "text": "Example 2: Input:start = \"X\", end = \"L\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 5.17%) | Memory: 82 MB (Top 5.24%)\nclass Solution {\n public boolean canTransform(String start, String end) {\n int startL = 0, startR = 0;\n int endL = 0, endR = 0;\n String stLR = \"\", edLR = \"\";\n for(int i = 0; i < start.length(); i++) {\n if(start.charAt(i) != 'X') {\n if(start.charAt(i) == 'L') {\n startL++;\n } else{\n startR++;\n }\n stLR+= start.charAt(i);\n }\n if(end.charAt(i) != 'X') {\n if(end.charAt(i) == 'L') {\n endL++;\n } else{\n endR++;\n }\n edLR += end.charAt(i);\n }\n\n if(startL > endL || startR < endR) //Check conditions at each instant\n return false;\n }\n\n if(startL != endL || startR != endR || !stLR.equals(edLR)) //check their final count and positions\n return false;\n\n return true;\n }\n\n}", + "title": "777. Swap Adjacent in LR String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a string composed of 'L' , 'R' , and 'X' characters, like \"RXXLRXRXL\" , a move consists of either replacing one occurrence of \"XL\" with \"LX\" , or replacing one occurrence of \"RX\" with \"XR\" . Given the starting string start and the ending string end , return True if and only if there exists a sequence of moves to transform one string to the other.", + "description_images": [], + "constraints": [ + "1 <= start.length <= 10^4", + "start.length == end.length", + "Both start and end will only consist of characters in 'L' , 'R' , and 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput:true\nExplanation:We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX", + "image": null + }, + { + "text": "Example 2: Input:start = \"X\", end = \"L\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canTransform(self, start: str, end: str) -> bool:\n def chars(s):\n for i, c in enumerate(s):\n if c != 'X':\n yield i, c\n \n yield -1, ' '\n \n for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):\n if (startC != endC or\n (startC == 'L' and startI < endI) or\n (startC == 'R' and startI > endI)):\n return False\n \n return True", + "title": "777. Swap Adjacent in LR String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string text . You can swap two of the characters in the text . Return the length of the longest substring with repeated characters .", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2 * 10^4", + "text consist of lowercase English characters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ababa\"\nOutput:3\nExplanation:We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aaabaaa\"\nOutput:6\nExplanation:Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.", + "image": null + }, + { + "text": "Example 3: Input:text = \"aaaaa\"\nOutput:5\nExplanation:No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 27.8%) | Memory: 41.85 MB (Top 50.9%)\n\nclass Solution {\n\t\tpublic int maxRepOpt1(String s) {\n\t\t int[] count = new int[26];\n\t\t int[] left = new int[s.length()];\n\t\t int[] right = new int[s.length()];\n\t\t\tint max =0;\n\t\t\t// Left Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=0;i 0){\n\t\t\t\t\tif(s.charAt(i) == s.charAt(i-1)){\n\t\t\t\t\t\tleft[i] = left[i-1]+1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleft[i] = 1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tleft[i] =1;\n\t\t\t\t}\n\t\t\t\tmax = Math.max(max,left[i]);\n\t\t\t}\n\t\t\t// Right Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=s.length()-1;i>=0;i--){\n\t\t\t\tif(i < s.length()-1){\n\t\t\t\t\tif(s.charAt(i+1) == s.charAt(i)){\n\t\t\t\t\t\tright[i] = right[i+1] +1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tright[i] =1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tright[i] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Count The Length Of SubString Having Maximum Length When A Character Is Swapped\n\t\t\tfor(int i=1 ; i int:\n char_groups = []\n \n for char, group in groupby(text):\n group_len = len(list(group))\n char_groups.append((char, group_len))\n \n char_count = Counter(text)\n \n longest_substr_len = 1 # Each char itself is substring of len 1\n \n # Scenario-1: Get the longest substr length by just adding one more char to each group\n for char, group_len in char_groups:\n # NOTE: If the total count of the char across full string is < group_len+1,\n # make sure to take the total count only\n #\n # It means we don't have any extra char occurrence which we can add to the current group\n \n group_len_w_one_addition = min(group_len+1, char_count[char])\n longest_substr_len = max(longest_substr_len, group_len_w_one_addition)\n \n \n # Scenario-2: \n # If there are two groups of same char, separated by a group of different char with length=1:\n # 1) We can either swap that one char in the middle with the same char as those two groups \n # Ex: 'aaa b aaa c a'\n # - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index\n # - So after swapping, it will become 'aaa a aaa c b' \n # - hence longest substr len of same char 'a' = 7\n #\n # 2) We can merge the two groups\n # Ex: 'aaa b aaa' \n # -> here there are two groups of char 'a' with len = 3 each.\n # -> they are separated by a group of char 'b' with len = 1\n # -> hence, we can merge both groups of char 'a' - so that longest substr len = 6\n # -> basically, swap the 'b' with 'a' at very last index\n # -> the final string will look like 'aaaaaa b'\n #\n # We will take max length we can get from above two options.\n #\n # Since we need to check the group prior to curr_idx \"i\" and also next to curr_idx \"i\";\n # we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive\n \n for i in range(1, len(char_groups)-1):\n prev_group_char, prev_group_len = char_groups[i-1]\n curr_group_char, curr_group_len = char_groups[i]\n next_group_char, next_group_len = char_groups[i+1]\n \n if curr_group_len != 1 or prev_group_char != next_group_char:\n continue\n \n len_after_swapping = min(prev_group_len + next_group_len + 1, char_count[next_group_char])\n longest_substr_len = max(longest_substr_len, len_after_swapping)\n \n return longest_substr_len\n", + "title": "1156. Swap For Longest Repeated Character Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]\nOutput:[2,1,4,3]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + }, + { + "text": "Example 2: Input:head = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 55.04%)\n\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0) , prev = dummy , curr = head;\n dummy.next = head;\n while(curr != null && curr.next != null){\n prev.next = curr.next;\n curr.next = curr.next.next ;\n prev.next.next = curr;\n curr = curr.next ;\n prev = prev.next.next;\n }\n return dummy.next;\n }\n}\n", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]\nOutput:[2,1,4,3]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + }, + { + "text": "Example 2: Input:head = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1]\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 43.62%) | Memory: 17.40 MB (Top 6.56%)\n\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\n if not head or not head.next: return head\n\n dummy = ListNode(0)\n dummy.next = head\n curr = dummy\n\n while curr.next and curr.next.next:\n first = curr.next\n second = curr.next.next\n curr.next = second\n first.next = second.next\n second.next = first\n curr = curr.next.next\n \n return dummy.next\n", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 ).", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 10^5", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" + }, + { + "text": "Example 2: Input:head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput:[7,9,6,6,8,7,3,0,9,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 56.9 MB (Top 96.11%)\nclass Solution {\n public ListNode swapNodes(ListNode head, int k) {\n ListNode fast = head;\n ListNode slow = head;\n ListNode first = head, second = head;\n\n // Put fast (k-1) nodes after slow\n for(int i = 0; i < k - 1; ++i)\n fast = fast.next;\n\n // Save the node for swapping\n first = fast;\n\n // Move until the end of the list\n while(fast.next != null) {\n slow = slow.next;\n fast = fast.next;\n }\n\n // Save the second node for swapping\n // Note that the pointer second isn't necessary: we could use slow for swapping as well\n // However, having second improves readability\n second = slow;\n\n // Swap values\n int temp = first.val;\n first.val = second.val;\n second.val = temp;\n\n return head;\n }\n}", + "title": "1721. Swapping Nodes in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 ).", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 10^5", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" + }, + { + "text": "Example 2: Input:head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput:[7,9,6,6,8,7,3,0,9,5]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 784 ms (Top 40.9%) | Memory: 50.79 MB (Top 42.2%)\n\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n tot = 0 # initialise total\n Head = head\n while Head: # count total nodes\n Head = Head.next # move forward\n tot += 1 # incerse count by one for each node\n one, two = None, None # two pointers of one and two\n count = 1 # we're initialising to one because we have one based index for swapping\n Head = head # regain original head to traverse\n while Head:\n if one and two: break # if we have both one and two then break loop to save time\n if count == k: # if from forward we reach at node k then it's our first node\n one = Head\n if count == (tot-k+1): # if from backward we reach to node k then save it\n two = Head\n Head = Head.next # move further\n count += 1 # increse count\n one.val, two.val = two.val, one.val # now swap values\n return head # return head", + "title": "1721. Swapping Nodes in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j) . The rain starts to fall. At time t , the depth of the water everywhere is t . 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 least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0) .", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] < n 2", + "Each value grid[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2],[1,3]]\nOutput:3\n\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg" + }, + { + "text": "Example 2: 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]]\nOutput:16\nExplanation:The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int swimInWater(int[][] grid) {\n int len = grid.length;\n Map reverseMap = new HashMap<>();\n for (int i = 0; i < len; i++) {\n for (int j = 0; j < len; j++) {\n reverseMap.put(grid[i][j], new int[] { i, j });\n }\n }\n \n int left = grid[0][0]; // answer cannot be less than value of starting position\n int right = len * len - 1;\n \n int ans = right;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (canSwim(grid, reverseMap, mid, len)) {\n ans = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n \n return ans;\n }\n \n boolean canSwim(int[][] grid, Map reverseIndex, int ans, int len) {\n int[] x_diff = { 1, -1, 0, 0 };\n int[] y_diff = { 0, 0, 1, -1 };\n \n // BFS\n Queue container = new LinkedList<>();\n container.add(new int[] { 0, 0 });\n \n boolean[][] visited = new boolean[grid.length][grid[0].length];\n visited[0][0] = true;\n \n while (!container.isEmpty()) {\n int[] curr = container.poll();\n int currVal = grid[curr[0]][curr[1]];\n for (int i = 0; i < 4; i++) {\n int newX = curr[0] + x_diff[i];\n int newY = curr[1] + y_diff[i];\n if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) {\n if (newX == grid.length-1 && newY == grid[0].length-1) {\n return true;\n }\n visited[newX][newY] = true;\n container.add(new int[] { newX, newY });\n }\n } \n }\n \n return false;\n }\n \n boolean isValidCell(int[][] grid, int x, int y, int ans) {\n\t // check boundary and if grid elevation is greater than evaluated answer\n return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans);\n }\n}\n", + "title": "778. Swim in Rising Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j) . The rain starts to fall. At time t , the depth of the water everywhere is t . 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 least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0) .", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] < n 2", + "Each value grid[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2],[1,3]]\nOutput:3\n\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg" + }, + { + "text": "Example 2: 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]]\nOutput:16\nExplanation:The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 94 ms (Top 84.44%) | Memory: 17.90 MB (Top 8.02%)\n\nclass DSU(object):\n def __init__(self, N):\n self.par = list(range(N))\n self.rnk = [0] * N\n\n def find(self, x):\n if self.par[x] != x:\n self.par[x] = self.find(self.par[x])\n return self.par[x]\n\n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n elif self.rnk[xr] < self.rnk[yr]:\n self.par[xr] = yr\n elif self.rnk[xr] > self.rnk[yr]:\n self.par[yr] = xr\n else:\n self.par[yr] = xr\n self.rnk[xr] += 1\n return True\n\nclass Solution:\n def swimInWater(self, grid):\n d, N = {}, len(grid)\n for i,j in product(range(N), range(N)):\n d[grid[i][j]] = (i, j)\n \n dsu = DSU(N*N)\n grid = [[0] * N for _ in range(N)] \n neib_list = [[0,1],[0,-1],[1,0],[-1,0]]\n \n for i in range(N*N):\n x, y = d[i]\n grid[x][y] = 1\n for dx, dy in neib_list:\n if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1:\n dsu.union((x+dx)*N + y + dy, x*N + y)\n \n if dsu.find(0) == dsu.find(N*N-1): return i\n", + "title": "778. Swim in Rising Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.02%) | Memory: 42.7 MB (Top 25.40%)\nclass Solution {\n public boolean isSymmetric(TreeNode root) {\n return isSymmetric(root.left,root.right);\n }\n\n public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) {\n if(rootLeft == null && rootRight == null) {return true;}\n if(rootLeft == null || rootRight == null) {return false;}\n if (rootLeft.val != rootRight.val) {return false;}\n else\n return isSymmetric(rootLeft.right, rootRight.left) && isSymmetric(rootLeft.left, rootRight.right);\n }\n}", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 60.40%) | Memory: 13.9 MB (Top 94.25%)\n\nclass Solution:\n def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n return root is None or self.findSymmetric(root.left, root.right)\n\n def findSymmetric(self, left, right):\n if (left is None or right is None):\n return left == right\n\n if (left.val != right.val):\n return False\n\n return self.findSymmetric(left.left, right.right) and self.findSymmetric(left.right, right.left)", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:", + "description_images": [], + "constraints": [ + "1 <= code.length <= 500", + "code consists of English letters, digits, '<' , '>' , '/' , '!' , '[' , ']' , '.' , and ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:code = \"
This is the first line ]]>
\"\nOutput:true\nExplanation:The code is wrapped in a closed tag :
and
. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.", + "image": null + }, + { + "text": "Example 2: Input:code = \"
>> ![cdata[]] ]>]]>]]>>]
\"\nOutput:true\nExplanation:We first separate the code into : start_tag|tag_content|end_tag.\nstart_tag ->\"
\"end_tag ->\"
\"tag_content could also be separated into : text1|cdata|text2.\ntext1 ->\">> ![cdata[]] \"cdata ->\"]>]]>\", where the CDATA_CONTENT is\"
]>\"text2 ->\"]]>>]\"The reason why start_tag is NOT\"
>>\"is because of the rule 6.\nThe reason why cdata is NOT\"]>]]>]]>\"is because of the rule 7.", + "image": null + }, + { + "text": "Example 3: Input:code = \" \"\nOutput:false\nExplanation:Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 66.89%) | Memory: 41.9 MB (Top 78.38%)\nclass Solution {\n // for the ease to check CDATA starting tag\n private static final char[] CDATA_TAG = {'[','C','D','A','T','A','['};\n public boolean isValid(String code) {\n // make sure it is possible to have a start tag and an end tag\n if (!code.startsWith(\"<\") || !code.endsWith(\">\")) {\n return false;\n }\n Deque stack = new ArrayDeque<>();\n for (int i = 0; i < code.length(); ++i) {\n char ch = code.charAt(i);\n // if it is a special tag\n if (ch == '<') {\n if (i == code.length() - 1) {\n return false;\n }\n ch = code.charAt(++i);\n // is end tag\n if (ch == '/') {\n // we should have a start tag to match the end tag\n if (stack.isEmpty()) {\n return false;\n }\n // get the end tag\n StringBuilder sb = new StringBuilder();\n // build tag and move i to the > for the next round\n i = buildTag(code, i + 1, sb);\n // if tag is unmatch, return false\n if (!stack.pop().equals(sb.toString())) {\n return false;\n }\n // if no start tag left and we are not at the end. The rest content is not enclosed. -> false\n if (stack.isEmpty() && i < code.length() - 1) {\n return false;\n }\n } else if (ch == '!') { // is CDATA tag\n // check if CDATA is encoded in a tag\n if (stack.isEmpty()) {\n return false;\n }\n // check CDATA and move i to the end of ]]> for the next round\n i = validAndMoveCDATA(code, i + 1);\n // the above function return -1 if CDATA is not valid\n if (i < 0) {\n return false;\n }\n } else { // start tag\n // TAG_NAME should not empty\n if (ch == '>') {\n return false;\n }\n StringBuilder sb = new StringBuilder();\n i = buildTag(code, i , sb);\n // TAG_NAME should less than 9\n if (sb.isEmpty() || sb.length() > 9) {\n return false;\n }\n stack.push(sb.toString());\n }\n }\n }\n return stack.isEmpty();\n }\n\n private int buildTag(String code, int start, StringBuilder sb) {\n int i = start;\n // we only go to 10 because the max length is 9\n for (; i < start + 10 && i < code.length(); ++i) {\n char ch = code.charAt(i);\n // find the end;\n if (ch == '>') {\n break;\n }\n // TAG_NAME should be in uppercase only\n if (!Character.isUpperCase(ch)) {\n // clear the string builder for invalid TAG_NAME\n sb.setLength(0);\n break;\n }\n sb.append(ch);\n }\n return i;\n }\n\n private int validAndMoveCDATA(String code, int start) {\n // the length of [CDATA[]]> is 10 we need at least 10 characters left\n if (code.length() - start < 10) {\n return -1;\n }\n // check the start part\n int i = start;\n for (int j = 0; j < CDATA_TAG.length; ++j) {\n char ch = code.charAt(i++);\n if (ch != CDATA_TAG[j]) {\n return -1;\n }\n }\n // keep the last two characters for identifying the end\n char prev0 = '\\0';\n char prev1 = '\\0';\n\n for (; i < code.length(); ++i) {\n char ch = code.charAt(i);\n if (ch == '>' && prev1 == ']' && prev0 == ']') {\n return i;\n }\n prev0 = prev1;\n prev1 = ch;\n }\n // no end found\n return -1;\n }\n}", + "title": "591. Tag Validator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:", + "description_images": [], + "constraints": [ + "1 <= code.length <= 500", + "code consists of English letters, digits, '<' , '>' , '/' , '!' , '[' , ']' , '.' , and ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:code = \"
This is the first line ]]>
\"\nOutput:true\nExplanation:The code is wrapped in a closed tag :
and
. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.", + "image": null + }, + { + "text": "Example 2: Input:code = \"
>> ![cdata[]] ]>]]>]]>>]
\"\nOutput:true\nExplanation:We first separate the code into : start_tag|tag_content|end_tag.\nstart_tag ->\"
\"end_tag ->\"
\"tag_content could also be separated into : text1|cdata|text2.\ntext1 ->\">> ![cdata[]] \"cdata ->\"]>]]>\", where the CDATA_CONTENT is\"
]>\"text2 ->\"]]>>]\"The reason why start_tag is NOT\"
>>\"is because of the rule 6.\nThe reason why cdata is NOT\"]>]]>]]>\"is because of the rule 7.", + "image": null + }, + { + "text": "Example 3: Input:code = \" \"\nOutput:false\nExplanation:Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != '<' or code[-1] != '>': return False\n i, n = 0, len(code)\n stk = []\n while i < n:\n if code[i] == '<':\n if i != 0 and code[i: i + 9] == '': j += 1\n if code[j: j + 3] == ']]>': i = j + 3\n else: return False\n else:\n start = i\n isend = False\n i += 1\n if i >= n: return False\n if code[i] == r'/':\n isend = True\n i += 1\n if i >= n: return False\n tag = ''\n while i < n and code[i] != '>':\n if not code[i].isupper(): return False\n tag += code[i]\n i += 1\n if i >= n or len(tag) == 0 or len(tag) > 9: return False\n if isend:\n if not stk or stk[-1] != tag: return False\n stk.pop(-1)\n else:\n if start != 0 and not stk: return False\n stk.append(tag)\n i += 1\n else:\n if not stk: return False\n while i < n and code[i] != '<': i += 1\n return not stk\n", + "title": "591. Tag Validator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1 , 2 , and 3 , you can weld them together to make a support of length 6 . Return the largest possible height of your billboard installation . If you cannot support the billboard, return 0 .", + "description_images": [], + "constraints": [ + "1 <= rods.length <= 20", + "1 <= rods[i] <= 1000", + "sum(rods[i]) <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:rods = [1,2,3,6]\nOutput:6\nExplanation:We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:rods = [1,2,3,4,5,6]\nOutput:10\nExplanation:We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.", + "image": null + }, + { + "text": "Example 3: Input:rods = [1,2]\nOutput:0\nExplanation:The billboard cannot be supported, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tallestBillboard(int[] rods) {\n int[] result = new int[1];\n dfs(rods, 0, 0, 0, rods.length, result);\n return result[0];\n }\n private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {\n if (level == n) {\n if (left == right) {\n result[0] = Math.max(left, result[0]);\n }\n return;\n }\n \n dfs(rods, left, right, level + 1, n, result);\n dfs(rods, left + rods[level], right, level + 1, n, result);\n dfs(rods, left, right + rods[level], level + 1, n, result);\n }\n}\n", + "title": "956. Tallest Billboard", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1 , 2 , and 3 , you can weld them together to make a support of length 6 . Return the largest possible height of your billboard installation . If you cannot support the billboard, return 0 .", + "description_images": [], + "constraints": [ + "1 <= rods.length <= 20", + "1 <= rods[i] <= 1000", + "sum(rods[i]) <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:rods = [1,2,3,6]\nOutput:6\nExplanation:We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:rods = [1,2,3,4,5,6]\nOutput:10\nExplanation:We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.", + "image": null + }, + { + "text": "Example 3: Input:rods = [1,2]\nOutput:0\nExplanation:The billboard cannot be supported, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 760 ms (Top 68.15%) | Memory: 14.5 MB (Top 56.05%)\n\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n dp = collections.defaultdict(int)\n dp[0] = 0\n for x in rods:\n nxt = dp.copy()\n for d, y in dp.items():\n # init state\n # ------|----- d -----| # tall side\n # - y --| # low side\n\n # put x to tall side\n # ------|----- d -----|---- x --|\n # - y --|\n nxt[d + x] = max(nxt.get(x + d, 0), y)\n\n nxt[abs(d - x)] = max(nxt.get(abs(d - x), 0), y + min(d, x))\n dp = nxt\n return dp[0]", + "title": "956. Tallest Billboard", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Return the number of different expressions that you can build, which evaluates to target .", + "description_images": [], + "constraints": [ + "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\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 3\nOutput:5\nExplanation:There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 89.09%) | Memory: 42.70 MB (Top 55.56%)\n\nclass Solution {\n public int findTargetSumWays(int[] nums, int target) {\n //Solution 1\n int sum = 0;\n for(int x : nums)\n sum += x;\n if(((sum - target) % 2 == 1) || (target > sum))\n return 0;\n \n int n = nums.length;\n int s2 = (sum - target)/2;\n int[][] t = new int[n + 1][s2 + 1];\n t[0][0] = 1;\n \n for(int i = 1; i < n + 1; i++) {\n for(int j = 0; j < s2 + 1; j++) {\n if(nums[i - 1] <= j)\n t[i][j] = t[i-1][j] + t[i - 1][j - nums[i - 1]];\n else\n t[i][j] = t[i - 1][j];\n }\n }\n return t[n][s2];\n \n //Solution 2\n// int sum = 0;\n// for(int x : nums)\n// sum += x;\n// if(((sum - target) % 2 != 0) || (target > sum))\n// return 0;\n \n// int n = nums.length;\n// int s2 = (sum - target)/2;\n \n// int[][] t = new int[n + 1][s2 + 1];\n// for(int i = 0; i < n + 1; i++) {\n// for(int j = 0; j < s2 + 1; j++) {\n// if(i == 0)\n// t[i][j] = 0;\n// if(j == 0)\n// t[i][j] = 1;\n// }\n// }\n \n// for(int i = 1; i < n + 1; i++) {\n// for(int j = 1; j < s2 + 1; j++) {\n// if((nums[i - 1] > j) || (nums[i - 1] == 0))\n// t[i][j] = t[i - 1][j];\n// else\n// t[i][j] = t[i - 1][j] + t[i - 1][j - nums[i - 1]];\n// }\n// }\n \n// int count = 0;\n// for(int x : nums)\n// if(x == 0)\n// count++;\n \n// return (int)(Math.pow(2,count)) * t[n][s2];\n }\n}\n", + "title": "494. Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Return the number of different expressions that you can build, which evaluates to target .", + "description_images": [], + "constraints": [ + "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\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 3\nOutput:5\nExplanation:There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTargetSumWays(self, nums: List[int], target: int) -> int:\n @cache\n def dfs(i, sum_):\n if i == len(nums):\n if sum_ == target: return 1\n else: return 0\n return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i])\n if abs(target) > sum(nums): return 0\n return dfs(0, 0)\n", + "title": "494. Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a characters array tasks , representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks .", + "description_images": [], + "constraints": [ + "1 <= task.length <= 10^4", + "tasks[i] is upper-case English letter.", + "The integer n is in the range [0, 100] ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2\nOutput:8\nExplanation:A -> B -> idle -> A -> B -> idle -> A -> B\nThere is at least 2 units of time between any two same tasks.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 0\nOutput:6\nExplanation:On this case any permutation of size 6 would work since n = 0.\n[\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"]\n[\"A\",\"B\",\"A\",\"B\",\"A\",\"B\"]\n[\"B\",\"B\",\"B\",\"A\",\"A\",\"A\"]\n...\nAnd so on.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], n = 2\nOutput:16\nExplanation:One possible solution is\nA -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1043 ms (Top 25.15%) | Memory: 14.3 MB (Top 64.15%)\n\nclass Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n max_heap = []\n queue = deque()\n word_count = defaultdict(int)\n timer = 0\n for i in range(len(tasks)):\n word_count[tasks[i]] += 1\n for _ , val in word_count.items():\n heappush(max_heap, -1*val)\n while max_heap or queue:\n timer += 1\n if max_heap:\n v = -1* heappop(max_heap)\n v -= 1\n if v:\n queue.append((v, timer+n))\n if queue and queue[0][1] == timer:\n heappush(max_heap, -1*queue.popleft()[0])\n return timer", + "title": "621. Task Scheduler", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array of positive integers tasks , representing tasks that need to be completed in order , where tasks[i] represents the type of the i th task. You are also given a positive integer space , which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Return the minimum number of days needed to complete all tasks .", + "description_images": [], + "constraints": [ + "Complete the next task from tasks , or", + "Take a break." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,1,2,3,1], space = 3\nOutput:9\nExplanation:One way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,8,8,5], space = 2\nOutput:6\nExplanation:One way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long taskSchedulerII(int[] tasks, int space) {\n HashMap map = new HashMap<>();\n long day = 0;\n\n for (int item : tasks) {\n if (map.containsKey(item) && map.get(item) > day)\n day = map.get(item);\n\n day++;\n map.put(item, day + space);\n }\n\n return day;\n }\n}\n", + "title": "2365. Task Scheduler II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed array of positive integers tasks , representing tasks that need to be completed in order , where tasks[i] represents the type of the i th task. You are also given a positive integer space , which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Return the minimum number of days needed to complete all tasks .", + "description_images": [], + "constraints": [ + "Complete the next task from tasks , or", + "Take a break." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,1,2,3,1], space = 3\nOutput:9\nExplanation:One way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,8,8,5], space = 2\nOutput:6\nExplanation:One way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2321 ms (Top 5.03%) | Memory: 29.8 MB (Top 75.04%)\nimport math\nclass Solution:\n def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n count_dict = {}\n total_days = 0\n for task in tasks:\n if task not in count_dict:\n count_dict[task] = -math.inf\n total_days = max(total_days + 1, count_dict[task] + space + 1)\n count_dict[task] = total_days\n return total_days", + "title": "2365. Task Scheduler II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1] . If Teemo attacks again before the poison effect ends, the timer for it is reset , and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries , where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i] , and an integer duration . Return the total number of seconds that Ashe is poisoned .", + "description_images": [], + "constraints": [ + "1 <= timeSeries.length <= 10^4", + "0 <= timeSeries[i], duration <= 10^7", + "timeSeries is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:timeSeries = [1,4], duration = 2\nOutput:4\nExplanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.", + "image": null + }, + { + "text": "Example 2: Input:timeSeries = [1,2], duration = 2\nOutput:3\nExplanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.", + "image": null + } + ], + "follow_up": null, + "solution": "// Teemo Attacking\n// https://leetcode.com/problems/teemo-attacking/\n\nclass Solution {\n public int findPoisonedDuration(int[] timeSeries, int duration) {\n int sum = 0;\n for (int i = 0; i < timeSeries.length; i++) {\n if (i == 0) {\n sum += duration;\n } else {\n sum += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);\n }\n }\n return sum; \n }\n}\n", + "title": "495. Teemo Attacking", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1] . If Teemo attacks again before the poison effect ends, the timer for it is reset , and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries , where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i] , and an integer duration . Return the total number of seconds that Ashe is poisoned .", + "description_images": [], + "constraints": [ + "1 <= timeSeries.length <= 10^4", + "0 <= timeSeries[i], duration <= 10^7", + "timeSeries is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:timeSeries = [1,4], duration = 2\nOutput:4\nExplanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.", + "image": null + }, + { + "text": "Example 2: Input:timeSeries = [1,2], duration = 2\nOutput:3\nExplanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n \n \"\"\"\n timeDur = (timeSeries[0], timeSeries[0] + duration - 1)\n i = 1\n total = 0\n while i < len(timeSeries):\n if timeSeries[i] > timeDur[1]:\n total += (timeDur[1] - timeDur[0] + 1)\n else:\n total += (timeSeries[i] - timeDur[0])\n timeDur = (timeSeries[i], timeSeries[i] + duration - 1)\n i += 1\n total += (timeDur[1] - timeDur[0] + 1)\n return total\n \n \"\"\"\n # Between two interval, Ashe can be poisoned only for max duration time,\n # if time differece is less than duranton, then we that value\n total = 0\n for i in range(len(timeSeries)-1):\n total += min(duration, timeSeries[i+1] - timeSeries[i])\n return total + duration\n \n", + "title": "495. Teemo Attacking", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\nOutput:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\nOutput:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]\nExplanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\nOutput:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 15.97%) | Memory: 42.1 MB (Top 76.75%)\nclass Solution {\n public List fullJustify(String[] words, int maxWidth) {\n List unBalanced = new ArrayList<>();\n List balanced = new ArrayList<>();\n int numSpaces = 0;\n\n StringBuffer sb = new StringBuffer();\n //Following code creates a list of unbalanced lines by appending words and 1 space between them\n for(String word : words){\n\n if(sb.length() == 0){\n sb.append(word);\n }else{\n if(sb.length() + 1 + word.length() <= maxWidth){\n sb.append(\" \"+word);\n }else{\n unBalanced.add(sb.toString());\n sb = new StringBuffer(word);\n }\n }\n\n }\n\n if(sb.length() >0){\n unBalanced.add(sb.toString());\n }\n\n for(int j = 0; j < unBalanced.size(); j++){\n String line = unBalanced.get(j);\n numSpaces = maxWidth - line.length();\n StringBuffer lineB = new StringBuffer(line);\n //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces\n if(j == unBalanced.size()-1 || !line.contains(\" \")){\n int tempSpaces = maxWidth - lineB.length();\n while(tempSpaces > 0){\n lineB.append(\" \");\n tempSpaces --;\n }\n balanced.add(lineB.toString());\n continue;\n };\n // The following block checks for each character and appends 1 space during each loop\n //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word\n while(numSpaces > 0){\n int i = 0;\n while(i < lineB.length() - 1){\n if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){\n lineB.insert(i+1, ' ');\n i++;\n numSpaces --;\n if(numSpaces == 0) break;\n }\n i++;\n }\n }\n balanced.add(lineB.toString());\n }\n\n return balanced;\n }\n}", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\nOutput:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\nOutput:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]\nExplanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\nOutput:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 59.19%) | Memory: 14 MB (Top 55.27%)\nclass Solution:\n def fullJustify(self, words: List[str], maxwidth: int) -> List[str]:\n curr = 0\n last = []\n res = []\n for i in words:\n if curr + len(i) + len(res) <= maxwidth:\n curr += len(i)\n res.append(i)\n else:\n last.append(res)\n curr = len(i)\n res = [i]\n last.append(res)\n ans = []\n for idx ,row in enumerate(last):\n x = maxwidth-len(\"\".join(row))\n t = len(row)-1\n if t == 0:\n ans.append(row[0] + \" \"*(x))\n elif idx != len(last)-1:\n spaces = x//t\n rem = x%t\n res = row[0]\n for i in row[1:]:\n temp = spaces\n if rem:\n temp += 1\n rem -= 1\n res = res + \" \"*temp + i\n # print(res, temp)\n ans.append(res)\n else:\n res = row[0]\n for i in row[1:]:\n res = res + ' '+i\n res = res + \" \"*(maxwidth-len(res))\n ans.append(res)\n\n return ans", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1 ). In each round, the i th player from the front of the row competes against the i th player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n , firstPlayer , and secondPlayer , return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively .", + "description_images": [], + "constraints": [ + "For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7 . Player 2 competes against player 6 . Player 4 automatically advances to the next round.", + "Player 1 competes against player 7 .", + "Player 2 competes against player 6 .", + "Player 4 automatically advances to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 11, firstPlayer = 2, secondPlayer = 4\nOutput:[3,4]\nExplanation:One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4", + "image": null + }, + { + "text": "Example 2: Input:n = 5, firstPlayer = 1, secondPlayer = 5\nOutput:[1,1]\nExplanation:The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n int firstPlayer,secondPlayer,n;\n boolean enumerate(ArrayList ret,int mask,int start,int end)\n {\n if(start>=end)\n {\n ret.add(mask);\n return false;\n }\n else\n {\n while((start=end)\n return enumerate(ret,mask,start+1,end-1);\n else if(start==firstPlayer&&end==secondPlayer)\n return true;\n else if(start==firstPlayer||start==secondPlayer)\n return enumerate(ret,mask|1< arr=new ArrayList();\n if(enumerate(arr,mask,start,end))\n return 1;\n else\n {\n int q=Integer.MAX_VALUE;\n for(int x:arr)\n q=Math.min(q,1+minDFS(x));\n return q;\n }\n } \n int maxDFS(int mask)\n {\n int start=0,end=n-1;\n ArrayList arr=new ArrayList();\n if(enumerate(arr,mask,start,end))\n return 1;\n else\n {\n int q=Integer.MIN_VALUE;\n for(int x:arr)\n q=Math.max(q,1+maxDFS(x));\n return q;\n }\n }\n\n public int[] earliestAndLatest(int n, int firstPlayer, int secondPlayer) \n {\n this.n=n;\n this.firstPlayer=firstPlayer-1;\n this.secondPlayer=secondPlayer-1;\n return new int[]{minDFS(0),maxDFS(0)}; \n }\n}\n", + "title": "1900. The Earliest and Latest Rounds Where Players Compete", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1 ). In each round, the i th player from the front of the row competes against the i th player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n , firstPlayer , and secondPlayer , return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively .", + "description_images": [], + "constraints": [ + "For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7 . Player 2 competes against player 6 . Player 4 automatically advances to the next round.", + "Player 1 competes against player 7 .", + "Player 2 competes against player 6 .", + "Player 4 automatically advances to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 11, firstPlayer = 2, secondPlayer = 4\nOutput:[3,4]\nExplanation:One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4", + "image": null + }, + { + "text": "Example 2: Input:n = 5, firstPlayer = 1, secondPlayer = 5\nOutput:[1,1]\nExplanation:The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef earliestAndLatest(self, n: int, first: int, second: int) -> List[int]:\n\t\tdef ceiling_of_log2(x: int) -> int:\n\t\t\t\"\"\" Return the ceiling of the integer log 2, i.e. index(MSB) - 1 + (1 if x not pow2) \"\"\"\n\t\t\tassert 0 < x < 0x100000000\n\t\t\t# Use power of 2 test. offset is 1 iff x is NOT a power of 2\n\t\t\toffset = 1 if (x & (x - 1)) != 0 else 0\n\t\t\tx |= (x >> 1)\n\t\t\tx |= (x >> 2)\n\t\t\tx |= (x >> 4)\n\t\t\tx |= (x >> 8)\n\t\t\tx |= (x >> 16)\n\t\t\t# Remove offset to get floor_of_log2. floor(log2(x)) + 1 == ceil(log2(x)) iff x not a power of 2.\n\t\t\treturn popcount(x) - 1 + offset\n\n\t\tdef popcount(x: int) -> int:\n\t\t\t\"\"\" Return the number of set bits in 32 bit unsigned x (Hamming weight) \"\"\"\n\t\t\tassert 0 <= x < 0x100000000\n\t\t\tx = x - ((x >> 1) & 0x55555555)\n\t\t\tx = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n\t\t\treturn (((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24\n\n\t\tdef count_trailing_zeroes(x: int) -> int:\n\t\t\t\"\"\" Return the number of trailing zeroes in 32 bit unsigned x > 0 (LSB + 1). This method is similar to\n\t\t\t\tbranchless binary search, but there are many other methods using the integer log2\"\"\"\n\t\t\tassert 0 < x < 0x100000000\n\t\t\tif x & 0x1: return 0 # odd x, quick break\n\t\t\tc = 1\n\t\t\tif (x & 0xffff) == 0:\n\t\t\t\tx >>= 16\n\t\t\t\tc += 16\n\t\t\tif (x & 0xff) == 0:\n\t\t\t\tx >>= 8\n\t\t\t\tc += 8\n\t\t\tif (x & 0xf) == 0:\n\t\t\t\tx >>= 4\n\t\t\t\tc += 4\n\t\t\tif (x & 0x3) == 0:\n\t\t\t\tx >>= 2\n\t\t\t\tc += 2\n\t\t\treturn c - (x & 0x1)\n\n\t\t# Base case, we can return instantly\n\t\tif first + second == n + 1: return [1, 1]\n\n\t\t# This ensures that 'first' is closer to the left than 'second' is to the right.\n\t\t# Also, crucially ensures that the sum of first and second is minimal among equivalent configs.\n\t\tif first + second >= n + 1: first, second = n + 1 - second, n + 1 - first\n\n\t\tfirst_plus_second = first + second\n\n\t\t# Special case if first + 1 == second, since we then need to find which round will have an even # of players\n\t\tif first + 1 != second and first_plus_second >= (n + 1) // 2 + 1:\n\t\t\tif first_plus_second == n:\n\t\t\t\t# If n is 4k + 2, first is 2k, and second is 2k+2, then parity of n also matters.\n\t\t\t\tif n % 4 == 2 and first + 2 == second:\n\t\t\t\t\t# Using n // 4 instead of n//4 + 1 because trailing_zeroes(x-1) = rounds until x is even\n\t\t\t\t\tans_earliest = 3 + count_trailing_zeroes(n // 4)\n\t\t\t\telse:\n\t\t\t\t\tans_earliest = 3 - (first % 2)\n\t\t\telse:\n\t\t\t\tans_earliest = 2\n\n\t\t# If we are in a special case: Players are too far left and close together to meet next round\n\t\telse:\n\t\t\tans_earliest = 1 + ceiling_of_log2((n + first_plus_second - 2) // (first_plus_second - 1))\n\t\t\tif first + 1 == second:\n\t\t\t\tans_earliest += count_trailing_zeroes(((n + (1 << (ans_earliest-1)) - 1) >> (ans_earliest-1)) - 1)\n\n\t\t# ceiling_of_log2 of n is the number of rounds left until there are exactly 2 players remaining, starting at n.\n\t\t# This implicitly assumes that optimal strategy for ans_latest is moving 'first' and 'second' to pos. 1 and 2\n\t\tans_latest = min(ceiling_of_log2(n), n + 1 - second)\n\n\t\treturn [ans_earliest, ans_latest]\n", + "title": "1900. The Earliest and Latest Rounds Where Players Compete", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr and an integer k . A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m| , then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j] . Return a list of the strongest k values in the array. return the answer in any arbitrary order . Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed) .", + "description_images": [], + "constraints": [ + "For arr = [6, -3, 7, 2, 11] , n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2 . The median is 6 .", + "For arr = [-7, 22, 17, 3] , n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1 . The median is 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 2\nOutput:[5,1]\nExplanation:Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is alsoacceptedanswer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,3,5,5], k = 2\nOutput:[5,5]\nExplanation:Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,7,11,7,6,8], k = 5\nOutput:[11,8,6,6,7]\nExplanation:Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] isaccepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 55 ms (Top 48.30%) | Memory: 81.3 MB (Top 78.98%)\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] result = new int[k];\n int n = arr.length, left = 0, right = n - 1, idx = 0;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n while (left <= right) {\n int diff_l = Math.abs(arr[left] - median);\n int diff_r = Math.abs(arr[right] - median);\n\n if (diff_r > diff_l)\n result[idx++] = arr[right--];\n else if (diff_l > diff_r)\n result[idx++] = arr[left++];\n else if (arr[right] > arr[left])\n result[idx++] = arr[right--];\n else\n result[idx++] = arr[left++];\n if (idx == k)\n break;\n }\n return result;\n }\n}", + "title": "1471. The k Strongest Values in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr and an integer k . A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m| , then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j] . Return a list of the strongest k values in the array. return the answer in any arbitrary order . Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed) .", + "description_images": [], + "constraints": [ + "For arr = [6, -3, 7, 2, 11] , n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2 . The median is 6 .", + "For arr = [-7, 22, 17, 3] , n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1 . The median is 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 2\nOutput:[5,1]\nExplanation:Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is alsoacceptedanswer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,3,5,5], k = 2\nOutput:[5,5]\nExplanation:Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,7,11,7,6,8], k = 5\nOutput:[11,8,6,6,7]\nExplanation:Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] isaccepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 708 ms (Top 81.36%) | Memory: 29.90 MB (Top 95.48%)\n\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n mid = arr[(len(arr)-1)//2]\n ans = []\n l ,r = 0, len(arr)-1\n while(l <= r):\n if abs(arr[l] - mid) > abs(arr[r]-mid) :\n ans.append(arr[l])\n l+=1\n else:\n ans.append(arr[r])\n r-=1\n return ans[:k]\n", + "title": "1471. The k Strongest Values in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary matrix mat of 1 's (representing soldiers) and 0 's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1 's will appear to the left of all the 0 's in each row. A row i is weaker than a row j if one of the following is true: Return the indices of the k weakest rows in the matrix ordered from weakest to strongest .", + "description_images": [], + "constraints": [ + "The number of soldiers in row i is less than the number of soldiers in row j .", + "Both rows have the same number of soldiers and i < j ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput:[2,0,3]\nExplanation:The number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput:[0,2]\nExplanation:The number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 17.72%) | Memory: 48.7 MB (Top 54.45%)\nclass Solution {\n public int[] kWeakestRows(int[][] mat, int k) {\n Map map = new HashMap<>();\n List list = new ArrayList<>();\n int[] arr = new int[k];\n for (int i = 0; i < mat.length; i++){\n int n = getBits(mat[i]);\n map.put(i, n);\n list.add(n);\n }\n Collections.sort(list);\n int z = 0;\n for (int i = 0; i < k; i++){\n for (Map.Entry m : map.entrySet()){\n if (list.get(i).equals(m.getValue())){\n arr[z++] = m.getKey();\n map.remove(m.getKey(), m.getValue());\n break;\n }\n }\n }\n\n return arr;\n }\n\n private static Integer getBits(int[] arr) {\n int count = 0;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == 1) count++;\n }\n\n return count;\n }\n}", + "title": "1337. The K Weakest Rows in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n binary matrix mat of 1 's (representing soldiers) and 0 's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1 's will appear to the left of all the 0 's in each row. A row i is weaker than a row j if one of the following is true: Return the indices of the k weakest rows in the matrix ordered from weakest to strongest .", + "description_images": [], + "constraints": [ + "The number of soldiers in row i is less than the number of soldiers in row j .", + "Both rows have the same number of soldiers and i < j ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput:[2,0,3]\nExplanation:The number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput:[0,2]\nExplanation:The number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n\n row = []\n for i in range(len(mat)):\n row.append((sum(mat[i]), i))\n\n row.sort()\n ans = [idx for (val, idx) in row[:k]]\n\n return ans\n", + "title": "1337. The K Weakest Rows in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A happy string is a string that: For example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings. Given two integers n and k , consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n .", + "description_images": [], + "constraints": [ + "consists only of letters of the set ['a', 'b', 'c'] .", + "s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 3\nOutput:\"c\"\nExplanation:The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 4\nOutput:\"\"\nExplanation:There are only 3 happy strings of length 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 9\nOutput:\"cab\"\nExplanation:There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9thstring = \"cab\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 59.76%) | Memory: 51.4 MB (Top 55.86%)\n\nclass Solution {\n\n public String getHappyString(int n, int k) {\n List innerList = new ArrayList<>();\n getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList);\n if (innerList.size() < k)\n return \"\";\n return innerList.get(k - 1);\n }\n\n public void getHappyStringUtil(int n, int k, char[] letter, StringBuilder tempString, List innerList) {\n // Base case\n if (tempString.length() == n) {\n innerList.add(tempString.toString());\n return;\n }\n\n // Recursive call\n for (int i = 0; i < 3; i++) {\n if (tempString.length() > 0 && tempString.charAt(tempString.length() - 1) == letter[i])\n continue;\n tempString.append(letter[i]);\n getHappyStringUtil(n, k, letter, tempString, innerList);\n tempString.deleteCharAt(tempString.length() - 1);\n }\n\n }\n}", + "title": "1415. The k-th Lexicographical String of All Happy Strings of Length n", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A happy string is a string that: For example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings. Given two integers n and k , consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n .", + "description_images": [], + "constraints": [ + "consists only of letters of the set ['a', 'b', 'c'] .", + "s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 3\nOutput:\"c\"\nExplanation:The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 4\nOutput:\"\"\nExplanation:There are only 3 happy strings of length 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 9\nOutput:\"cab\"\nExplanation:There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9thstring = \"cab\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getHappyString(self, n: int, k: int) -> str:\n ans = []\n letters = ['a','b','c']\n def happystr(n,prev,temp):\n if n==0:\n ans.append(\"\".join(temp))\n return \n for l in letters: \n if l!=prev: \n happystr(n-1,l,temp+[l])\n happystr(n,\"\",[])\n if len(ans) list = new ArrayList<>();\n\n for (int i = 1; i <= n; i++) {\n\n if (n % i == 0){\n list.add(i);\n }\n }\n if (list.size() < k){\n return -1;\n }\n \n return list.get(k-1);\n }\n}\n", + "title": "1492. The kth Factor of n", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two positive integers n and k . A factor of an integer n is defined as an integer i where n % i == 0 . Consider a list of all factors of n sorted in ascending order , return the k th factor in this list or return -1 if n has less than k factors.", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, k = 3\nOutput:3\nExplanation:Factors list is [1, 2, 3, 4, 6, 12], the 3rdfactor is 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 7, k = 2\nOutput:7\nExplanation:Factors list is [1, 7], the 2ndfactor is 7.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, k = 4\nOutput:-1\nExplanation:Factors list is [1, 2, 4], there is only 3 factors. We should return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthFactor(self, n: int, k: int) -> int:\n start=[1]\n end=[n]\n for i in range(2,math.ceil(math.sqrt(n))+1):\n if n%i==0:\n start.append(i)\n if i!=n//i:\n end.append(n//i)\n start=sorted(set(start).union(set(end)))\n if k<=len(start):\n return start[k-1]\n else:\n return -1\n", + "title": "1492. The kth Factor of n", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array buses of length n , where buses[i] represents the departure time of the i th bus. You are also given a 0-indexed integer array passengers of length m , where passengers[j] represents the arrival time of the j th passenger. All bus departure times are unique. All passenger arrival times are unique. You are given an integer capacity , which represents the maximum number of passengers that can get on each bus. When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x , and the bus is not full. Passengers with the earliest arrival times get on the bus first. More formally when a bus arrives, either: Return the latest time you may arrive at the bus station to catch a bus . You cannot arrive at the same time as another passenger. Note: The arrays buses and passengers are not necessarily sorted.", + "description_images": [], + "constraints": [ + "If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or", + "The capacity passengers with the earliest arrival times will get on the bus." + ], + "examples": [ + { + "text": "Example 1: Input:buses = [10,20], passengers = [2,17,18,19], capacity = 2\nOutput:16\nExplanation:Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0thpassenger. \nAt time 20, the second bus departs with you and the 1stpassenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1stpassenger to catch the bus.", + "image": null + }, + { + "text": "Example 2: Input:buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2\nOutput:20\nExplanation:Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rdpassenger. \nAt time 20, the second bus departs with the 5thand 1stpassengers.\nAt time 30, the third bus departs with the 0thpassenger and you.\nNotice if you had arrived any later, then the 6thpassenger would have taken your seat on the third bus.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 59 ms (Top 40.13%) | Memory: 106.7 MB (Top 13.12%)\nclass Solution {\n public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) {\n Arrays.sort(buses);\n Arrays.sort(passengers);\n HashSet set = new HashSet<>();\n for(int val : passengers){\n set.add(val);\n }\n int n = buses.length;\n int m = passengers.length;\n int solb = capacity; // solb = space on last bus\n int lastPerson = 0;\n int i = 0, j = 0;\n while(i < n && j < m){\n int cc = capacity; // cc => current capacity;\n while(j < m && cc > 0 && buses[i] >= passengers[j]){\n cc--;\n lastPerson = passengers[j];\n j++;\n }\n i++;\n solb = cc;\n }\n int x = lastPerson;\n if(solb > 0 || i != n){\n x = buses[n - 1];\n }\n while(set.contains(x) == true){\n x--;\n }\n return x;\n }\n}", + "title": "2332. The Latest Time to Catch a Bus", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array buses of length n , where buses[i] represents the departure time of the i th bus. You are also given a 0-indexed integer array passengers of length m , where passengers[j] represents the arrival time of the j th passenger. All bus departure times are unique. All passenger arrival times are unique. You are given an integer capacity , which represents the maximum number of passengers that can get on each bus. When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x , and the bus is not full. Passengers with the earliest arrival times get on the bus first. More formally when a bus arrives, either: Return the latest time you may arrive at the bus station to catch a bus . You cannot arrive at the same time as another passenger. Note: The arrays buses and passengers are not necessarily sorted.", + "description_images": [], + "constraints": [ + "If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or", + "The capacity passengers with the earliest arrival times will get on the bus." + ], + "examples": [ + { + "text": "Example 1: Input:buses = [10,20], passengers = [2,17,18,19], capacity = 2\nOutput:16\nExplanation:Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0thpassenger. \nAt time 20, the second bus departs with you and the 1stpassenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1stpassenger to catch the bus.", + "image": null + }, + { + "text": "Example 2: Input:buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2\nOutput:20\nExplanation:Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rdpassenger. \nAt time 20, the second bus departs with the 5thand 1stpassengers.\nAt time 30, the third bus departs with the 0thpassenger and you.\nNotice if you had arrived any later, then the 6thpassenger would have taken your seat on the third bus.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n passengers.sort()\n cur = 0\n\n for time in sorted(buses):\n cap = capacity\n while cur < len(passengers) and passengers[cur] <= time and cap > 0:\n cur += 1\n cap -= 1\n\n best = time if cap > 0 else passengers[cur - 1]\n\n passengers = set(passengers)\n while best in passengers:\n best -= 1\n return best\n", + "title": "2332. The Latest Time to Catch a Bus", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00 , and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime , this means you have played from loginTime to midnight and from midnight to logoutTime . Return the number of full chess rounds you have played in the tournament . Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45 .", + "description_images": [], + "constraints": [ + "For example, the second round starts at 00:15 , the fourth round starts at 00:45 , and the seventh round starts at 01:30 ." + ], + "examples": [ + { + "text": "Example 1: Input:loginTime = \"09:31\", logoutTime = \"10:14\"\nOutput:1\nExplanation:You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.", + "image": null + }, + { + "text": "Example 2: Input:loginTime = \"21:30\", logoutTime = \"03:00\"\nOutput:22\nExplanation:You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.49%) | Memory: 42.3 MB (Top 21.28%)\nclass Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n String[] arr1 = loginTime.split(\":\");\n String[] arr2 = logoutTime.split(\":\");\n\n int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]);\n int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]);\n\n if(time1 > time2) time2 = time2 + 24*60;\n if(time1%15 != 0) time1 = time1 + 15-time1%15;\n\n return (time2 - time1)/15;\n }\n}", + "title": "1904. The Number of Full Rounds You Have Played", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00 , and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime , this means you have played from loginTime to midnight and from midnight to logoutTime . Return the number of full chess rounds you have played in the tournament . Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45 .", + "description_images": [], + "constraints": [ + "For example, the second round starts at 00:15 , the fourth round starts at 00:45 , and the seventh round starts at 01:30 ." + ], + "examples": [ + { + "text": "Example 1: Input:loginTime = \"09:31\", logoutTime = \"10:14\"\nOutput:1\nExplanation:You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.", + "image": null + }, + { + "text": "Example 2: Input:loginTime = \"21:30\", logoutTime = \"03:00\"\nOutput:22\nExplanation:You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 41 ms (Top 45.3%) | Memory: 16.25 MB (Top 71.7%)\n\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(\":\"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(\":\"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96", + "title": "1904. The Number of Full Rounds You Have Played", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 10^9 + 7 . A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums . Two subsets are different if and only if the chosen indices to delete are different.", + "description_images": [], + "constraints": [ + "For example, if nums = [1, 2, 3, 4] : [2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.", + "[2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively.", + "[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:6\nExplanation:The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,15]\nOutput:5\nExplanation:The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 100.0%) | Memory: 63.20 MB (Top 13.04%)\n\nclass Solution {\n static int MOD = 1_000_000_000 + 7;\n\n // These numbers contain duplicate factors (e.g 4, 8, 9, 25), will be excluded\n static List excludes = new ArrayList<>();\n\n // Distinct prime factors of composites\n // e.g 6 = 2 * 3, 15 = 3 * 5, 30 = 2 * 3 * 5\n static List[] factors = new List[31];\n\n // Coprime numbers permutation\n // Coprime means some composites don't have common factor and can coexist\n // e.g. 14 = 2 * 7 and 15 = 3 * 5\n static List coprimes_pmt = new ArrayList<>();\n\n static {\n List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);\n int[] masks = new int[31];\n\n for (int i = 4; i <= 30; i++) {\n // exclude 4, 8, 9, 25 ...\n if (i % 4 == 0 || i % 9 == 0 || i % 25 == 0) {\n excludes.add(i);\n continue;\n }\n\n if (primes.contains(i)) {\n continue;\n }\n\n // Set distinct prime factors of composites\n for (int j = 0; j < primes.size(); j++) {\n if (i % primes.get(j) == 0) {\n if (factors[i] == null) {\n factors[i] = new ArrayList<>();\n }\n factors[i].add(primes.get(j));\n masks[i] |= (1 << j);\n }\n }\n }\n\n // Recursively build coprime permutation\n buildCoprimes(0, masks, 0, new int[]{});\n }\n\n static void buildCoprimes(int mask, int[] masks, int num, int[] prev) {\n for (; num < masks.length; num++) {\n if (masks[num] > 0 && (mask & masks[num]) == 0) {\n int[] arr = Arrays.copyOf(prev, prev.length + 1);\n arr[prev.length] = num;\n coprimes_pmt.add(arr);\n buildCoprimes(mask | masks[num], masks, num + 1, arr);\n }\n }\n }\n\n public int numberOfGoodSubsets(int[] nums) {\n\n int[] prime_count = new int[31];\n int[] composite_count = new int[31];\n\n for (int num : nums) {\n prime_count[num]++;\n }\n\n // exclude numbers having duplicate factors, like 4, 8, 9, 25...\n for (int ex : excludes) {\n prime_count[ex] = 0;\n }\n\n // split prime numbers and composite numbers\n for (int i = 0; i < prime_count.length; i++) {\n if (factors[i] != null) {\n composite_count[i] = prime_count[i];\n prime_count[i] = 0;\n }\n }\n\n // sum result for prime numbers\n long result = sum(prime_count, null);\n\n // sum result for coprime numbers\n for (int[] coprimes : coprimes_pmt) {\n long count_mul = 1;\n for (int composite : coprimes) {\n count_mul *= composite_count[composite];\n }\n\n if (count_mul > 0) {\n result = (result + (sum(prime_count, coprimes) + 1) * count_mul) % MOD;\n }\n }\n\n // Each `1` will double the result\n while (prime_count[1] > 0) {\n result = (result * 2) % MOD;\n prime_count[1]--;\n }\n\n return (int) result;\n }\n\n int sum(int[] prime_count, int[] coprimes) {\n int[] dp = Arrays.copyOf(prime_count, prime_count.length);\n\n // Exclude prime factors of coprime numbers\n if (coprimes != null) {\n for (int composite : coprimes) {\n for (int factor : factors[composite]) {\n dp[factor] = 0;\n }\n }\n }\n\n for (int i = 3; i <= 29 ; i++) {\n dp[i] = (int) ((dp[i - 1] + 1L * dp[i - 1] * dp[i] + dp[i]) % MOD);\n }\n return dp[29];\n }\n}\n", + "title": "1994. The Number of Good Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 10^9 + 7 . A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums . Two subsets are different if and only if the chosen indices to delete are different.", + "description_images": [], + "constraints": [ + "For example, if nums = [1, 2, 3, 4] : [2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.", + "[2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively.", + "[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:6\nExplanation:The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,15]\nOutput:5\nExplanation:The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nfrom functools import lru_cache\nfrom typing import List, Tuple\n\nPRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29)\n\nBIG_NUMBER = 10 ** 9 + 7\n\n\n@lru_cache(maxsize=32)\ndef factor(n) -> Tuple[int, bool]:\n \"\"\"\n :param n: 1 < n <= max(PRIMES)\n :return: (factors in bit mask, has duplicate primes)\n \"\"\"\n output = 0\n\n for e in PRIMES:\n while n > 1 and n % e == 0:\n mask = 1 << e\n\n if mask & output:\n return -1, False\n\n output |= mask\n\n n //= e\n\n if n == 1:\n break\n\n return output, True\n\n\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n masks = []\n\n for e in nums:\n if 1 < e and (fr := factor(e))[1]:\n masks.append(fr[0])\n\n cnt = Counter(masks)\n good_nums = Counter({0: 0})\n\n for mask in cnt:\n for f in tuple(good_nums):\n if f & mask: # some prime dividing \"mask\" is also dividing the \"f\"\n continue\n\n new_mask = f | mask\n\n count_for_new_mask = good_nums[new_mask] + cnt[mask] * (good_nums[f] or 1)\n\n good_nums[new_mask] = count_for_new_mask % BIG_NUMBER\n\n effect_of_one = pow(2, nums.count(1), BIG_NUMBER)\n total_subsets_without_one = sum(good_nums.values()) % BIG_NUMBER\n\n return (effect_of_one * total_subsets_without_one) % BIG_NUMBER\n", + "title": "1994. The Number of Good Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity . When a friend arrives at the party, they sit on the unoccupied chair with the smallest number . When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrival i , leaving i ] , indicating the arrival and leaving times of the i th friend respectively, and an integer targetFriend . All arrival times are distinct . Return the chair number that the friend numbered targetFriend will sit on .", + "description_images": [], + "constraints": [ + "For example, if chairs 0 , 1 , and 5 are occupied when a friend comes, they will sit on chair number 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:times = [[1,4],[2,3],[4,6]], targetFriend = 1\nOutput:1\nExplanation:- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.", + "image": null + }, + { + "text": "Example 2: Input:times = [[3,10],[1,5],[2,6]], targetFriend = 0\nOutput:2\nExplanation:- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 116 ms (Top 33.59%) | Memory: 71.2 MB (Top 32.82%)\nclass Solution {\n public int smallestChair(int[][] times, int targetFriend) {\n int targetStart = times[targetFriend][0];\n Arrays.sort(times, (a, b) -> a[0] - b[0]);\n\n PriorityQueue available = new PriorityQueue<>();\n for (int i = 0; i < times.length; ++ i) {\n available.offer(i);\n }\n\n PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n\n for (int i = 0; i < times.length; ++ i) {\n while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) {\n available.offer(pq.poll()[1]);\n }\n\n if (times[i][0] == targetStart) {\n break;\n }\n\n pq.offer(new int[]{times[i][1], available.poll()});\n }\n\n return available.peek();\n }\n}", + "title": "1942. The Number of the Smallest Unoccupied Chair", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity . When a friend arrives at the party, they sit on the unoccupied chair with the smallest number . When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrival i , leaving i ] , indicating the arrival and leaving times of the i th friend respectively, and an integer targetFriend . All arrival times are distinct . Return the chair number that the friend numbered targetFriend will sit on .", + "description_images": [], + "constraints": [ + "For example, if chairs 0 , 1 , and 5 are occupied when a friend comes, they will sit on chair number 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:times = [[1,4],[2,3],[4,6]], targetFriend = 1\nOutput:1\nExplanation:- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.", + "image": null + }, + { + "text": "Example 2: Input:times = [[3,10],[1,5],[2,6]], targetFriend = 0\nOutput:2\nExplanation:- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n arrivals = []\n departures = []\n for ind, (x, y) in enumerate(times):\n heappush(arrivals, (x, ind))\n heappush(departures, (y, ind))\n d = {}\n occupied = [0] * len(times)\n while True:\n if arrivals and departures and arrivals[0][0] < departures[0][0]:\n _, ind = heappop(arrivals)\n d[ind] = occupied.index(0)\n occupied[d[ind]] = 1\n if ind == targetFriend:\n return d[ind]\n elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n _, ind = heappop(departures)\n occupied[d[ind]] = 0\n", + "title": "1942. The Number of the Smallest Unoccupied Chair", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense . You are given a 2D integer array properties where properties[i] = [attack i , defense i ] represents the properties of the i th character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attack j > attack i and defense j > defense i . Return the number of weak characters .", + "description_images": [], + "constraints": [ + "2 <= properties.length <= 10^5", + "properties[i].length == 2", + "1 <= attack i , defense i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:properties = [[5,5],[6,3],[3,6]]\nOutput:0\nExplanation:No character has strictly greater attack and defense than the other.", + "image": null + }, + { + "text": "Example 2: Input:properties = [[2,2],[3,3]]\nOutput:1\nExplanation:The first character is weak because the second character has a strictly greater attack and defense.", + "image": null + }, + { + "text": "Example 3: Input:properties = [[1,5],[10,4],[4,3]]\nOutput:1\nExplanation:The third character is weak because the second character has a strictly greater attack and defense.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 90.90%) | Memory: 138 MB (Top 23.61%)\nclass Solution {\n public int numberOfWeakCharacters(int[][] properties) {\n int[] maxH = new int[100002];\n int count = 0;\n for(int[] point:properties){\n maxH[point[0]] = Math.max(point[1],maxH[point[0]]);\n }\n for(int i=100000;i>=0;i--){\n maxH[i] = Math.max(maxH[i+1],maxH[i]);\n }\n\n for(int[] point:properties){\n if(point[1] attack i and defense j > defense i . Return the number of weak characters .", + "description_images": [], + "constraints": [ + "2 <= properties.length <= 10^5", + "properties[i].length == 2", + "1 <= attack i , defense i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:properties = [[5,5],[6,3],[3,6]]\nOutput:0\nExplanation:No character has strictly greater attack and defense than the other.", + "image": null + }, + { + "text": "Example 2: Input:properties = [[2,2],[3,3]]\nOutput:1\nExplanation:The first character is weak because the second character has a strictly greater attack and defense.", + "image": null + }, + { + "text": "Example 3: Input:properties = [[1,5],[10,4],[4,3]]\nOutput:1\nExplanation:The third character is weak because the second character has a strictly greater attack and defense.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4914 ms (Top 7.28%) | Memory: 66.6 MB (Top 91.64%)\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n\n properties.sort(key=lambda x: (-x[0],x[1]))\n\n ans = 0\n curr_max = 0\n\n for _, d in properties:\n if d < curr_max:\n ans += 1\n else:\n curr_max = d\n return ans", + "title": "1996. The Number of Weak Characters in the Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s that contains digits 0-9 , addition symbols '+' , and multiplication symbols '*' only , representing a valid math expression of single digit numbers (e.g., 3+5*2 ). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations : You are given an integer array answers of length n , which are the submitted answers of the students in no particular order. You are asked to grade the answers , by following these rules : Return the sum of the points of the students .", + "description_images": [], + "constraints": [ + "If an answer equals the correct answer of the expression, this student will be rewarded 5 points;", + "Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic , this student will be rewarded 2 points;", + "Otherwise, this student will be rewarded 0 points." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"7+3*1*2\", answers = [20,13,42]\nOutput:7\nExplanation:As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.", + "image": "https://assets.leetcode.com/uploads/2021/09/17/student_solving_math.png" + }, + { + "text": "Example 2: Input:s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput:19\nExplanation:The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.", + "image": null + }, + { + "text": "Example 3: Input:s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput:10\nExplanation:The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 161 ms (Top 97.83%) | Memory: 45.80 MB (Top 93.48%)\n\nclass Solution {\n public int scoreOfStudents(String s, int[] answers) {\n BitSet[][] ok = new BitSet[32][32];\n solve(0, s.length()-1, s, ok);\n int ans = 0, correct = eval(s);\n for (int n : answers){\n if (correct == n){\n ans += 5;\n }else if (ok[0][s.length()-1].get(n)){\n ans += 2;\n }\n }\n return ans;\n }\n\n private BitSet solve(int lo, int hi, String s, BitSet[][] memo){\n if (memo[lo][hi] != null){ // memo\n return memo[lo][hi];\n }\n BitSet cur = new BitSet();\n if (lo == hi){ // base case -> number itself [0 - 9]\n cur.set(s.charAt(lo) - '0');\n return memo[lo][hi]=cur;\n }\n for (int i = lo; i <= hi; i++){\n if (s.charAt(i) == '+' || s.charAt(i) == '*'){\n BitSet l = solve(lo, i-1, s, memo); // left\n BitSet r = solve(i+1, hi, s, memo); // right\n for (int j = l.nextSetBit(0); j >= 0; j = l.nextSetBit(j+1)){\n for (int k = r.nextSetBit(0); k >= 0; k = r.nextSetBit(k+1)){\n int val = s.charAt(i) == '+'? j+k:j*k;\n if (val > 1000){\n break;\n }\n cur.set(val);\n }\n }\n }\n }\n return memo[lo][hi]=cur;\n }\n\n private int eval(String s){\n Deque stack = new ArrayDeque<>();\n Deque op = new ArrayDeque<>();\n for(char ch : s.toCharArray()){\n if (ch == '+' || ch == '*'){\n while(!op.isEmpty() && (ch == '+' || op.peek() == '*')){\n char w = op.pop();\n int r = stack.pop(), l = stack.pop();\n stack.push(w == '+'? l + r : l * r);\n }\n op.push(ch);\n }else{\n stack.push(ch-'0');\n }\n }\n while(!op.isEmpty()){\n char w = op.pop();\n int r = stack.pop(), l = stack.pop();\n stack.push(w == '+'? l + r : l * r);\n }\n\n return stack.pop();\n }\n}\n", + "title": "2019. The Score of Students Solving Math Expression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that contains digits 0-9 , addition symbols '+' , and multiplication symbols '*' only , representing a valid math expression of single digit numbers (e.g., 3+5*2 ). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations : You are given an integer array answers of length n , which are the submitted answers of the students in no particular order. You are asked to grade the answers , by following these rules : Return the sum of the points of the students .", + "description_images": [], + "constraints": [ + "If an answer equals the correct answer of the expression, this student will be rewarded 5 points;", + "Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic , this student will be rewarded 2 points;", + "Otherwise, this student will be rewarded 0 points." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"7+3*1*2\", answers = [20,13,42]\nOutput:7\nExplanation:As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.", + "image": "https://assets.leetcode.com/uploads/2021/09/17/student_solving_math.png" + }, + { + "text": "Example 2: Input:s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput:19\nExplanation:The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.", + "image": null + }, + { + "text": "Example 3: Input:s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput:10\nExplanation:The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \n @cache\n def fn(lo, hi): \n \"\"\"Return possible answers of s[lo:hi].\"\"\"\n if lo+1 == hi: return {int(s[lo])}\n ans = set()\n for mid in range(lo+1, hi, 2): \n for x in fn(lo, mid): \n for y in fn(mid+1, hi): \n if s[mid] == \"+\" and x + y <= 1000: ans.add(x + y)\n elif s[mid] == \"*\" and x * y <= 1000: ans.add(x * y)\n return ans \n \n target = eval(s)\n cand = fn(0, len(s))\n ans = 0 \n for x in answers: \n if x == target: ans += 5\n elif x in cand: ans += 2\n return ans ", + "title": "2019. The Score of Students Solving Math Expression", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively . The geometric information of each building is given in the array buildings where buildings[i] = [left i , right i , height i ] : You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 . The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x 1 ,y 1 ],[x 2 ,y 2 ],...] . Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]", + "description_images": [], + "constraints": [ + "left i is the x coordinate of the left edge of the i th building.", + "right i is the x coordinate of the right edge of the i th building.", + "height i is the height of the i th building." + ], + "examples": [ + { + "text": "Example 1: Input:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:Figure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" + }, + { + "text": "Example 2: Input:buildings = [[0,2,3],[2,5,3]]\nOutput:[[0,3],[5,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class height implements Comparable{\n int val = -1;\n int pos = -1;\n boolean isStart = false;\n height(int a, int b, boolean c){\n val = a;\n pos = b;\n isStart = c;\n }\n public int compareTo(height h){\n if(this.pos != h.pos)\n return this.pos-h.pos;\n if(isStart)\n return -1;\n if(h.isStart)\n return 1;\n \n return this.val-h.val;\n }\n}\nclass Solution {\n public List> getSkyline(int[][] buildings) {\n \n PriorityQueue mQ = new PriorityQueue<>();\n int len = buildings.length;\n for(int[] b: buildings) {\n mQ.add(new height(b[2],b[0],true));\n mQ.add(new height(b[2],b[1],false));\n }\n PriorityQueue heap = new PriorityQueue<>(Collections.reverseOrder());\n heap.add(0);\n int prevHeight = 0;\n List> res = new ArrayList<>();\n List lst;\n while(mQ.size()>0) {\n height h = mQ.poll();\n if(h.isStart){\n heap.offer(h.val);\n } else {\n heap.remove(h.val);\n }\n \n if(prevHeight != heap.peek()){\n lst = new ArrayList<>();\n lst.add(h.pos);\n \n if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){\n lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1)));\n res.remove(res.size()-1);\n } else \n lst.add(heap.peek());\n res.add(lst);\n prevHeight = heap.peek();\n }\n }\n return res;\n }\n}\n", + "title": "218. The Skyline Problem", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively . The geometric information of each building is given in the array buildings where buildings[i] = [left i , right i , height i ] : You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 . The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x 1 ,y 1 ],[x 2 ,y 2 ],...] . Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]", + "description_images": [], + "constraints": [ + "left i is the x coordinate of the left edge of the i th building.", + "right i is the x coordinate of the right edge of the i th building.", + "height i is the height of the i th building." + ], + "examples": [ + { + "text": "Example 1: Input:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:Figure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" + }, + { + "text": "Example 2: Input:buildings = [[0,2,3],[2,5,3]]\nOutput:[[0,3],[5,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(list)\n \n for i,(start, end, height) in enumerate(buildings):\n d[start].append(height)\n d[end].append(-height)\n \n l = list(d.keys())\n l.sort()\n \n result = []\n \n active = []\n \n for key in l:\n o = d[key]\n o.sort(reverse=True)\n for j in o:\n if j > 0:\n if not result or not active:\n result.append([key, j])\n active.append(j)\n else:\n if j > active[-1]:\n result.append([key, j])\n active.append(j)\n else:\n active.insert(bisect_left(active, j), j)\n else:\n idx = active.index(-j)\n if idx == len(active) - 1:\n active.pop()\n if active:\n result.append([key, active[-1]])\n else:\n result.append([key, 0])\n else:\n active.pop(idx)\n \n return result\n \n", + "title": "218. The Skyline Problem", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a network of n servers, labeled from 0 to n - 1 . You are given a 2D integer array edges , where edges[i] = [u i , v i ] indicates there is a message channel between servers u i and v i , and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n . All servers are connected , i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally , so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0 , each data server sends its message to be processed. Starting from second 1 , at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle .", + "description_images": [], + "constraints": [ + "If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.", + "Otherwise, no more resending will occur from this server." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput:8\nExplanation:At (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/quiet-place-example1.png" + }, + { + "text": "Example 2: Input:edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput:3\nExplanation:Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/04/network_a_quiet_place_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 193 ms (Top 55.29%) | Memory: 195.4 MB (Top 40.00%)\n\nclass Solution {\n public int networkBecomesIdle(int[][] edges, int[] patience) {\n int n = patience.length;\n\n // creating adjacency list\n ArrayList> adj = new ArrayList<>();\n for(int i = 0 ; i < n ; i++ ) {\n adj.add(new ArrayList<>());\n }\n\n for(int[] edge : edges) {\n adj.get(edge[0]).add(edge[1]);\n adj.get(edge[1]).add(edge[0]);\n }\n\n // getting the distance array using dijkstra algorithm\n int[] dist = dijkstra(adj);\n\n // variable to store the result\n int ans = 0;\n\n // performing the calculations discussed above for each index\n for(int x = 1; x < n ; x++) {\n\n // round trip time\n int time = 2*dist[x];\n\n int p = patience[x];\n\n //total number of messages the station will send until it receives the reply of first message\n int numberOfMessagesSent = (time)/p;\n\n //handling an edge case if round trip time is a multiple of patience example time =24 patience = 4\n //then the reply would be received at 24 therefore station will not send any message at t = 24\n if(time%p == 0) {\n numberOfMessagesSent--;\n }\n\n // time of last message\n int lastMessage = numberOfMessagesSent*p;\n\n // updating the ans to store max of time at which the station becomes idle\n ans = Math.max(ans,lastMessage+ 2*dist[x]+1);\n\n }\n\n return ans;\n }\n\n // simple dijkstra algorithm implementation\n private int[] dijkstra(ArrayList> adj) {\n\n int n = adj.size();\n\n int[] dist = new int[n];\n boolean[] visited = new boolean[n];\n\n Arrays.fill(dist,Integer.MAX_VALUE);\n dist[0] = 0;\n\n PriorityQueue pq = new PriorityQueue<>((o1,o2)->o1[1]-o2[1]);\n\n pq.add(new int[]{0,0});\n\n while(!pq.isEmpty()) {\n int[] node = pq.remove();\n if(!visited[node[0]]) {\n visited[node[0]] = true;\n for(int nbr : adj.get(node[0])) {\n if(dist[nbr] > dist[node[0]]+1) {\n dist[nbr] = dist[node[0]]+1;\n pq.add(new int[]{nbr,dist[nbr]});\n }\n }\n }\n\n }\n\n return dist;\n }\n\n}\n", + "title": "2039. The Time When the Network Becomes Idle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a network of n servers, labeled from 0 to n - 1 . You are given a 2D integer array edges , where edges[i] = [u i , v i ] indicates there is a message channel between servers u i and v i , and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n . All servers are connected , i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally , so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0 , each data server sends its message to be processed. Starting from second 1 , at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle .", + "description_images": [], + "constraints": [ + "If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.", + "Otherwise, no more resending will occur from this server." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput:8\nExplanation:At (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/quiet-place-example1.png" + }, + { + "text": "Example 2: Input:edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput:3\nExplanation:Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/04/network_a_quiet_place_2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2578 ms (Top 92.45%) | Memory: 69.3 MB (Top 19.78%)\nclass Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n\n #Build Adjency List\n adjList = defaultdict(list)\n\n for source, target in edges:\n adjList[source].append(target)\n adjList[target].append(source)\n\n #BFS to get the shortest route from node to master.\n shortest = {}\n queue = deque([(0,0)])\n seen = set()\n while queue:\n currPos, currDist = queue.popleft()\n\n if currPos in seen:\n continue\n seen.add(currPos)\n shortest[currPos] = currDist\n\n for nei in adjList[currPos]:\n queue.append((nei, currDist+1))\n\n #Calculate answer using shortest paths.\n ans = 0\n for index in range(1,len(patience)):\n resendInterval = patience[index]\n\n #The server will stop sending requests after it's been sent to the master node and back.\n shutOffTime = (shortest[index] * 2)\n\n # shutOffTime-1 == Last second the server can send a re-request.\n lastSecond = shutOffTime-1\n\n #Calculate the last time a packet is actually resent.\n lastResentTime = (lastSecond//resendInterval)*resendInterval\n\n # At the last resent time, the packet still must go through 2 more cycles to the master node and back.\n lastPacketTime = lastResentTime + shutOffTime\n\n ans = max(lastPacketTime, ans)\n\n #Add +1, the current answer is the last time the packet is recieved by the target server (still active).\n #We must return the first second the network is idle, therefore + 1\n return ans + 1", + "title": "2039. The Time When the Network Becomes Idle", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums , return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1]\nOutput:1\nExplanation:The first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]\nOutput:2\nExplanation:The first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,3,1]\nOutput:1\nExplanation:The first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.70 MB (Top 89.77%)\n\nclass Solution {\n public int thirdMax(int[] nums) {\n\t\n\t\t// taking long data type since array can contain Integer.MIN_VALUE\n long max = Long.MIN_VALUE, sMax = Long.MIN_VALUE, tMax = Long.MIN_VALUE;\n for (int i : nums) {\n if (i > max) {\n tMax = sMax;\n sMax = max;\n max = i;\n } else if (i > sMax && i != max) {\n tMax = sMax;\n sMax = i;\n } else if (i > tMax && i != sMax && i != max) {\n tMax = i;\n }\n }\n\t\t\n\t\t// if thirdMax was not updated, return the first Max\n\t\t\n return tMax == Long.MIN_VALUE ? (int) max : (int) tMax;\n }\n}\n", + "title": "414. Third Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1]\nOutput:1\nExplanation:The first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]\nOutput:2\nExplanation:The first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,3,1]\nOutput:1\nExplanation:The first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def thirdMax(self, nums: List[int]) -> int:\n nums_set = set(nums)\n sorted_set = sorted(nums_set)\n return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1]\n \n \n #use set() to remove dups\n #if len of nums after dups have been removed is at least 2, a third max val must exist\n #if not, just return the max\n \n \n #you can do it in 1 line like this but then you have to call the same functions repeatedly\n #return sorted(set(nums))[-3] if len(set(nums)) > 2 else sorted(set(nums))[-1]\n \n \n \n", + "title": "414. Third Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , add a dot (\".\") as the thousands separator and return it in string format.", + "description_images": [], + "constraints": [ + "0 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 987\nOutput:\"987\"", + "image": null + }, + { + "text": "Example 2: Input:n = 1234\nOutput:\"1.234\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.69 MB (Top 67.9%)\n\nclass Solution {\n public String thousandSeparator(int n) {\n \n StringBuffer str = new StringBuffer(Integer.toString(n));\n int index = str.length() - 3;\n \n while(index >= 1){\n str.insert(index , '.');\n index = index - 3;\n }\n \n return str.toString();\n }\n}", + "title": "1556. Thousand Separator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , add a dot (\".\") as the thousands separator and return it in string format.", + "description_images": [], + "constraints": [ + "0 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 987\nOutput:\"987\"", + "image": null + }, + { + "text": "Example 2: Input:n = 1234\nOutput:\"1.234\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 17 ms (Top 24.0%) | Memory: 13.24 MB (Top 48.1%)\n\nclass Solution(object):\n def thousandSeparator(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n n = str(n)\n if len(n) <= 3:\n return str(n)\n result = \"\" \n dot = '.'\n index = 0\n startPos = len(n) % 3 \n if startPos == 0:\n startPos += 3\n val = -1\n while index < len(n):\n result += n[index]\n if index == startPos - 1:\n result += dot\n val = 0\n if val != -1:\n val += 1\n if val > 3 and (val - 1) % 3 == 0 and index != len(n) - 1:\n result += dot\n val = 1 \n index += 1\n\n return result", + "title": "1556. Thousand Separator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,6,4,1]\nOutput:false\nExplanation:There are no three consecutive odds.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,34,3,4,5,7,23,12]\nOutput:true\nExplanation:[5,7,23] are three consecutive odds.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean threeConsecutiveOdds(int[] arr) {\n int count = 0,n = arr.length;\n for(int i=0;i 0)\n {\n count++;\n if(count == 3) return true;\n }\n else\n {\n count = 0;\n }\n }\n return false;\n }\n}\n", + "title": "1550. Three Consecutive Odds", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,6,4,1]\nOutput:false\nExplanation:There are no three consecutive odds.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,34,3,4,5,7,23,12]\nOutput:true\nExplanation:[5,7,23] are three consecutive odds.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 106 ms (Top 5.05%) | Memory: 14 MB (Top 60.17%)\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n c=0\n for i in arr:\n if i%2==0:\n c=0\n else:\n c+=1\n if c==3:\n return True\n return False", + "title": "1550. Three Consecutive Odds", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return true if n has exactly three positive divisors . Otherwise, return false . An integer m is a divisor of n if there exists an integer k such that n = k * m .", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:falseExplantion:2 has only two divisors: 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4\nOutput:trueExplantion:4 has three divisors: 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isThree(int n) {\n if(n<4 ) return false;\n int res = (int)Math.sqrt(n);\n for(int i=2;i*i bool:\n return sum(n%i == 0 for i in range(1, n+1)) == 3\n", + "title": "1952. Three Divisors", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j , such that: If it is not possible, return [-1, -1] . Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3 . Also, leading zeros are allowed , so [0,1,1] and [1,1] represent the same value.", + "description_images": [], + "constraints": [ + "arr[0], arr[1], ..., arr[i] is the first part,", + "arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and", + "arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.", + "All three parts have equal binary values." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,1,0,1]\nOutput:[0,3]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,0,1,1]\nOutput:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,1,0,0,1]\nOutput:[0,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 43.75%) | Memory: 48.2 MB (Top 87.50%)\nclass Solution {\n public int[] threeEqualParts(int[] arr) {\n List ones = new ArrayList<>();\n for (int i = 0; i < arr.length; i++){\n if (arr[i]==1){\n ones.add(i);\n }\n }\n if (ones.size()==0){ // edge case\n return new int[]{0,2};\n }\n int[] ans = new int[2];\n int each = ones.size()/3;\n for (int i = 0; i < 2 && ones.size()%3==0; i++){ // for the first 2 partitions\n for (int j = 0; j < each-1; j++){ // compare gaps\n if (ones.get(j+1+i*each)-ones.get(j+i*each)!=ones.get(j+2*each+1)-ones.get(j+2*each))\n return new int[]{-1, -1};\n }\n ans[i]=ones.get((i+1)*each-1)+i+(arr.length - 1 - ones.get(ones.size()-1)); // cut point\n }\n return ones.size()%3>0||ans[0]>=ones.get(each)||ans[1]>ones.get(2*each)?\n new int[]{-1, -1} : ans;\n }\n}", + "title": "927. Three Equal Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j , such that: If it is not possible, return [-1, -1] . Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3 . Also, leading zeros are allowed , so [0,1,1] and [1,1] represent the same value.", + "description_images": [], + "constraints": [ + "arr[0], arr[1], ..., arr[i] is the first part,", + "arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and", + "arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.", + "All three parts have equal binary values." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,1,0,1]\nOutput:[0,3]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,0,1,1]\nOutput:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,1,0,0,1]\nOutput:[0,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n n = len(arr)\n count_one = arr.count(1)\n if count_one == 0: return [0,n-1]\n if count_one % 3!= 0: return [-1,-1]\n target_ones = count_one // 3\n breaks = []\n one_count = 0\n for i , bit in enumerate(arr):\n if bit ==1 :\n one_count +=1\n if one_count in [1,target_ones+1,2*target_ones+1]:breaks.append(i) \n if one_count in [target_ones,2*target_ones,3*target_ones]:breaks.append(i)\n i1,j1,i2,j2,i3,j3 = breaks\n \n if not arr[i1:j1+1] == arr[i2:j2+1] == arr[i3:j3+1]:return [-1,-1]\n \n trailing_zeroes_left = i2 - j1 - 1\n trailing_zeroes_mid = i3 - j2 - 1\n trailing_zeroes_right = n - j3 - 1\n if trailing_zeroes_right > min(trailing_zeroes_left,trailing_zeroes_mid):return [-1,-1]\n j1 += trailing_zeroes_right\n j2 += trailing_zeroes_right\n return [j1,j2+1]\n \n", + "title": "927. Three Equal Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder) , which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. Using the above function, we can always obtain a unique order of inheritance. Implement the ThroneInheritance class:", + "description_images": [], + "constraints": [ + "ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.", + "void birth(string parentName, string childName) Indicates that parentName gave birth to childName .", + "void death(string name) Indicates the death of name . The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.", + "string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people." + ], + "examples": [ + { + "text": "Example 1: Input[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]Output[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]ExplanationThroneInheritance t= new ThroneInheritance(\"king\"); // order:kingt.birth(\"king\", \"andy\"); // order: king >andyt.birth(\"king\", \"bob\"); // order: king > andy >bobt.birth(\"king\", \"catherine\"); // order: king > andy > bob >catherinet.birth(\"andy\", \"matthew\"); // order: king > andy >matthew> bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob >alex> catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex >asha> catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew >bob> alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]", + "image": null + }, + { + "text": "Successor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder", + "image": null + } + ], + "follow_up": null, + "solution": "class Tree{\n Listchild;\n String name;\n public Tree(String name,Listchild){\n this.name=name;\n this.child=child;\n }\n}\nclass ThroneInheritance {\n private Setdeath;\n private Tree tree;\n private MapaddtoTree;\n public ThroneInheritance(String kingName) {\n death=new HashSet<>(); \n tree=new Tree(kingName,new ArrayList());\n addtoTree=new HashMap();\n addtoTree.put(kingName,tree); \n }\n \n public void birth(String parentName, String childName) {\n Tree tmp =addtoTree.get(parentName);\n Tree childtree=new Tree(childName,new ArrayList());\n tmp.child.add(childtree);\n addtoTree.put( childName,childtree); \n }\n \n public void death(String name) {\n death.add(name);\n }\n \n public List getInheritanceOrder() {\n Listans=new ArrayList<>();\n preOreder(tree,ans,death);\n return ans;\n }\n \n void preOreder(Tree n,Listans,Setdeath){\n if(n==null)return;\n if(!death.contains(n.name))ans.add(n.name);\n for(Tree name:n.child){\n preOreder(name,ans,death);\n }\n }\n}\n", + "title": "1600. Throne Inheritance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder) , which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. Using the above function, we can always obtain a unique order of inheritance. Implement the ThroneInheritance class:", + "description_images": [], + "constraints": [ + "ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.", + "void birth(string parentName, string childName) Indicates that parentName gave birth to childName .", + "void death(string name) Indicates the death of name . The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.", + "string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people." + ], + "examples": [ + { + "text": "Example 1: Input[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]Output[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]ExplanationThroneInheritance t= new ThroneInheritance(\"king\"); // order:kingt.birth(\"king\", \"andy\"); // order: king >andyt.birth(\"king\", \"bob\"); // order: king > andy >bobt.birth(\"king\", \"catherine\"); // order: king > andy > bob >catherinet.birth(\"andy\", \"matthew\"); // order: king > andy >matthew> bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob >alex> catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex >asha> catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew >bob> alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]", + "image": null + }, + { + "text": "Successor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1338 ms (Top 35.29%) | Memory: 68.8 MB (Top 82.35%)\n\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n # Taking kingName as root\n self.root = kingName\n\n # notDead will hold all the people who are alive and their level number\n self.alive = {}\n self.alive[kingName] = 0\n\n # hold edges existing in our graph\n self.edges = {self.root:[]}\n\n def birth(self, parentName: str, childName: str) -> None:\n # birth --> new child so update alive\n self.alive[childName] = self.alive[parentName]+1\n\n # add parent to child edges in the edges dictionary\n if parentName in self.edges:\n self.edges[parentName].append(childName)\n if childName not in self.edges:\n self.edges[childName] = []\n else:\n if childName not in self.edges:\n self.edges[childName] = []\n self.edges[parentName] = [childName]\n\n def death(self, name: str) -> None:\n # removing the dead people from alive map\n del self.alive[name]\n\n def getInheritanceOrder(self) -> List[str]:\n\n hierarchy = []\n def dfs(cur,parent=-1):\n nonlocal hierarchy\n\n # current person available in alive then only add in hierarchy\n if cur in self.alive:\n hierarchy.append(cur)\n\n # traverse all the children of current node\n for i in self.edges[cur]:\n if i!=parent:\n dfs(i,cur)\n dfs(self.root)\n return hierarchy", + "title": "1600. Throne Inheritance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a rectangle of size n x m , return the minimum number of integer-sided squares that tile the rectangle .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/17/sample_11_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_22_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_33_1592.png" + ], + "constraints": [ + "1 <= n, m <= 13" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3\nOutput:3\nExplanation:3squares are necessary to cover the rectangle.2(squares of1x1)1(square of2x2)", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 8\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:n = 11, m = 13\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 31.8%) | Memory: 39.08 MB (Top 78.7%)\n\nclass Solution {\n int ret; // store the final result\n int m, n; // m is the height, and n is the width\n\t\n\t// Note: original signature is changed from n,m to m,n\n public int tilingRectangle(int m, int n) { \n this.m = m;\n this.n = n;\n this.ret = m * n; // initilize the result as m*n if cut rectangle to be all 1*1 squares\n int[][] mat = new int[m][n]; // record the status of every location, 0 means not covered, 1 means covered\n backtrack(mat, 0); // start backtracking\n return ret;\n }\n \n\t// the size means how many squares cut now\n public void backtrack(int[][] mat, int size) {\n if (size > ret) return; // if we already have more squares than the min result, no need to go forward\n \n\t\t// find out the leftmost and topmost postion where is not covered yet\n int x = -1, y = -1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n x = i;\n y = j;\n break;\n }\n }\n if (x != -1 && y != -1) break;\n }\n\t\t// if not found, we know that all positions are covered\n if (x == -1 && y == -1) {\n\t\t // update the result\n ret = Math.min(size, ret);\n }\n else {\n int len = findWidth(x, y, mat); // find the maximum width to cut the square\n while(len >= 1) {\n cover(x, y, len, mat, 1); // cover the current square\n backtrack(mat, size + 1);\n cover(x, y, len, mat, 0); // uncover the previous result\n len--; // decrement the square width by 1\n }\n }\n }\n \n public int findWidth(int x, int y, int[][] mat) {\n int len = 1;\n while(x + len < m && y + len < n) {\n boolean flag = true; // flag means the len is reachable\n for (int i = 0; i <= len; i++) {\n\t\t\t // check the right i-th column and the bottom i-th row away from (x, y) \n if (mat[x + i][y + len] == 1 || mat[x + len][y + i] == 1) {\n flag = false;\n break;\n }\n }\n if (!flag) break;\n len++;\n }\n return len;\n }\n \n public void cover(int x, int y, int len, int[][] mat, int val) {\n for (int i = x; i < x + len; i++) {\n for (int j = y; j < y + len; j++) {\n mat[i][j] = val;\n }\n }\n }\n}", + "title": "1240. Tiling a Rectangle with the Fewest Squares", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a rectangle of size n x m , return the minimum number of integer-sided squares that tile the rectangle .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/17/sample_11_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_22_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_33_1592.png" + ], + "constraints": [ + "1 <= n, m <= 13" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3\nOutput:3\nExplanation:3squares are necessary to cover the rectangle.2(squares of1x1)1(square of2x2)", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 8\nOutput:5", + "image": null + }, + { + "text": "Example 3: Input:n = 11, m = 13\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 197 ms (Top 21.3%) | Memory: 16.48 MB (Top 34.6%)\n\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n # try brute force backtracking?\n board = [[0 for _ in range(n)] for _ in range(m)]\n\n ans = math.inf\n def bt(counts):\n nonlocal ans\n if counts >= ans:\n return\n \n pos = None\n found = False\n for row in range(m):\n for col in range(n):\n if board[row][col] == 0:\n pos = (row, col)\n found = True\n break\n if found:\n break\n if not found:\n ans = min(ans, counts)\n return\n\n # see how many difference size of squares we can place from this spot\n r, c = pos\n offset = 0\n while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n offset += 1\n # max can place size is offset\n for row in range(r, r + offset):\n for col in range(c, c + offset):\n board[row][col] = 1\n # do bt and shrink\n while offset > 0:\n bt(counts + 1)\n # shrink\n for row in range(r, r + offset):\n board[row][c + offset - 1] = 0\n for col in range(c, c + offset):\n board[r + offset - 1][col] = 0\n offset -= 1\n\n bt(0)\n return ans", + "title": "1240. Tiling a Rectangle with the Fewest Squares", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap {\n private Map> map;\n private final String NOT_FOUND = \"\";\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n List entries = map.getOrDefault(key, new ArrayList<>());\n entries.add(new Entry(value, timestamp));\n map.put(key, entries);\n }\n \n public String get(String key, int timestamp) {\n List entries = map.get(key);\n if (entries == null) {\n return NOT_FOUND;\n }\n return binarySearch(entries, timestamp);\n }\n \n private String binarySearch(List entries, int timestamp) {\n int lo = 0, hi = entries.size() - 1, mid = -1;\n String ans = \"\";\n \n // Base cases - if value is not set, return empty\n if (entries.get(lo).timestamp > timestamp) {\n return NOT_FOUND;\n }\n // If timestamp is equal or greater, return the last value saved in map against this key, since that will have the largest timestamp\n else if (entries.get(hi).timestamp <= timestamp) {\n return entries.get(hi).value;\n }\n \n // Else apply binary search to get correct value\n while (lo <= hi) {\n mid = lo + (hi-lo)/2;\n Entry entry = entries.get(mid);\n // System.out.println(\"mid: \"+mid);\n if (entry.timestamp == timestamp) {\n return entry.value;\n }\n // Save ans, and look for ans on right half to find greater timestamp\n else if (entry.timestamp < timestamp) {\n ans = entry.value;\n lo = mid + 1;\n }\n else {\n hi = mid - 1;\n }\n }\n return ans;\n }\n}\n\nclass Entry {\n String value;\n int timestamp;\n \n public Entry(String value, int timestamp) {\n this.value = value;\n this.timestamp = timestamp;\n }\n}\n", + "title": "981. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap:\n\n def __init__(self):\n self.dict = {}\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.dict:\n self.dict[key] = ([], [])\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n else:\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n \n \n def bsearch(self, nums, target):\n beg = 0\n end = len(nums)-1\n lastIndex = len(nums)-1\n \n while beg<=end:\n mid = (beg+end)//2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n end = mid-1\n elif target > nums[mid]:\n beg = mid+1\n \n \n if target < nums[mid] and mid == 0:\n return -1\n if target > nums[mid]:\n return mid\n return mid-1\n \n def get(self, key: str, timestamp: int) -> str:\n if key not in self.dict:\n return \"\"\n \n index = self.bsearch(self.dict[key][1], timestamp)\n return self.dict[key][0][index] if 0 <= index < len(self.dict[key][0]) else \"\"\n \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n", + "title": "981. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people in a line queuing to buy tickets, where the 0 th person is at the front of the line and the (n - 1) th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the i th person would like to buy is tickets[i] . Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously ) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k (0-indexed) to finish buying tickets .", + "description_images": [], + "constraints": [ + "n == tickets.length", + "1 <= n <= 100", + "1 <= tickets[i] <= 100", + "0 <= k < n" + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [2,3,2], k = 2\nOutput:6\nExplanation:- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tickets = [5,1,1,1], k = 0\nOutput:8\nExplanation:- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].\n- In the next 4 passes, only the person in position 0 is buying tickets.\nThe person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 62.6%) | Memory: 40.11 MB (Top 61.2%)\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k){\n int n= tickets.length;\n int time=0;\n \n if(tickets[k]==1) return k+1;\n while(tickets[k]>0){\n for(int i=0;i int:\n return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t))\n", + "title": "2073. Time Needed to Buy Tickets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput:0\nExplanation:The head of the company is the only employee in the company.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput:1\nExplanation: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.\nThe tree structure of the employees in the company is shown.", + "image": "https://assets.leetcode.com/uploads/2020/02/27/graph.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 89 ms (Top 45.5%) | Memory: 63.76 MB (Top 32.3%)\n\nclass Solution {\n public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {\n Map> graph = new HashMap<>();\n for(int i=0; i());\n graph.get(manager[i]).add(i);\n }\n return dfs(graph, headID, informTime);\n }\n\n int dfs(Map> graph, int curHead, int[] informTime) {\n int curMax = 0;\n if(!graph.containsKey(curHead)){\n return curMax;\n }\n for(int subordinate : graph.get(curHead)) {\n curMax = Math.max(curMax, dfs(graph, subordinate, informTime));\n }\n return curMax + informTime[curHead];\n }\n}", + "title": "1376. Time Needed to Inform All Employees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput:0\nExplanation:The head of the company is the only employee in the company.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput:1\nExplanation: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.\nThe tree structure of the employees in the company is shown.", + "image": "https://assets.leetcode.com/uploads/2020/02/27/graph.png" + } + ], + "follow_up": null, + "solution": "import queue\nclass Solution:\n\tdef numOfMinutes(self, n: int, headID: int, manager: List[int],time: List[int]) -> int:\n\t\tnodes = []\n\t\tfor i in range(n): nodes.append([])\n\t\tfor i in range(n): \n\t\t\tif i != headID: nodes[manager[i]].append(i)\n\n\t\tq = queue.LifoQueue()\n\t\tq.put([headID,0])\n\t\tans = 0\n\t\twhile not q.empty():\n\t\t\tcur = q.get()\n\t\t\tfor nxt in nodes[cur[0]]:\n\t\t\t\tq.put([nxt,cur[1]+time[cur[0]]])\n\t\t\t\tans = max(ans,cur[1]+time[cur[0]])\n\t\treturn ans", + "title": "1376. Time Needed to Inform All Employees", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , return the string after replacing every uppercase letter with the same lowercase letter .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello\"\nOutput:\"hello\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"here\"\nOutput:\"here\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"LOVELY\"\nOutput:\"lovely\"", + "image": null + } + ], + "follow_up": null, + "solution": "#approach -1\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n ch = \"\"\n for i in s:\n asc = ord(i)\n if asc > 64 and asc < 91:\n ch += chr(asc+32)\n else:\n ch +=chr(asc)\n return ch\n \n#approach -2\nclass Solution:\n return s.lower()\n", + "title": "709. To Lower Case", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix , return true if the matrix is Toeplitz. Otherwise, return false . A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 20", + "0 <= matrix[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput:true\nExplanation:In the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2],[2,2]]\nOutput:false\nExplanation:The diagonal \"[1, 2]\" has different elements.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isToeplitzMatrix(int[][] matrix) {\n \n \n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int i = 0; i < m; i++){\n int row = 0;\n int col = i;\n int e = matrix[row++][col++];\n while(row < n && col< m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n } \n }\n \n for(int r = 1; r < n; r++){\n int row = r;\n int col = 0;\n int e =matrix[row++][col++];\n while(row < n && col < m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n }\n }\n \n return true;\n }\n}\n", + "title": "766. Toeplitz Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix , return true if the matrix is Toeplitz. Otherwise, return false . A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 20", + "0 <= matrix[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput:true\nExplanation:In the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2],[2,2]]\nOutput:false\nExplanation:The diagonal \"[1, 2]\" has different elements.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg" + } + ], + "follow_up": null, + "solution": "###########################################################################################\n# Runtime: O(MN)\n# Number of rows(M) x expected numbers(N)\n# Space: O(N)\n# We need to store the expected numbers in list\n############################################################################################\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n # Validate Input\n if not matrix or not matrix[0]:\n return False \n \n # Create a deque tracking the expected values for the next row\n expected = matrix[0]\n # We only care about the elements before last element\n expected.pop()\n \n # From the second row, pop out the last element of the expected numbers and compare it with the target row[1:]\n for row in matrix[1:]:\n # Compare row with expected numbers, invalidate it as soon as we find the numbers are not the same (O(N))\n if row[1:] != expected:\n return False\n else:\n # Pop the last element from row, use it as the expected numbers for the next iteration\n row.pop()\n expected = row\n # If we've reached here, all diagonals aligned\n return True\n", + "title": "766. Toeplitz Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the k most frequent elements . You may return the answer in any order .", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int[] topKFrequent(int[] nums, int k) {\n\t\tMap map = new HashMap<>();\n\n\t\tfor (int num : nums) { \n\t\t\tmap.merge(num, 1, Integer::sum);\n\t\t}\n\n\t\treturn map.entrySet()\n\t\t\t.stream()\n\t\t\t.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n\t\t\t.map(Map.Entry::getKey)\n\t\t\t.mapToInt(x -> x)\n\t\t\t.limit(k)\n\t\t\t.toArray();\n\t}\n}\n", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and an integer k , return the k most frequent elements . You may return the answer in any order .", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [i[0] for i in Counter(nums).most_common(k)]\n", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words and an integer k , return the k most frequent strings . Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 500", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters.", + "k is in the range [1, The number of unique words[i]]" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\nOutput:[\"i\",\"love\"]\nExplanation:\"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\nOutput:[\"the\",\"is\",\"sunny\",\"day\"]\nExplanation:\"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public List topKFrequent(String[] words, int k) {\n Map map=new LinkedHashMap<>();\n for(String word:words) \n map.put(word,map.getOrDefault(word,0)+1);\n PriorityQueue> queue=new PriorityQueue<>(new Comparator>(){\n @Override\n public int compare(Pair a,Pair b){\n if(a.getValue()!=b.getValue()) return b.getValue()-a.getValue();\n return a.getKey().compareTo(b.getKey());\n }\n });\n map.forEach((key,val)->{\n queue.add(new Pair(key,val));\n });\n List list=new ArrayList<>();\n while(k>0){\n list.add(queue.poll().getKey());\n k--;\n }\n return list;\n }\n}", + "title": "692. Top K Frequent Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words and an integer k , return the k most frequent strings . Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order .", + "description_images": [], + "constraints": [ + "1 <= words.length <= 500", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters.", + "k is in the range [1, The number of unique words[i]]" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\nOutput:[\"i\",\"love\"]\nExplanation:\"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\nOutput:[\"the\",\"is\",\"sunny\",\"day\"]\nExplanation:\"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "import heapq\nclass Solution:\n def topKFrequent(self, words: List[str], k: int) -> List[str]:\n \n li = {}\n for i in words:\n if i in li:\n li[i]+=1\n else:\n li[i]=1\n \n heap = []\n for i in li:\n heap.append([-li[i],i])\n \n heapq.heapify(heap)\n \n ans = []\n for i in range(k):\n ans.append(heapq.heappop(heap)[1])\n \n return ans", + "title": "692. Top K Frequent Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The appeal of a string is the number of distinct characters found in the string. Given a string s , return the total appeal of all of its substrings . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "For example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbca\"\nOutput:28\nExplanation:The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.", + "image": null + }, + { + "text": "Example 2: Input:s = \"code\"\nOutput:20\nExplanation:The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 66.9%) | Memory: 43.90 MB (Top 92.4%)\n\nclass Solution {\n public long appealSum(String s) {\n long res = 0;\n char[] cs = s.toCharArray();\n int n = cs.length;\n int[] pos = new int[26];\n Arrays.fill(pos, -1);\n for (int i = 0; i < n; ++i) {\n int j = cs[i] - 'a', prev = pos[j]; \n res += (i - prev) * (long) (n - i);\n pos[j] = i;\n }\n return res;\n }\n}", + "title": "2262. Total Appeal of A String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The appeal of a string is the number of distinct characters found in the string. Given a string s , return the total appeal of all of its substrings . A substring is a contiguous sequence of characters within a string.", + "description_images": [], + "constraints": [ + "For example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbca\"\nOutput:28\nExplanation:The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.", + "image": null + }, + { + "text": "Example 2: Input:s = \"code\"\nOutput:20\nExplanation:The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 201 ms (Top 33.23%) | Memory: 18.20 MB (Top 28.53%)\n\nclass Solution:\n def appealSum(self, s: str) -> int:\n res, n, prev = 0, len(s), defaultdict(lambda: -1)\n for i, ch in enumerate(s):\n res += (i - prev[ch]) * (n - i)\n prev[ch] = i\n return res\n", + "title": "2262. Total Appeal of A String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums , return the sum of Hamming distances between all the pairs of the integers in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^9", + "The answer for the given input will fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,14,2]\nOutput:6\nExplanation:In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,14,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 19.37%) | Memory: 53.8 MB (Top 78.38%)\nclass Solution {\n public int totalHammingDistance(int[] nums) {\n int total = 0;\n int[][] cnt = new int[2][32];\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < 32; j++) {\n int idx = (nums[i] >> j) & 1;\n total += cnt[idx ^ 1][j];\n cnt[idx][j]++;\n }\n }\n return total;\n }\n}", + "title": "477. Total Hamming Distance", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums , return the sum of Hamming distances between all the pairs of the integers in nums .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^9", + "The answer for the given input will fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,14,2]\nOutput:6\nExplanation:In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,14,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 947 ms (Top 34.04%) | Memory: 15.5 MB (Top 30.97%)\nclass Solution:\n def totalHammingDistance(self, arr: List[int]) -> int:\n\n total = 0\n for i in range(0,31):\n count = 0\n for j in arr :\n count+= (j >> i) & 1\n total += count*(len(arr)-count)\n return total", + "title": "477. Total Hamming Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary grid board . In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board . If the task is impossible, return -1 . A chessboard board is a board where no 0 's and no 1 's are 4-directionally adjacent.", + "description_images": [], + "constraints": [ + "n == board.length", + "n == board[i].length", + "2 <= n <= 30", + "board[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput:2\nExplanation:One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[0,1],[1,0]]\nOutput:0\nExplanation:Also note that the board with 0 in the top left corner, is also a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[1,0],[1,0]]\nOutput:-1\nExplanation:No matter what sequence of moves you make, you cannot end with a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n return -1;\n }\n }\n }\n for (int i = 0; i < N; i++) {\n rowOneCnt += board[0][i];\n colOneCnt += board[i][0];\n if (board[i][0] == i % 2) {\n rowToMove++;\n }\n if (board[0][i] == i % 2) {\n colToMove++;\n }\n }\n if (rowOneCnt < N / 2 || rowOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (N % 2 == 1) {\n // we cannot make it when ..ToMove is odd\n if (colToMove % 2 == 1) {\n colToMove = N - colToMove;\n }\n if (rowToMove % 2 == 1) {\n rowToMove = N - rowToMove;\n }\n } else {\n colToMove = Math.min(colToMove, N - colToMove);\n rowToMove = Math.min(rowToMove, N - rowToMove);\n }\n return (colToMove + rowToMove) / 2;\n }\n\n}\n", + "title": "782. Transform to Chessboard", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n binary grid board . In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board . If the task is impossible, return -1 . A chessboard board is a board where no 0 's and no 1 's are 4-directionally adjacent.", + "description_images": [], + "constraints": [ + "n == board.length", + "n == board[i].length", + "2 <= n <= 30", + "board[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput:2\nExplanation:One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[0,1],[1,0]]\nOutput:0\nExplanation:Also note that the board with 0 in the top left corner, is also a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[1,0],[1,0]]\nOutput:-1\nExplanation:No matter what sequence of moves you make, you cannot end with a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def movesToChessboard(self, board):\n N = len(board)\n ans = 0\n # For each count of lines from {rows, columns}...\n for count in (collections.Counter(map(tuple, board)), # get row\n collections.Counter(zip(*board))): #get column\n\n # If there are more than 2 kinds of lines,\n # or if the number of kinds is not appropriate ...\n if len(count) != 2 or sorted(count.values()) != [N/2, (N+1)/2]:\n return -1\n\n # If the lines are not opposite each other, impossible\n line1, line2 = count\n if not all(x ^ y for x, y in zip(line1, line2)):\n return -1\n\n # starts = what could be the starting value of line1\n # If N is odd, then we have to start with the more\n # frequent element\n starts = [int(line1.count(1) * 2 > N)] if N%2 else [0, 1]\n\n # To transform line1 into the ideal line [i%2 for i ...],\n # we take the number of differences and divide by two\n ans += min(sum((x-i) % 2 for i, x in enumerate(line1, start))\n for start in starts) / 2 \n\n return ans\n", + "title": "782. Transform to Chessboard", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array matrix , return the transpose of matrix . The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png" + ], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "-10^9 <= matrix[i][j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[[1,4,7],[2,5,8],[3,6,9]]", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[4,5,6]]\nOutput:[[1,4],[2,5],[3,6]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 43.1 MB (Top 92.66%)\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n int[][] trans = new int[n][m];\n\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n trans[i][j] = matrix[j][i];\n }\n }\n\n return trans;\n }\n}", + "title": "867. Transpose Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D integer array matrix , return the transpose of matrix . The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png" + ], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "-10^9 <= matrix[i][j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[[1,4,7],[2,5,8],[3,6,9]]", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[4,5,6]]\nOutput:[[1,4],[2,5],[3,6]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n rows=len(matrix)\n cols=len(matrix[0])\n ans=[[0]*rows]*cols\n for i in range(cols):\n for j in range(rows):\n ans[i][j]=matrix[j][i]\n return ans\n", + "title": "867. Transpose Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput:6\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trap(int[] height) {\n int left = 0;\n int right = height.length - 1;\n \n int l_max = height[left];\n int r_max = height[right];\n int res = 0;\n \n while(left < right) {\n if(l_max < r_max) {\n left+=1;\n l_max = Math.max(l_max, height[left]);\n res += l_max - height[left];\n }\n else{\n right-=1;\n r_max = Math.max(r_max, height[right]);\n res += r_max - height[right];\n }\n }\n \n return res;\n }\n}\n", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput:6\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 254 ms (Top 43.79%) | Memory: 16.1 MB (Top 46.67%)\nclass Solution:\n def trap(self, a: List[int]) -> int:\n l=0\n r=len(a)-1\n maxl=0\n maxr=0\n res=0\n\n while (l<=r):\n if a[l]<=a[r]:\n if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >=\n else: res+=maxl-a[l] #adding captured water when maxl>a[l]\n l+=1\n else:\n if a[r]>=maxr: maxr=a[r]\n else: res+=maxr-a[r]\n r-=1\n return res\n", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining .", + "description_images": [], + "constraints": [ + "m == heightMap.length", + "n == heightMap[i].length", + "1 <= m, n <= 200", + "0 <= heightMap[i][j] <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\nOutput:4\nExplanation:After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" + }, + { + "text": "Example 2: Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\nOutput:10", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public class pair implements Comparable{\n int row;\n int col;\n int val;\n pair(int row, int col,int val){\n this.row = row;\n this.col = col;\n this.val = val;\n }\n public int compareTo(pair o){\n return this.val - o.val;\n }\n }\n int[][] dir = {{1,0},{0,-1},{-1,0},{0,1}};\n public int trapRainWater(int[][] heightMap) {\n int n = heightMap.length;\n int m = heightMap[0].length;\n \n PriorityQueue pq = new PriorityQueue<>();\n \n boolean[][] visited = new boolean[n][m];\n \n // add all the boundary elements in pq\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(i == 0 || j == 0 || i == n-1 || j == m-1){\n pq.add(new pair(i, j, heightMap[i][j]));\n visited[i][j] = true;\n }\n }\n }\n \n int ans = 0;\n \n while(pq.size() > 0){\n pair rem = pq.remove();\n for(int i = 0; i < 4; i++){\n \n int rowdash = rem.row + dir[i][0];\n int coldash = rem.col + dir[i][1];\n \n if(rowdash >= 0 && coldash >= 0 && rowdash < n && coldash < m && visited[rowdash][coldash] == false){\n visited[rowdash][coldash] = true;\n if(heightMap[rowdash][coldash] >= rem.val){\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated\n }else{\n int waterstored = rem.val - heightMap[rowdash][coldash];\n ans += waterstored; // now this will act as a wall add in pq\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));\n }\n }\n }\n }\n return ans;\n }\n}\n", + "title": "407. Trapping Rain Water II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining .", + "description_images": [], + "constraints": [ + "m == heightMap.length", + "n == heightMap[i].length", + "1 <= m, n <= 200", + "0 <= heightMap[i][j] <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\nOutput:4\nExplanation:After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" + }, + { + "text": "Example 2: Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\nOutput:10", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n ROW, COL = len(heightMap), len(heightMap[0])\n\n pq = []\n heapq.heapify(pq)\n visited = {}\n \n for row in range(ROW):\n for col in range(COL):\n if row == 0 or row == ROW-1 or col == 0 or col == COL-1:\n heapq.heappush(pq, (heightMap[row][col],row,col))\n visited[(row,col)] = True\n \n def getnbr(row,col):\n res = []\n if row-1 >=0:\n res.append((row-1,col))\n if col-1 >=0:\n res.append((row, col-1))\n if row+1 < ROW:\n res.append((row+1,col))\n if col+1 < COL:\n res.append((row, col+1))\n\n return res\n \n res = 0\n \n while pq:\n h, i, j = heapq.heappop(pq)\n \n for dx, dy in getnbr(i,j):\n if (dx,dy) not in visited: \n \n res += max(0, h-heightMap[dx][dy])\n \n heapq.heappush(pq, (max(h, heightMap[dx][dy]),dx,dy))\n visited[(dx,dy)] = True\n\n return res\n", + "title": "407. Trapping Rain Water II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0 . To represent this tree, you are given an integer array nums and a 2D array edges . Each nums[i] represents the i th node's value, and each edges[j] = [u j , v j ] represents an edge between nodes u j and v j in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y . An ancestor of a node i is any other node on the shortest path from node i to the root . A node is not considered an ancestor of itself. Return an array ans of size n , where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime , or -1 if there is no such ancestor .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram.png", + "https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram1.png" + ], + "constraints": [ + "nums.length == n", + "1 <= nums[i] <= 50", + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[j].length == 2", + "0 <= u j , v j < n", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput:[-1,0,0,1]\nExplanation:In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput:[-1,0,-1,0,0,0,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n //made TreeNode class for simple implementation in recurring function\n class TreeNode{\n int id;\n int val;\n List child;\n public TreeNode(int id,int val){\n this.id=id;this.val=val;child=new ArrayList<>();\n }\n }\n public int[] getCoprimes(int[] nums, int[][] edges) {\n // making tree/graph with edges\n TreeNode[] tr=new TreeNode[nums.length];\n for(int i=0;i List[int]:\n \n gcdset = [set() for i in range(51)]\n for i in range(1,51):\n for j in range(1,51):\n if math.gcd(i,j) == 1:\n gcdset[i].add(j)\n gcdset[j].add(i)\n \n graph = defaultdict(list)\n for v1, v2 in edges:\n graph[v1].append(v2)\n graph[v2].append(v1)\n \n ans = [-1]*len(nums)\n q = [[0, {}]]\n seen = set([0])\n depth = 0\n while q:\n temp = []\n for node, ancestors in q:\n index_depth = (-1,-1)\n for anc in list(ancestors.keys()):\n if anc in gcdset[nums[node]]:\n index, d = ancestors[anc]\n if d > index_depth[1]:\n index_depth = (index,d)\n ans[node] = index_depth[0]\n \n copy = ancestors.copy()\n copy[nums[node]] = (node,depth)\n \n for child in graph[node]:\n if child not in seen:\n seen.add(child)\n temp.append([child, copy])\n q = temp\n depth += 1\n return ans", + "title": "1766. Tree of Coprimes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a triangle array, return the minimum path sum from top to bottom . For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.", + "description_images": [], + "constraints": [ + "1 <= triangle.length <= 200", + "triangle[0].length == 1", + "triangle[i].length == triangle[i - 1].length + 1", + "-10^4 <= triangle[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput:11\nExplanation:The triangle looks like:234\n 657\n418 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).", + "image": null + }, + { + "text": "Example 2: Input:triangle = [[-10]]\nOutput:-10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 41.54%) | Memory: 43.9 MB (Top 66.49%)\nclass Solution {\n public int minimumTotal(List> triangle) {\n\n int n = triangle.get( triangle.size() - 1).size();\n int dp[] = new int[n + 1];\n\n for(int i = triangle.size() - 1; i>=0; i--)\n {\n for(int j = 0; j int:\n dp = []\n dp.append(t[0])\n \n r = len(t)\n answer = float('inf')\n for i in range(1, r):\n c = len(t[i])\n dp.append([])\n for j in range(0, c):\n if j == 0:\n val = dp[i - 1][j] + t[i][j]\n elif j == c - 1:\n val = dp[i - 1][j - 1] + t[i][j]\n else:\n val = min(dp[i - 1][j], dp[i - 1][j - 1]) + t[i][j]\n if i == r - 1:\n answer = min(answer, val)\n dp[i].append(val)\n return answer if r > 1 else t[0][0]\n", + "title": "120. Triangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high , trim the tree so that all its elements lies in [low, high] . Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer . Return the root of the trimmed binary search tree . Note that the root may change depending on the given bounds.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The value of each node in the tree is unique .", + "root is guaranteed to be a valid binary search tree.", + "0 <= low <= high <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,2], low = 1, high = 2\nOutput:[1,null,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg" + }, + { + "text": "Example 2: Input:root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput:[3,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 45.6 MB (Top 46.04%)\nclass Solution {\n public TreeNode trimBST(TreeNode root, int low, int high) {\n if (root == null) return root;\n while (root.val < low || root.val > high) {\n root = root.val < low ? root.right : root.left;\n if (root == null)\n return root;\n }\n root.left = trimBST(root.left, low, high);\n root.right = trimBST(root.right, low, high);\n return root;\n }\n}", + "title": "669. Trim a Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high , trim the tree so that all its elements lies in [low, high] . Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer . Return the root of the trimmed binary search tree . Note that the root may change depending on the given bounds.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The value of each node in the tree is unique .", + "root is guaranteed to be a valid binary search tree.", + "0 <= low <= high <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,2], low = 1, high = 2\nOutput:[1,null,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg" + }, + { + "text": "Example 2: Input:root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput:[3,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 58 ms (Top 27.96%) | Memory: 20.40 MB (Top 38.8%)\n\nclass Solution:\n\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\tif not root: return root\n\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\troot.left = self.trimBST(root.left, low, high)\n\t\troot.right = self.trimBST(root.right, low, high)\n\t\treturn root", + "title": "669. Trim a Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums, return the number of AND triples . An AND triple is a triple of indices (i, j, k) such that:", + "description_images": [], + "constraints": [ + "0 <= i < nums.length", + "0 <= j < nums.length", + "0 <= k < nums.length", + "nums[i] & nums[j] & nums[k] == 0 , where & represents the bitwise-AND operator." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:12\nExplanation:We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]\nOutput:27", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 113 ms (Top 49.3%) | Memory: 43.66 MB (Top 52.1%)\n\nclass Solution {\n public int countTriplets(int[] nums) {\n int[] count = new int[1 << 16];\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < nums.length; j++) {\n count[nums[i] & nums[j]]++;\n }\n }\n int ans = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < 1 << 16; j++) {\n if ((nums[i] & j) == 0) {\n ans += count[j];\n }\n }\n }\n return ans;\n }\n}", + "title": "982. Triples with Bitwise AND Equal To Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums, return the number of AND triples . An AND triple is a triple of indices (i, j, k) such that:", + "description_images": [], + "constraints": [ + "0 <= i < nums.length", + "0 <= j < nums.length", + "0 <= k < nums.length", + "nums[i] & nums[j] & nums[k] == 0 , where & represents the bitwise-AND operator." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]\nOutput:12\nExplanation:We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]\nOutput:27", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 549 ms (Top 98.6%) | Memory: 23.43 MB (Top 9.7%)\n\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans ", + "title": "982. Triples with Bitwise AND Equal To Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). You are given a sentence s ​​​​​​ and an integer k ​​​​​​. You want to truncate s ​​​​​​ such that it contains only the first k ​​​​​​ words. Return s ​​​​ ​​ after truncating it.", + "description_images": [], + "constraints": [ + "For example, \"Hello World\" , \"HELLO\" , and \"hello world hello world\" are all sentences." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello how are you Contestant\", k = 4\nOutput:\"Hello how are you\"\nExplanation:The words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"What is the solution to this problem\", k = 4\nOutput:\"What is the solution\"\nExplanation:The words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"chopper is not a tanuki\", k = 5\nOutput:\"chopper is not a tanuki\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 77.37%)\n\nclass Solution {\n public String truncateSentence(String s, int k) {\n int n = s.length();\n int count = 0;\n int i = 0;\n while(i str:\n words = s.split(\" \")\n return \" \".join(words[0:k])\n", + "title": "1816. Truncate Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a , b , c , and d are elements of nums , and a != b != c != d .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "All elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,4,6]\nOutput:8\nExplanation:There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,5,10]\nOutput:16\nExplanation:There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tupleSameProduct(int[] nums) {\n \n if(nums.length < 4){\n return 0;\n }\n \n int res = 0;\n \n HashMap map = new HashMap<>();\n \n for(int i = 0; i < nums.length - 1; i++){\n \n for(int j = i + 1; j < nums.length; j++){\n \n int val = nums[i] * nums[j];\n map.put(val, map.getOrDefault(val, 0) + 1);\n }\n }\n \n for(int key : map.keySet()){\n \n int val = map.get(key);\n \n if(val > 1){\n res += val * (val - 1) * 4; // (val * (val - 1) / 2) * 8\n }\n }\n \n return res;\n }\n}\n", + "title": "1726. Tuple with Same Product", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a , b , c , and d are elements of nums , and a != b != c != d .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "All elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,4,6]\nOutput:8\nExplanation:There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,5,10]\nOutput:16\nExplanation:There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1072 ms (Top 44.44%) | Memory: 42.9 MB (Top 86.75%)\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n\n from itertools import combinations\n mydict=defaultdict(int)\n ans=0\n\n for a,b in combinations(nums,2):\n mydict[a*b]+=1\n\n for i,j in mydict.items():\n if j>1:\n ans+=(j*(j-1)//2)*8\n\n return ans", + "title": "1726. Tuple with Same Product", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute , hour , or day ). For example, the period [10, 10000] (in seconds ) would be partitioned into the following time chunks with these frequencies: Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period ( 10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: Example:", + "description_images": [], + "constraints": [ + "Every minute (60-second chunks): [10,69] , [70,129] , [130,189] , ... , [9970,10000]", + "Every hour (3600-second chunks): [10,3609] , [3610,7209] , [7210,10000]", + "Every day (86400-second chunks): [10,10000]" + ], + "examples": [ + { + "text": "Example: Input[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]Output[null,null,null,null,[2],[2,1],null,[4]]ExplanationTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 351 ms (Top 16.84%) | Memory: 93.3 MB (Top 14.74%)\nclass TweetCounts {\n Map> map;\n public TweetCounts() {\n map = new HashMap<>();\n }\n\n public void recordTweet(String tweetName, int time) {\n map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time);\n }\n\n public List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {\n List res = new ArrayList<>();\n if(map.containsKey(tweetName)) {\n Collections.sort(map.get(tweetName));\n while(startTime<=endTime) {\n int interval = Freq.valueOf(freq).getVal();\n int end = Math.min(startTime+interval-1, endTime); // need this to handle the last interval\n res.add(getFreq(map.get(tweetName), startTime, end));\n startTime=end+1; // ex: for minute, the interval is 60 so our end is 59. The next startTime is end+1\n }\n }\n return res;\n }\n\n public int getFreq(List list, int start, int end) {\n int st = Collections.binarySearch(list, start);\n if(st<0) {\n st = (st+1)*-1; // our exact start time might not be in the list, to get the 1st timestamp greater than start\n }\n int en = Collections.binarySearch(list, end);\n if(en<0) {\n en = (en+2)*-1; // our exact end time might not be in the list, to get the last timestamp just smaller than end\n }\n\n return en-st+1; // the freq count\n }\n}\n\n enum Freq {\n minute(60), hour(3600), day(86400);\n Map map = new HashMap<>();\n Freq(int val) {\n map.put(this, val);\n }\n\n public int getVal() {\n return map.get(this);\n }\n\n}\n\n/**\n * Your TweetCounts object will be instantiated and called as such:\n * TweetCounts obj = new TweetCounts();\n * obj.recordTweet(tweetName,time);\n * List param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);\n */\n", + "title": "1348. Tweet Counts Per Frequency", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute , hour , or day ). For example, the period [10, 10000] (in seconds ) would be partitioned into the following time chunks with these frequencies: Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period ( 10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: Example:", + "description_images": [], + "constraints": [ + "Every minute (60-second chunks): [10,69] , [70,129] , [130,189] , ... , [9970,10000]", + "Every hour (3600-second chunks): [10,3609] , [3610,7209] , [7210,10000]", + "Every day (86400-second chunks): [10,10000]" + ], + "examples": [ + { + "text": "Example: Input[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]Output[null,null,null,null,[2],[2,1],null,[4]]ExplanationTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass TweetCounts:\n\n def __init__(self):\n self.tweets = {}\n \n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if not tweetName in self.tweets:\n self.tweets[tweetName] = []\n index = bisect.bisect_left(self.tweets[tweetName], time)\n self.tweets[tweetName].insert(index, time)\n \n \n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n \n def find(step):\n nonlocal tweet\n result = []\n for i in range(startTime, endTime+1, step):\n result.append(bisect.bisect_right(tweet, min(endTime, i + step - 1)) - bisect.bisect_left(tweet, i))\n return result\n \n \n tweet = self.tweets[tweetName]\n if freq == \"minute\":\n return find(60)\n elif freq == \"hour\":\n return find(3600)\n else:\n return find(86400)", + "title": "1348. Tweet Counts Per Frequency", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array of events where events[i] = [startTime i , endTime i , value i ] . The i th event starts at startTime i and ends at endTime i , and if you attend this event, you will receive a value of value i . You can choose at most two non-overlapping events to attend such that the sum of their values is maximized . Return this maximum sum. Note that the start time and end time is inclusive : that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t , the next event must start at or after t + 1 .", + "description_images": [], + "constraints": [ + "2 <= events.length <= 10^5", + "events[i].length == 3", + "1 <= startTime i <= endTime i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,3,2],[4,5,2],[2,4,3]]\nOutput:4\nExplanation:Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture5.png" + }, + { + "text": "Example 2: Input:events = [[1,3,2],[4,5,2],[1,5,5]]\nOutput:5\nExplanation:Choose event 2 for a sum of 5.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture1.png" + }, + { + "text": "Example 3: Input:events = [[1,5,3],[1,5,1],[6,6,5]]\nOutput:8\nExplanation:Choose events 0 and 2 for a sum of 3 + 5 = 8.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 92 ms (Top 45.29%) | Memory: 159.8 MB (Top 35.88%)\nclass Solution {\n public int maxTwoEvents(int[][] events) {\n Arrays.sort(events, (a, b) -> a[0] - b[0]);\n int onRight = 0, maxOne = 0, n = events.length;\n int[] rightMax = new int[n+1];\n for (int i = n - 1; i >= 0; i--) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n maxOne = Math.max(val, maxOne);\n rightMax[i] = Math.max(rightMax[i+1], val);\n }\n int two = 0;\n for (int i = 0; i < n; i++) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n int idx = binarySearch(end, events);\n if (idx < n) {\n two = Math.max(rightMax[idx] + val, two);\n }\n }\n return Math.max(two, maxOne);\n }\n\n public int binarySearch(int end, int[][] arr) {\n int left = 0, right = arr.length;\n while (left < right) {\n int mid = left + (right - left) / 2;\n if (arr[mid][0] > end) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n}", + "title": "2054. Two Best Non-Overlapping Events", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed 2D integer array of events where events[i] = [startTime i , endTime i , value i ] . The i th event starts at startTime i and ends at endTime i , and if you attend this event, you will receive a value of value i . You can choose at most two non-overlapping events to attend such that the sum of their values is maximized . Return this maximum sum. Note that the start time and end time is inclusive : that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t , the next event must start at or after t + 1 .", + "description_images": [], + "constraints": [ + "2 <= events.length <= 10^5", + "events[i].length == 3", + "1 <= startTime i <= endTime i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,3,2],[4,5,2],[2,4,3]]\nOutput:4\nExplanation:Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture5.png" + }, + { + "text": "Example 2: Input:events = [[1,3,2],[4,5,2],[1,5,5]]\nOutput:5\nExplanation:Choose event 2 for a sum of 5.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture1.png" + }, + { + "text": "Example 3: Input:events = [[1,5,3],[1,5,1],[6,6,5]]\nOutput:8\nExplanation:Choose events 0 and 2 for a sum of 3 + 5 = 8.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\ndef maxTwoEvents(self, events: List[List[int]]) -> int:\n \n events.sort()\n heap = []\n res2,res1 = 0,0\n for s,e,p in events:\n while heap and heap[0][0] Integer.compare(c2[1] - c2[0], c1[1] - c1[0]));// biggest to smallest\n int minCost = 0; \n int n = costs.length;\n for (int i = 0; i < n; i++) {\n minCost += i < n/2? costs[i][0] : costs[i][1];//First half -> A; Last half -> B 259 + 184 + 577 + 54 + 667 + 118\n }\n return minCost;\n }\n}\n", + "title": "1029. Two City Scheduling", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCost i , bCost i ] , the cost of flying the i th person to city a is aCost i , and the cost of flying the i th person to city b is bCost i . Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.", + "description_images": [], + "constraints": [ + "2 * n == costs.length", + "2 <= costs.length <= 100", + "costs.length is even.", + "1 <= aCost i , bCost i <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput:110\nExplanation:The first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.", + "image": null + }, + { + "text": "Example 2: Input:costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput:1859", + "image": null + }, + { + "text": "Example 3: Input:costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput:3086", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n n = len(costs)\n m = n // 2\n \n @lru_cache(None)\n def dfs(cur, a):\n\t\t\t# cur is the current user index\n\t\t\t# `a` is the number of people travel to city `a`\n\t\t\t\n if cur == n:\n return 0\n \n\t\t\t# people to b city\n b = cur - a\n ans = float('inf')\n \n\t\t\t# the number of people to `a` city number did not reach to limit, \n\t\t\t# then current user can trval to city `a`\n\t\t\t\n if a < m:\n ans = min(dfs(cur+1, a+1)+costs[cur][0], ans)\n \n\t\t\t# the number of people to `b` city number did not reach to limit\n\t\t\t# then current user can trval to city `b`\n if b < m:\n ans = min(dfs(cur+1, a)+costs[cur][1], ans)\n \n return ans\n \n return dfs(0, 0)\n", + "title": "1029. Two City Scheduling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n , where colors[i] represents the color of the i th house. Return the maximum distance between two houses with different colors . The distance between the i th and j th houses is abs(i - j) , where abs(x) is the absolute value of x .", + "description_images": [], + "constraints": [ + "n == colors.length", + "2 <= n <= 100", + "0 <= colors[i] <= 100", + "Test data are generated such that at least two houses have different colors." + ], + "examples": [ + { + "text": "Example 1: Input:colors = [1,1,1,6,1,1,1]\nOutput:3\nExplanation:In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg1.png" + }, + { + "text": "Example 2: Input:colors = [1,8,3,8,3]\nOutput:4\nExplanation:In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg2.png" + }, + { + "text": "Example 3: Input:colors = [0,1]\nOutput:1\nExplanation:The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.7 MB (Top 13.21%)\nclass Solution {\n public int maxDistance(int[] colors) {\n int l = 0, r = colors.length-1;\n while(colors[colors.length-1] == colors[l]) l++;\n while(colors[0] == colors[r]) r--;\n return Math.max(r, colors.length - 1 - l);\n }\n}", + "title": "2078. Two Furthest Houses With Different Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n , where colors[i] represents the color of the i th house. Return the maximum distance between two houses with different colors . The distance between the i th and j th houses is abs(i - j) , where abs(x) is the absolute value of x .", + "description_images": [], + "constraints": [ + "n == colors.length", + "2 <= n <= 100", + "0 <= colors[i] <= 100", + "Test data are generated such that at least two houses have different colors." + ], + "examples": [ + { + "text": "Example 1: Input:colors = [1,1,1,6,1,1,1]\nOutput:3\nExplanation:In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg1.png" + }, + { + "text": "Example 2: Input:colors = [1,8,3,8,3]\nOutput:4\nExplanation:In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg2.png" + }, + { + "text": "Example 3: Input:colors = [0,1]\nOutput:1\nExplanation:The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 98.18%) | Memory: 17.40 MB (Top 5.01%)\n\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n\t\t#first pass\n l, r = 0, len(colors)-1\n dist = 0\n \n while r > l:\n if colors[r] != colors[l]:\n dist = r-l\n\t\t\t\t#slight performance increase, break out if you find it \n\t\t\t\t#because it can't get bigger than this\n break \n r -= 1\n\t\t\t\n #second pass, backwards\n l, r = 0, len(colors)-1\n while r > l:\n if colors[r] != colors[l]:\n dist = max(dist, r-l)\n break\n l += 1\n \n return dist\n\t\n", + "title": "2078. Two Furthest Houses With Different Colors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length, nums3.length <= 100", + "1 <= nums1[i], nums2[j], nums3[k] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput:[3,2]\nExplanation:The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput:[2,3,1]\nExplanation:The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput:[]\nExplanation:No value is present in at least two arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.56%) | Memory: 46.7 MB (Top 58.76%)\nclass Solution {\n public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {\n int[] bits = new int[101];\n for (int n : nums1) bits[n] |= 0b110;\n for (int n : nums2) bits[n] |= 0b101;\n for (int n : nums3) bits[n] |= 0b011;\n List result = new ArrayList();\n for (int i = bits.length - 1; i > 0; i--)\n if (bits[i] == 0b111)\n result.add(i);\n return result;\n }\n}", + "title": "2032. Two Out of Three", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length, nums3.length <= 100", + "1 <= nums1[i], nums2[j], nums3[k] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput:[3,2]\nExplanation:The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput:[2,3,1]\nExplanation:The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput:[]\nExplanation:No value is present in at least two arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 93.8%) | Memory: 16.30 MB (Top 83.7%)\n\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n output = []\n for i in nums1:\n if i in nums2 or i in nums3:\n if i not in output:\n output.append(i)\n for j in nums2:\n if j in nums3 or j in nums1:\n if j not in output:\n output.append(j)\n return output", + "title": "2032. Two Out of Three", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9\nOutput:[0,1]\nExplanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6\nOutput:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] twoSum(int[] nums, int target) {\n int[] answer = new int[2];\n\t\t// Two for loops for selecting two numbers and check sum equal to target or not\n\t\t\n for(int i = 0; i < nums.length; i++){\n for(int j = i+1; j < nums.length; j++) {\n\t\t\t // j = i + 1; no need to check back elements it covers in i;\n if(nums[i] + nums[j] == target) {\n\t\t\t\t// Check sum == target or not\n answer[0] = i;\n answer[1] = j;\n return answer;\n }\n } \n }\n return null;\n }\n}\n", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9\nOutput:[0,1]\nExplanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6\nOutput:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 2571 ms (Top 18.27%) | Memory: 17.10 MB (Top 86.21%)\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n n = len(nums)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n return [] # No solution found\n\n", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 , added 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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:numbers = [2,7,11,15], target = 9\nOutput:[1,2]\nExplanation:The sum of 2 and 7 is 9. Therefore, index1= 1, index2= 2. We return [1, 2].", + "image": null + }, + { + "text": "Example 2: Input:numbers = [2,3,4], target = 6\nOutput:[1,3]\nExplanation:The sum of 2 and 4 is 6. Therefore index1= 1, index2= 3. We return [1, 3].", + "image": null + }, + { + "text": "Example 3: Input:numbers = [-1,0], target = -1\nOutput:[1,2]\nExplanation:The sum of -1 and 0 is -1. Therefore index1= 1, index2= 2. We return [1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n s=0\n e=len(numbers)-1\n while s set = new HashSet<>();\n public boolean findTarget(TreeNode root, int k) {\n if(root == null){\n return false;\n }\n if(set.contains(k-root.val)){\n return true;\n }\n set.add(root.val);\n return findTarget(root.left,k) || findTarget(root.right,k);\n }\n}\n", + "title": "653. Two Sum IV - Input is a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a Binary Search Tree and a target number k , return true if there exist two elements in the BST such that their sum is equal to the given target .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^4 <= Node.val <= 10^4", + "root is guaranteed to be a valid binary search tree.", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], k = 9\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], k = 28\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n def inorder(root,l):\n if root:\n inorder(root.left,l)\n l.append(root.val)\n inorder(root.right,l)\n l = []\n inorder(root,l)\n left,right=0,len(l)-1\n while left!=right:\n sum = l[left] + l[right]\n if sum > k :\n right -=1\n elif sum bool:\n if n == 0:\n return False\n res=[2, 3, 5]\n while n!= 1:\n for i in res:\n if n%i==0:\n n=n//i\n break\n else:\n return False\n return True", + "title": "263. Ugly Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An ugly number is a positive integer whose prime factors are limited to 2 , 3 , and 5 . Given an integer n , return the n th ugly number .", + "description_images": [], + "constraints": [ + "1 <= n <= 1690" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:12\nExplanation:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1\nExplanation:1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 41.12%) | Memory: 41.5 MB (Top 87.73%)\n// Ugly number II\n// https://leetcode.com/problems/ugly-number-ii/\n\nclass Solution {\n public int nthUglyNumber(int n) {\n int[] dp = new int[n];\n dp[0] = 1;\n int i2 = 0, i3 = 0, i5 = 0;\n for (int i = 1; i < n; i++) {\n dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5));\n if (dp[i] == dp[i2] * 2) i2++;\n if (dp[i] == dp[i3] * 3) i3++;\n if (dp[i] == dp[i5] * 5) i5++;\n }\n return dp[n - 1];\n }\n}", + "title": "264. Ugly Number II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An ugly number is a positive integer whose prime factors are limited to 2 , 3 , and 5 . Given an integer n , return the n th ugly number .", + "description_images": [], + "constraints": [ + "1 <= n <= 1690" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10\nOutput:12\nExplanation:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:1\nExplanation:1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 354 ms (Top 28.01%) | Memory: 13.9 MB (Top 55.93%)\nimport heapq\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n h1, h2, h3 = [], [], []\n heapq.heappush(h1, 1)\n heapq.heappush(h2, 1)\n heapq.heappush(h3, 1)\n ugly_number = 1\n last_ugly_number = 1\n count = 1\n while count < n:\n if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:\n # pop from h1\n x = heapq.heappop(h1)\n ugly_number = 2 * x\n if ugly_number == last_ugly_number:\n # do nothing\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:\n # pop from h2\n x = heapq.heappop(h2)\n ugly_number = 3 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n else:\n # pop from h3\n x = heapq.heappop(h3)\n ugly_number = 5 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n return last_ugly_number", + "title": "264. Ugly Number II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An ugly number is a positive integer that is divisible by a , b , or c . Given four integers n , a , b , and c , return the n th ugly number .", + "description_images": [], + "constraints": [ + "1 <= n, a, b, c <= 10^9", + "1 <= a * b * c <= 10^18", + "It is guaranteed that the result will be in range [1, 2 * 10^9 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, a = 2, b = 3, c = 5\nOutput:4\nExplanation:The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rdis 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3, c = 4\nOutput:6\nExplanation:The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4this 6.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, a = 2, b = 11, c = 13\nOutput:10\nExplanation:The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5this 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.60 MB (Top 12.2%)\n\nclass Solution {\n public int nthUglyNumber(int n, int a, int b, int c) {\n int left = 1;\n int right = Integer.MAX_VALUE;\n int count = 0;\n while (left < right) {\n int middle = left + (right - left) / 2;\n if (isUgly(middle, a, b, c, n)) {\n right = middle;\n }\n else\n left = middle + 1;\n }\n return left;\n }\n public boolean isUgly(long middle, long a, long b, long c, long n) {\n return (int) (middle/a + middle/b + middle/c - middle/lcm(a, b) - middle/lcm(b, c) - middle/lcm(c, a) + middle/lcm(a, lcm(b, c))) >= n;\n }\n public long gcd(long a, long b) {\n if (a == 0)\n return b;\n else return gcd(b%a, a);\n }\n public long lcm(long a, long b) {\n return a * b / (gcd(a, b)); \n }\n}\n", + "title": "1201. Ugly Number III", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An ugly number is a positive integer that is divisible by a , b , or c . Given four integers n , a , b , and c , return the n th ugly number .", + "description_images": [], + "constraints": [ + "1 <= n, a, b, c <= 10^9", + "1 <= a * b * c <= 10^18", + "It is guaranteed that the result will be in range [1, 2 * 10^9 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, a = 2, b = 3, c = 5\nOutput:4\nExplanation:The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rdis 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3, c = 4\nOutput:6\nExplanation:The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4this 6.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, a = 2, b = 11, c = 13\nOutput:10\nExplanation:The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5this 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n times = [1,1,1]\n smallest = inf\n while n != 0:\n smallest = min ( times[0]*a,times[1]*b,times[2]*c)\n if times[0]*a == smallest: times[0] += 1\n if times[1]*b == smallest: times[1] += 1\n if times[2]*c == smallest: times[2] += 1\n n -= 1\n return smallest\n", + "title": "1201. Ugly Number III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2 , return a list of all the uncommon words . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 200", + "s1 and s2 consist of lowercase English letters and spaces.", + "s1 and s2 do not have leading or trailing spaces.", + "All the words in s1 and s2 are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"this apple is sweet\", s2 = \"this apple is sour\"\nOutput:[\"sweet\",\"sour\"]", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"apple apple\", s2 = \"banana\"\nOutput:[\"banana\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String[] uncommonFromSentences(String s1, String s2) {\n List list=new LinkedList<>();\n Map map=new HashMap<>();\n String[] arr1=s1.split(\" \");\n String[] arr2=s2.split(\" \");\n for(int i=0;i entry:map.entrySet()){\n if(entry.getValue()==1)\n list.add(entry.getKey());\n }\n String[] res=new String[list.size()];\n for(int i=0;i List[str]:\n x = dict(Counter(s1.split() + s2.split()))\n ans = []\n for key in x:\n if x[key] == 1:\n ans.append(key)\n \n return ans", + "title": "884. Uncommon Words from Two Sentences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 . We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way .", + "description_images": [], + "constraints": [ + "nums1[i] == nums2[j] , and", + "the line we draw does not intersect any other connecting (non-horizontal) line." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,4,2], nums2 = [1,2,4]\nOutput:2\nExplanation:We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.", + "image": "https://assets.leetcode.com/uploads/2019/04/26/142.png" + }, + { + "text": "Example 2: Input:nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxUncrossedLines(int[] nums1, int[] nums2) {\n int m = nums1.length;\n int n = nums2.length;\n int[][] dp = new int[m + 1][n + 1];\n for(int i = 1; i <= m; i ++){\n for(int j = 1; j <= n; j ++){\n if(nums1[i - 1] == nums2[j - 1])\n dp[i][j] = dp[i - 1][j - 1] + 1;\n else\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n return dp[m][n];\n }\n}\n", + "title": "1035. Uncrossed Lines", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 . We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way .", + "description_images": [], + "constraints": [ + "nums1[i] == nums2[j] , and", + "the line we draw does not intersect any other connecting (non-horizontal) line." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,4,2], nums2 = [1,2,4]\nOutput:2\nExplanation:We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.", + "image": "https://assets.leetcode.com/uploads/2019/04/26/142.png" + }, + { + "text": "Example 2: Input:nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n \n @lru_cache(None)\n def dp(a,b):\n if a>=len(nums1) or b>=len(nums2): return 0\n if nums1[a]==nums2[b]: return 1+dp(a+1,b+1)\n else: return max(dp(a+1,b),dp(a,b+1))\n \n return dp(0,0)\n", + "title": "1035. Uncrossed Lines", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n .", + "description_images": [], + "constraints": [ + "1 <= n <= 19" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:5", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numTrees(int n) {\n // Create 'sol' array of length n+1...\n int[] sol = new int[n+1];\n // The value of the first index will be 1.\n sol[0] = 1;\n // Run a loop from 1 to n+1...\n for(int i = 1; i <= n; i++) {\n // Within the above loop, run a nested loop from 0 to i...\n for(int j = 0; j < i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n }\n}\n", + "title": "96. Unique Binary Search Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n .", + "description_images": [], + "constraints": [ + "1 <= n <= 19" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:5", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 20.54%) | Memory: 13.9 MB (Top 13.32%)\nclass Solution(object):\n def numTrees(self, n):\n if n == 0 or n == 1:\n return 1\n # Create 'sol' array of length n+1...\n sol = [0] * (n+1)\n # The value of the first index will be 1.\n sol[0] = 1\n # Run a loop from 1 to n+1...\n for i in range(1, n+1):\n # Within the above loop, run a nested loop from 0 to i...\n for j in range(i):\n # Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1]\n # Return the value of the nth index of the array to get the solution...\n return sol[n]", + "title": "96. Unique Binary Search Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return all the structurally unique BST' s (binary search trees), which has exactly n nodes of unique values from 1 to n . Return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List generateTrees(int n) {\n return helper(1,n);\n }\n \n public List helper(int lo, int hi){\n List res=new ArrayList<>();\n if(lo>hi){\n res.add(null);\n return res;\n }\n \n \n for(int i=lo;i<=hi;i++){\n List left=helper(lo,i-1);\n List right=helper(i+1,hi);\n \n for(TreeNode l:left){\n for(TreeNode r:right){\n TreeNode head=new TreeNode(i);\n head.left=l;\n head.right=r;\n \n res.add(head);\n }\n }\n }\n \n return res;\n }\n}\n", + "title": "95. Unique Binary Search Trees II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return all the structurally unique BST' s (binary search trees), which has exactly n nodes of unique values from 1 to n . Return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 73 ms (Top 74.11%) | Memory: 15.7 MB (Top 42.55%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n # define a sorted list of the numbers, for each num in that list , leftvalues\n# are left tree and right val are rightree, then for each number create a tree\n# assign the left and right to that root and append the root to the ans\n nums = list(range(1,n+1))\n def dfs(nums):\n if not nums:\n return [None]\n ans = []\n for i in range(len(nums)):\n leftTrees = dfs(nums[:i])\n rightTrees = dfs(nums[i+1:])\n\n for l in leftTrees:\n for r in rightTrees:\n root = TreeNode(nums[i])\n root.left = l\n root.right = r\n ans.append(root)\n return ans\n\n return dfs(nums)\n", + "title": "95. Unique Binary Search Trees II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Every valid email consists of a local name and a domain name , separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+' . If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names . If you add a plus '+' in the local name , everything after the first plus sign will be ignored . This allows certain emails to be filtered. Note that this rule does not apply to domain names . It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i] , return the number of different addresses that actually receive mails .", + "description_images": [], + "constraints": [ + "For example, in \"alice@leetcode.com\" , \"alice\" is the local name , and \"leetcode.com\" is the domain name ." + ], + "examples": [ + { + "text": "Example 1: Input:emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]\nOutput:2\nExplanation:\"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.", + "image": null + }, + { + "text": "Example 2: Input:emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 57.45%) | Memory: 46.9 MB (Top 71.39%)\nclass Solution {\n public int numUniqueEmails(String[] emails) {\n\n Set finalEmails = new HashSet<>();\n for(String email: emails){\n StringBuilder name = new StringBuilder();\n boolean ignore = false;\n for(int i=0;i int:\n def ets(email):\n s, domain = email[:email.index('@')], email[email.index('@'):]\n s = s.replace(\".\", \"\")\n s = s[:s.index('+')] if '+' in s else s\n return s+domain\n dict = {}\n for i in emails:\n dict[ets(i)] = 1\n return len(dict)\n", + "title": "929. Unique Email Addresses", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"\nOutput:3\nExplanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"\nOutput:0\nExplanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"\nOutput:4\nExplanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPalindromicSubsequence(String s) {\n \n int n = s.length();\n \n char[] chArr = s.toCharArray();\n \n int[] firstOcc = new int[26];\n int[] lastOcc = new int[26];\n \n Arrays.fill(firstOcc, -1);\n Arrays.fill(lastOcc, -1);\n \n for(int i = 0; i < n; i++){\n \n char ch = chArr[i];\n \n if(firstOcc[ch - 'a'] == -1){\n firstOcc[ch - 'a'] = i;\n }\n \n lastOcc[ch - 'a'] = i;\n }\n \n int ans = 0, count = 0;\n \n boolean[] visited;\n \n\t\t// check for each character ( start or end of palindrome )\n for(int i = 0; i < 26; i++){\n \n int si = firstOcc[i]; // si - starting index\n int ei = lastOcc[i]; // ei - ending index\n \n visited = new boolean[26];\n \n count = 0;\n \n\t\t\t// check for unique charcters ( middle of palindrome )\n for(int j = si + 1; j < ei; j++){\n \n if(!visited[chArr[j] - 'a']){\n visited[chArr[j] - 'a'] = true;\n count++;\n }\n }\n \n ans += count;\n }\n \n return ans;\n }\n}\n", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"\nOutput:3\nExplanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"\nOutput:0\nExplanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"\nOutput:4\nExplanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countPalindromicSubsequence(self, s):\n d=defaultdict(list)\n for i,c in enumerate(s):\n d[c].append(i)\n ans=0\n for el in d:\n if len(d[el])<2:\n continue\n a=d[el][0]\n b=d[el][-1]\n ans+=len(set(s[a+1:b]))\n return(ans)\n", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"\nOutput:3\nExplanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"\nOutput:0\nExplanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"\nOutput:4\nExplanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countPalindromicSubsequence(self, s):\n d=defaultdict(list)\n for i,c in enumerate(s):\n d[c].append(i)\n ans=0\n for el in d:\n if len(d[el])<2:\n continue\n a=d[el][0]\n b=d[el][-1]\n ans+=len(set(s[a+1:b]))\n return(ans)\n\t\t", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: For convenience, the full table for the 26 letters of the English alphabet is given below: Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. Return the number of different transformations among all words we have .", + "description_images": [], + "constraints": [ + "'a' maps to \".-\" ,", + "'b' maps to \"-...\" ,", + "'c' maps to \"-.-.\" , and so on." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"gin\",\"zen\",\"gig\",\"msg\"]\nOutput:2\nExplanation:The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\"]\nOutput:1", + "image": null + }, + { + "text": "[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniqueMorseRepresentations(String[] words) {\n HashSet set = new HashSet<>();\n String[] morse = new String[]{\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n \n for (int i = 0; i < words.length; ++i) {\n String temp = \"\";\n for (int j = 0; j < words[i].length(); ++j) {\n temp += morse[(int)words[i].charAt(j)-'a'];\n }\n set.add(temp);\n }\n return set.size();\n }\n}\n", + "title": "804. Unique Morse Code Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: For convenience, the full table for the 26 letters of the English alphabet is given below: Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. Return the number of different transformations among all words we have .", + "description_images": [], + "constraints": [ + "'a' maps to \".-\" ,", + "'b' maps to \"-...\" ,", + "'c' maps to \"-.-.\" , and so on." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"gin\",\"zen\",\"gig\",\"msg\"]\nOutput:2\nExplanation:The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\"]\nOutput:1", + "image": null + }, + { + "text": "[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 50.2%) | Memory: 17.50 MB (Top 5.12%)\n\nclass Solution:\n def uniqueMorseRepresentations(self, words: List[str]) -> int:\n \n # create a dictionary for morse code (You can just copy & paste it! ^.^)\n ENG_to_MORSE = { \n 'a':\".-\", 'b':\"-...\", 'c':\"-.-.\", 'd':\"-..\", 'e':\".\",\n 'f':\"..-.\", 'g':\"--.\", 'h':\"....\", 'i':\"..\", 'j':\".---\",\n 'k':\"-.-\", 'l':\".-..\", 'm':\"--\", 'n':\"-.\", 'o':\"---\",\n 'p':\".--.\", 'q':\"--.-\", 'r':\".-.\", 's':\"...\", 't':\"-\",\n 'u':\"..-\", 'v':\"...-\", 'w':\".--\", 'x':\"-..-\", 'y':\"-.--\", 'z':\"--..\",\n }\n \n cnt = {} # dictionary for different transformations\n \n for word in words: # loop through every word\n \n tmp = \"\"\n \n for c in word: # loop through every character\n tmp += ENG_to_MORSE[c] # convert the word to morse code\n \n if tmp not in cnt:\n cnt[tmp] = 0\n else:\n cnt[tmp] += 1\n\n return len(cnt) # return how many different elements in cnt\n", + "title": "804. Unique Morse Code Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique , or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]\nOutput:true\nExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean uniqueOccurrences(int[] arr) {\n Arrays.sort(arr);\n HashSet set = new HashSet<>();\n\n int c = 1;\n for(int i = 1; i < arr.length; i++)\n {\n if(arr[i] == arr[i-1]) c++;\n\n else\n {\n if(set.contains(c)) return false;\n\n set.add(c);\n\n c = 1;\n }\n }\n\n if(set.contains(c)) return false;\n\n return true;\n }\n}", + "title": "1207. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique , or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]\nOutput:true\nExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n\t\t# defining dictionary\n occ = dict()\n \n\t\t# adding elements with their counts in dictionary\n for element in arr:\n if element not in occ:\n occ[element] = 0\n else:\n occ[element] += 1\n \n\t\t# list of count of elements\n values = list(occ.values())\n\t\t# Unique count\n unique = set(values)\n \n if len(values) == len(unique):\n return True\n else:\n return False\n", + "title": "1207. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7\nOutput:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2\nOutput:3\nExplanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePaths(int m, int n) {\n int[][] dp = new int[m][n];\n \n for(int i = 0; i < m; i ++) {\n for(int j = 0; j < n; j ++) {\n dp[i][j] = -1;\n }\n }\n \n return helper(m, 0, n, 0, dp);\n }\n \n private int helper(int m, int i, int n, int j, int[][] dp) {\n if(i == m || j == n) {\n return 0;\n }\n \n if(i == m-1 && j == n-1) {\n dp[i][j] = 1;\n }\n \n if(dp[i][j] == -1) {\n dp[i][j] = helper(m, i+1, n, j, dp) + helper(m, i, n, j+1, dp);\n }\n \n return dp[i][j];\n }\n}", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7\nOutput:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2\nOutput:3\nExplanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 53.95%) | Memory: 17.30 MB (Top 9.72%)\n\nclass Solution:\n def uniquePaths(self, m, n):\n dp = [[1]*n for i in range(m)]\n for i, j in product(range(1, m), range(1, n)):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n return dp[-1][-1]\n", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 .", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:2\nExplanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.40 MB (Top 60.59%)\n\nclass Solution {\n public int uniquePathsWithObstacles(int[][] OG) {\n if (OG[0][0] == 1) return 0;\n int m = OG.length, n = OG[0].length;\n int[][] dp = new int[m][n];\n dp[0][0] = 1;\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n if (OG[i][j] == 1 || (i == 0 && j == 0)) continue;\n else dp[i][j] = (i > 0 ? dp[i-1][j] : 0) + (j > 0 ? dp[i][j-1] : 0);\n return dp[m-1][n-1];\n }\n}\n", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 .", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:2\nExplanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 36.49%) | Memory: 14 MB (Top 43.32%)\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n def valid(r,c,matrix):\n return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0])\n\n dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))]\n dp[0][0] = 1 ^ obstacleGrid[0][0]\n\n for r in range(len(obstacleGrid)):\n for c in range(len(obstacleGrid[0])):\n if obstacleGrid[r][c] != 1:\n if valid(r-1, c, dp) and obstacleGrid[r-1][c] != 1:\n dp[r][c] += dp[r-1][c]\n if valid(r, c-1, dp) and obstacleGrid[r][c-1] != 1:\n dp[r][c] += dp[r][c-1]\n\n return dp[-1][-1]", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n integer array grid where grid[i][j] could be: Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once .", + "description_images": [], + "constraints": [ + "1 representing the starting square. There is exactly one starting square.", + "2 representing the ending square. There is exactly one ending square.", + "0 representing empty squares we can walk over.", + "-1 representing obstacles that we cannot walk over." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput:2\nExplanation:We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput:4\nExplanation:We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,1],[2,0]]\nOutput:0\nExplanation:There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 41.86%) | Memory: 42.7 MB (Top 13.82%)\nclass Solution {\n int walk = 0;\n public int uniquePathsIII(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0) {\n walk++;\n }\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n return ways(grid, i, j, m, n, 0);\n }\n }\n }\n return 0;\n }\n public int ways(int[][] grid, int cr, int cc, int m, int n, int count) {\n if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) {\n return 0;\n }\n if (grid[cr][cc] == 2) {\n if (count - 1 == walk) return 1;\n return 0;\n }\n grid[cr][cc] = -1;\n int ans = 0;\n int[] r = {0, 1, 0, -1};\n int[] c = {1, 0, -1, 0};\n for (int i = 0; i < 4; i++) {\n ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1);\n }\n grid[cr][cc] = 0;\n return ans;\n }\n}", + "title": "980. Unique Paths III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer array grid where grid[i][j] could be: Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once .", + "description_images": [], + "constraints": [ + "1 representing the starting square. There is exactly one starting square.", + "2 representing the ending square. There is exactly one ending square.", + "0 representing empty squares we can walk over.", + "-1 representing obstacles that we cannot walk over." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput:2\nExplanation:We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput:4\nExplanation:We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,1],[2,0]]\nOutput:0\nExplanation:There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ans, empty = 0, 1\n \n def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None:\n if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1:\n return\n nonlocal ans\n if grid[row][col] == 2:\n if empty == count:\n ans += 1\n return\n if (row, col) not in visited:\n visited.add((row, col))\n dfs(grid, row + 1, col, count + 1, visited)\n dfs(grid, row - 1, col, count + 1, visited)\n dfs(grid, row, col + 1, count + 1, visited)\n dfs(grid, row, col - 1, count + 1, visited)\n visited.remove((row, col))\n \n row, col = 0, 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n row, col = i, j\n elif grid[i][j] == 0:\n empty += 1\n dfs(grid, row, col, 0, set())\n return ans\n", + "title": "980. Unique Paths III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\" , so s will look like this: Given a string p , return the number of unique non-empty substrings of p are present in s .", + "description_images": [], + "constraints": [ + "\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\" ." + ], + "examples": [ + { + "text": "Example 1: Input:p = \"a\"\nOutput:1\n\nExplanation: Only the substring \"a\" of p is in s.", + "image": null + }, + { + "text": "Example 2: Input:p = \"cac\"\nOutput:2\nExplanation:There are two substrings (\"a\", \"c\") of p in s.", + "image": null + }, + { + "text": "Example 3: Input:p = \"zab\"\nOutput:6\nExplanation:There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.", + "image": null + } + ], + "follow_up": null, + "solution": "// One Pass Counting Solution\n// 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring.\n// 2. counts to track the longest continuos subtring starting with current character.\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int findSubstringInWraproundString(String p) {\n final int N = p.length();\n int res = 0, len = 1;\n int[] counts = new int[26];\n for (int i = 0; i < N; i++) {\n char ch = p.charAt(i);\n if (i > 0 && (ch - p.charAt(i-1) == 1 || ch - p.charAt(i-1) == -25)) {\n len++;\n } else {\n len = 1;\n }\n int idx = ch - 'a';\n counts[idx] = Math.max(counts[idx], len);\n }\n for (int count : counts) {\n res += count;\n }\n return res;\n }\n}\n", + "title": "467. Unique Substrings in Wraparound String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\" , so s will look like this: Given a string p , return the number of unique non-empty substrings of p are present in s .", + "description_images": [], + "constraints": [ + "\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\" ." + ], + "examples": [ + { + "text": "Example 1: Input:p = \"a\"\nOutput:1\n\nExplanation: Only the substring \"a\" of p is in s.", + "image": null + }, + { + "text": "Example 2: Input:p = \"cac\"\nOutput:2\nExplanation:There are two substrings (\"a\", \"c\") of p in s.", + "image": null + }, + { + "text": "Example 3: Input:p = \"zab\"\nOutput:6\nExplanation:There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.", + "image": null + } + ], + "follow_up": null, + "solution": "def get_next(char):\n x = ord(char)-ord('a')\n x = (x+1)%26\n return chr(ord('a') + x)\nclass Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n i = 0\n n = len(p)\n map_ = collections.defaultdict(int)\n while i bool:\n val1 = root.val\n self.tracker = False\n def dfs(root,val1):\n if not root:\n return \n if root.val!=val1:\n self.tracker=True\n dfs(root.left,val1)\n dfs(root.right,val1)\n return \n dfs(root,val1)\n \n if self.tracker == False:\n return True\n return False\n", + "title": "965. Univalued Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: This is how the UTF-8 encoding would work: x denotes a bit in the binary form of a byte that may be either 0 or 1 . Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.", + "description_images": [], + "constraints": [ + "1 <= data.length <= 2 * 10^4", + "0 <= data[i] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:data = [197,130,1]\nOutput:true\nExplanation:data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.", + "image": null + }, + { + "text": "Example 2: Input:data = [235,140,4]\nOutput:false\nExplanation:data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.", + "image": null + }, + { + "text": "Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 48.5 MB (Top 26.95%)\nclass Solution {\n public boolean validUtf8(int[] data) {\n return help(data,0);\n }\n\n public boolean help(int[] data,int index) {\n int n=data.length-index;\n if(n==0){\n return true;\n }\n int c0=count(data[index]);\n if(c0<0||c0>n){\n return false;\n }\n for(int i=index+1;i>3)==0b11110){\n return 4;\n }else if((a>>4)==0b1110){\n return 3;\n }else if((a>>5)==0b110){\n return 2;\n }else if((a>>7)==0){\n return 1;\n }\n return -1;\n }\n}", + "title": "393. UTF-8 Validation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: This is how the UTF-8 encoding would work: x denotes a bit in the binary form of a byte that may be either 0 or 1 . Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.", + "description_images": [], + "constraints": [ + "1 <= data.length <= 2 * 10^4", + "0 <= data[i] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:data = [197,130,1]\nOutput:true\nExplanation:data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.", + "image": null + }, + { + "text": "Example 2: Input:data = [235,140,4]\nOutput:false\nExplanation:data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.", + "image": null + }, + { + "text": "Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validUtf8(self, data: List[int]) -> bool:\n # Keep track of how many continuation bytes are left\n\t\t# Start at 0 since we are not expecting any continuation bytes at the beginning.\n cont_bytes_left = 0\n for byte in data:\n if cont_bytes_left == 0:\n\t\t\t # If we don't expect any continuation bytes\n\t\t\t # then there are 4 valid case for the current byte\n # byte >> 5 gives us the first 3 bits (8 bits - 5 = 3).\n if byte >> 5 == 0b110:\n\t\t\t\t # After seeing a byte that starts with 110,\n\t\t\t\t\t# we expect to see one continuation byte\n cont_bytes_left = 1\n elif byte >> 4 == 0b1110:\n cont_bytes_left = 2\n elif byte >> 3 == 0b11110:\n cont_bytes_left = 3\n # finally if the first bit isn't 0 then it's invalid\n elif byte >> 7 != 0:\n return False\n else:\n\t\t\t # If we are expecting a continuation byte there is only one valid case.\n # It's invalid if the continuation byte doesn't start with 10\n if byte >> 6 != 0b10:\n return False\n cont_bytes_left -= 1\n \n\t\t# Only valid if we aren't expecting any more continuation bytes\n return cont_bytes_left == 0\n", + "title": "393. UTF-8 Validation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return true if t is an anagram of s , and false otherwise . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"anagram\", t = \"nagaram\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\", t = \"car\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 73.70%) | Memory: 42.2 MB (Top 97.84%)\nclass Solution {\n public boolean isAnagram(String s, String t) {\n if (s.length() != t.length()) return false;\n int[] haha1 = new int[26];//26 because input contains of only lower english letters\n int[] haha2 = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n haha1[(int)s.charAt(i)-97] += 1;//omitting 97 because 'a' is 97, it will be 0 now\n haha2[(int)t.charAt(i)-97] += 1;\n }\n for (int i = 0; i < haha1.length; ++i) {\n if (haha1[i] != haha2[i]) return false;\n }\n return true;\n }\n}", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , return true if t is an anagram of s , and false otherwise . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"anagram\", t = \"nagaram\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\", t = \"car\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 42.25%) | Memory: 14.4 MB (Top 67.11%)\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n return Counter(s) == Counter(t)\n", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [start i , end i ] . An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length , we have end i-1 == start i . Return any valid arrangement of pairs . Note: The inputs will be generated such that there exists a valid arrangement of pairs .", + "description_images": [], + "constraints": [ + "1 <= pairs.length <= 10^5", + "pairs[i].length == 2", + "0 <= start i , end i <= 10^9", + "start i != end i", + "No two pairs are exactly the same.", + "There exists a valid arrangement of pairs ." + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[5,1],[4,5],[11,9],[9,4]]\nOutput:[[11,9],[9,4],[4,5],[5,1]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 9 == 9 = start1end1= 4 == 4 = start2end2= 5 == 5 = start3", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,3],[3,2],[2,1]]\nOutput:[[1,3],[3,2],[2,1]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 3 == 3 = start1end1= 2 == 2 = start2The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.", + "image": null + }, + { + "text": "Example 3: Input:pairs = [[1,2],[1,3],[2,1]]\nOutput:[[1,2],[2,1],[1,3]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 2 == 2 = start1end1= 1 == 1 = start2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] validArrangement(int[][] pairs) {\n int n = pairs.length;\n \n int[][] ans = new int[n][2];\n for (int[] a : ans) {\n a[0] = -1;\n a[1] = -1;\n }\n \n Map outdegree = new HashMap<>();\n Map> out = new HashMap<>();\n \n for (int[] pair : pairs) {\n outdegree.put(pair[0], outdegree.getOrDefault(pair[0], 0) + 1);\n outdegree.put(pair[1], outdegree.getOrDefault(pair[1], 0) - 1);\n \n out.computeIfAbsent(pair[0], k -> new ArrayDeque<>());\n out.computeIfAbsent(pair[1], k -> new ArrayDeque<>());\n \n out.get(pair[0]).addLast(pair[1]);\n }\n \n for (Map.Entry entry : outdegree.entrySet()) {\n if (entry.getValue() == 1) ans[0][0] = entry.getKey();\n if (entry.getValue() == -1) ans[n - 1][1] = entry.getKey();\n }\n \n if (ans[0][0] == -1) {\n ans[0][0] = pairs[0][0];\n ans[n - 1][1] = pairs[0][0];\n }\n \n int i = 0;\n int j = n - 1;\n while (i < j) {\n int from = ans[i][0];\n \n Deque toList = out.get(from);\n \n if (toList.size() == 0) {\n ans[j][0] = ans[--i][0];\n ans[--j][1] = ans[j + 1][0];\n } else {\n ans[i++][1] = toList.removeLast();\n ans[i][0] = ans[i - 1][1];\n }\n }\n \n return ans;\n }\n}\n", + "title": "2097. Valid Arrangement of Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [start i , end i ] . An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length , we have end i-1 == start i . Return any valid arrangement of pairs . Note: The inputs will be generated such that there exists a valid arrangement of pairs .", + "description_images": [], + "constraints": [ + "1 <= pairs.length <= 10^5", + "pairs[i].length == 2", + "0 <= start i , end i <= 10^9", + "start i != end i", + "No two pairs are exactly the same.", + "There exists a valid arrangement of pairs ." + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[5,1],[4,5],[11,9],[9,4]]\nOutput:[[11,9],[9,4],[4,5],[5,1]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 9 == 9 = start1end1= 4 == 4 = start2end2= 5 == 5 = start3", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,3],[3,2],[2,1]]\nOutput:[[1,3],[3,2],[2,1]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 3 == 3 = start1end1= 2 == 2 = start2The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.", + "image": null + }, + { + "text": "Example 3: Input:pairs = [[1,2],[1,3],[2,1]]\nOutput:[[1,2],[2,1],[1,3]]\nExplanation:This is a valid arrangement since endi-1always equals starti.\nend0= 2 == 2 = start1end1= 1 == 1 = start2", + "image": null + } + ], + "follow_up": null, + "solution": "#Hierholzer Algorithm\nfrom collections import defaultdict\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n G = defaultdict(list)\n din = defaultdict(int)\n dout = defaultdict(int)\n for v, w in pairs:\n G[v].append(w)\n dout[v] += 1\n din[w] += 1\n start = pairs[0][0]\n for v in G:\n if din[v]+1 == dout[v]:\n start = v\n route = []\n def dfs(v):\n while G[v]:\n w = G[v].pop()\n dfs(w)\n route.append(v)\n dfs(start)\n route.reverse()\n return [[route[i],route[i+1]] for i in range(len(route)-1)]\n", + "title": "2097. Valid Arrangement of Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array points where points[i] = [x i , y i ] represents a point on the X-Y plane, return true if these points are a boomerang . A boomerang is a set of three points that are all distinct and not in a straight line .", + "description_images": [], + "constraints": [ + "points.length == 3", + "points[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,3],[3,2]]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 58.12%) | Memory: 42.3 MB (Top 12.94%)\nclass Solution {\n public boolean isBoomerang(int[][] points) {\n double a, b, c, d, area;\n a=points[0][0]-points[1][0];\n b=points[1][0]-points[2][0];\n c=points[0][1]-points[1][1];\n d=points[1][1]-points[2][1];\n area=0.5*((a*d)-(b*c));\n return area!=0;\n }\n}", + "title": "1037. Valid Boomerang", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array points where points[i] = [x i , y i ] represents a point on the X-Y plane, return true if these points are a boomerang . A boomerang is a set of three points that are all distinct and not in a straight line .", + "description_images": [], + "constraints": [ + "points.length == 3", + "points[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,3],[3,2]]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n a,b,c=points\n return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0])\n", + "title": "1037. Valid Boomerang", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , return true if and only if it is a valid mountain array . Recall that arr is a mountain array if and only if:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1]\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,5,5]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,3,2,1]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.02%) | Memory: 54.3 MB (Top 41.77%)\nclass Solution {\n public boolean validMountainArray(int[] arr) {\n // edge case\n if(arr.length < 3) return false;\n // keep 2 pointers\n int i=0;\n int j=arr.length-1;\n // use i pointer to iterate through steep increase from LHS\n while(ii && arr[j]0;\n }\n}", + "title": "941. Valid Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , return true if and only if it is a valid mountain array . Recall that arr is a mountain array if and only if:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1]\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,5,5]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,3,2,1]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 153 ms (Top 95.7%) | Memory: 18.70 MB (Top 43.81%)\n\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr)<=2 or max(arr)==arr[0] or max(arr)==arr[len(arr)-1]:\n return False\n f=True\n for i in range(len(arr)-1):\n if f and arr[i]>=arr[i+1]:\n f=False\n if not f and arr[i]<=arr[i+1]:\n return False\n return True\n", + "title": "941. Valid Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"] , while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"] . Given a string s , return true if s is a valid number .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "s consists of only English letters (both uppercase and lowercase), digits ( 0-9 ), plus '+' , minus '-' , or dot '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"e\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:s = \".\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 19.3%) | Memory: 44.65 MB (Top 6.2%)\n\nclass Solution {\n public boolean isNumber(String s) {\n try{\n int l=s.length();\n if(s.equals(\"Infinity\")||s.equals(\"-Infinity\")||s.equals(\"+Infinity\")||s.charAt(l-1)=='f'||s.charAt(l-1)=='d'||s.charAt(l-1)=='D'||s.charAt(l-1)=='F')\n return false;\n double x=Double.parseDouble(s);\n return true;\n }\n catch(Exception e){\n return false;\n }\n \n }\n}", + "title": "65. Valid Number", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"] , while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"] . Given a string s , return true if s is a valid number .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "s consists of only English letters (both uppercase and lowercase), digits ( 0-9 ), plus '+' , minus '-' , or dot '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"e\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:s = \".\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isNumber(self, s: str) -> bool:\n if s == \"inf\" or s == \"-inf\" or s == \"+inf\" or s == \"Infinity\" or s == \"-Infinity\" or s == \"+Infinity\":\n return False\n try:\n float(s)\n except (Exception):\n return False\n return True\n", + "title": "65. Valid Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s consists only of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"A man, a plan, a canal: Panama\"\nOutput:true\nExplanation:\"amanaplanacanalpanama\" is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"race a car\"\nOutput:false\nExplanation:\"raceacar\" is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \" \"\nOutput:true\nExplanation:s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 313 ms (Top 34.84%) | Memory: 43.9 MB (Top 52.81%)\nclass Solution {\n public boolean isPalindrome(String s) {\n if(s.length()==1 || s.length()==0)\n {\n return true;\n }\n\n s=s.trim().toLowerCase();\n //s=s.toLowerCase();\n String a=\"\";\n boolean bool=false;\n for(int i=0;i='a' && s.charAt(i)<='z') || (s.charAt(i)>='0' && s.charAt(i)<='9'))\n {\n a=a+s.charAt(i);\n }\n }\n if(a.length()==1 || a.length()==0)\n {\n return true;\n }\n for(int i=0;i bool:\n cleaned = \"\"\n for c in s:\n if c.isalnum():\n cleaned += c.lower()\n return (cleaned == cleaned[::-1])\n\n \n", + "title": "125. Valid Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return true if the s can be palindrome after deleting at most one character from it .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"\nOutput:true\nExplanation:You could delete the character 'c'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n boolean first = false;\n public boolean validPalindrome(String s) {\n int left = 0;\n int right = s.length()-1;\n \n \n while(left <= right){\n if( s.charAt(left) == (s.charAt(right))){\n left++;\n right--;\n }else if(!first){\n first = true;\n String removeLeft = s.substring(0,left).concat(s.substring(left+1));\n String removeright = s.substring(0,right).concat(s.substring(right+1));\n left++;\n right--;\n return validPalindrome(removeLeft) || validPalindrome(removeright); \n } else {\n return false;\n }\n }\n return true; \n }\n}\n", + "title": "680. Valid Palindrome II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return true if the s can be palindrome after deleting at most one character from it .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"\nOutput:true\nExplanation:You could delete the character 'c'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 9164 ms (Top 5.04%) | Memory: 645.8 MB (Top 5.21%)\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n has_deleted = False\n\n def compare(s, has_deleted):\n\n if len(s) <= 1:\n return True\n\n if s[0] == s[-1]:\n return compare(s[1:-1], has_deleted)\n else:\n if not has_deleted:\n return compare(s[1:], True) or compare(s[:-1], True)\n else:\n return False\n\n return compare(s, has_deleted)", + "title": "680. Valid Palindrome II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"()[]{}\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(]\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 84.7%) | Memory: 40.80 MB (Top 15.0%)\n\nclass Solution {\n public boolean isValid(String s) {\n Stack stack = new Stack(); // create an empty stack\n for (char c : s.toCharArray()) { // loop through each character in the string\n if (c == '(') // if the character is an opening parenthesis\n stack.push(')'); // push the corresponding closing parenthesis onto the stack\n else if (c == '{') // if the character is an opening brace\n stack.push('}'); // push the corresponding closing brace onto the stack\n else if (c == '[') // if the character is an opening bracket\n stack.push(']'); // push the corresponding closing bracket onto the stack\n else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket\n // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack\n // does not match the closing bracket, the string is not valid, so return false\n return false;\n }\n // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n return stack.isEmpty();\n }\n}\n", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"()[]{}\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(]\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, string: str) -> bool:\n while True:\n if '()' in string:\n string = string.replace('()', '')\n elif '{}' in string:\n string = string.replace('{}', '')\n elif '[]' in string:\n string = string.replace('[]', '')\n\n else:\n return not string\n", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing only three types of characters: '(' , ')' and '*' , return true if s is valid . The following rules define a valid string:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"(*)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(*))\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution{\n\tpublic boolean checkValidString(String s){\n\t\tStack stack = new Stack<>();\n\t\tStack star = new Stack<>();\n\t\tfor(int i=0;i bool:\n left,right,star = deque(), deque(), deque() #indexes of all unmatched left right parens and all '*'\n # O(n) where n=len(s)\n for i,c in enumerate(s):\n if c == '(': # we just append left paren's index\n left.append(i)\n elif c == ')': # we check if we can find a match of left paren\n if left and left[-1] < i:\n left.pop()\n else:\n right.append(i)\n else: #'*' case we just add the postion\n star.append(i)\n if not left and not right: return True\n elif not star: return False #no star to save the string, return False\n l,r = 0 ,len(star)-1\n #O(n) since star will be length less than n\n # Note: left, right,and star are always kept in ascending order! And for any i in left, j in right, i > j, or they would have been matched in the previous for loop.\n while l<=r:\n if left:\n if left[-1]< star[r]: # we keep using right most star to match with right most '('\n left.pop()\n r -= 1\n else: return False # even the right most '*' can not match a '(', we can not fix the string.\n if right:\n if right[0] > star[l]:\n right.popleft()\n l += 1\n else: return False\n if not left and not right: return True #if after some fix, all matched, we return True\n", + "title": "678. Valid Parenthesis String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer num , write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt .", + "description_images": [], + "constraints": [ + "1 <= num <= 2^31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 16\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:num = 14\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.6 MB (Top 74.32%)\n\nclass Solution {\n public boolean isPerfectSquare(int num) {\n long start = 1;\n long end = num;\n\n while(start<=end){\n long mid = start +(end - start)/2;\n\n if(mid*mid==num){\n return true;\n }\n else if(mid*mid bool:\n if num == 1:\n return True\n lo = 2\n hi = num // 2\n while lo <= hi:\n mid = lo + (hi - lo) //2\n print(mid)\n if mid * mid == num:\n return True\n if mid * mid > num:\n hi = mid - 1\n else:\n lo = mid + 1\n return False\n", + "title": "367. Valid Perfect Square", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of length n where s[i] is either: A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i : Return the number of valid permutations perm . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "'D' means decreasing, or", + "'I' means increasing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"DID\"\nOutput:5\nExplanation:The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)", + "image": null + }, + { + "text": "Example 2: Input:s = \"D\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 88.89%) | Memory: 42.50 MB (Top 24.07%)\n\nclass Solution {\n\tpublic int numPermsDISequence(String s) {\n\t\tint length = s.length();\n\t\tint mod = 1000000007;\n\t\tint[] dp1 = new int[length + 1];\n\t\tint[] dp2 = new int[length];\n\t\tfor (int j = 0; j <= length; j++) {\n\t\t\tdp1[j] = 1;\n\t\t}\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (s.charAt(i) == 'I') {\n\t\t\t\tfor (int j = 0, curr = 0; j < length - i; j++) {\n\t\t\t\t\tdp2[j] = curr = (curr + dp1[j]) % mod;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (int j = length - i - 1, curr = 0; j >= 0; j--) {\n\t\t\t\t\tdp2[j] = curr = (curr + dp1[j + 1]) % mod;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdp1 = Arrays.copyOf(dp2, length);\n\t\t}\n\t\treturn dp1[0];\n\t}\n}\n", + "title": "903. Valid Permutations for DI Sequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s of length n where s[i] is either: A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i : Return the number of valid permutations perm . Since the answer may be large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "'D' means decreasing, or", + "'I' means increasing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"DID\"\nOutput:5\nExplanation:The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)", + "image": null + }, + { + "text": "Example 2: Input:s = \"D\"\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 80.0%) | Memory: 18.80 MB (Top 54.55%)\n\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [[None for j in range(n-i+1)] for i in range(n)]\n for j in range(n-1, 0-1, -1):\n if s[j] == \"I\":\n if j == n-1:\n dp[j][0] = 1\n dp[j][1] = 0\n else:\n dp[j][n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[j][i] = dp[j+1][i]+dp[j][i+1]\n else:\n if j == n-1:\n dp[j][0] = 0\n dp[j][1] = 1\n else:\n dp[j][0] = 0\n for i in range(1, n-j+1):\n dp[j][i] = dp[j+1][i-1]+dp[j][i-1]\n return sum([dp[0][i] for i in range(n+1)])%(10**9+7)\n", + "title": "903. Valid Permutations for DI Sequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the coordinates of four points in 2D space p1 , p2 , p3 and p4 , return true if the four points construct a square . The coordinate of a point p i is represented as [x i , y i ] . The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles).", + "description_images": [], + "constraints": [ + "p1.length == p2.length == p3.length == p4.length == 2", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.1%) | Memory: 40.42 MB (Top 51.8%)\n\nclass Solution {\n // This method returns true if the given 4 points form a square, false otherwise\n public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n // We use a set to store the distances between the points\n Set set = new HashSet();\n // Calculate the distances between all pairs of points and add them to the set\n set.add(distanceSquare(p1,p2));\n set.add(distanceSquare(p1,p3));\n set.add(distanceSquare(p1,p4));\n set.add(distanceSquare(p2,p3));\n set.add(distanceSquare(p2,p4));\n set.add(distanceSquare(p3,p4));\n // A square must have 4 equal sides, so the set must contain 2 different values (the lengths of the sides and the diagonals)\n // The set should not contain 0, as that would mean that two points have the same coordinates\n return !set.contains(0) && set.size() == 2;\n }\n // This method calculates the distance between two points and returns its square\n private int distanceSquare(int[] a, int[] b){\n // We use the Pythagorean theorem to calculate the distance between the points\n return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]);\n }\n}\n", + "title": "593. Valid Square", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the coordinates of four points in 2D space p1 , p2 , p3 and p4 , return true if the four points construct a square . The coordinate of a point p i is represented as [x i , y i ] . The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles).", + "description_images": [], + "constraints": [ + "p1.length == p2.length == p3.length == p4.length == 2", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 24.05%) | Memory: 13.9 MB (Top 50.57%)\nclass Solution:\n def validSquare(self, p1, p2, p3, p4):\n\n def cal(A, B):\n return abs(A[0] - B[0]) + abs(A[1] - B[1])\n\n d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)]\n d.sort()\n\n return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5]\n", + "title": "593. Valid Square", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:false\nExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": " for(int i=0; i<9; i++){\n for(int j=0; j<9; j++){\n if(board[i][j] != '.'){ \n char currentVal = board[i][j];\n if(!(seen.add(currentVal + \"found in row \"+ i)) ||\n !(seen.add(currentVal + \"found in column \"+ j) ) ||\n !(seen.add(currentVal + \"found in sub box \"+ i/3 + \"-\"+ j/3)))\n return false;\n }\n \n } \n \n }\n return true;\n}\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:false\nExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 104 ms (Top 89.12%) | Memory: 14 MB (Top 35.48%)\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n\n hrow = {}\n hcol = {}\n hbox = defaultdict(list)\n\n #CHECK FOR DUPLICATES ROWWISE\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[i][j] != '.':\n\n if board[i][j] not in hrow:\n hrow[board[i][j]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS ROW\n hrow.clear()\n print(\"TRUE1\")\n #CHECK FOR DUPLICATES COLUMNWISE\n\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[j][i] != '.':\n\n if board[j][i] not in hcol:\n hcol[board[j][i]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS COL\n\n hcol.clear()\n\n print('TRUE2')\n\n #CHECK DUPLICATE IN BOX, THIS IS WHERE KEY DESIGN SKILLS COME INTO PLAY, FOR SUDOKU YOU COMBINE ROW INDICES AND COL INDICES\n\n for i in range(9):\n for j in range(9):\n\n i_3 = i //3\n j_3 = j//3\n\n # print(hbox)\n if board[i][j] != '.':\n\n #CHECK ELEMENT OF ORIGINAL INDICE present in key i_3 , j_3\n if board[i][j] not in hbox[i_3 , j_3]:\n# #CHECKED IN NEW KEY\n hbox[i_3 ,j_3 ]= hbox[i_3 ,j_3 ] + [board[i][j]]\n\n else:\n return False\n\n return True\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a Tic-Tac-Toe board as a string array board , return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ' , 'X' , and 'O' . The ' ' character represents an empty square. Here are the rules of Tic-Tac-Toe:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player always places 'X' characters, while the second player always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"O \",\" \",\" \"]\nOutput:false\nExplanation:The first player always plays \"X\".", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [\"XOX\",\" X \",\" \"]\nOutput:false\nExplanation:Players take turns making moves.", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [\"XOX\",\"O O\",\"XOX\"]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 71.13%) | Memory: 41.6 MB (Top 42.96%)\nclass Solution {\n public boolean validTicTacToe(String[] board) {\n //cnt number of X and O\n int x = cntNumber('X', board);\n //this check can be omitted, it can be covered in the second number check.\n if(x >5){\n return false;\n }\n int o = cntNumber('O', board);\n if(x < o || x > o + 1){\n return false;\n }\n //if(x <3 ) true, no need to see winning\n if(o >= 3){\n //if x has won, but game doesnt stop\n if(x == o && hasWon('X', board)){\n return false;\n }\n //if o has won, but game doesnt stop\n if( x > o && hasWon('O', board) ){\n return false;\n }\n }\n return true;\n }\n\n private int cntNumber(char target, String[] board){\n int res = 0;\n for(int i = 0; i<3; i++) {\n for(int j = 0; j<3; j++) {\n if(target == board[i].charAt(j)){\n res++;\n }\n }\n }\n return res;\n }\n\n private boolean hasWon(char target, String[] board){\n String toWin = Character.toString(target).repeat(3);\n for(int i = 0; i<3; i++) {\n if(board[i].equals(toWin)){\n return true;\n }\n }\n for(int j = 0; j<3; j++) {\n boolean col = true;\n for(int i = 0; i<3; i++) {\n col = col && target == board[i].charAt(j);\n if(!col){\n break;\n }\n }\n if(col){\n return true;\n }\n }\n //check diagonal. If center is not target, not possible to form diag win.\n if(target != board[1].charAt(1)){\n return false;\n }\n\n boolean diagonal1 = target == board[0].charAt(0);\n //only proceed if the first letter match. Otherwise might get false positive\n if(diagonal1){\n if(target == board[2].charAt(2)){\n return true;\n }\n }\n\n boolean diagonal2 = target == board[0].charAt(2);\n if(diagonal2){\n if(target == board[2].charAt(0)){\n return true;\n }\n }\n return false;\n }\n}", + "title": "794. Valid Tic-Tac-Toe State", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a Tic-Tac-Toe board as a string array board , return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ' , 'X' , and 'O' . The ' ' character represents an empty square. Here are the rules of Tic-Tac-Toe:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player always places 'X' characters, while the second player always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"O \",\" \",\" \"]\nOutput:false\nExplanation:The first player always plays \"X\".", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [\"XOX\",\" X \",\" \"]\nOutput:false\nExplanation:Players take turns making moves.", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [\"XOX\",\"O O\",\"XOX\"]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def validTicTacToe(self, board: List[str]) -> bool:\n # The two criteria for a valid board are:\n # 1) num of Xs - num of Os is 0 or 1\n # 2) X is not a winner if the # of moves is even, and\n # O is not a winner if the # of moves is odd.\n\n d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array\n s = [d[ch] for ch in ''.join(board)] # Ex: [\"XOX\",\" X \",\" \"] --> [1,-1,1,0,1,0,0,0,0]\n sm = sum(s)\n\n if sm>>1: return False # <-- criterion 1\n \n n = -3 if sm == 1 else 3 # <-- criterion 2.\n if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], \n s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are \n s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags\n \n return True # <-- both criteria are true", + "title": "794. Valid Tic-Tac-Toe State", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,4]\nOutput:3\nExplanation:Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 95.13%) | Memory: 43.50 MB (Top 23.38%)\n\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int i=n-1;i>=1;i--){\n int left=0,right=i-1;\n while(lefta[i]){\n count+=right-left;\n right--;\n }\n else\n left++;\n }\n }\n return count;\n }\n}\n", + "title": "611. Valid Triangle Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,4]\nOutput:3\nExplanation:Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,4]\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}\n", + "title": "611. Valid Triangle Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]\nOutput:false\nExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValidBST(TreeNode root) {\n return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);\n }\n \n public boolean dfs(TreeNode root, int min, int max) {\n if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) || (root.val == Integer.MAX_VALUE && root.right != null)) return false;\n boolean leftRight = true;\n if (root.left == null && root.right == null) return true;\n if (root.left != null) {\n leftRight = dfs(root.left, min, root.val - 1);\n }\n if (root.right != null) {\n leftRight = dfs(root.right, root.val + 1, max) && leftRight;\n }\n return leftRight;\n }\n}\n", + "title": "98. Validate Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]\nOutput:false\nExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 89 ms (Top 18.35%) | Memory: 16.5 MB (Top 80.77%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n\n def valid(node,left,right):\n if not node: # checking node is none\n return True\n if not (node.val>left and node.val 1) {\n return false;\n }\n }\n if (r != -1) {\n // Same thing for parent node and the right child node\n if (!uf.union(i, r) || ++indeg[r] > 1) {\n return false;\n }\n }\n }\n return uf.connected();\n }\n}\n", + "title": "1361. Validate Binary Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i] , return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1 , similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem.", + "description_images": [], + "constraints": [ + "n == leftChild.length == rightChild.length", + "1 <= n <= 10^4", + "-1 <= leftChild[i], rightChild[i] <= n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex1.png" + }, + { + "text": "Example 2: Input:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex2.png" + }, + { + "text": "Example 3: Input:n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex3.png" + } + ], + "follow_up": null, + "solution": " class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \n left_set=set(leftChild)\n right_set=set(rightChild) \n\n que=[]\n\n for i in range(n):\n if i not in left_set and i not in right_set:\n que.append(i)\n \n if len(que)>1 or len(que)==0:\n return False\n \n \n graph=defaultdict(list)\n\n for i in range(n):\n graph[i]=[]\n\n if leftChild[i]!=-1:\n graph[i].append(leftChild[i])\n\n if rightChild[i]!=-1:\n graph[i].append(rightChild[i])\n \n visited=set()\n visited.add(que[0])\n \n \n while len(que)>0:\n item=que.pop(0)\n \n\n children=graph[item]\n\n for child in children:\n if child not in visited:\n que.append(child)\n visited.add(child)\n else:\n return False\n\n\n for i in range(n):\n if i not in visited:\n return False\n\n return True\n", + "title": "1361. Validate Binary Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string queryIP , return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form \"x 1 .x 2 .x 3 .x 4 \" where 0 <= x i <= 255 and x i cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\" , \"192.168.1.00\" , and \"192.168@1.1\" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form \"x 1 :x 2 :x 3 :x 4 :x 5 :x 6 :x 7 :x 8 \" where: For example, \" 2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \" 2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \" 2001:0db8:85a3::8A2E:037j:7334\" and \" 02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses.", + "description_images": [], + "constraints": [ + "1 <= x i .length <= 4", + "x i is a hexadecimal string which may contain digits, lowercase English letter ( 'a' to 'f' ) and upper-case English letters ( 'A' to 'F' ).", + "Leading zeros are allowed in x i ." + ], + "examples": [ + { + "text": "Example 1: Input:queryIP = \"172.16.254.1\"\nOutput:\"IPv4\"\nExplanation:This is a valid IPv4 address, return \"IPv4\".", + "image": null + }, + { + "text": "Example 2: Input:queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\nOutput:\"IPv6\"\nExplanation:This is a valid IPv6 address, return \"IPv6\".", + "image": null + }, + { + "text": "Example 3: Input:queryIP = \"256.256.256.256\"\nOutput:\"Neither\"\nExplanation:This is neither a IPv4 address nor a IPv6 address.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 94.74%) | Memory: 41.50 MB (Top 35.64%)\n\nclass Solution {\n public String validIPAddress(String IP) {\n if(IP.length()==0) return \"Neither\";\n \n if(IP.indexOf(\".\")>=0) return validateIPV4(IP);\n \n if(IP.indexOf(\":\")>=0) return validateIPV6(IP);\n \n return \"Neither\";\n }\n \n private String validateIPV4(String ip){\n\t // step 1 \n if(ip.charAt(0)=='.' || ip.charAt(ip.length()-1)=='.') return \"Neither\";\n \n\t\t //step 2 \n String[] component=ip.split(\"\\\\.\");\n \n\t\t //step 3\n if(component.length!=4) return \"Neither\";\n \n\t\t //step 4\n for(String comp:component){\n if(comp.length()==0 || comp.length()>3 || (comp.charAt(0)=='0' && comp.length()>1)){\n return \"Neither\";\n }\n \n\t\t\t //step5\n for(char ch:comp.toCharArray()){\n if(ch<'0' || ch>'9') return \"Neither\";\n }\n \n\t\t\t //step6\n int num=Integer.parseInt(comp);\n if(num<0 || num>255) return \"Neither\";\n \n }\n \n return \"IPv4\";\n }\n \n private String validateIPV6(String ip){\n if(ip.charAt(0)==':' || ip.charAt(ip.length()-1)==':') return \"Neither\";\n \n String[] component=ip.split(\":\");\n \n if(component.length!=8) return \"Neither\";\n \n for(String comp:component){\n if(comp.length()==0 || comp.length()>4) return \"Neither\";\n \n \n for(char ch:comp.toLowerCase().toCharArray()){\n if((ch<'0' || ch>'9') && (ch!='a' && ch!='b' && ch!='c' && ch!='d' && ch!='e' && ch!='f')){\n return \"Neither\";\n } \n }\n }\n return \"IPv6\";\n }\n }\n", + "title": "468. Validate IP Address", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string queryIP , return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form \"x 1 .x 2 .x 3 .x 4 \" where 0 <= x i <= 255 and x i cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\" , \"192.168.1.00\" , and \"192.168@1.1\" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form \"x 1 :x 2 :x 3 :x 4 :x 5 :x 6 :x 7 :x 8 \" where: For example, \" 2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \" 2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \" 2001:0db8:85a3::8A2E:037j:7334\" and \" 02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses.", + "description_images": [], + "constraints": [ + "1 <= x i .length <= 4", + "x i is a hexadecimal string which may contain digits, lowercase English letter ( 'a' to 'f' ) and upper-case English letters ( 'A' to 'F' ).", + "Leading zeros are allowed in x i ." + ], + "examples": [ + { + "text": "Example 1: Input:queryIP = \"172.16.254.1\"\nOutput:\"IPv4\"\nExplanation:This is a valid IPv4 address, return \"IPv4\".", + "image": null + }, + { + "text": "Example 2: Input:queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\nOutput:\"IPv6\"\nExplanation:This is a valid IPv6 address, return \"IPv6\".", + "image": null + }, + { + "text": "Example 3: Input:queryIP = \"256.256.256.256\"\nOutput:\"Neither\"\nExplanation:This is neither a IPv4 address nor a IPv6 address.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validIPAddress(self, queryIP: str) -> str:\n queryIP = queryIP.replace(\".\",\":\")\n ct = 0\n for i in queryIP.split(\":\"):\n if i != \"\":\n ct += 1\n if ct == 4:\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if i.isnumeric():\n if len(i) > 1:\n if i.count('0') == len(i) or int(i) > 255 or i[0] == '0':\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv4\"\n elif ct == 8:\n a = ['a','b','c','d','e','f','A','B','C','D','E','F']\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if len(i) < 5:\n for j in i:\n if j not in a and j.isdigit() == False:\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv6\"\n else:\n return \"Neither\"\n \n\n\n ", + "title": "468. Validate IP Address", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= pushed.length <= 1000", + "0 <= pushed[i] <= 1000", + "All the elements of pushed are unique .", + "popped.length == pushed.length", + "popped is a permutation of pushed ." + ], + "examples": [ + { + "text": "Example 1: Input:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput:true\nExplanation:We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1", + "image": null + }, + { + "text": "Example 2: Input:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput:false\nExplanation:1 cannot be popped before 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 57.66%) | Memory: 44.5 MB (Top 82.21%)\n\nclass Solution {\n public boolean validateStackSequences(int[] pushed, int[] popped) {\n Stack st = new Stack<>(); // Create a stack\n\n int j = 0; // Intialise one pointer pointing on popped array\n\n for(int val : pushed){\n st.push(val); // insert the values in stack\n while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j];\n st.pop(); // then pop out\n j++; // increment j\n }\n }\n return st.isEmpty(); // check if stack is empty return true else false\n }\n}", + "title": "946. Validate Stack Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.", + "description_images": [], + "constraints": [ + "1 <= pushed.length <= 1000", + "0 <= pushed[i] <= 1000", + "All the elements of pushed are unique .", + "popped.length == pushed.length", + "popped is a permutation of pushed ." + ], + "examples": [ + { + "text": "Example 1: Input:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput:true\nExplanation:We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1", + "image": null + }, + { + "text": "Example 2: Input:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput:false\nExplanation:1 cannot be popped before 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n i=0\n for num in pushed:\n stack.append(num) #we are pushing the number to the stack\n while len(stack) >0 and stack[len(stack)-1] == popped[i] :\n #if the last element of the stack is equal to the popped element\n stack.pop()\n i+=1 #we are incrementing i\n return True if len(stack) ==0 else False\n\t\t\n", + "title": "946. Validate Stack Sequences", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Return true if the equation is solvable, otherwise return false .", + "description_images": [], + "constraints": [ + "Each character is decoded as one digit (0 - 9).", + "No two characters can map to the same digit.", + "Each words[i] and result are decoded as one number without leading zeros.", + "Sum of numbers on the left side ( words ) will equal to the number on the right side ( result )." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput:true\nExplanation:Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652", + "image": null + }, + { + "text": "Example 2: Input:words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput:true\nExplanation:Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214", + "image": null + }, + { + "text": "Example 3: Input:words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput:false\nExplanation:There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 96.2%) | Memory: 40.32 MB (Top 56.2%)\n\nclass Solution {\n public static boolean isSolvable(String[] words, String result) {\n\t // reverse all strings to facilitate add calculation.\n for (int i = 0; i < words.length; i++) {\n words[i] = new StringBuilder(words[i]).reverse().toString();\n }\n result = new StringBuilder(result).reverse().toString();\n if (!checkLength(words, result)) {\n return false;\n }\n boolean[] visited = new boolean[10]; // digit 0, 1, ..., 9\n int[] chToDigit = new int[26];\n Arrays.fill(chToDigit, -1);\n return dfs(0, 0, 0, visited, chToDigit, words, result);\n }\n\n /**\n * Elminate the case where result is too long\n * word1: AAA\n * word2: BBB\n * result: XXXXXXXXX\n */\n private static boolean checkLength(String[] words, String result) {\n int maxLen = 0;\n for (String word : words) {\n maxLen = Math.max(maxLen, word.length());\n }\n return result.length() == maxLen || result.length() == maxLen + 1;\n }\n\n /*\n Put all words like this:\n w1: ABC\n w2: EF\n w3: GHIJ\n result: KLMNO\n i, is the row\n j, is the column\n carrier, the one contributed from previous calculation\n chToDigit, 26 int array, which records choosen digit for 'A', 'B', 'C', ... If not choosen any, default is -1 \n */\n private static boolean dfs(int i, int j, int carrier, boolean[] visited, int[] chToDigit, String[] words, String result) {\n if (i == words.length) {\n char ch = result.charAt(j);\n // (i, i) at bottom right corner. final check\n if (j == result.length() - 1) {\n // 1. check if carrier is equal or greater than 10. If so, false.\n if (carrier >= 10) {\n return false;\n }\n // 2. check if result.length() > 1 && result.lastCh is zero. If so the false.\n if (j > 0 && j == result.length() - 1 && chToDigit[ch - 'A'] == 0) {\n return false;\n }\n // not selected, can select any. True.\n if (chToDigit[ch - 'A'] == -1) {\n System.out.println(Arrays.toString(chToDigit));\n return true;\n } else { // if selected, check if it matches with carrier. Also, carrier can't be 0. result = '00' is invalid\n return chToDigit[ch - 'A'] == carrier;\n }\n } else { // reached normal result line.\n // 1. if not selected. Use current carrier's unit digit\n if (chToDigit[ch - 'A'] == -1) {\n int selectedDigit = carrier % 10;\n // For example carrier = 13. selectedDigit = 3. ch = 'H'. Should set 3 to 'H'.\n // But 3 is already taken by 'B' previously. So wrong.\n if (visited[selectedDigit]) {\n return false;\n }\n visited[selectedDigit] = true;\n chToDigit[ch - 'A'] = selectedDigit;\n if (dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result)) {\n return true;\n }\n chToDigit[ch - 'A'] = -1;\n visited[selectedDigit] = false;\n } else { // 2. selected\n // just need to check if ch.digit equals to unit digit.\n if (chToDigit[ch - 'A'] != carrier % 10) {\n return false;\n }\n boolean ans = dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result);\n return ans;\n }\n } //\n } else { // normal word\n String word = words[i];\n // 1. check if j is equal or greater than word.len. If so pass to next word.\n if (j >= word.length()) {\n boolean ans = dfs(i + 1, j, carrier, visited, chToDigit, words, result);\n return ans;\n }\n // 2. check if it's last ch, word.len is greater than 1, and is '0'. If so false;\n if (j == word.length() - 1 && word.length() > 1 && chToDigit[word.charAt(j) - 'A'] == 0) {\n return false;\n }\n char ch = word.charAt(j);\n // 3. check if word.ch is selected. Just add current digit and move to next word.\n if (chToDigit[ch - 'A'] != -1) {\n int newSum = carrier + chToDigit[ch - 'A'];\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n return ans;\n } else {\n for (int k = 0; k < visited.length; k++) {\n if (visited[k]) {\n continue;\n }\n visited[k] = true;\n chToDigit[ch - 'A'] = k;\n int newSum = k + carrier;\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n if (ans) {\n return true;\n }\n visited[k] = false;\n chToDigit[ch - 'A'] = -1;\n }\n }\n }\n return false;\n }\n}", + "title": "1307. Verbal Arithmetic Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Return true if the equation is solvable, otherwise return false .", + "description_images": [], + "constraints": [ + "Each character is decoded as one digit (0 - 9).", + "No two characters can map to the same digit.", + "Each words[i] and result are decoded as one number without leading zeros.", + "Sum of numbers on the left side ( words ) will equal to the number on the right side ( result )." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput:true\nExplanation:Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652", + "image": null + }, + { + "text": "Example 2: Input:words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput:true\nExplanation:Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214", + "image": null + }, + { + "text": "Example 3: Input:words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput:false\nExplanation:There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n \n # reverse words\n words = [i[::-1] for i in words]\n result = result[::-1]\n allWords = words + [result]\n \n # chars that can not be 0\n nonZero = set()\n for word in allWords:\n if len(word) > 1:\n nonZero.add(word[-1])\n \n # numbers selected in backtracking\n selected = set()\n # char to Int map\n charToInt = dict()\n mxLen = max([len(i) for i in allWords])\n \n def res(i = 0, c = 0, sm = 0):\n if c == mxLen:\n return 1 if sm == 0 else 0\n elif i == len(words):\n num = sm % 10\n carry = sm // 10\n if c >= len(result):\n if num == 0:\n return res(0, c+1, carry)\n else:\n return 0\n # result[c] should be mapped to num if a mapping exists\n if result[c] in charToInt:\n if charToInt[result[c]] != num:\n return 0\n else:\n return res(0, c+1, carry)\n elif num in selected:\n return 0\n # if mapping does not exist, create a mapping\n elif (num == 0 and result[c] not in nonZero) or num > 0:\n selected.add(num)\n charToInt[result[c]] = num\n ret = res(0, c + 1, carry)\n del charToInt[result[c]]\n selected.remove(num)\n return ret\n else:\n return 0\n else:\n word = words[i]\n if c >= len(word):\n return res(i+1, c, sm)\n elif word[c] in charToInt:\n return res(i+1, c, sm + charToInt[word[c]])\n else:\n ret = 0\n # possibilities for word[c]\n for j in range(10):\n if (j == 0 and word[c] not in nonZero) or j > 0:\n if j not in selected:\n selected.add(j)\n charToInt[word[c]] = j\n ret += res(i + 1, c, sm + j)\n del charToInt[word[c]]\n selected.remove(j)\n return ret\n \n return res() > 0", + "title": "1307. Verbal Arithmetic Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "One way to serialize a binary tree is to use preorder traversal . When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#' . For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\" , where '#' represents a null node. Given a string of comma-separated values preorder , return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. Note: You are not allowed to reconstruct the tree.", + "description_images": [], + "constraints": [ + "For example, it could never contain two consecutive commas, such as \"1,,3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:preorder = \"1,#\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:preorder = \"9,#,#,1\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValidSerialization(String preorder) {\n String[] strs = preorder.split(\",\");\n //In starting we have one vacany for root\n int vacancy = 1;\n \n for(String str : strs){\n \n if(--vacancy < 0 ) return false;\n \n // whenever we encounter a new node vacancy decreases by 1 and left and right two vacancy for that node will added in total\n if(!str.equals(\"#\")) \n vacancy += 2;\n \n }\n \n \n return vacancy == 0;\n \n }\n}\n", + "title": "331. Verify Preorder Serialization of a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "One way to serialize a binary tree is to use preorder traversal . When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#' . For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\" , where '#' represents a null node. Given a string of comma-separated values preorder , return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. Note: You are not allowed to reconstruct the tree.", + "description_images": [], + "constraints": [ + "For example, it could never contain two consecutive commas, such as \"1,,3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:preorder = \"1,#\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:preorder = \"9,#,#,1\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 77 ms (Top 11.09%) | Memory: 13.8 MB (Top 99.05%)\nclass Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n nodes = preorder.split(',')\n counter=1\n for i, node in enumerate(nodes):\n if node != '#':\n counter+=1\n else:\n if counter <= 1 and i != len(nodes) - 1:\n return False\n counter-=1\n return counter == 0", + "title": "331. Verify Preorder Serialization of a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order . The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "order.length == 26", + "All characters in words[i] and order are English lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\nOutput:true\nExplanation:As 'h' comes before 'l' in this language, then the sequence is sorted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\nOutput:false\nExplanation:As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\nOutput:false\nExplanation:The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 80.43%) | Memory: 42.9 MB (Top 28.86%)\nclass Solution {\n public boolean isAlienSorted(String[] words, String order) {\n int val=1;\n int[] alp = new int[26];\n\n for(int i=0;i alp[words[i+1].charAt(j)-'a']) {\n return false;\n } else if(alp[words[i].charAt(j)-'a'] < alp[words[i+1].charAt(j)-'a']) {\n flag=1;\n break;\n }\n }\n if(flag==0 && words[i].length()>words[i+1].length()) {\n return false; // if second word is sub string of first word starting from the beginning, return false.\n }\n }\n\n return true;\n }\n}", + "title": "953. Verifying an Alien Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order . The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "order.length == 26", + "All characters in words[i] and order are English lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\nOutput:true\nExplanation:As 'h' comes before 'l' in this language, then the sequence is sorted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\nOutput:false\nExplanation:As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\nOutput:false\nExplanation:The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 17.14%) | Memory: 13.7 MB (Top 99.39%)\nclass Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n order_index = {key:index for index, key in enumerate(order)}\n\n for i in range(len(words)-1):\n w1,w2 = words[i] , words[i + 1]\n for j in range(len(w1)):\n if j == len(w2):\n return False\n if w1[j] != w2[j]:\n if order_index.get(w2[j]) < order_index.get(w1[j]):\n return False\n break\n return True", + "title": "953. Verifying an Alien Dictionary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col) , its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0) . The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[9],[3,15],[20],[7]]\nExplanation:Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7]\nOutput:[[4],[2],[1,5,6],[3],[7]]\nExplanation:Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2,3,4,6,5,7]\nOutput:[[4],[2],[1,5,6],[3],[7]]\nExplanation:This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.64%) | Memory: 42.3 MB (Top 95.72%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n private static class MNode {\n TreeNode Node;\n int hDist;\n int level;\n MNode(TreeNode node, int hd, int l) {\n Node = node;\n hDist = hd;\n level = l;\n }\n }\n\n public List> verticalTraversal(TreeNode root) {\n Map> map = new TreeMap<>();\n Queue q = new LinkedList<>();\n\n q.add(new MNode(root, 0, 0));\n\n while(!q.isEmpty()) {\n\n MNode curr = q.poll();\n if(map.containsKey(curr.hDist))\n map.get(curr.hDist).add(curr);\n\n else {\n PriorityQueue pq = new PriorityQueue<>\n ((a,b) -> (a.level == b.level)? a.Node.val - b.Node.val: a.level - b.level);\n pq.add(curr);\n map.put(curr.hDist, pq);\n }\n\n if(curr.Node.left != null)\n q.add(new MNode(curr.Node.left, curr.hDist -1, curr.level + 1));\n\n if(curr.Node.right != null)\n q.add(new MNode(curr.Node.right, curr.hDist +1, curr.level + 1));\n }\n\n List> ans = new ArrayList<>();\n for(Integer key: map.keySet()) {\n List temp = new ArrayList<>();\n while(!map.get(key).isEmpty()) { temp.add(map.get(key).poll().Node.val); }\n ans.add(new ArrayList<>(temp));\n }\n\n return ans;\n\n }\n\n}", + "title": "987. Vertical Order Traversal of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col) , its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0) . The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[9],[3,15],[20],[7]]\nExplanation:Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7]\nOutput:[[4],[2],[1,5,6],[3],[7]]\nExplanation:Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2,3,4,6,5,7]\nOutput:[[4],[2],[1,5,6],[3],[7]]\nExplanation:This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 69 ms (Top 15.25%) | Memory: 14.3 MB (Top 28.85%)\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def verticalTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n q = [(0, 0, root)]\n l = []\n while q:\n col, row, node = q.pop()\n l.append((col, row, node.val))\n if node.left:\n q.append((col-1, row+1, node.left))\n if node.right:\n q.append((col+1, row+1, node.right))\n l.sort()\n print(l)\n ans = []\n ans.append([l[0][-1]])\n for i in range(1, len(l)):\n if l[i][0] > l[i-1][0]:\n ans.append([l[i][-1]])\n else:\n ans[-1].append(l[i][-1])\n return ans\n", + "title": "987. Vertical Order Traversal of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [start i , end i ] indicates that the ith clip started at start i and ended at end i . We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time] . If the task is impossible, return -1 .", + "description_images": [], + "constraints": [ + "For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7] ." + ], + "examples": [ + { + "text": "Example 1: Input:clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput:3\nExplanation:We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].", + "image": null + }, + { + "text": "Example 2: Input:clips = [[0,1],[1,2]], time = 5\nOutput:-1\nExplanation:We cannot cover [0,5] with only [0,1] and [1,2].", + "image": null + }, + { + "text": "Example 3: Input:clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput:3\nExplanation:We can take clips [0,4], [4,7], and [6,9].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int videoStitching(int[][] clips, int time) {\n Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);\n int n = clips.length;\n int interval[] = new int[2];\n int cuts = 0;\n while(true){\n cuts++;\n int can_reach = 0;\n for(int i = interval[0]; i <= interval[1]; i++){\n int j = 0;\n while(j < n){\n if(clips[j][0] < i){\n j++;\n }\n else if(clips[j][0] == i){\n can_reach = Math.max(can_reach , clips[j][1]);\n j++;\n }\n else{\n break;\n }\n }\n if(can_reach >= time) return cuts;\n }\n interval[0] = interval[1] + 1;\n interval[1] = can_reach;\n if(interval[0] > interval[1]) return -1;\n }\n }\n}", + "title": "1024. Video Stitching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [start i , end i ] indicates that the ith clip started at start i and ended at end i . We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time] . If the task is impossible, return -1 .", + "description_images": [], + "constraints": [ + "For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7] ." + ], + "examples": [ + { + "text": "Example 1: Input:clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput:3\nExplanation:We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].", + "image": null + }, + { + "text": "Example 2: Input:clips = [[0,1],[1,2]], time = 5\nOutput:-1\nExplanation:We cannot cover [0,5] with only [0,1] and [1,2].", + "image": null + }, + { + "text": "Example 3: Input:clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput:3\nExplanation:We can take clips [0,4], [4,7], and [6,9].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 41.2%) | Memory: 16.25 MB (Top 82.7%)\n\nclass Solution:\n def videoStitching(self, clips: List[List[int]], T: int) -> int:\n dp = [float('inf')] * (T + 1)\n dp[0] = 0\n for i in range(1, T + 1):\n for start, end in clips:\n if start <= i <= end:\n dp[i] = min(dp[start] + 1, dp[i])\n if dp[T] == float('inf'):\n return -1\n return dp[T]", + "title": "1024. Video Stitching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a wordlist , we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: In addition, the spell checker operates under the following precedence rules: Given some queries , return a list of words answer , where answer[i] is the correct word for query = queries[i] .", + "description_images": [], + "constraints": [ + "Capitalization: If the query matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\" Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\" Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\"", + "Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\" Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match) Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\"", + "Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)" + ], + "examples": [ + { + "text": "Example 1: Input:wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput:[\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]", + "image": null + }, + { + "text": "Example 2: Input:wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput:[\"yellow\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 184 ms (Top 7.48%) | Memory: 114.1 MB (Top 5.44%)\nclass Solution {\n public String[] spellchecker(String[] wordlist, String[] queries) {\n String[] ans = new String[queries.length];\n Map[] map = new HashMap[3];\n Arrays.setAll(map, o -> new HashMap<>());\n String pattern = \"[aeiou]\";\n\n for (String w : wordlist){\n String lo = w.toLowerCase();\n map[0].put(w, \"\");\n map[1].putIfAbsent(lo, w);\n map[2].putIfAbsent(lo.replaceAll(pattern, \".\"), map[1].getOrDefault(w, w));\n }\n\n int i = 0;\n for (String q : queries){\n String lo = q.toLowerCase();\n String re = lo.replaceAll(pattern, \".\");\n if (map[0].containsKey(q)){\n ans[i] = q;\n }else if (map[1].containsKey(lo)){\n ans[i] = map[1].get(lo);\n }else if (map[2].containsKey(re)){\n ans[i] = map[2].get(re);\n }else{\n ans[i] = \"\";\n }\n i++;\n }\n\n return ans;\n }\n}", + "title": "966. Vowel Spellchecker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a wordlist , we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: In addition, the spell checker operates under the following precedence rules: Given some queries , return a list of words answer , where answer[i] is the correct word for query = queries[i] .", + "description_images": [], + "constraints": [ + "Capitalization: If the query matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\" Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\" Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\"", + "Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\" Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match) Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\"", + "Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)" + ], + "examples": [ + { + "text": "Example 1: Input:wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput:[\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]", + "image": null + }, + { + "text": "Example 2: Input:wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput:[\"yellow\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 166 ms (Top 89.12%) | Memory: 19.20 MB (Top 76.17%)\n\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n capital={i.lower():i for i in wordlist[::-1]}\n vovel={''.join([j if j not in \"aeiou\" else '.' for j in i.lower()]):i for i in wordlist[::-1]}\n wordlist=set(wordlist)\n res=[]\n for i in queries:\n if i in wordlist:\n res.append(i)\n elif i.lower() in capital:\n res.append(capital[i.lower()])\n elif ''.join([j if j not in \"aeiou\" else '.' for j in i.lower()]) in vovel:\n res.append(vovel[''.join([j if j not in \"aeiou\" else '.' for j in i.lower()])])\n else:\n res.append(\"\")\n return res\n", + "title": "966. Vowel Spellchecker", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string word , return the sum of the number of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) in every substring of word . A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.", + "description_images": [], + "constraints": [ + "1 <= word.length <= 10^5", + "word consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"\nOutput:6\nExplanation:All possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:word = \"abc\"\nOutput:3\nExplanation:All possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.", + "image": null + }, + { + "text": "Example 3: Input:word = \"ltcd\"\nOutput:0\nExplanation:There are no vowels in any substring of \"ltcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 33.08%) | Memory: 50 MB (Top 44.62%)\nclass Solution {\n\n boolean isVowel(char ch) {\n return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';\n }\n\n public long countVowels(String word) {\n long count = 0;\n int len = word.length();\n\n for(int pos = 0; pos < len; pos++) {\n if(isVowel(word.charAt(pos))) {\n count += (long)(len - pos) * (long)(pos + 1);\n }\n }\n\n return count;\n }\n}", + "title": "2063. Vowels of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string word , return the sum of the number of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) in every substring of word . A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.", + "description_images": [], + "constraints": [ + "1 <= word.length <= 10^5", + "word consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"\nOutput:6\nExplanation:All possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:word = \"abc\"\nOutput:3\nExplanation:All possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.", + "image": null + }, + { + "text": "Example 3: Input:word = \"ltcd\"\nOutput:0\nExplanation:There are no vowels in any substring of \"ltcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countVowels(self, word: str) -> int:\n count = vowelIndexSum = 0\n vowels = {'a', 'e', 'i', 'o', 'u'}\n\n for i, c in enumerate(word, start=1):\n if c in vowels:\n vowelIndexSum += i\n count += vowelIndexSum\n \n return count", + "title": "2063. Vowels of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands : Some of the grid squares are obstacles . The i th obstacle is at grid point obstacles[i] = (x i , y i ) . If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5 , return 25 ) . Note:", + "description_images": [], + "constraints": [ + "-2 : Turn left 90 degrees.", + "-1 : Turn right 90 degrees.", + "1 <= k <= 9 : Move forward k units, one unit at a time." + ], + "examples": [ + { + "text": "Example 1: Input:commands = [4,-1,3], obstacles = []\nOutput:25\nExplanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32+ 42= 25 units away.", + "image": null + }, + { + "text": "Example 2: Input:commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput:65\nExplanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12+ 82= 65 units away.", + "image": null + }, + { + "text": "Example 3: Input:commands = [6,-1,-1,6], obstacles = []\nOutput:36\nExplanation:The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62= 36 units away.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 162 ms (Top 8.26%) | Memory: 66.8 MB (Top 51.38%)\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n int dir = 0; // states 0north-1east-2south-3west\n int farthestSofar = 0;\n\n int xloc = 0;\n int yloc = 0;\n\n Set set = new HashSet<>();\n for (int[] obs : obstacles) {\n set.add(obs[0] + \",\" + obs[1]);\n }\n\n int steps;\n\n for(int i: commands){\n\n if( i == -1){//turn right 90\n dir++;\n }\n else if (i == -2){//turn left 90\n dir--;\n }\n else{//move forward value of i baring no obsticals\n dir = dir%4;\n if (dir== -1){\n dir = 3;\n }\n else if(dir == -3){\n dir = 1;\n }\n else if(dir == -2){\n dir = 2;\n }\n // dir %4 = -1 -> 3\n // dir %4 = -2 -> 2\n // dir %4 = -3 -> 1\n if(dir == 0){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc+1))) {\n yloc++;\n steps++;\n }\n }\n else if (dir == 1){\n steps = 0;\n while (steps < i && !set.contains((xloc+1) + \",\" + (yloc))) {\n xloc++;\n steps++;\n }\n }\n else if (dir == 2){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc-1))) {\n yloc--;\n steps++;\n }\n }\n else{ //case dir == 3\n steps = 0;\n while (steps < i && !set.contains((xloc-1) + \",\" + (yloc))) {\n xloc--;\n steps++;\n }\n }\n }\n farthestSofar = Math.max(farthestSofar, xloc*xloc + yloc*yloc);\n }\n return farthestSofar;\n }\n}", + "title": "874. Walking Robot Simulation", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands : Some of the grid squares are obstacles . The i th obstacle is at grid point obstacles[i] = (x i , y i ) . If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5 , return 25 ) . Note:", + "description_images": [], + "constraints": [ + "-2 : Turn left 90 degrees.", + "-1 : Turn right 90 degrees.", + "1 <= k <= 9 : Move forward k units, one unit at a time." + ], + "examples": [ + { + "text": "Example 1: Input:commands = [4,-1,3], obstacles = []\nOutput:25\nExplanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32+ 42= 25 units away.", + "image": null + }, + { + "text": "Example 2: Input:commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput:65\nExplanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12+ 82= 65 units away.", + "image": null + }, + { + "text": "Example 3: Input:commands = [6,-1,-1,6], obstacles = []\nOutput:36\nExplanation:The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62= 36 units away.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 970 ms (Top 9.86%) | Memory: 20.6 MB (Top 59.47%)\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obs = set(tuple(o) for o in obstacles)\n x = y = a = out = 0\n move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}\n for c in commands:\n if c == -1:\n a += 90\n elif c == -2:\n a -= 90\n else:\n direction = a % 360\n dx, dy = move[direction]\n for _ in range(c):\n if (x + dx, y + dy) in obs:\n break\n x += dx\n y += dy\n out = max(out, x**2 + y**2)\n return out", + "title": "874. Walking Robot Simulation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1) . The grid is aligned with the four cardinal directions ( \"North\" , \"East\" , \"South\" , and \"West\" ). A robot is initially at cell (0, 0) facing direction \"East\" . The robot can be instructed to move for a specific number of steps . For each step, it does the following. After the robot finishes moving the number of steps required, it stops and awaits the next instruction. Implement the Robot class:", + "description_images": [], + "constraints": [ + "Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\" .", + "void step(int num) Instructs the robot to move forward num steps.", + "int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y] .", + "String getDir() Returns the current direction of the robot, \"North\" , \"East\" , \"South\" , or \"West\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]Output[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]ExplanationRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and facesNorth(not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"", + "image": "https://assets.leetcode.com/uploads/2021/10/09/example-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 134 ms (Top 50.88%) | Memory: 98.9 MB (Top 12.28%)\nclass Robot {\n\n int p;\n int w;\n int h;\n public Robot(int width, int height) {\n w = width - 1;\n h = height - 1;\n p = 0;\n }\n\n public void step(int num) {\n p += num;\n }\n\n public int[] getPos() {\n int remain = p % (2 * (w + h));\n if (remain <= w)\n return new int[]{remain, 0};\n remain -= w;\n if (remain <= h)\n return new int[]{w, remain};\n remain -= h;\n if (remain <= w)\n return new int[]{w - remain, h};\n remain -= w;\n return new int[]{0, h - remain};\n }\n\n public String getDir() {\n int[] pos = getPos();\n if (p == 0 || pos[1] == 0 && pos[0] > 0)\n return \"East\";\n else if (pos[0] == w && pos[1] > 0)\n return \"North\";\n else if (pos[1] == h && pos[0] < w)\n return \"West\";\n else\n return \"South\";\n }\n}", + "title": "2069. Walking Robot Simulation II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1) . The grid is aligned with the four cardinal directions ( \"North\" , \"East\" , \"South\" , and \"West\" ). A robot is initially at cell (0, 0) facing direction \"East\" . The robot can be instructed to move for a specific number of steps . For each step, it does the following. After the robot finishes moving the number of steps required, it stops and awaits the next instruction. Implement the Robot class:", + "description_images": [], + "constraints": [ + "Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\" .", + "void step(int num) Instructs the robot to move forward num steps.", + "int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y] .", + "String getDir() Returns the current direction of the robot, \"North\" , \"East\" , \"South\" , or \"West\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]Output[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]ExplanationRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and facesNorth(not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"", + "image": "https://assets.leetcode.com/uploads/2021/10/09/example-1.png" + } + ], + "follow_up": null, + "solution": "class Robot:\n\n def __init__(self, width: int, height: int):\n self.perimeter = 2*width + 2*(height - 2)\n self.pos = 0\n self.atStart = True\n\n self.bottomRight = width - 1\n self.topRight = self.bottomRight + (height - 1)\n self.topLeft = self.topRight + (width - 1)\n\n def step(self, num: int) -> None:\n self.atStart = False\n self.pos = (self.pos + num) % self.perimeter\n\n def getPos(self) -> List[int]:\n if 0 <= self.pos <= self.bottomRight:\n return [self.pos, 0]\n\n if self.bottomRight < self.pos <= self.topRight:\n return [self.bottomRight, self.pos - self.bottomRight]\n\n if self.topRight < self.pos <= self.topLeft:\n return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]\n \n return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]\n\n def getDir(self) -> str:\n if self.atStart or 0 < self.pos <= self.bottomRight:\n return 'East'\n\n if self.bottomRight < self.pos <= self.topRight:\n return 'North'\n\n if self.topRight < self.pos <= self.topLeft:\n return 'West'\n \n return 'Sout", + "title": "2069. Walking Robot Simulation II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed:", + "description_images": [], + "constraints": [ + "Fill any of the jugs with water.", + "Empty any of the jugs.", + "Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty." + ], + "examples": [ + { + "text": "Example 1: Input:jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4\nOutput:true\nExplanation:The famousDie Hardexample", + "image": null + }, + { + "text": "Example 2: Input:jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static int gcd(int a,int b){\n if(b==0)return a;\n return gcd(b,a%b);\n }\n public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n if(targetCapacity>jug1Capacity+jug2Capacity){\n return false;\n }\n int g=gcd(jug1Capacity,jug2Capacity);\n return (targetCapacity%g==0);\n }\n}\n", + "title": "365. Water and Jug Problem", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed:", + "description_images": [], + "constraints": [ + "Fill any of the jugs with water.", + "Empty any of the jugs.", + "Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty." + ], + "examples": [ + { + "text": "Example 1: Input:jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4\nOutput:true\nExplanation:The famousDie Hardexample", + "image": null + }, + { + "text": "Example 2: Input:jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:\n n1, n2, t = jug1Capacity, jug2Capacity, targetCapacity\n if n1 == t or n2 == t or n1 + n2 == t:\n return True\n if n1 + n2 < t:\n return False\n if n1 < n2:\n n1, n2 = n2, n1\n stack = []\n visited = set()\n d = n1 - n2\n if d == t:\n return True\n while d > n2:\n d -= n2\n if d == t:\n return True\n stack.append(d)\n while stack:\n #print(stack)\n d = stack.pop()\n visited.add(d)\n n = n1 + d\n if n == t:\n return True\n n = n1 - d\n if n == t:\n return True\n while n > n2:\n n -= n2\n if n == t:\n return True\n if n < n2 and n not in visited:\n stack.append(n)\n n = n2 - d\n if n == t:\n return True\n if n not in visited:\n stack.append(n)\n return False\n", + "title": "365. Water and Jug Problem", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange , return the maximum number of water bottles you can drink .", + "description_images": [], + "constraints": [ + "1 <= numBottles <= 100", + "2 <= numExchange <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:numBottles = 9, numExchange = 3\nOutput:13\nExplanation:You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_1_1875.png" + }, + { + "text": "Example 2: Input:numBottles = 15, numExchange = 4\nOutput:19\nExplanation:You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_2_1875.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 8.35%)\nclass Solution {\n public int numWaterBottles(int numBottles, int numExchange) {\n int drinkedBottles = numBottles;\n int emptyBottles = numBottles;\n\n while(emptyBottles >= numExchange){\n int gainedBottles = emptyBottles / numExchange;\n\n drinkedBottles += gainedBottles;\n\n int unusedEmptyBottles = emptyBottles % numExchange;\n\n emptyBottles = gainedBottles + unusedEmptyBottles;\n }\n return drinkedBottles;\n }\n}", + "title": "1518. Water Bottles", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange , return the maximum number of water bottles you can drink .", + "description_images": [], + "constraints": [ + "1 <= numBottles <= 100", + "2 <= numExchange <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:numBottles = 9, numExchange = 3\nOutput:13\nExplanation:You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_1_1875.png" + }, + { + "text": "Example 2: Input:numBottles = 15, numExchange = 4\nOutput:19\nExplanation:You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_2_1875.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numWaterBottles(self, a: int, b: int) -> int:\n \n def sol(a,b,e,res):\n if a!=0: res += a\n if (a+e)=plants[i]){\n c-=plants[i];\n count++;\n }\n else {\n c=capacity;\n count=count+i+(i+1);\n c-=plants[i];\n }\n }\n return count;\n }\n}\n", + "title": "2079. Watering Plants", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: You are initially at the river (i.e., x = -1 ). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants .", + "description_images": [], + "constraints": [ + "Water the plants in order from left to right.", + "After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.", + "You cannot refill the watering can early." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacity = 5\nOutput:14\nExplanation:Start at the river with a full watering can:\n- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.\n- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.\n- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).\n- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.\n- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).\n- Walk to plant 3 (4 steps) and water it.\nSteps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.", + "image": null + }, + { + "text": "Example 2: Input:plants = [1,1,1,4,2,3], capacity = 4\nOutput:30\nExplanation:Start at the river with a full watering can:\n- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).\n- Water plant 3 (4 steps). Return to river (4 steps).\n- Water plant 4 (5 steps). Return to river (5 steps).\n- Water plant 5 (6 steps).\nSteps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.", + "image": null + }, + { + "text": "Example 3: Input:plants = [7,7,7,7,7,7,7], capacity = 8\nOutput:49\nExplanation:You have to refill before watering each plant.\nSteps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 93 ms (Top 33.43%) | Memory: 14.1 MB (Top 44.38%)\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n result = 0\n curCap = capacity\n\n for i in range(len(plants)):\n if curCap >= plants[i]:\n curCap -= plants[i]\n result += 1\n\n else:\n result += i * 2 + 1\n curCap = capacity - plants[i]\n\n return result", + "title": "2079. Watering Plants", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full . They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants .", + "description_images": [], + "constraints": [ + "Alice waters the plants in order from left to right , starting from the 0 th plant. Bob waters the plants in order from right to left , starting from the (n - 1) th plant. They begin watering the plants simultaneously .", + "It takes the same amount of time to water each plant regardless of how much water it needs.", + "Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.", + "In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput:1\nExplanation:- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput:2\nExplanation:- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.", + "image": null + }, + { + "text": "Example 3: Input:plants = [5], capacityA = 10, capacityB = 8\nOutput:0\nExplanation:- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 96.18%) | Memory: 57.70 MB (Top 65.65%)\n\nclass Solution {\n public int minimumRefill(int[] p, int ca, int cb) { \n\t\n int refill= 0,oca = ca, ocb = cb;// let save our orginal capacity , needed to refill can again\n int i=0, j = p.length-1; // starting both end \n \n while(i<=j){\n\t\t\n if(i==j){// mean both at same position\n if(ca>=cb){\n if(p[i]>ca){\n refill++;\n } \n }\n else{ \n if(p[j]>cb){\n refill++; \n } \n }\n\t\t\t\t // no more plant left for watering so break loop \n break; \n }\n \n // first check if they have sufficient amount of water \n // if not then refill it with orginal capacity \n\t\t\t\n if(p[i]>ca){\n refill++;\n ca = oca;\n } \n if(p[j]>cb){\n refill++;\n cb= ocb;\n }\n \n\t\t\t// decrease consumed water \n ca-=p[i] ; \n cb-=p[j]; \n\t\t\t\n\t\t\t// move both \n\t\t\ti++; \n j--;\t\t\t \n }\n return refill; \n }\n}\n", + "title": "2105. Watering Plants II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full . They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants .", + "description_images": [], + "constraints": [ + "Alice waters the plants in order from left to right , starting from the 0 th plant. Bob waters the plants in order from right to left , starting from the (n - 1) th plant. They begin watering the plants simultaneously .", + "It takes the same amount of time to water each plant regardless of how much water it needs.", + "Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.", + "In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput:1\nExplanation:- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput:2\nExplanation:- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.", + "image": null + }, + { + "text": "Example 3: Input:plants = [5], capacityA = 10, capacityB = 8\nOutput:0\nExplanation:- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 591 ms (Top 95.38%) | Memory: 31.60 MB (Top 92.31%)\n\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n canA, canB = capacityA, capacityB\n while lo < hi: \n if canA < plants[lo]: ans += 1; canA = capacityA\n canA -= plants[lo]\n if canB < plants[hi]: ans += 1; canB = capacityB\n canB -= plants[hi]\n lo, hi = lo+1, hi-1\n if lo == hi and max(canA, canB) < plants[lo]: ans += 1\n return ans \n", + "title": "2105. Watering Plants II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You can choose exactly one index ( 0-indexed ) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1] : An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair .", + "description_images": [], + "constraints": [ + "Choosing to remove index 1 results in nums = [6,7,4,1] .", + "Choosing to remove index 2 results in nums = [6,1,4,1] .", + "Choosing to remove index 4 results in nums = [6,1,7,4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,6,4]\nOutput:1\nExplanation:Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:3\nExplanation:You can remove any index and the remaining array is fair.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:0\nExplanation:You cannot make a fair array after removing any index.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 97.91%) | Memory: 58.00 MB (Top 9.21%)\n\nclass Solution {\n public int waysToMakeFair(int[] nums) {\n int esum = 0; // Sum of even-indexed elements\n int osum = 0; // Sum of odd-indexed elements\n int n=nums.length;\n for (int i = 0; i < n; i++) {\n if (i % 2 == 0) {\n osum += nums[i];\n } else {\n esum += nums[i];\n }\n }\n int count = 0;\n int prev = 0;\n for (int i = 0; i < n; i++) {\n if (i % 2 == 0) {\n osum = osum - nums[i] + prev;\n } else {\n esum = esum - nums[i] + prev;\n }\n if (esum == osum) {\n count++;\n }\n prev = nums[i];\n }\n return count;\n }\n}\n\n", + "title": "1664. Ways to Make a Fair Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . You can choose exactly one index ( 0-indexed ) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1] : An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair .", + "description_images": [], + "constraints": [ + "Choosing to remove index 1 results in nums = [6,7,4,1] .", + "Choosing to remove index 2 results in nums = [6,1,4,1] .", + "Choosing to remove index 4 results in nums = [6,1,7,4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,6,4]\nOutput:1\nExplanation:Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]\nOutput:3\nExplanation:You can remove any index and the remaining array is fair.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:0\nExplanation:You cannot make a fair array after removing any index.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef waysToMakeFair(self, nums: List[int]) -> int:\n\t\tif len(nums) == 1:\n\t\t\treturn 1\n\n\t\tif len(nums) == 2:\n\t\t\treturn 0\n\n\t\tprefixEven = sum(nums[2::2])\n\t\tprefixOdd = sum(nums[1::2])\n\t\tresult = 0\n\n\t\tif prefixEven == prefixOdd and len(set(nums)) == 1:\n\t\t\tresult += 1\n\n\t\tfor i in range(1,len(nums)):\n\t\t\tif i == 1:\n\t\t\t\tprefixOdd, prefixEven = prefixEven, prefixOdd \n\n\t\t\tif i > 1:\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tprefixEven -= nums[i-1]\n\t\t\t\t\tprefixEven += nums[i-2]\n\n\t\t\t\telse:\n\t\t\t\t\tprefixOdd -= nums[i-1]\n\t\t\t\t\tprefixOdd += nums[i-2]\n\n\t\t\tif prefixOdd == prefixEven:\n\t\t\t\tresult += 1\n\n\t\treturn result\n", + "title": "1664. Ways to Make a Fair Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A split of an integer array is good if: Given nums , an array of non-negative integers, return the number of good ways to split nums . As the number may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "The array is split into three non-empty contiguous subarrays - named left , mid , right respectively from left to right.", + "The sum of the elements in left is less than or equal to the sum of the elements in mid , and the sum of the elements in mid is less than or equal to the sum of the elements in right ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]\nOutput:1\nExplanation:The only good way to split nums is [1] [1] [1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,5,0]\nOutput:3\nExplanation:There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]\nOutput:0\nExplanation:There is no good way to split nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int waysToSplit(int[] nums) {\n int size = nums.length;\n for (int i = 1; i < size; ++i) {\n nums[i] += nums[i - 1];\n }\n int res = 0;\n int mod = 1_000_000_007;\n for (int i = 0; i < size - 2; ++i) {\n int left = searchLeft(nums, i, size - 1);\n int right = searchRight(nums, i, size - 1);\n if (left == -1 || right == -1) {\n continue;\n }\n res = (res + right - left + 1) % mod;\n }\n return res;\n }\n \n private int searchLeft(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n hi = mi - 1;\n }\n }\n return pos;\n }\n \n private int searchRight(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n lo = mi + 1;\n }\n }\n return pos;\n }\n \n}\n", + "title": "1712. Ways to Split Array Into Three Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A split of an integer array is good if: Given nums , an array of non-negative integers, return the number of good ways to split nums . As the number may be too large, return it modulo 10^9 + 7 .", + "description_images": [], + "constraints": [ + "The array is split into three non-empty contiguous subarrays - named left , mid , right respectively from left to right.", + "The sum of the elements in left is less than or equal to the sum of the elements in mid , and the sum of the elements in mid is less than or equal to the sum of the elements in right ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]\nOutput:1\nExplanation:The only good way to split nums is [1] [1] [1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,5,0]\nOutput:3\nExplanation:There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]\nOutput:0\nExplanation:There is no good way to split nums.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1271 ms (Top 38.4%) | Memory: 29.79 MB (Top 48.0%)\n\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007", + "title": "1712. Ways to Split Array Into Three Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the i th column at the top, or -1 if the ball gets stuck in the box .", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/26/ball.jpg" + ], + "constraints": [ + "A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1 .", + "A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput:[1,-1,-1,-1,-1]\nExplanation:This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[-1]]\nOutput:[-1]\nExplanation:The ball gets stuck against the left wall.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput:[0,1,2,3,4,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.85%) | Memory: 54.4 MB (Top 47.92%)\nclass Solution {\n public int dfs(int[][] grid, int i, int j){\n if(i==grid.length)\n return j;\n\n if(j<0 || j>=grid[0].length)\n return -1;\n\n if(grid[i][j]==1 && j+1=0 && grid[i][j-1]==-1)\n return dfs(grid,i+1,j-1);\n\n return -1;\n }\n public int[] findBall(int[][] grid) {\n int m = grid[0].length;\n int[] ar = new int[m];\n\n for(int j=0;j List[int]:\n\n m,n=len(grid),len(grid[0])\n for i in range(m):\n grid[i].insert(0,1)\n grid[i].append(-1)\n res=[]\n\n for k in range(1,n+1):\n i , j = 0 , k\n struck = False\n while idiff){\n diff=arr[i]-arr[i-1];\n }\n }\n return diff;\n }\n}", + "title": "1637. Widest Vertical Area Between Two Points Containing No Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given n points on a 2D plane where points[i] = [x i , y i ] , Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area.", + "description_images": [], + "constraints": [ + "n == points.length", + "2 <= n <= 10^5", + "points[i].length == 2", + "0 <= x i , y i <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[8,7],[9,9],[7,4],[9,7]]\nOutput:1\nExplanation:Both the red and the blue area are optimal.", + "image": "https://assets.leetcode.com/uploads/2020/09/19/points3.png" + }, + { + "text": "Example 2: Input:points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n # only taking x-axis point as it's relevant\n arr = [i[0] for i in points]\n \n arr.sort()\n \n diff = -1\n for i in range(1, len(arr)):\n diff = max(diff, arr[i] - arr[i - 1])\n \n return diff\n", + "title": "1637. Widest Vertical Area Between Two Points Containing No Points", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , reorder it such that nums[0] < nums[1] > nums[2] < nums[3]... . You may assume the input array always has a valid answer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5000", + "It is guaranteed that there will be an answer for the given input nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,1,1,6,4]\nOutput:[1,6,1,5,1,4]\nExplanation:[1,4,1,5,1,6] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,2,3,1]\nOutput:[2,3,1,3,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 77.52%) | Memory: 56 MB (Top 40.18%)\nclass Solution {\n public void wiggleSort(int[] nums) {\n int a[]=nums.clone();\n Arrays.sort(a);\n int left=(nums.length-1)/2;\n int right=nums.length-1;\n for(int i=0;i nums[2] < nums[3]... . You may assume the input array always has a valid answer.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5000", + "It is guaranteed that there will be an answer for the given input nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,1,1,6,4]\nOutput:[1,6,1,5,1,4]\nExplanation:[1,4,1,5,1,6] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,2,3,1]\nOutput:[2,3,1,3,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Heap:\n\tdef __init__(self):\n\t\tself.q = []\n\tdef push(self,data):\n\t\ti = len(self.q)\n\t\tself.q.append(data)\n\t\twhile i>0:\n\t\t\tif self.q[i] > self.q[(i-1)//2]:\n\t\t\t\tself.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i]\n\t\t\t\ti = (i-1)//2\n\t\t\telse: return \n\tdef pop(self):\n\t\tif len(self.q)==0:return\n\t\tself.q[0] = self.q[-1]\n\t\tself.q.pop()\n\t\tdef heapify(i):\n\t\t\tind = i\n\t\t\tl = 2*i+1\n\t\t\tr = 2*i+2\n\t\t\tif r None:\n\t\tn = len(nums)\n\t\th = Heap()\n\t\tfor i in nums: h.push(i)\n\t\tfor i in range(1,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()\n\t\tfor i in range(0,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()", + "title": "324. Wiggle Sort II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums , return the length of the longest wiggle subsequence of nums .", + "description_images": [], + "constraints": [ + "For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.", + "In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,4,9,2,5]\nOutput:6\nExplanation:The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,17,5,10,13,15,10,5,16,8]\nOutput:7\nExplanation:There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 5.98%) | Memory: 74.5 MB (Top 5.03%)\nclass Solution {\n int n;\n int dp[][][];\n public int wiggleMaxLength(int[] nums) {\n n = nums.length;\n dp = new int[n][1005][2];\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int pos = f(0 , 0 , nums , -1);\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int neg = f(0 , 1 , nums , 1001);\n return Math.max(pos , neg);\n }\n int f(int i , int posPre , int a[] , int prev){\n if(i == n) return 0;\n if(dp[i][prev + 1][posPre] != -1) return dp[i][prev + 1][posPre];\n if(posPre == 0){\n int not = f(i + 1 , 0 , a , prev);\n int take = 0;\n if(a[i] - prev > 0){\n take = f(i + 1 , 1 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n else{\n int not = f(i + 1 , 1 , a , prev);\n int take = 0;\n if(a[i] - prev < 0){\n take = f(i + 1 , 0 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n }\n}", + "title": "376. Wiggle Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums , return the length of the longest wiggle subsequence of nums .", + "description_images": [], + "constraints": [ + "For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.", + "In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,4,9,2,5]\nOutput:6\nExplanation:The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,17,5,10,13,15,10,5,16,8]\nOutput:7\nExplanation:There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 48.8%) | Memory: 16.22 MB (Top 87.1%)\n\n#####################################################################################################################\n# Problem: Wiggle Subsequence\n# Solution : Dynamic Programming\n# Time Complexity : O(n) \n# Space Complexity : O(1)\n#####################################################################################################################\n\nclass Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n \n positive, negative = 1, 1\n \n if len(nums) < 2:\n return len(nums)\n \n for i in range(1, len(nums)):\n if nums[i] > nums[i - 1]:\n positive = negative + 1\n elif nums[i] < nums[i - 1]:\n negative = positive + 1\n \n return max(positive, negative)", + "title": "376. Wiggle Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string ( s ) and a pattern ( p ), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).", + "description_images": [], + "constraints": [ + "'?' Matches any single character.", + "'*' Matches any sequence of characters (including the empty sequence)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\", p = \"a\"\nOutput:false\nExplanation:\"a\" does not match the entire string \"aa\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aa\", p = \"*\"\nOutput:true\nExplanation:'*' matches any sequence.", + "image": null + }, + { + "text": "Example 3: Input:s = \"cb\", p = \"?a\"\nOutput:false\nExplanation:'?' matches 'c', but the second letter is 'a', which does not match 'b'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 42.3 MB (Top 99.02%)\nclass Solution {\n public boolean isMatch(String s, String p) {\n int i=0;\n int j=0;\n int starIdx=-1;\n int lastMatch=-1;\n\n while(i bool:\n m= len(s)\n n= len(p)\n\n dp = [[False]*(n+1) for i in range(m+1)]\n\n dp[0][0] = True\n\n for j in range(len(p)):\n if p[j] == \"*\":\n dp[0][j+1] = dp[0][j]\n\n for i in range(1,m+1):\n for j in range(1,n+1):\n if p[j-1] == \"*\":\n dp[i][j] = dp[i-1][j] or dp[i][j-1]\n\n elif s[i-1] == p[j-1] or p[j-1] == \"?\":\n dp[i][j] = dp[i-1][j-1]\n\n return dp[-1][-1]", + "title": "44. Wildcard Matching", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", wordDict = [\"leet\",\"code\"]\nOutput:true\nExplanation:Return true because \"leetcode\" can be segmented as \"leet code\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]\nOutput:true\nExplanation:Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 16.65%) | Memory: 47.4 MB (Top 24.65%)\nclass Solution {\n Mapmap= new HashMap<>();\n public boolean wordBreak(String s, List wordDict) {\n\n if(wordDict.contains(s)){\n return true;\n }\n if(map.containsKey(s)){\n return map.get(s);\n }\n for(int i=0;i bool:\n memo = {}\n\n\n def can_construct(target, strings_bank, memo): \n if target in memo:\n return memo[target]\n if target == \"\":\n return True\n for element in strings_bank: # for every element in our dict we check if we can start constructing the string \"s\"\n if element == target[0:len(element)]: # the remaining of the string \"s\" (which is the suffix) is the new target \n suffix = target[len(element):]\n if can_construct(suffix, strings_bank, memo):\n memo[target] = True\n return True\n memo[target] = False\n return False\n\n\n return can_construct(s, wordDict, memo)", + "title": "139. Word Break", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and a dictionary of strings wordDict , add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order . Note that the same word in the dictionary may be reused multiple times in the segmentation.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "1 <= wordDict.length <= 1000", + "1 <= wordDict[i].length <= 10", + "s and wordDict[i] consist of only lowercase English letters.", + "All the strings of wordDict are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\nOutput:[\"cats and dog\",\"cat sand dog\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\nOutput:[\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\nExplanation:Note that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tList res = new ArrayList<>();\n\tString s;\n\tint index = 0;\n\tSet set = new HashSet<>();\n public List wordBreak(String s, List wordDict) {\n this.s = s;\n\t\tfor (String word: wordDict) set.add(word);\n\t\tbacktrack(\"\");\n\t\treturn res;\n }\n\tpublic void backtrack(String sentence) {\n\t if (index == s.length()) {\n\t res.add(sentence.trim());\n\t return;\n }\n int indexCopy = index;\n for (int i = index + 1; i <= s.length(); i++) {\n\t String str = s.substring(index, i);\n\t if (set.contains(str)) {\n\t index = i;\n\t backtrack(sentence + \" \" + str);\n\t index = indexCopy;\n }\n }\n return;\n }\n}\n", + "title": "140. Word Break II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s and a dictionary of strings wordDict , add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order . Note that the same word in the dictionary may be reused multiple times in the segmentation.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "1 <= wordDict.length <= 1000", + "1 <= wordDict[i].length <= 10", + "s and wordDict[i] consist of only lowercase English letters.", + "All the strings of wordDict are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\nOutput:[\"cats and dog\",\"cat sand dog\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\nOutput:[\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\nExplanation:Note that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 56 ms (Top 49.21%) | Memory: 14 MB (Top 33.37%)\nclass Solution(object):\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: List[str]\n \"\"\"\n\n dic = defaultdict(list)\n for w in wordDict:\n dic[w[0]].append(w)\n result = []\n def recursion(idx , ans):\n if idx >= len(s):\n result.append(\" \".join(ans))\n return\n\n for w in dic[s[idx]]:\n if s[idx : idx+len(w)] == w:\n ans.append(w)\n recursion(idx+len(w), ans)\n ans.pop()\n\n return\n recursion(0, [])\n return result\n", + "title": "140. Word Break II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput:5\nExplanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput:0\nExplanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int ladderLength(String beginWord, String endWord, List wordList) {\n int count = 1;\n Set words = new HashSet<>(wordList);\n Queue q = new LinkedList();\n q.add(beginWord);\n \n while(!q.isEmpty()) {\n int size = q.size();\n \n while(size-- > 0) {\n String word = q.poll();\n char[] chList = word.toCharArray();\n \n for(int i=0; i s 1 -> s 2 -> ... -> s k such that: 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.", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput:5\nExplanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput:0\nExplanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n e = defaultdict(list)\n m = len(beginWord)\n for word in wordList + [beginWord]:\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n e[w].append(word)\n q = deque([beginWord])\n used = set([beginWord])\n d = 0\n while q:\n d += 1\n for _ in range(len(q)):\n word = q.popleft()\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n if w in e:\n for v in e[w]:\n if v == endWord:\n return d + 1\n if v not in used:\n q.append(v)\n used.add(v)\n e.pop(w)\n return 0\n", + "title": "127. Word Ladder", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Given two words, beginWord and endWord , and a dictionary wordList , return all the shortest transformation sequences from beginWord to endWord , or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s 1 , s 2 , ..., s k ] .", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput:[[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\nExplanation:There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput:[]\nExplanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> findLadders(String beginWord, String endWord, List wordList) {\n Set dict = new HashSet(wordList);\n if( !dict.contains(endWord) )\n return new ArrayList();\n \n // adjacent words for each word\n Map> adjacency = new HashMap();\n Queue queue = new LinkedList();\n // does path exist?\n boolean found = false;\n \n // BFS for shortest path, keep removing visited words\n queue.offer(beginWord);\n dict.remove(beginWord);\n \n while( !found && !queue.isEmpty() ) {\n int size = queue.size();\n // adjacent words in current level\n HashSet explored = new HashSet();\n\n while( size-- > 0 ) {\n String word = queue.poll();\n \n if( adjacency.containsKey(word) )\n continue;\n \n // remove current word from dict, and search for adjacent words\n dict.remove(word);\n List adjacents = getAdjacents(word, dict);\n adjacency.put(word, adjacents);\n\n for(String adj : adjacents) {\n if( !found && adj.equals(endWord) ) \n found = true;\n \n explored.add(adj);\n queue.offer(adj);\n }\n }\n // remove words explored in current level from dict\n for(String word : explored)\n dict.remove(word);\n }\n\n // if a path exist, dfs to find all the paths\n if( found ) \n return dfs(beginWord, endWord, adjacency, new HashMap());\n else\n return new ArrayList();\n }\n \n private List getAdjacents(String word, Set dict) {\n List adjs = new ArrayList();\n char[] wordChars = word.toCharArray();\n \n for(int i=0; i> dfs(String src, String dest, \n Map> adjacency, \n Map>> memo) {\n if( memo.containsKey(src) )\n return memo.get(src);\n \n List> paths = new ArrayList();\n \n\t\t// reached dest? return list with dest word\n if( src.equals( dest ) ) {\n paths.add( new ArrayList(){{ add(dest); }} );\n return paths;\n }\n\n\t\t// no adjacent for curr word? return empty list\n List adjacents = adjacency.get(src);\n if( adjacents == null || adjacents.isEmpty() )\n return paths;\n\n for(String adj : adjacents) {\n List> adjPaths = dfs(adj, dest, adjacency, memo);\n \n for(List path : adjPaths) {\n if( path.isEmpty() ) continue;\n \n List newPath = new ArrayList(){{ add(src); }};\n newPath.addAll(path);\n \n paths.add(newPath);\n }\n } \n memo.put(src, paths);\n return paths;\n }\n}\n", + "title": "126. Word Ladder II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Given two words, beginWord and endWord , and a dictionary wordList , return all the shortest transformation sequences from beginWord to endWord , or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s 1 , s 2 , ..., s k ] .", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput:[[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\nExplanation:There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput:[]\nExplanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 80 ms (Top 72.71%) | Memory: 14.5 MB (Top 54.17%)\nclass Solution:\n\n WILDCARD = \".\"\n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \"\"\"\n Given a wordlist, we perform BFS traversal to generate a word tree where\n every node points to its parent node.\n\n Then we perform a DFS traversal on this tree starting at the endWord.\n \"\"\"\n if endWord not in wordList:\n # end word is unreachable\n return []\n\n # first generate a word tree from the wordlist\n word_tree = self.getWordTree(beginWord, endWord, wordList)\n\n # then generate a word ladder from the word tree\n return self.getLadders(beginWord, endWord, word_tree)\n\n def getWordTree(self,\n beginWord: str,\n endWord: str,\n wordList: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n BFS traversal from begin word until end word is encountered.\n\n This functions constructs a tree in reverse, starting at the endWord.\n \"\"\"\n # Build an adjacency list using patterns as keys\n # For example: \".it\" -> (\"hit\"), \"h.t\" -> (\"hit\"), \"hi.\" -> (\"hit\")\n adjacency_list = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n adjacency_list[pattern].append(word)\n\n # Holds the tree of words in reverse order\n # The key is an encountered word.\n # The value is a list of preceding words.\n # For example, we got to beginWord from no other nodes.\n # {a: [b,c]} means we got to \"a\" from \"b\" and \"c\"\n visited_tree = {beginWord: []}\n\n # start off the traversal without finding the word\n found = False\n\n q = deque([beginWord])\n while q and not found:\n n = len(q)\n\n # keep track of words visited at this level of BFS\n visited_this_level = {}\n\n for i in range(n):\n word = q.popleft()\n\n for i in range(len(word)):\n # for each pattern of the current word\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n for next_word in adjacency_list[pattern]:\n if next_word == endWord:\n # we don't return immediately because other\n # sequences might reach the endWord in the same\n # BFS level\n found = True\n if next_word not in visited_tree:\n if next_word not in visited_this_level:\n visited_this_level[next_word] = [word]\n # queue up next word iff we haven't visited it yet\n # or already are planning to visit it\n q.append(next_word)\n else:\n visited_this_level[next_word].append(word)\n\n # add all seen words at this level to the global visited tree\n visited_tree.update(visited_this_level)\n\n return visited_tree\n\n def getLadders(self,\n beginWord: str,\n endWord: str,\n wordTree: Dict[str, List[str]]) -> List[List[str]]:\n \"\"\"\n DFS traversal from endWord to beginWord in a given tree.\n \"\"\"\n def dfs(node: str) -> List[List[str]]:\n if node == beginWord:\n return [[beginWord]]\n if node not in wordTree:\n return []\n\n res = []\n parents = wordTree[node]\n for parent in parents:\n res += dfs(parent)\n for r in res:\n r.append(node)\n return res\n\n return dfs(endWord)", + "title": "126. Word Ladder II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a pattern and a string s , find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s .", + "description_images": [], + "constraints": [ + "1 <= pattern.length <= 300", + "pattern contains only lower-case English letters.", + "1 <= s.length <= 3000", + "s contains only lowercase English letters and spaces ' ' .", + "s does not contain any leading or trailing spaces.", + "All the words in s are separated by a single space ." + ], + "examples": [ + { + "text": "Example 1: Input:pattern = \"abba\", s = \"dog cat cat dog\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:pattern = \"abba\", s = \"dog cat cat fish\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:pattern = \"aaaa\", s = \"dog cat cat dog\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean wordPattern(String pattern, String s) {\n String[] arr=s.split(\" \");\n if(pattern.length()!=arr.length) return false;\n Map map=new HashMap();\n \n for(int i=0;i=board.length || cd>=board[0].length\n || vis[rd][cd]==true ||\n board[rd][cd]!=word.charAt(idx)) continue;\n boolean is=isexist(rd,cd,board,vis,idx+1,word);\n if(is) return true;\n }\n vis[r][c]=false;\n return false;\n }\n}", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word2.jpg" + }, + { + "text": "Example 2: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg" + }, + { + "text": "Example 3: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/15/word3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n m = len(board)\n n = len(board[0])\n \n marked = set() # visited by the dfs\n def dfs(cell: Tuple[int, int], wp: int) -> bool:\n i = cell[0]\n j = cell[1]\n \n if wp == len(word):\n return True\n \n # Get appropriate neighbours and perform dfs on them\n # When going on dfs, we mark certain cells, we should remove # \n #them from the marked list after we return from the dfs\n marked.add((i,j))\n neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]\n for x, y in neibs:\n if (\n x < 0 or y < 0 or\n x >= m or y >= n or\n (x, y) in marked or\n board[x][y] != word[wp]\n ):\n continue\n \n if dfs((x,y), wp + 1):\n return True\n \n marked.remove((i,j))\n return False\n \n \n for i in range(m):\n for j in range(n):\n if board[i][j] == word[0]:\n if dfs((i,j), 1):\n return True\n \n return False\n", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\nOutput:[\"eat\",\"oath\"]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" + }, + { + "text": "Example 2: Input:board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n class TrieNode {\n Map children = new HashMap();\n boolean word = false;\n public TrieNode() {}\n }\n \n int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};\n \n public List findWords(char[][] board, String[] words) {\n Set res = new HashSet<>();\n TrieNode root = new TrieNode();\n int m = board.length;\n int n = board[0].length;\n \n for(String word : words){\n char[] cArr = word.toCharArray();\n TrieNode dummy = root;\n \n for(char c : cArr){\n if(!dummy.children.containsKey(c)){\n dummy.children.put(c, new TrieNode());\n }\n dummy = dummy.children.get(c);\n }\n \n dummy.word = true;\n }\n \n for(int i=0; i(res);\n }\n \n Set dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word){\n Set res = new HashSet<>();\n \n if(root.word){\n res.add(word);\n root.word = false;\n }\n \n visited[i][j] = true;\n \n for(int[] dir : dirs){\n int newI = i + dir[0];\n int newJ = j + dir[1];\n \n if(newI>=0 && newI=0 && newJ List[str]:\n solution = set()\n trie = self.make_trie(words)\n visited = set()\n for i in range(len(board)):\n for j in range(len(board[0])):\n self.dfs(i,j,board,trie,visited,\"\",solution)\n return solution\n \n def dfs(self,i,j,board,trie,visited,word,solution):\n if \"*\" in trie:\n if len(trie.keys()) == 0:\n return\n else:\n solution.add(word)\n del trie[\"*\"]\n if (i,j) in visited:\n return\n if (i < 0 or i == len(board) or j < 0 or j == len(board[0])):\n return\n if board[i][j] not in trie:\n return\n if len(trie[board[i][j]]) == 0:\n del trie[board[i][j]]\n return\n visited.add((i,j))\n neighbours = [(i,j-1),(i-1,j),(i,j+1),(i+1,j)]\n for n_x,n_y in neighbours:\n self.dfs(n_x,n_y,board,trie[board[i][j]],visited,word+board[i][j],solution) \n visited.remove((i,j))\n \n def make_trie(self,words):\n trie = {}\n for word in words:\n current = trie\n for char in word:\n if char not in current:\n current[char] = {}\n current = current[char]\n current[\"*\"] = \"*\"\n return trie\n\n", + "title": "212. Word Search II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two string arrays words1 and words2 . A string b is a subset of string a if every letter in b occurs in a including multiplicity. A string a from words1 is universal if for every string b in words2 , b is a subset of a . Return an array of all the universal strings in words1 . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\nOutput:[\"facebook\",\"google\",\"leetcode\"]", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\nOutput:[\"apple\",\"google\",\"leetcode\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List wordSubsets(String[] words1, String[] words2) {\n List list=new ArrayList<>();\n int[] bmax=count(\"\");\n for(String w2:words2)\n {\n int[] b=count(w2);\n for(int i=0;i<26;i++)\n {\n bmax[i]=Math.max(bmax[i],b[i]);\n }\n }\n for(String w1:words1)\n {\n int[] a=count(w1);\n for(int i=0;i<26;i++)\n {\n if(a[i] List[str]:\n freq = [0]*26 \n \n for w in B: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n for i in range(26): freq[i] = max(freq[i], temp[i])\n \n ans = []\n for w in A: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n if all(freq[i] <= temp[i] for i in range(26)): ans.append(w)\n return ans ", + "title": "916. Word Subsets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:", + "description_images": [], + "constraints": [ + "Each group has exactly X cards.", + "All the cards in each group have the same integer." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [1,2,3,4,4,3,2,1]\nOutput:true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1,1,2,2,2,3,3]\nOutput:false\nExplanation: No possible partition.", + "image": null + } + ], + "follow_up": null, + "solution": "// X of a Kind in a Deck of Cards\n// Leetcode problem : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/\n\nclass Solution {\n public boolean hasGroupsSizeX(int[] deck) {\n int[] count = new int[10000];\n for(int i : deck)\n count[i]++;\n int gcd = 0;\n for(int i : count)\n if(i != 0)\n gcd = gcd == 0 ? i : gcd(gcd, i);\n return gcd >= 2; \n }\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}\n", + "title": "914. X of a Kind in a Deck of Cards", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:", + "description_images": [], + "constraints": [ + "Each group has exactly X cards.", + "All the cards in each group have the same integer." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [1,2,3,4,4,3,2,1]\nOutput:true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1,1,2,2,2,3,3]\nOutput:false\nExplanation: No possible partition.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 130 ms (Top 52.6%) | Memory: 16.56 MB (Top 64.6%)\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n \n f=defaultdict(int)\n \n for j in deck:\n f[j]+=1\n \n \n import math\n \n u=list(f.values())\n \n g=u[0]\n \n for j in range(1,len(u)):\n g=math.gcd(g,u[j])\n return g!=1\n \n ", + "title": "914. X of a Kind in a Deck of Cards", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n and an integer start . Define an array nums where nums[i] = start + 2 * i ( 0-indexed ) and n == nums.length . Return the bitwise XOR of all elements of nums .", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= start <= 1000", + "n == nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, start = 0\nOutput:8\nExplanation:Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, start = 3\nOutput:8\nExplanation:Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int xorOperation(int n, int start) {\n int nums[]=new int[n];\n for(int i=0;i int:\n nums = [start + 2*i for i in range(n)] #generate list of numbers\n ans = nums[0]\n for i in range(1,n):\n ans = ans^nums[i] # XOR operation\n return ans\n \n \n", + "title": "1486. XOR Operation in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [left i, right i ] . For each query i compute the XOR of elements from left i to right i (that is, arr[left i ] XOR arr[left i + 1] XOR ... XOR arr[right i ] ). Return an array answer where answer[i] is the answer to the i th query.", + "description_images": [], + "constraints": [ + "1 <= arr.length, queries.length <= 3 * 10^4", + "1 <= arr[i] <= 10^9", + "queries[i].length == 2", + "0 <= left i <= right i < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput:[2,7,14,8]\nExplanation:The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput:[8,0,4,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 748 ms (Top 12.05%) | Memory: 68.5 MB (Top 10.97%)\nclass Solution\n{\n public int[] xorQueries(int[] arr, int[][] queries)\n {\n int[] ans = new int[queries.length];\n int[] xor = new int[arr.length];\n xor[0] = arr[0];\n // computing prefix XOR of arr\n for(int i = 1; i < arr.length; i++)\n {\n xor[i] = arr[i] ^ xor[i-1];\n }\n for(int i = 0; i < queries.length; i++)\n {\n // if query starts from something other than 0 (say i), then we XOR all values from arr[0] to arr[i-1]\n if(queries[i][0] != 0)\n {\n ans[i] = xor[queries[i][1]];\n for(int j = 0; j < queries[i][0]; j++)\n {\n ans[i] = arr[j] ^ ans[i];\n }\n }\n // if start of query is 0, then we striaght up use the prefix XOR till ith element\n else\n ans[i] = xor[queries[i][1]];\n }\n return ans;\n }\n}", + "title": "1310. XOR Queries of a Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [left i, right i ] . For each query i compute the XOR of elements from left i to right i (that is, arr[left i ] XOR arr[left i + 1] XOR ... XOR arr[right i ] ). Return an array answer where answer[i] is the answer to the i th query.", + "description_images": [], + "constraints": [ + "1 <= arr.length, queries.length <= 3 * 10^4", + "1 <= arr[i] <= 10^9", + "queries[i].length == 2", + "0 <= left i <= right i < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput:[2,7,14,8]\nExplanation:The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput:[8,0,4,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n\n\n \"\"\"\n\n arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\n\n find pref xor of arr\n\n pref = [x,x,x,x]\n\n for each query find the left and right indices\n the xor for range (l, r) would be pref[r] xor pref[l-1]\n \n \"\"\" \n n, m = len(queries), len(arr)\n\n answer = [1]*n\n\n pref = [1]*m\n pref[0] = arr[0]\n if m > 1:\n for i in range(1,m):\n pref[i] = pref[i-1] ^ arr[i]\n\n for (i, (l,r)) in enumerate(queries):\n if l == 0: answer[i] = pref[r] \n else: answer[i] = pref[r] ^ pref[l-1]\n\n return answer", + "title": "1310. XOR Queries of a Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3\nOutput:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4\nOutput:\"PINALSIGYAHRPI\"\nExplanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convert(String s, int numRows) {\n if (numRows==1)return s;\n StringBuilder builder = new StringBuilder();\n for (int i=1;i<=numRows;i++){\n int ind = i-1;\n boolean up = true;\n while (ind < s.length()){\n builder.append(s.charAt(ind));\n if (i==1){\n ind += 2*(numRows-i);\n } else if (i==numRows){\n ind += 2*(i-1);\n } else {\n ind += up ? 2*(numRows-i) : 2*(i-1);\n up=!up;\n }\n }\n }\n return builder.toString();\n }\n}\n", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3\nOutput:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4\nOutput:\"PINALSIGYAHRPI\"\nExplanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 96 ms (Top 61.23%) | Memory: 14 MB (Top 75.15%)\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n\n # safety check to not process single row\n if numRows == 1:\n return s\n\n # safety check to not process strings shorter/equal than numRows\n if len(s) <= numRows:\n return s\n\n # safety check to not process double rows\n if numRows == 2:\n # slice every other character\n return s[0::2] + s[1::2]\n\n # list that stores the lines\n # add lines with initial letters\n lines: list[str] = [letter for letter in s[:numRows]]\n\n # positive direction goes down\n # lines are created, so it's going up\n direction: int = -1\n\n # track the position at which the letter will be added\n # position after bouncing off, after adding initial lines\n line_index: int = numRows - 2\n\n # edge indexes\n # 0 can only be reached by going up\n # numRows only by going down\n edges: set[int] = {0, numRows}\n\n for letter in s[numRows:]:\n # add letter at tracked index position\n lines[line_index] += letter\n\n # prepare index before next loop iteration\n line_index += direction\n\n # reaching one of the edges\n if line_index in edges:\n # change direction\n direction = -direction\n # bounce off if bottom edge\n if line_index == numRows:\n line_index += direction * 2\n\n return \"\".join(lines)", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R' , yellow 'Y' , blue 'B' , green 'G' , or white 'W' . You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Given a string board , representing the row of balls on the board, and a string hand , representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1 .", + "description_images": [], + "constraints": [ + "Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.", + "If there is a group of three or more consecutive balls of the same color , remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If there are no more balls on the board, then you win the game.", + "Repeat this process until you either win or do not have any more balls in your hand." + ], + "examples": [ + { + "text": "Example 1: Input:board = \"WRRBBW\", hand = \"RB\"\nOutput:-1\nExplanation:It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.", + "image": null + }, + { + "text": "Example 2: Input:board = \"WWRRBBWW\", hand = \"WRBRW\"\nOutput:2\nExplanation:To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW ->WWWW-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + }, + { + "text": "Example 3: Input:board = \"G\", hand = \"GGGGG\"\nOutput:2\nExplanation:To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG.GGG-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1091 ms (Top 50.54%) | Memory: 147.1 MB (Top 58.06%)\nclass Solution {\n static class Hand {\n int red;\n int yellow;\n int green;\n int blue;\n int white;\n\n Hand(String hand) {\n // add an extra character, because .split() throws away trailing empty strings\n String splitter = hand + \"x\";\n red = splitter.split(\"R\").length - 1;\n yellow = splitter.split(\"Y\").length - 1;\n green = splitter.split(\"G\").length - 1;\n blue = splitter.split(\"B\").length - 1;\n white = splitter.split(\"W\").length - 1;\n }\n Hand(Hand hand) {\n red = hand.red;\n yellow = hand.yellow;\n blue = hand.blue;\n green = hand.green;\n white = hand.white;\n }\n boolean isEmpty() {\n return red == 0 && yellow == 0 && green == 0 && blue == 0 && white == 0;\n }\n List colors() {\n List res = new ArrayList<>();\n if(red > 0) res.add(\"R\");\n if(yellow > 0) res.add(\"Y\");\n if(green > 0) res.add(\"G\");\n if(blue > 0) res.add(\"B\");\n if(white > 0) res.add(\"W\");\n return res;\n }\n void removeColor(String color) {\n switch(color) {\n case \"R\":\n red--;\n break;\n case \"Y\":\n yellow--;\n break;\n case \"G\":\n green--;\n break;\n case \"B\":\n blue--;\n break;\n case \"W\":\n white--;\n break;\n }\n }\n public StringBuilder buildStringWithColon() {\n return new StringBuilder().append(red)\n .append(\",\")\n .append(yellow)\n .append(\",\")\n .append(green)\n .append(\",\")\n .append(blue)\n .append(\",\")\n .append(white)\n .append(\":\");\n }\n }\n\n /** key = hand + \":\" + board */\n private final Map boardHandToMinStep = new HashMap<>();\n\n /**\n store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n for each color in your hand:\n try to insert the color in each *effective* location\n - effective location means \"one preceding a same-color set of balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n resolve the board\n if inserting to that location finishes the game, return 1\n otherwise, recur to the resulting hand\n minstep for this setup == minimum of all resulting hands + 1\n memoize this minstep, then return it\n */\n public int findMinStep(String board, String hand) {\n // store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n Hand h = new Hand(hand);\n return findMinStep(board, h, 9999);\n }\n\n private int findMinStep(String board, Hand hand, int remainingDepth) {\n // resolve board, i.e. remove triples and higher\n board = resolve(board);\n final String key = hand.buildStringWithColon().append(board).toString();\n if(board.length() == 0) {\n return 0;\n } else if(boardHandToMinStep.containsKey(key)) {\n return boardHandToMinStep.get(key);\n }\n\n // OPTIMIZATION #3 - reduced time by 25%\n // don't go deeper than the deepest known solution - 1\n if (remainingDepth <= 0\n // OPTIMIZATION #2 - lowered from 1min to 4sec reduced time by 93%\n // for each color in the board, if there are ever fewer than three of that color in the board and hand combined, fast fail\n || !canWin(board, hand)) {\n boardHandToMinStep.put(key, -1);\n return -1;\n }\n\n int minStep = -1;\n // for each color in your hand:\n for(String color : hand.colors()) {\n // Store a new \"next hand\" and remove the color\n Hand nextHand = new Hand(hand);\n nextHand.removeColor(color);\n // for each *effective* insert location\n // - effective location means \"one preceding same-color ball(s)\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n for(int loc : effectiveLocations(color, board, nextHand.isEmpty())) {\n // insert the color and store as \"next board\"\n String nextBoard = board.substring(0, loc) + color + board.substring(loc);\n // recur to the resulting hand\n int childMinStep = findMinStep(nextBoard, nextHand, minStep == -1 ? remainingDepth - 1 : minStep - 2);\n if(childMinStep != -1) {\n // minstep for this setup == minimum of all resulting hands + 1\n minStep = minStep == -1 ? (1 + childMinStep) : Math.min(minStep, 1 + childMinStep);\n }\n }\n }\n // memoize this minstep, then return it\n boardHandToMinStep.put(key, minStep);\n return minStep;\n }\n\n private boolean canWin(String board, Hand hand) {\n String splitter = board + \"x\";\n int red = splitter.split(\"R\").length - 1;\n int yellow = splitter.split(\"Y\").length - 1;\n int green = splitter.split(\"G\").length - 1;\n int blue = splitter.split(\"B\").length - 1;\n int white = splitter.split(\"W\").length - 1;\n\n return (red == 0 || red + hand.red > 2)\n && (yellow == 0 || yellow + hand.yellow > 2)\n && (green == 0 || green + hand.green > 2)\n && (blue == 0 || blue + hand.blue > 2)\n && (white == 0 || white + hand.white > 2);\n }\n\n /**\n * effective location means \"one preceding a same-color set of 1 or more balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n * ^^ The above first pass is incorrect. Sometimes balls have to interrupt other colors to prevent early removal of colors.\n *\n * effective location means \"all locations except after a same-color ball\"\n *\n */\n private List effectiveLocations(String color, String board, boolean isLastInHand) {\n List res = new ArrayList<>();\n\n // OPTIMIZATION #4 - prefer greedy locations by adding them in this order: - reduced time by 93%\n // - preceding 2 of the same color\n // - preceding exactly 1 of the same color\n // - neighboring 0 of the same color\n List greedy2 = new ArrayList<>();\n List greedy3 = new ArrayList<>();\n\n // Preceding 2 of the same color:\n for (int i = 0; i <= board.length(); i++) {\n if (i < board.length() - 1 && board.substring(i, i + 2).equals(color + color)) {\n res.add(i);\n // skip the next 2 locations; they would be part of the same consecutive set of \"this\" color\n i+=2;\n } else if(i < board.length() && board.substring(i,i+1).equals(color)) {\n greedy2.add(i);\n // skip the next 1 location; it would be part of the same consecutive set of \"this\" color\n i++;\n } else {\n // OPTIMIZATION #5 - if a ball is not next to one of the same color, it must be between two identical, of a different color - 10s to .8s\n// greedy3.add(i);\n if(i > 0 && board.length() > i && board.substring(i-1, i).equals(board.substring(i, i+1))) {\n greedy3.add(i);\n }\n }\n }\n // OPTIMIZATION #1 - reduced time by 90%\n // if this is the last one in the hand, then it MUST be added to 2 others of the same color\n if(isLastInHand) {\n return res;\n }\n res.addAll(greedy2);\n res.addAll(greedy3);\n return res;\n }\n\n /**\n * repeatedly collapse sets of 3 or more\n */\n private String resolve(String board) {\n String copy = \"\";\n while(!board.equals(copy)) {\n copy = board;\n // min 3 in a row\n board = copy.replaceFirst(\"(.)\\\\1\\\\1+\", \"\");\n }\n return board;\n }\n}", + "title": "488. Zuma Game", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R' , yellow 'Y' , blue 'B' , green 'G' , or white 'W' . You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Given a string board , representing the row of balls on the board, and a string hand , representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1 .", + "description_images": [], + "constraints": [ + "Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.", + "If there is a group of three or more consecutive balls of the same color , remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If there are no more balls on the board, then you win the game.", + "Repeat this process until you either win or do not have any more balls in your hand." + ], + "examples": [ + { + "text": "Example 1: Input:board = \"WRRBBW\", hand = \"RB\"\nOutput:-1\nExplanation:It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.", + "image": null + }, + { + "text": "Example 2: Input:board = \"WWRRBBWW\", hand = \"WRBRW\"\nOutput:2\nExplanation:To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW ->WWWW-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + }, + { + "text": "Example 3: Input:board = \"G\", hand = \"GGGGG\"\nOutput:2\nExplanation:To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG.GGG-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \n # start from i and remove continues ball\n def remove_same(s, i):\n if i < 0:\n return s\n \n left = right = i\n while left > 0 and s[left-1] == s[i]:\n left -= 1\n while right+1 < len(s) and s[right+1] == s[i]:\n right += 1\n \n length = right - left + 1\n if length >= 3:\n new_s = s[:left] + s[right+1:]\n return remove_same(new_s, left-1)\n else:\n return s\n\n\n\n hand = \"\".join(sorted(hand))\n\n # board, hand and step\n q = collections.deque([(board, hand, 0)])\n visited = set([(board, hand)])\n\n while q:\n curr_board, curr_hand, step = q.popleft()\n for i in range(len(curr_board)+1):\n for j in range(len(curr_hand)):\n # skip the continue balls in hand\n if j > 0 and curr_hand[j] == curr_hand[j-1]:\n continue\n \n # only insert at the begin of continue balls in board\n if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color\n continue\n \n pick = False\n # 1. same color with right\n # 2. left and right are same but pick is different\n if i < len(curr_board) and curr_board[i] == curr_hand[j]:\n pick = True\n if 0 None:\n with self.cv:\n self.cv.wait_for(lambda : -2 <= self.sum <= 1)\n self.sum += 1\n releaseHydrogen()\n self.cv.notifyAll()\n\n def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:\n with self.cv:\n self.cv.wait_for(lambda : 0 <= self.sum <= 2)\n self.sum -= 2\n releaseOxygen()\n self.cv.notifyAll()", + "title": "1117. Building H2O", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz , buzz , fizzbuzz and number . The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, \"fizz\", 4, \"buzz\", ...] where the i th token ( 1-indexed ) of the series is: Implement the FizzBuzz class:", + "description_images": [], + "constraints": [ + "printFizz that prints the word \"fizz\" to the console,", + "printBuzz that prints the word \"buzz\" to the console,", + "printFizzBuzz that prints the word \"fizzbuzz\" to the console, and", + "printNumber that prints a given integer to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 15\nOutput:[1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[1,2,\"fizz\",4,\"buzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "import threading\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.fz = threading.Semaphore(0)\n self.bz = threading.Semaphore(0)\n self.fzbz = threading.Semaphore(0)\n self.num = threading.Semaphore(1)\n\n def fizz(self, printFizz):\n for i in range(self.n/3-self.n/15):\n self.fz.acquire()\n printFizz()\n self.num.release()\n\n def buzz(self, printBuzz):\n for i in range(self.n/5-self.n/15):\n self.bz.acquire()\n printBuzz()\n self.num.release()\n\n def fizzbuzz(self, printFizzBuzz):\n for i in range(self.n/15):\n self.fzbz.acquire()\n printFizzBuzz()\n self.num.release()\n \n def number(self, printNumber):\n for i in range(1, self.n+1):\n self.num.acquire()\n if i%3==0 and i%5 ==0:\n self.fzbz.release()\n elif i%3==0:\n self.fz.release()\n elif i%5==0:\n self.bz.release()\n else:\n printNumber(i)\n self.num.release()\n \n", + "title": "1195. Fizz Buzz Multithreaded", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose you are given the following code: The same instance of FooBar will be passed to two different threads: Modify the given program to output \"foobar\" n times.", + "description_images": [], + "constraints": [ + "thread A will call foo() , while", + "thread B will call bar() ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:\"foobar\"\nExplanation:There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n\"foobar\" is being output 1 time.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:\"foobarfoobar\"\nExplanation:\"foobar\" is being output 2 times.", + "image": null + }, + { + "text": "class FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n self.bar_lock.acquire()\n\n\n def foo(self, printFoo: 'Callable[[], None]') -> None:\n for i in range(self.n):\n self.foo_lock.acquire()\n # printFoo() outputs \"foo\". Do not change or remove this line.\n printFoo()\n self.bar_lock.release()\n\n\n def bar(self, printBar: 'Callable[[], None]') -> None:\n for i in range(self.n):\n self.bar_lock.acquire()\n # printBar() outputs \"bar\". Do not change or remove this line.\n printBar()\n self.foo_lock.release()\n", + "title": "1115. Print FooBar Alternately", + "topic": "Concurrency" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose we have a class: The same instance of Foo will be passed to three different threads. Thread A will call first() , thread B will call second() , and thread C will call third() . Design a mechanism and modify the program to ensure that second() is executed after first() , and third() is executed after second() . Note: We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.", + "description_images": [], + "constraints": [ + "nums is a permutation of [1, 2, 3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:\"firstsecondthird\"\nExplanation:There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). \"firstsecondthird\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2]\nOutput:\"firstsecondthird\"\nExplanation:The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). \"firstsecondthird\" is the correct output.", + "image": null + }, + { + "text": "public class Foo {\n public void first() { print(\"first\"); }\n public void second() { print(\"second\"); }\n public void third() { print(\"third\"); }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "import threading\n\nclass Foo:\n def __init__(self):\n\t\t# create lock to control sequence between first and second functions\n self.lock1 = threading.Lock()\n\t\tself.lock1.acquire()\n\t\t\n\t\t# create another lock to control sequence between second and third functions\n self.lock2 = threading.Lock()\n self.lock2.acquire()\n\n def first(self, printFirst: 'Callable[[], None]') -> None:\n printFirst()\n\t\t\n\t\t# since second function is waiting for the lock1, let's release it\n self.lock1.release()\n\n def second(self, printSecond: 'Callable[[], None]') -> None:\n\t\t# wait for first funtion to finish\n self.lock1.acquire()\n \n\t\tprintSecond()\n\t\t\n\t\t# let's release lock2, so third function can run\n self.lock2.release()\n\n def third(self, printThird: 'Callable[[], None]') -> None:\n\t\t# wait for second funtion to finish\n self.lock2.acquire()\n\t\t\n printThird()\n", + "title": "1114. Print in Order", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a function printNumber that can be called with an integer parameter and prints it to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero , even , and odd . The same instance of ZeroEvenOdd will be passed to three different threads: Modify the given class to output the series \"010203040506...\" where the length of the series must be 2n . Implement the ZeroEvenOdd class:", + "description_images": [], + "constraints": [ + "For example, calling printNumber(7) prints 7 to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:\"0102\"\nExplanation:There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n\"0102\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:\"0102030405\"", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Semaphore\nclass ZeroEvenOdd:\n def __init__(self, n):\n self.n = n\n self.semOdd = Semaphore(0) # Permission to write an Odd Number\n self.semEven = Semaphore(0) # Permission to write an Even Number\n self.semZero = Semaphore(1) # Permission to write a Zero\n\t# printNumber(x) outputs \"x\", where x is an integer.\n def zero(self, printNumber):\n for i in range(1,self.n+1):\n # A) Request Permission to Write a Zero\n self.semZero.acquire()\n printNumber(0)\n # B) Check if \"i\" if Odd or Even, and give permission to write the number\n if i&1:\n self.semOdd.release()\n else:\n self.semEven.release()\n # C) Permission to write a zero is returned by another Thread ( release triggers a change)\n def even(self, printNumber):\n # A) Iterate only through Even numbers\n for i in range(2,self.n+1,2):\n # B) Request Permission to Write Current Number\n self.semEven.acquire()\n printNumber(i)\n # C) Return Permission to Write a Zero (if applicable)\n self.semZero.release()\n def odd(self, printNumber):\n # A) Iterate only through Odd numbers\n for i in range(1,self.n+1,2):\n # B) Request Permission to Write Current Number\n self.semOdd.acquire()\n printNumber(i)\n # C) Return Permission to Write a Zero (if applicable)\n self.semZero.release()\n", + "title": "1116. Print Zero Even Odd", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers. Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks. Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed. Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e. , each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think. The problem statement and the image above are taken from wikipedia.org The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where: Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/an_illustration_of_the_dining_philosophers_problem.png" + ], + "constraints": [ + "philosopher is the id of the philosopher who wants to eat.", + "pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.", + "eat is a function you can call to let the philosopher eat once he has picked both forks.", + "putLeftFork and putRightFork are functions you can call to put down the corresponding forks of that philosopher.", + "The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:[[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]\nExplanation:n is the number of times each philosopher will call the function.\nThe output array describes the calls you made to the functions controlling the forks and the eat function, its format is:\noutput[i] = [a, b, c] (three integers)\n- a is the id of a philosopher.\n- b specifies the fork: {1 : left, 2 : right}.\n- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Semaphore\n\nclass DiningPhilosophers:\n def __init__(self):\n self.sizelock = Semaphore(4)\n self.locks = [Semaphore(1) for _ in range(5)]\n\n def wantsToEat(self, index, *actions):\n left, right = index, (index - 1) % 5\n with self.sizelock:\n with self.locks[left], self.locks[right]:\n for action in actions:\n action()\n", + "title": "1226. The Dining Philosophers", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9\nOutput:[0,1]\nExplanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6\nOutput:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] twoSum(int[] nums, int target) { // Time: O(n), Space: O(1)\n\n for (int i = 1; i < nums.length; i++) {\n\n for (int j = i; j < nums.length; j++) {\n\n if (nums[j] + nums[j - i] == target) {\n return new int[] { j - i, j };\n }\n }\n }\n\n return new int[] {};\n }\n}", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]\nOutput:[7,0,8]\nExplanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]\nOutput:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n\n ListNode head = new ListNode(0);\n ListNode current = head;\n int carry = 0;\n\n while (l1 != null || l2 != null) {\n\n int x = (l1 != null) ? l1.val : 0;\n int y = (l2 != null) ? l2.val : 0;\n int sum = x + y + carry;\n\n carry = sum / 10;\n current.next = new ListNode(sum % 10);\n current = current.next;\n\n if (l1 != null)\n l1 = l1.next;\n if (l2 != null)\n l2 = l2.next;\n }\n\n if (carry > 0) {\n current.next = new ListNode(carry);\n }\n\n return head.next;\n }\n}", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the length of the longest substring without repeating characters.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"\nOutput:3\nExplanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"\nOutput:1\nExplanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"\nOutput:3\nExplanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLongestSubstring(String s) { // Sliding Window + Hash Table (ASCII Array)\n\n // approach 2\n // int left = 0, maxLength = 0;\n // HashSet charSet = new HashSet<>();\n\n // for (int right = 0; right < s.length(); right++) {\n\n // while (charSet.contains(s.charAt(right))) {\n // charSet.remove(s.charAt(left));\n // left++;\n // }\n\n // charSet.add(s.charAt(right));\n // maxLength = Math.max(maxLength, right - left + 1);\n // }\n // return maxLength;\n\n // approach 2\n\n int[] charIndex = new int[128]; // ASCII characters\n int maxLength = 0, left = 0;\n\n for (int right = 0; right < s.length(); right++) {\n\n left = Math.max(left, charIndex[s.charAt(right)]);\n maxLength = Math.max(maxLength, right - left + 1);\n\n charIndex[s.charAt(right)] = right + 1;\n }\n\n return maxLength;\n }\n}", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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)) .", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]\nOutput:2.00000\nExplanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]\nOutput:2.50000\nExplanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n\n if (nums1.length > nums2.length) {\n return findMedianSortedArrays(nums2, nums1); // Ensure nums1 is smaller\n }\n\n int m = nums1.length, n = nums2.length;\n int left = 0, right = m;\n\n while (left <= right) {\n int i = left + (right - left) / 2;\n int j = (m + n + 1) / 2 - i;\n\n int maxLeft1 = (i == 0) ? Integer.MIN_VALUE : nums1[i - 1];\n int minRight1 = (i == m) ? Integer.MAX_VALUE : nums1[i];\n\n int maxLeft2 = (j == 0) ? Integer.MIN_VALUE : nums2[j - 1];\n int minRight2 = (j == n) ? Integer.MAX_VALUE : nums2[j];\n\n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n\n if ((m + n) % 2 == 0) {\n return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;\n } else {\n return Math.max(maxLeft1, maxLeft2);\n }\n\n } else if (maxLeft1 > minRight2) {\n right = i - 1; // Move left\n } else {\n left = i + 1; // Move right\n }\n }\n\n throw new IllegalArgumentException(\"Input arrays are not sorted.\");\n }\n}", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the longest palindromic substring in s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"\nOutput:\"bab\"\nExplanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"\nOutput:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestPalindrome(String s) {\n if (s == null || s.length() < 1)\n return \"\";\n\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expandFromCenter(s, i, i); // Odd length\n int len2 = expandFromCenter(s, i, i + 1); // Even length\n int len = Math.max(len1, len2);\n\n if (len > end - start) {\n start = i - (len - 1) / 2;\n end = i + len / 2;\n }\n }\n\n return s.substring(start, end + 1);\n }\n\n private int expandFromCenter(String s, int left, int right) {\n\n while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {\n left--;\n right++;\n }\n return right - left - 1;\n }\n}", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3\nOutput:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4\nOutput:\"PINALSIGYAHRPI\"\nExplanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convert(String s, int numRows) {\n\n // Edge case: if numRows is 1, no zigzag needed\n if (numRows == 1)\n return s;\n\n StringBuilder[] rows = new StringBuilder[numRows];\n for (int i = 0; i < numRows; i++) {\n rows[i] = new StringBuilder();\n }\n\n int currentRow = 0;\n boolean goingDown = false;\n\n // Iterate through each character in the string\n for (char c : s.toCharArray()) {\n rows[currentRow].append(c);\n\n // Change direction at the top and bottom\n if (currentRow == 0 || currentRow == numRows - 1) {\n goingDown = !goingDown;\n }\n\n // Move to the next row\n currentRow += goingDown ? 1 : -1;\n }\n\n StringBuilder result = new StringBuilder();\n for (StringBuilder row : rows) {\n result.append(row);\n }\n\n return result.toString();\n }\n}", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123\nOutput:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123\nOutput:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120\nOutput:21", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reverse(int x) {\n \n int result = 0;\n\n while (x != 0) {\n \n int pop = x % 10;\n x /= 10;\n\n // Check for overflow\n if (result > Integer.MAX_VALUE / 10 || \n (result == Integer.MAX_VALUE / 10 && pop > 7)) {\n \n return 0;\n }\n \n // Check for underflow\n if (result < Integer.MIN_VALUE / 10 || \n (result == Integer.MIN_VALUE / 10 && pop < -8)) {\n return 0;\n }\n\n result = result * 10 + pop;\n }\n\n return result;\n }\n}", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Return the integer as the final result.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 200", + "s consists of English letters (lower-case and upper-case), digits ( 0-9 ), ' ' , '+' , '-' , and '.' ." + ], + "examples": [ + { + "text": "Example 1: The underlined characters are what is read in and the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^", + "image": null + }, + { + "text": "Example 2: Step 1: \"-042\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-042\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -042\" (\"042\" is read in, leading zeros ignored in the result)\n ^", + "image": null + }, + { + "text": "Example 3: Step 1: \"1337c0d3\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"1337c0d3\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"1337c0d3\" (\"1337\" is read in; reading stops because the next character is a non-digit)\n ^", + "image": null + }, + { + "text": "Example 4: Step 1: \"0-1\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"0-1\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"0-1\" (\"0\" is read in; reading stops because the next character is a non-digit)\n ^", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int myAtoi(String s) {\n \n int index = 0, sign = 1, total = 0;\n int n = s.length();\n \n // Check if the string is empty\n if (n == 0) return 0;\n \n // Triming whitespaces --> 1. Whitespace: Ignore any leading whitespace (\" \").\n while (index < n && s.charAt(index) == ' ') {\n index++;\n }\n \n \n // removing whitespaces, if the index is 0 or not \n if (index == n) return 0;\n \n \n // --> 2. Signedness: checking if the next character is '-' or '+'\n if (s.charAt(index) == '+' || s.charAt(index) == '-') {\n sign = (s.charAt(index) == '-') ? -1 : 1;\n index++;\n }\n \n // Convert the number and avoid non-digit characters --> 3. Rounding: If the integer \n while (index < n) {\n \n char currentChar = s.charAt(index);\n \n if (currentChar < '0' || currentChar > '9') break;\n\n // Check for overflow and underflow\n if (total > (Integer.MAX_VALUE - (currentChar - '0')) / 10) {\n return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;\n }\n \n // Append current digit to the total\n total = total * 10 + (currentChar - '0');\n index++;\n }\n \n // --> Return the final result with the correct sign\n return total * sign;\n }\n}\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer x , return true if x is a palindrome , and false otherwise .", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 121\nOutput:true\nExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121\nOutput:false\nExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10\nOutput:false\nExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0))\n return false;\n\n int revHalf = 0;\n while (x > revHalf) {\n revHalf = revHalf * 10 + x % 10;\n x /= 10;\n }\n\n return x == revHalf || x == revHalf / 10;\n }\n}", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == height.length", + "2 <= n <= 10^5", + "0 <= height[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:height = [1,8,6,2,5,4,8,3,7]\nOutput:49\nExplanation: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.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg" + }, + { + "text": "Example 2: Input:height = [1,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxArea(int[] height) { // two pointer approach\n\n int start = 0, end = height.length - 1, maxArea = 0;\n\n while (start < end) {\n // MaxArea -> height * min width from start or end\n maxArea = Math.max(maxArea, (end - start) * Math.min(height[start], height[end]));\n\n if (height[start] < height[end]) {\n start++;\n } else {\n end--;\n }\n }\n\n return maxArea;\n }\n}", + "title": "11. Container With Most Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Seven different symbols represent Roman numerals with the following values: 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: Given an integer, convert it to a Roman numeral.", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n 40 = XL as 10 (X) less of 50 (L)\n 9 = IX as 1 (I) less of 10 (X)\nNote: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places", + "image": null + }, + { + "text": "Example 2: 50 = L\n 8 = VIII", + "image": null + }, + { + "text": "Example 3: 1000 = M\n 900 = CM\n 90 = XC\n 4 = IV", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n private static final int[] n = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };\n private static final String[] s = { \"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\" };\n\n public String intToRoman(int num) {\n\n StringBuilder roman = new StringBuilder();\n\n for (int i = 0; i < n.length; i++) {\n\n while (num >= n[i]) { // Deduct values as long as the current numeral can be used\n roman.append(s[i]);\n num -= n[i];\n }\n }\n\n return roman.toString();\n }\n}", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given a roman numeral, convert it to an integer.", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"III\"\nOutput:3\nExplanation:III = 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"LVIII\"\nOutput:58\nExplanation:L = 50, V= 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:s = \"MCMXCIV\"\nOutput:1994\nExplanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int romanToInt(String s) {\n\n int ans = 0, num = 0;\n\n for (int i = s.length() - 1; i >= 0; i--) {\n\n switch (s.charAt(i)) {\n case 'I':\n num = 1;\n break;\n case 'V':\n num = 5;\n break;\n case 'X':\n num = 10;\n break;\n case 'L':\n num = 50;\n break;\n case 'C':\n num = 100;\n break;\n case 'D':\n num = 500;\n break;\n case 'M':\n num = 1000;\n break;\n }\n\n if (4 * num < ans)\n ans -= num;\n else\n ans += num;\n }\n\n return ans;\n\n // Map roman = new HashMap<>();\n // roman.put('I', 1);\n // roman.put('V', 5);\n // roman.put('X', 10);\n // roman.put('L', 50);\n // roman.put('C', 100);\n // roman.put('D', 500);\n // roman.put('M', 1000);\n\n // int result = 0;\n // int n = s.length();\n\n // for (int i = 0; i < n; i++) {\n\n // if (i + 1 < n && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) {\n // result -= roman.get(s.charAt(i));\n // } else {\n // result += roman.get(s.charAt(i));\n // }\n // }\n\n // return result;\n }\n}", + "title": "13. Roman to Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\" .", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 200", + "0 <= strs[i].length <= 200", + "strs[i] consists of only lowercase English letters if it is non-empty." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"flower\",\"flow\",\"flight\"]\nOutput:\"fl\"", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"dog\",\"racecar\",\"car\"]\nOutput:\"\"\nExplanation:There is no common prefix among the input strings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public String longestCommonPrefix(String[] strs) {\n\n if (strs.length == 0) {\n return \"\";\n }\n\n String firstEliment = strs[0];\n\n for (int i = 1; i < strs.length; i++) {\n\n while (strs[i].indexOf(firstEliment) != 0) {\n firstEliment = firstEliment.substring(0, firstEliment.length() - 1);\n }\n }\n return firstEliment;\n }\n}", + "title": "14. Longest Common Prefix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 3000", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,1,2,-1,-4]\nOutput:[[-1,-1,2],[-1,0,1]]\nExplanation:nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1]\nOutput:[]\nExplanation:The only possible triplet does not sum up to 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0]\nOutput:[[0,0,0]]\nExplanation:The only possible triplet sums up to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> threeSum(int[] nums) {\n \n List> res = new ArrayList<>();\n Arrays.sort(nums); // Sorting the array (O(n log n))\n\n for (int i = 0; i < nums.length - 2; i++) { // Avoid unnecessary iterations\n if (i > 0 && nums[i] == nums[i - 1])\n continue; // Skip duplicates for i\n\n int j = i + 1, k = nums.length - 1;\n\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n\n if (sum > 0) {\n k--;\n } else if (sum < 0) {\n j++;\n } else {\n res.add(Arrays.asList(nums[i], nums[j], nums[k]));\n\n // Move pointers to avoid duplicates\n while (j < k && nums[j] == nums[j + 1])\n j++; // Skip duplicate for j\n while (j < k && nums[k] == nums[k - 1])\n k--; // Skip duplicate for k\n\n j++;\n k--;\n }\n }\n }\n return res;\n }\n}\n", + "title": "15. 3Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of length n and an integer target , find three integers in nums such that the sum is closest to target . Return the sum of the three integers . You may assume that each input would have exactly one solution.", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 500", + "-1000 <= nums[i] <= 1000", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,2,1,-4], target = 1\nOutput:2\nExplanation:The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], target = 1\nOutput:0\nExplanation:The sum that is closest to the target is 0. (0 + 0 + 0 = 0).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int n = nums.length;\n int closesSum = nums[0] + nums[1] + nums[2];\n\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1;\n int right = n - 1;\n\n while (left < right) {\n\n int curSum = nums[i] + nums[left] + nums[right];\n\n if (Math.abs(curSum - target) < Math.abs(closesSum - target)) {\n closesSum = curSum;\n }\n\n if (curSum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n\n return closesSum;\n }\n}", + "title": "16. 3Sum Closest", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"\nOutput:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"\nOutput:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public static List letterCombinations(String digits) {\n if (digits == null || digits.isEmpty())\n return new ArrayList<>();\n\n Map phoneMap = Map.of(\n '2', \"abc\", '3', \"def\", '4', \"ghi\", '5', \"jkl\",\n '6', \"mno\", '7', \"pqrs\", '8', \"tuv\", '9', \"wxyz\");\n\n List result = new ArrayList<>();\n backtrack(result, digits, phoneMap, new StringBuilder(), 0);\n return result;\n }\n\n private static void backtrack(\n List result,\n String digits,\n Map phoneMap,\n StringBuilder path,\n int index) {\n\n if (index == digits.length()) {\n result.add(path.toString());\n return;\n }\n\n String letters = phoneMap.get(digits.charAt(index));\n for (char letter : letters.toCharArray()) {\n path.append(letter);\n\n backtrack(result, digits, phoneMap, path, index + 1);\n path.deleteCharAt(path.length() - 1); // Backtrack\n }\n }\n}", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order .", + "description_images": [], + "constraints": [ + "0 <= a, b, c, d < n", + "a , b , c , and d are distinct .", + "nums[a] + nums[b] + nums[c] + nums[d] == target" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,-1,0,-2,2], target = 0\nOutput:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], target = 8\nOutput:[[2,2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> fourSum(int[] nums, int target) {\n List> result = new ArrayList<>();\n Arrays.sort(nums);\n int n = nums.length;\n\n for (int i = 0; i < n - 3; i++) {\n\n if (i > 0 && nums[i] == nums[i - 1])\n continue;\n\n for (int j = i + 1; j < n - 2; j++) {\n\n if (j > i + 1 && nums[j] == nums[j - 1])\n continue;\n\n int left = j + 1;\n int right = n - 1;\n\n while (left < right) {\n long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];\n\n if (sum == target) {\n result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));\n\n while (left < right && nums[left] == nums[left + 1])\n left++;\n\n while (left < right && nums[right] == nums[right - 1])\n right--;\n\n left++;\n right--;\n\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n }\n\n return result;\n }\n}", + "title": "18. 4Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2\nOutput:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n\n ListNode fast = dummy, slow = dummy;\n\n for (int i = 0; i <= n; i++) {\n fast = fast.next;\n }\n\n while (fast != null) {\n fast = fast.next;\n slow = slow.next;\n }\n\n slow.next = slow.next.next;\n\n return dummy.next;\n }\n}", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [], + "follow_up": null, + "solution": "import java.util.Stack;\n\nclass Solution {\n public boolean isValid(String s) {\n\n char[] chars = new char[s.length()];\n int top = -1;\n\n for (char c : s.toCharArray()) {\n\n if (c == '(' || c == '{' || c == '[') {\n top += 1;\n chars[top] = c;\n\n } else {\n\n if (top == -1)\n return false;\n char pop = chars[top];\n top -= 1;\n\n if (!((pop == '(' && c == ')') ||\n (pop == '[' && c == ']') ||\n (pop == '{' && c == '}'))) {\n return false;\n }\n }\n }\n\n return top == -1;\n }\n}", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]\nOutput:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n\n ListNode head = new ListNode(0);\n ListNode current = head;\n\n while (list1 != null && list2 != null) {\n\n if (list1.val <= list2.val) {\n current.next = list1;\n list1 = list1.next;\n } else {\n current.next = list2;\n list2 = list2.next;\n }\n\n current = current.next;\n }\n\n if (list1 != null)\n current.next = list1;\n if (list2 != null)\n current.next = list2;\n\n return head.next;\n }\n}", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses .", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1\nOutput:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List generateParenthesis(int n) {\n List result = new ArrayList<>();\n \n backtrack(result, new StringBuilder(), 0, 0, n);\n return result;\n }\n\n private void backtrack(List result, StringBuilder current, int open, int close, int n) {\n if (current.length() == 2 * n) {\n result.add(current.toString());\n return;\n }\n\n if (open < n) {\n current.append('(');\n backtrack(result, current, open + 1, close, n);\n current.deleteCharAt(current.length() - 1);\n }\n\n if (close < open) {\n current.append(')');\n backtrack(result, current, open, close + 1, n);\n current.deleteCharAt(current.length() - 1);\n }\n }\n}", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]\nOutput:[1,1,2,3,4,4,5,6]\nExplanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);\n\n for (ListNode list : lists) {\n if (list != null) {\n minHeap.add(list);\n }\n }\n\n ListNode dummy = new ListNode(0);\n ListNode tail = dummy;\n\n while (!minHeap.isEmpty()) {\n ListNode smallest = minHeap.poll();\n tail.next = smallest;\n tail = tail.next;\n\n if (smallest.next != null) {\n minHeap.add(smallest.next);\n }\n }\n\n return dummy.next;\n }\n}", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + ], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n\n ListNode prev = dummy;\n\n while (head != null && head.next != null) {\n ListNode first = head;\n ListNode second = head.next;\n\n prev.next = second;\n first.next = second.next;\n second.next = first;\n\n prev = first;\n head = first.next;\n }\n\n return dummy.next;\n }\n}", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3\nOutput:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n\n if (head == null || k == 1)\n return head;\n\n ListNode temp = head;\n int count = 0;\n\n while (temp != null && count < k) {\n temp = temp.next;\n count++;\n }\n\n if (count < k)\n return head;\n\n ListNode prev = null, curr = head, next = null;\n\n for (int i = 0; i < k; i++) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n head.next = reverseKGroup(curr, k);\n\n return prev;\n }\n}", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove the duplicates in-place such that each unique element appears only once . The relative order of the elements should be kept the same . Then return the number of unique elements in nums . Consider the number of unique elements of nums to be k , to get accepted, you need to do the following things: Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums .", + "Return k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]\nOutput:2, nums = [1,2,_]\nExplanation:Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,2,2,3,3,4]\nOutput:5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation:Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeDuplicates(int[] nums) {\n\n int k = 1;\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] != nums[i - 1]) {\n nums[k] = nums[i];\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "26. Remove Duplicates from Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer val , remove all occurrences of val in nums in-place . The order of the elements may be changed. Then return the number of elements in nums which are not equal to val . Consider the number of elements in nums which are not equal to val be k , to get accepted, you need to do the following things: Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "Change the array nums such that the first k elements of nums contain the elements which are not equal to val . The remaining elements of nums are not important as well as the size of nums .", + "Return k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,2,3], val = 3\nOutput:2, nums = [2,2,_,_]\nExplanation:Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2,2,3,0,4,2], val = 2\nOutput:5, nums = [0,1,4,0,3,_,_,_]\nExplanation:Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeElement(int[] nums, int val) {\n \n int k = 0;\n\n for (int i = 0; i < nums.length; i++) {\n\n if(nums[i] != val) {\n nums[k] = nums[i]; // shifting elements if if not equal to val\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "27. Remove Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings needle and haystack , return the index of the first occurrence of needle in haystack , or -1 if needle is not part of haystack .", + "description_images": [], + "constraints": [ + "1 <= haystack.length, needle.length <= 10^4", + "haystack and needle consist of only lowercase English characters." + ], + "examples": [ + { + "text": "Example 1: Input:haystack = \"sadbutsad\", needle = \"sad\"\nOutput:0\nExplanation:\"sad\" occurs at index 0 and 6.\nThe first occurrence is at index 0, so we return 0.", + "image": null + }, + { + "text": "Example 2: Input:haystack = \"leetcode\", needle = \"leeto\"\nOutput:-1\nExplanation:\"leeto\" did not occur in \"leetcode\", so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int strStr(String haystack, String needle) { // Time complexity: O(n∗m) || Space complexity: O(1)\n\n if (haystack.length() < needle.length()) {\n return -1;\n }\n\n for (int i = 0; i <= haystack.length() - needle.length(); i++) {\n\n if (haystack.substring(i, i + needle.length()).equals(needle)) { // sliding window approach\n return i;\n }\n }\n\n return -1;\n }\n}", + "title": "28. Find the Index of the First Occurrence in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8 , and -2.7335 would be truncated to -2 . Return the quotient after dividing dividend by divisor . Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1] . For this problem, if the quotient is strictly greater than 2 31 - 1 , then return 2 31 - 1 , and if the quotient is strictly less than -2 31 , then return -2 31 .", + "description_images": [], + "constraints": [ + "-2 31 <= dividend, divisor <= 2 31 - 1", + "divisor != 0" + ], + "examples": [ + { + "text": "Example 1: Input:dividend = 10, divisor = 3\nOutput:3\nExplanation:10/3 = 3.33333.. which is truncated to 3.", + "image": null + }, + { + "text": "Example 2: Input:dividend = 7, divisor = -3\nOutput:-2\nExplanation:7/-3 = -2.33333.. which is truncated to -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divide(int dividend, int divisor) {\n if (dividend == Integer.MIN_VALUE && divisor == -1) {\n return Integer.MAX_VALUE;\n }\n\n long a = Math.abs((long) dividend);\n long b = Math.abs((long) divisor);\n int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;\n\n int result = 0;\n\n for (int i = 31; i >= 0; i--) {\n if ((a >> i) >= b) {\n result += 1 << i;\n a -= b << i;\n }\n }\n\n return sign * result;\n }\n}", + "title": "29. Divide Two Integers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated. Return an array of the starting indices of all the concatenated substrings in s . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated string because it is not the concatenation of any permutation of words ." + ], + "examples": [], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List findSubstring(String s, String[] words) {\n List result = new ArrayList<>();\n if (s == null || words == null || words.length == 0)\n return result;\n\n int wordLen = words[0].length();\n int wordCount = words.length;\n int windowLen = wordLen * wordCount;\n\n if (s.length() < windowLen)\n return result;\n\n // Store word frequency\n Map wordMap = new HashMap<>();\n for (String word : words) {\n wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);\n }\n\n // Iterate over possible start positions\n for (int i = 0; i < wordLen; i++) {\n int left = i, right = i;\n Map seenWords = new HashMap<>();\n\n while (right + wordLen <= s.length()) {\n String word = s.substring(right, right + wordLen);\n right += wordLen;\n\n if (wordMap.containsKey(word)) {\n seenWords.put(word, seenWords.getOrDefault(word, 0) + 1);\n\n // checks if the current window has more occurrences of word than allowed\n while (seenWords.get(word) > wordMap.get(word)) {\n String leftWord = s.substring(left, left + wordLen);\n seenWords.put(leftWord, seenWords.get(leftWord) - 1);\n left += wordLen;\n }\n\n if (right - left == windowLen) {\n result.add(left);\n }\n } else {\n // Reset everything if word not found\n seenWords.clear();\n left = right;\n }\n }\n }\n\n return result;\n }\n}\n", + "title": "30. Substring with Concatenation of All Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory.", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are all the permutations of arr : [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]\nOutput:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]\nOutput:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void nextPermutation(int[] nums) {\n if (nums == null || nums.length <= 1)\n return;\n\n int i = nums.length - 2;\n\n while (i >= 0 && nums[i] >= nums[i + 1]) {\n i--;\n }\n\n if (i >= 0) {\n int j = nums.length - 1;\n\n while (nums[j] <= nums[i]) {\n j--;\n }\n\n swap(nums, i, j);\n }\n\n reverse(nums, i + 1, nums.length - 1);\n }\n\n private void reverse(int[] nums, int left, int right) {\n while (left < right) {\n swap(nums, left++, right--);\n }\n }\n\n private void swap(int[] nums, int i, int j) {\n int tmp = nums[i];\n nums[i] = nums[j];\n nums[j] = tmp;\n }\n}", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string containing just the characters '(' and ')' , return the length of the longest valid (well-formed) parentheses substring .", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"\nOutput:2\nExplanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"\nOutput:4\nExplanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestValidParentheses(String s) {\n Stack stack = new Stack<>();\n stack.push(-1);\n int maxLength = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (s.charAt(i) == '(') {\n stack.push(i);\n } else {\n stack.pop();\n \n if (stack.isEmpty()) {\n stack.push(i);\n } else {\n maxLength = Math.max(maxLength, i - stack.peek());\n }\n }\n }\n\n return maxLength;\n }\n}", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot 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 rotated at pivot index 3 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.", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,6,7,0,1,2], target = 0\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2], target = 3\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], target = 0\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1; // Prevents overflow\n\n if (nums[mid] == target) {\n return mid; // base case\n }\n\n // Determine the sorted half\n if (nums[low] <= nums[mid]) { // Left half is sorted\n\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1; // Search left\n } else {\n low = mid + 1; // Search right\n }\n\n } else { // Right half is sorted\n\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1; // Search right\n } else {\n high = mid - 1; // Search left\n }\n }\n }\n\n return -1;\n }\n}", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8\nOutput:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6\nOutput:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0\nOutput:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] searchRange(int[] nums, int target) {\n int[] result = new int[] { -1, -1 };\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n\n if (nums[mid] == target) {\n\n int left = mid;\n while (left - 1 >= low && nums[left - 1] == target) {\n left--;\n }\n result[0] = left;\n\n int right = mid;\n while (right + 1 <= high && nums[right + 1] == target) {\n right++;\n }\n result[1] = right;\n\n break;\n }\n\n if (nums[mid] < target) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return result;\n }\n}", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int searchInsert(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] < target) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return low;\n }\n}", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput:false\nExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n\n public static boolean isValidSudoku(char[][] board) {\n int[] rows = new int[9]; // Track numbers in rows\n int[] cols = new int[9]; // Track numbers in columns\n int[] boxes = new int[9]; // Track numbers in 3x3 boxes\n\n for (int i = 0; i < 9; i++) {\n\n for (int j = 0; j < 9; j++) {\n char num = board[i][j];\n\n if (num != '.') {\n int val = num - '1'; // Convert '1'-'9' to 0-8\n int boxIndex = (i / 3) * 3 + (j / 3);\n\n int mask = 1 << val; // Bit mask for current number\n if ((rows[i] & mask) != 0 || (cols[j] & mask) != 0 || (boxes[boxIndex] & mask) != 0) {\n return false; // Duplicate detected\n }\n\n // Mark the number in row, column, and box\n rows[i] |= mask;\n cols[j] |= mask;\n boxes[boxIndex] |= mask;\n }\n }\n }\n\n return true;\n }\n}\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules : The '.' character indicates empty cells.", + "description_images": [], + "constraints": [ + "board.length == 9", + "board[i].length == 9", + "board[i][j] is a digit or '.' .", + "It is guaranteed that the input board has only one solution." + ], + "examples": [ + { + "text": "Example 1: 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\"]]\nOutput:[[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]\nExplanation:The input board is shown above and the only valid solution is shown below:", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n\n private boolean solve(char[][] board) {\n\n for (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n\n if (board[row][col] == '.') {\n\n for (char d = '1'; d <= '9'; d++) {\n\n if (isValid(board, row, col, d)) {\n board[row][col] = d;\n if (solve(board))\n return true;\n board[row][col] = '.'; // backtrack\n }\n }\n return false;\n }\n }\n }\n return true;\n }\n\n private boolean isValid(char[][] board, int row, int col, char d) {\n\n for (int i = 0; i < 9; i++) {\n if (board[row][i] == d)\n return false; // check row\n if (board[i][col] == d)\n return false; // check col\n if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == d)\n return false; // check box\n }\n\n return true;\n }\n}", + "title": "37. Sudoku Solver", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "2 <= candidates[i] <= 40", + "All elements of candidates are distinct .", + "1 <= target <= 40" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7\nOutput:[[2,2,3],[7]]\nExplanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8\nOutput:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public List> combinationSum(int[] candidates, int target) {\n List> result = new ArrayList<>();\n backtrack(0, candidates, target, new ArrayList<>(), result);\n\n return result;\n }\n\n private void backtrack(int index, int[] candidates, int target, List path, List> result) {\n if (target == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = index; i < candidates.length; i++) {\n\n if (candidates[i] <= target) {\n path.add(candidates[i]);\n backtrack(i, candidates, target - candidates[i], path, result);\n path.removeLast(); // Backtrack\n }\n }\n }\n}", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8\nOutput:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5\nOutput:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combinationSum2(int[] candidates, int target) {\n Arrays.sort(candidates);\n List> result = new ArrayList<>();\n \n backtrack(candidates, 0, target, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int[] candidates, int start, int target, List path, List> result) {\n if (target == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i < candidates.length; i++) {\n\n if (i > start && candidates[i] == candidates[i - 1])\n continue;\n\n if (candidates[i] > target)\n break;\n\n path.add(candidates[i]);\n backtrack(candidates, i + 1, target - candidates[i], path, result);\n path.removeLast();\n }\n }\n}", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an unsorted integer array nums . Return the smallest positive integer that is not present in nums . You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0]\nOutput:3\nExplanation:The numbers in the range [1,2] are all in the array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,-1,1]\nOutput:2\nExplanation:1 is in the array but 2 is missing.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,8,9,11,12]\nOutput:1\nExplanation:The smallest positive integer 1 is missing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstMissingPositive(int[] nums) {\n int n = nums.length;\n\n for (int i = 0; i < n; i++) {\n while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {\n swap(nums, i, nums[i] - 1);\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (nums[i] != i + 1)\n return i + 1;\n }\n\n return n + 1;\n }\n\n private void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}", + "title": "41. First Missing Positive", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput:6\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trap(int[] height) {\n\n int n = height.length;\n int left = 0, right = n - 1;\n int leftMax = height[left], rightMax = height[right];\n int result = 0;\n\n if (n < 1)\n return 0;\n\n while (left < right) {\n\n if (leftMax < rightMax) {\n left++;\n leftMax = leftMax > height[left] ? leftMax : height[left];\n result += leftMax - height[left];\n\n } else {\n right--;\n rightMax = rightMax > height[right] ? rightMax : height[right];\n result += rightMax - height[right];\n }\n }\n\n return result;\n }\n}", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of integers nums of length n . You are initially positioned at nums[0] . Each element nums[i] represents the maximum length of a forward jump from index i . In other words, if you are at nums[i] , you can jump to any nums[i + j] where: Return the minimum number of jumps to reach nums[n - 1] . The test cases are generated such that you can reach nums[n - 1] .", + "description_images": [], + "constraints": [ + "0 <= j <= nums[i] and", + "i + j < n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]\nOutput:2\nExplanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int jump(int[] nums) {\n int farthest = 0; // farthest index\n int end = 0; // farthest end to reach\n int jump = 0; // number of jumps taken to reach the goal\n int n = nums.length; // last index\n\n for (int i = 0; i < n - 1; i++) {\n\n if (farthest < i + nums[i]) {\n farthest = i + nums[i];\n }\n\n if (i == end) {\n jump++;\n end = farthest;\n }\n }\n return jump;\n }\n}", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]\nOutput:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n\n backtrack(nums, new ArrayList<>(), used, result);\n return result;\n }\n\n private void backtrack(int[] nums, List path, boolean[] used, List> result) {\n\n if (path.size() == nums.length) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = 0; i < nums.length; i++) {\n\n if (!used[i]) {\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, path, used, result);\n path.removeLast();\n used[i] = false;\n }\n }\n }\n}", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[][] matrix) {\n int n = matrix.length;\n\n // Step 1: Transpose the matrix\n for (int i = 0; i < n; i++) {\n\n for (int j = i + 1; j < n; j++) {\n\n int temp = matrix[i][j];\n matrix[i][j] = matrix[j][i];\n matrix[j][i] = temp;\n }\n }\n\n // Step 2: Reverse each row\n for (int i = 0; i < n; i++) {\n\n for (int j = 0; j < n / 2; j++) {\n\n int temp = matrix[i][j];\n matrix[i][j] = matrix[i][n - j - 1];\n matrix[i][n - j - 1] = temp;\n }\n }\n }\n}", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings strs , group the anagrams together. You can return the answer in any order .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public List> groupAnagrams(String[] strs) {\n Map> map = new HashMap<>();\n\n for (String str : strs) {\n int[] count = new int[26]; // Array to count frequency of each character\n\n // Count frequency of characters\n for (char c : str.toCharArray()) {\n count[c - 'a']++;\n }\n\n // Convert the frequency count array to a string (for use as a key)\n StringBuilder key = new StringBuilder();\n for (int c : count) {\n key.append(\"#\"); // Separate frequencies for better uniqueness\n key.append(c);\n }\n\n // Group anagrams based on the frequency count\n map.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(str);\n }\n\n return new ArrayList<>(map.values());\n }\n}", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ).", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "n is an integer.", + "Either x is not zero or n > 0 .", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10\nOutput:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3\nOutput:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2\nOutput:0.25000\nExplanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double myPow(double x, int n) {\n if (n == 0)\n return 1.0;\n\n long power = n;\n if (n < 0) {\n x = 1 / x; // Handle negative exponent\n power = -power; // Convert to positive\n }\n\n double result = 1.0;\n while (power > 0) {\n\n if ((power & 1) == 1) { // If current bit is set, multiply\n result *= x;\n }\n\n x *= x; // Square x\n power >>= 1; // Divide power by 2\n }\n\n return result;\n }\n}", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\nExplanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private List> solutions = new ArrayList<>();\n\n public List> solveNQueens(int n) {\n char[][] board = new char[n][n];\n\n for (char[] row : board) {\n Arrays.fill(row, '.');\n }\n\n backtrack(0, n, 0, 0, 0, board);\n return solutions;\n }\n\n private void backtrack(int row, int n, int cols, int diagonals, int antiDiagonals, char[][] board) {\n if (row == n) {\n solutions.add(constructBoard(board));\n return;\n }\n\n int availablePositions = ((1 << n) - 1) & ~(cols | diagonals | antiDiagonals);\n\n while (availablePositions != 0) {\n int position = availablePositions & -availablePositions; // Get rightmost available position\n availablePositions -= position; // Remove this position\n\n int col = Integer.bitCount(position - 1); // Convert bitmask to column index\n\n board[row][col] = 'Q'; // Place queen\n backtrack(row + 1,\n n,\n cols | position,\n (diagonals | position) << 1,\n (antiDiagonals | position) >> 1,\n board);\n board[row][col] = '.'; // Backtrack\n }\n }\n\n private List constructBoard(char[][] board) {\n List res = new ArrayList<>();\n\n for (char[] row : board) {\n res.add(new String(row));\n }\n return res;\n }\n}", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:2\nExplanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int count = 0;\n\n public int totalNQueens(int n) {\n backtrack(0, n, 0, 0, 0);\n return count;\n }\n\n private void backtrack(int row, int n, int cols, int diagonals, int antiDiagonals) {\n if (row == n) {\n count++;\n return;\n }\n\n int availablePositions = ((1 << n) - 1) & ~(cols | diagonals | antiDiagonals);\n\n while (availablePositions != 0) {\n int position = availablePositions & -availablePositions; // Get rightmost available position\n availablePositions -= position; // Remove this position\n\n backtrack(row + 1, n, cols | position, (diagonals | position) << 1, (antiDiagonals | position) >> 1);\n }\n }\n}", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , find the subarray with the largest sum, and return its sum .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput:6\nExplanation:The subarray [4,-1,2,1] has the largest sum 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]\nOutput:1\nExplanation:The subarray [1] has the largest sum 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,4,-1,7,8]\nOutput:23\nExplanation:The subarray [5,4,-1,7,8] has the largest sum 23.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubArray(int[] nums) {\n int maxSum = Integer.MIN_VALUE;\n int currentSum = 0;\n\n for (int num : nums) {\n currentSum += num;\n maxSum = Math.max(maxSum, currentSum);\n\n if (currentSum < 0)\n currentSum = 0;\n }\n\n return maxSum;\n }\n}", + "title": "53. Maximum Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nOutput:[1,2,3,4,8,12,11,10,9,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List spiralOrder(int[][] matrix) {\n List result = new ArrayList<>();\n\n if (matrix == null || matrix.length == 0)\n return result;\n\n int m = matrix.length, n = matrix[0].length;\n int top = 0, bottom = m - 1, left = 0, right = n - 1;\n\n while (top <= bottom && left <= right) {\n // Move Right\n for (int i = left; i <= right; i++)\n result.add(matrix[top][i]);\n top++;\n\n // Move Down\n for (int i = top; i <= bottom; i++)\n result.add(matrix[i][right]);\n right--;\n\n // Move Left (Check if we still have rows left)\n if (top <= bottom) {\n for (int i = right; i >= left; i--)\n result.add(matrix[bottom][i]);\n bottom--;\n }\n\n // Move Up (Check if we still have columns left)\n if (left <= right) {\n for (int i = bottom; i >= top; i--)\n result.add(matrix[i][left]);\n left++;\n }\n }\n \n return result;\n }\n}\n", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]\nOutput:true\nExplanation:Jump 1 step from index 0 to 1, then 3 steps to the last index.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,0,4]\nOutput:false\nExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canJump(int[] nums) {\n\n int steps = 0;\n\n for (int i = 0; i < nums.length; i++) {\n\n if (steps < i) {\n return false;\n }\n\n steps = Math.max(steps, i + nums[i]);\n\n if (steps >= nums.length - 1) {\n return true;\n }\n }\n return false;\n }\n}", + "title": "55. Jump Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput:[[1,6],[8,10],[15,18]]\nExplanation:Since intervals [1,3] and [2,6] overlap, merge them into [1,6].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]\nOutput:[[1,5]]\nExplanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] merge(int[][] intervals) {\n\n Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));\n int index = 0;\n\n for (int i = 1; i < intervals.length; i++) {\n\n if (intervals[index][1] >= intervals[i][0]) {\n intervals[index][1] = Math.max(intervals[index][1], intervals[i][1]);\n } else {\n index++;\n intervals[index] = intervals[i];\n }\n }\n\n return Arrays.copyOfRange(intervals, 0, index + 1);\n }\n}\n", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput:[[1,2],[3,10],[12,16]]\nExplanation:Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n\n List result = new ArrayList<>();\n int i = 0, n = intervals.length;\n\n // Step 1: Add all intervals before newInterval\n while (i < n && intervals[i][1] < newInterval[0]) {\n result.add(intervals[i]);\n i++;\n }\n\n // Step 2: Merge overlapping intervals\n while (i < n && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(newInterval[0], intervals[i][0]);\n newInterval[1] = Math.max(newInterval[1], intervals[i][1]);\n i++;\n }\n result.add(newInterval);\n\n // Step 3: Add remaining intervals\n while (i < n) {\n result.add(intervals[i]);\n i++;\n }\n\n int[][] resultList = new int[result.size()][2];\n for (int j = 0; j < result.size(); j++) {\n resultList[j] = result.get(j);\n }\n \n return resultList;\n }\n}", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"\nOutput:5\nExplanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"\nOutput:4\nExplanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"\nOutput:6\nExplanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLastWord(String s) {\n\n String[] words = s.split(\" \");\n return words[words.length - 1].length();\n\n // int length = 0;\n // boolean count = false;\n\n // for (char c : s.toCharArray()) {\n\n // if (c != ' ') {\n\n // if (!count) {\n\n // count = true;\n // length = 1;\n // } else {\n // length++;\n // }\n // } else {\n // count = false;\n // }\n // }\n // return length;\n\n }\n}", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, rotate the list to the right by k places.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2\nOutput:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4\nOutput:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode rotateRight(ListNode head, int k) {\n\n if (head == null || head.next == null || k == 0)\n return head;\n\n ListNode tail = head;\n int length = 1;\n\n while (tail.next != null) {\n tail = tail.next;\n length++;\n }\n\n k = k % length;\n if (k == 0)\n return head;\n\n ListNode newTail = head;\n for (int i = 0; i < length - k - 1; i++) {\n newTail = newTail.next;\n }\n\n ListNode newHead = newTail.next;\n newTail.next = null;\n tail.next = head;\n\n return newHead;\n }\n}", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7\nOutput:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2\nOutput:3\nExplanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePaths(int m, int n) { // Combinatorics\n long paths = 1;\n\n for (int i = 1; i <= m - 1; i++) { // The total number of unique ways = C(m+n-2, m-1)\n paths = paths * (n - 1 + i) / i;\n }\n\n return (int) paths;\n }\n}", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 .", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:2\nExplanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n int[] dp = new int[obstacleGrid[0].length];\n\n dp[0] = obstacleGrid[0][0] == 0 ? 1 : 0;\n\n for (int[] row : obstacleGrid) {\n for (int col = 0; col < obstacleGrid[0].length; col++) {\n\n if (row[col] == 1)\n dp[col] = 0;\n else if (col > 0)\n dp[col] += dp[col - 1];\n }\n }\n\n return dp[obstacleGrid[0].length - 1];\n }\n}", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 200", + "0 <= grid[i][j] <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,3,1],[1,5,1],[4,2,1]]\nOutput:7\nExplanation:Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6]]\nOutput:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n int[][] dp = new int[m][n];\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n\n if (i == 0 && j == 0)\n dp[i][j] = grid[i][j];\n else {\n int up = i > 0 ? dp[i - 1][j] : Integer.MAX_VALUE;\n int left = j > 0 ? dp[i][j - 1] : Integer.MAX_VALUE;\n dp[i][j] = grid[i][j] + Math.min(up, left);\n }\n }\n }\n\n return dp[m - 1][n - 1];\n }\n}", + "title": "64. Minimum Path Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]\nOutput:[1,2,4]\nExplanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]\nOutput:[4,3,2,2]\nExplanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]\nOutput:[1,0]\nExplanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] plusOne(int[] digits) {\n int n = digits.length;\n\n for (int i = n - 1; i >= 0; i--) {\n\n if (digits[i] < 9) {\n digits[i]++;\n return digits;\n }\n digits[i] = 0;\n }\n\n int[] newDigits = new int[n + 1];\n newDigits[0] = 1;\n return newDigits;\n }\n}", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary strings a and b , return their sum as a binary string .", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"\nOutput:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"\nOutput:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String addBinary(String a, String b) {\n\n StringBuilder result = new StringBuilder();\n int i = a.length() - 1, j = b.length() - 1, carry = 0;\n\n while (i >= 0 || j >= 0 || carry > 0) {\n int sum = carry;\n\n if (i >= 0)\n sum += a.charAt(i--) - '0'; // Convert char to int\n\n if (j >= 0)\n sum += b.charAt(j--) - '0';\n\n result.append(sum % 2);\n carry = sum / 2;\n }\n\n return result.reverse().toString();\n }\n}", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\nOutput:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\nOutput:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]\nExplanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\nOutput:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List fullJustify(String[] words, int maxWidth) {\n List result = new ArrayList<>();\n int i = 0;\n\n while (i < words.length) {\n int j = i, lineLength = 0;\n // Find words that fit into the current line\n while (j < words.length && lineLength + words[j].length() + (j - i) <= maxWidth) {\n lineLength += words[j].length();\n j++;\n }\n\n int numWords = j - i;\n int numSpaces = maxWidth - lineLength;\n StringBuilder line = new StringBuilder();\n\n // If it's the last line or contains only one word -> left-justify\n if (j == words.length || numWords == 1) {\n for (int k = i; k < j; k++) {\n line.append(words[k]);\n if (k < j - 1)\n line.append(\" \"); // Space between words\n }\n // Fill the remaining spaces to match maxWidth\n while (line.length() < maxWidth) {\n line.append(\" \");\n }\n }\n // Otherwise, distribute spaces evenly\n else {\n int spacesBetween = numSpaces / (numWords - 1);\n int extraSpaces = numSpaces % (numWords - 1);\n\n for (int k = i; k < j; k++) {\n line.append(words[k]);\n if (k < j - 1) {\n int spaces = spacesBetween + (extraSpaces > 0 ? 1 : 0);\n extraSpaces--;\n for (int s = 0; s < spaces; s++) {\n line.append(\" \");\n }\n }\n }\n }\n\n result.add(line.toString());\n i = j; // Move to the next group of words\n }\n\n return result;\n }\n}\n", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-negative integer x , return the square root of x rounded down to the nearest integer . The returned integer should be non-negative as well. You must not use any built-in exponent function or operator.", + "description_images": [], + "constraints": [ + "For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python." + ], + "examples": [ + { + "text": "Example 1: Input:x = 4\nOutput:2\nExplanation:The square root of 4 is 2, so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 8\nOutput:2\nExplanation:The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mySqrt(int x) {\n if (x < 2)\n return x;\n\n long num;\n int mid, low = 2, high = x / 2;\n\n while (low <= high) {\n mid = low + high >>> 1;\n num = (long) mid * mid;\n\n if (num > x) {\n high = mid - 1;\n } else if (num < x) {\n low = mid + 1;\n } else {\n return mid;\n }\n }\n\n return high;\n }\n}", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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?", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:2\nExplanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3\nOutput:3\nExplanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int climbStairs(int n) {\n if(n == 1) return 1;\n int prev2 = 1, prev1 = 2;\n\n for(int i = 3; i <= n; i++) {\n int cur = prev1 + prev2;\n prev2 = prev1;\n prev1 = cur;\n }\n\n return prev1;\n }\n}", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an absolute path for a Unix-style file system, which always begins with a slash '/' . Your task is to transform this absolute path into its simplified canonical path . The rules of a Unix-style file system are as follows: The simplified canonical path should follow these rules : Return the simplified canonical path .", + "description_images": [], + "constraints": [ + "A single period '.' represents the current directory.", + "A double period '..' represents the previous/parent directory.", + "Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/' .", + "Any sequence of periods that does not match the rules above should be treated as a valid directory or file name . For example, '...' and '....' are valid directory or file names." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public String simplifyPath(String path) {\n\n Stack stack = new Stack<>();\n String[] split = path.split(\"/\");\n\n for (String dir : split) {\n\n if (dir.equals(\"..\")) {\n\n if (!stack.isEmpty())\n stack.pop();\n\n } else if (!dir.isEmpty() && !dir.equals(\".\")) {\n stack.push(dir);\n }\n }\n\n return \"/\" + String.join(\"/\", stack);\n }\n}", + "title": "71. Simplify Path", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "Insert a character", + "Delete a character", + "Replace a character" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"horse\", word2 = \"ros\"\nOutput:3\nExplanation:horse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"\nOutput:5\nExplanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDistance(String word1, String word2) {\n int m = word1.length(), n = word2.length();\n Integer[][] memo = new Integer[m + 1][n + 1];\n \n return dp(word1, word2, m, n, memo);\n }\n\n private int dp(String word1, String word2, int i, int j, Integer[][] memo) {\n if (i == 0)\n return j;\n if (j == 0)\n return i;\n\n if (memo[i][j] != null)\n return memo[i][j];\n\n if (word1.charAt(i - 1) == word2.charAt(j - 1)) {\n memo[i][j] = dp(word1, word2, i - 1, j - 1, memo);\n\n } else {\n int insert = dp(word1, word2, i, j - 1, memo);\n int delete = dp(word1, word2, i - 1, j, memo);\n int replace = dp(word1, word2, i - 1, j - 1, memo);\n\n memo[i][j] = 1 + Math.min(insert, Math.min(delete, replace));\n }\n\n return memo[i][j];\n }\n}", + "title": "72. Edit Distance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void setZeroes(int[][] matrix) {\n\n int m = matrix.length, n = matrix[0].length;\n boolean firstRowZero = false, firstColZero = false;\n\n // Step 1: Check if first row/column should be zero\n for (int i = 0; i < m; i++) {\n if (matrix[i][0] == 0) {\n firstColZero = true;\n break;\n }\n }\n \n for (int j = 0; j < n; j++) {\n if (matrix[0][j] == 0) {\n firstRowZero = true;\n break;\n }\n }\n\n // Step 2: Mark zeroes using first row/column\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Step 3: Set zeroes using first row/column markers\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Step 4: Handle first row & column separately\n if (firstColZero) {\n for (int i = 0; i < m; i++) {\n matrix[i][0] = 0;\n }\n }\n\n if (firstRowZero) {\n for (int j = 0; j < n; j++) {\n matrix[0][j] = 0;\n }\n }\n\n }\n}", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix matrix with the following two properties: 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.", + "description_images": [], + "constraints": [ + "Each row is sorted in non-decreasing order.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return false;\n\n int rows = matrix.length, cols = matrix[0].length;\n int low = 0, high = rows * cols - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1; // Prevents overflow\n int midValue = matrix[mid / cols][mid % cols]; // Convert 1D index to 2D\n\n if (midValue == target)\n return true;\n else if (midValue < target)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return false;\n }\n}", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]\nOutput:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]\nOutput:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void sortColors(int[] nums) {\n int[] count = new int[3];\n\n for (int num : nums) {\n count[num]++;\n }\n\n int index = 0;\n for (int i = 0; i <= 2; i++) {\n\n while (count[i]-- > 0) {\n nums[index++] = i;\n }\n }\n }\n}", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"\nOutput:\"BANC\"\nExplanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"\nOutput:\"a\"\nExplanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"\nOutput:\"\"\nExplanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String minWindow(String s, String t) {\n // checking base cases\n if (s == null || t == null || s.length() == 0 || t.length() == 0 || s.length() < t.length()) {\n return \"\";\n }\n\n int[] map = new int[128];\n int count = t.length();\n int start = 0, minLen = Integer.MAX_VALUE, startIndex = 0;\n\n for (char ch : t.toCharArray()) { // creating a int map to store char frequency\n map[ch]++;\n }\n\n for (int end = 0; end < s.length(); end++) {\n // If character at `end` exists in `t`, decrement the count\n if (map[s.charAt(end)]-- > 0) {\n count--;\n }\n\n while (count == 0) {\n // Update minimum window size and starting index\n if (end - start + 1 < minLen) {\n startIndex = start;\n minLen = end - start + 1;\n }\n\n // Try to shrink the window from the left\n if (map[s.charAt(start)]++ == 0) {\n count++;\n }\n start++;\n }\n }\n\n return minLen == Integer.MAX_VALUE ? \"\" : s.substring(startIndex, startIndex + minLen);\n }\n}", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2\nOutput:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1\nOutput:[[1]]\nExplanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combine(int n, int k) {\n List> result = new ArrayList<>();\n backtrack(1, new ArrayList<>(), n, k, result);\n return result;\n }\n\n private void backtrack(int start, List path, int n, int k, List> result) {\n if (path.size() == k) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i <= n; i++) {\n path.add(i);\n backtrack(i + 1, path, n, k, result);\n path.removeLast();\n }\n }\n}", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]\nOutput:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n List subset = new ArrayList<>();\n\n createSubset(nums, 0, result, subset);\n return result;\n }\n\n private void createSubset(int[] nums, int index, List> result, List subset) {\n if (index == nums.length) {\n result.add(new ArrayList<>(subset));\n return;\n }\n\n subset.add(nums[index]);\n createSubset(nums, index + 1, result, subset);\n\n subset.remove(subset.removeLast());\n createSubset(nums, index + 1, result, subset);\n }\n}", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word2.jpg" + }, + { + "text": "Example 2: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg" + }, + { + "text": "Example 3: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/15/word3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length, n = board[0].length;\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (dfs(board, i, j, word, 0)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n private boolean dfs(char[][] board, int i, int j, String word, int index) {\n\n if (index == word.length()) {\n return true; // Word found\n }\n\n if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index)) {\n return false;\n }\n\n char temp = board[i][j];\n board[i][j] = '#'; // Mark visited\n\n boolean found = dfs(board, i + 1, j, word, index + 1) || // Down\n dfs(board, i - 1, j, word, index + 1) || // Up\n dfs(board, i, j + 1, word, index + 1) || // Right\n dfs(board, i, j - 1, word, index + 1); // Left\n\n board[i][j] = temp; // Backtrack\n return found;\n }\n}", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove some duplicates in-place such that each unique element appears at most twice . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3]\nOutput:5, nums = [1,1,2,2,3,_]\nExplanation:Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,1,2,3,3]\nOutput:7, nums = [0,0,1,1,2,3,3,_,_]\nExplanation:Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeDuplicates(int[] nums) {\n\n int k = 1;\n\n for (int i = 1; i < nums.length; i++) {\n\n if (k == 1 || nums[i] != nums[k - 2]) {\n nums[k] = nums[i];\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "80. Remove Duplicates from Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]\nOutput:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]\nOutput:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n\n if (head == null)\n return null;\n\n ListNode dummy = new ListNode(0, head);\n ListNode prev = dummy;\n ListNode current = head;\n\n while (current != null) {\n boolean isDuplicate = false;\n\n while (current.next != null && current.val == current.next.val) {\n isDuplicate = true;\n current = current.next;\n }\n\n if (isDuplicate) {\n prev.next = current.next;\n } else {\n prev = prev.next;\n }\n\n current = current.next;\n }\n\n return dummy.next;\n }\n}", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once . Return the linked list sorted as well .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,1,2]\nOutput:[1,2]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/list1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,2,3,3]\nOutput:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/list2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n\n ListNode current = head;\n\n while (current != null && current.next != null) {\n\n if (current.val == current.next.val) {\n current.next = current.next.next;\n } else {\n current = current.next;\n }\n }\n\n return head;\n }\n}", + "title": "83. Remove Duplicates from Sorted List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 10^5", + "0 <= heights[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [2,1,5,6,2,3]\nOutput:10\nExplanation:The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.", + "image": "https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg" + }, + { + "text": "Example 2: Input:heights = [2,4]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestRectangleArea(int[] heights) {\n int n = heights.length;\n int[] newHeights = new int[n + 2];\n System.arraycopy(heights, 0, newHeights, 1, n);\n\n Stack stack = new Stack<>();\n int maxArea = 0;\n\n for (int i = 0; i < newHeights.length; i++) {\n\n while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {\n int height = newHeights[stack.pop()];\n int width = i - stack.peek() - 1;\n maxArea = Math.max(maxArea, height * width);\n }\n stack.push(i);\n }\n\n return maxArea;\n }\n}", + "title": "84. Largest Rectangle in Histogram", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3\nOutput:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2\nOutput:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode partition(ListNode head, int x) {\n\n if (head == null || head.next == null)\n return head;\n\n ListNode lessHead = new ListNode(0);\n ListNode greaterHead = new ListNode(0);\n\n ListNode less = lessHead;\n ListNode greater = greaterHead;\n ListNode current = head;\n\n while (current != null) {\n\n if (current.val < x) {\n less.next = current;\n less = less.next;\n } else {\n greater.next = current;\n greater = greater.next;\n }\n\n current = current.next;\n }\n\n greater.next = null;\n less.next = greaterHead.next;\n\n return lessHead.next;\n }\n}", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n .", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput:[1,2,2,3,5,6]\nExplanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0\nOutput:[1]\nExplanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput:[1]\nExplanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // using two-pointer approch\n\n int p1 = m - 1; // Last valid element in nums1\n int p2 = n - 1; // Last element in nums2\n int p = m + n - 1; // Last position in nums1\n\n while (p1 >= 0 && p2 >= 0) {\n\n if (nums1[p1] > nums2[p2]) {\n nums1[p] = nums1[p1];\n p1--;\n\n } else {\n nums1[p] = nums2[p2];\n p2--;\n }\n p--;\n }\n\n // copying remaining to nums1\n while (p2 >= 0) {\n nums1[p] = nums2[p2];\n p2--;\n p--;\n }\n }\n}", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list and two integers left and right where left <= right , reverse the nodes of the list from position left to position right , and return the reversed list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 500", + "-500 <= Node.val <= 500", + "1 <= left <= right <= n" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], left = 2, right = 4\nOutput:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg" + }, + { + "text": "Example 2: Input:head = [5], left = 1, right = 1\nOutput:[5]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if (head == null || left == right)\n return head;\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prev = dummy;\n\n // Move `prev` to just before `left`\n for (int i = 1; i < left; i++) {\n prev = prev.next;\n }\n\n // Reverse sublist from `left` to `right`\n ListNode curr = prev.next;\n ListNode next = null;\n ListNode prevSublist = null;\n\n for (int i = left; i <= right; i++) {\n next = curr.next;\n curr.next = prevSublist;\n prevSublist = curr;\n curr = next;\n }\n\n prev.next.next = curr; // Connect end of reversed list to remaining list\n prev.next = prevSublist; // Connect start of reversed list to prev node\n\n return dummy.next;\n }\n}", + "title": "92. Reverse Linked List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values .", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List inorderTraversal(TreeNode root) {\n List list = new ArrayList<>();\n inorder(root, list);\n return list;\n }\n\n private void inorder(TreeNode root, List list) {\n if (root == null)\n return;\n\n inorder(root.left, list);\n list.add(root.val);\n inorder(root.right, list);\n }\n}", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Note: a + b is the concatenation of strings a and b .", + "description_images": [], + "constraints": [ + "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 + ..." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"\nOutput:true\nExplanation:One way to obtain s3 is:\nSplit s1 into s1 = \"aa\" + \"bc\" + \"c\", and s2 into s2 = \"dbbc\" + \"a\".\nInterleaving the two splits, we get \"aa\" + \"dbbc\" + \"bc\" + \"a\" + \"c\" = \"aadbbcbcac\".\nSince s3 can be obtained by interleaving s1 and s2, we return true.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg" + }, + { + "text": "Example 2: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"\nOutput:false\nExplanation:Notice how it is impossible to interleave s2 with any other string to obtain s3.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"\", s2 = \"\", s3 = \"\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n\n if (s1.length() + s2.length() != s3.length())\n return false;\n Boolean[][] memo = new Boolean[s1.length() + 1][s2.length() + 1];\n return dfs(0, 0, s1, s2, s3, memo);\n }\n\n private boolean dfs(int i, int j, String s1, String s2, String s3, Boolean[][] memo) {\n if (i == s1.length() && j == s2.length())\n return true;\n if (memo[i][j] != null)\n return memo[i][j];\n\n int k = i + j;\n\n if (i < s1.length() && s1.charAt(i) == s3.charAt(k)) {\n if (dfs(i + 1, j, s1, s2, s3, memo)) {\n return memo[i][j] = true;\n }\n }\n\n if (j < s2.length() && s2.charAt(j) == s3.charAt(k)) {\n if (dfs(i, j + 1, s1, s2, s3, memo)) {\n return memo[i][j] = true;\n }\n }\n\n return memo[i][j] = false;\n }\n}", + "title": "97. Interleaving String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]\nOutput:false\nExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return validate(root, null, null);\n }\n\n private boolean validate(TreeNode node, Integer min, Integer max) {\n if (node == null)\n return true;\n\n if ((min != null && node.val <= min) || (max != null && node.val >= max))\n return false;\n\n return validate(node.left, min, node.val) && validate(node.right, node.val, max);\n }\n}", + "title": "98. Validate Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n\n if (p == null && q == null)\n return true;\n if (p == null || q == null)\n return false;\n if (p.val != q.val)\n return false;\n\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isSymmetric(TreeNode root) {\n\n if (root == null)\n return true;\n\n return isMirror(root.left, root.right);\n }\n\n private boolean isMirror(TreeNode t1, TreeNode t2) {\n\n if (t1 == null && t2 == null)\n return true;\n if (t1 == null || t2 == null)\n return false;\n if (t1.val != t2.val)\n return false;\n\n return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);\n }\n}", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> levelOrder(TreeNode root) {\n List> result = new ArrayList<>();\n Queue queue = new LinkedList<>();\n\n if(root == null) return result;\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n int level = queue.size();\n List levelNodes = new ArrayList<>();\n\n for (int i = 0; i < level; i++) {\n TreeNode node = queue.poll();\n levelNodes.add(node.val);\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(levelNodes);\n }\n\n return result;\n }\n}", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values . (i.e., from left to right, then right to left for the next level and alternate between).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[[3],[20,9],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]\nOutput:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> zigzagLevelOrder(TreeNode root) {\n\n List> result = new ArrayList<>();\n if (root == null)\n return result;\n\n Queue queue = new LinkedList<>();\n queue.offer(root);\n boolean leftToRight = true;\n\n while (!queue.isEmpty()) {\n int levelSize = queue.size();\n Deque levelNodes = new LinkedList<>();\n\n for (int i = 0; i < levelSize; i++) {\n TreeNode node = queue.poll();\n\n if (leftToRight) {\n levelNodes.addLast(node.val);\n } else {\n levelNodes.addFirst(node.val);\n }\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(new ArrayList<>(levelNodes));\n leftToRight = !leftToRight;\n }\n\n return result;\n }\n}", + "title": "103. Binary Tree Zigzag Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxDepth(TreeNode root) {\n \n if (root == null) {\n return 0;\n }\n return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));\n }\n}", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n int preIndex = 0;\n HashMap inMap;\n\n public TreeNode buildTree(int[] preorder, int[] inorder) {\n inMap = new HashMap<>();\n\n for (int i = 0; i < inorder.length; i++) {\n inMap.put(inorder[i], i); // (key,value) -> (array value, index)\n }\n\n return build(preorder, 0, inorder.length - 1);\n }\n\n private TreeNode build(int[] preorder, int left, int right) {\n if (left > right)\n return null;\n\n int rootValue = preorder[preIndex++];\n int inIndex = inMap.get(rootValue);\n TreeNode root = new TreeNode(rootValue);\n\n root.left = build(preorder, left, inIndex - 1);\n root.right = build(preorder, inIndex + 1, right);\n\n return root;\n }\n}", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree .", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]\nOutput:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n private static int postIndex;\n private static HashMap inorderMap;\n\n public static TreeNode buildTree(int[] inorder, int[] postorder) {\n inorderMap = new HashMap<>();\n postIndex = postorder.length - 1;\n\n for (int i = 0; i < inorder.length; i++) {\n inorderMap.put(inorder[i], i);\n }\n return build(postorder, 0, inorder.length - 1);\n }\n\n private static TreeNode build(int[] postorder, int left, int right) {\n if (left > right)\n return null;\n\n int rootValue = postorder[postIndex--];\n TreeNode root = new TreeNode(rootValue);\n int inorderIndex = inorderMap.get(rootValue);\n\n root.right = build(postorder, inorderIndex + 1, right);\n root.left = build(postorder, left, inorderIndex - 1);\n\n return root;\n }\n}", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]\nOutput:[0,-3,9,-10,null,5]\nExplanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]\nOutput:[3,1]\nExplanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode sortedArrayToBST(int[] nums) {\n return constructBST(nums, 0, nums.length - 1);\n }\n\n private TreeNode constructBST(int[] nums, int left, int right) {\n if (left > right)\n return null;\n\n int mid = left + (right - left) / 2;\n TreeNode root = new TreeNode(nums[mid]);\n\n root.left = constructBST(nums, left, mid - 1);\n root.right = constructBST(nums, mid + 1, right);\n\n return root;\n }\n}", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree, determine if it is height-balanced .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isBalanced(TreeNode root) {\n return findH(root) == -1 ? false : true;\n }\n\n public int findH(TreeNode root) {\n if (root == null)\n return 0;\n int left = findH(root.left);\n if (left == -1)\n return -1;\n int right = findH(root.right);\n if (right == -1)\n return -1;\n if (Math.abs(left - right) > 1)\n return -1;\n return 1 + Math.max(left, right);\n }\n}", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]\nOutput:5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int minDepth(TreeNode root) {\n if (root == null)\n return 0;\n\n if (root.left == null)\n return minDepth(root.right) + 1;\n\n if (root.right == null)\n return minDepth(root.left) + 1;\n\n return Math.min(minDepth(root.left), minDepth(root.right)) + 1;\n }\n}", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput:true\nExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5\nOutput:false\nExplanation:There are two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0\nOutput:false\nExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n\n if (root == null)\n return false;\n\n if (root.left == null && root.right == null) {\n return targetSum == root.val;\n }\n\n return hasPathSum(root.left, targetSum - root.val) ||\n hasPathSum(root.right, targetSum - root.val);\n }\n}", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\":", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]\nOutput:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public void flatten(TreeNode root) {\n\n while (root != null) {\n\n if (root.left != null) {\n TreeNode rightmost = root.left;\n\n while (rightmost.right != null) {\n rightmost = rightmost.right;\n }\n\n rightmost.right = root.right;\n root.right = root.left;\n root.left = null;\n }\n\n root = root.right;\n }\n }\n}", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]\nOutput:[1,#,2,3,#,4,5,7,#]\nExplanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public Node left;\n public Node right;\n public Node next;\n\n public Node() {}\n \n public Node(int _val) {\n val = _val;\n }\n\n public Node(int _val, Node _left, Node _right, Node _next) {\n val = _val;\n left = _left;\n right = _right;\n next = _next;\n }\n};\n*/\n\nclass Solution {\n public Node connect(Node root) { // LinkedList Implementation to achieve Space Complexity O(1)\n\n Node dummy = new Node(0);\n Node prev = dummy;\n Node curr = root;\n\n while (curr != null) {\n\n if (curr.left != null) {\n prev.next = curr.left;\n prev = prev.next;\n }\n\n if (curr.right != null) {\n prev.next = curr.right;\n prev = prev.next;\n }\n\n curr = curr.next;\n if (curr == null) {\n curr = dummy.next;\n dummy.next = null;\n prev = dummy;\n }\n }\n\n return root;\n }\n}", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5\nOutput:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1\nOutput:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> generate(int numRows) {\n List> result = new ArrayList<>();\n if (numRows == 0) {\n return result;\n }\n\n if (numRows == 1) {\n List firstRow = new ArrayList<>();\n firstRow.add(1);\n result.add(firstRow);\n return result;\n }\n\n result = generate(numRows - 1);\n List prevRow = result.get(numRows - 2);\n List currentRow = new ArrayList<>();\n currentRow.add(1);\n\n for (int i = 1; i < numRows - 1; i++) {\n currentRow.add(prevRow.get(i - 1) + prevRow.get(i));\n }\n\n currentRow.add(1);\n result.add(currentRow);\n\n return result;\n }\n}", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3\nOutput:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0\nOutput:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1\nOutput:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List getRow(int rowIndex) {\n List row = new ArrayList<>();\n long value = 1;\n row.add(1);\n\n for (int k = 1; k <= rowIndex; k++) {\n value = value * (rowIndex - k + 1) / k;\n row.add((int) value);\n }\n\n return row;\n }\n}", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a triangle array, return the minimum path sum from top to bottom . For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.", + "description_images": [], + "constraints": [ + "1 <= triangle.length <= 200", + "triangle[0].length == 1", + "triangle[i].length == triangle[i - 1].length + 1", + "-10^4 <= triangle[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput:11\nExplanation:The triangle looks like:234\n 657\n418 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).", + "image": null + }, + { + "text": "Example 2: Input:triangle = [[-10]]\nOutput:-10", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumTotal(List> triangle) {\n int n = triangle.size();\n int[] dp = new int[n];\n\n for (int i = 0; i < n; i++) {\n dp[i] = triangle.get(n - 1).get(i);\n }\n\n for (int row = n - 2; row >= 0; row--) {\n for (int col = 0; col <= row; col++) {\n dp[col] = triangle.get(row).get(col) + Math.min(dp[col], dp[col + 1]);\n }\n }\n\n return dp[0];\n }\n}", + "title": "120. Triangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:5\nExplanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// class Solution { // solution - 1 : Kadane's Algorithm -> takes 2ms time\n// public int maxProfit(int[] prices) {\n\n// int buy = prices[0], maxProfit = 0;\n\n// for (int i = 1; i < prices.length; i++) {\n\n// if (prices[i] < buy) { // lower price to buy\n// buy = prices[i]; // update min price to buy\n// } else if (prices[i] - buy > maxProfit) {\n// maxProfit = prices[i] - buy; // profit = selling price - buying price\n// }\n// }\n\n// return maxProfit;\n// }\n// }\n\nclass Solution { // solution - 1 : DP -> takes 0ms time\n public int maxProfit(int[] prices) {\n \n int minPrice = Integer.MAX_VALUE;\n int maxProfit = 0;\n \n for (int currentPrice : prices) {\n minPrice = Math.min(currentPrice, minPrice);\n maxProfit = Math.max(maxProfit, currentPrice - minPrice);\n }\n \n return maxProfit;\n }\n}", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve .", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]\nOutput:7\nExplanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n\n // using simple array iteration\n int profit = 0;\n for (int i = 1; i < prices.length; i++) {\n\n if (prices[i] > prices[i - 1]) {\n profit += prices[i] - prices[i - 1];\n }\n }\n\n return profit;\n }\n}", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]\nOutput:6\nExplanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]\nOutput:4\nExplanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]\nOutput:0\nExplanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n int buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE;\n int sell1 = 0, sell2 = 0;\n\n for (int price : prices) {\n buy1 = Math.max(buy1, -price);\n sell1 = Math.max(sell1, buy1 + price);\n buy2 = Math.max(buy2, sell1 - price);\n sell2 = Math.max(sell2, buy2 + price);\n }\n\n return sell2;\n }\n}", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:6\nExplanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]\nOutput:42\nExplanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxSum = Integer.MIN_VALUE;\n\n public int maxPathSum(TreeNode root) {\n dfs(root);\n return maxSum;\n }\n\n private int dfs(TreeNode node) {\n if (node == null)\n return 0;\n\n int left = Math.max(0, dfs(node.left));\n int right = Math.max(0, dfs(node.right));\n maxSum = Math.max(maxSum, left + right + node.val);\n\n return Math.max(left, right) + node.val;\n }\n}", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s consists only of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"A man, a plan, a canal: Panama\"\nOutput:true\nExplanation:\"amanaplanacanalpanama\" is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"race a car\"\nOutput:false\nExplanation:\"raceacar\" is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \" \"\nOutput:true\nExplanation:s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(String s) { // two pinter approach\n\n s = s.toLowerCase().replaceAll(\"[^a-z0-9]\", \"\");\n int start = 0, end = s.length() - 1;\n\n while (start < end) {\n\n if (s.charAt(start) != s.charAt(end)) {\n return false;\n }\n start++;\n end--;\n }\n return true;\n }\n}", + "title": "125. Valid Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: 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.", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput:5\nExplanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput:0\nExplanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int ladderLength(String beginWord, String endWord, List wordList) {\n Set wordSet = new HashSet<>(wordList);\n\n if (!wordSet.contains(endWord))\n return 0;\n\n Queue queue = new LinkedList<>();\n queue.offer(beginWord);\n int level = 1;\n\n Set visited = new HashSet<>();\n visited.add(beginWord);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n String currentWord = queue.poll();\n char[] wordArray = currentWord.toCharArray();\n\n for (int j = 0; j < wordArray.length; j++) {\n char originalChar = wordArray[j];\n\n // Try all letters from 'a' to 'z'\n for (char c = 'a'; c <= 'z'; c++) {\n wordArray[j] = c;\n String newWord = new String(wordArray);\n\n // If newWord is in the other set, we have found a path\n if (newWord.equals(endWord)) {\n return level + 1;\n }\n\n // If newWord exists in wordSet and hasn't been visited\n if (wordSet.contains(newWord) && !visited.contains(newWord)) {\n queue.offer(newWord);\n visited.add(newWord);\n }\n }\n\n wordArray[j] = originalChar; // Restore the original character\n }\n }\n level++;\n }\n\n return 0;\n }\n}", + "title": "127. Word Ladder", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]\nOutput:4\nExplanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]\nOutput:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestConsecutive(int[] nums) {\n if (nums.length == 0)\n return 0;\n\n HashSet set = new HashSet<>();\n for (int n : nums) {\n set.add(n);\n }\n\n int longestSeq = 0;\n for (int num : set) {\n\n if (!set.contains(num - 1)) {\n int currentNum = num;\n int currentSeq = 1;\n\n while (set.contains(currentNum + 1)) {\n currentNum++;\n currentSeq++;\n }\n\n longestSeq = Math.max(longestSeq, currentSeq);\n }\n }\n\n return longestSeq;\n }\n}", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]\nOutput:25\nExplanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]\nOutput:1026\nExplanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int sumNumbers(TreeNode root) {\n return dfs(root, 0);\n }\n\n private int dfs(TreeNode node, int currentSum) {\n if (node == null)\n return 0;\n\n currentSum = currentSum * 10 + node.val;\n\n // If it's a leaf node, return the accumulated sum\n if (node.left == null && node.right == null) {\n return currentSum;\n }\n\n // Recursively sum left and right subtrees\n return dfs(node.left, currentSum) + dfs(node.right, currentSum);\n }\n}", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix board containing letters 'X' and 'O' , capture regions that are surrounded : 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.", + "description_images": [], + "constraints": [ + "Connect : A cell is connected to adjacent cells horizontally or vertically.", + "Region : To form a region connect every 'O' cell.", + "Surround : The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public void solve(char[][] board) {\n if (board == null || board.length == 0)\n return;\n\n int rows = board.length, cols = board[0].length;\n Queue queue = new LinkedList<>();\n\n // Step 1: Capture all border 'O's into the queue\n for (int i = 0; i < rows; i++) {\n\n if (board[i][0] == 'O')\n queue.offer(new int[] { i, 0 });\n\n if (board[i][cols - 1] == 'O')\n queue.offer(new int[] { i, cols - 1 });\n }\n\n for (int j = 0; j < cols; j++) {\n\n if (board[0][j] == 'O')\n queue.offer(new int[] { 0, j });\n\n if (board[rows - 1][j] == 'O')\n queue.offer(new int[] { rows - 1, j });\n }\n\n // Step 2: BFS to mark connected 'O's as safe ('#')\n int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int r = cell[0], c = cell[1];\n\n if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != 'O')\n continue;\n\n board[r][c] = '#';\n\n for (int[] dir : directions) {\n queue.offer(new int[] { r + dir[0], c + dir[1] });\n }\n }\n\n // Step 3: Flip surrounded 'O' to 'X' and restore '#' to 'O'\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n\n if (board[i][j] == 'O')\n board[i][j] = 'X'; // Flip surrounded\n\n if (board[i][j] == '#')\n board[i][j] = 'O'; // Restore safe regions\n }\n }\n }\n\n}", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome . Return all possible palindrome partitioning of s .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"\nOutput:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> partition(String s) {\n return dfs(s, 0, new HashMap<>());\n }\n\n private List> dfs(String s, int start, Map>> memo) {\n if (memo.containsKey(start)) {\n return memo.get(start);\n }\n\n List> result = new ArrayList<>();\n if (start == s.length()) {\n result.add(new ArrayList<>());\n }\n\n for (int end = start; end < s.length(); end++) {\n\n if (isPalindrome(s, start, end)) {\n String prefix = s.substring(start, end + 1);\n\n for (List sub : dfs(s, end + 1, memo)) {\n List newList = new ArrayList<>();\n newList.add(prefix);\n newList.addAll(sub);\n result.add(newList);\n }\n }\n }\n\n memo.put(start, result);\n return result;\n }\n\n private boolean isPalindrome(String s, int l, int r) {\n while (l < r) {\n if (s.charAt(l++) != s.charAt(r--))\n return false;\n }\n return true;\n }\n}", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput:[[2,4],[1,3],[2,4],[1,3]]\nExplanation:There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: Input:adjList = [[]]\nOutput:[[]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []\nOutput:[]\nExplanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public Node cloneGraph(Node node) {\n if (node == null)\n return null;\n\n Map clonedNodes = new HashMap<>();\n\n return dfs(node, clonedNodes);\n }\n\n private Node dfs(Node node, Map clonedNodes) {\n\n if (clonedNodes.containsKey(node))\n return clonedNodes.get(node);\n\n Node clone = new Node(node.val);\n clonedNodes.put(node, clone);\n\n for (Node neighbor : node.neighbors) {\n clone.neighbors.add(dfs(neighbor, clonedNodes));\n }\n\n return clone;\n }\n}", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "n == gas.length == cost.length", + "1 <= n <= 10^5", + "0 <= gas[i], cost[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput:3\nExplanation:Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.", + "image": null + }, + { + "text": "Example 2: Input:gas = [2,3,4], cost = [3,4,3]\nOutput:-1\nExplanation:You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int canCompleteCircuit(int[] gas, int[] cost) { // using gready approach\n\n int totalGas = 0, totalCost = 0;\n int total = 0, start = 0;\n int n = gas.length;\n\n for (int i = 0; i < n; i++) {\n totalGas += gas[i];\n totalCost += cost[i];\n }\n\n if (totalGas < totalCost) {\n return -1;\n }\n\n for (int i = 0; i < n; i++) {\n total += gas[i] - cost[i];\n\n if (total < 0) {\n total = 0;\n start = i + 1;\n }\n }\n\n return start;\n }\n}", + "title": "134. Gas Station", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings . You are giving candies to these children subjected to the following requirements: Return the minimum number of candies you need to have to distribute the candies to the children .", + "description_images": [], + "constraints": [ + "Each child must have at least one candy.", + "Children with a higher rating get more candies than their neighbors." + ], + "examples": [ + { + "text": "Example 1: Input:ratings = [1,0,2]\nOutput:5\nExplanation:You can allocate to the first, second and third child with 2, 1, 2 candies respectively.", + "image": null + }, + { + "text": "Example 2: Input:ratings = [1,2,2]\nOutput:4\nExplanation:You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int candy(int[] ratings) { // using gready approach\n\n int n = ratings.length;\n int[] candies = new int[n];\n Arrays.fill(candies, 1);\n int total = 0;\n\n for (int i = 1; i < n; i++) {\n if (ratings[i] > ratings[i - 1]) {\n candies[i] = candies[i - 1] + 1;\n }\n }\n\n for (int i = n - 2; i >= 0; i--) {\n if (ratings[i] > ratings[i + 1]) {\n candies[i] = candies[i + 1] + 1 > candies[i] ? candies[i + 1] + 1 : candies[i];\n }\n }\n\n for (int candy : candies) {\n total += candy;\n }\n\n return total;\n }\n}", + "title": "135. Candy", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int singleNumber(int[] nums) {\n int result = 0;\n\n for (int num : nums) {\n result ^= num;\n }\n\n return result;\n }\n}", + "title": "136. Single Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums where every element appears three times except for one, which appears exactly once . Find the single element and return it . You must implement a solution with a linear runtime complexity and use only constant extra space.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "Each element in nums appears exactly three times except for one element which appears once ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,2]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,1,0,1,99]\nOutput:99", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int singleNumber(int[] nums) {\n int ones = 0, twos = 0;\n\n for (int num : nums) {\n ones = (ones ^ num) & ~twos; // Add new number or remove it if seen twice\n twos = (twos ^ num) & ~ones; // Track numbers that appear twice\n }\n\n return ones;\n }\n}", + "title": "137. Single Number II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Your code will only be given the head of the original linked list.", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]\nOutput:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]\nOutput:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n int val;\n Node next;\n Node random;\n\n public Node(int val) {\n this.val = val;\n this.next = null;\n this.random = null;\n }\n}\n*/\n\nclass Solution {\n public Node copyRandomList(Node head) {\n\n if (head == null)\n return null;\n\n Node current = head;\n while (current != null) {\n Node copy = new Node(current.val);\n copy.next = current.next;\n current.next = copy;\n current = copy.next;\n }\n\n current = head;\n while (current != null) {\n if (current.random != null) {\n current.next.random = current.random.next;\n }\n current = current.next.next;\n }\n\n Node dummyHead = new Node(0);\n Node copyCurrent = dummyHead;\n current = head;\n\n while (current != null) {\n copyCurrent.next = current.next;\n copyCurrent = copyCurrent.next;\n current.next = current.next.next;\n current = current.next;\n }\n\n return dummyHead.next;\n }\n}", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", wordDict = [\"leet\",\"code\"]\nOutput:true\nExplanation:Return true because \"leetcode\" can be segmented as \"leet code\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]\nOutput:true\nExplanation:Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean wordBreak(String s, List wordDict) {\n Set wordSet = new HashSet<>(wordDict);\n boolean[] dp = new boolean[s.length() + 1];\n dp[0] = true; // for empty \"\" string\n\n for (int i = 1; i <= s.length(); i++) {\n for (int j = 0; j < i; j++) {\n\n if (dp[j] && wordSet.contains(s.substring(j, i))) {\n dp[i] = true;\n break;\n }\n }\n }\n\n return dp[s.length()];\n }\n}", + "title": "139. Word Break", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:true\nExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:false\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public boolean hasCycle(ListNode head) {\n\n if (head == null || head.next == null)\n return false;\n\n ListNode slow = head;\n ListNode fast = head;\n\n while (fast != null && fast.next != null) {\n\n slow = slow.next;\n fast = fast.next.next;\n\n if (slow == fast) {\n return true;\n }\n }\n\n return false;\n }\n}", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1\nOutput:tail connects to node index 1\nExplanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0\nOutput:tail connects to node index 0\nExplanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1\nOutput:no cycle\nExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public ListNode detectCycle(ListNode head) {\n if (head == null || head.next == null)\n return null;\n\n ListNode slow = head;\n ListNode fast = head;\n\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n\n if (fast == slow) {\n ListNode entry = head;\n\n while (entry != slow) {\n entry = entry.next;\n slow = slow.next;\n }\n\n return entry;\n }\n }\n\n return null;\n }\n}", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values .", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List preorderTraversal(TreeNode root) {\n List preorderList = new ArrayList<>();\n helper(root, preorderList);\n return preorderList;\n }\n\n public void helper(TreeNode root, List preorderList) {\n if (root == null)\n return;\n\n preorderList.add(root.val);\n helper(root.left, preorderList);\n helper(root.right, preorderList);\n }\n}", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values .", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List postorderTraversal(TreeNode root) {\n List postorderList = new ArrayList<>();\n helper(root, postorderList);\n return postorderList;\n }\n\n public void helper(TreeNode root, List postorderList) {\n if (root == null)\n return;\n\n helper(root.left, postorderList);\n helper(root.right, postorderList);\n postorderList.add(root.val);\n }\n}", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n\n private class Node {\n int key, value;\n Node prev, next;\n\n Node(int key, int value) {\n this.key = key;\n this.value = value;\n }\n }\n\n private int capacity;\n private Map cache;\n private Node head, tail;\n\n public LRUCache(int capacity) {\n this.capacity = capacity;\n this.cache = new HashMap<>();\n\n head = new Node(0, 0);\n tail = new Node(0, 0);\n head.next = tail;\n tail.prev = head;\n }\n\n public int get(int key) {\n\n if (!cache.containsKey(key)) {\n return -1;\n }\n\n Node node = cache.get(key);\n remove(node);\n insertAtFront(node);\n\n return node.value;\n }\n\n public void put(int key, int value) {\n\n if (cache.containsKey(key)) {\n remove(cache.get(key));\n }\n\n if (cache.size() == capacity) {\n remove(tail.prev);\n }\n\n insertAtFront(new Node(key, value));\n }\n\n private void remove(Node node) {\n cache.remove(node.key);\n node.prev.next = node.next;\n node.next.prev = node.prev;\n }\n\n private void insertAtFront(Node node) {\n cache.put(node.key, node);\n\n node.next = head.next;\n node.prev = head;\n head.next.prev = node;\n head.next = node;\n }\n}\n\n/**\n * Your LRUCache object will be instantiated and called as such:\n * LRUCache obj = new LRUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the list after sorting it in ascending order .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]\nOutput:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]\nOutput:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode sortList(ListNode head) { // Fast & Slow Pointer - Two Pointer Approach\n if (head == null || head.next == null)\n return head;\n\n ListNode mid = findMiddle(head);\n ListNode rightHead = mid.next;\n mid.next = null;\n\n ListNode left = sortList(head);\n ListNode right = sortList(rightHead);\n\n return mergeTwoLists(left, right);\n }\n\n private ListNode findMiddle(ListNode head) {\n ListNode slow = head, fast = head.next;\n\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n return slow;\n }\n\n private ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode current = dummy;\n\n while (l1 != null && l2 != null) {\n\n if (l1.val < l2.val) {\n current.next = l1;\n l1 = l1.next;\n } else {\n current.next = l2;\n l2 = l2.next;\n }\n current = current.next;\n }\n\n if (l1 != null)\n current.next = l1;\n if (l2 != null)\n current.next = l2;\n\n return dummy.next;\n }\n}", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of points where points[i] = [x i , y i ] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 300", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[3,3]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" + }, + { + "text": "Example 2: Input:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxPoints(int[][] points) {\n if (points.length < 2)\n return points.length;\n\n int maxPoints = 1; // Minimum answer is at least 1\n\n for (int i = 0; i < points.length; i++) {\n Map slopeMap = new HashMap<>();\n int duplicate = 0, localMax = 1;\n\n for (int j = i + 1; j < points.length; j++) {\n int dx = points[j][0] - points[i][0];\n int dy = points[j][1] - points[i][1];\n\n // If the points are identical\n if (dx == 0 && dy == 0) {\n duplicate++;\n continue;\n }\n\n // Normalize the slope by reducing (dy/dx) to lowest terms\n int gcd = gcd(dx, dy);\n dx /= gcd;\n dy /= gcd;\n\n // Ensure a consistent representation\n String slope = dx + \"/\" + dy;\n\n slopeMap.put(slope, slopeMap.getOrDefault(slope, 1) + 1);\n localMax = Math.max(localMax, slopeMap.get(slope));\n }\n\n // Add duplicate points to max count\n maxPoints = Math.max(maxPoints, localMax + duplicate);\n }\n\n return maxPoints;\n }\n\n // Compute GCD to normalize slope representation\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}", + "title": "149. Max Points on a Line", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\nOutput:9\nExplanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\nOutput:6\nExplanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\nOutput:22\nExplanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int evalRPN(String[] tokens) {\n\n Stack stack = new Stack<>();\n\n for (String token : tokens) {\n\n if (token.equals(\"+\") || token.equals(\"-\") || token.equals(\"*\") || token.equals(\"/\")) {\n\n int b = stack.pop(); // Second operand\n int a = stack.pop(); // First operand\n\n int result = cal(a, b, token);\n\n stack.push(result);\n } else {\n stack.push(Integer.parseInt(token));\n }\n }\n\n return stack.pop();\n\n }\n\n private int cal(int a, int b, String operator) {\n\n switch (operator) {\n case \"+\":\n return a + b;\n case \"-\":\n return a - b;\n case \"*\":\n return a * b;\n case \"/\":\n return a / b;\n default:\n throw new IllegalArgumentException(\"Invalid operator: \" + operator);\n }\n }\n}", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string s , reverse the order of the words . A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s contains English letters (upper-case and lower-case), digits, and spaces ' ' .", + "There is at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"the sky is blue\"\nOutput:\"blue is sky the\"", + "image": null + }, + { + "text": "Example 2: Input:s = \" hello world \"\nOutput:\"world hello\"\nExplanation:Your reversed string should not contain leading or trailing spaces.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a good example\"\nOutput:\"example good a\"\nExplanation:You need to reduce multiple spaces between two words to a single space in the reversed string.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public String reverseWords(String s) {\n\n String[] arr = s.trim().split(\"\\\\s+\");\n StringBuilder reversed = new StringBuilder();\n\n for (int i = arr.length - 1; i >= 0; i--) {\n\n reversed.append(arr[i]);\n\n if (i != 0) { // Add a space between words, but not after the last word\n reversed.append(\" \");\n }\n }\n\n return reversed.toString();\n }\n}", + "title": "151. Reverse Words in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]\nOutput:6\nExplanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]\nOutput:0\nExplanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProduct(int[] nums) {\n int maxProduct = nums[0];\n int currentMax = nums[0];\n int currentMin = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] < 0) {\n int temp = currentMax;\n currentMax = currentMin;\n currentMin = temp;\n }\n\n currentMax = Math.max(nums[i], currentMax * nums[i]);\n currentMin = Math.min(nums[i], currentMin * nums[i]);\n\n maxProduct = Math.max(maxProduct, currentMax);\n }\n\n return maxProduct;\n }\n}", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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 .", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:1\nExplanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]\nOutput:0\nExplanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]\nOutput:11\nExplanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMin(int[] nums) {\n int left = 0, right = nums.length - 1;\n\n while (left < right) {\n int mid = (left + right) >>> 1;\n\n if (nums[mid] > nums[right]) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n return nums[left];\n }\n}", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: You must implement a solution with O(1) time complexity for each function.", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n[[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2", + "image": null + } + ], + "follow_up": null, + "solution": "class MinStack {\n\n private int min;\n private final Stack stack;\n\n public MinStack() {\n stack = new Stack<>();\n min = Integer.MAX_VALUE; // Initially set min to a large value\n }\n\n public void push(int x) {\n // only push the old minimum value when the current\n // minimum value changes after pushing the new value x\n\n if (x <= min) {\n stack.push(min);\n min = x;\n }\n\n stack.push(x);\n }\n\n public void pop() {\n // if pop operation could result in the changing of the current minimum value,\n // pop twice and change the current minimum value to the last minimum value.\n if (stack.pop() == min)\n min = stack.pop();\n }\n\n public int top() {\n return stack.peek();\n }\n\n public int getMin() {\n return min;\n }\n}\n\n/**\n * Your MinStack object will be instantiated and called as such:\n * MinStack obj = new MinStack();\n * obj.push(val);\n * obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.getMin();\n */", + "title": "155. Min Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted .", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput:Intersected at '8'\nExplanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput:Intersected at '2'\nExplanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput:No intersection\nExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\n\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n if (headA == null || headB == null)\n return null;\n\n ListNode pA = headA, pB = headB;\n\n while (pA != pB) {\n pA = (pA == null) ? headB : pA.next;\n pB = (pB == null) ? headA : pB.next;\n }\n\n return pA;\n }\n}", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:2\nExplanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]\nOutput:5\nExplanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findPeakElement(int[] nums) {\n int low = 0, high = nums.length - 1;\n\n while (low < high) {\n int mid = (low + high) >>> 1;\n\n if (nums[mid] < nums[mid + 1]) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n }\n}", + "title": "162. Find Peak Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 , added 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.", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:numbers = [2,7,11,15], target = 9\nOutput:[1,2]\nExplanation:The sum of 2 and 7 is 9. Therefore, index1= 1, index2= 2. We return [1, 2].", + "image": null + }, + { + "text": "Example 2: Input:numbers = [2,3,4], target = 6\nOutput:[1,3]\nExplanation:The sum of 2 and 4 is 6. Therefore index1= 1, index2= 3. We return [1, 3].", + "image": null + }, + { + "text": "Example 3: Input:numbers = [-1,0], target = -1\nOutput:[1,2]\nExplanation:The sum of -1 and 0 is -1. Therefore index1= 1, index2= 2. We return [1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] twoSum(int[] numbers, int target) { // two pointer approach\n\n int start = 0, end = numbers.length - 1;\n\n while (start < end) {\n int sum = numbers[start] + numbers[end];\n\n if (sum > target) {\n end--; \n } else if (sum < target) {\n start++; \n } else {\n return new int[] { start + 1, end + 1 }; \n }\n }\n\n return new int[] { -1, -1 }; \n }\n}", + "title": "167. Two Sum II - Input Array Is Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1\nOutput:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701\nOutput:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convertToTitle(int columnNumber) {\n StringBuilder res = new StringBuilder();\n\n while (columnNumber > 0) {\n int num = (columnNumber - 1) % 26;\n res.append((char) ('A' + num));\n columnNumber = (columnNumber - 1) / 26;\n }\n\n return res.reverse().toString();\n }\n}", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]\nOutput:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]\nOutput:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int majorityElement(int[] nums) {\n\n // using Moore Voting Algorithm\n int count = 0;\n int candidate = 0;\n\n for (int num : nums) {\n if (count == 0) {\n candidate = num;\n }\n\n if (num == candidate) {\n count++;\n } else {\n count--;\n }\n }\n\n return candidate;\n }\n}", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"\nOutput:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"\nOutput:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int titleToNumber(String columnTitle) {\n int result = 0;\n for (char c : columnTitle.toCharArray()) {\n result = result * 26 + (c - 'A' + 1);\n }\n return result;\n }\n}", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:0\nExplanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:1\nExplanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trailingZeroes(int n) {\n int count = 0;\n\n while (n >= 5) {\n count += n / 5;\n n /= 5;\n }\n\n return count;\n }\n}", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass BSTIterator {\n private final Stack stack;\n\n public BSTIterator(TreeNode root) {\n this.stack = new Stack<>();\n pushLeftNodes(root);\n }\n\n public int next() {\n TreeNode node = this.stack.pop();\n\n pushLeftNodes(node.right);\n return node.val;\n }\n\n public boolean hasNext() {\n return !this.stack.isEmpty();\n }\n\n private void pushLeftNodes(TreeNode node) {\n\n while (node != null) {\n this.stack.push(node);\n node = node.left;\n }\n }\n}\n\n/**\n * Your BSTIterator object will be instantiated and called as such:\n * BSTIterator obj = new BSTIterator(root);\n * int param_1 = obj.next();\n * boolean param_2 = obj.hasNext();\n */", + "title": "173. Binary Search Tree Iterator", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= prices.length <= 1000", + "0 <= prices[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, prices = [2,4,1]\nOutput:2\nExplanation:Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, prices = [3,2,6,5,0,3]\nOutput:7\nExplanation:Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int k, int[] prices) {\n int n = prices.length;\n if (n == 0 || k == 0)\n return 0;\n\n if (k >= n / 2) {\n int maxProfit = 0;\n\n for (int i = 1; i < n; i++) {\n if (prices[i] > prices[i - 1]) {\n maxProfit += prices[i] - prices[i - 1];\n }\n }\n return maxProfit;\n }\n\n int[] prev = new int[n];\n int[] cur = new int[n];\n\n for (int t = 1; t <= k; t++) {\n int maxDiff = -prices[0];\n\n for (int d = 1; d < n; d++) {\n cur[d] = Math.max(cur[d - 1], prices[d] + maxDiff);\n maxDiff = Math.max(maxDiff, prev[d] - prices[d]);\n }\n\n int[] temp = prev;\n prev = cur;\n cur = temp;\n }\n\n return prev[n - 1];\n }\n}", + "title": "188. Best Time to Buy and Sell Stock IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , rotate the array to the right by k steps, where k is non-negative.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7], k = 3\nOutput:[5,6,7,1,2,3,4]\nExplanation:rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-100,3,99], k = 2\nOutput:[3,99,-1,-100]\nExplanation:rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[] nums, int k) {\n\n int len = nums.length;\n k = k % len;\n\n reversed(nums, 0, len - 1); // reverse full array\n reversed(nums, 0, k - 1); // reverse till k-th elements\n reversed(nums, k, len - 1); // reverse las elements\n }\n\n private void reversed(int[] nums, int p1, int p2) {\n\n while (p1 < p2) { // swaping values\n int temp = nums[p1];\n nums[p1] = nums[p2];\n nums[p2] = temp;\n p1++;\n p2--;\n }\n }\n}\n", + "title": "189. Rotate Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Reverse bits of a given 32 bits unsigned integer. Note:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825 ." + ], + "examples": [ + { + "text": "Example 2 Input:n = 00000010100101000001111010011100\nOutput:964176192 (00111001011110000010100101000000)\nExplanation:The input binary string00000010100101000001111010011100represents the unsigned integer 43261596, so return 964176192 which its binary representation is00111001011110000010100101000000.", + "image": null + }, + { + "text": "Example 2: Input:n = 11111111111111111111111111111101\nOutput:3221225471 (10111111111111111111111111111111)\nExplanation:The input binary string11111111111111111111111111111101represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is10111111111111111111111111111111.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need treat n as an unsigned value\n public int reverseBits(int n) {\n int result = 0;\n\n for(int i = 0; i < 32; i++) {\n int bit = (n & 1);\n result = (result << 1) | bit;\n n >>>= 1;\n }\n\n return result;\n }\n}", + "title": "190. Reverse Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 ).", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int hammingWeight(int n) {\n int count = 0;\n while (n != 0) {\n count += (n & 1); // Check if last bit is 1\n n >>>= 1; // Unsigned right shift\n }\n return count;\n }\n}", + "title": "191. Number of 1 Bits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]\nOutput:4\nExplanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]\nOutput:12\nExplanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int rob(int[] nums) {\n if (nums.length == 0)\n return 0;\n if (nums.length == 1)\n return nums[0];\n\n int prev2 = 0, prev1 = 0;\n for (int num : nums) {\n int curr = Math.max(prev1, prev2 + num);\n prev2 = prev1;\n prev1 = curr;\n }\n \n return prev1;\n }\n}", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/11/24/tmpd5jn43fs-1.png", + "https://assets.leetcode.com/uploads/2024/11/24/tmpkpe40xeh-1.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List rightSideView(TreeNode root) {\n List result = new ArrayList<>();\n dfs(root, 0, result);\n\n return result;\n }\n\n private void dfs(TreeNode node, int depth, List result) {\n\n if (node == null)\n return;\n if (depth == result.size())\n result.add(node.val);\n\n dfs(node.right, depth + 1, result);\n dfs(node.left, depth + 1, result);\n }\n}", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numIslands(char[][] grid) {\n if (grid == null || grid.length == 0)\n return 0;\n\n int numIslands = 0;\n int rows = grid.length, cols = grid[0].length;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (grid[r][c] == '1') {\n numIslands++;\n dfs(grid, r, c);\n }\n }\n }\n\n return numIslands;\n }\n\n private void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == '0') {\n return;\n }\n\n grid[r][c] = '0';\n\n dfs(grid, r + 1, c);\n dfs(grid, r - 1, c);\n dfs(grid, r, c + 1);\n dfs(grid, r, c - 1);\n }\n}", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive .", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int rangeBitwiseAnd(int left, int right) {\n int shiftCount = 0;\n\n while (left < right) {\n left >>= 1;\n right >>= 1;\n shiftCount++;\n }\n\n return left << shiftCount;\n }\n}", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not .", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19\nOutput:true\nExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Floyd’s Cycle Detection (Tortoise and Hare)\n public boolean isHappy(int n) {\n\n int slow = n, fast = getNext(n);\n\n while (fast != 1 && slow != fast) {\n slow = getNext(slow);\n fast = getNext(getNext(fast)); // Move fast twice\n }\n\n return fast == 1;\n }\n\n private int getNext(int n) {\n int squareSum = 0;\n\n while (n > 0) {\n int digit = n % 10;\n squareSum += digit * digit;\n n /= 10;\n }\n\n return squareSum;\n }\n}\n", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6\nOutput:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1\nOutput:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode removeElements(ListNode head, int val) {\n ListNode result = new ListNode(0, head);\n ListNode dummy = result;\n\n while (dummy != null) {\n while (dummy.next != null && dummy.next.val == val) {\n dummy.next = dummy.next.next;\n }\n dummy = dummy.next;\n }\n\n return result.next;\n }\n}", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , determine if they are isomorphic . Two strings s and t are isomorphic if the characters in s can be replaced to get t . All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.", + "description_images": [], + "constraints": [ + "Mapping 'e' to 'a' .", + "Mapping 'g' to 'd' ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean isIsomorphic(String s, String t) {\n\n Map map = new HashMap<>();\n Set mappedValues = new HashSet<>();\n\n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n\n if (map.containsKey(charS)) {\n if (map.get(charS) != charT)\n return false; // Conflict\n } else {\n if (mappedValues.contains(charT))\n return false; // Prevent multiple mappings\n map.put(charS, charT);\n mappedValues.add(charT);\n }\n }\n\n return true;\n }\n}", + "title": "205. Isomorphic Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]\nOutput:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode node = null;\n\n while (head != null) {\n ListNode temp = head.next;\n head.next = node;\n node = head;\n head = temp;\n }\n\n return node;\n }\n}", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Return true if you can finish all courses. Otherwise, return false .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:true\nExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput:false\nExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFinish(int numCourses, int[][] prerequisites) {\n\n // Build graph and in-degree array\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n\n for (int[] pre : prerequisites) {\n int course = pre[0], prereq = pre[1];\n graph.putIfAbsent(prereq, new ArrayList<>());\n graph.get(prereq).add(course);\n inDegree[course]++;\n }\n\n // Find courses with no prerequisites\n Queue queue = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0)\n queue.offer(i);\n }\n\n // Process courses in BFS order\n int count = 0;\n while (!queue.isEmpty()) {\n int curr = queue.poll();\n count++;\n\n if (graph.containsKey(curr)) {\n\n for (int neighbor : graph.get(curr)) {\n inDegree[neighbor]--;\n if (inDegree[neighbor] == 0)\n queue.offer(neighbor);\n }\n }\n }\n\n return count == numCourses;\n }\n}", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]Output[null, null, true, false, true, null, true]ExplanationTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\"); // return True\ntrie.search(\"app\"); // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode {\n TrieNode[] children = new TrieNode[26];\n boolean isWord;\n}\n\nclass Trie { // Array Based - fixed size\n private TrieNode root;\n\n public Trie() {\n root = new TrieNode();\n }\n\n public void insert(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.isWord = true;\n }\n\n public boolean search(String word) {\n TrieNode node = findNode(word);\n return node != null && node.isWord;\n }\n\n public boolean startsWith(String prefix) {\n return findNode(prefix) != null;\n }\n\n private TrieNode findNode(String prefix) {\n TrieNode node = root;\n \n for (char c : prefix.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n return null;\n }\n node = node.children[index];\n }\n return node;\n }\n}", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a subarray whose sum is greater than or equal to target . If there is no such subarray, return 0 instead.", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]\nOutput:2\nExplanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSubArrayLen(int target, int[] nums) { // sliding window approach - Time: O(n) || Space: O(1)\n\n int left = 0, sum = 0;\n int minLength = Integer.MAX_VALUE;\n\n for (int right = 0; right < nums.length; right++) {\n sum += nums[right];\n\n while (sum >= target) {\n minLength = Math.min(minLength, right - left + 1);\n sum -= nums[left];\n left++;\n }\n }\n\n return minLength != Integer.MAX_VALUE ? minLength : 0;\n }\n}", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . 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 .", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]\nOutput:[0,1]\nExplanation: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].", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput:[0,2,1,3]\nExplanation: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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] findOrder(int numCourses, int[][] prerequisites) {\n\n // Build graph and in-degree array\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n\n for (int[] pre : prerequisites) {\n int course = pre[0], prereq = pre[1];\n graph.putIfAbsent(prereq, new ArrayList<>());\n graph.get(prereq).add(course);\n inDegree[course]++;\n }\n\n // Find courses with no prerequisites\n Queue queue = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0)\n queue.offer(i);\n }\n\n // Process courses in BFS order\n int[] order = new int[numCourses];\n int index = 0; // To track course order\n\n while (!queue.isEmpty()) {\n int curr = queue.poll();\n order[index++] = curr;\n\n if (graph.containsKey(curr)) {\n\n for (int neighbor : graph.get(curr)) {\n inDegree[neighbor]--;\n if (inDegree[neighbor] == 0)\n queue.offer(neighbor);\n }\n }\n }\n\n return index == numCourses ? order : new int[0];\n }\n}", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "public class TrieNode {\n TrieNode[] children;\n public boolean isWord;\n\n public TrieNode() {\n this.children = new TrieNode[26];\n this.isWord = false;\n }\n}\n\nclass WordDictionary {\n\n private final TrieNode root;\n\n public WordDictionary() {\n this.root = new TrieNode();\n }\n\n // Add a word to the Trie\n public void addWord(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a'; // Convert char to index (0 to 25)\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.isWord = true;\n }\n\n // Search a word with support for '.'\n public boolean search(String word) {\n return dfsSearch(word, 0, root);\n }\n\n private boolean dfsSearch(String word, int index, TrieNode node) {\n if (node == null)\n return false;\n if (index == word.length())\n return node.isWord;\n\n char c = word.charAt(index);\n if (c == '.') {\n\n // Wildcard case: Try all 26 children\n for (TrieNode child : node.children) {\n if (child != null && dfsSearch(word, index + 1, child)) {\n return true;\n }\n }\n return false;\n } else {\n // Regular character lookup\n int charIndex = c - 'a';\n return dfsSearch(word, index + 1, node.children[charIndex]);\n }\n }\n\n}\n\n/**\n * Your WordDictionary object will be instantiated and called as such:\n * WordDictionary obj = new WordDictionary();\n * obj.addWord(word);\n * boolean param_2 = obj.search(word);\n */", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\nOutput:[\"eat\",\"oath\"]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" + }, + { + "text": "Example 2: Input:board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n static class TrieNode {\n TrieNode[] children = new TrieNode[26];\n String word = null; \n }\n\n private final TrieNode root = new TrieNode();\n private final List result = new ArrayList<>();\n\n private void insertWord(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.word = word; \n }\n\n public List findWords(char[][] board, String[] words) {\n for (String word : words) {\n insertWord(word);\n }\n\n int m = board.length, n = board[0].length;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n dfs(board, i, j, root);\n }\n }\n return result;\n }\n\n private void dfs(char[][] board, int i, int j, TrieNode node) {\n char c = board[i][j];\n\n if (c == '#' || node.children[c - 'a'] == null)\n return;\n\n node = node.children[c - 'a'];\n\n if (node.word != null) {\n result.add(node.word);\n node.word = null; // Avoid duplicate results\n }\n\n board[i][j] = '#';\n \n if (i > 0)\n dfs(board, i - 1, j, node); // Up\n if (i < board.length - 1)\n dfs(board, i + 1, j, node); // Down\n if (j > 0)\n dfs(board, i, j - 1, node); // Left\n if (j < board[0].length - 1)\n dfs(board, i, j + 1, node); // Right\n\n // Step 7: Restore cell\n board[i][j] = c;\n }\n}\n", + "title": "212. Word Search II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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?", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,5,6,4], k = 2\nOutput:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,3,1,2,4,5,5,6], k = 4\nOutput:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthLargest(int[] nums, int k) {\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for (int num : nums) {\n minHeap.offer(num);\n\n if (minHeap.size() > k)\n minHeap.poll();\n }\n\n return minHeap.peek();\n }\n}", + "title": "215. Kth Largest Element in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order.", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7\nOutput:[[1,2,4]]\nExplanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9\nOutput:[[1,2,6],[1,3,5],[2,3,4]]\nExplanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1\nOutput:[]\nExplanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combinationSum3(int k, int n) {\n List> result = new ArrayList<>();\n backtrack(result, new ArrayList<>(), k, n, 1);\n return result;\n }\n\n private void backtrack(List> result, List path, int k, int n, int start) {\n\n if (path.size() == k && n == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i <= 9; i++) {\n path.add(i);\n backtrack(result, path, k, n - i, i + 1);\n path.removeLast();\n }\n }\n}", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean containsDuplicate(int[] nums) {\n HashSet seen = new HashSet<>();\n for (int num : nums) {\n if (seen.contains(num)) {\n return true;\n }\n seen.add(num);\n }\n\n return false;\n }\n}", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsNearbyDuplicate(int[] nums, int k) { // Using HashMap for Index Tracking\n\n HashMap map = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n\n if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {\n return true;\n }\n map.put(nums[i], i);\n }\n\n return false;\n }\n}", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area .", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximalSquare(char[][] matrix) {\n if (matrix == null || matrix.length == 0)\n return 0;\n\n int m = matrix.length, n = matrix[0].length;\n int[][] dp = new int[m + 1][n + 1]; // add padding\n int maxSide = 0;\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n\n if (matrix[i - 1][j - 1] == '1') {\n dp[i][j] = 1 + Math.min(\n dp[i - 1][j],\n Math.min(dp[i][j - 1], dp[i - 1][j - 1]));\n maxSide = Math.max(maxSide, dp[i][j]);\n }\n }\n }\n\n return maxSide * maxSide;\n }\n}", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]\nOutput:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int countNodes(TreeNode root) {\n if (root == null)\n return 0;\n return 1 + countNodes(root.left) + countNodes(root.right);\n }\n}", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int calculate(String s) {\n\n Stack stack = new Stack<>();\n\n int num = 0, result = 0, sign = 1; // `sign = 1` means positive, `-1` means negative\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n if (Character.isDigit(c)) {\n num = num * 10 + (c - '0'); // Extract full number\n\n } else if (c == '+' || c == '-') {\n result += sign * num;\n num = 0;\n sign = c == '+' ? 1 : -1;\n\n } else if (c == '(') {\n stack.push(result); // Store the current result\n stack.push(sign); // Store the current sign\n result = 0;\n sign = 1;\n\n } else if (c == ')') {\n result += sign * num; // Complete the last pending operation\n num = 0;\n result *= stack.pop(); // Apply sign before '('\n result += stack.pop(); // Add result before '('\n }\n }\n\n return result + (sign * num); // Add last number to result\n\n }\n}", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, invert the tree, and return its root .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]\nOutput:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]\nOutput:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode invertTree(TreeNode root) {\n\n if (root == null)\n return null;\n\n TreeNode left = invertTree(root.left);\n TreeNode right = invertTree(root.right);\n\n root.left = right;\n root.right = left;\n \n return root;\n }\n}", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a sorted unique integer array nums . A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly . That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums . Each range [a,b] in the list should be output as:", + "description_images": [], + "constraints": [ + "\"a->b\" if a != b", + "\"a\" if a == b" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,4,5,7]\nOutput:[\"0->2\",\"4->5\",\"7\"]\nExplanation:The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,2,3,4,6,8,9]\nOutput:[\"0\",\"2->4\",\"6\",\"8->9\"]\nExplanation:The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List summaryRanges(int[] nums) {\n\n List result = new ArrayList<>();\n if (nums.length == 0)\n return result;\n\n int start = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] != nums[i - 1] + 1) {\n result.add(formatRange(start, nums[i - 1]));\n start = nums[i];\n }\n }\n\n result.add(formatRange(start, nums[nums.length - 1]));\n return result;\n }\n\n private String formatRange(int start, int end) {\n return (start == end) ? String.valueOf(start) : start + \"->\" + end;\n }\n}\n", + "title": "228. Summary Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int kthSmallest(TreeNode root, int k) {\n int leftSize = countNodes(root.left);\n\n if (k == leftSize + 1)\n return root.val;\n else if (k <= leftSize)\n return kthSmallest(root.left, k);\n else\n return kthSmallest(root.right, k - leftSize - 1);\n }\n\n private int countNodes(TreeNode node) {\n if (node == null)\n return 0;\n return 1 + countNodes(node.left) + countNodes(node.right);\n }\n}", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class MyQueue {\n\n Stack input;\n Stack output;\n\n public MyQueue() {\n this.input = new Stack();\n this.output = new Stack();\n }\n\n public void push(int x) {\n this.input.push(x);\n }\n\n public int pop() {\n this.peek();\n return this.output.pop();\n }\n\n public int peek() {\n if (this.output.isEmpty()) {\n while (!this.input.isEmpty()) {\n this.output.push(this.input.pop());\n }\n }\n return this.output.peek();\n }\n\n public boolean empty() {\n return this.input.isEmpty() && this.output.isEmpty();\n }\n}\n\n/**\n * Your MyQueue object will be instantiated and called as such:\n * MyQueue obj = new MyQueue();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.peek();\n * boolean param_4 = obj.empty();\n */", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return true if it is a palindrome or false otherwise .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 10^5 ] .", + "0 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,2,1]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n ListNode curr;\n\n public boolean isPalindrome(ListNode head) {\n curr = head;\n return solve(head);\n }\n\n public boolean solve(ListNode head) {\n if (head == null)\n return true;\n \n boolean ans = solve(head.next) && head.val == curr.val;\n curr = curr.next;\n return ans;\n }\n}", + "title": "234. Palindrome Linked List", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 ).”", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput:6\nExplanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput:2\nExplanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n \n while (root != null) {\n if (p.val < root.val && q.val < root.val) {\n root = root.left;\n } else if (p.val > root.val && q.val > root.val) {\n root = root.right;\n } else {\n return root;\n }\n }\n\n return null;\n }\n}", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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 ).”", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput:3\nExplanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput:5\nExplanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n\n // Base case: If root is null return null\n if (root == null)\n return null;\n\n // if we find either p or q, return root\n if (root.val == p.val || root.val == q.val)\n return root;\n\n // Search in the left and right subtree\n TreeNode left = lowestCommonAncestor(root.left, p, q);\n TreeNode right = lowestCommonAncestor(root.right, p, q);\n\n // If both left and right are non-null, root is the LCA\n if (left != null && right != null)\n return root;\n\n // Otherwise, return whichever side is non-null\n return left != null ? left : right;\n }\n}", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]\nOutput:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]\nOutput:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n static {\n for (int i = 0; i < 500; i++) {\n productExceptSelf(new int[] { 0, 0 });\n }\n }\n\n public static int[] productExceptSelf(int[] nums) {\n // Time: O(n) || Space: O(1)\n\n int n = nums.length;\n int answer[] = new int[n];\n\n answer[n - 1] = 1;\n int multiply = nums[0];\n\n for (int i = n - 2; i >= 0; i--) {\n answer[i] = nums[i + 1] * answer[i + 1];\n }\n\n for (int i = 1; i < n; i++) {\n answer[i] = multiply * answer[i];\n multiply = multiply * nums[i];\n }\n\n return answer;\n }\n}\n\n// Example go throuth -->\n// Input: nums = [1, 2, 3, 4]\n//\n// First Pass (Right-to-Left):\n// Initialize: answer = [0, 0, 0, 1].\n// Iteration:\n// i = 2: answer[2] = nums[3] * answer[3] = 4 * 1 = 4.\n// i = 1: answer[1] = nums[2] * answer[2] = 3 * 4 = 12.\n// i = 0: answer[0] = nums[1] * answer[1] = 2 * 12 = 24.\n// After first pass: answer = [24, 12, 4, 1].\n\n// Second Pass (Left-to-Right):\n// Initialize: multiply = nums[0] = 1.\n// Iteration:\n// i = 1: answer[1] = multiply * answer[1] = 1 * 12 = 12. Update multiply =\n// multiply * nums[1] = 1 * 2 = 2.\n// i = 2: answer[2] = multiply * answer[2] = 2 * 4 = 8. Update multiply =\n// multiply * nums[2] = 2 * 3 = 6.\n// i = 3: answer[3] = multiply * answer[3] = 6 * 1 = 6. Update multiply =\n// multiply * nums[3] = 6 * 4 = 24.\n// After second pass: answer = [24, 12, 8, 6].\n\n// Output:\n\n// [24, 12, 8, 6]", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput:[3,3,5,5,6,7]\nExplanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSlidingWindow(int[] nums, int k) {\n if (nums.length == 0 || k == 0)\n return new int[0];\n\n int n = nums.length;\n int[] result = new int[n - k + 1];\n Deque deque = new ArrayDeque<>();\n\n for (int i = 0; i < n; i++) {\n\n if (!deque.isEmpty() && deque.peek() <= i - k) {\n deque.poll();\n }\n\n while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {\n deque.pollLast();\n }\n\n deque.offer(i);\n\n if (i >= k - 1) {\n result[i - k + 1] = nums[deque.peek()];\n }\n }\n\n return result;\n }\n}", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return false;\n\n int row = 0;\n int col = matrix[0].length - 1;\n\n while (row < matrix.length && col >= 0) {\n int value = matrix[row][col];\n \n if (value == target) {\n return true;\n } else if (value > target) {\n col--;\n } else {\n row++;\n }\n }\n\n return false;\n }\n}", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , return true if t is an anagram of s , and false otherwise.", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean isAnagram(String s, String t) {\n\n if (s.length() != t.length()) {\n return false;\n }\n\n int[] alphabets = new int[26];\n\n for (char c : s.toCharArray()) {\n alphabets[c - 'a']++;\n }\n\n for (char c : t.toCharArray()) {\n alphabets[c - 'a']--;\n }\n\n for (int alphabet : alphabets) {\n if (alphabet != 0) {\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return the researcher's h-index . According to the definition of h-index on Wikipedia : The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]\nOutput:3\nExplanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) { // Time: O(n) || Space: O(n + 1) -> 1 n for using counting array\n\n int n = citations.length;\n int[] count = new int[n + 1];\n int max = 0;\n\n for (int citation : citations) {\n ++count[Math.min(citation, n)];\n }\n\n for (int i = n; i >= 0; --i) { // i is the candidate's h-index\n max += count[i];\n if (max >= i)\n return i;\n }\n\n return 0;\n }\n}\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4\nOutput:4\nExplanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/* The isBadVersion API is defined in the parent class VersionControl.\n boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n public int firstBadVersion(int n) {\n int low = 1, high = n;\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n if (isBadVersion(mid)) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n return low;\n }\n}", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the least number of perfect square numbers that sum to n . A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1 , 4 , 9 , and 16 are perfect squares while 3 and 11 are not.", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12\nOutput:3\nExplanation:12 = 4 + 4 + 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 13\nOutput:2\nExplanation:13 = 4 + 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSquares(int n) {\n int[] dp = new int[n + 1];\n\n for (int i = 1; i <= n; i++) {\n dp[i] = Integer.MAX_VALUE;\n \n for (int j = 1; j * j <= i; j++) {\n dp[i] = Math.min(dp[i], dp[i - j * j] + 1);\n }\n }\n\n return dp[n];\n }\n}", + "title": "279. Perfect Squares", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , move all 0 's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,3,12]\nOutput:[1,3,12,0,0]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]\nOutput:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void moveZeroes(int[] nums) { // Two Pointer Approach\n int left = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n if (nums[right] != 0) {\n int temp = nums[right];\n nums[right] = nums[left];\n nums[left] = temp;\n left++;\n }\n }\n }\n}", + "title": "283. Move Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]\nOutput:3", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3,3,3,3]\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findDuplicate(int[] nums) {\n int slow = nums[0];\n int fast = nums[0];\n\n // First part: find the intersection point\n do {\n slow = nums[slow];\n fast = nums[nums[fast]];\n } while (slow != fast);\n\n // Second part: find the entrance to the cycle\n slow = nums[0];\n while (slow != fast) {\n slow = nums[slow];\n fast = nums[fast];\n }\n\n return slow;\n }\n}", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board . In this process, births and deaths occur simultaneously . Given the current state of the board , update the board to reflect its next state. Note that you do not need to return anything.", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]\nOutput:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void gameOfLife(int[][] board) {\n int m = board.length, n = board[0].length;\n\n // Directions for 8 neighbors\n int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1 };\n int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\n // Step 1: Encode changes in-place\n for (int i = 0; i < m; i++) {\n\n for (int j = 0; j < n; j++) {\n int liveNeighbors = 0;\n\n // Count live neighbors\n for (int d = 0; d < 8; d++) {\n int ni = i + dx[d], nj = j + dy[d];\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && Math.abs(board[ni][nj]) == 1) {\n liveNeighbors++;\n }\n }\n\n // Apply rules using encoded values\n if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {\n board[i][j] = -1; // Alive → Dead\n } else if (board[i][j] == 0 && liveNeighbors == 3) {\n board[i][j] = 2; // Dead → Alive\n }\n }\n }\n\n // Step 2: Decode the matrix\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n\n if (board[i][j] == -1)\n board[i][j] = 0;\n if (board[i][j] == 2)\n board[i][j] = 1;\n }\n }\n }\n}", + "title": "289. Game of Life", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a pattern and a string s , find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s . Specifically:", + "description_images": [], + "constraints": [ + "Each letter in pattern maps to exactly one unique word in s .", + "Each unique word in s maps to exactly one letter in pattern .", + "No two letters map to the same word, and no two words map to the same letter." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean wordPattern(String pattern, String s) {\n String[] words = s.split(\" \");\n\n if (pattern.length() != words.length)\n return false;\n\n Map map = new HashMap<>();\n Set mappedWords = new HashSet<>();\n\n for (int i = 0; i < pattern.length(); i++) {\n\n char c = pattern.charAt(i);\n String word = words[i];\n\n if (map.containsKey(c)) {\n\n if (!map.get(c).equals(word))\n return false;\n\n } else {\n\n if (mappedWords.contains(word))\n return false;\n\n map.put(c, word);\n mappedWords.add(word);\n }\n }\n\n return true;\n }\n}", + "title": "290. Word Pattern", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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. Implement the MedianFinder class:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "class MedianFinder {\n\n private final PriorityQueue maxHeap;\n private final PriorityQueue minHeap;\n\n public MedianFinder() {\n maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n minHeap = new PriorityQueue<>();\n }\n\n public void addNum(int num) {\n if (maxHeap.isEmpty() || num <= maxHeap.peek()) {\n maxHeap.offer(num);\n } else {\n minHeap.offer(num);\n }\n\n if (maxHeap.size() > minHeap.size() + 1) {\n minHeap.offer(maxHeap.poll());\n } else if (minHeap.size() > maxHeap.size()) {\n maxHeap.offer(minHeap.poll());\n }\n }\n\n public double findMedian() {\n if (maxHeap.size() > minHeap.size()) {\n return maxHeap.peek(); // Odd number of elements\n }\n\n return (maxHeap.peek() + minHeap.peek()) / 2.0; // Even number of elements\n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * MedianFinder obj = new MedianFinder();\n * obj.addNum(num);\n * double param_2 = obj.findMedian();\n */", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,null,4,5]\nOutput:[1,2,3,null,null,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" + }, + { + "text": "Example 2: Input:root = []\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\npublic class Codec {\n\n public String serialize(TreeNode root) {\n if (root == null)\n return \"null\";\n\n StringBuilder sb = new StringBuilder();\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n TreeNode node = queue.poll();\n if (node == null) {\n sb.append(\"null,\");\n continue;\n }\n sb.append(node.val).append(\",\");\n queue.offer(node.left);\n queue.offer(node.right);\n }\n\n sb.setLength(sb.length() - 1);\n return sb.toString();\n }\n\n public TreeNode deserialize(String data) {\n if (data.equals(\"null\"))\n return null;\n\n String[] values = data.split(\",\");\n TreeNode root = new TreeNode(Integer.parseInt(values[0]));\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n for (int i = 1; i < values.length; i++) {\n TreeNode parent = queue.poll();\n\n if (!values[i].equals(\"null\")) {\n parent.left = new TreeNode(Integer.parseInt(values[i]));\n queue.offer(parent.left);\n }\n i++;\n\n if (i < values.length && !values[i].equals(\"null\")) {\n parent.right = new TreeNode(Integer.parseInt(values[i]));\n queue.offer(parent.right);\n }\n }\n\n return root;\n }\n}\n\n// Your Codec object will be instantiated and called as such:\n// Codec ser = new Codec();\n// Codec deser = new Codec();\n// TreeNode ans = deser.deserialize(ser.serialize(root));", + "title": "297. Serialize and Deserialize Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the length of the longest strictly increasing subsequence .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2500", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,9,2,5,3,7,101,18]\nOutput:4\nExplanation:The longest increasing subsequence is [2,3,7,101], therefore the length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,3,2,3]\nOutput:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7,7,7,7]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLIS(int[] nums) {\n int n = nums.length;\n int[] tails = new int[n]; // Max possible size is n\n int size = 0;\n\n for (int num : nums) {\n int idx = binarySearch(tails, 0, size - 1, num);\n\n if (idx == size) {\n tails[size++] = num; // Extend the sequence\n } else {\n tails[idx] = num; // Replace to maintain minimal tails\n }\n }\n\n return size;\n }\n\n // Binary search: Find first index where tails[i] >= target\n private int binarySearch(int[] tails, int left, int right, int target) {\n while (left <= right) {\n int mid = (left + right) >>> 1;\n\n if (tails[mid] >= target) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left; // Insertion point\n }\n}", + "title": "300. Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following type: Implement the NumArray class:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"sumRange\", \"sumRange\"]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]Output[null, 1, -1, -3]ExplanationNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray {\n\n private final int[] prefix;\n\n public NumArray(int[] nums) {\n prefix = new int[nums.length + 1];\n\n for (int i = 0; i < nums.length; i++) {\n prefix[i + 1] = prefix[i] + nums[i];\n }\n }\n\n public int sumRange(int left, int right) {\n return prefix[right + 1] - prefix[left];\n }\n}\n\n/**\n * Your NumArray object will be instantiated and called as such:\n * NumArray obj = new NumArray(nums);\n * int param_1 = obj.sumRange(left,right);\n */", + "title": "303. Range Sum Query - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "public class NumArray {\n private int[] tree;\n private int n;\n\n public NumArray(int[] nums) {\n if (nums.length > 0) {\n n = nums.length;\n tree = new int[2 * n];\n buildTree(nums);\n }\n }\n\n private void buildTree(int[] nums) {\n\n // fill leaf nodes\n if (n >= 0) System.arraycopy(nums, 0, tree, n, n);\n\n // build the tree by calculating parents\n for (int i = n - 1; i > 0; --i) {\n tree[i] = tree[2 * i] + tree[2 * i + 1];\n }\n }\n\n public void update(int index, int val) {\n index += n; // Move to leaf\n tree[index] = val;\n\n while (index > 0) {\n\n int left = index;\n int right = index;\n\n if (index % 2 == 0) {\n right = index + 1;\n } else {\n left = index - 1;\n }\n\n // move one level up\n tree[index / 2] = tree[left] + tree[right];\n index /= 2;\n }\n }\n\n public int sumRange(int left, int right) {\n left += n;\n right += n;\n int sum = 0;\n\n while (left <= right) {\n\n if (left % 2 == 1) {\n sum += tree[left];\n left++;\n }\n if (right % 2 == 0) {\n sum += tree[right];\n right--;\n }\n left /= 2;\n right /= 2;\n }\n\n return sum;\n }\n}\n\n/**\n * Your NumArray object will be instantiated and called as such:\n * NumArray obj = new NumArray(nums);\n * obj.update(index,val);\n * int param_2 = obj.sumRange(left,right);\n */", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput:[1]\nExplanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findMinHeightTrees(int n, int[][] edges) {\n if (n == 1)\n return Collections.singletonList(0);\n\n List> graph = new ArrayList<>();\n for (int i = 0; i < n; i++)\n graph.add(new HashSet<>());\n \n for (int[] e : edges) {\n graph.get(e[0]).add(e[1]);\n graph.get(e[1]).add(e[0]);\n }\n\n List leaves = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n if (graph.get(i).size() == 1) {\n leaves.add(i);\n }\n }\n\n int remaining = n;\n while (remaining > 2) {\n remaining -= leaves.size();\n List newLeaves = new ArrayList<>();\n\n for (int leaf : leaves) {\n int neighbor = graph.get(leaf).iterator().next();\n graph.get(neighbor).remove(leaf);\n if (graph.get(neighbor).size() == 1) {\n newLeaves.add(neighbor);\n }\n }\n\n leaves = newLeaves;\n }\n\n return leaves;\n }\n}", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 12", + "1 <= coins[i] <= 2 31 - 1", + "0 <= amount <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,2,5], amount = 11\nOutput:3\nExplanation:11 = 5 + 5 + 1", + "image": null + }, + { + "text": "Example 2: Input:coins = [2], amount = 3\nOutput:-1", + "image": null + }, + { + "text": "Example 3: Input:coins = [1], amount = 0\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int coinChange(int[] coins, int amount) { // Bottom-Up DP (Tabulation) \n int max = amount + 1;\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, max);\n dp[0] = 0;\n\n for (int i = 1; i <= amount; i++) {\n for (int coin : coins) {\n \n if (i - coin >= 0) {\n dp[i] = Math.min(dp[i], dp[i - coin] + 1);\n }\n }\n }\n\n return dp[amount] == max ? -1 : dp[amount];\n }\n}", + "title": "322. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list . The first node is considered odd , and the second node is even , and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity.", + "description_images": [], + "constraints": [ + "The number of nodes in the linked list is in the range [0, 10^4 ] .", + "-10^6 <= Node.val <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[1,3,5,2,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [2,1,3,5,6,4,7]\nOutput:[2,3,6,7,1,5,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode oddEvenList(ListNode head) {\n if (head == null || head.next == null)\n return head;\n\n ListNode odd = head, even = head.next, evenHead = even;\n\n while (even != null && even.next != null) {\n odd.next = even.next;\n odd = odd.next;\n even.next = even.next.next;\n even = even.next;\n }\n \n odd.next = evenHead;\n return head;\n }\n}", + "title": "328. Odd Even Linked List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6\nOutput:1\n\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20\nOutput:2\n\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPatches(int[] nums, int n) {\n \n long miss = 1; // Start with the smallest number we need to cover\n int i = 0; // Index to traverse the nums array\n int patches = 0; // Number of patches added\n\n while (miss <= n) {\n \n if (i < nums.length && nums[i] <= miss) {\n \n // If nums[i] can contribute to forming the number `miss`\n miss += nums[i];\n i++;\n \n } else { // Otherwise, patch the array with `miss`\n miss += miss;\n patches++;\n }\n }\n\n return patches;\n }\n}", + "title": "330. Patching Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]\nOutput:true\nExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]\nOutput:false\nExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]\nOutput:true\nExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;\n\n for (int num : nums) {\n \n if (num <= first)\n first = num;\n else if (num <= second)\n second = num;\n else\n return true;\n }\n\n return false;\n }\n}", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "0 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:[0,1,1]\nExplanation:0 --> 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:[0,1,1,2,1,2]\nExplanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] countBits(int n) {\n int[] ans = new int[n + 1];\n\n for (int i = 1; i <= n; i++) {\n ans[i] = ans[i >> 1] + (i & 1);\n }\n\n return ans;\n }\n}", + "title": "338. Counting Bits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both lower and upper cases, more than once.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public String reverseVowels(String s) {\n if (s == null || s.length() == 0)\n return s;\n\n Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u',\n 'A', 'E', 'I', 'O', 'U'));\n\n char[] chars = s.toCharArray();\n int i = 0, j = s.length() - 1;\n\n while (i < j) {\n while (i < j && !vowels.contains(chars[i])) {\n i++;\n }\n\n while (i < j && !vowels.contains(chars[j])) {\n j--;\n }\n\n if (i < j) {\n char temp = chars[i];\n chars[i] = chars[j];\n chars[j] = temp;\n i++;\n j--;\n }\n }\n\n return new String(chars);\n }\n}", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the k most frequent elements . You may return the answer in any order .", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2\nOutput:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1\nOutput:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map freqMap = new HashMap<>();\n\n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n\n List[] bucket = new List[nums.length + 1];\n for (int key : freqMap.keySet()) {\n int freq = freqMap.get(key);\n\n if (bucket[freq] == null)\n bucket[freq] = new ArrayList<>();\n bucket[freq].add(key);\n }\n\n List result = new ArrayList<>();\n for (int i = bucket.length - 1; i >= 0 && result.size() < k; i--) {\n if (bucket[i] != null)\n result.addAll(bucket[i]);\n }\n\n return result.stream().mapToInt(i -> i).toArray();\n }\n}", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums .", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in non-decreasing order .", + "1 <= k <= 10^4", + "k <= nums1.length * nums2.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput:[[1,2],[1,4],[1,6]]\nExplanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput:[[1,1],[1,1]]\nExplanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n List> result = new ArrayList<>();\n\n // Edge case\n if (nums1.length == 0 || nums2.length == 0) {\n return result;\n }\n\n PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n\n for (int i = 0; i < nums1.length; i++) {\n minHeap.offer(new int[] { nums1[i] + nums2[0], i, 0 }); // Store (sum, i, j)\n }\n\n // Extract the k smallest pairs\n while (k-- > 0 && !minHeap.isEmpty()) {\n int[] current = minHeap.poll();\n int i = current[1], j = current[2];\n\n result.add(Arrays.asList(nums1[i], nums2[j]));\n\n if (j + 1 < nums2.length) {\n minHeap.offer(new int[] { nums1[i] + nums2[j + 1], i, j + 1 });\n }\n }\n\n return result;\n }\n}", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked .", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6\nOutput:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/** \n * Forward declaration of guess API.\n * @param num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n public int guessNumber(int n) {\n int low = 0;\n int high = n;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n\n if (guess(mid) == 0) {\n return mid;\n } else if (guess(mid) == -1) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n \n return -1;\n }\n}", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity.", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass RandomizedSet {\n\n private ArrayList list;\n private Map map; // Maps value to its index in the list\n private int size = 0;\n private Random rand;\n\n public RandomizedSet() {\n this.list = new ArrayList<>();\n this.map = new HashMap<>();\n this.rand = new Random();\n }\n\n private boolean search(int val) {\n return map.containsKey(val);\n }\n\n public boolean insert(int val) {\n\n if (search(val))\n return false;\n\n map.put(val, list.size());\n list.add(val);\n size++;\n\n return true;\n }\n\n public boolean remove(int val) {\n\n if (!search(val))\n return false;\n\n int index = map.get(val);\n int temp = list.get(size - 1);\n\n list.set(index, temp);\n map.put(temp, index);\n\n list.remove(size - 1);\n map.remove(val);\n size--;\n\n return true;\n }\n\n public int getRandom() {\n return list.get(rand.nextInt(list.size()));\n }\n}\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * boolean param_1 = obj.insert(val);\n * boolean param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote .", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"\nOutput:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canConstruct(String ransomNote, String magazine) {\n int[] count = new int[26];\n\n // Count occurrences of characters in the magazine\n for (char c : magazine.toCharArray()) {\n count[c - 'a']++;\n }\n\n // Check if we can construct the ransomNote from the magazine\n for (char c : ransomNote.toCharArray()) {\n if (count[c - 'a'] == 0) {\n return false; // Not enough characters in magazine\n }\n count[c - 'a']--; \n }\n\n return true;\n }\n}\n\n// class Solution {\n// public boolean canConstruct(String ransomNote, String magazine) {\n\n// HashMap map = new HashMap<>();\n\n// for (char c : magazine.toCharArray()) {\n// map.put(c, map.getOrDefault(c, 0) + 1);\n// }\n\n// for (char c : ransomNote.toCharArray()) {\n// if (!map.containsKey(c) || map.get(c) <= 0) {\n// return false;\n// }\n// map.put(c, map.get(c) - 1);\n// }\n\n// return true;\n// }\n// }", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , find the first non-repeating character in it and return its index. If it does not exist, return -1 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int firstUniqChar(String s) {\n int[] freq = new int[26];\n\n for (char c : s.toCharArray()) {\n freq[c - 'a']++;\n }\n\n for (int i = 0; i < s.length(); i++) {\n if (freq[s.charAt(i) - 'a'] == 1) {\n return i;\n }\n }\n\n return -1;\n }\n}", + "title": "387. First Unique Character in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not).", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isSubsequence(String s, String t) {\n\n int p1 = 0, p2 = 0;\n\n while (p1 < s.length() && p2 < t.length()) {\n\n if (s.charAt(p1) == t.charAt(p2)) {\n p1++;\n }\n p2++;\n }\n return p1 == s.length();\n }\n}", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"\nOutput:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"\nOutput:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"\nOutput:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String decodeString(String s) {\n Stack countStack = new Stack<>();\n Stack stringStack = new Stack<>();\n StringBuilder current = new StringBuilder();\n int k = 0;\n\n for (char ch : s.toCharArray()) {\n\n if (Character.isDigit(ch)) {\n k = k * 10 + (ch - '0');\n } else if (ch == '[') {\n countStack.push(k);\n stringStack.push(current);\n current = new StringBuilder();\n k = 0;\n } else if (ch == ']') {\n StringBuilder decoded = stringStack.pop();\n int repeat = countStack.pop();\n \n decoded.append(String.valueOf(current).repeat(repeat));\n current = decoded;\n } else {\n current.append(ch);\n }\n }\n\n return current.toString();\n }\n}", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput:[6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnote: x is undefined => -1.0", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private Map> graph = new HashMap<>();\n\n public double[] calcEquation(List> equations, double[] values, List> queries) {\n\n // Step 1: Build the Graph\n for (int i = 0; i < equations.size(); i++) {\n String a = equations.get(i).get(0);\n String b = equations.get(i).get(1);\n double value = values[i];\n\n graph.putIfAbsent(a, new HashMap<>());\n graph.putIfAbsent(b, new HashMap<>());\n\n graph.get(a).put(b, value);\n graph.get(b).put(a, 1.0 / value);\n }\n\n // Step 2: Process Queries using DFS\n double[] results = new double[queries.size()];\n\n for (int i = 0; i < queries.size(); i++) {\n String start = queries.get(i).get(0);\n String end = queries.get(i).get(1);\n results[i] = dfs(start, end, new HashSet<>());\n }\n\n return results;\n }\n\n private double dfs(String start, String end, Set visited) {\n\n // If nodes are not in graph, return -1\n if (!graph.containsKey(start) || !graph.containsKey(end))\n return -1.0;\n\n // If start and end are the same, return 1.0\n if (start.equals(end))\n return 1.0;\n\n visited.add(start);\n Map neighbors = graph.get(start);\n\n for (String neighbor : neighbors.keySet()) {\n\n if (!visited.contains(neighbor)) {\n double weight = neighbors.get(neighbor);\n double result = dfs(neighbor, end, visited);\n\n if (result != -1.0)\n return weight * result;\n }\n }\n\n return -1.0;\n }\n}", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome.", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"\nOutput:7\nExplanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"\nOutput:1\nExplanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestPalindrome(String s) {\n int oddCount = 0;\n Map map = new HashMap<>();\n\n for (char ch : s.toCharArray()) {\n map.put(ch, map.getOrDefault(ch, 0) + 1);\n\n if (map.get(ch) % 2 == 1)\n oddCount++;\n else\n oddCount--;\n }\n\n return oddCount > 1 ? s.length() - oddCount + 1 : s.length();\n }\n}", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,11,5]\nOutput:true\nExplanation:The array can be partitioned as [1, 5, 5] and [11].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5]\nOutput:false\nExplanation:The array cannot be partitioned into equal sum subsets.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPartition(int[] nums) {\n int total = Arrays.stream(nums).sum();\n \n if (total % 2 != 0)\n return false;\n int target = total / 2;\n\n boolean[] dp = new boolean[target + 1];\n dp[0] = true;\n\n for (int num : nums) {\n for (int i = target; i >= num; i--) {\n dp[i] |= dp[i - num];\n }\n }\n\n return dp[target];\n }\n}", + "title": "416. Partition Equal Subset Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "public class AllOne {\n\n class Bucket {\n int count;\n Set keys;\n Bucket prev, next;\n\n Bucket(int count) {\n this.count = count;\n this.keys = new LinkedHashSet<>();\n }\n }\n\n private Map keyCount;\n private Map countBucket;\n private Bucket head, tail;\n\n public AllOne() {\n keyCount = new HashMap<>();\n countBucket = new HashMap<>();\n head = new Bucket(Integer.MIN_VALUE);\n tail = new Bucket(Integer.MAX_VALUE);\n head.next = tail;\n tail.prev = head;\n }\n\n public void inc(String key) {\n int count = keyCount.getOrDefault(key, 0);\n keyCount.put(key, count + 1);\n\n Bucket currBucket = countBucket.get(count);\n Bucket newBucket = countBucket.get(count + 1);\n\n if (newBucket == null) {\n newBucket = new Bucket(count + 1);\n countBucket.put(count + 1, newBucket);\n insertAfter(currBucket == null ? head : currBucket, newBucket);\n }\n\n newBucket.keys.add(key);\n\n if (currBucket != null) {\n currBucket.keys.remove(key);\n if (currBucket.keys.isEmpty()) {\n remove(currBucket);\n countBucket.remove(count);\n }\n }\n }\n\n public void dec(String key) {\n if (!keyCount.containsKey(key))\n return;\n\n int count = keyCount.get(key);\n Bucket currBucket = countBucket.get(count);\n\n if (count == 1) {\n keyCount.remove(key);\n } else {\n keyCount.put(key, count - 1);\n Bucket newBucket = countBucket.get(count - 1);\n if (newBucket == null) {\n newBucket = new Bucket(count - 1);\n countBucket.put(count - 1, newBucket);\n insertBefore(currBucket, newBucket);\n }\n newBucket.keys.add(key);\n }\n\n currBucket.keys.remove(key);\n if (currBucket.keys.isEmpty()) {\n remove(currBucket);\n countBucket.remove(count);\n }\n }\n\n public String getMaxKey() {\n if (tail.prev == head)\n return \"\";\n return tail.prev.keys.iterator().next();\n }\n\n public String getMinKey() {\n if (head.next == tail)\n return \"\";\n return head.next.keys.iterator().next();\n }\n\n private void insertAfter(Bucket prev, Bucket newBucket) {\n newBucket.next = prev.next;\n newBucket.prev = prev;\n prev.next.prev = newBucket;\n prev.next = newBucket;\n }\n\n private void insertBefore(Bucket next, Bucket newBucket) {\n newBucket.prev = next.prev;\n newBucket.next = next;\n next.prev.next = newBucket;\n next.prev = newBucket;\n }\n\n private void remove(Bucket bucket) {\n bucket.prev.next = bucket.next;\n bucket.next.prev = bucket.prev;\n }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A' , 'C' , 'G' , and 'T' . Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings startGene and endGene and the gene bank bank , return the minimum number of mutations needed to mutate from startGene to endGene . If there is no such a mutation, return -1 . Note that the starting point is assumed to be valid, so it might not be included in the bank.", + "description_images": [], + "constraints": [ + "For example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:startGene = \"AACCGGTT\", endGene = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput:1", + "image": null + }, + { + "text": "Example 2: Input:startGene = \"AACCGGTT\", endGene = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMutation(String startGene, String endGene, String[] bank) {\n Queue queue = new LinkedList<>();\n boolean[] visited = new boolean[bank.length];\n\n queue.offer(startGene);\n int mutations = 0;\n\n // Process the queue using BFS\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n String currentGene = queue.poll();\n\n // If we've reached the end gene, return the number of mutations\n if (currentGene.equals(endGene)) {\n return mutations;\n }\n\n // Try all genes in the bank to see if they differ by exactly one character\n for (int j = 0; j < bank.length; j++) {\n\n if (visited[j])\n continue;\n\n if (isOneMutationApart(bank[j], currentGene)) {\n visited[j] = true; // Mark as visited\n queue.offer(bank[j]);\n }\n }\n }\n mutations++;\n }\n\n return -1;\n }\n\n // Helper function to check if two genes differ by exactly one character\n private boolean isOneMutationApart(String gene1, String gene2) {\n int differences = 0;\n\n for (int i = 0; i < gene1.length(); i++) {\n\n if (gene1.charAt(i) != gene2.charAt(i)) {\n differences++;\n if (differences > 1)\n return false;\n }\n }\n return differences == 1;\n }\n}", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput:1\nExplanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]\nOutput:2\nExplanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]\nOutput:0\nExplanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int eraseOverlapIntervals(int[][] intervals) {\n if (intervals.length == 0)\n return 0;\n\n Arrays.sort(intervals, Comparator.comparingInt(a -> a[1]));\n\n int count = 1;\n int end = intervals[0][1];\n\n for (int i = 1; i < intervals.length; i++) {\n if (intervals[i][0] >= end) {\n count++;\n end = intervals[i][1];\n }\n }\n\n return intervals.length - count;\n }\n}", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput:3\nExplanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int pathSum(TreeNode root, int targetSum) {\n HashMap prefixSum = new HashMap<>();\n prefixSum.put(0L, 1); // Base case for prefix sum\n\n return dfs(root, 0L, targetSum, prefixSum);\n }\n\n private int dfs(TreeNode node, long currentSum, int targetSum, HashMap prefixSum) {\n if (node == null)\n return 0;\n\n currentSum += node.val;\n int count = prefixSum.getOrDefault(currentSum - targetSum, 0);\n\n prefixSum.put(currentSum, prefixSum.getOrDefault(currentSum, 0) + 1);\n\n count += dfs(node.left, currentSum, targetSum, prefixSum);\n count += dfs(node.right, currentSum, targetSum, prefixSum);\n\n prefixSum.put(currentSum, prefixSum.get(currentSum) - 1);\n\n return count;\n }\n}\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order .", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"\nOutput:[0,6]\nExplanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"\nOutput:[0,1,2]\nExplanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findAnagrams(String s, String p) {\n List result = new ArrayList<>();\n\n if (p.length() > s.length())\n return result;\n\n int[] pFreq = new int[26];\n int[] sFreq = new int[26];\n\n for (int i = 0; i < p.length(); i++) {\n pFreq[p.charAt(i) - 'a']++;\n sFreq[s.charAt(i) - 'a']++;\n }\n\n if (Arrays.equals(pFreq, sFreq))\n result.add(0);\n\n for (int i = p.length(); i < s.length(); i++) {\n sFreq[s.charAt(i) - 'a']++;\n sFreq[s.charAt(i - p.length()) - 'a']--;\n\n if (Arrays.equals(pFreq, sFreq))\n result.add(i - p.length() + 1);\n }\n\n return result;\n }\n}", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space.", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]\nOutput:Return 1, and the first character of the input array should be: [\"a\"]\nExplanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compress(char[] chars) {\n int write = 0;\n int read = 0;\n\n while (read < chars.length) {\n char currentChar = chars[read];\n int count = 0;\n\n while (read < chars.length && chars[read] == currentChar) {\n read++;\n count++;\n }\n\n chars[write++] = currentChar;\n\n if (count > 1) {\n for (char c : String.valueOf(count).toCharArray()) {\n chars[write++] = c;\n }\n }\n }\n\n return write;\n }\n}", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3\nOutput:[5,4,6,2,null,null,7]\nExplanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0\nOutput:[5,3,6,2,4,null,7]\nExplanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0\nOutput:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode deleteNode(TreeNode root, int key) {\n if (root == null)\n return null;\n\n if (key < root.val) {\n root.left = deleteNode(root.left, key);\n } else if (key > root.val) {\n root.right = deleteNode(root.right, key);\n } else {\n // Case 1 & 2: one child or no child\n if (root.left == null)\n return root.right;\n if (root.right == null)\n return root.left;\n\n // Case 3: Two children\n TreeNode successor = findMin(root.right);\n root.val = successor.val;\n root.right = deleteNode(root.right, successor.val);\n }\n\n return root;\n }\n\n // Helper to find inorder successor (min in right subtree)\n private static TreeNode findMin(TreeNode node) {\n while (node.left != null)\n node = node.left;\n return node;\n }\n}", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons .", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]\nOutput:4\nExplanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]\nOutput:2\nExplanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMinArrowShots(int[][] points) {\n\n if (points.length == 0)\n return 0;\n \n Arrays.sort(points, Comparator.comparingInt(a -> a[1]));\n\n int arrows = 1;\n int arrowPosition = points[0][1];\n\n for (int i = 1; i < points.length; i++) {\n if (points[i][0] > arrowPosition) {\n arrowPosition = points[i][1];\n arrows++;\n }\n }\n\n return arrows;\n }\n}", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity.", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "class LFUCache {\n\n private final int capacity;\n private int minFreq;\n private final Map keyToVal;\n private final Map keyToFreq;\n private final Map> freqToKeys;\n\n public LFUCache(int capacity) {\n this.capacity = capacity;\n this.minFreq = 0;\n this.keyToVal = new HashMap<>();\n this.keyToFreq = new HashMap<>();\n this.freqToKeys = new HashMap<>();\n }\n\n public int get(int key) {\n if (!keyToVal.containsKey(key))\n return -1;\n\n int freq = keyToFreq.get(key);\n keyToFreq.put(key, freq + 1);\n\n freqToKeys.get(freq).remove(key);\n if (freqToKeys.get(freq).isEmpty()) {\n freqToKeys.remove(freq);\n if (freq == minFreq)\n minFreq++;\n }\n\n freqToKeys.computeIfAbsent(freq + 1, k -> new LinkedHashSet<>()).add(key);\n return keyToVal.get(key);\n }\n\n public void put(int key, int value) {\n if (capacity == 0)\n return;\n\n if (keyToVal.containsKey(key)) {\n keyToVal.put(key, value);\n get(key); // update frequency\n return;\n }\n\n if (keyToVal.size() >= capacity) {\n LinkedHashSet minFreqKeys = freqToKeys.get(minFreq);\n int evictKey = minFreqKeys.iterator().next();\n minFreqKeys.remove(evictKey);\n if (minFreqKeys.isEmpty())\n freqToKeys.remove(minFreq);\n\n keyToVal.remove(evictKey);\n keyToFreq.remove(evictKey);\n }\n\n keyToVal.put(key, value);\n keyToFreq.put(key, 1);\n freqToKeys.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);\n minFreq = 1;\n }\n}\n\n/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary array nums , return the maximum number of consecutive 1 's in the array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1,1,1]\nOutput:3\nExplanation:The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1,0,1]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMaxConsecutiveOnes(int[] nums) {\n int res = 0;\n int count = 0;\n\n for (int n : nums) {\n if (n == 0) {\n count = 0;\n } else {\n count++;\n }\n\n if (res < count) {\n res = count;\n }\n }\n\n return res;\n }\n}", + "title": "485. Max Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput:[-1,3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]\nOutput:[3,-1]\nExplanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n Map ng = new HashMap<>();\n Deque st = new ArrayDeque<>();\n\n for (int num : nums2) {\n while (!st.isEmpty() && st.peek() < num) {\n ng.put(st.pop(), num);\n }\n st.push(num);\n }\n\n int[] res = new int[nums1.length];\n for (int i = 0; i < nums1.length; i++) {\n res[i] = ng.getOrDefault(nums1[i], -1);\n }\n \n return res;\n }\n}", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer.", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput:4\nExplanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n int n = profits.length;\n\n PriorityQueue minCapitalHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.capital));\n PriorityQueue maxProfitHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n for (int i = 0; i < n; i++) {\n minCapitalHeap.offer(new Project(capital[i], profits[i]));\n }\n\n // Perform up to k projects\n for (int i = 0; i < k; i++) {\n\n // Add all projects we can afford to maxProfitHeap\n while (!minCapitalHeap.isEmpty() && minCapitalHeap.peek().capital <= w) {\n maxProfitHeap.offer(minCapitalHeap.poll().profit);\n }\n\n if (maxProfitHeap.isEmpty()) {\n break;\n }\n\n w += maxProfitHeap.poll();\n }\n\n return w;\n }\n\n private static class Project {\n int capital;\n int profit;\n\n Project(int capital, int profit) {\n this.capital = capital;\n this.profit = profit;\n }\n }\n}", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 10^4 ] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]\nOutput:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n private int minDiff = Integer.MAX_VALUE;\n private Integer prev = null;\n\n public int getMinimumDifference(TreeNode root) {\n inorder(root);\n return minDiff;\n }\n\n private void inorder(TreeNode node) {\n if (node == null)\n return;\n\n inorder(node.left);\n\n if (prev != null) {\n minDiff = Math.min(minDiff, node.val - prev);\n }\n prev = node.val;\n\n inorder(node.right);\n }\n}", + "title": "530. Minimum Absolute Difference in BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two cells sharing a common edge is 1 .", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] updateMatrix(int[][] mat) {\n int m = mat.length, n = mat[0].length;\n Queue queue = new LinkedList<>();\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n queue.offer(new int[] { i, j });\n } else {\n mat[i][j] = -1;\n }\n }\n }\n\n int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int x = cell[0], y = cell[1];\n for (int[] d : dirs) {\n int nx = x + d[0], ny = y + d[1];\n if (nx >= 0 && ny >= 0 && nx < m && ny < n && mat[nx][ny] == -1) {\n mat[nx][ny] = mat[x][y] + 1;\n queue.offer(new int[] { nx, ny });\n }\n }\n }\n\n return mat;\n }\n}", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]\nOutput:3\nExplanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution { // DFS (Post-order)\n private int maxDiameter = 0;\n\n public int diameterOfBinaryTree(TreeNode root) {\n depth(root);\n return maxDiameter;\n }\n\n private int depth(TreeNode node) {\n if (node == null)\n return 0;\n\n int left = depth(node.left);\n int right = depth(node.right);\n\n maxDiameter = Math.max(maxDiameter, left + right);\n\n return Math.max(left, right) + 1;\n }\n}", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b , and city b is connected directly with city c , then city a is connected indirectly with city c . A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the i th city and the j th city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces .", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n == isConnected.length", + "n == isConnected[i].length", + "isConnected[i][j] is 1 or 0 .", + "isConnected[i][i] == 1", + "isConnected[i][j] == isConnected[j][i]" + ], + "examples": [ + { + "text": "Example 1: Input:isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput:2", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg" + }, + { + "text": "Example 2: Input:isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput:3", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findCircleNum(int[][] isConnected) {\n int n = isConnected.length;\n boolean[] visited = new boolean[n];\n int provinceCount = 0;\n\n for (int i = 0; i < n; i++) {\n if (!visited[i]) {\n dfs(isConnected, visited, i);\n provinceCount++;\n }\n }\n\n return provinceCount;\n }\n\n private void dfs(int[][] isConnected, boolean[] visited, int city) {\n visited[city] = true;\n\n for (int j = 0; j < isConnected.length; j++) {\n if (isConnected[city][j] == 1 && !visited[j]) {\n dfs(isConnected, visited, j);\n }\n }\n }\n \n}", + "title": "547. Number of Provinces", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the total number of subarrays whose sum equals to k . A subarray is a contiguous non-empty sequence of elements within an array.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-1000 <= nums[i] <= 1000", + "-10^7 <= k <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1], k = 2\nOutput:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 3\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int subarraySum(int[] nums, int k) {\n Map prefSum = new HashMap<>();\n int count = 0, sum = 0;\n\n prefSum.put(0, 1); // base case\n\n for (int num : nums) {\n sum += num;\n\n if (prefSum.containsKey(sum - k)) {\n count += prefSum.get(sum - k);\n }\n\n prefSum.put(sum, prefSum.getOrDefault(sum, 0) + 1);\n }\n\n return count;\n }\n}", + "title": "560. Subarray Sum Equals K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"\nOutput:true\nExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkInclusion(String s1, String s2) {\n int s1Freq[] = new int[26];\n int s2Freq[] = new int[26];\n\n for (char c : s1.toCharArray()) {\n s1Freq[c - 'a']++;\n }\n\n for (int i = 0; i < s2.length(); i++) {\n s2Freq[s2.charAt(i) - 'a']++;\n\n if (i >= s1.length()) {\n s2Freq[(s2.charAt(i - s1.length())) - 'a']--;\n }\n\n if (Arrays.equals(s1Freq, s2Freq)) {\n return true;\n }\n }\n\n return false;\n }\n}", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise .", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPlaceFlowers(int[] flowerbed, int n) {\n\n if (n == 0)\n return true;\n\n for (int i = 0; i < flowerbed.length; i++) {\n\n if ((i == 0 || flowerbed[i - 1] == 0) &&\n (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) &&\n flowerbed[i] == 0) {\n\n flowerbed[i] = 1;\n n--;\n }\n }\n\n return n <= 0;\n }\n}", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^4", + "tasks[i] is an uppercase English letter.", + "0 <= n <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int leastInterval(char[] tasks, int n) {\n int[] freq = new int[26];\n for (char task : tasks) {\n freq[task - 'A']++;\n }\n\n int maxFreq = 0;\n for (int f : freq) {\n maxFreq = Math.max(maxFreq, f);\n }\n\n int countMax = 0;\n for (int f : freq) {\n if (f == maxFreq)\n countMax++;\n }\n\n return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + countMax);\n }\n}", + "title": "621. Task Scheduler", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c .", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5\nOutput:true\nExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3\nOutput:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean judgeSquareSum(int c) {\n \n if (c < 0) {\n return false;\n }\n \n int left = 0;\n int right = (int) Math.sqrt(c); // Find the upper bound for right\n \n while (left <= right) {\n \n long sum = (long) left * left + (long) right * right; // Use long to prevent overflow\n \n if (sum == c) {\n return true;\n } else if (sum < c) {\n left++;\n } else {\n right--;\n }\n }\n \n return false;\n }\n}", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]\nOutput:[3.00000,14.50000,11.00000]\n\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]\nOutput:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List averageOfLevels(TreeNode root) {\n List result = new ArrayList<>();\n \n if (root == null)\n return result;\n\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n int levelSize = queue.size();\n double sum = 0;\n\n for (int i = 0; i < levelSize; i++) {\n\n TreeNode node = queue.poll();\n sum += node.val;\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(sum / levelSize);\n }\n\n return result;\n }\n}", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums consisting of n elements, and an integer k . Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value . Any answer with a calculation error less than 10 -5 will be accepted.", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= k <= n <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,12,-5,-6,50,3], k = 4\nOutput:12.75000\nExplanation:Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 1\nOutput:5.00000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double findMaxAverage(int[] nums, int k) {\n int sum = 0;\n\n for (int i = 0; i < k; i++) {\n sum += nums[i];\n }\n\n double maxSum = sum;\n for (int i = k; i < nums.length; i++) {\n sum += nums[i] - nums[i - k];\n maxSum = Math.max(maxSum, sum);\n }\n\n return maxSum / k;\n }\n}", + "title": "643. Maximum Average Subarray I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" .", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"\nOutput:\"Radiant\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"\nOutput:\"Dire\"\nExplanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String predictPartyVictory(String senate) {\n int n = senate.length();\n Queue radiant = new LinkedList<>();\n Queue dire = new LinkedList<>();\n\n for (int i = 0; i < n; i++) {\n if (senate.charAt(i) == 'R') {\n radiant.offer(i);\n } else {\n dire.offer(i);\n }\n }\n\n while (!radiant.isEmpty() && !dire.isEmpty()) {\n int r = radiant.poll();\n int d = dire.poll();\n\n if (r < d) {\n radiant.offer(r + n);\n } else {\n dire.offer(d + n);\n }\n }\n\n return radiant.isEmpty() ? \"Dire\" : \"Radiant\";\n }\n}", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing only three types of characters: '(' , ')' and '*' , return true if s is valid . The following rules define a valid string:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"\nOutput:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"(*)\"\nOutput:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(*))\"\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkValidString(String s) {\n int min = 0, max = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (s.charAt(i) == '(') {\n min += 1;\n max += 1;\n } else if (s.charAt(i) == ')') {\n min -= 1;\n max -= 1;\n } else {\n min -= 1;\n max += 1;\n }\n\n if (min < 0) {\n min = 0;\n }\n \n if (max < 0) {\n return false;\n }\n }\n\n return min == 0;\n }\n}", + "title": "678. Valid Parenthesis String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note:", + "description_images": [], + "constraints": [ + "You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "The transaction fee is only charged once for each stock purchase and sale." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2\nOutput:8\nExplanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3\nOutput:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices, int fee) {\n int cash = 0;\n int hold = -prices[0];\n\n for (int i = 1; i < prices.length; i++) {\n cash = Math.max(cash, hold + prices[i] - fee); // Sell\n hold = Math.max(hold, cash - prices[i]); // Buy\n }\n\n return cash;\n }\n}", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order .", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> accountsMerge(List> accounts) {\n Map emailToName = new HashMap<>();\n Map parent = new HashMap<>();\n \n // Step 1: Initialize parent pointers\n for (List account : accounts) {\n String name = account.get(0);\n for (int i = 1; i < account.size(); i++) {\n String email = account.get(i);\n parent.putIfAbsent(email, email);\n emailToName.put(email, name);\n }\n }\n\n // Step 2: Union emails in same account\n for (List account : accounts) {\n String firstEmail = account.get(1);\n for (int i = 2; i < account.size(); i++) {\n union(parent, firstEmail, account.get(i));\n }\n }\n\n // Step 3: Group emails by root parent\n Map> unions = new HashMap<>();\n for (String email : parent.keySet()) {\n String root = find(parent, email);\n unions.putIfAbsent(root, new TreeSet<>());\n unions.get(root).add(email);\n }\n\n // Step 4: Build result\n List> res = new ArrayList<>();\n for (String root : unions.keySet()) {\n List merged = new ArrayList<>();\n merged.add(emailToName.get(root));\n merged.addAll(unions.get(root));\n res.add(merged);\n }\n\n return res;\n }\n\n private String find(Map parent, String s) {\n if (!parent.get(s).equals(s)) {\n parent.put(s, find(parent, parent.get(s)));\n }\n return parent.get(s);\n }\n\n private void union(Map parent, String a, String b) {\n String pa = find(parent, a);\n String pb = find(parent, b);\n if (!pa.equals(pb)) {\n parent.put(pa, pb);\n }\n }\n}", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index . If no such index exists, return -1 .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,3,6,5,6]\nOutput:3\nExplanation:The pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]\nOutput:-1\nExplanation:There is no index that satisfies the conditions in the problem statement.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,-1]\nOutput:0\nExplanation:The pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int pivotIndex(int[] nums) {\n int totalSum = 0;\n\n for (int num : nums) {\n totalSum += num;\n }\n\n int leftSum = 0;\n for (int i = 0; i < nums.length; i++) {\n\n int rigthSum = totalSum - leftSum - nums[i];\n if (leftSum == rigthSum)\n return i;\n leftSum += nums[i];\n }\n\n return -1;\n }\n}", + "title": "724. Find Pivot Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5\nOutput:[[1],[2],[3],[],[]]\nExplanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput:[[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation: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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n ListNode[] result = new ListNode[k];\n int length = 0;\n ListNode current = head;\n\n while (current != null) {\n length++;\n current = current.next;\n }\n\n int partSize = length / k;\n int longerParts = length % k;\n\n current = head;\n for (int i = 0; i < k; i++) {\n result[i] = current;\n int currentPartSize = partSize + (i < longerParts ? 1 : 0);\n\n for (int j = 0; j < currentPartSize - 1 && current != null; j++) {\n current = current.next;\n }\n\n if (current != null) {\n ListNode nextPartHead = current.next;\n current.next = null;\n current = nextPartHead;\n }\n }\n\n return result;\n }\n}", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an image represented by an m x n grid of integers image , where image[i][j] represents the pixel value of the image. You are also given three integers sr , sc , and color . Your task is to perform a flood fill on the image starting from the pixel image[sr][sc] . To perform a flood fill : Return the modified image after performing the flood fill.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg" + ], + "constraints": [ + "m == image.length", + "n == image[i].length", + "1 <= m, n <= 50", + "0 <= image[i][j], color < 2 16", + "0 <= sr < m", + "0 <= sc < n" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n private int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n public int[][] floodFill(int[][] image, int sr, int sc, int color) {\n int oldColor = image[sr][sc];\n if (oldColor == color)\n return image;\n\n dfs(image, sr, sc, oldColor, color);\n\n return image;\n }\n\n private void dfs(int[][] image, int r, int c, int oldColor, int newColor) {\n if (r < 0 || r >= image.length || c < 0 || c >= image[0].length)\n return;\n if (image[r][c] != oldColor)\n return;\n\n image[r][c] = newColor;\n for (int[] dir : directions) {\n dfs(image, r + dir[0], c + dir[1], oldColor, newColor);\n }\n }\n}", + "title": "733. Flood Fill", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]\nOutput:[5,10]\nExplanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]\nOutput:[]\nExplanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]\nOutput:[10]\nExplanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Deque stack = new ArrayDeque<>();\n\n for (int a : asteroids) {\n boolean alive = true;\n\n while (alive && a < 0 && !stack.isEmpty() && stack.peek() > 0) {\n int top = stack.peek();\n\n if (top < -a) {\n stack.pop();\n } else if (top == -a) {\n stack.pop();\n alive = false;\n } else {\n alive = false;\n }\n }\n\n if (alive) {\n stack.push(a);\n }\n }\n\n int[] result = new int[stack.size()];\n for (int i = stack.size() - 1; i >= 0; i--) {\n result[i] = stack.pop();\n }\n\n return result;\n }\n}", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= temperatures.length <= 10^5", + "30 <= temperatures[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:temperatures = [73,74,75,71,69,72,76,73]\nOutput:[1,1,4,2,1,1,0,0]", + "image": null + }, + { + "text": "Example 2: Input:temperatures = [30,40,50,60]\nOutput:[1,1,1,0]", + "image": null + }, + { + "text": "Example 3: Input:temperatures = [30,60,90]\nOutput:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] dailyTemperatures(int[] temperatures) {\n int n = temperatures.length;\n int[] answer = new int[n];\n Deque stack = new ArrayDeque<>();\n\n for (int i = 0; i < n; i++) {\n\n while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {\n int prevIndex = stack.pop();\n answer[prevIndex] = i - prevIndex;\n }\n\n stack.push(i);\n }\n\n return answer;\n }\n}", + "title": "739. Daily Temperatures", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "2 <= cost.length <= 1000", + "0 <= cost[i] <= 999" + ], + "examples": [ + { + "text": "Example 1: Input:cost = [10,15,20]\nOutput:15\nExplanation:You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.", + "image": null + }, + { + "text": "Example 2: Input:cost = [1,100,1,1,1,100,1,1,100,1]\nOutput:6\nExplanation:You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int first = cost[0];\n int second = cost[1];\n\n if (n <= 2)\n return Math.min(first, second);\n\n for (int i = 2; i < n; i++) {\n int curr = cost[i] + Math.min(first, second);\n first = second;\n second = curr;\n }\n\n return Math.min(first, second);\n }\n}", + "title": "747. Min Cost Climbing Stairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababcbacadefegdehijhklij\"\nOutput:[9,7,8]\nExplanation:The partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.", + "image": null + }, + { + "text": "Example 2: Input:s = \"eccbbbbdec\"\nOutput:[10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List partitionLabels(String s) {\n List result = new ArrayList<>();\n int[] lastIndex = new int[26];\n\n for (int i = 0; i < s.length(); i++) {\n lastIndex[s.charAt(i) - 'a'] = i;\n }\n\n int start = 0, end = 0;\n\n for (int i = 0; i < s.length(); i++) {\n end = Math.max(end, lastIndex[s.charAt(i) - 'a']);\n if (i == end) {\n result.add(end - start + 1);\n start = i + 1;\n }\n }\n\n return result;\n }\n}", + "title": "768. Partition Labels", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. Return the root of the Quad-Tree representing grid . A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 .", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer.", + "isLeaf : True if the node is a leaf node on the tree or False if the node has four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]\nOutput:[[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation:The explanation of this example is shown below:\nNotice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nOutput:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a QuadTree node.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n \n public Node() {\n this.val = false;\n this.isLeaf = false;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = topLeft;\n this.topRight = topRight;\n this.bottomLeft = bottomLeft;\n this.bottomRight = bottomRight;\n }\n}\n*/\n\nclass Solution {\n public Node construct(int[][] grid) {\n return buildQuadTree(grid, 0, 0, grid.length);\n }\n\n private Node buildQuadTree(int[][] grid, int row, int col, int size) {\n\n if (isUniform(grid, row, col, size)) {\n return new Node(grid[row][col] == 1, true);\n }\n\n int half = size / 2;\n Node topLeft = buildQuadTree(grid, row, col, half);\n Node topRight = buildQuadTree(grid, row, col + half, half);\n Node bottomLeft = buildQuadTree(grid, row + half, col, half);\n Node bottomRight = buildQuadTree(grid, row + half, col + half, half);\n\n return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);\n }\n\n private boolean isUniform(int[][] grid, int row, int col, int size) {\n int val = grid[row][col];\n\n for (int i = row; i < row + size; i++) {\n for (int j = col; j < col + size; j++) {\n if (grid[i][j] != val)\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "772. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2\nOutput:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5\nOutput:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode searchBST(TreeNode root, int val) {\n if (root == null)\n return null;\n\n if (root.val == val)\n return root;\n else if (root.val < val)\n return searchBST(root.right, val);\n else\n return searchBST(root.left, val);\n }\n}", + "title": "783. Search in a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9\nOutput:4\nExplanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2\nOutput:-1\nExplanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n\n while (left <= right) {\n int mid = (left + right) >> 1;\n\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n return -1;\n }\n}", + "title": "792. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3\nOutput:5\nExplanation:The five different ways are shown above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int MOD = 1_000_000_007;\n\n public int numTilings(int n) {\n if (n == 0)\n return 1;\n if (n == 1)\n return 1;\n if (n == 2)\n return 2;\n\n long[] dp = new long[n + 1];\n dp[0] = 1;\n dp[1] = 1;\n dp[2] = 2;\n\n for (int i = 3; i <= n; i++) {\n dp[i] = (2 * dp[i - 1] + dp[i - 3]) % MOD;\n }\n\n return (int) dp[n];\n }\n}", + "title": "806. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n jobs and m workers. You are given three arrays: difficulty , profit , and worker where: Every worker can be assigned at most one job , but one job can be completed multiple times . Return the maximum profit we can achieve after assigning the workers to the jobs.", + "description_images": [], + "constraints": [ + "difficulty[i] and profit[i] are the difficulty and the profit of the i th job, and", + "worker[j] is the ability of j th worker (i.e., the j th worker can only complete a job with difficulty at most worker[j] )." + ], + "examples": [ + { + "text": "Example 1: Input:difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput:100\nExplanation:Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.", + "image": null + }, + { + "text": "Example 2: Input:difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n \n int n = difficulty.length;\n int m = worker.length;\n\n // Combine and sort jobs based on difficulty\n int[][] jobs = new int[n][2];\n \n for (int i = 0; i < n; i++) {\n \n jobs[i][0] = difficulty[i];\n jobs[i][1] = profit[i];\n }\n \n Arrays.sort(jobs, (a, b) -> a[0] - b[0]);\n\n // Sort workers\n Arrays.sort(worker);\n\n // Track the maximum profit available for any given difficulty\n int maxProfit = 0;\n int jobIndex = 0;\n int totalProfit = 0;\n\n // Assign jobs to workers\n for (int ability : worker) {\n \n while (jobIndex < n && ability >= jobs[jobIndex][0]) {\n \n maxProfit = Math.max(maxProfit, jobs[jobIndex][1]);\n jobIndex++;\n }\n \n totalProfit += maxProfit;\n }\n\n return totalProfit;\n }\n}", + "title": "826. Most Profit Assigning Work", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the i th bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target . You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target . Return -1 if it is not possible.", + "description_images": [], + "constraints": [ + "For example, if routes[0] = [1, 5, 7] , this means that the 0 th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever." + ], + "examples": [ + { + "text": "Example 1: Input:routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput:2\nExplanation:The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.", + "image": null + }, + { + "text": "Example 2: Input:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target)\n return 0;\n\n Map> stopToBuses = new HashMap<>();\n\n for (int i = 0; i < routes.length; i++) {\n for (int stop : routes[i]) {\n stopToBuses.computeIfAbsent(stop, k -> new ArrayList<>()).add(i);\n }\n }\n\n Queue queue = new LinkedList<>();\n Set visitedStops = new HashSet<>();\n Set visitedBuses = new HashSet<>();\n\n for (int bus : stopToBuses.getOrDefault(source, new ArrayList<>())) {\n queue.offer(bus);\n visitedBuses.add(bus);\n }\n\n int busesTaken = 1;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n int bus = queue.poll();\n\n for (int stop : routes[bus]) {\n if (stop == target)\n return busesTaken;\n\n if (visitedStops.contains(stop))\n continue;\n visitedStops.add(stop);\n\n for (int nextBus : stopToBuses.getOrDefault(stop, new ArrayList<>())) {\n if (!visitedBuses.contains(nextBus)) {\n visitedBuses.add(nextBus);\n queue.offer(nextBus);\n }\n }\n }\n }\n\n busesTaken++;\n }\n\n return -1;\n }\n}", + "title": "833. Bus Routes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput:true\nExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4\nOutput:false\nExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isNStraightHand(int[] hand, int groupSize) {\n \n boolean output = false;\n \n if (hand.length % groupSize != 0) return false;\n \n TreeMap countMap = new TreeMap<>();\n \n for (int card : hand) {\n countMap.put(card, countMap.getOrDefault(card, 0) + 1);\n }\n\n while (!countMap.isEmpty()) {\n int first = countMap.firstKey();\n for (int i = 0; i < groupSize; i++) {\n int current = first + i;\n if (!countMap.containsKey(current)) return false;\n int count = countMap.get(current);\n if (count == 1) {\n countMap.remove(current);\n } else {\n countMap.put(current, count - 1);\n }\n }\n }\n\n return true;\n }\n}", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise .", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]\nOutput:true\nExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]\nOutput:false\nExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canVisitAllRooms(List> rooms) {\n int n = rooms.size();\n boolean[] visited = new boolean[n];\n Queue queue = new LinkedList<>();\n queue.offer(0);\n visited[0] = true;\n\n while (!queue.isEmpty()) {\n int room = queue.poll();\n for (int key : rooms.get(room)) {\n if (!visited[key]) {\n visited[key] = true;\n queue.offer(key);\n }\n }\n }\n\n for (boolean v : visited) {\n if (!v)\n return false;\n }\n\n return true;\n }\n}", + "title": "871. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]\nOutput:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n List list1 = new ArrayList<>();\n List list2 = new ArrayList<>();\n\n helper(list1, root1);\n helper(list2, root2);\n\n return list1.equals(list2) ? true : false;\n }\n\n private void helper(List list, TreeNode root) {\n if (root == null)\n return;\n\n if (root.left == null && root.right == null) {\n list.add(root.val);\n return;\n\n } else {\n helper(list, root.left);\n helper(list, root.right);\n }\n }\n}", + "title": "904. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 .", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8\nOutput:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5\nOutput:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6\nOutput:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public static int minEatingSpeed(int[] piles, int h) {\n int low = 1;\n int high = Arrays.stream(piles).max().getAsInt();\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n\n if (canFinish(piles, mid, h)) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n return low;\n }\n\n private static boolean canFinish(int[] piles, int k, int h) {\n int hours = 0;\n\n for (int pile : piles) {\n hours += (pile + k - 1) / k; // ceil(pile / k)\n }\n\n return hours <= h;\n }\n\n}", + "title": "907. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return the middle node of the linked list . If there are two middle nodes, return the second middle node.", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 100] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]\nOutput:[3,4,5]\nExplanation:The middle node of the list is node 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6]\nOutput:[4,5,6]\nExplanation:Since the list has two middle nodes with values 3 and 4, we return the second one.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode middleNode(ListNode head) {\n if (head == null || head.next == null)\n return head;\n \n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n}", + "title": "908. Middle of the Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Implement the StockSpanner class:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class StockSpanner {\n private Deque stack;\n\n public StockSpanner() {\n stack = new ArrayDeque<>();\n }\n\n public int next(int price) {\n int span = 1;\n\n while (!stack.isEmpty() && stack.peek()[0] <= price) {\n span += stack.pop()[1];\n }\n\n stack.push(new int[] { price, span });\n return span;\n }\n\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */", + "title": "937. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix board where the cells are labeled from 1 to n 2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0] ) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr , do the following: A board square on row r and column c has a snake or ladder if board[r][c] != -1 . The destination of that snake or ladder is board[r][c] . Squares 1 and n 2 are not the starting points of any snake or ladder. Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. Return the least number of dice rolls required to reach the square n 2 . If it is not possible to reach the square, return -1 .", + "description_images": [], + "constraints": [ + "Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n 2 )] . This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next .", + "The game ends when you reach the square n 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput:4\nExplanation:In the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.", + "image": "https://assets.leetcode.com/uploads/2018/09/23/snakes.png" + }, + { + "text": "Example 2: Input:board = [[-1,-1],[-1,3]]\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int snakesAndLadders(int[][] board) { // BFS\n int N = board.length;\n int[] flattenBoard = new int[N * N + 1]; // 1-based indexing\n boolean leftToRight = true;\n int index = 1;\n\n // Step 1: Flatten 2D board into 1D array\n for (int row = N - 1; row >= 0; row--) {\n\n if (leftToRight) {\n for (int col = 0; col < N; col++) {\n flattenBoard[index++] = board[row][col];\n }\n } else {\n for (int col = N - 1; col >= 0; col--) {\n flattenBoard[index++] = board[row][col];\n }\n }\n\n leftToRight = !leftToRight;\n }\n\n // Step 2: BFS to find the shortest path\n Queue queue = new LinkedList<>();\n boolean[] visited = new boolean[N * N + 1];\n \n queue.offer(new int[] { 1, 0 }); // {current square, moves}\n visited[1] = true;\n\n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n int pos = current[0], moves = current[1];\n\n // If we reached the last square, return moves\n if (pos == N * N)\n return moves;\n\n // Roll dice (1 to 6)\n for (int i = 1; i <= 6; i++) {\n int nextPos = pos + i;\n\n if (nextPos > N * N)\n break; // Out of bounds\n\n if (flattenBoard[nextPos] != -1) {\n nextPos = flattenBoard[nextPos]; // Ladder or snake\n }\n\n if (!visited[nextPos]) {\n visited[nextPos] = true;\n queue.offer(new int[] { nextPos, moves + 1 });\n }\n }\n }\n\n return -1; // No way to reach the last square\n }\n}", + "title": "945. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n .", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]\nOutput:3\nExplanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]\nOutput:10\nExplanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]\nOutput:-2\nExplanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubarraySumCircular(int[] nums) {\n int maxKadane = kadane(nums);\n\n int totalSum = 0;\n for (int i = 0; i < nums.length; i++) {\n totalSum += nums[i];\n nums[i] = -nums[i];\n }\n\n int minKadane = kadane(nums);\n int maxCircular = totalSum + minKadane;\n\n if (maxCircular == 0)\n return maxKadane;\n\n return Math.max(maxKadane, maxCircular);\n }\n\n private int kadane(int[] nums) {\n int maxSum = Integer.MIN_VALUE, currentSum = 0;\n for (int num : nums) {\n currentSum = Math.max(num, currentSum + num);\n maxSum = Math.max(maxSum, currentSum);\n }\n\n return maxSum;\n }\n}", + "title": "954. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "class RecentCounter {\n\n private Queue queue;\n\n public RecentCounter() {\n queue = new LinkedList<>();\n }\n\n public int ping(int t) {\n queue.offer(t);\n\n while(queue.peek() < t - 3000) {\n queue.poll();\n }\n\n return queue.size();\n }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */", + "title": "969. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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).", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1\nOutput:[[-2,2]]\nExplanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput:[[3,3],[-2,4]]\nExplanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] kClosest(int[][] points, int K) {\n \n PriorityQueue heap = new PriorityQueue(new Comparator() { \n @Override\n public int compare(int[] left, int[] right) {\n return getDistance(right) - getDistance(left);\n }\n });\n \n for (int[] point: points) {\n heap.add(point);\n \n if (heap.size() > K)\n heap.poll();\n }\n \n int[][] result = new int[K][2];\n while (K > 0)\n result[--K] = heap.poll();\n \n return result;\n \n }\n \n private int getDistance(int [] point) {\n return point[0] * point[0] + point[1] * point[1];\n }\n}", + "title": "1014. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap {\n\n private Map> map;\n\n public TimeMap() {\n map = new HashMap<>();\n }\n\n // O(log n)\n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new TreeMap<>());\n map.get(key).put(timestamp, value);\n }\n \n // O(log n)\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) \n return \"\";\n\n TreeMap tree = map.get(key);\n Integer floorKey = tree.floorKey(timestamp);\n\n if (floorKey == null) \n return \"\"; \n\n return tree.get(floorKey);\n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */", + "title": "1023. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n grid where each cell can have one of three values: 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 .", + "description_images": [], + "constraints": [ + "0 representing an empty cell,", + "1 representing a fresh orange, or", + "2 representing a rotten orange." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput:4", + "image": "https://assets.leetcode.com/uploads/2019/02/16/oranges.png" + }, + { + "text": "Example 2: Input:grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput:-1\nExplanation:The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[0,2]]\nOutput:0\nExplanation:Since there are already no fresh oranges at minute 0, the answer is just 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int orangesRotting(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n Queue queue = new LinkedList<>();\n int freshCount = 0;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n\n if (grid[r][c] == 2) {\n queue.offer(new int[] { r, c });\n } else if (grid[r][c] == 1) {\n freshCount++;\n }\n }\n }\n\n int minutes = 0;\n int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty() && freshCount >= 1) {\n int size = queue.size();\n minutes++;\n\n for (int i = 0; i < size; i++) {\n int[] pos = queue.poll();\n int r = pos[0], c = pos[1];\n\n for (int[] d : directions) {\n int newR = r + d[0];\n int newC = c + d[1];\n\n if (newR >= 0 && newR < rows && newC >= 0 && newC < cols && grid[newR][newC] == 1) {\n grid[newR][newC] = 2;\n queue.offer(new int[] { newR, newC });\n freshCount--;\n }\n }\n }\n }\n\n return freshCount == 0 ? minutes : -1;\n }\n}", + "title": "1036. Rotting Oranges", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput:6\nExplanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput:10\nExplanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestOnes(int[] nums, int k) {\n int left = 0, maxLen = 0, zeroCount = 0;\n\n for (int right = 0; right < nums.length; right++) {\n if (nums[right] == 0) {\n zeroCount++;\n }\n\n while (zeroCount > k) {\n if (nums[left] == 0)\n zeroCount--;\n left++;\n }\n maxLen = Math.max(maxLen, right - left + 1);\n }\n\n return maxLen;\n }\n}", + "title": "1046. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day .", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput:16\nExplanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1\nOutput:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n int n = customers.length;\n int unrealizedCustomers = 0;\n\n // Calculate initial number of unrealized customers in first 'minutes' window\n for (int i = 0; i < minutes; i++) {\n unrealizedCustomers += customers[i] * grumpy[i];\n }\n\n int maxUnrealizedCustomers = unrealizedCustomers;\n\n // Slide the 'minutes' window across the rest of the customers array\n for (int i = minutes; i < n; i++) {\n // Add the current minute's unsatisfied customers if the owner is grumpy\n // and remove the customers that are out of the current window\n unrealizedCustomers += customers[i] * grumpy[i];\n unrealizedCustomers -= customers[i - minutes] * grumpy[i - minutes];\n\n // Update the maximum unrealized customers\n maxUnrealizedCustomers = Math.max(\n maxUnrealizedCustomers,\n unrealizedCustomers\n );\n }\n\n // Start with maximum possible satisfied customers due to secret technique\n int totalCustomers = maxUnrealizedCustomers;\n\n // Add the satisfied customers during non-grumpy minutes\n for (int i = 0; i < customers.length; i++) {\n totalCustomers += customers[i] * (1 - grumpy[i]);\n }\n\n // Return the maximum number of satisfied customers\n return totalCustomers;\n }\n}", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, the level of its root is 1 , the level of its children is 2 , and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal .", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,7,0,7,-8,null,null]\nOutput:2\nExplanation:Level 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" + }, + { + "text": "Example 2: Input:root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxLevelSum(TreeNode root) {\n if (root == null)\n return 0;\n\n Queue queue = new LinkedList<>();\n queue.add(root);\n\n int maxSum = Integer.MIN_VALUE;\n int maxLevel = 1;\n int level = 1;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n int levelSum = 0;\n\n for (int i = 0; i < size; i++) {\n TreeNode curr = queue.poll();\n levelSum += curr.val;\n\n if (curr.left != null)\n queue.add(curr.left);\n if (curr.right != null)\n queue.add(curr.right);\n }\n\n if (levelSum > maxSum) {\n maxSum = levelSum;\n maxLevel = level;\n }\n\n level++;\n }\n\n return maxLevel;\n }\n}", + "title": "1116. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 .", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"\nOutput:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"\nOutput:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String gcdOfStrings(String str1, String str2) {\n\n if (str1.length() < str2.length())\n return gcdOfStrings(str2, str1);\n\n if (!str1.startsWith(str2))\n return \"\";\n\n if (str2.isEmpty())\n return str1;\n\n return gcdOfStrings(str1.substring(str2.length()), str2);\n }\n}", + "title": "1146. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose you are given the following code: The same instance of FooBar will be passed to two different threads: Modify the given program to output \"foobar\" n times.", + "description_images": [], + "constraints": [ + "thread A will call foo() , while", + "thread B will call bar() ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1\nOutput:\"foobar\"\nExplanation:There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n\"foobar\" is being output 1 time.", + "image": null + }, + { + "text": "Example 2: Input:n = 2\nOutput:\"foobarfoobar\"\nExplanation:\"foobar\" is being output 2 times.", + "image": null + }, + { + "text": "class FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "public class FooBar {\n private int n;\n private Semaphore fooSemaphore = new Semaphore(1);\n private Semaphore barSemaphore = new Semaphore(0);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n fooSemaphore.acquire();\n printFoo.run();\n barSemaphore.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n barSemaphore.acquire();\n printBar.run();\n fooSemaphore.release();\n }\n }\n}", + "title": "1187. Print FooBar Alternately", + "topic": "Concurrency" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a function printNumber that can be called with an integer parameter and prints it to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero , even , and odd . The same instance of ZeroEvenOdd will be passed to three different threads: Modify the given class to output the series \"010203040506...\" where the length of the series must be 2n . Implement the ZeroEvenOdd class:", + "description_images": [], + "constraints": [ + "For example, calling printNumber(7) prints 7 to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2\nOutput:\"0102\"\nExplanation:There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n\"0102\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:n = 5\nOutput:\"0102030405\"", + "image": null + } + ], + "follow_up": null, + "solution": "class ZeroEvenOdd {\n private final int n;\n private final Lock lock = new ReentrantLock();\n private final Condition zeroCondition = lock.newCondition();\n private final Condition numbCondition = lock.newCondition();\n private volatile boolean zeroTime = true;\n private final AtomicInteger curr = new AtomicInteger(1);\n\n public ZeroEvenOdd(int n) {\n this.n = n;\n }\n\n // printNumber.accept(x) outputs \"x\", where x is an integer.\n public void zero(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() <= n) {\n try {\n lock.lock();\n while (!zeroTime) {\n zeroCondition.await();\n }\n if (curr.get() <= n) {\n printNumber.accept(0);\n }\n\n zeroTime = false;\n numbCondition.signalAll();\n } finally {\n lock.unlock();\n }\n }\n }\n\n public void even(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() < n) {\n try {\n lock.lock();\n while (zeroTime || curr.get() % 2 != 0) {\n numbCondition.await();\n }\n\n if (curr.get() <= n) {\n printNumber.accept(curr.get());\n }\n\n curr.getAndIncrement();\n zeroTime = true;\n zeroCondition.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n\n public void odd(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() <= n) {\n try {\n lock.lock();\n while (zeroTime || curr.get() % 2 == 0) {\n numbCondition.await();\n }\n\n if (curr.get() <= n) {\n printNumber.accept(curr.get());\n }\n curr.getAndIncrement();\n zeroTime = true;\n zeroCondition.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n}", + "title": "1216. Print Zero Even Odd", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n .", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4\nOutput:4\nExplanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25\nOutput:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tribonacci(int n) {\n if (n == 0)\n return 0;\n if (n == 1 || n == 2)\n return 1;\n\n int t0 = 0, t1 = 1, t2 = 1, tn = 0;\n\n for (int i = 3; i <= n; i++) {\n tn = t0 + t1 + t2;\n t0 = t1;\n t1 = t2;\n t2 = tn;\n }\n\n return tn;\n }\n}", + "title": "1236. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3\nOutput:2\nExplanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1\nOutput:0\nExplanation:There are no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int numberOfSubarrays(int[] nums, int k) {\n Queue oddIndices = new LinkedList<>();\n int subarrays = 0;\n int lastPopped = -1;\n int initialGap = -1;\n\n for (int i = 0; i < nums.length; i++) {\n // If element is odd, append its index to the list.\n if (nums[i] % 2 == 1) {\n oddIndices.offer(i);\n }\n // If the number of odd numbers exceeds k, remove the first odd index.\n if (oddIndices.size() > k) {\n lastPopped = oddIndices.poll();\n }\n // If there are exactly k odd numbers, add the number of even numbers\n // in the beginning of the subarray to the result.\n if (oddIndices.size() == k) {\n initialGap = oddIndices.element() - lastPopped;\n subarrays += initialGap;\n }\n }\n\n return subarrays;\n }\n}", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings.", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"\nOutput:3\nExplanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"\nOutput:3\nExplanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"\nOutput:0\nExplanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestCommonSubsequence(String text1, String text2) {\n int m = text1.length(), n = text2.length();\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n \n if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n dp[i][j] = 1 + dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n return dp[m][n];\n }\n}", + "title": "1250. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]\nOutput:[3,1,2,1,1,0]\nExplanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]\nOutput:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] canSeePersonsCount(int[] heights) {\n int n = heights.length;\n int[] res = new int[n];\n Deque stack = new ArrayDeque<>();\n\n for (int i = n - 1; i >= 0; i--) {\n int count = 0;\n\n while (!stack.isEmpty() && heights[i] > stack.peek()) {\n stack.pop();\n count++;\n }\n\n if (!stack.isEmpty())\n count++; // taller or equal \n res[i] = count;\n stack.push(heights[i]);\n }\n\n return res;\n }\n}", + "title": "1305. Number of Visible People in a Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique or false otherwise .", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]\nOutput:true\nExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]\nOutput:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean uniqueOccurrences(int[] arr) {\n Map freqMap = new HashMap<>();\n\n for (int num : arr) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n\n Set seenFreq = new HashSet<>();\n for (int count : freqMap.values()) {\n if (!seenFreq.add(count)) {\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "1319. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order.", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]\nOutput:[[1,3],[4,6]]\nExplanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums1. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput:[[3],[]]\nExplanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n Set set1 = new HashSet<>();\n Set set2 = new HashSet<>();\n\n for (int n : nums1)\n set1.add(n);\n \n for (int n : nums2)\n set2.add(n);\n\n List onlyInNums1 = new ArrayList<>();\n List onlyInNums2 = new ArrayList<>();\n\n for (int n : set1) {\n if (!set2.contains(n)) {\n onlyInNums1.add(n);\n }\n }\n\n for (int n : set2) {\n if (!set1.contains(n)) {\n onlyInNums2.add(n);\n }\n }\n\n return List.of(onlyInNums1, onlyInNums2);\n }\n}", + "title": "1392. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed .", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput:[[\"mobile\",\"moneypot\",\"monitor\"],[\"mobile\",\"moneypot\",\"monitor\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"]]\nExplanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"].\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"].\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"].", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"\nOutput:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\nExplanation:The only word \"havana\" will be always suggested while typing the search word.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products);\n List> result = new ArrayList<>();\n int n = products.length;\n String prefix = \"\";\n \n for (char ch : searchWord.toCharArray()) {\n prefix += ch;\n List suggestions = new ArrayList<>();\n\n int start = lowerBound(products, prefix);\n\n for (int i = start; i < Math.min(start + 3, n); i++) {\n if (products[i].startsWith(prefix)) {\n suggestions.add(products[i]);\n } else {\n break;\n }\n }\n result.add(suggestions);\n }\n\n return result;\n }\n\n private int lowerBound(String[] products, String prefix) {\n int low = 0, high = products.length;\n\n while (low < high) {\n int mid = (low + high) >> 1;\n\n if (products[mid].compareTo(prefix) < 0) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n }\n}", + "title": "1397. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4\nOutput:2\nExplanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5\nOutput:4\nExplanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums, int limit) {\n Deque maxDeque = new LinkedList<>();\n Deque minDeque = new LinkedList<>();\n\n int left = 0, maxLen = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n while (!maxDeque.isEmpty() && nums[right] > maxDeque.peekLast()) {\n maxDeque.pollLast();\n }\n maxDeque.offerLast(nums[right]);\n\n while (!minDeque.isEmpty() && nums[right] < minDeque.peekLast()) {\n minDeque.pollLast();\n }\n minDeque.offerLast(nums[right]);\n\n while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {\n if (maxDeque.peekFirst() == nums[left])\n maxDeque.pollFirst();\n if (minDeque.peekFirst() == nums[left])\n minDeque.pollFirst();\n left++;\n }\n\n maxLen = Math.max(maxLen, right - left + 1);\n }\n\n return maxLen;\n }\n}", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given 3 positives numbers a , b and c . Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png" + ], + "constraints": [ + "1 <= a <= 10^9", + "1 <= b <= 10^9", + "1 <= c <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 6, c = 5\nOutput:3\nExplanation:After flips a = 1 , b = 4 , c = 5 such that (aORb==c)", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 2, c = 7\nOutput:1", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 2, c = 3\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(int a, int b, int c) {\n int flips = 0;\n\n for (int i = 0; i < 32; i++) {\n int aBit = (a >> i) & 1;\n int bBit = (b >> i) & 1;\n int cBit = (c >> i) & 1;\n\n int orBit = aBit | bBit;\n\n if (orBit == cBit) {\n continue; // no flips needed\n }\n\n if (cBit == 0) {\n flips += aBit + bBit; // need to flip 1s to 0\n } else {\n flips += 1; // cBit == 1 but orBit == 0 → flip one to 1\n }\n }\n\n return flips;\n }\n}", + "title": "1441. Minimum Flips to Make a OR b Equal to c", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree .", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]\nOutput:3\nExplanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput:4\nExplanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxPath = 0;\n\n public int longestZigZag(TreeNode root) {\n if (root == null)\n return 0;\n\n dfs(root.left, 1, true);\n dfs(root.right, 1, false);\n\n return maxPath;\n }\n\n private void dfs(TreeNode node, int length, boolean isLeft) {\n if (node == null)\n return;\n\n maxPath = Math.max(maxPath, length);\n\n if (isLeft) {\n dfs(node.right, length + 1, false); // turn right\n dfs(node.left, 1, true); // reset\n } else {\n dfs(node.left, length + 1, true); // turn left\n dfs(node.right, 1, false); // reset\n }\n }\n}", + "title": "1474. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array bloomDay , an integer m and an integer k . You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the i th flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden . If it is impossible to make m bouquets return -1 .", + "description_images": [], + "constraints": [ + "bloomDay.length == n", + "1 <= n <= 10^5", + "1 <= bloomDay[i] <= 10^9", + "1 <= m <= 10^6", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput:3\nExplanation:Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput:-1\nExplanation:We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.", + "image": null + }, + { + "text": "Example 3: Input:bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput:12\nExplanation:We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n // Return the number of maximum bouquets that can be made on day mid.\n private int getNumOfBouquets(int[] bloomDay, int mid, int k) {\n int numOfBouquets = 0;\n int count = 0;\n\n for (int i = 0; i < bloomDay.length; i++) {\n // If the flower is bloomed, add to the set. Else reset the count.\n if (bloomDay[i] <= mid) {\n count++;\n } else {\n count = 0;\n }\n\n if (count == k) {\n numOfBouquets++;\n count = 0;\n }\n }\n\n return numOfBouquets;\n }\n\n public int minDays(int[] bloomDay, int m, int k) {\n int start = 0;\n int end = 0;\n for (int day : bloomDay) {\n end = Math.max(end, day);\n }\n\n int minDays = -1;\n while (start <= end) {\n int mid = (start + end) / 2;\n\n if (getNumOfBouquets(bloomDay, mid, k) >= m) {\n minDays = mid;\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n\n return minDays;\n }\n}", + "title": "1482. Minimum Number of Days to Make m Bouquets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system .", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput:\"ACB\"\nExplanation:Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]\nOutput:\"XWYZ\"\nExplanation:X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation:Only one voter, so their votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String rankTeams(String[] votes) {\n if (votes == null || votes.length == 0) return \"\";\n\n int numPositions = votes[0].length();\n Map countMap = new HashMap<>();\n\n // Initialize map\n for (char c : votes[0].toCharArray()) {\n countMap.put(c, new int[numPositions]);\n }\n\n // Count votes\n for (String vote : votes) {\n for (int i = 0; i < vote.length(); i++) {\n char team = vote.charAt(i);\n countMap.get(team)[i]++;\n }\n }\n\n // Sort with custom comparator\n List teams = new ArrayList<>(countMap.keySet());\n teams.sort((a, b) -> {\n for (int i = 0; i < numPositions; i++) {\n if (countMap.get(a)[i] != countMap.get(b)[i]) {\n return countMap.get(b)[i] - countMap.get(a)[i];\n }\n }\n return Character.compare(a, b);\n });\n\n // Build result\n StringBuilder sb = new StringBuilder();\n for (char c : teams) sb.append(c);\n return sb.toString();\n }\n}\n", + "title": "1483. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies.", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3\nOutput:[true,true,true,false,true]\nExplanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1\nOutput:[true,false,false,false,false]\nExplanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10\nOutput:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List kidsWithCandies(int[] candies, int extraCandies) {\n int maxCandies = 0;\n\n for (int candy : candies) {\n if (candy > maxCandies) {\n maxCandies = candy;\n }\n }\n\n List result = new ArrayList<>();\n for (int candy : candies) {\n result.add(candy + extraCandies >= maxCandies);\n }\n\n return result;\n }\n}", + "title": "1528. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]\nOutput:4\nExplanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]\nOutput:3\nExplanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]\nOutput:1\nExplanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int goodNodes(TreeNode root) {\n return dfs(root, root.val);\n }\n\n private int dfs(TreeNode node, int maxSoFar) {\n if (node == null)\n return 0;\n\n int good = node.val >= maxSoFar ? 1 : 0;\n maxSoFar = Math.max(maxSoFar, node.val);\n good += dfs(node.left, maxSoFar);\n good += dfs(node.right, maxSoFar);\n\n return good;\n }\n}", + "title": "1544. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' .", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3\nOutput:3\nExplanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2\nOutput:2\nExplanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3\nOutput:2\nExplanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxVowels(String s, int k) {\n Set vowels = Set.of('a', 'e', 'i', 'o', 'u');\n int maxVowels = 0, currVowels = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (vowels.contains(s.charAt(i))) {\n currVowels++;\n }\n\n if (i >= k && vowels.contains(s.charAt(i - k))) {\n currVowels--;\n }\n\n maxVowels = Math.max(maxVowels, currVowels);\n }\n\n return maxVowels;\n }\n}", + "title": "1567. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput:3\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput:2\nExplanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]\nOutput:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minReorder(int n, int[][] connections) {\n Map> graph = new HashMap<>();\n Set directedEdges = new HashSet<>();\n\n for (int[] conn : connections) {\n int from = conn[0], to = conn[1];\n graph.computeIfAbsent(from, x -> new ArrayList<>()).add(to);\n graph.computeIfAbsent(to, x -> new ArrayList<>()).add(from);\n directedEdges.add(from + \"->\" + to);\n }\n\n boolean[] visited = new boolean[n];\n return dfs(0, graph, directedEdges, visited);\n }\n\n private int dfs(int curr, Map> graph, Set directedEdges, boolean[] visited) {\n visited[curr] = true;\n int changes = 0;\n\n for (int neighbor : graph.getOrDefault(curr, new ArrayList<>())) {\n\n if (!visited[neighbor]) {\n if (directedEdges.contains(curr + \"->\" + neighbor)) {\n changes++;\n }\n changes += dfs(neighbor, graph, directedEdges, visited);\n }\n }\n\n return changes;\n }\n}", + "title": "1576. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]\nOutput:3\nExplanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]\nOutput:5\nExplanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]\nOutput:2\nExplanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums) {\n int left = 0, maxLength = 0, zeroCount = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n if (nums[right] == 0)\n zeroCount++;\n\n while (zeroCount > 1) {\n\n if (nums[left] == 0)\n zeroCount--;\n left++;\n }\n\n maxLength = Math.max(maxLength, right - left);\n }\n\n return maxLength;\n }\n}", + "title": "1586. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise.", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"\nOutput:true\nExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"\nOutput:false\nExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"\nOutput:true\nExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"\nApply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length())\n return false;\n\n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n\n for (int i = 0; i < word1.length(); i++) {\n freq1[word1.charAt(i) - 'a']++;\n freq2[word2.charAt(i) - 'a']++;\n }\n\n for (int i = 0; i < 26; i++) {\n if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {\n return false;\n }\n }\n\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n\n return Arrays.equals(freq1, freq2);\n }\n}", + "title": "1777. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5\nOutput:2\nExplanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6\nOutput:1\nExplanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxOperations(int[] nums, int k) {\n Map freq = new HashMap<>();\n int count = 0;\n\n for (int num : nums) {\n int complement = k - num;\n\n if (freq.getOrDefault(complement, 0) > 0) {\n count++;\n freq.put(complement, freq.get(complement) - 1);\n } else {\n freq.put(num, freq.getOrDefault(num, 0) + 1);\n }\n }\n\n return count;\n }\n}", + "title": "1798. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0 . You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i ​​​​​​ and i + 1 for all ( 0 <= i < n) . Return the highest altitude of a point.", + "description_images": [], + "constraints": [ + "n == gain.length", + "1 <= n <= 100", + "-100 <= gain[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:gain = [-5,1,5,0,-7]\nOutput:1\nExplanation:The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.", + "image": null + }, + { + "text": "Example 2: Input:gain = [-4,-3,-2,-1,4,3,2]\nOutput:0\nExplanation:The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestAltitude(int[] gain) {\n int altitude = 0, maxAltitude = 0;\n\n for (int i : gain) {\n altitude += i;\n maxAltitude = Math.max(maxAltitude, altitude);\n }\n\n return maxAltitude;\n }\n}", + "title": "1833. Find the Highest Altitude", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them .", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]\nOutput:[[1,0],[2,1]]\nExplanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput:[[1,1,0],[0,1,1],[1,2,2]]\nExplanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] highestPeak(int[][] isWater) {\n int m = isWater.length, n = isWater[0].length;\n int[][] height = new int[m][n];\n Deque queue = new ArrayDeque<>();\n\n for (int[] row : height)\n Arrays.fill(row, -1);\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (isWater[i][j] == 1) {\n height[i][j] = 0;\n queue.offer(new int[] { i, j });\n }\n }\n }\n\n int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int x = cell[0], y = cell[1];\n\n for (int[] d : dirs) {\n int nx = x + d[0], ny = y + d[1];\n\n if (nx >= 0 && ny >= 0 && nx < m && ny < n && height[nx][ny] == -1) {\n height[nx][ny] = height[x][y] + 1;\n queue.offer(new int[] { nx, ny });\n }\n }\n }\n\n return height;\n }\n}", + "title": "1876. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation.", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]\nOutput:true\nExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]\nOutput:false\nExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]\nOutput:true\nExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean check(int[] nums) {\n int count = 0, n = nums.length;\n \n for (int i = 0; i < n; i++) {\n if (nums[i] > nums[(i + 1) % n]) \n count++;\n if (count > 1) \n return false;\n }\n \n return true;\n }\n}", + "title": "1878. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings word1 and word2 . Merge the strings by adding letters in alternating order, starting with word1 . If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 100", + "word1 and word2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"pqr\"\nOutput:\"apbqcr\"\nExplanation:The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"pqrs\"\nOutput:\"apbqrs\"\nExplanation:Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"abcd\", word2 = \"pq\"\nOutput:\"apbqcd\"\nExplanation:Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String mergeAlternately(String word1, String word2) {\n StringBuilder merged = new StringBuilder();\n int maxLength = Math.max(word1.length(), word2.length());\n\n for (int i = 0; i < maxLength; i++) {\n\n if (i < word1.length()) {\n merged.append(word1.charAt(i));\n }\n\n if (i < word2.length()) {\n merged.append(word2.charAt(i));\n }\n }\n\n return merged.toString();\n }\n}", + "title": "1894. Merge Strings Alternately", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists .", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput:1\nExplanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput:2\nExplanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput:-1\nExplanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length;\n int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\n Queue queue = new LinkedList<>();\n queue.offer(new int[] { entrance[0], entrance[1], 0 });\n\n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n int r = current[0], c = current[1], steps = current[2];\n\n if ((r != entrance[0] || c != entrance[1]) &&\n (r == 0 || r == rows - 1 || c == 0 || c == cols - 1)) {\n return steps;\n }\n\n for (int[] dir : directions) {\n int nr = r + dir[0], nc = c + dir[1];\n\n if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] == '.') {\n queue.offer(new int[] { nr, nc, steps + 1 });\n maze[nr][nc] = '+';\n }\n }\n }\n\n return -1;\n }\n}", + "title": "2038. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1] . If middleIndex == 0 , the left side sum is considered to be 0 . Similarly, if middleIndex == nums.length - 1 , the right side sum is considered to be 0 . Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index .", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-1,8,4]\nOutput:3\nExplanation:The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-1,4]\nOutput:2\nExplanation:The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,5]\nOutput:-1\nExplanation:There is no valid middleIndex.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMiddleIndex(int[] nums) {\n int totalSum = 0;\n\n for (int num : nums) {\n totalSum += num;\n }\n\n int leftSum = 0;\n for (int i = 0; i < nums.length; i++) {\n\n int rigthSum = totalSum - leftSum - nums[i];\n if (leftSum == rigthSum)\n return i;\n\n leftSum += nums[i];\n }\n\n return -1;\n }\n}", + "title": "2102. Find the Middle Index in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x .", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]\nOutput:[1,3,4,1,2,6]\nExplanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]\nOutput:[1,2,4]\nExplanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]\nOutput:[2]\nExplanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteMiddle(ListNode head) {\n if (head == null || head.next == null)\n return null;\n\n ListNode fast = head;\n ListNode slow = new ListNode(0);\n slow.next = head;\n\n while (fast != null && fast.next != null) {\n fast = fast.next.next;\n slow = slow.next;\n }\n\n slow.next = slow.next.next;\n return head;\n }\n}", + "title": "2216. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list .", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]\nOutput:6\nExplanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]\nOutput:7\nExplanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]\nOutput:100001\nExplanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int pairSum(ListNode head) {\n // Step 1: Find the middle of the list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half\n ListNode prev = null, curr = slow;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n // Step 3: Calculate twin sums\n int maxSum = Integer.MIN_VALUE;\n ListNode left = head;\n ListNode right = prev; // Head of reversed second half\n\n while (right != null) {\n int sum = left.val + right.val;\n maxSum = Math.max(maxSum, sum);\n left = left.next;\n right = right.next;\n }\n\n return maxSum;\n }\n}", + "title": "2236. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput:[4,0,3]\nExplanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16\nOutput:[2,0,2]\nExplanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] successfulPairs(int[] spells, int[] potions, long success) {\n Arrays.sort(potions);\n int m = potions.length;\n int[] ans = new int[spells.length];\n\n for (int i = 0; i < spells.length; i++) {\n long required = (success + spells[i] - 1) / spells[i]; // ceil division\n int idx = lowerBound(potions, required);\n ans[i] = m - idx;\n }\n return ans;\n }\n\n private int lowerBound(int[] arr, long target) {\n int l = 0, r = arr.length;\n\n while (l < r) { // binary search\n int mid = l + (r - l) / 2;\n if (arr[mid] < target)\n l = mid + 1;\n else\n r = mid;\n }\n\n return l;\n }\n}", + "title": "2392. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet {\n\n private PriorityQueue minHeap;\n private int current;\n\n public SmallestInfiniteSet() {\n minHeap = new PriorityQueue<>();\n current = 1;\n }\n\n public int popSmallest() {\n\n if (!minHeap.isEmpty()) {\n return minHeap.poll();\n } else {\n return current++;\n }\n }\n\n public void addBack(int num) {\n if (num < current && !minHeap.contains(num)) {\n minHeap.offer(num);\n }\n }\n}\n\n/**\n * Your SmallestInfiniteSet object will be instantiated and called as such:\n * SmallestInfiniteSet obj = new SmallestInfiniteSet();\n * int param_1 = obj.popSmallest();\n * obj.addBack(num);\n */", + "title": "2413. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (r i , c j ) such that row r i and column c j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput:1\nExplanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput:3\nExplanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int equalPairs(int[][] grid) {\n int n = grid.length;\n Map rowMap = new HashMap<>();\n int count = 0;\n\n for (int[] row : grid) {\n String key = encode(row);\n rowMap.put(key, rowMap.getOrDefault(key, 0) + 1);\n }\n\n for (int c = 0; c < n; c++) {\n int[] col = new int[n];\n \n for (int r = 0; r < n; r++) {\n col[r] = grid[r][c];\n }\n\n String colKey = encode(col);\n count += rowMap.getOrDefault(colKey, 0);\n }\n\n return count;\n }\n\n private static String encode(int[] arr) {\n StringBuilder sb = new StringBuilder();\n for (int num : arr) {\n sb.append(num).append(\"#\");\n }\n return sb.toString();\n }\n}", + "title": "2428. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , which contains stars * . In one operation, you can: Return the string after all stars have been removed . Note:", + "description_images": [], + "constraints": [ + "Choose a star in s .", + "Remove the closest non-star character to its left , as well as remove the star itself." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet**cod*e\"\nOutput:\"lecoe\"\nExplanation:Performing the removals from left to right:\n- The closest character to the 1ststar is 't' in \"leet**cod*e\". s becomes \"lee*cod*e\".\n- The closest character to the 2ndstar is 'e' in \"lee*cod*e\". s becomes \"lecod*e\".\n- The closest character to the 3rdstar is 'd' in \"lecod*e\". s becomes \"lecoe\".\nThere are no more stars, so we return \"lecoe\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"erase*****\"\nOutput:\"\"\nExplanation:The entire string is removed, so we return an empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String removeStars(String s) {\n Deque stack = new ArrayDeque<>();\n\n for (char c : s.toCharArray()) {\n if (c == '*') {\n stack.pollLast();\n } else {\n stack.addLast(c);\n }\n }\n\n // Convert stack to string\n StringBuilder sb = new StringBuilder();\n for (char ch : stack) {\n sb.append(ch);\n }\n\n return sb.toString();\n }\n}", + "title": "2470. Removing Stars From a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the i th worker. You are also given two integers k and candidates . We want to hire exactly k workers according to the following rules: Return the total cost to hire exactly k workers.", + "description_images": [], + "constraints": [ + "You will run k sessions and hire exactly one worker in each session.", + "In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index. For example, if costs = [3,2,7,7,1,2] and candidates = 2 , then in the first hiring session, we will choose the 4 th worker because they have the lowest cost [ 3,2 ,7,7, 1 ,2 ] . In the second hiring session, we will choose 1 st worker because they have the same lowest cost as 4 th worker but they have the smallest index [ 3, 2 ,7, 7,2 ] . Please note that the indexing may be changed in the process.", + "For example, if costs = [3,2,7,7,1,2] and candidates = 2 , then in the first hiring session, we will choose the 4 th worker because they have the lowest cost [ 3,2 ,7,7, 1 ,2 ] .", + "In the second hiring session, we will choose 1 st worker because they have the same lowest cost as 4 th worker but they have the smallest index [ 3, 2 ,7, 7,2 ] . Please note that the indexing may be changed in the process.", + "If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.", + "A worker can only be chosen once." + ], + "examples": [ + { + "text": "Example 1: Input:costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4\nOutput:11\nExplanation:We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.\n- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.\n- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.\nThe total hiring cost is 11.", + "image": null + }, + { + "text": "Example 2: Input:costs = [1,2,4,1], k = 3, candidates = 3\nOutput:4\nExplanation:We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.\n- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.\n- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.\nThe total hiring cost is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long totalCost(int[] costs, int k, int candidates) {\n int n = costs.length;\n long total = 0;\n int left = 0, right = n - 1;\n PriorityQueue heap = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n\n for (int i = 0; i < candidates && left <= right; i++) {\n heap.offer(new int[] { costs[left], left });\n left++;\n }\n\n for (int i = 0; i < candidates && left <= right; i++) {\n heap.offer(new int[] { costs[right], right });\n right--;\n }\n\n for (int hired = 0; hired < k; hired++) {\n int[] curr = heap.poll();\n int cost = curr[0];\n int idx = curr[1];\n total += cost;\n\n if (idx < left) { // Came from left side\n if (left <= right) {\n heap.offer(new int[] { costs[left], left });\n left++;\n }\n } else { // Came from right side\n if (left <= right) {\n heap.offer(new int[] { costs[right], right });\n right--;\n }\n }\n }\n\n return total;\n }\n}", + "title": "2553. Total Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k . You must choose a subsequence of indices from nums1 of length k . For chosen indices i 0 , i 1 , ..., i k - 1 , your score is defined as: Return the maximum possible score. A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.", + "description_images": [], + "constraints": [ + "The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2 .", + "It can defined simply as: (nums1[i 0 ] + nums1[i 1 ] +...+ nums1[i k - 1 ]) * min(nums2[i 0 ] , nums2[i 1 ], ... ,nums2[i k - 1 ]) ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3\nOutput:12\nExplanation:The four possible subsequence scores are:\n- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.\n- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6. \n- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12. \n- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.\nTherefore, we return the max score, which is 12.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1\nOutput:30\nExplanation:Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxScore(int[] nums1, int[] nums2, int k) {\n int n = nums1.length;\n int[][] pairs = new int[n][2];\n\n for (int i = 0; i < n; i++) {\n pairs[i][0] = nums2[i];\n pairs[i][1] = nums1[i];\n }\n\n Arrays.sort(pairs, (a, b) -> b[0] - a[0]);\n\n PriorityQueue minHeap = new PriorityQueue<>();\n long maxScore = 0, sum = 0;\n\n for (int i = 0; i < n; i++) {\n int currNum1 = pairs[i][1];\n int currNum2 = pairs[i][0];\n\n sum += currNum1;\n minHeap.add(currNum1);\n\n if (minHeap.size() > k) {\n sum -= minHeap.poll();\n }\n\n if (minHeap.size() == k) {\n maxScore = Math.max(maxScore, sum * currNum2);\n }\n }\n\n return maxScore;\n }\n}", + "title": "2636. Maximum Subsequence Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k . Return the number of unique XOR triplet values from all possible triplets (i, j, k) .", + "description_images": [], + "constraints": [ + "(0, 0, 0) → 1 XOR 1 XOR 1 = 1", + "(0, 0, 1) → 1 XOR 1 XOR 3 = 3", + "(0, 1, 1) → 1 XOR 3 XOR 3 = 1", + "(1, 1, 1) → 3 XOR 3 XOR 3 = 3" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int uniqueXorTriplets(int[] nums) {\n Set pairs = new HashSet<>(List.of(0));\n for (int i = 0, n = nums.length; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n pairs.add(nums[i] ^ nums[j]);\n }\n }\n\n BitSet triplets = new BitSet();\n for (int xy : pairs) {\n for (int z : nums) {\n triplets.set(xy ^ z);\n }\n }\n\n return triplets.cardinality();\n }\n}", + "title": "3820. Number of Unique XOR Triplets II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n , where nums is a permutation of the numbers in the range [1, n] . A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k . Return the number of unique XOR triplet values from all possible triplets (i, j, k) .", + "description_images": [], + "constraints": [ + "(0, 0, 0) → 1 XOR 1 XOR 1 = 1", + "(0, 0, 1) → 1 XOR 1 XOR 2 = 2", + "(0, 1, 1) → 1 XOR 2 XOR 2 = 1", + "(1, 1, 1) → 2 XOR 2 XOR 2 = 2" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int uniqueXorTriplets(int[] nums) {\n int n = nums.length;\n\n if (n < 3)\n return n;\n\n // Find the Most Significant Bit\n int count = 0;\n int temp = n;\n while (temp > 0) {\n temp >>= 1;\n count++;\n }\n\n return (int) Math.pow(2, count);\n }\n}", + "title": "3824. Number of Unique XOR Triplets I", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums and an integer k . You can perform the following operation any number of times: Return the minimum number of operations required to make the sum of the array divisible by k .", + "description_images": [], + "constraints": [ + "Select an index i and replace nums[i] with nums[i] - 1 ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums, int k) {\n int sum = 0;\n\n for (int num : nums) {\n sum += num;\n }\n\n int remainder = sum % k;\n\n if (remainder == 0)\n return 0;\n\n return remainder;\n }\n}", + "title": "3846. Minimum Operations to Make Array Sum Divisible by K", + "topic": "Array" + } +] \ No newline at end of file diff --git a/question-service/prisma/seed/questions-list.json b/question-service/prisma/seed/questions-list.json new file mode 100644 index 000000000..e4fcdc7dd --- /dev/null +++ b/question-service/prisma/seed/questions-list.json @@ -0,0 +1,101923 @@ +[ + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two adjacent cells is 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]Output:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]Output:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n// BFS\n// We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it.\n boolean visited[][];\n \n // Could also convert the indexes to a single number by mat[0].length * i + j.\n class Pair{\n int x;\n int y;\n Pair(int x, int y){\n this.x = x;\n this.y = y;\n }\n }\n public int[][] updateMatrix(int[][] mat) {\n int level = 0;\n visited = new boolean[mat.length][mat[0].length];\n Queue q = new ArrayDeque<>();\n // Addition of all pairs in mat that have 0.\n for(int i = 0; i < mat.length; i++){\n for(int j = 0; j < mat[0].length; j++){\n if(mat[i][j] == 0){\n visited[i][j] = true;\n q.add(new Pair(i, j));\n }\n }\n }\n while(q.size()>0){\n int size = q.size();\n while(size-- > 0){\n Pair p = q.remove();\n mat[p.x][p.y] = level;\n if(p.x > 0 && visited[p.x - 1][p.y] == false){\n visited[p.x-1][p.y] = true;\n q.add(new Pair(p.x-1, p.y));\n }\n if(p.x < mat.length - 1 && visited[p.x + 1][p.y] == false){\n visited[p.x+1][p.y] = true;\n q.add(new Pair(p.x+1, p.y));\n \n }\n if(p.y > 0 && visited[p.x][p.y-1] == false){\n visited[p.x][p.y-1] = true;\n q.add(new Pair(p.x, p.y-1));\n \n }\n if(p.y < mat[0].length-1 && visited[p.x][p.y + 1] == false){\n visited[p.x][p.y+1] = true;\n q.add(new Pair(p.x, p.y + 1));\n }\n }\n level++;\n }\n return mat;\n }\n}\n", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two adjacent cells is 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]Output:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]Output:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 534 ms (Top 69.67%) | Memory: 19.20 MB (Top 71.26%)\n\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n if not mat or not mat[0]:\n return []\n\n m, n = len(mat), len(mat[0])\n queue = deque()\n MAX_VALUE = m * n\n \n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n queue.append((i, j))\n else:\n mat[i][j] = MAX_VALUE\n \n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n \n while queue:\n row, col = queue.popleft()\n for dr, dc in directions:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n queue.append((r, c))\n mat[r][c] = mat[row][col] + 1\n \n return mat\n", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We have two special characters: Given a binary array bits that ends with 0 , return true if the last character must be a one-bit character. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first character can be represented by one bit 0 .", + "The second character can be represented by two bits ( 10 or 11 )." + ], + "examples": [ + { + "text": "Example 1: Input:bits = [1,0,0]Output:trueExplanation:The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.", + "image": null + }, + { + "text": "Example 2: Input:bits = [1,1,1,0]Output:falseExplanation:The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isOneBitCharacter(int[] bits) {\n int ones = 0;\n //Starting from one but last, as last one is always 0.\n for (int i = bits.length - 2; i >= 0 && bits[i] != 0 ; i--) { \n ones++;\n }\n if (ones % 2 > 0) return false; \n return true;\n }\n}\n", + "title": "717. 1-bit and 2-bit Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have two special characters: Given a binary array bits that ends with 0 , return true if the last character must be a one-bit character. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first character can be represented by one bit 0 .", + "The second character can be represented by two bits ( 10 or 11 )." + ], + "examples": [ + { + "text": "Example 1: Input:bits = [1,0,0]Output:trueExplanation:The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.", + "image": null + }, + { + "text": "Example 2: Input:bits = [1,1,1,0]Output:falseExplanation:The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.", + "image": null + } + ], + "follow_up": null, + "solution": "# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282638543/\n# (Time, Space) Complexity : O(n), O(1)\n\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n # Important Rules:\n # 1. If bit n is 0, bit n+1 must be a new char\n # 2. If bits end with 1, last bit must be a two bit char\n # However, this case had been rejected by question\n # 3. If 1s in row and end with 0, \n # we can use count or 1s to check last char\n # If count is even, last char is \"0\"\n # If count is odd, last char is \"10\"\n # Strategy:\n # 1. We don't care last element, since it must be 0.\n # 2. We check from reversed, and count 1s in a row\n # 3. Once 0 occur or list end, We stop counting\n # 4. We use count to determin result\n # 5. Since we will mod count by 2, we simplify it to bool\n ret = True\n for bit in bits[-2::-1]:\n if bit: ret = not ret\n else: break\n return ret\n", + "title": "717. 1-bit and 2-bit Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of n integers nums , a 132 pattern is a subsequence of three integers nums[i] , nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j] . Return true if there is a 132 pattern in nums , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 2 * 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:falseExplanation:There is no 132 pattern in the sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,4,2]Output:trueExplanation:There is a 132 pattern in the sequence: [1, 4, 2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,3,2,0]Output:trueExplanation:There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 96.40%) | Memory: 67 MB (Top 55.57%)\nclass Solution {\n public boolean find132pattern(int[] nums) {\n int min = Integer.MIN_VALUE;\n int peak = nums.length;\n for (int i = nums.length - 1; i >= 0; i--) {\n // We find a \"132\" pattern if nums[i] < min, so return true...\n if (nums[i] < min)\n return true;\n // If peak < nums.length & nums[i] is greater than the peak element...\n while (peak < nums.length && nums[i] > nums[peak])\n min = nums[peak++];\n // Now we have nums[i] <= nums[peak]\n // We push nums[i] to the \"stack\"\n peak--;\n nums[peak] = nums[i];\n }\n return false;\n }\n}", + "title": "456. 132 Pattern", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of n integers nums , a 132 pattern is a subsequence of three integers nums[i] , nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j] . Return true if there is a 132 pattern in nums , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 2 * 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:falseExplanation:There is no 132 pattern in the sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,4,2]Output:trueExplanation:There is a 132 pattern in the sequence: [1, 4, 2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,3,2,0]Output:trueExplanation:There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 476 ms (Top 99.36%) | Memory: 36.40 MB (Top 85.77%)\n\nclass Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n stack, third = [], float('-inf')\n \n for num in reversed(nums):\n if num < third:\n return True\n while stack and stack[-1] < num:\n third = stack.pop()\n stack.append(num)\n return False\n", + "title": "456. 132 Pattern", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Given an integer n , return the minimum number of operations to get the character 'A' exactly n times on the screen . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).", + "Paste: You can paste the characters which are copied last time." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3Explanation:Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSteps(int n) {\n int rem = n-1, copied = 0, ans = 0, onScreen = 1;\n \n while(rem>0){\n if(rem % onScreen == 0){\n ans++; // copy operation\n copied = onScreen; \n }\n rem-=copied;\n ans++; // paste operation\n onScreen = n-rem; // no. of characters on screen currently that can be copied in next copy operation\n }\n \n return ans;\n }\n}\n", + "title": "650. 2 Keys Keyboard", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step: Given an integer n , return the minimum number of operations to get the character 'A' exactly n times on the screen . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).", + "Paste: You can paste the characters which are copied last time." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3Explanation:Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, n: int) -> int: \n # at every step we can copy or paste\n # paste -> we need to know the current clipboard content (count)\n # copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste)\n \n memo = {}\n \n def dfs(clipboard_count, screen_count):\n if (clipboard_count, screen_count) in memo: \n return memo[(clipboard_count, screen_count)]\n \n # we reached n, this is a valid option\n if screen_count == n: return 0\n \n # we passed n, not a valid option\n if screen_count > n: return float('inf') \n \n # paste or copy\n copy_opt = paste_opt = float('inf')\n \n # we should only paste if clipboard is not empty\n if clipboard_count > 0:\n paste_opt = dfs(clipboard_count, screen_count + clipboard_count) \n \n # we should consider copy only if the last operation was paste\n if screen_count > clipboard_count:\n copy_opt = dfs(screen_count, screen_count) \n \n # save to memo\n memo[(clipboard_count, screen_count)] = 1 + min(paste_opt, copy_opt) \n return memo[(clipboard_count, screen_count)]\n \n return dfs(0, 1)\n \n", + "title": "650. 2 Keys Keyboard", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array cards of length 4 . You have four cards, each containing a number in the range [1, 9] . You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: Return true if you can get such expression that evaluates to 24 , and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid.", + "For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid." + ], + "examples": [ + { + "text": "Example 1: Input:cards = [4,1,8,7]Output:trueExplanation:(8-4) * (7-1) = 24", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,2,1,2]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 96.55%) | Memory: 40.80 MB (Top 91.57%)\n\n// 0 ms. 100%\nclass Solution {\n private static final double EPS = 1e-6;\n private boolean backtrack(double[] A, int n) {\n if(n == 1) return Math.abs(A[0] - 24) < EPS;\n for(int i = 0; i < n; i++) {\n for(int j = i + 1; j < n; j++) {\n double a = A[i], b = A[j];\n A[j] = A[n-1];\n A[i] = a + b;\n if(backtrack(A, n - 1)) return true;\n A[i] = a - b;\n if(backtrack(A, n - 1)) return true;\n A[i] = b - a;\n if(backtrack(A, n - 1)) return true;\n A[i] = a * b;\n if(backtrack(A, n - 1)) return true;\n if(Math.abs(b) > EPS) {\n A[i] = a / b;\n if(backtrack(A, n - 1)) return true;\n }\n if(Math.abs(a) > EPS) {\n A[i] = b / a;\n if(backtrack(A, n - 1)) return true;\n }\n A[i] = a; A[j] = b;\n }\n }\n return false;\n }\n public boolean judgePoint24(int[] nums) {\n double[] A = new double[nums.length];\n for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n return backtrack(A, A.length);\n }\n}\n", + "title": "679. 24 Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array cards of length 4 . You have four cards, each containing a number in the range [1, 9] . You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. You are restricted with the following rules: Return true if you can get such expression that evaluates to 24 , and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The division operator '/' represents real division, not integer division. For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12 .", + "Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator. For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "For example, if cards = [1, 1, 1, 1] , the expression \"-1 - 1 - 1 - 1\" is not allowed .", + "You cannot concatenate numbers together For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid.", + "For example, if cards = [1, 2, 1, 2] , the expression \"12 + 12\" is not valid." + ], + "examples": [ + { + "text": "Example 1: Input:cards = [4,1,8,7]Output:trueExplanation:(8-4) * (7-1) = 24", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,2,1,2]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n return self.allComputeWays(cards, 4, 24)\n \n def allComputeWays(self, nums, l, target):\n if l == 1:\n if abs(nums[0] - target) <= 1e-6:\n return True\n return False\n for first in range(l):\n for second in range(first + 1, l):\n tmp1, tmp2 = nums[first], nums[second]\n nums[second] = nums[l - 1]\n \n nums[first] = tmp1 + tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 - tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp2 - tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 * tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp2:\n nums[first] = tmp1 / tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp1:\n nums[first] = tmp2 / tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first], nums[second] = tmp1, tmp2\n return False", + "title": "679. 24 Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 3000", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1]Output:[]Explanation:The only possible triplet does not sum up to 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0]Output:[[0,0,0]]Explanation:The only possible triplet sums up to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def threeSum(self, nums):\n ans = []\n nums.sort()\n \n for i in range(len(nums)):\n if nums[i] > 0: break # after sorting, if the min > 0, we couldn't find such three values\n if i > 0 and nums[i] == nums[i - 1]: # ensure that nums[i] is not duplicated\n continue \n l, r = i + 1, len(nums) - 1\n while l < r:\n if nums[l] + nums[r] > -nums[i]:\n r -= 1\n elif nums[l] + nums[r] < -nums[i]:\n l += 1\n else:\n ans.append([nums[i], nums[l], nums[r]])\n\t\t\t\t\t# update l to get a different sum\n l += 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n return ans\n", + "title": "15. 3Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums of length n and an integer target , find three integers in nums such that the sum is closest to target . Return the sum of the three integers . You may assume that each input would have exactly one solution. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 1000", + "-1000 <= nums[i] <= 1000", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,2,1,-4], target = 1Output:2Explanation:The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], target = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1535 ms (Top 7.9%) | Memory: 16.58 MB (Top 11.9%)\n\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n closet = float('inf')\n nums.sort()\n for i in range(len(nums) - 2):\n l, r = i + 1, len(nums) - 1\n while l < r:\n sum3 = nums[i] + nums[l] + nums[r]\n print(sum3)\n if sum3 < target:\n l += 1\n else:\n r -=1\n if abs(sum3 - target) < abs(closet - target):\n closet = sum3\n return closet\n ", + "title": "16. 3Sum Closest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr , and an integer target , return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target . As the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 3000", + "0 <= arr[i] <= 100", + "0 <= target <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,1,2,2,3,3,4,4,5,5], target = 8Output:20Explanation:Enumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,2,2], target = 5Output:12Explanation:arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,1,3], target = 6Output:1Explanation:(1, 2, 3) occured one time in the array so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int threeSumMulti(int[] arr, int target) {\n long[] cnt = new long[101];\n long res = 0;\n for (int i : arr) {\n cnt[i]++;\n }\n for (int i = 0; i < 101 && i <= target; i++) {\n if (cnt[i] == 0) {\n continue;\n }\n for (int j = i; j < 101 && i + j <= target; j++) {\n int k = target - i - j;\n if (k < j) {\n break;\n }\n if (cnt[j] == 0 || k >= 101 || cnt[k] == 0) {\n continue;\n }\n if (i == j && j == k) {\n res += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 3 / 2;\n } else if (i == j) {\n res += cnt[k] * cnt[j] * (cnt[j] - 1) / 2;\n } else if (j == k) {\n res += cnt[i] * cnt[j] * (cnt[j] - 1) / 2;\n } else {\n res += cnt[i] * cnt[j] * cnt[target - i - j];\n }\n }\n }\n return (int) (res % (Math.pow(10, 9) + 7));\n }\n}\n", + "title": "923. 3Sum With Multiplicity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr , and an integer target , return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target . As the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 3000", + "0 <= arr[i] <= 100", + "0 <= target <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,1,2,2,3,3,4,4,5,5], target = 8Output:20Explanation:Enumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,2,2], target = 5Output:12Explanation:arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,1,3], target = 6Output:1Explanation:(1, 2, 3) occured one time in the array so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n arr.sort()\n count = 0\n for i in range(0, len(arr)-2):\n rem_sum = target - arr[i]\n hash_map = {}\n for j in range(i+1, len(arr)):\n if arr[j] > rem_sum:\n break\n if rem_sum - arr[j] in hash_map:\n count = count + hash_map[rem_sum-arr[j]]\n # update the hash_map\n hash_map[arr[j]] = hash_map.get(arr[j], 0) + 1\n return count % 1000000007\n", + "title": "923. 3Sum With Multiplicity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= a, b, c, d < n", + "a , b , c , and d are distinct .", + "nums[a] + nums[b] + nums[c] + nums[d] == target" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,-1,0,-2,2], target = 0Output:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], target = 8Output:[[2,2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 82.83%) | Memory: 42.5 MB (Top 98.57%)\nclass Solution {\n public List> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n List> llans = new LinkedList<>();\n if(nums == null || nums.length <= 2){\n return llans;\n }\n for(int i=0;i ll = new LinkedList<>();\n ll.add(nums[i]);\n ll.add(nums[j]);\n ll.add(nums[l]);\n ll.add(nums[r]);\n llans.add(ll);\n\n while( l List[List[int]]:\n \n if len(nums) < 4: return []\n \n nums.sort()\n res = []\n \n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n l = j+1\n r = len(nums)-1\n while l < r:\n\n sum_ = nums[i]+nums[j]+nums[l]+nums[r]\n a = [nums[i], nums[j], nums[l], nums[r]]\n \n if sum_ == target and a not in res:\n res.append(a)\n \n if sum_ > target:\n r -= 1\n \n else:\n l += 1\n while l < r and nums[l-1] == nums[l]:\n l += 1\n \n return res\n \n # An Upvote will be encouraging\n \n \n", + "title": "18. 4Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given four integer arrays nums1 , nums2 , nums3 , and nums4 all of length n , return the number of tuples (i, j, k, l) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i, j, k, l < n", + "nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]Output:2Explanation:The two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 81.61%) | Memory: 44.50 MB (Top 61.42%)\n\nclass Solution {\n public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {\n Map map = new HashMap<>();\n for(int k : nums3)\n for(int l : nums4)\n map.put(k + l, map.getOrDefault(k + l, 0) + 1);\n int count = 0;\n for(int i : nums1)\n for(int j : nums2)\n count += map.getOrDefault(-(i + j), 0);\n return count;\n }\n}\n", + "title": "454. 4Sum II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given four integer arrays nums1 , nums2 , nums3 , and nums4 all of length n , return the number of tuples (i, j, k, l) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i, j, k, l < n", + "nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]Output:2Explanation:The two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1360 ms (Top 29.95%) | Memory: 14.2 MB (Top 70.39%)\nclass Solution:\n def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:\n n1n2 = defaultdict(int)\n for n1 in nums1:\n for n2 in nums2:\n n1n2[n1+n2] += 1\n n3n4 = defaultdict(int)\n for n3 in nums3:\n for n4 in nums4:\n n3n4[n3+n4] += 1\n ans = 0\n for s in n1n2:\n ans += n1n2[s] * n3n4[-s]\n return ans", + "title": "454. 4Sum II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Reversing an integer means to reverse all its digits. Given an integer num , reverse num to get reversed1 , then reverse reversed1 to get reversed2 . Return true if reversed2 equals num . Otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, reversing 2021 gives 1202 . Reversing 12300 gives 321 as the leading zeros are not retained ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 526Output:trueExplanation:Reverse num to get 625, then reverse 625 to get 526, which equals num.", + "image": null + }, + { + "text": "Example 2: Input:num = 1800Output:falseExplanation:Reverse num to get 81, then reverse 81 to get 18, which does not equal num.", + "image": null + }, + { + "text": "Example 3: Input:num = 0Output:trueExplanation:Reverse num to get 0, then reverse 0 to get 0, which equals num.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.24 MB (Top 48.0%)\n\nclass Solution {\n public boolean isSameAfterReversals(int num) {\n return (num%10!=0||num<10);\n }\n}", + "title": "2119. A Number After a Double Reversal", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Reversing an integer means to reverse all its digits. Given an integer num , reverse num to get reversed1 , then reverse reversed1 to get reversed2 . Return true if reversed2 equals num . Otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, reversing 2021 gives 1202 . Reversing 12300 gives 321 as the leading zeros are not retained ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 526Output:trueExplanation:Reverse num to get 625, then reverse 625 to get 526, which equals num.", + "image": null + }, + { + "text": "Example 2: Input:num = 1800Output:falseExplanation:Reverse num to get 81, then reverse 81 to get 18, which does not equal num.", + "image": null + }, + { + "text": "Example 3: Input:num = 0Output:trueExplanation:Reverse num to get 0, then reverse 0 to get 0, which equals num.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isSameAfterReversals(self, num):\n\t\t# All you have to do is check the Trailing zeros\n return num == 0 or num % 10 # num % 10 means num % 10 != 0\n", + "title": "2119. A Number After a Double Reversal", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two positive integers left and right with left <= right . Calculate the product of all integers in the inclusive range [left, right] . Since the product may be very large, you will abbreviate it following these steps: Return a string denoting the abbreviated product of all integers in the inclusive range [left, right] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, there are 3 trailing zeros in 1000 , and there are 0 trailing zeros in 546 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 4Output:\"24e0\"Explanation:The product is 1 × 2 × 3 × 4 = 24.\nThere are no trailing zeros, so 24 remains the same. The abbreviation will end with \"e0\".\nSince the number of digits is 2, which is less than 10, we do not have to abbreviate it further.\nThus, the final representation is \"24e0\".", + "image": null + }, + { + "text": "Example 2: Input:left = 2, right = 11Output:\"399168e2\"Explanation:The product is 39916800.\nThere are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with \"e2\".\nThe number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.\nHence, the abbreviated product is \"399168e2\".", + "image": null + }, + { + "text": "Example 3: Input:left = 371, right = 375Output:\"7219856259e3\"Explanation:The product is 7219856259000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n c2 = c5 = 0\n top12 = tail5 = 1\n\n for i in range(left, right+1):\n # count and remove all 2 and 5\n while i % 2 == 0:\n i //= 2\n c2 += 1\n while i % 5 == 0:\n i //= 5\n c5 += 1\n\n # track top 12 and last 5\n top12 = int(str(top12 * i)[:12])\n tail5 = tail5 * i % 100000\n \n # multiply the remained 2 or 5\n if c2 > c5:\n for _ in range(c2 - c5):\n top12 = int(str(top12 * 2)[:12])\n tail5 = tail5 * 2 % 100000\n elif c2 < c5:\n for _ in range(c5 - c2):\n top12 = int(str(top12 * 5)[:12])\n tail5 = tail5 * 5 % 100000\n\n zero = min(c2, c5)\n\n # as is included in top 12, it's easy to tell when d<=10\n if len(str(top12))<=10:\n return str(top12)+'e'+str(zero)\n \n return str(top12)[:5] + '.'*3 + '0'*(5-len(str(tail5)))+str(tail5)+'e'+str(zero)\n", + "title": "2117. Abbreviating the Product of a Range", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Output:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Explanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]Output:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 92.2%) | Memory: 47.60 MB (Top 65.47%)\n\nclass Solution {\n class UnionFind {\n int[] parent;\n int[] weight;\n \n public UnionFind(int num) {\n parent = new int[num];\n weight = new int[num];\n \n for(int i = 0; i < num; i++) {\n parent[i] = i;\n weight[i] = 1;\n }\n }\n \n public void union(int a, int b) {\n int rootA = root(a);\n int rootB = root(b);\n \n if (rootA == rootB) {\n return;\n }\n \n if (weight[rootA] > weight[rootB]) {\n parent[rootB] = rootA;\n weight[rootA] += weight[rootB];\n } else {\n parent[rootA] = rootB;\n weight[rootB] += weight[rootA];\n }\n }\n \n public int root(int a) {\n if (parent[a] == a) {\n return a;\n }\n \n parent[a] = root(parent[a]);\n return parent[a];\n }\n }\n\n public List> accountsMerge(List> accounts) {\n int size = accounts.size();\n\n UnionFind uf = new UnionFind(size);\n\n // prepare a hash with unique email address as key and index in accouts as value\n HashMap emailToId = new HashMap<>();\n for(int i = 0; i < size; i++) {\n List details = accounts.get(i);\n for(int j = 1; j < details.size(); j++) {\n String email = details.get(j);\n \n\t\t\t\t// if we have already seen this email before, merge the account \"i\" with previous account\n\t\t\t\t// else add it to hash\n if (emailToId.containsKey(email)) {\n uf.union(i, emailToId.get(email));\n } else {\n emailToId.put(email, i);\n }\n }\n }\n \n // prepare a hash with index in accounts as key and list of unique email address for that account as value\n HashMap> idToEmails = new HashMap<>();\n for(String key : emailToId.keySet()) {\n int root = uf.root(emailToId.get(key));\n \n if (!idToEmails.containsKey(root)) {\n idToEmails.put(root, new ArrayList());\n }\n \n idToEmails.get(root).add(key);\n }\n \n // collect the emails from idToEmails, sort it and add account name at index 0 to get the final list to add to final return List\n List> mergedDetails = new ArrayList<>();\n for(Integer id : idToEmails.keySet()) {\n List emails = idToEmails.get(id);\n Collections.sort(emails);\n emails.add(0, accounts.get(id).get(0));\n \n mergedDetails.add(emails);\n }\n \n return mergedDetails;\n }\n}\n", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Output:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Explanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]Output:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n def merge(accounts):\n res = []\n ls = []\n for i in range(len(accounts)):\n temp = list(set(accounts[i][1:]))\n temp.sort()\n temp = [accounts[i][0]] + temp\n if i in ls:\n continue\n for j in range(len(accounts[i:])):\n s = i+j\n if i == s:\n continue\n if accounts[i][0] != accounts[s][0]:\n continue\n temp3 = list(set(accounts[s][1:]))\n uni = list(set(temp[1:]) | set(temp3))\n if len(uni) < len(temp[1:]) + len(temp3):\n temp1 = list(set(temp[1:]) | set(temp3))\n temp = [temp[0]] + temp1 \n ls.append(s)\n temp0 = temp[1:]\n temp0.sort()\n temp = [temp[0]]+temp0\n res.append(temp)\n return res\n merged = merge(accounts)\n while merge(merged) != merged:\n merged = merge(merged)\n\n return merged\n", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two binary strings a and b , return their sum as a binary string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"Output:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"Output:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 42.20 MB (Top 42.63%)\n\nclass Solution {\n public String addBinary(String a, String b) {\n StringBuilder res = new StringBuilder();\n int i = a.length() - 1;\n int j = b.length() - 1;\n int carry = 0;\n while(i >= 0 || j >= 0){\n int sum = carry;\n if(i >= 0) sum += a.charAt(i--) - '0';\n if(j >= 0) sum += b.charAt(j--) - '0';\n carry = sum > 1 ? 1 : 0;\n res.append(sum % 2);\n }\n if(carry != 0) res.append(carry);\n return res.reverse().toString();\n }\n}\n", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two binary strings a and b , return their sum as a binary string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"Output:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"Output:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n\n return str(bin(int(a, base = 2)+int(b, base = 2)))[2:]\n", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer num , repeatedly add all its digits until the result has only one digit, and return it. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 38Output:2Explanation:The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.", + "image": null + }, + { + "text": "Example 2: Input:num = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 73.88%) | Memory: 41.9 MB (Top 17.90%)\nclass Solution {\n public int addDigits(int num) {\n if(num == 0) return 0;\n else if(num % 9 == 0) return 9;\n else return num % 9;\n }\n}", + "title": "258. Add Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , repeatedly add all its digits until the result has only one digit, and return it. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 38Output:2Explanation:The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.", + "image": null + }, + { + "text": "Example 2: Input:num = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 20.34%) | Memory: 16.40 MB (Top 13.14%)\n\nclass Solution:\n def addDigits(self, num: int) -> int:\n while num > 9:\n num = num % 10 + num // 10\n return num\n", + "title": "258. Add Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0 , and you want to reach the last rung. You are also given an integer dist . You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist . You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rungs.length <= 10^5", + "1 <= rungs[i] <= 10^9", + "1 <= dist <= 10^9", + "rungs is strictly increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:rungs = [1,3,5,10], dist = 2Output:2Explanation:You currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "image": null + }, + { + "text": "Example 2: Input:rungs = [3,6,8,10], dist = 3Output:0Explanation:This ladder can be climbed without adding additional rungs.", + "image": null + }, + { + "text": "Example 3: Input:rungs = [3,4,6,7], dist = 2Output:1Explanation:You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 46.95%) | Memory: 72.5 MB (Top 49.39%)\nclass Solution {\n public int addRungs(int[] rungs, int dist) {\n int ans = 0;\n for (int i=0 ; i dist ) {\n ans += d/dist;\n ans += ( d%dist == 0 ) ? -1 : 0;\n }\n }\n return ans;\n }\n}", + "title": "1936. Add Minimum Number of Rungs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0 , and you want to reach the last rung. You are also given an integer dist . You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist . You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rungs.length <= 10^5", + "1 <= rungs[i] <= 10^9", + "1 <= dist <= 10^9", + "rungs is strictly increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:rungs = [1,3,5,10], dist = 2Output:2Explanation:You currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].", + "image": null + }, + { + "text": "Example 2: Input:rungs = [3,6,8,10], dist = 3Output:0Explanation:This ladder can be climbed without adding additional rungs.", + "image": null + }, + { + "text": "Example 3: Input:rungs = [3,4,6,7], dist = 2Output:1Explanation:You currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n rungs=[0]+rungs\n i,ans=1,0\n while i dist:\n ans+=ceil((rungs[i]-rungs[i-1])/dist)-1\n i+=1\n return ans\n\n\n\n ", + "title": "1936. Add Minimum Number of Rungs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and two integers val and depth , add a row of nodes with value val at the given depth depth . Note that the root node is at depth 1 . The adding rule is: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Given the integer depth , for each not null tree node cur at the depth depth - 1 , create two tree nodes with value val as cur 's left subtree root and right subtree root.", + "cur 's original left subtree should be the left subtree of the new left subtree root.", + "cur 's original right subtree should be the right subtree of the new right subtree root.", + "If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,3,1,5], val = 1, depth = 2Output:[4,1,1,2,null,null,6,3,1,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,null,3,1], val = 1, depth = 3Output:[4,2,null,1,1,3,null,null,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.40 MB (Top 37.52%)\n\nclass Solution {\n public TreeNode addOneRow(TreeNode root, int v, int d) {\n if (d == 1) return new TreeNode(v, root, null);\n else if (d == 2) {\n root.left = new TreeNode(v, root.left, null);\n root.right = new TreeNode(v, null, root.right);\n } else {\n if (root.left != null) addOneRow(root.left, v, d-1);\n if (root.right != null) addOneRow(root.right, v, d-1);\n }\n return root;\n }\n}\n", + "title": "623. Add One Row to Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and two integers val and depth , add a row of nodes with value val at the given depth depth . Note that the root node is at depth 1 . The adding rule is: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Given the integer depth , for each not null tree node cur at the depth depth - 1 , create two tree nodes with value val as cur 's left subtree root and right subtree root.", + "cur 's original left subtree should be the left subtree of the new left subtree root.", + "cur 's original right subtree should be the right subtree of the new right subtree root.", + "If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,3,1,5], val = 1, depth = 2Output:[4,1,1,2,null,null,6,3,1,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,null,3,1], val = 1, depth = 3Output:[4,2,null,1,1,3,null,null,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 6.3%) | Memory: 18.50 MB (Top 98.9%)\n\nclass Solution:\n def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:\n if d == 1: return TreeNode(v, root, None)\n elif d == 2:\n root.left = TreeNode(v, root.left, None)\n root.right = TreeNode(v, None, root.right)\n else:\n if root.left: self.addOneRow(root.left, v, d-1)\n if root.right: self.addOneRow(root.right, v, d-1)\n return root\n", + "title": "623. Add One Row to Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string . You must solve the problem without using any built-in library for handling large integers (such as BigInteger ). You must also not convert the inputs to integers directly. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num1.length, num2.length <= 10^4", + "num1 and num2 consist of only digits.", + "num1 and num2 don't have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"11\", num2 = \"123\"Output:\"134\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"456\", num2 = \"77\"Output:\"533\"", + "image": null + }, + { + "text": "Example 3: Input:num1 = \"0\", num2 = \"0\"Output:\"0\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 29.95%) | Memory: 42.8 MB (Top 82.92%)\nimport java.math.BigInteger;\nclass Solution {\n public String addStrings(String num1, String num2) {\n return new BigInteger(num1).add(new BigInteger(num2)).toString();\n }\n}", + "title": "415. Add Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string . You must solve the problem without using any built-in library for handling large integers (such as BigInteger ). You must also not convert the inputs to integers directly. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num1.length, num2.length <= 10^4", + "num1 and num2 consist of only digits.", + "num1 and num2 don't have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"11\", num2 = \"123\"Output:\"134\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"456\", num2 = \"77\"Output:\"533\"", + "image": null + }, + { + "text": "Example 3: Input:num1 = \"0\", num2 = \"0\"Output:\"0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n def func(n):\n value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}\n result = 0\n for digit in n:\n result = 10 * result + value[digit]\n\n return result\n\n ans = func(num1) + func(num2)\n return str(ans)", + "title": "415. Add Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num , the array-form of an integer, and an integer k , return the array-form of the integer num + k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for num = 1321 , the array form is [1,3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = [1,2,0,0], k = 34Output:[1,2,3,4]Explanation:1200 + 34 = 1234", + "image": null + }, + { + "text": "Example 2: Input:num = [2,7,4], k = 181Output:[4,5,5]Explanation:274 + 181 = 455", + "image": null + }, + { + "text": "Example 3: Input:num = [2,1,5], k = 806Output:[1,0,2,1]Explanation:215 + 806 = 1021", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List addToArrayForm(int[] num, int k) {\n List res = new ArrayList<>();\n \n int i = num.length;\n while(--i >= 0 || k > 0) {\n if(i >= 0)\n k += num[i];\n \n res.add(k % 10);\n k /= 10;\n }\n Collections.reverse(res);\n \n return res;\n }\n}\n", + "title": "989. Add to Array-Form of Integer", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The array-form of an integer num is an array representing its digits in left to right order. Given num , the array-form of an integer, and an integer k , return the array-form of the integer num + k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for num = 1321 , the array form is [1,3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = [1,2,0,0], k = 34Output:[1,2,3,4]Explanation:1200 + 34 = 1234", + "image": null + }, + { + "text": "Example 2: Input:num = [2,7,4], k = 181Output:[4,5,5]Explanation:274 + 181 = 455", + "image": null + }, + { + "text": "Example 3: Input:num = [2,1,5], k = 806Output:[1,0,2,1]Explanation:215 + 806 = 1021", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 384 ms (Top 73.70%) | Memory: 15 MB (Top 73.95%)\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(str(int(\"\".join(map(str,num)))+k))", + "title": "989. Add to Array-Form of Integer", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-100 <= num1, num2 <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 12, num2 = 5Output:17Explanation:num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.", + "image": null + }, + { + "text": "Example 2: Input:num1 = -10, num2 = 4Output:-6Explanation:num1 + num2 = -6, so -6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sum(int num1, int num2) {\n int l = -200, r = 200;\n while (l < r) {\n int mid = (l + r) >> 1;\n if (mid == num1 + num2) { return mid; }\n if (mid < num1 + num2) l = mid + 1;\n if (mid > num1 + num2) r = mid - 1;\n }\n return l;\n }\n}\n \n", + "title": "2235. Add Two Integers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-100 <= num1, num2 <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 12, num2 = 5Output:17Explanation:num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.", + "image": null + }, + { + "text": "Example 2: Input:num1 = -10, num2 = 4Output:-6Explanation:num1 + num2 = -6, so -6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 99.37%) | Memory: 16.60 MB (Top 53.73%)\n\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n", + "title": "2235. Add Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]Output:[7,0,8]Explanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]Output:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n \n ListNode dummy = new ListNode(-1);\n ListNode temp = dummy;\n int carry = 0;\n while(l1 != null || l2 != null || carry != 0){\n int sum = 0;\n if(l1 != null){\n sum += l1.val;\n l1 = l1.next;\n }\n if(l2 != null){\n sum += l2.val;\n l2 = l2.next;\n } \n sum += carry;\n carry = sum / 10;\n ListNode node = new ListNode(sum % 10);\n temp.next = node;\n temp = temp.next;\n }\n return dummy.next;\n }\n}\n", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]Output:[7,0,8]Explanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]Output:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 13.64%) | Memory: 16.40 MB (Top 51.59%)\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummyHead = ListNode(0)\n tail = dummyHead\n carry = 0\n\n while l1 is not None or l2 is not None or carry != 0:\n digit1 = l1.val if l1 is not None else 0\n digit2 = l2.val if l2 is not None else 0\n\n sum = digit1 + digit2 + carry\n digit = sum % 10\n carry = sum // 10\n\n newNode = ListNode(digit)\n tail.next = newNode\n tail = tail.next\n\n l1 = l1.next if l1 is not None else None\n l2 = l2.next if l2 is not None else None\n\n result = dummyHead.next\n dummyHead.next = None\n return result\n", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [7,2,4,3], l2 = [5,6,4]Output:[7,8,0,7]", + "image": "https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg" + }, + { + "text": "Example 2: Input:l1 = [2,4,3], l2 = [5,6,4]Output:[8,0,7]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [0], l2 = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode res=new ListNode(0);\n ListNode curr=res;\n l1=reverseLinkedList(l1);\n l2=reverseLinkedList(l2);\n int carry=0;\n while(l1!=null||l2!=null||carry==1)\n {\n int sum=0;\n if(l1!=null)\n {\n sum+=l1.val;\n l1=l1.next;\n }\n if(l2!=null)\n {\n sum+=l2.val;\n l2=l2.next;\n }\n sum+=carry;\n carry = sum/10; \n curr.next= new ListNode(sum % 10); \n \n curr = curr.next; \n }\n return reverseLinkedList(res.next);\n }\n public ListNode reverseLinkedList(ListNode head)\n {\n ListNode curr=head;\n ListNode prev=null;\n ListNode next;\n while(curr!=null)\n {\n next=curr.next;\n curr.next=prev;\n prev=curr;\n curr=next;\n }\n return prev;\n }\n}\n", + "title": "445. Add Two Numbers II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [7,2,4,3], l2 = [5,6,4]Output:[7,8,0,7]", + "image": "https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg" + }, + { + "text": "Example 2: Input:l1 = [2,4,3], l2 = [5,6,4]Output:[8,0,7]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [0], l2 = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n def number(head):\n ans = ''\n while head:\n ans+=str(head.val)\n head = head.next\n return int(ans) \n temp = dummy = ListNode(0)\n for i in str(number(l1) + number(l2)):\n temp.next = ListNode(i)\n temp = temp.next\n return dummy.next\n \n\n", + "title": "445. Add Two Numbers II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given s = \"EnjoyYourCoffee\" and spaces = [5, 9] , we place spaces before 'Y' and 'C' , which are at indices 5 and 9 respectively. Thus, we obtain \"Enjoy Y our C offee\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetcodeHelpsMeLearn\", spaces = [8,13,15]Output:\"Leetcode Helps Me Learn\"Explanation:The indices 8, 13, and 15 correspond to the underlined characters in \"LeetcodeHelpsMeLearn\".\nWe then place spaces before those characters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"icodeinpython\", spaces = [1,5,7,9]Output:\"i code in py thon\"Explanation:The indices 1, 5, 7, and 9 correspond to the underlined characters in \"icodeinpython\".\nWe then place spaces before those characters.", + "image": null + }, + { + "text": "Example 3: Input:s = \"spacing\", spaces = [0,1,2,3,4,5,6]Output:\" s p a c i n g\"Explanation:We are also able to place spaces before the first character of the string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 68.74%) | Memory: 81.70 MB (Top 14.26%)\n\nclass Solution {\n public String addSpaces(String s, int[] spaces) {\n StringBuilder sb=new StringBuilder();\n int k=0;\n for(int i=0;i str:\n \n arr = []\n prev = 0\n for space in spaces:\n arr.append(s[prev:space])\n prev = space\n arr.append(s[space:])\n \n return \" \".join(arr)\n", + "title": "2109. Adding Spaces to a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two numbers arr1 and arr2 in base -2 , return the result of adding them together. Each number is given in array format :  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3 .  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1 . Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 1000", + "arr1[i] and arr2[i] are 0 or 1", + "arr1 and arr2 have no leading zeros" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,1,1,1,1], arr2 = [1,0,1]Output:[1,0,0,0,0]Explanation:arr1 represents 11, arr2 represents 5, the output represents 16.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [0], arr2 = [0]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [0], arr2 = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.4 MB (Top 98.61%)\nclass Solution {\n public int[] addNegabinary(int[] arr1, int[] arr2) {\n\n List result = new ArrayList();\n int pointer_1 = arr1.length-1;\n int pointer_2 = arr2.length-1;\n\n int carry = 0;\n int current = 0;\n int sum = 0;\n\n while(pointer_1 >= 0 || pointer_2 >= 0){\n\n int a = (pointer_1 >=0)? arr1[pointer_1]: 0;\n int b = (pointer_2 >=0)? arr2[pointer_2]: 0;\n\n sum = a+b+carry;\n if(sum == 3){\n current = 1; carry = -1;\n }\n else if(sum == 2){\n current = 0; carry = -1;\n }\n else if(sum == 1){\n current = 1; carry = 0;\n }\n else if(sum == 0){\n current = 0; carry = 0;\n }\n else if(sum == -1)\n {\n current = 1; carry = 1;\n }\n\n result.add(current);\n pointer_1--;\n pointer_2--;\n }\n\n if(carry != 0)\n result.add(1);\n if(carry == -1)\n result.add(1);\n\n // Removing leading zeros\n int idx = result.size()-1;\n while(idx > 0 && result.get(idx) == 0)\n idx--;\n\n // reversing the list and adding the result to an array\n int len = idx+1;\n int[] negaBinary = new int[len];\n for(int i=0; i List[int]:\n \n //final answer\n new = []\n carry = 0\n \n\t\t//make arrays length equal \n if len(arr1) < len(arr2):\n diff = len(arr2) - len(arr1)\n arr1 = ([0] * diff) + arr1\n \n if len(arr1) > len(arr2):\n diff = len(arr1) - len(arr2)\n arr2 = ([0] * diff) + arr2\n \n \n \n //add values at every index and set carry and new value appropriately\n while arr1 and arr2:\n \n top = arr1.pop()\n down = arr2.pop()\n \n add = top + down + carry\n \n if add == -1:\n new = [1] + new\n carry = 1\n \n elif add == 1 or add == 0:\n new = [add] + new\n carry = 0\n \n elif add == 2:\n new = [0] + new\n carry = -1\n \n else:\n new = [1] + new\n carry = -1\n \n // if carry -1 add 1 1 since -1 is 11 in negabinary\n if carry == -1:\n new = [1,1] + new\n \n\t\t//remove any leading zeros\n while new[0] == 0 and len(new) >1:\n new = new[1:]\n \n return new\n", + "title": "1073. Adding Two Negabinary Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An additive number is a string whose digits can form an additive sequence . A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 35", + "num consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:\"112358\"Output:trueExplanation:The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8", + "image": null + }, + { + "text": "Example 2: Input:\"199100199\"Output:trueExplanation:The additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public boolean isAdditiveNumber(String num) {\n return backtrack(num, 0, 0, 0, 0);\n }\n \n public boolean backtrack(String num, int idx, long sum, long prev, int length){\n if(idx == num.length()){\n return length >= 3;\n }\n \n long currLong = 0;\n \n for(int i = idx; i < num.length(); i++){\n //make sure it won't start with 0\n if(i > idx && num.charAt(idx) == '0') break;\n currLong = currLong * 10 + num.charAt(i) - '0';\n \n if(length >= 2){\n if(sum < currLong){\n //currLong is greater than sum of previous 2 numbers\n break;\n }else if(sum > currLong){\n //currLong is smaller than sum of previous 2 numbers\n continue;\n }\n }\n //currLong == sum of previous 2 numbers\n if(backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true){\n return true;\n }\n }\n return false;\n }\n}\n", + "title": "306. Additive Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An additive number is a string whose digits can form an additive sequence . A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return true if it is an additive number or false otherwise. Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 35", + "num consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:\"112358\"Output:trueExplanation:The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8", + "image": null + }, + { + "text": "Example 2: Input:\"199100199\"Output:trueExplanation:The additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef isAdditiveNumber(self, num: str) -> bool:\n \n def isadditive(num1,num2,st):\n if len(st) == 0:\n return True\n num3 = str(num1+num2)\n l = len(num3)\n return num3 == st[:l] and isadditive(num2,int(num3),st[l:])\n \n for i in range(1,len(num)-1):\n for j in range(i+1,len(num)):\n if num [0] == \"0\" and i != 1:\n break\n if num[i] == \"0\" and i+1 != j:\n break\n \n if isadditive(int(num[:i]),int(num[i:j]),num[j:]):\n \n return True\n return False\n", + "title": "306. Additive Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i] . Return any permutation of nums1 that maximizes its advantage with respect to nums2 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= 10^5", + "nums2.length == nums1.length", + "0 <= nums1[i], nums2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,7,11,15], nums2 = [1,10,4,11]Output:[2,11,7,15]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [12,24,8,32], nums2 = [13,25,32,11]Output:[24,32,8,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] advantageCount(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n PriorityQueue pq = new PriorityQueue<>((a,b)->(b[0]-a[0]));\n for(int i=0;imax){\n nums2[pos]=nums1[right];\n right--;\n }else{\n nums2[pos]=nums1[left];\n left++;\n }\n }\n return nums2;\n }\n}\n", + "title": "870. Advantage Shuffle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i] . Return any permutation of nums1 that maximizes its advantage with respect to nums2 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= 10^5", + "nums2.length == nums1.length", + "0 <= nums1[i], nums2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,7,11,15], nums2 = [1,10,4,11]Output:[2,11,7,15]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [12,24,8,32], nums2 = [13,25,32,11]Output:[24,32,8,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n # sort by ascend order\n nums1.sort()\n\n # heapq in python is a minimal heap, so if we need to use a maximal heap, the element in the queue should be like: (-num, index)\n q = []\n for i, n in enumerate(nums2):\n heapq.heappush(q, (-n, i))\n\n n = len(nums1)\n l = 0\n r = n - 1\n ans = [0] * n\n\n while q:\n # pop out the maximum number from nums2\n num, i = heapq.heappop(q)\n num = -num\n\n # no number in nums1 > max number in nums2, so grap the minimum numer from nums1\n if nums1[r] <= num:\n ans[i] = nums1[l]\n l += 1\n else:\n ans[i] = nums1[r]\n r -= 1\n\n return ans", + "title": "870. Advantage Shuffle", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Return the probability that the n th person gets his own seat . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Take their own seat if it is still available, and", + "Pick other seats randomly when they find their seat occupied" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:1.00000Explanation:The first person can only get the first seat.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:0.50000Explanation:The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39 MB (Top 96.77%)\nlass Solution {\n public double nthPersonGetsNthSeat(int n) {\n if(n==1)\n return (double)1;\n return (double)1/2;\n }\n}", + "title": "1227. Airplane Seat Assignment Probability", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will: Return the probability that the n th person gets his own seat . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Take their own seat if it is still available, and", + "Pick other seats randomly when they find their seat occupied" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:1.00000Explanation:The first person can only get the first seat.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:0.50000Explanation:The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n\n return 0.5 if n > 1 else 1\n", + "title": "1227. Airplane Seat Assignment Probability", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day . Access times are given in the 24-hour time format \"HH:MM\" , such as \"23:51\" and \"09:49\" . Return a list of unique worker names who received an alert for frequent keycard use . Sort the names in ascending order alphabetically . Notice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= keyName.length, keyTime.length <= 10^5", + "keyName.length == keyTime.length", + "keyTime[i] is in the format \"HH:MM\" .", + "[keyName[i], keyTime[i]] is unique .", + "1 <= keyName[i].length <= 10", + "keyName[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]Output:[\"daniel\"]Explanation:\"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").", + "image": null + }, + { + "text": "Example 2: Input:keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]Output:[\"bob\"]Explanation:\"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List alertNames(String[] keyName, String[] keyTime) {\n Map> map = new HashMap<>();\n\t\t// for every entry in keyName and keyTime, add that time to a priorityqueue for that name\n for(int i=0;i pq = map.getOrDefault(keyName[i], new PriorityQueue());\n\t\t\t//convert the time to an integer (0- 2359 inclusive) for easy comparisons\n pq.add(Integer.parseInt(keyTime[i].substring(0,2))*100+Integer.parseInt(keyTime[i].substring(3)));\n map.put(keyName[i],pq);\n }\n \n\t\t// Generate the \"answer\" list\n List ans = new ArrayList<>();\n for(String s: map.keySet()){\n\t\t\t// For each name in the map, determine if that name used the keycard within 1 hour\n PriorityQueue pq = map.get(s);\n if(active(pq)){\n ans.add(s);\n }\n }\n \n\t\t// Sort the names alphabetically\n Collections.sort(ans);\n return ans;\n }\n \n\t// Greedy function to determine if there were 3 uses within an hour\n private boolean active(PriorityQueue pq){\n\t\t// If there are two or less entries, the user could not have entered 3 times, return false\n if(pq.size()<3) return false;\n\t\t\n\t\t// Create rolling data\n\t\t// Using PriorityQueues, the lowest number is removed first by default\n int a = pq.poll();\n int b = pq.poll();\n int c = pq.poll();\n \n\t\t// Test if two entrances are within 1 hour (100 in integer)\n if(c-a <=100) return true;\n while(pq.size()>0){\n a = b;\n b = c;\n c = pq.poll();\n if(c-a <=100) return true;\n }\n\t\t\n\t\t// If the full Queue has been checked, return false\n return false;\n }\n}\n", + "title": "1604. Alert Using Same Key-Card Three or More Times in a One Hour Period", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day . Access times are given in the 24-hour time format \"HH:MM\" , such as \"23:51\" and \"09:49\" . Return a list of unique worker names who received an alert for frequent keycard use . Sort the names in ascending order alphabetically . Notice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= keyName.length, keyTime.length <= 10^5", + "keyName.length == keyTime.length", + "keyTime[i] is in the format \"HH:MM\" .", + "[keyName[i], keyTime[i]] is unique .", + "1 <= keyName[i].length <= 10", + "keyName[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]Output:[\"daniel\"]Explanation:\"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").", + "image": null + }, + { + "text": "Example 2: Input:keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]Output:[\"bob\"]Explanation:\"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n # 668 ms, 99.52%. Time: O(NlogN). Space: O(N)\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n \n def is_within_1hr(t1, t2):\n h1, m1 = t1.split(\":\")\n h2, m2 = t2.split(\":\")\n if int(h1) + 1 < int(h2): return False\n if h1 == h2: return True\n return m1 >= m2\n \n records = collections.defaultdict(list)\n for name, time in zip(keyName, keyTime):\n records[name].append(time)\n \n rv = []\n for person, record in records.items():\n record.sort()\n\t\t\t# Loop through 2 values at a time and check if they are within 1 hour.\n if any(is_within_1hr(t1, t2) for t1, t2 in zip(record, record[2:])):\n rv.append(person)\n return sorted(rv)\n \n", + "title": "1604. Alert Using Same Key-Card Three or More Times in a One Hour Period", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 ( inclusive ). You are also given a 2D integer array edges , where edges[i] = [from i , to i ] denotes that there is a unidirectional edge from from i to to i in the graph. Return a list answer , where answer[i] is the list of ancestors of the i th node, sorted in ascending order . A node u is an ancestor of another node v if u can reach v via a set of edges. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= edges.length <= min(2000, n * (n - 1) / 2)", + "edges[i].length == 2", + "0 <= from i , to i <= n - 1", + "from i != to i", + "There are no duplicate edges.", + "The graph is directed and acyclic ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]Output:[[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]Explanation:The above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3.", + "image": "https://assets.leetcode.com/uploads/2019/12/12/e1.png" + }, + { + "text": "Example 2: Input:n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Output:[[],[0],[0,1],[0,1,2],[0,1,2,3]]Explanation:The above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3.", + "image": "https://assets.leetcode.com/uploads/2019/12/12/e2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2132 ms (Top 14.62%) | Memory: 30.4 MB (Top 89.89%)\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n graph = {}\n for a, b in edges:\n graph[b] = graph.get(b, []) + [a]\n op = [[] for i in range(n)]\n for a in graph:\n visited = set()\n paths = [a]\n while len(paths) > 0:\n curr = paths.pop()\n for b in graph.get(curr, []):\n if b not in visited:\n visited.add(b)\n paths.append(b)\n op[a] = sorted(visited)\n return op", + "title": "2192. All Ancestors of a Node in a Directed Acyclic Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed binary array nums of length n . nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) nums left and nums right : The division score of an index i is the sum of the number of 0 's in nums left and the number of 1 's in nums right . Return all distinct indices that have the highest possible division score . You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums left has all the elements of nums between index 0 and i - 1 (inclusive) , while nums right has all the elements of nums between index i and n - 1 (inclusive) .", + "If i == 0 , nums left is empty , while nums right has all the elements of nums .", + "If i == n , nums left has all the elements of nums, while nums right is empty ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,0,1,0]Output:[2,4]Explanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleftis [0]. numsrightis [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleftis [0,0]. numsrightis [1,0]. The score is 2 + 1 = 3.\n- 3: numsleftis [0,0,1]. numsrightis [0]. The score is 2 + 0 = 2.\n- 4: numsleftis [0,0,1,0]. numsrightis []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]Output:[3]Explanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleftis [0]. numsrightis [0,0]. The score is 1 + 0 = 1.\n- 2: numsleftis [0,0]. numsrightis [0]. The score is 2 + 0 = 2.\n- 3: numsleftis [0,0,0]. numsrightis []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1]Output:[0]Explanation:Division at index\n- 0: numsleftis []. numsrightis [1,1]. The score is 0 + 2 = 2.\n- 1: numsleftis [1]. numsrightis [1]. The score is 0 + 1 = 1.\n- 2: numsleftis [1,1]. numsrightis []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 98.47%) | Memory: 61.2 MB (Top 91.95%)\nclass Solution {\n public List maxScoreIndices(int[] nums) {\n int N = nums.length;\n List res = new ArrayList<>();\n\n int[] pref = new int[N + 1];\n pref[0] = 0; // at zeroth division we have no elements\n for(int i = 0; i < N; ++i) pref[i+1] = nums[i] + pref[i];\n\n int maxScore = -1;\n int onesToRight, zeroesToLeft, currScore;\n\n for(int i = 0; i < N + 1; ++i) {\n onesToRight = pref[N] - pref[i];\n zeroesToLeft = i - pref[i];\n currScore = zeroesToLeft + onesToRight;\n\n if(currScore > maxScore) {\n res.clear();\n maxScore = currScore;\n }\n if(currScore == maxScore) res.add(i);\n }\n return res;\n }\n}", + "title": "2155. All Divisions With the Highest Score of a Binary Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed binary array nums of length n . nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) nums left and nums right : The division score of an index i is the sum of the number of 0 's in nums left and the number of 1 's in nums right . Return all distinct indices that have the highest possible division score . You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums left has all the elements of nums between index 0 and i - 1 (inclusive) , while nums right has all the elements of nums between index i and n - 1 (inclusive) .", + "If i == 0 , nums left is empty , while nums right has all the elements of nums .", + "If i == n , nums left has all the elements of nums, while nums right is empty ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,0,1,0]Output:[2,4]Explanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleftis [0]. numsrightis [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleftis [0,0]. numsrightis [1,0]. The score is 2 + 1 = 3.\n- 3: numsleftis [0,0,1]. numsrightis [0]. The score is 2 + 0 = 2.\n- 4: numsleftis [0,0,1,0]. numsrightis []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]Output:[3]Explanation:Division at index\n- 0: numsleftis []. numsrightis [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleftis [0]. numsrightis [0,0]. The score is 1 + 0 = 1.\n- 2: numsleftis [0,0]. numsrightis [0]. The score is 2 + 0 = 2.\n- 3: numsleftis [0,0,0]. numsrightis []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1]Output:[0]Explanation:Division at index\n- 0: numsleftis []. numsrightis [1,1]. The score is 0 + 2 = 2.\n- 1: numsleftis [1]. numsrightis [1]. The score is 0 + 1 = 1.\n- 2: numsleftis [1,1]. numsrightis []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5049 ms (Top 67.40%) | Memory: 29.4 MB (Top 23.35%)\nclass Solution:\n def maxScoreIndices(self, nums: List[int]) -> List[int]:\n zeroFromLeft = [0] * (len(nums) + 1)\n oneFromRight = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n if nums[i] == 0:\n zeroFromLeft[i + 1] = zeroFromLeft[i] + 1\n else:\n zeroFromLeft[i + 1] = zeroFromLeft[i]\n\n for i in range(len(nums))[::-1]:\n if nums[i] == 1:\n oneFromRight[i] = oneFromRight[i + 1] + 1\n else:\n oneFromRight[i] = oneFromRight[i + 1]\n\n allSum = [0] * (len(nums) + 1)\n currentMax = 0\n res = []\n for i in range(len(nums) + 1):\n allSum[i] = oneFromRight[i] + zeroFromLeft[i]\n if allSum[i] > currentMax:\n res = []\n currentMax = allSum[i]\n if allSum[i] == currentMax:\n res.append(i)\n return res\n", + "title": "2155. All Divisions With the Highest Score of a Binary Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary search trees root1 and root2 , return a list containing all the integers from both trees sorted in ascending order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 5000] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [2,1,4], root2 = [1,0,3]Output:[0,1,1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png" + }, + { + "text": "Example 2: Input:root1 = [1,null,8], root2 = [8,1]Output:[1,1,8,8]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 53.0%) | Memory: 44.86 MB (Top 93.0%)\n\nclass Solution {\n public List getAllElements(TreeNode root1, TreeNode root2) {\n Stack st1 = new Stack<>();\n Stack st2 = new Stack<>();\n \n List res = new ArrayList<>();\n \n while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){\n while(root1 != null){\n st1.push(root1);\n root1 = root1.left;\n }\n while(root2 != null){\n st2.push(root2);\n root2 = root2.left;\n }\n if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){\n root1 = st1.pop();\n res.add(root1.val);\n root1 = root1.right;\n }\n else{\n root2 = st2.pop();\n res.add(root2.val);\n root2 = root2.right;\n }\n }\n return res;\n }\n}", + "title": "1305. All Elements in Two Binary Search Trees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two binary search trees root1 and root2 , return a list containing all the integers from both trees sorted in ascending order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 5000] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [2,1,4], root2 = [1,0,3]Output:[0,1,1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png" + }, + { + "text": "Example 2: Input:root1 = [1,null,8], root2 = [8,1]Output:[1,1,8,8]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png" + } + ], + "follow_up": null, + "solution": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n \n \n l1,l2=[],[]\n def preorder(root,l):\n if root is None:\n return \n preorder(root.left,l)\n l.append(root.val)\n preorder(root.right,l)\n preorder(root1,l1)\n preorder(root2,l2)\n return sorted(l1+l2)\n", + "title": "1305. All Elements in Two Binary Search Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, the value of a target node target , and an integer k , return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 500] .", + "0 <= Node.val <= 500", + "All the values Node.val are unique .", + "target is the value of one of the nodes in the tree.", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2Output:[7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png" + }, + { + "text": "Example 2: Input:root = [1], target = 1, k = 3Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List distanceK(TreeNode root, TreeNode target, int k) {\n HashMap map=new HashMap<>();\n get_parent(root,map);\n Queue q=new LinkedList<>();\n q.add(target);\n int distance=0;\n HashSet visited=new HashSet<>();\n visited.add(target);\n while(!q.isEmpty())\n {\n if(distance==k)\n break;\n distance++;\n int size=q.size();\n for(int i=0;i ans=new ArrayList<>();\n while(!q.isEmpty())\n ans.add(q.poll().val);\n return ans;\n \n }\n public void get_parent(TreeNode root,HashMap map)\n {\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i K:\n break\n \n for neighbor in graph[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n queue.append((neighbor, distance + 1))\n \n return result\n \n def buildGraph(self, node, parent, graph):\n if not node:\n return\n \n if node not in graph:\n graph[node] = []\n \n if parent:\n graph[node].append(parent)\n graph[parent].append(node)\n \n self.buildGraph(node.left, node, graph)\n self.buildGraph(node.right, node, graph)\n\n", + "title": "863. All Nodes Distance K in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "//Intuitions get from the top answer by @AaronLin1992\nclass AllOne {\n //Thoughts\n //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)?\n //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min\n //to maintain some kind of ordering, the first thing we think about is arrays/lists, however, arrays/lists when insert and delete in the middle, it is O(N) operation\n //so instead, a linked list might work\n //as a result, we considering using Map(s) and LinkedList for our supporting data structures, details below\n \n private Map stringToBucket; //maps a string to bucket\n private Map countToBucket; //maps string count to bucket, note that because when we design this we can have multiple strings in a bucket, that makes it convenient so that for each count, we only need 1 bucket, thus the map data structure\n private BucketList bucketList;\n \n //first, we need to create a class for the LinkedList elements\n class Bucket {\n private Bucket prev;\n private Bucket next;\n \n private int count; //recording the count of instances\n private Set keys; //note that we are using Set of Strings. The reason is because multiple Strings can have the same count and we want to put them in one bucket. This makes the problem easier to solve instead of putting them into different buckets.\n \n Bucket() {\n this.keys = new HashSet<>();\n }\n \n Bucket(String key) {\n this();\n this.count = 1;\n this.keys.add(key);\n }\n \n }\n \n //second, we need to create a linked list data structure of buckets\n class BucketList {\n private Bucket dummyHead; //the fake head before the real head //useful for getMinKey()\n private Bucket dummyTail; //the fake tail before the real tail //useful for getMaxKey()\n \n public BucketList() {\n dummyHead = new Bucket();\n dummyTail = new Bucket();\n dummyHead.next = dummyTail;\n dummyTail.prev = dummyHead;\n }\n \n public Bucket createNewBucket(String key) {\n Bucket bucket = new Bucket(key);\n \n Bucket nextBucket = dummyHead.next;\n dummyHead.next = bucket;\n bucket.prev = dummyHead;\n nextBucket.prev = bucket;\n bucket.next = nextBucket;\n \n return bucket;\n }\n \n public Bucket createBucketToTheRight(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket nextBucket = fromBucket.next;\n fromBucket.next = toBucket;\n toBucket.prev = fromBucket;\n nextBucket.prev = toBucket;\n toBucket.next = nextBucket;\n \n return toBucket;\n }\n \n public Bucket createBucketToTheLeft(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket prevBucket = fromBucket.prev;\n prevBucket.next = toBucket;\n toBucket.prev = prevBucket;\n fromBucket.prev = toBucket;\n toBucket.next = fromBucket;\n \n return toBucket;\n }\n \n public boolean clean(Bucket oldBucket) {//clean bucket if bucket does not have any keys\n if (!oldBucket.keys.isEmpty()) {\n return false;\n }\n \n removeBucket(oldBucket);\n \n return true;\n }\n \n public void removeBucket(Bucket bucket) {\n Bucket prevBucket = bucket.prev;\n Bucket nextBucket = bucket.next;\n \n prevBucket.next = nextBucket;\n nextBucket.prev = prevBucket;\n }\n }\n \n\n public AllOne() {\n this.stringToBucket = new HashMap<>();\n this.countToBucket = new HashMap<>();\n this.bucketList = new BucketList();\n }\n \n public void inc(String key) {\n //first check if the string already present\n if (!stringToBucket.containsKey(key)) { //if not present \n Bucket bucket = null;\n \n //check if there is count of 1 bucket already\n if (!countToBucket.containsKey(1)) { //if does not contain count of 1\n //we need to create a new bucket for count of 1 and add to the head (the minimum). Because count 1 should be the minimum exists in the bucket list\n bucket = bucketList.createNewBucket(key);\n } else { //if contains count of 1\n //then we just need to add the key to the bucket\n bucket = countToBucket.get(1);\n bucket.keys.add(key);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, bucket);\n countToBucket.put(1, bucket);\n } else { //if the key alreay present\n //first of all we need to get the current count for the key\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count++; //increment 1\n //don't forget that we need to remove the key from existing bucket\n oldBucket.keys.remove(key);\n \n //now let's add the key with new count\n if (countToBucket.containsKey(count)) { //if there is already a bucket for this count\n //then just add to the set of keys\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else { //if there is no bucket for this count, create a new bucket, but where to place it? Ans: to the right of the old bucket\n newBucket = bucketList.createBucketToTheRight(oldBucket, key, count); \n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n }\n \n public void dec(String key) {\n //since it is given that \"It is guaranteed that key exists in the data structure before the decrement.\" we don't do additional validation for key exists here\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count--; //decrement\n oldBucket.keys.remove(key);\n \n //special scenario - when count == 0\n if (count == 0) {\n stringToBucket.remove(key);\n } else {\n //now let's find a new bucket for the decremented count\n if (countToBucket.containsKey(count)) {//if there is already a bucket for the count\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else {//if there is no bucket for the count, then following similar logic as before, we need to add a bucket to the left of the existing bucket\n newBucket = bucketList.createBucketToTheLeft(oldBucket, key, count);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n }\n \n public String getMaxKey() {\n Set maxSet = bucketList.dummyTail.prev.keys;\n \n return maxSet.isEmpty() ? \"\" : maxSet.iterator().next(); //if maxSet is empty, that means the bucketList don't have actual buckets\n \n }\n \n public String getMinKey() {\n Set minSet = bucketList.dummyHead.next.keys;\n \n return minSet.isEmpty() ? \"\" : minSet.iterator().next(); //if minSet is empty, that means the bucketList don't have actual buckets\n }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */\n", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\n\nclass Set(object):\n\n def __init__(self):\n self._dict = {}\n self._list = []\n self._len = 0\n\n def add(self, v):\n if v in self._dict:\n pass\n else:\n self._list.append(v)\n self._dict[v] = self._len\n self._len += 1\n\n def __contains__(self, item):\n return item in self._dict\n\n def remove(self, v):\n if v not in self._dict:\n pass\n else:\n idx = self._dict[v]\n\n if idx < self._len - 1:\n self._list[idx] = self._list[-1]\n self._dict[self._list[idx]] = idx\n\n del self._dict[v]\n self._list.pop()\n self._len -= 1\n\n def __iter__(self):\n return iter(self._list)\n\n def check(self):\n assert len(self._dict) == len(self._list)\n for idx, key in enumerate(self._list):\n assert self._dict[key] == idx\n\n def __len__(self):\n return self._len\n\n def __repr__(self):\n return f\"{self._dict}\\n{self._list}\"\n\n\nclass Node(object):\n\n def __init__(self, value):\n self.value = value\n self.prev = None\n self.next = None\n\n def set_prev(self, other_node):\n self.prev = other_node\n if other_node is not None:\n other_node.next = self\n\n def set_next(self, other_node):\n self.next = other_node\n if other_node is not None:\n other_node.prev = self\n\n def __repr__(self):\n return str(self.value)\n\n\nclass SortedKeyList(object):\n\n def __init__(self):\n self.head = Node(value=0)\n self.tail = Node(value=float(\"inf\"))\n self.head.set_next(self.tail)\n\n def is_empty(self):\n return self.head.next is self.tail\n\n def min_key(self):\n if self.is_empty():\n return None\n else:\n return self.head.next.value\n\n def max_key(self):\n if self.is_empty():\n return None\n else:\n return self.tail.prev.value\n\n def incr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value + 1\n next_node = orig_node.next\n if next_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_prev(orig_node)\n new_node.set_next(next_node)\n return self\n\n def decr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value - 1\n prev_node = orig_node.prev\n if prev_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_next(orig_node)\n new_node.set_prev(prev_node)\n return self\n\n def delete_node(self, node):\n prev_node = node.prev\n next_node = node.next\n prev_node.set_next(next_node)\n return self\n\n def __repr__(self):\n a = []\n node = self.head.next\n while True:\n if node is self.tail:\n break\n\n assert node.next.prev is node\n assert node.prev.next is node\n\n a.append(node.value)\n node = node.next\n return str(a)\n\n\nclass AllOne:\n\n def __init__(self):\n self.count_list = SortedKeyList()\n self.counter = defaultdict(lambda: self.count_list.head)\n self.keyed_by_count = defaultdict(set)\n\n def __repr__(self):\n return f\"count_list={self.count_list}\\ncounter={dict(self.counter)}\\nkeyed_by_count={dict(self.keyed_by_count)}\"\n\n def inc(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.incr_key(orig_count_node)\n new_count_node = orig_count_node.next\n new_count = new_count_node.value\n assert new_count == orig_count + 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n if orig_count_node.value > 0:\n self.count_list.delete_node(orig_count_node)\n\n def dec(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.decr_key(orig_count_node)\n new_count_node = orig_count_node.prev\n new_count = new_count_node.value\n assert new_count == orig_count - 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if new_count == 0:\n del self.counter[key]\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n self.count_list.delete_node(orig_count_node)\n\n def getMaxKey(self) -> str:\n max_count = self.count_list.max_key()\n if max_count is not None:\n return next(iter(self.keyed_by_count[max_count]))\n else:\n return \"\"\n\n def getMinKey(self) -> str:\n min_count = self.count_list.min_key()\n if min_count is not None:\n return next(iter(self.keyed_by_count[min_count]))\n else:\n return \"\"\n\n\ndef drive(m, p):\n s = AllOne()\n\n naive_counter = defaultdict(int)\n\n for method, param in zip(m, p):\n if method in (\"inc\", \"dec\"):\n word = param[0]\n\n if method == \"inc\":\n s.inc(word)\n naive_counter[word] += 1\n\n elif method == 'dec':\n s.dec(word)\n naive_counter[word] -= 1\n\n if naive_counter[word] == 0:\n del naive_counter[word]\n\n tmp_counter = defaultdict(set)\n for k, v in naive_counter.items():\n tmp_counter[v].add(k)\n\n sorted_keys = sorted(tmp_counter.keys())\n min_key = sorted_keys[0]\n max_key = sorted_keys[-1]\n\n if s.getMaxKey() not in tmp_counter[max_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n if s.getMinKey() not in tmp_counter[min_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n return None, None, None\n\n\nif __name__ == '__main__':\n m = [\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n p = [[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\n s, naive_counter, tmp_counter = drive(m, p)\n", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a directed acyclic graph ( DAG ) of n nodes labeled from 0 to n - 1 , find all possible paths from node 0 to node n - 1 and return them in any order . The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j] ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == graph.length", + "2 <= n <= 15", + "0 <= graph[i][j] < n", + "graph[i][j] != i (i.e., there will be no self-loops).", + "All the elements of graph[i] are unique .", + "The input graph is guaranteed to be a DAG ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[3],[3],[]]Output:[[0,1,3],[0,2,3]]Explanation:There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg" + }, + { + "text": "Example 2: Input:graph = [[4,3,1],[3,2,4],[3],[4],[]]Output:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg" + } + ], + "follow_up": null, + "solution": "Approach : Using dfs+ backtracking we can solve it\t\n\t\n\tclass Solution {\n\t\tpublic List> allPathsSourceTarget(int[][] graph) {\n\t\t\tList> ans=new ArrayList<>();\n\t\t\tList temp=new ArrayList<>();\n\t\t\t boolean []visit=new boolean [graph.length];\n\t\t\thelper(graph,0,graph.length-1,ans,temp,visit);\n\n\t\t\treturn ans;\n\t\t}\n\t\tpublic void helper(int[][] graph, int src,int dest,List> ans,List temp,boolean[]vis)\n\t\t{\n\n\t\t\tvis[src]=true;\n\t\t\ttemp.add(src);\n\t\t\tif(src==dest)\n\t\t\t{\n\t\t\t\tList b =new ArrayList<>();\n\t\t\t\tfor(int h:temp){\n\t\t\t\t\tb.add(h);\n\t\t\t\t}\n\t\t\t\tans.add(b);\n\t\t\t}\n\n\t\t\tfor(int i:graph[src])\n\t\t\t{\n\t\t\t\tif(vis[i]!=true)\n\t\t\t\t{\n\t\t\t\t\thelper(graph,i,dest,ans,temp,vis);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tvis[src]=false;\n\t\t\ttemp.remove(temp.size()-1);\n\t\t}\n\t}\n", + "title": "797. All Paths From Source to Target", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a directed acyclic graph ( DAG ) of n nodes labeled from 0 to n - 1 , find all possible paths from node 0 to node n - 1 and return them in any order . The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j] ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == graph.length", + "2 <= n <= 15", + "0 <= graph[i][j] < n", + "graph[i][j] != i (i.e., there will be no self-loops).", + "All the elements of graph[i] are unique .", + "The input graph is guaranteed to be a DAG ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[3],[3],[]]Output:[[0,1,3],[0,2,3]]Explanation:There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_1.jpg" + }, + { + "text": "Example 2: Input:graph = [[4,3,1],[3,2,4],[3],[4],[]]Output:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]", + "image": "https://assets.leetcode.com/uploads/2020/09/28/all_2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n res = []\n self.explore(graph, graph[0], [0], res)\n return res\n \n def explore(self, graph, candidates, step, res):\n if step[-1] == len(graph)-1:\n res.append(list(step))\n else:\n for i in range(len(candidates)):\n step.append(candidates[i])\n self.explore(graph, graph[candidates[i]], step, res)\n step.pop()\n", + "title": "797. All Paths From Source to Target", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return a list of all possible full binary trees with n nodes . Each node of each tree in the answer must have Node.val == 0 . Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order . A full binary tree is a binary tree where each node has exactly 0 or 2 children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" + }, + { + "text": "Example 2: Input:n = 3Output:[[0,0,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 43.9 MB (Top 94.53%)\nclass Solution {\n List[] memo;\n public List allPossibleFBT(int n) {\n memo = new ArrayList[n+1];\n return dp(n);\n }\n\n public List dp(int n){\n if(n==0 || n==2){\n return new ArrayList();\n }\n if(n==1){\n List temp = new ArrayList<>();\n temp.add(new TreeNode(0));\n return temp;\n }\n List res = new ArrayList<>();\n for(int i=1;i right;\n List left;\n if(memo[i]!=null) right = memo[i];\n else right = dp(i);\n if(memo[n-1-i]!=null) left = memo[n-1-i];\n else left = dp(n-1-i);\n\n for(TreeNode l : left){\n for(TreeNode r : right){\n TreeNode temp = new TreeNode(0);\n temp.left=l;\n temp.right=r;\n res.add(temp);\n }\n }\n }\n memo[n] = res;\n return res;\n\n }\n}", + "title": "894. All Possible Full Binary Trees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a list of all possible full binary trees with n nodes . Each node of each tree in the answer must have Node.val == 0 . Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order . A full binary tree is a binary tree where each node has exactly 0 or 2 children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" + }, + { + "text": "Example 2: Input:n = 3Output:[[0,0,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "We can't create Full Binary tree with even number of nodes. e.g n = 2/4/6/8...\nstart with cache having n = 1\n\tcache = {1:TreeNode()}\n\t\n\tn = 3\n\t\t\t\t\t\t\t0 (root)\n\t\t\t\t\t\t 1 1\n\tn = 5 \n\t 0 (root1) 0 (root2) \n\t\t\t\t\t\t 1 3 3 1\n\tn = 7 \n\t 0 0 0\n\t\t\t\t\t\t 1 5 3 3 5 1\n\n\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n def helper(n):\n if n in cache:\n return cache[n]\n # We use result array to store all possible binary tree of size n\n result = [] \n leftNodes, rightNodes = 1,n-2\n # if n = 7 then, (leftNodes,rightNodes) should be : (1,5),(3,3),(5,1) \n while rightNodes >0:\n root = TreeNode()\n if leftNodes not in cache:\n helper(leftNodes)\n if rightNodes not in cache:\n helper(rightNodes)\n leftTree = cache[leftNodes]\n rightTree = cache[rightNodes]\n # Using two for loops we generate all possible binary tree.\n # Always remember root of each binary tree is diffrent, So create new root every time\n for i in range(len(leftTree)):\n for j in range(len(rightTree)):\n root.left = leftTree[i]\n root.right = rightTree[j]\n result.append(root)\n root = TreeNode()\n leftNodes += 2\n rightNodes -= 2\n cache[n] = result\n return result\n \n if n % 2 == 0:\n return \n else:\n cache = {1:[TreeNode()]}\n return helper(n)\n\t\t\t\nThank You 😊\n\n", + "title": "894. All Possible Full Binary Trees", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array houses where houses[i] is the location of the i th house along a street and an integer k , allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= houses.length <= 100", + "1 <= houses[i] <= 10^4", + "All the integers of houses are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,4,8,10,20], k = 3Output:5Explanation:Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" + }, + { + "text": "Example 2: Input:houses = [2,3,5,12,18], k = 2Output:9Explanation:Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 85.53%) | Memory: 42.5 MB (Top 53.95%)\nclass Solution {\n public int minDistance(int[] houses, int k) {\n Arrays.sort(houses);\n int n = houses.length;\n int[] dp = new int[n];\n for (int i = 1; i < n; i++){ // know optimal dist for i-1, then for i, we add houses[i] - houses[i/2]\n dp[i]=dp[i-1]+houses[i]-houses[i/2];\n }\n for (int i = 0; i < k-1; i++){\n int[] next = new int[n];\n Arrays.fill(next, Integer.MAX_VALUE);\n for (int j = 0; j < n; j++){\n int sum = 0;\n for (int m = j; m >= 0; m--){\n sum += houses[(m+j+1)>>1]-houses[m]; // likewise, adding to the front needs the +1 to account for the truncation.\n next[j] = Math.min(next[j], (m==0?0:dp[m-1])+sum);\n }\n }\n dp=next;\n }\n return dp[n-1];\n }\n}", + "title": "1478. Allocate Mailboxes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the array houses where houses[i] is the location of the i th house along a street and an integer k , allocate k mailboxes in the street. Return the minimum total distance between each house and its nearest mailbox . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= houses.length <= 100", + "1 <= houses[i] <= 10^4", + "All the integers of houses are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,4,8,10,20], k = 3Output:5Explanation:Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" + }, + { + "text": "Example 2: Input:houses = [2,3,5,12,18], k = 2Output:9Explanation:Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.", + "image": "https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n houses.sort()\n\n @lru_cache(None)\n def dp(left, right, k):\n if k == 1: # <-- 1.\n mid = houses[(left+right) // 2]\n return sum(abs(houses[i] - mid) for i in range(left, right + 1))\n\n return min(dp(left, i, 1) + dp(i+1, right, k - 1) \n for i in range(left, right - k + 2)) # <-- 2.\n\n return dp(0, len(houses)-1, k)", + "title": "1478. Allocate Mailboxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an alphabet board, we start at position (0, 0) , corresponding to character board[0][0] . Here, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"] , as shown in the diagram below. We may make the following moves: (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/07/28/azboard.png" + ], + "constraints": [ + "'U' moves our position up one row, if the position exists on the board;", + "'D' moves our position down one row, if the position exists on the board;", + "'L' moves our position left one column, if the position exists on the board;", + "'R' moves our position right one column, if the position exists on the board;", + "'!' adds the character board[r][c] at our current position (r, c) to the answer." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"leet\"Output:\"DDR!UURRR!!DDD!\"", + "image": null + }, + { + "text": "Example 2: Input:target = \"code\"Output:\"RR!DDRR!UUL!R!\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.07 MB (Top 98.6%)\n\nclass Solution {\n public String alphabetBoardPath(String target) {\n int x = 0, y = 0;\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < target.length(); i++){\n char ch = target.charAt(i);\n int x1 = (ch - 'a') / 5;\n int y1 = (ch - 'a') % 5;\n while(x1 < x) {x--; sb.append('U');}\n while(y1 > y) {y++; sb.append('R');}\n while(y1 < y) {y--; sb.append('L');}\n while(x1 > x) {x++; sb.append('D');}\n sb.append('!');\n }\n return sb.toString();\n }\n}", + "title": "1138. Alphabet Board Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an alphabet board, we start at position (0, 0) , corresponding to character board[0][0] . Here, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"] , as shown in the diagram below. We may make the following moves: (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/07/28/azboard.png" + ], + "constraints": [ + "'U' moves our position up one row, if the position exists on the board;", + "'D' moves our position down one row, if the position exists on the board;", + "'L' moves our position left one column, if the position exists on the board;", + "'R' moves our position right one column, if the position exists on the board;", + "'!' adds the character board[r][c] at our current position (r, c) to the answer." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"leet\"Output:\"DDR!UURRR!!DDD!\"", + "image": null + }, + { + "text": "Example 2: Input:target = \"code\"Output:\"RR!DDRR!UUL!R!\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 16.25%) | Memory: 14 MB (Top 13.50%)\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n def shortestPath(r,c,tr,tc):\n path = \"\"\n pr = r\n while r > tr:\n path += 'U'\n r -= 1\n while r < tr:\n path += 'D'\n r += 1\n if tr == 5 and pr != tr: path = path[:len(path) - 1]\n while c > tc:\n path += 'L'\n c -= 1\n while c < tc:\n path += 'R'\n c += 1\n if tr == 5 and pr != tr: path = path + 'D'\n return path\n\n table = ['abcde','fghij','klmno','pqrst','uvwxy','z']\n r,c = 0,0\n ans = \"\"\n for character in target:\n t_row = None\n for i,word in enumerate(table):\n if character in word:\n t_row = i\n break\n t_col = table[i].index(character)\n ans += shortestPath(r,c,t_row,t_col) + '!'\n r,c = t_row,t_col\n return ans", + "title": "1138. Alphabet Board Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\" . Then, we removed all commas, decimal points, and spaces and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been . Our original representation never had extraneous zeroes, so we never started with numbers like \"00\" , \"0.0\" , \"0.00\" , \"1.0\" , \"001\" , \"00.01\" , or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\" . The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(123)\"Output:[\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"(0123)\"Output:[\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]Explanation:0.0, 00, 0001 or 00.01 are not allowed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(00011)\"Output:[\"(0, 0.011)\",\"(0.001, 1)\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List ret;\n public List ans;\n public List ambiguousCoordinates(String s) {\n ret=new ArrayList<>();\n ans=new ArrayList<>();\n String start=s.substring(0,2);\n util(s,1);\n fun();\n return ans;\n }\n \n //putting comma\n void util(String s,int idx) {\n if(idx==s.length()-2) {\n return;\n }\n \n String ns=s.substring(0,idx+1)+\", \"+s.substring(idx+1);\n ret.add(ns);\n util(s,idx+1);\n }\n \n //helper function for puting decimals after comma\n void fun() {\n for(String s:ret) {\n int cIndex=0;\n for(int i=0;i n1=dot(a);\n List n2=dot(b);\n if(n1==null || n2==null) { //invalid strings\n continue;\n }else { //valid strings\n for(String fir:n1) {\n for(String sec:n2) {\n ans.add(\"(\"+fir+\", \"+sec+\")\");\n }\n }\n }\n }\n }\n \n //putting decimal point\n List dot(String n) {\n List li=new ArrayList<>();\n if(n.length()==1) {\n li.add(n);\n }else {\n \n //just checking for first and last zeroes and making conditions accordingly\n\n if(n.charAt(n.length()-1)=='0') {\n if(n.charAt(0)=='0') {\n return null;\n }else {\n li.add(n);\n }\n }else if(n.charAt(0)=='0') {\n li.add(\"0.\"+n.substring(1));\n }else {\n for(int i=0;i1 and re.match('/^[0]+$/',s) else True\n\n def _isValidNum(ipart,fpart):\n return False if (len(ipart)>1 and ipart[0]=='0') or (fpart and fpart[-1]=='0') else True\n\n def _splitToNums(s):\n rets=[]\n if len(s)==1:return [s]\n for i in range(1,len(s)+1):\n a,b=s[:i],s[i:]\n if _isValidNum(a,b):rets.append(\"%s.%s\"%(a,b) if b else \"%s\"%(a))\n return rets\n\n ans,s=[],s[1:-1]\n for i in range(1,len(s)):\n a,b=s[:i],s[i:]\n if not _isValidSplit(a) or not _isValidSplit(b):continue\n for c1,c2 in itertools.product(_splitToNums(a),_splitToNums(b)):ans.append(\"(%s, %s)\"%(c1,c2))\n return ans", + "title": "816. Ambiguous Coordinates", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two numbers, hour and minutes , return the smaller angle (in degrees) formed between the hour and the minute hand . Answers within 10 -5 of the actual value will be accepted as correct. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= hour <= 12", + "0 <= minutes <= 59" + ], + "examples": [ + { + "text": "Example 1: Input:hour = 12, minutes = 30Output:165", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png" + }, + { + "text": "Example 2: Input:hour = 3, minutes = 30Output:75", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png" + }, + { + "text": "Example 3: Input:hour = 3, minutes = 15Output:7.5", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 38.02%)\nclass Solution {\n public double angleClock(int hour, int minutes) {\n // Position of hour hand in a circle of 0 - 59\n double hrPos = 5 * (hour % 12);\n\n // Adjust hour hand position according to minute hand\n hrPos += (5 * minutes/60.0);\n\n double units = Math.abs(minutes - hrPos);\n\n // Take the min of distance between minute & hour hand and hour & minute hand\n return Math.min(units, 60-units) * 6;\n }\n}", + "title": "1344. Angle Between Hands of a Clock", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two numbers, hour and minutes , return the smaller angle (in degrees) formed between the hour and the minute hand . Answers within 10 -5 of the actual value will be accepted as correct. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= hour <= 12", + "0 <= minutes <= 59" + ], + "examples": [ + { + "text": "Example 1: Input:hour = 12, minutes = 30Output:165", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png" + }, + { + "text": "Example 2: Input:hour = 3, minutes = 30Output:75", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png" + }, + { + "text": "Example 3: Input:hour = 3, minutes = 15Output:7.5", + "image": "https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n \n x = abs(minutes * 6 -(hour * 30 + minutes/2))\n return min(360-x , x)\n", + "title": "1344. Angle Between Hands of a Clock", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum . Return the sum of the k integers appended to nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,25,10,25], k = 2Output:5Explanation:The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6], k = 6Output:25Explanation:The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 563 ms (Top 89.1%) | Memory: 31.37 MB (Top 44.5%)\n\nclass Solution:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n ans = k*(k+1)//2\n prev = -inf \n for x in sorted(nums): \n if prev < x: \n if x <= k: \n k += 1\n ans += k - x\n else: break\n prev = x\n return ans ", + "title": "2195. Append K Integers With Minimal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices , where the i th product has an ID of products[i] and a price of prices[i] . When a customer is paying, their bill is represented as two parallel integer arrays product and amount , where the j th product they purchased has an ID of product[j] , and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the j th product) . The supermarket decided to have a sale. Every n th customer paying for their groceries will be given a percentage discount . The discount amount is given by discount , where they will be given discount percent off their subtotal. More formally, if their subtotal is bill , then they would actually pay bill * ((100 - discount) / 100) . Implement the Cashier class: Example 1:", + "description_images": [], + "constraints": [ + "Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n , the discount , and the products and their prices .", + "double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10 -5 of the actual value will be accepted." + ], + "examples": [ + { + "text": "Example 1: Input[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]Output[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]ExplanationCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1stcustomer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2ndcustomer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rdcustomer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4thcustomer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5thcustomer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6thcustomer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6thcustomer, no discount.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 93.75%) | Memory: 76.80 MB (Top 6.6%)\n\nclass Cashier {\n private final int[] prices;\n private final int n;\n private final int discount;\n private int customerNumber;\n\n public Cashier(int n, int discount, int[] products, int[] prices) {\n this.prices = new int[200];\n\n for(int i = 0; i < products.length; ++i)\n this.prices[products[i] - 1] = prices[i];\n\n this.n = n;\n this.discount = discount;\n this.customerNumber = 1;\n }\n \n public double getBill(int[] product, int[] amount) {\n double sum = 0;\n\n for(int i = 0; i < product.length; ++i)\n sum += this.prices[product[i] - 1] * amount[i];\n\n if(this.customerNumber != 0 && this.customerNumber % n == 0)\n sum *= (double) (100 - this.discount) / 100;\n\n this.customerNumber++;\n\n return sum;\n }\n}\n\n/**\n * Your Cashier object will be instantiated and called as such:\n * Cashier obj = new Cashier(n, discount, products, prices);\n * double param_1 = obj.getBill(product,amount);\n */\n", + "title": "1357. Apply Discount Every n Orders", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices , where the i th product has an ID of products[i] and a price of prices[i] . When a customer is paying, their bill is represented as two parallel integer arrays product and amount , where the j th product they purchased has an ID of product[j] , and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the j th product) . The supermarket decided to have a sale. Every n th customer paying for their groceries will be given a percentage discount . The discount amount is given by discount , where they will be given discount percent off their subtotal. More formally, if their subtotal is bill , then they would actually pay bill * ((100 - discount) / 100) . Implement the Cashier class: Example 1:", + "description_images": [], + "constraints": [ + "Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n , the discount , and the products and their prices .", + "double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10 -5 of the actual value will be accepted." + ], + "examples": [ + { + "text": "Example 1: Input[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]Output[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]ExplanationCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1stcustomer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2ndcustomer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rdcustomer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4thcustomer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5thcustomer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6thcustomer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6thcustomer, no discount.", + "image": null + } + ], + "follow_up": null, + "solution": "class Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n \n self.n = n \n self.discount = discount \n self.price = { }\n self.customer = 0 \n \n for i in range(len(products)) : \n self.price[products[i]] = prices[i]\n\n def getBill(self, product: List[int], amount: List[int]) -> float:\n \n self.customer += 1\n \n bill = 0 \n \n for i in range(len(product)) : \n bill += amount[i] * self.price[product[i]]\n \n \n if self.customer == self.n : \n bill = bill * (1 - self.discount / 100)\n self.customer = 0 \n \n \n return bill\n \n \n\n\n# Your Cashier object will be instantiated and called as such:\n# obj = Cashier(n, discount, products, prices)\n# param_1 = obj.getBill(product,amount)\n", + "title": "1357. Apply Discount Every n Orders", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$' . A word represents a price if it is a sequence of digits preceded by a dollar sign. You are given a string sentence representing a sentence and an integer discount . For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence . Note that all prices will contain at most 10 digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"$100\" , \"$23\" , and \"$6\" represent prices while \"100\" , \"$\" , and \"$1e5\" do not." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50Output:\"there are $0.50 $1.00 and 5$ candies in the shop\"Explanation:The words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100Output:\"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"Explanation:Applying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public String discountPrices(String sentence, int discount) {\n String x[] = sentence.split(\" \");\n StringBuilder sb = new StringBuilder();\n for (String s : x) {\n if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + \" \"); \n else sb.append(s + \" \");\n }\n sb.deleteCharAt(sb.length() - 1);\n return sb.toString();\n }\n\n boolean isPrice(String s) {\n return s.startsWith(\"$\") && s.substring(1).matches(\"\\\\d+\");\n }\n\n String calc(double num, double discount) {\n double ans = num - (double) ((double) num * discount / 100.00);\n return \"$\" + String.format(\"%.2f\", ans);\n }\n}\n", + "title": "2288. Apply Discount to Prices", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$' . A word represents a price if it is a sequence of digits preceded by a dollar sign. You are given a string sentence representing a sentence and an integer discount . For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places. Return a string representing the modified sentence . Note that all prices will contain at most 10 digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"$100\" , \"$23\" , and \"$6\" represent prices while \"100\" , \"$\" , and \"$1e5\" do not." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50Output:\"there are $0.50 $1.00 and 5$ candies in the shop\"Explanation:The words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100Output:\"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"Explanation:Applying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n s = sentence.split() # convert to List to easily update\n m = discount / 100 \n for i,word in enumerate(s):\n if word[0] == \"$\" and word[1:].isdigit(): # Check whether it is in correct format\n num = int(word[1:]) * (1-m) # discounted price\n w = \"$\" + \"{:.2f}\".format(num) #correctly format\n s[i] = w #Change inside the list\n \n return \" \".join(s) #Combine the updated list\n\t\t```", + "title": "2288. Apply Discount to Prices", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums , return the number of arithmetic subarrays of nums . A subarray is a contiguous subsequence of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1,3,5,7,9] , [7,7,7,7] , and [3,-1,-5,-9] are arithmetic sequences." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:3Explanation:We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n = nums.length;\n if (n < 3) {\n return 0;\n }\n int[] dp = new int[n - 1];\n dp[0] = nums[1] - nums[0];\n for (int i = 2; i < n; i++) {\n dp[i - 1] = nums[i] - nums[i - 1];\n }\n int si = 0;\n int count = 0;\n for (int i = 1; i < n - 1; i++) {\n if (dp[i] == dp[i - 1]) {\n count += (i - si);\n } else {\n si = i;\n }\n }\n return count;\n }\n}\n", + "title": "413. Arithmetic Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. Given an integer array nums , return the number of arithmetic subarrays of nums . A subarray is a contiguous subsequence of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1,3,5,7,9] , [7,7,7,7] , and [3,-1,-5,-9] are arithmetic sequences." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:3Explanation:We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 86.27%) | Memory: 16.90 MB (Top 84.26%)\n\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n ans = 0\n table = [0] * len(nums)\n\n for r in range(2, len(nums)):\n diff1 = nums[r] - nums[r-1]\n diff2 = nums[r-1] - nums[r-2]\n\n if diff1 == diff2:\n table[r] = table[r-1] + 1\n ans += table[r-1] + 1\n\n return ans\n", + "title": "413. Arithmetic Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the number of all the arithmetic subsequences of nums . A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1, 3, 5, 7, 9] , [7, 7, 7, 7] , and [3, -1, -5, -9] are arithmetic sequences.", + "For example, [1, 1, 2, 5, 7] is not an arithmetic sequence." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,6,8,10]Output:7Explanation:All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7]Output:16Explanation:Any subsequence of this array is arithmetic.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n=nums.length;\n \n HashMap []dp=new HashMap[n];\n \n for(int i=0;i();\n }\n \n int ans=0;\n \n for(int i=1;i=Integer.MAX_VALUE){\n continue;\n }\n \n int endingAtj=dp[j].getOrDefault((int)cd,0);\n int endingAti=dp[i].getOrDefault((int)cd,0);\n \n ans+=endingAtj;\n \n dp[i].put((int)cd,endingAtj+endingAti+1);\n }\n }\n \n return ans;\n }\n}\n", + "title": "446. Arithmetic Slices II - Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of all the arithmetic subsequences of nums . A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. The test cases are generated so that the answer fits in 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1, 3, 5, 7, 9] , [7, 7, 7, 7] , and [3, -1, -5, -9] are arithmetic sequences.", + "For example, [1, 1, 2, 5, 7] is not an arithmetic sequence." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,6,8,10]Output:7Explanation:All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7]Output:16Explanation:Any subsequence of this array is arithmetic.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0\n for i in range(1, sz):\n for j in range(i):\n difference = nums[i] - nums[j]\n dp[i][difference] += 1\n if difference in dp[j]:\n dp[i][difference] += dp[j][difference]\n ans += dp[j][difference]\n return ans\n", + "title": "446. Arithmetic Slices II - Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i . For example, these are arithmetic sequences: The following sequence is not arithmetic : You are given an array of n integers, nums , and two arrays of m integers each, l and r , representing the m range queries, where the i th query is the range [l[i], r[i]] . All the arrays are 0-indexed . Return a list of boolean elements answer , where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "m == l.length", + "m == r.length", + "2 <= n <= 500", + "1 <= m <= 500", + "0 <= l[i] < r[i] < n", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums =[4,6,5,9,3,7], l =[0,0,2], r =[2,3,5]Output:[true,false,true]Explanation:In the 0thquery, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1stquery, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2ndquery, the subarray is[5,9,3,7]. Thiscan be rearranged as[3,5,7,9], which is an arithmetic sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]Output:[false,true,false,false,true,true]", + "image": null + }, + { + "text": "1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9", + "image": null + }, + { + "text": "1, 1, 2, 5, 7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 83.14%) | Memory: 45.90 MB (Top 9.57%)\n\nclass Solution {\n public Boolean check(int[] arr) {\n Arrays.sort(arr);\n int diff = arr[1] - arr[0];\n \n for (int i = 2; i < arr.length; i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false;\n }\n }\n \n return true;\n }\n \n public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List ans = new ArrayList();\n for (int i = 0; i < l.length; i++) {\n int[] arr = new int[r[i] - l[i] + 1];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = nums[l[i] + j];\n }\n \n ans.add(check(arr));\n }\n\n return ans;\n }\n}\n\n", + "title": "1630. Arithmetic Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i . For example, these are arithmetic sequences: The following sequence is not arithmetic : You are given an array of n integers, nums , and two arrays of m integers each, l and r , representing the m range queries, where the i th query is the range [l[i], r[i]] . All the arrays are 0-indexed . Return a list of boolean elements answer , where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "m == l.length", + "m == r.length", + "2 <= n <= 500", + "1 <= m <= 500", + "0 <= l[i] < r[i] < n", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums =[4,6,5,9,3,7], l =[0,0,2], r =[2,3,5]Output:[true,false,true]Explanation:In the 0thquery, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1stquery, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2ndquery, the subarray is[5,9,3,7]. Thiscan be rearranged as[3,5,7,9], which is an arithmetic sequence.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]Output:[false,true,false,false,true,true]", + "image": null + }, + { + "text": "1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9", + "image": null + }, + { + "text": "1, 1, 2, 5, 7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 22.81%) | Memory: 17.70 MB (Top 6.09%)\n\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n ans = []\n \n def find_diffs(arr):\n \n arr.sort()\n\n dif = []\n \n for i in range(len(arr) - 1):\n dif.append(arr[i] - arr[i + 1])\n \n return len(set(dif)) == 1\n \n for i , j in zip(l , r):\n ans.append(find_diffs(nums[i:j + 1]))\n \n return ans\n", + "title": "1630. Arithmetic Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i th row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n , return the number of complete rows of the staircase you will build . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:Because the 3rdrow is incomplete, we return 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 8Output:3Explanation:Because the 4throw is incomplete, we return 3.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 44.14%) | Memory: 40.7 MB (Top 83.77%)\nclass Solution {\n public int arrangeCoins(int n) {\n long s =0; long e = n;\n while (s <= e) {\n long mid = s +(e-s)/2;\n long coin = mid *( mid +1)/2;\n if(coin > n){\n e = mid -1;\n } else if (coin < n){\n s = mid +1;\n } else return (int) mid;\n }\n return (int)e;\n }\n}", + "title": "441. Arranging Coins", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the i th row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n , return the number of complete rows of the staircase you will build . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:Because the 3rdrow is incomplete, we return 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 8Output:3Explanation:Because the 4throw is incomplete, we return 3.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 6683 ms (Top 5.01%) | Memory: 13.8 MB (Top 57.45%)\nclass Solution:\n def arrangeCoins(self, n: int) -> int:\n for i in range(1,2**31):\n val=i*(i+1)//2\n if val>n:\n a=i\n break\n elif val==n:\n return i\n return a-1", + "title": "441. Arranging Coins", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1] . You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: Return the longest length of a set s[k] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first element in s[k] starts with the selection of the element nums[k] of index = k .", + "The next element in s[k] should be nums[nums[k]] , and then nums[nums[nums[k]]] , and so on.", + "We stop adding right before a duplicate element occurs in s[k] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,4,0,3,1,6,2]Output:4Explanation:nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int arrayNesting(int[] nums) {\n int res=0;\n boolean[] visited = new boolean[nums.length];\n for(int i=0;i int:\n max_len = 0\n visited = set()\n def dfs(nums, index, dfs_visited):\n if index in dfs_visited:\n return len(dfs_visited)\n \n # add the index to dfs_visited and visited\n visited.add(index)\n dfs_visited.add(index)\n return dfs(nums, nums[index], dfs_visited)\n \n for i in range(len(nums)):\n if i not in visited:\n max_len = max(max_len, dfs(nums, i, set()))\n return max_len\n", + "title": "565. Array Nesting", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array of even length arr , return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2 , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 3 * 10^4", + "arr.length is even.", + "-10^5 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,3,6]Output:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,1,2,6]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,-2,2,-4]Output:trueExplanation:We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReorderDoubled(int[] arr) {\n Map map=new HashMap<>();\n int zeroCount=0,out=0,len=arr.length;\n Arrays.sort(arr);\n for(int ar:arr){\n if(ar%2==1)\n map.put(ar,map.getOrDefault(ar,0)+1);\n else\n {\n if(ar>0)\n {\n int val=map.getOrDefault(ar/2,0);\n if(val>0){\n out++;\n map.put(ar/2,val-1);\n }\n else map.put(ar,map.getOrDefault(ar,0)+1);\n }\n else if(ar<0)\n {\n int val=map.getOrDefault(ar2,0);\n if(val>0){\n out++;\n map.put(ar2,val-1);\n } \n else map.put(ar,map.getOrDefault(ar,0)+1);\n }\n else zeroCount++; \n }\n }\n zeroCount=zeroCount/2;\n return out+zeroCount==len/2;\n }\n}\n", + "title": "954. Array of Doubled Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array of even length arr , return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2 , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 3 * 10^4", + "arr.length is even.", + "-10^5 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,3,6]Output:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,1,2,6]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,-2,2,-4]Output:trueExplanation:We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1769 ms (Top 5.17%) | Memory: 16.6 MB (Top 56.95%)\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n n = len(arr)\n arr.sort()\n times = n//2\n count = {}\n for i in arr :\n if i in count:count[i] += 1\n else: count[i] = 1\n for i in count:\n if i == 0:\n tmp = count[0]//2\n times -= tmp\n if times <=0 : return True\n else:\n if i*2 in count:\n ct1 = count[i]\n ct2 = count[i*2]\n while ct1 > 0 and ct2 > 0 and times > 0:\n ct1 -= 1\n ct2 -= 1\n times -= 1\n count[i] = ct1\n count[i*2] = ct2\n if times == 0:return True\n return False", + "title": "954. Array of Doubled Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums of 2n integers, group these integers into n pairs (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) such that the sum of min(a i , b i ) for all i is maximized . Return the maximized sum . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "nums.length == 2 * n", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,2]Output:4Explanation:All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,6,5,1,2]Output:9Explanation:The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 17.21%) | Memory: 54.6 MB (Top 23.48%)\nclass Solution {\n public int arrayPairSum(int[] nums) {\n Arrays.sort(nums);\n int sum = 0;\n for(int i = 0; i < nums.length; i+=2){\n sum += nums[i];\n }\n return sum;\n }\n}", + "title": "561. Array Partition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums of 2n integers, group these integers into n pairs (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) such that the sum of min(a i , b i ) for all i is maximized . Return the maximized sum . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "nums.length == 2 * n", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,2]Output:4Explanation:All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,6,5,1,2]Output:9Explanation:The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n \n nums = sorted(nums)\n \n summ = 0\n for i in range(0,len(nums),2):\n summ += min(nums[i],nums[i+1])\n return summ", + "title": "561. Array Partition", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors. More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1 , (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i] . Return any rearrangement of nums that meets the requirements . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]Output:[1,2,4,5,3]Explanation:When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,2,0,9,7]Output:[9,7,6,2,0]Explanation:When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 67 ms (Top 33.85%) | Memory: 147.3 MB (Top 73.33%)\nclass Solution {\n public int[] rearrangeArray(int[] nums) {\n Arrays.sort(nums);\n // sort in wave format\n for(int i = 0;i List[int]:\n for i in range(1, len(nums) -1):\n pre = nums[i-1]\n current = nums[i]\n next = nums[i+1]\n \n # If block will run when we meet 1 2 3 or 6 4 2\n if (pre < current < next) or (pre > current > next):\n # Swap next and current\n # For example: \n # 1 2 3 -> 1 3 2\n # 6 4 2 -> 6 2 4\n nums[i+1], nums[i] = nums[i], nums[i+1]\n \n return nums\n", + "title": "1968. Array With Elements Not Equal to Average of Neighbors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n grid containing only values 0 and 1 , where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1 . The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1| . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,1],[0,0,0],[1,0,1]]Output:2Explanation:The cell (1, 1) is as far as possible from all the land with distance 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/1336_ex1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,0,0],[0,0,0],[0,0,0]]Output:4Explanation:The cell (2, 2) is as far as possible from all the land with distance 4.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/1336_ex2.JPG" + } + ], + "follow_up": null, + "solution": "class Solution {\n class Point {\n int x, y;\n public Point(int x, int y){\n this.x=x;\n this.y=y;\n }\n }\n int[][] dist;\n int n,ans;\n int[] dx={0, 0, +1, -1};\n int[] dy={+1, -1, 0, 0};\n public int maxDistance(int[][] grid) {\n n=grid.length;\n dist = new int[n][n];\n Queue q = new LinkedList<>();\n for (int i=0;idist[x][y]+1){\n dist[r][c]=dist[x][y]+1;\n Point newP = new Point(r,c);\n q.add(newP);\n }\n }\n }\n for (int i=0;i=0&&c>=0&&r int:\n m,n=len(grid),len(grid[0])\n queue=deque([])\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1:\n queue.append((i,j))\n c=-1\n while queue:\n # print(queue)\n temp=len(queue)\n for _ in range(temp):\n (i,j)=queue.popleft()\n for (x,y) in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):\n if x < 0 or x >= m or y < 0 or y >= n or grid[x][y]==1:\n continue\n grid[x][y]=1\n queue.append((x,y))\n c+=1\n return c if c!=0 else -1\n", + "title": "1162. As Far from Land as Possible", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i] , which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j] . If s[j] >= g[i] , we can assign the cookie j to the child i , and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= g.length <= 3 * 10^4", + "0 <= s.length <= 3 * 10^4", + "1 <= g[i], s[j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:g = [1,2,3], s = [1,1]Output:1Explanation:You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.", + "image": null + }, + { + "text": "Example 2: Input:g = [1,2], s = [1,2,3]Output:2Explanation:You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 98.76%) | Memory: 45.20 MB (Top 5.55%)\n\nclass Solution {\n public int findContentChildren(int[] g, int[] s) {\n int i =0,j=0,c=0;\n \n Arrays.sort(g);\n Arrays.sort(s);\n \n \n for(;i< g.length;i++)\n {\n // System.out.println(s[j]+\" \"+g[i]);\n \n while(j=g[i] )\n {\n // System.out.println(s[j]+\" \"+g[i]);\n j++;c++;\n break;\n }\n j++;\n }\n }\n \n return c;\n \n }\n}\n", + "title": "455. Assign Cookies", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i] , which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j] . If s[j] >= g[i] , we can assign the cookie j to the child i , and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= g.length <= 3 * 10^4", + "0 <= s.length <= 3 * 10^4", + "1 <= g[i], s[j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:g = [1,2,3], s = [1,1]Output:1Explanation:You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.", + "image": null + }, + { + "text": "Example 2: Input:g = [1,2], s = [1,2,3]Output:2Explanation:You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 437 ms (Top 8.80%) | Memory: 15.9 MB (Top 13.77%)\nclass Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort()\n s.sort()\n cont = 0\n c = 0\n k = 0\n while k< len(s) and c < len(g):\n if s[k] >= g[c]:\n c+=1\n k+=1\n cont+=1\n else:\n k+=1\n return cont", + "title": "455. Assign Cookies", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]Output:[5,10]Explanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]Output:[]Explanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]Output:[10]Explanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 6.85%) | Memory: 49 MB (Top 11.86%)\n/*\n0. Start iterating over the asteroid one by one.\n1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n6. Convert the stack to an array in return it.\n\n*/\nclass Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Stack stack = new Stack<>();\n //0. Start iterating over the asteroid one by one.\n for(int a : asteroids) {\n\n //1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n //2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n while(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() < Math.abs(a)) {\n stack.pop();\n }\n\n //3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() == Math.abs(a)) {\n stack.pop();\n continue;\n }\n\n //4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() > Math.abs(a)) {\n continue;\n }\n\n //5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n stack.push(a);\n\n }\n\n //6. Convert the stack to an array in return it.\n int[] ans = new int[stack.size()];\n int i = stack.size() - 1;\n while(!stack.isEmpty()) {\n ans[i] = stack.pop();\n i--;\n }\n return ans;\n }\n}", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]Output:[5,10]Explanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]Output:[]Explanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]Output:[10]Explanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 103 ms (Top 70.1%) | Memory: 17.56 MB (Top 44.2%)\n\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for a in asteroids:\n while stack and stack[-1] > 0 > a:\n if stack[-1] < abs(a):\n stack.pop()\n continue\n elif stack[-1] == abs(a):\n stack.pop()\n break # this means asteroid must be destroyed (not add to stack in else statement below)\n else:\n stack.append(a)\n \n return stack", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B' , black pawns 'p' , and empty squares '.' . When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking . Return the number of available captures for the white rook . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "board.length == 8", + "board[i].length == 8", + "board[i][j] is either 'R' , '.' , 'B' , or 'p'", + "There is exactly one cell with board[i][j] == 'R'" + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:3Explanation:In this example, the rook is attacking all the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:0Explanation:The bishops are blocking the rook from attacking any of the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG" + }, + { + "text": "Example 3: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:3Explanation:The rook is attacking the pawns at positions b5, d6, and f5.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.3 MB (Top 62.26%)\nclass Solution {\n public int numRookCaptures(char[][] board) {\n int ans = 0;\n\n int row = 0;\n int col = 0;\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 'R') {\n row = i;\n col = j;\n break;\n }\n }\n }\n\n int j = col;\n while (j >= 0) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j--;\n }\n\n j = col;\n while (j <= board[0].length - 1) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j++;\n }\n\n int i = row;\n while (i <= board.length - 1) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i++;\n }\n\n i = row;\n while (i >= 0) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i--;\n }\n\n return ans;\n }\n}", + "title": "999. Available Captures for Rook", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B' , black pawns 'p' , and empty squares '.' . When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking . Return the number of available captures for the white rook . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "board.length == 8", + "board[i].length == 8", + "board[i][j] is either 'R' , '.' , 'B' , or 'p'", + "There is exactly one cell with board[i][j] == 'R'" + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:3Explanation:In this example, the rook is attacking all the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:0Explanation:The bishops are blocking the rook from attacking any of the pawns.", + "image": "https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG" + }, + { + "text": "Example 3: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]Output:3Explanation:The rook is attacking the pawns at positions b5, d6, and f5.", + "image": "https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n\t\t# Checking for possible case to the right of Rook\n def right_position(n,i):\n List = i[0:n][::-1] # taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List: # Checking if 'p' in list \n pIndex = List.index('p')\n if 'B' in List: # Checking if 'B' in list\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1: # if list does not have 'B' and have 'p'\n return True\n if pIndex == -1: # if list does not have 'p'\n return False\n return bIndex>pIndex \n def left_position(n,i):\n List = i[n+1:]# taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List:\n pIndex = List.index('p')\n if 'B' in List:\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1:\n return True\n if pIndex == -1:\n return False\n return bIndex>pIndex\n Count = 0\n\t\t# Checking for possibilites in row\n for i in board:\n if 'R' in i:\n print(i)\n n = i.index('R')\n if left_position(n,i):\n Count += 1\n if right_position(n,i):\n Count += 1\n Col = []\n\t\t# checking for possibilites in col\n for i in range(0,len(board)):\n Col.append(board[i][n]) # taking the elements from the same col of Rook\n n = Col.index('R')\n if left_position(n,Col):\n Count += 1\n if right_position(n,Col):\n Count += 1\n return Count\n", + "title": "999. Available Captures for Rook", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]Output:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.1%) | Memory: 45.45 MB (Top 6.9%)\n\nclass Solution {\n public List averageOfLevels(TreeNode root) {\n Queue q = new LinkedList<>(List.of(root));\n List ans = new ArrayList<>();\n while (q.size() > 0) {\n double qlen = q.size(), row = 0;\n for (int i = 0; i < qlen; i++) {\n TreeNode curr = q.poll();\n row += curr.val;\n if (curr.left != null) q.offer(curr.left);\n if (curr.right != null) q.offer(curr.right);\n }\n ans.add(row/qlen);\n }\n return ans;\n }\n}", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]Output:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 94.14%) | Memory: 19.30 MB (Top 21.03%)\n\nclass Solution:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n \n if not root:\n \n # Quick response for empty tree\n return []\n \n traversal_q = [root]\n \n average = []\n \n while traversal_q:\n \n # compute current level average\n cur_avg = sum( (node.val for node in traversal_q if node) ) / len(traversal_q)\n \n # add to result\n average.append( cur_avg )\n \n # update next level queue\n next_level_q = [ child for node in traversal_q for child in (node.left, node.right) if child ]\n \n # update traversal queue as next level's\n traversal_q = next_level_q\n \n return average\n", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of unique integers salary where salary[i] is the salary of the i th employee. Return the average salary of employees excluding the minimum and maximum salary . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= salary.length <= 100", + "1000 <= salary[i] <= 10^6", + "All the integers of salary are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:salary = [4000,3000,1000,2000]Output:2500.00000Explanation:Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500", + "image": null + }, + { + "text": "Example 2: Input:salary = [1000,2000,3000]Output:2000.00000Explanation:Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double average(int[] salary) {\n int n = salary.length-2;\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n int sum = 0;\n for(int i=0;i float: \n\n return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)\n", + "title": "1491. Average Salary Excluding the Minimum and Maximum Salary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a restaurant with a single chef. You are given an array customers , where customers[i] = [arrival i , time i ]: When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input . Return the average waiting time of all customers . Solutions within 10 -5 from the actual answer are considered accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arrival i is the arrival time of the i th customer. The arrival times are sorted in non-decreasing order.", + "time i is the time needed to prepare the order of the i th customer." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [[1,2],[2,5],[4,3]]Output:5.00000Explanation:1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.", + "image": null + }, + { + "text": "Example 2: Input:customers = [[5,2],[5,4],[10,3],[20,1]]Output:3.25000Explanation:1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 7.49%) | Memory: 101.1 MB (Top 30.84%)\nclass Solution {\n public double averageWaitingTime(int[][] customers) {\n double time = 0;\n double waitingTime = 0;\n\n for(int[] cust : customers){\n time = Math.max(cust[0],time);\n time = time + cust[1];\n waitingTime += (time - cust[0]);\n }\n\n return waitingTime/customers.length;\n }\n}", + "title": "1701. Average Waiting Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a restaurant with a single chef. You are given an array customers , where customers[i] = [arrival i , time i ]: When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input . Return the average waiting time of all customers . Solutions within 10 -5 from the actual answer are considered accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arrival i is the arrival time of the i th customer. The arrival times are sorted in non-decreasing order.", + "time i is the time needed to prepare the order of the i th customer." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [[1,2],[2,5],[4,3]]Output:5.00000Explanation:1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.", + "image": null + }, + { + "text": "Example 2: Input:customers = [[5,2],[5,4],[10,3],[20,1]]Output:3.25000Explanation:1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n start = customers[0][0]\n end = start + customers[0][1]\n total_wait = end - start\n for c in customers[1:]:\n start = c[0]\n if start <= end:\n end += c[1]\n total_wait = total_wait + end - start\n else:\n end = c[0]+c[1]\n total_wait += c[1]\n return total_wait/len(customers)\n \n \n \n \n", + "title": "1701. Average Waiting Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water , there will be a flood . Your goal is to avoid floods in any lake. Given an integer array rains where: Return an array ans where: If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array . Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "rains[i] > 0 means there will be rains over the rains[i] lake.", + "rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it ." + ], + "examples": [ + { + "text": "Example 1: Input:rains = [1,2,3,4]Output:[-1,-1,-1,-1]Explanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.", + "image": null + }, + { + "text": "Example 2: Input:rains = [1,2,0,0,2,1]Output:[-1,-1,2,1,-1,-1]Explanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.", + "image": null + }, + { + "text": "Example 3: Input:rains = [1,2,0,1,2]Output:[]Explanation:After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 47.1%) | Memory: 59.86 MB (Top 71.2%)\n\nclass Solution {\n public int[] avoidFlood(int[] rains) {\n // the previous appeared idx of rains[i]\n Map map = new HashMap<>();\n TreeSet zeros = new TreeSet<>();\n int[] res = new int[rains.length];\n for (int i = 0; i < rains.length; i++) {\n if (rains[i] == 0) {\n zeros.add(i);\n } else {\n if (map.containsKey(rains[i])) {\n // find the location of zero that can be used to empty rains[i]\n Integer next = zeros.ceiling(map.get(rains[i]));\n if (next == null) return new int[0];\n res[next] = rains[i];\n zeros.remove(next);\n }\n res[i] = -1;\n\t\t\t\tmap.put(rains[i], i);\n }\n }\n for (int i : zeros) res[i] = 1;\n return res;\n }\n}", + "title": "1488. Avoid Flood in The City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water , there will be a flood . Your goal is to avoid floods in any lake. Given an integer array rains where: Return an array ans where: If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array . Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "rains[i] > 0 means there will be rains over the rains[i] lake.", + "rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it ." + ], + "examples": [ + { + "text": "Example 1: Input:rains = [1,2,3,4]Output:[-1,-1,-1,-1]Explanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.", + "image": null + }, + { + "text": "Example 2: Input:rains = [1,2,0,0,2,1]Output:[-1,-1,2,1,-1,-1]Explanation:After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.", + "image": null + }, + { + "text": "Example 3: Input:rains = [1,2,0,1,2]Output:[]Explanation:After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_left\n\nclass Solution:\n def avoidFlood(self, rains):\n full_lakes, dry_dates = {}, []\n ans = [-1] * len(rains)\n\n for date, rain_lake in enumerate(rains):\n if rain_lake == 0: # no rain, we can dry one lake\n dry_dates.append(date) # keep dry date, we'll decide later\n continue\n\n if rain_lake in full_lakes: # the lake is already full\n # BS find out earliest day we can use to dry that lake | greedy\n dry_day = bisect_left(dry_dates, full_lakes[rain_lake])\n\n if dry_day >= len(dry_dates): return [] # can not find a date to dry this lake\n\n ans[dry_dates.pop(dry_day)] = rain_lake # dry this lake at the date we choose\n\n # remember latest rain on this lake\n full_lakes[rain_lake] = date\n\n # we may have dry dates remain, on these days, rain > 0, we can not use -1, just choose day 1 to dry (maybe nothing happend)\n for dry_day in dry_dates:\n ans[dry_day] = 1\n\n return ans\n", + "title": "1488. Avoid Flood in The City", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two strings s and t , return true if they are equal when both are typed into empty text editors . '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 200", + "s and t only contain lowercase letters and '#' characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab#c\", t = \"ad#c\"Output:trueExplanation:Both s and t become \"ac\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab##\", t = \"c#d#\"Output:trueExplanation:Both s and t become \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a#c\", t = \"b\"Output:falseExplanation:s becomes \"c\" while t becomes \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 94.73%) | Memory: 42.2 MB (Top 59.43%)\n\nclass Solution {\n public boolean backspaceCompare(String s, String t) {\n int i = s.length() - 1, j = t.length() - 1;\n while(i >= 0 || j >= 0) {\n i = getCurPos(i, s);\n j = getCurPos(j, t);\n if (i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j)) return false;\n if ((i >= 0) != (j >= 0)) return false;\n i--;\n j--;\n }\n return true;\n }\n private int getCurPos(int i, String s) {\n int dels = 0;\n while( i >= 0) {\n if (s.charAt(i) == '#') {\n dels++;\n i--;\n } else if (dels > 0) {\n dels--;\n i--;\n } else break;\n }\n return i;\n }\n}", + "title": "844. Backspace String Compare", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , return true if they are equal when both are typed into empty text editors . '#' means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 200", + "s and t only contain lowercase letters and '#' characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab#c\", t = \"ad#c\"Output:trueExplanation:Both s and t become \"ac\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab##\", t = \"c#d#\"Output:trueExplanation:Both s and t become \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a#c\", t = \"b\"Output:falseExplanation:s becomes \"c\" while t becomes \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def backwardResult(string):\n debt = 0\n \n for c in reversed(string):\n if c == '#':\n debt += 1\n \n elif debt > 0:\n debt -= 1\n \n else:\n yield c\n \n return all(a == b for (a, b) in zip_longest(backwardResult(s), backwardResult(t)))", + "title": "844. Backspace String Compare", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an initial power of power , an initial score of 0 , and a bag of tokens where tokens[i] is the value of the i th token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: Each token may be played at most once and in any order . You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If your current power is at least tokens[i] , you may play the i th token face up, losing tokens[i] power and gaining 1 score .", + "If your current score is at least 1 , you may play the i th token face down, gaining tokens[i] power and losing 1 score ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [100], power = 50Output:0Explanation:Playing the only token in the bag is impossible because you either have too little power or too little score.", + "image": null + }, + { + "text": "Example 2: Input:tokens = [100,200], power = 150Output:1Explanation:Play the 0thtoken (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1sttoken since you cannot play it face up to add to your score.", + "image": null + }, + { + "text": "Example 3: Input:tokens = [100,200,300,400], power = 200Output:2Explanation:Play the tokens in this order to get a score of 2:\n1. Play the 0thtoken (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3rdtoken (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1sttoken (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2ndtoken (300) face up, your power becomes 0 and score becomes 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int bagOfTokensScore(int[] tokens, int power) { \n //initially score is 0, that's why in these conditions, return 0. \n if(tokens.length == 0 || power < tokens[0])\n\t\t\treturn 0; \n Arrays.sort(tokens); //sort the array\n \n int i = 0;\n int r = tokens.length - 1;\n int score = 0;\n int answer = 0;\n \n while(i<=r){ \n if(power >= tokens[i]){\n power -= tokens[i++]; \n answer = Math.max(answer, ++score); //play all tokens, but store the max score in answer. \n }\n else if (score > 0){\n power += tokens[r--]; //take power from greatest element\n score--; //decrease by 1.\n } \n //when you can't do any of the steps (face up, face down)\n else\n return answer;\n } \n return answer;\n }\n}\n", + "title": "948. Bag of Tokens", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an initial power of power , an initial score of 0 , and a bag of tokens where tokens[i] is the value of the i th token (0-indexed). Your goal is to maximize your total score by potentially playing each token in one of two ways: Each token may be played at most once and in any order . You do not have to play all the tokens. Return the largest possible score you can achieve after playing any number of tokens . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If your current power is at least tokens[i] , you may play the i th token face up, losing tokens[i] power and gaining 1 score .", + "If your current score is at least 1 , you may play the i th token face down, gaining tokens[i] power and losing 1 score ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [100], power = 50Output:0Explanation:Playing the only token in the bag is impossible because you either have too little power or too little score.", + "image": null + }, + { + "text": "Example 2: Input:tokens = [100,200], power = 150Output:1Explanation:Play the 0thtoken (100) face up, your power becomes 50 and score becomes 1.\nThere is no need to play the 1sttoken since you cannot play it face up to add to your score.", + "image": null + }, + { + "text": "Example 3: Input:tokens = [100,200,300,400], power = 200Output:2Explanation:Play the tokens in this order to get a score of 2:\n1. Play the 0thtoken (100) face up, your power becomes 100 and score becomes 1.\n2. Play the 3rdtoken (400) face down, your power becomes 500 and score becomes 0.\n3. Play the 1sttoken (200) face up, your power becomes 300 and score becomes 1.\n4. Play the 2ndtoken (300) face up, your power becomes 0 and score becomes 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 88.07%) | Memory: 17.40 MB (Top 31.65%)\n\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j=0,len(tokens)-1\n m=score=0\n while ipower and score==0:\n break \n if tokens[i]<=power:\n score+=1\n power-=tokens[i]\n m=max(m,score)\n i+=1\n else:\n if score>0:\n score-=1\n power+=tokens[j]\n j-=1\n if i arr = new ArrayList();\n InOrder( root, arr);\n return sortedArrayToBST( arr, 0, arr.size()-1);\n }\n \n public void InOrder(TreeNode node, List arr){\n if(node != null){\n InOrder( node.left, arr);\n arr.add(node.val);\n InOrder( node.right, arr);\n }\n }\n \n public TreeNode sortedArrayToBST(List arr, int start, int end) {\n\n if (start > end) {\n return null;\n }\n \n int mid = (start + end) / 2;\n \n TreeNode node = new TreeNode(arr.get(mid));\n node.left = sortedArrayToBST(arr, start, mid - 1);\n node.right = sortedArrayToBST(arr, mid + 1, end);\n \n return node;\n }\n}\n", + "title": "1382. Balance a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary search tree, return a balanced binary search tree with the same node values . If there is more than one answer, return any of them . A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,null,3,null,4,null,null]Output:[2,1,3,null,null,null,4]Explanation:This is not the only correct answer, [3,1,4,null,2] is also correct.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/balance1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]Output:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/10/balanced2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def balanceBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n arr = []\n self.flatTree(root, arr)\n return self.createTree(arr, 0, len(arr))\n \n def flatTree(self, root, arr):\n if not root:\n return\n self.flatTree(root.left, arr)\n arr.append(root)\n self.flatTree(root.right, arr)\n \n def createTree(self, arr, start, length):\n if length == 0:\n return None\n root = arr[start + length / 2]\n root.left = self.createTree(arr, start, length / 2)\n root.right = self.createTree(arr, start + length / 2 + 1, length - length / 2 - 1)\n return root\n", + "title": "1382. Balance a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 86 ms (Top 5.00%) | Memory: 44 MB (Top 76.22%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n public int treeHeight(TreeNode root){\n if (root == null)\n return 0;\n\n int left = treeHeight(root.left);\n int right = treeHeight(root.right);\n\n return ( Math.max(left,right) + 1);\n\n }\n\n public boolean isBalanced(TreeNode root) {\n\n if (root == null)\n return true;\n\n boolean leftBalanced = isBalanced( root.left);\n boolean rightBalanced = isBalanced( root.right);\n int leftHeight = treeHeight(root.left);\n int rightHeight = treeHeight(root.right);\n\n //Return true only when all conditions are true\n return (leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1);\n\n }\n}", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n\n # Initialize the result to True\n res = True\n\n # DFS through the tree\n def dfs(node, i):\n nonlocal res\n\n # If there isn't a node, return previous depth\n if not node:\n return i - 1\n\n # Check depths of the left and right subtrees\n left, right = dfs(node.left, i + 1), dfs(node.right, i + 1)\n\n # If they are more than 1 difference, save False to the result\n if abs(right - left) > 1:\n res = False\n\n # Return the max depth of both subtrees\n return max(left, right)\n\n dfs(root, 0)\n\n return res\n", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops , where ops[i] is the i th operation you must apply to the record and is one of the following: Return the sum of all the scores on the record . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= ops.length <= 1000", + "ops[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." + ], + "examples": [ + { + "text": "Example 1: Input:ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]Output:30Explanation:\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.", + "image": null + }, + { + "text": "Example 2: Input:ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]Output:27Explanation:\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.", + "image": null + }, + { + "text": "Example 3: Input:ops = [\"1\",\"C\"]Output:0Explanation:\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int calPoints(String[] ops) {\n List list = new ArrayList();\n \n for(int i = 0; i < ops.length; i++){\n switch(ops[i]){\n case \"C\":\n list.remove(list.size() - 1);\n break;\n case \"D\":\n list.add(list.get(list.size() - 1) * 2);\n break;\n case \"+\":\n list.add(list.get(list.size() - 1) + list.get(list.size() - 2));\n break;\n default:\n list.add(Integer.valueOf(ops[i]));\n break;\n }\n }\n \n int finalScore = 0;\n for(Integer score: list)\n finalScore += score;\n \n return finalScore;\n }\n}\n", + "title": "682. Baseball Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops , where ops[i] is the i th operation you must apply to the record and is one of the following: Return the sum of all the scores on the record . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= ops.length <= 1000", + "ops[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." + ], + "examples": [ + { + "text": "Example 1: Input:ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]Output:30Explanation:\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.", + "image": null + }, + { + "text": "Example 2: Input:ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]Output:27Explanation:\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.", + "image": null + }, + { + "text": "Example 3: Input:ops = [\"1\",\"C\"]Output:0Explanation:\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def calPoints(self, ops: List[str]) -> int:\n temp = []\n for i in ops:\n if i!=\"C\" and i!=\"D\" and i!=\"+\":\n temp.append(int(i))\n elif i==\"C\":\n temp.remove(temp[len(temp)-1])\n elif i==\"D\":\n temp.append(2*temp[len(temp)-1])\n elif i==\"+\":\n temp.append(temp[len(temp)-1]+temp[len(temp)-2])\n \n \n return sum(temp)\n", + "title": "682. Baseball Game", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"Output:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"Output:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int idx; // this index traverse the string in one pass, between different level of recursion\n public int calculate(String s) {\n idx = 0; // Initialization should be here\n return helper(s);\n }\n \n private int helper(String s) {\n int res = 0, num = 0, preSign = 1, n = s.length();\n while (idx < n) {\n char c = s.charAt(idx++);\n if (c == '(') num = helper(s); // Let recursion solve the sub-problem\n else if (c >= '0' && c <= '9') num = num * 10 + c - '0';\n if (c == '+' || c == '-' || c == ')' || idx == n) { // we need one more calculation when idx == n\n res += preSign * num;\n if (c == ')') return res; // end of a sub-problem\n num = 0;\n preSign = c == '+' ? 1 : -1;\n }\n }\n return res;\n }\n}\n", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"Output:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"Output:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 57.95%) | Memory: 15.5 MB (Top 50.78%)\n\n```class Solution:\n def calculate(self, s: str) -> int:\n curr,output,sign,stack = 0,0,1,[]\n\n for ch in s:\n if ch.isdigit():\n curr = curr * 10 + int(ch)\n\n elif ch == '+':\n output += sign * curr\n sign = 1\n curr = 0\n\n elif ch == '-':\n output += sign * curr\n sign = -1\n curr = 0\n\n elif ch == '(':\n #push the result and then the sign\n stack.append(output)\n stack.append(sign)\n sign = 1\n output = 0\n\n elif ch == ')':\n output += sign * curr\n output *= stack.pop()\n output += stack.pop()\n curr = 0\n return output + sign*curr``", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s which represents an expression, evaluate this expression and return its value . The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.", + "s represents a valid expression .", + "All the integers in the expression are non-negative integers in the range [0, 2 31 - 1] .", + "The answer is guaranteed to fit in a 32-bit integer ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3+2*2\"Output:7", + "image": null + }, + { + "text": "Example 2: Input:s = \" 3/2 \"Output:1", + "image": null + }, + { + "text": "Example 3: Input:s = \" 3+5 / 2 \"Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 27.28%) | Memory: 45.6 MB (Top 25.17%)\nclass Solution {\n public int calculate(String s) {\n if(s==null ||s.length()==0)return 0;\n Stack st = new Stack<>();\n int curr=0;\n char op = '+';\n char [] ch = s.toCharArray();\n for(int i=0;i int:\n stack = []\n currentNumber = 0\n operator = '+'\n operations = '+-/*'\n for i in range(len(s)):\n ch = s[i]\n if ch.isdigit():\n currentNumber = currentNumber * 10 + int(ch)\n\n if ch in operations or i == len(s) - 1:\n if operator == '+':\n stack.append(currentNumber)\n\n elif operator == '-':\n stack.append(-currentNumber)\n\n elif operator == '*':\n stack.append(stack.pop() * currentNumber)\n\n elif operator == '/':\n stack.append(int(stack.pop()/currentNumber))\n\n currentNumber =0\n operator = ch\n\n return sum(stack)\n", + "title": "227. Basic Calculator II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1] ), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"] Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. The format of the output is as follows: Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "An expression alternates chunks and symbols, with a space separating each chunk and symbol.", + "A chunk is either an expression in parentheses, a variable, or a non-negative integer.", + "A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like \"2x\" or \"-x\" ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]Output:[\"-1*a\",\"14\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]Output:[\"-1*pressure\",\"5\"]", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []Output:[\"1*e*e\",\"-64\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Node {\n Map, Integer> mem = new HashMap<>();\n \n void update(List cur, int cnt) {\n Collections.sort(cur);\n mem.put(cur, mem.getOrDefault(cur, 0) + cnt);\n }\n \n Node add(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n ans.update(key1, mem.get(key1));\n }\n for (List key2 : cur.mem.keySet()) {\n ans.update(key2, cur.mem.get(key2));\n }\n return ans;\n }\n Node sub(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n ans.update(key1, mem.get(key1));\n }\n for (List key2 : cur.mem.keySet()) {\n ans.update(key2, -cur.mem.get(key2));\n }\n return ans;\n }\n \n Node mul(Node cur) {\n Node ans = new Node();\n for (List key1 : mem.keySet()) {\n for (List key2 : cur.mem.keySet()) {\n List next = new ArrayList<>();\n next.addAll(key1);\n next.addAll(key2);\n ans.update(next, mem.get(key1) * cur.mem.get(key2));\n }\n }\n return ans;\n }\n \n Node evaluate(Map vars) {\n Node ans = new Node();\n for (List cur : mem.keySet()) {\n int cnt = mem.get(cur);\n List free = new ArrayList<>();\n for (String tmp : cur) {\n if (vars.containsKey(tmp)) {\n cnt = cnt * vars.get(tmp);\n } else {\n free.add(tmp);\n }\n }\n ans.update(free, cnt);\n }\n \n return ans;\n }\n \n List toList() {\n List ans = new ArrayList<>();\n List> keys = new ArrayList<>(mem.keySet());\n Collections.sort(keys, (List a, List b) -> {\n if (a.size() != b.size()) {\n return b.size() - a.size();\n }\n for (int i = 0; i < a.size(); i ++) {\n if (a.get(i).compareTo(b.get(i)) != 0) {\n return a.get(i).compareTo(b.get(i));\n }\n }\n return 0;\n });\n \n for (List key : keys) {\n if (mem.get(key) == 0) {\n continue;\n }\n String cur = \"\" + String.valueOf(mem.get(key));\n for (String data : key) {\n cur += \"*\";\n cur += data;\n }\n ans.add(cur);\n }\n return ans;\n }\n }\n \n Node make(String cur) {\n Node ans = new Node();\n List tmp = new ArrayList<>();\n if (Character.isDigit(cur.charAt(0))) {\n ans.update(tmp, Integer.valueOf(cur));\n } else {\n tmp.add(cur);\n ans.update(tmp, 1);\n }\n return ans;\n }\n int getNext(String expression, int start) {\n int end = start;\n while (end < expression.length() && Character.isLetterOrDigit(expression.charAt(end))) {\n end ++;\n }\n return end - 1;\n }\n \n int getPriority(char a) {\n if (a == '+' || a == '-') {\n return 1;\n } else if (a == '*') {\n return 2;\n }\n return 0;\n }\n \n Node helper(Stack nums, Stack ops) {\n Node b = nums.pop();\n Node a = nums.pop();\n char op = ops.pop();\n if (op == '*') {\n return a.mul(b);\n } else if (op == '+') {\n return a.add(b);\n } \n return a.sub(b);\n }\n \n public List basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {\n List ans = new ArrayList<>();\n if (expression == null || expression.length() == 0 || evalvars == null || evalints == null) {\n return ans;\n }\n \n Map vars = new HashMap<>();\n for (int i = 0; i < evalvars.length; i ++) {\n vars.put(evalvars[i], evalints[i]);\n }\n \n int n = expression.length();\n Stack nums = new Stack<>();\n Stack ops = new Stack<>();\n for (int i = 0; i < n; i ++) {\n char a = expression.charAt(i);\n if (Character.isLetterOrDigit(a)) {\n int end = getNext(expression, i);\n String cur = expression.substring(i, end + 1);\n i = end;\n Node now = make(cur);\n nums.add(now);\n } else if (a == '(') {\n ops.add(a);\n } else if (a == ')') {\n while (ops.peek() != '(') {\n nums.add(helper(nums, ops));\n }\n ops.pop();\n } else if (a == '+' || a == '-' || a == '*') {\n while (ops.size() > 0 && getPriority(ops.peek()) >= getPriority(a)) {\n nums.add(helper(nums, ops));\n }\n ops.add(a);\n }\n }\n \n while (ops.size() > 0) {\n nums.add(helper(nums, ops));\n }\n \n return nums.peek().evaluate(vars).toList();\n \n }\n}\n", + "title": "770. Basic Calculator IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1] ), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"] Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. The format of the output is as follows: Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-2 31 , 2 31 - 1] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "An expression alternates chunks and symbols, with a space separating each chunk and symbol.", + "A chunk is either an expression in parentheses, a variable, or a non-negative integer.", + "A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like \"2x\" or \"-x\" ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]Output:[\"-1*a\",\"14\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]Output:[\"-1*pressure\",\"5\"]", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []Output:[\"1*e*e\",\"-64\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 83.61%) | Memory: 14.1 MB (Top 62.30%)\nclass Term:\n def __init__(self, exp: Optional[str]='', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r'^\\-?\\d+$', exp):\n self.d[''] += int(exp)\n elif exp:\n self.d[exp] += 1\n\n def __add__(self, other: 'Term') -> 'Term':\n return self._pm(other, add=True)\n\n def __mul__(self, other: 'Term') -> 'Term':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res['*'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n\n def __sub__(self, other: 'Term') -> 'Term':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+'*'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n\n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split('*')))\n\n def _pm(self, other: 'Term', *, add: bool) -> 'Term':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r'[a-z0-9]+', lambda m: \"Term('\"+str(vals.get(m.group(), m.group()))+\"')\", expression)).get()", + "title": "770. Basic Calculator IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.' , return the number of the battleships on board . Battleships can only be placed horizontally or vertically on board . In other words, they can only be made of the shape 1 x k ( 1 row, k columns) or k x 1 ( k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is either '.' or 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/04/10/battelship-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[\".\"]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 10.56%) | Memory: 44.7 MB (Top 26.11%)\nclass Solution {\n public int countBattleships(char[][] board) {\n int result = 0;\n for(int i = 0;i= board.length || j<0 || j>=board[0].length || board[i][j] == '.')\n {\n return;\n }\n board[i][j] = '.';\n remover(i+1, j, board);\n remover(i, j+1, board);\n }\n}", + "title": "419. Battleships in a Board", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.' , return the number of the battleships on board . Battleships can only be placed horizontally or vertically on board . In other words, they can only be made of the shape 1 x k ( 1 row, k columns) or k x 1 ( k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is either '.' or 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/04/10/battelship-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[\".\"]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBattleships(self, board: List[List[str]]) -> int:\n \n m = len(board)\n n = len(board[0])\n res = 0\n \n pole = [ [True for i in range(n)] for j in range(m) ]\n \n for i in range(m):\n for j in range(n):\n if board[i][j] == 'X' and pole[i][j]:\n for z in range(i+1, m):\n if board[z][j] == 'X':\n pole[z][j] = False\n else:\n break\n \n for z in range(j+1, n):\n if board[i][z] == 'X':\n pole[i][z] = False\n else:\n break\n \n \n res += 1\n \n\n \n return res\n", + "title": "419. Battleships in a Board", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Suppose you have n integers labeled 1 through n . A permutation of those n integers perm ( 1-indexed ) is considered a beautiful arrangement if for every i ( 1 <= i <= n ), either of the following is true: Given an integer n , return the number of the beautiful arrangements that you can construct . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "perm[i] is divisible by i .", + "i is divisible by perm[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:The first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 93.01%) | Memory: 44.8 MB (Top 13.42%)\nclass Solution {\n int N;\n Integer[][] memo;\n public int countArrangement(int n) {\n this.N = n;\n memo = new Integer[n+1][1< int:\n self.count = 0\n self.backtrack(n, 1, [])\n return self.count\n \n def backtrack(self, N, idx, temp):\n if len(temp) == N:\n self.count += 1\n return\n \n for i in range(1, N+1):\n if i not in temp and (i % idx == 0 or idx % i == 0):\n temp.append(i)\n self.backtrack(N, idx+1, temp)\n temp.pop()", + "title": "526. Beautiful Arrangement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers n and k , construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Return the list answer . If there multiple valid answers, return any of them . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Suppose this list is answer = [a 1 , a 2 , a 3 , ... , a n ] , then the list [|a 1 - a 2 |, |a 2 - a 3 |, |a 3 - a 4 |, ... , |a n-1 - a n |] has exactly k distinct integers." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1Output:[1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 2Output:[1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] constructArray(int n, int k) {\n int [] result = new int[n];\n result[0] = 1;\n int sign = 1;\n for(int i = 1 ; i < n; i++, k--){\n if(k > 0){\n result[i] = result[i-1] + k * sign;\n sign *= -1;\n }\n else{\n result[i] = i+1;\n }\n }\n return result;\n }\n}\n", + "title": "667. Beautiful Arrangement II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two integers n and k , construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement: Return the list answer . If there multiple valid answers, return any of them . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Suppose this list is answer = [a 1 , a 2 , a 3 , ... , a n ] , then the list [|a 1 - a 2 |, |a 2 - a 3 |, |a 3 - a 4 |, ... , |a n-1 - a n |] has exactly k distinct integers." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1Output:[1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 2Output:[1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n # n = 8, k = 5\n # 1 2 3 8 4 7 5 6\n # 1 1 5 4 3 2 1\n res = list(range(1,n-k+1))\n sign, val = 1, k\n for i in range(k):\n res.append(res[-1]+sign*val)\n sign *= -1\n val -= 1\n return res\n", + "title": "667. Beautiful Arrangement II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array nums of length n is beautiful if: Given the integer n , return any beautiful array nums of length n . There will be at least one valid answer for the given n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums is a permutation of the integers in the range [1, n] .", + "For every 0 <= i < j < n , there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:[2,1,4,3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[3,1,2,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import permutations\nclass Solution:\n def invalid(self, x):\n n = len(x)\n flag = False\n for i in range(n):\n if flag: break\n for j in range(i+2, n):\n if flag: break\n for k in range(i+1, j):\n if 2*x[k] == x[i]+x[j]: flag = True; break\n return flag\n \n def beautifulArray(self, n: int) -> List[int]:\n for perm in permutations(range(1, n+1)):\n if not self.invalid(perm):\n return perm\n", + "title": "932. Beautiful Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array ranks and a character array suits . You have 5 cards where the i th card has a rank of ranks[i] and a suit of suits[i] . The following are the types of poker hands you can make from best to worst: Return a string representing the best type of poker hand you can make with the given cards. Note that the return values are case-sensitive . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "ranks.length == suits.length == 5", + "1 <= ranks[i] <= 13", + "'a' <= suits[i] <= 'd'", + "No two cards have the same rank and suit." + ], + "examples": [ + { + "text": "Example 1: Input:ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]Output:\"Flush\"Explanation:The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".", + "image": null + }, + { + "text": "Example 2: Input:ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]Output:\"Three of a Kind\"Explanation:The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.", + "image": null + }, + { + "text": "Example 3: Input:ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]Output:\"Pair\"Explanation:The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 33.75%)\nclass Solution {\n public String bestHand(int[] ranks, char[] suits) {\n int max = 0;\n int card = 0;\n char ch = suits[0];\n int[] arr = new int[14];\n for(int i = 0; i < 5; i++){\n arr[ranks[i]]++;\n max = Math.max(max,arr[ranks[i]]);\n if(suits[i] == ch) card++;\n }\n if(card == 5) return \"Flush\";\n return max >= 3 ? \"Three of a Kind\":(max == 2 ? \"Pair\" : \"High Card\");\n }\n}", + "title": "2347. Best Poker Hand", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array ranks and a character array suits . You have 5 cards where the i th card has a rank of ranks[i] and a suit of suits[i] . The following are the types of poker hands you can make from best to worst: Return a string representing the best type of poker hand you can make with the given cards. Note that the return values are case-sensitive . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "ranks.length == suits.length == 5", + "1 <= ranks[i] <= 13", + "'a' <= suits[i] <= 'd'", + "No two cards have the same rank and suit." + ], + "examples": [ + { + "text": "Example 1: Input:ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]Output:\"Flush\"Explanation:The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".", + "image": null + }, + { + "text": "Example 2: Input:ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]Output:\"Three of a Kind\"Explanation:The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.", + "image": null + }, + { + "text": "Example 3: Input:ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]Output:\"Pair\"Explanation:The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 59.18%) | Memory: 13.9 MB (Top 14.06%)\nclass Solution:\n def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n s={}\n for i in suits:\n if i in s:\n s[i]+=1\n if s[i]==5:\n return 'Flush'\n else:\n s[i]=1\n r={}\n max_ = 0\n for i in ranks:\n if i in r:\n r[i]+=1\n max_=max(max_,r[i])\n else:\n r[i]=1\n if max_>=3:\n return \"Three of a Kind\"\n elif max_==2:\n return \"Pair\"\n else:\n return \"High Card\"", + "title": "2347. Best Poker Hand", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum . Given an array positions where positions[i] = [x i , y i ] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [x centre , y centre ] such that the following formula is minimized: Answers within 10 -5 of the actual value will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 50", + "positions[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[0,1],[1,0],[1,2],[2,1]]Output:4.00000Explanation:As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg" + }, + { + "text": "Example 2: Input:positions = [[1,1],[3,3]]Output:2.82843Explanation:The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final double MIN_STEP = 0.0000001;\n private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n public double getMinDistSum(int[][] positions) {\n double cx = 0, cy = 0;\n int n = positions.length;\n for (int[] pos: positions) {\n cx += pos[0];\n cy += pos[1];\n }\n cx /= n; cy /= n;\n Node center = new Node(cx, cy, totalDistance(positions, cx, cy));\n\n double step = 50.0;\n while (step > MIN_STEP) {\n Node min = center;\n for (int[] direction: DIRECTIONS) {\n double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step;\n double totalDist = totalDistance(positions, dx, dy);\n if (totalDist < center.dist) min = new Node(dx, dy, totalDist);\n }\n if (center == min) step /= 2;\n center = min;\n }\n\n return center.dist;\n }\n\n private double sq(double p) {\n return p * p;\n }\n\n private double dist(int[] pos, double x, double y) {\n return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1]));\n }\n\n private double totalDistance(int[][] positions, double x, double y) {\n double dist = 0;\n for (int[] pos: positions) dist += dist(pos, x, y);\n return dist;\n }\n\n private static class Node {\n double x, y, dist;\n Node (double x, double y, double dist) {\n this.x = x;\n this.y = y;\n this.dist = dist;\n }\n }\n}\n", + "title": "1515. Best Position for a Service Centre", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum . Given an array positions where positions[i] = [x i , y i ] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [x centre , y centre ] such that the following formula is minimized: Answers within 10 -5 of the actual value will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 50", + "positions[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[0,1],[1,0],[1,2],[2,1]]Output:4.00000Explanation:As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg" + }, + { + "text": "Example 2: Input:positions = [[1,1],[3,3]]Output:2.82843Explanation:The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843", + "image": "https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n n = len(positions)\n if n == 1: return 0\n def gradient(x,y):\n ans = [0,0]\n for i in range(n):\n denom = math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n ans[0] += (x-positions[i][0])/denom if denom else 0\n ans[1] += (y-positions[i][1])/denom if denom else 0\n return ans\n def fn(x, y):\n res = 0\n for i in range(n):\n res += math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n return res\n x = sum(x for x,_ in positions)/n\n y = sum(y for _,y in positions)/n\n lr = 1\n while lr > 1e-7:\n dx, dy = gradient(x,y)\n x -= lr*dx\n y -= lr*dy\n lr *= 0.997\n if not dx and not dy:\n lr /= 2\n return fn(x,y)", + "title": "1515. Best Position for a Service Centre", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array values where values[i] represents the value of the i th sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair ( i < j ) of sightseeing spots is values[i] + values[j] + i - j : the sum of the values of the sightseeing spots, minus the distance between them. Return the maximum score of a pair of sightseeing spots . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= values.length <= 5 * 10^4", + "1 <= values[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [8,1,5,2,6]Output:11Explanation:i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 77.63%) | Memory: 50.10 MB (Top 66.67%)\n\nclass Solution {\n public int maxScoreSightseeingPair(int[] A) {\n // A[i] + A[j] + i - j = (A[i]+i) + (A[j]-j)\n // think about dividing them into two parts\n // get the max of left part and right part, then add them \n // to get the maximum score\n //\n // max(left) + max(right)\n // maximum score = max(A[i]+i) + max((A[j]-j))\n\n /* example:\n i 0 1 2 3 4\n A [8, 1, 5, 2, 6], max = 0\n \n i=1,\n left = A[0]+0 = 8\n right = A[1]-1 = 0\n => max = max(max=0, left + right=8) = 8\n Before moving to i=2, we need to update left part by \n comparing current left and right\n so ----> left = max(left=8, A[1]+1=2) = 8\n i=2,\n left = 8\n right = A[2]-2 = 3\n => max = max(max=8, left + right=11) = 11\n so ----> left = max(left=8, A[2]+2=7) = 8 \n i=3,\n left = 8\n right = A[3]-3 = 1\n => max = max(max=11, left + right=9) = 11\n so ----> left = max(left=8, A[3]+3=5) = 8 \n i=4,\n left = 8\n right = A[4]-4 = 2\n => max = max(max=11, left + right=10) = 11\n so ----> left = max(left=8, A[4]+4=10) = 8 \n end loop\n max = 11\n */\n int N = A.length;\n int left = A[0]+0;\n int right = 0; \n int max = 0;\n\n for (int i=1; i int:\n left_max_vals = [float('-inf') for _ in range(len(values))]\n right_max_vals = [float('-inf') for _ in range(len(values))]\n \n for i in range(1, len(values)):\n left_max_vals[i] = max(left_max_vals[i-1]-1, values[i-1]-1)\n \n for i in range(len(values)-2, -1, -1):\n right_max_vals[i] = max(right_max_vals[i+1]-1, values[i+1]-1)\n \n max_pair = float('-inf')\n for i in range(len(values)):\n max_pair = max(max_pair, values[i] + max(left_max_vals[i], right_max_vals[i]))\n return max_pair\n", + "title": "1014. Best Sightseeing Pair", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts . A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages , where each scores[i] and ages[i] represents the score and age of the i th player, respectively, return the highest overall score of all possible basketball teams . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= scores.length, ages.length <= 1000", + "scores.length == ages.length", + "1 <= scores[i] <= 10^6", + "1 <= ages[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:scores = [1,3,5,10,15], ages = [1,2,3,4,5]Output:34Explanation:You can choose all the players.", + "image": null + }, + { + "text": "Example 2: Input:scores = [4,5,6,5], ages = [2,1,2,1]Output:16Explanation:It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.", + "image": null + }, + { + "text": "Example 3: Input:scores = [1,2,3,5], ages = [8,9,10,1]Output:6Explanation:It is best to choose the first 3 players.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 92.02%) | Memory: 45.10 MB (Top 27.31%)\n\nclass Solution {\n int res = 0;\n public int bestTeamScore(int[] scores, int[] ages) {\n int len = scores.length;\n int[][] team = new int[len][2];\n for (int i = 0; i < len; i++) {\n team[i][0] = ages[i];\n team[i][1] = scores[i]; // team is [age, score]\n }\n\t\t// double sort first by age then by score, then we can traverse from young to old\n Arrays.sort(team, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);\n \n int[] dp = new int[len];\n // dp is the max sum for all sequences (not necessarily consecutive) ending in current idx\n dp[0] = team[0][1];\n for (int i = 1; i < len; i++) {\n int max = team[i][1]; // At least it could start a new sequence by itself without extend\n\t\t\t// for each current idx, go visit all previous index to grow the sequences\n for (int j = 0; j < i; j++) {\n if (team[i][1] >= team[j][1]) {\n max = Math.max(max, dp[j] + team[i][1]);\n }\n }\n dp[i] = max;\n }\n \n int res = 0;\n for (int num : dp) {\n res = Math.max(res, num);\n }\n \n return res;\n }\n}\n", + "title": "1626. Best Team With No Conflicts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team. However, the basketball team is not allowed to have conflicts . A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age. Given two lists, scores and ages , where each scores[i] and ages[i] represents the score and age of the i th player, respectively, return the highest overall score of all possible basketball teams . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= scores.length, ages.length <= 1000", + "scores.length == ages.length", + "1 <= scores[i] <= 10^6", + "1 <= ages[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:scores = [1,3,5,10,15], ages = [1,2,3,4,5]Output:34Explanation:You can choose all the players.", + "image": null + }, + { + "text": "Example 2: Input:scores = [4,5,6,5], ages = [2,1,2,1]Output:16Explanation:It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.", + "image": null + }, + { + "text": "Example 3: Input:scores = [1,2,3,5], ages = [8,9,10,1]Output:6Explanation:It is best to choose the first 3 players.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5727 ms (Top 5.11%) | Memory: 14.3 MB (Top 62.50%)\nclass Solution(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n l = len(scores)\n mapped = [[ages[i], scores[i]] for i in range(l)]\n mapped = sorted(mapped, key = lambda x : (x[0], x[1]))\n dp = [i[1] for i in mapped]\n\n for i in range(l):\n for j in range(0, i):\n if mapped[j][1] <= mapped[i][1]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n elif mapped[i][0] == mapped[j][0]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n\n return max(dp)", + "title": "1626. Best Team With No Conflicts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:5Explanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 93.59%) | Memory: 83.9 MB (Top 46.18%)\nclass Solution {\n public int maxProfit(int[] prices) {\n int lsf = Integer.MAX_VALUE;\n int op = 0;\n int pist = 0;\n\n for(int i = 0; i < prices.length; i++){\n if(prices[i] < lsf){\n lsf = prices[i];\n }\n pist = prices[i] - lsf;\n if(op < pist){\n op = pist;\n }\n }\n return op;\n }\n}", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:5Explanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2509 ms (Top 5.01%) | Memory: 25 MB (Top 86.17%)\n\nclass Solution:\n def maxProfit(self,prices):\n left = 0 #Buy\n right = 1 #Sell\n max_profit = 0\n while right < len(prices):\n currentProfit = prices[right] - prices[left] #our current Profit\n if prices[left] < prices[right]:\n max_profit =max(currentProfit,max_profit)\n else:\n left = right\n right += 1\n return max_profit", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:7Explanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n int n = prices.length,profit = 0;\n for(int i=0;iprices[i]){\n profit += prices[i+1]-prices[i];\n }\n }\n return profit;\n }\n}", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:7Explanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n=len(prices)\n ans=0\n want=\"valley\"\n for i in range(n-1):\n if want==\"valley\" and prices[i]prices[i+1]:\n ans+=prices[i]\n want=\"valley\"\n if want==\"hill\":\n ans+=prices[-1]\n return ans\n", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]Output:6Explanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n \n int n = prices.length;\n int maxSellProfit = 0;\n int min = prices[0];\n int[] maxSellArr = new int[n];\n int i = 1;\n \n while(i < n){\n if(prices[i] < min){\n min = prices[i];\n }\n maxSellArr[i] = Math.max(maxSellArr[i-1],prices[i] - min); \n \n i++;\n }\n int[] maxBuyArr = new int[n];\n int j = n-2;\n int max = prices[n-1];\n while(j >= 0){\n if(prices[j] > max){\n max = prices[j];\n }\n maxBuyArr[j] = Math.max(maxBuyArr[j+1],max - prices[j]);\n \n j--;\n }\n int maxProfitTwoTrans = 0;\n for(int k = 0; k < n; k++){\n maxProfitTwoTrans = Math.max(maxProfitTwoTrans,maxBuyArr[k] + maxSellArr[k]);\n }\n return maxProfitTwoTrans;\n }\n}\n", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]Output:6Explanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy1, sell1, buy2, sell2 = -inf,0,-inf,0\n for price in prices:\n buy1 = max(buy1,-price)\n sell1 = max(sell1,price+buy1)\n \n buy2 = max(buy2,sell1-price)\n sell2 = max(sell2,price+buy2)\n return sell2\n", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= k <= 100", + "0 <= prices.length <= 1000", + "0 <= prices[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, prices = [2,4,1]Output:2Explanation:Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, prices = [3,2,6,5,0,3]Output:7Explanation:Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int k, int[] prices) {\n int transaction = k;\n int N = prices.length;\n int[][][]dp =new int[N][2][k+1];\n for(int i=0;i int:\n buy = [-inf] * (k+1)\n sell = [0] * (k+1)\n for price in prices:\n for i in range(1,k+1):\n buy[i] = max(buy[i],sell[i-1]-price)\n sell[i] = max(sell[i],buy[i]+price)\n return sell[-1]\n", + "title": "188. Best Time to Buy and Sell Stock IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day)." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,2,3,0,2]Output:3Explanation:transactions = [buy, sell, cooldown, buy, sell]", + "image": null + }, + { + "text": "Example 2: Input:prices = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 55.13%) | Memory: 42.3 MB (Top 47.48%)\nclass Solution {\n public int maxProfit(int[] prices) {\n\n int n = prices.length;\n\n int[][] dp = new int[n+2][2];\n\n for(int index = n-1; index>=0; index--){\n for(int buy = 0; buy<=1; buy++){\n\n int profit = 0;\n\n if(buy == 0){ // buy stocks\n profit = Math.max(-prices[index] + dp[index+1][1], 0 + dp[index+1][0]);\n }\n if(buy == 1){ // we can sell stocks\n profit = Math.max(prices[index] + dp[index+2][0], 0 + dp[index+1][1]);\n }\n dp[index][buy] = profit;\n }\n }\n return dp[0][0];\n }\n}", + "title": "309. Best Time to Buy and Sell Stock with Cooldown", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day)." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,2,3,0,2]Output:3Explanation:transactions = [buy, sell, cooldown, buy, sell]", + "image": null + }, + { + "text": "Example 2: Input:prices = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n \n cache = {}\n def dfs(i, buying):\n \n if i >= len(prices):\n return 0\n \n if (i, buying) in cache:\n return cache[(i, buying)]\n \n if buying:\n # if have sell the share in previous step\n # then currently we have two options\n # either buy or not buy(cooldown)\n \n # we have bought so, increment the index and set buying flag to not buying\n # and don't forget that we bought so, we have to reduce that share amount from profit\n buy = dfs(i+1, not buying) - prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( buy, cooldown )\n cache[(i, buying)] = profit\n \n else:\n # we have sell the share so, \n # we cannot buy next share we have to skip the next price(cooldown for one day)\n # set (not buying) flag to buying\n # we also have to add that share price to profit\n sell = dfs(i+2, not buying) + prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( sell, cooldown )\n cache[(i, buying)] = profit\n \n return cache[(i, buying)]\n \n return dfs(0, True)\n\n", + "title": "309. Best Time to Buy and Sell Stock with Cooldown", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 5 * 10^4", + "1 <= prices[i] < 5 * 10^4", + "0 <= fee < 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2Output:8Explanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 22.74%) | Memory: 58.7 MB (Top 87.06%)\nclass Solution {\n public int maxProfit(int[] prices, int fee) {\n int[][] dp = new int[prices.length][2];\n for (int[] a : dp) {\n a[0] = -1;\n a[1] = -1;\n }\n return profit(prices, fee, 0, 1, dp);\n }\n public int profit(int[] prices, int fee, int i, int buy, int[][] dp) {\n if (i == prices.length) {\n return 0;\n }\n if (dp[i][buy] != -1) {\n return dp[i][buy];\n }\n int maxProfit = 0;\n if (buy == 1) {\n int yesBuy = profit(prices, fee, i + 1, 0, dp) - prices[i];\n int noBuy = profit(prices, fee, i + 1, 1, dp);\n maxProfit = Math.max(yesBuy, noBuy);\n } else {\n int yesSell = prices[i] - fee + profit(prices, fee, i + 1, 1, dp);\n int noSell = profit(prices, fee, i + 1, 0, dp);\n maxProfit = Math.max(yesSell, noSell);\n }\n return dp[i][buy] = maxProfit;\n }\n}", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 5 * 10^4", + "1 <= prices[i] < 5 * 10^4", + "0 <= fee < 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2Output:8Explanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n n = len(prices)\n lookup = {}\n def f(ind, buy, lookup):\n \n if ind == n: return 0\n \n if (ind, buy) in lookup: return lookup[(ind, buy)]\n profit = 0\n if buy:\n profit = max(-prices[ind] + f(ind+1,0,lookup), f(ind+1, 1,lookup))\n else:\n profit = max(prices[ind] + f(ind+1,1,lookup) - fee, f(ind+1, 0,lookup))\n \n lookup[(ind,buy)] = profit\n return lookup[(ind,buy)]\n \n return f(0, 1,lookup)\n\n", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , find and return the longest distance between any two adjacent 1 's in the binary representation of n . If there are no two adjacent 1 's, return 0 . Two 1 's are adjacent if there are only 0 's separating them (possibly no 0 's). The distance between two 1 's is the absolute difference between their bit positions. For example, the two 1 's in \"1001\" have a distance of 3. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 22Output:2Explanation:22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 8Output:0Explanation:8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.", + "image": null + }, + { + "text": "Example 3: Input:n = 5Output:2Explanation:5 in binary is \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 30.57%) | Memory: 41 MB (Top 56.77%)\nclass Solution {\n public int binaryGap(int n) {\n char[] arr = Integer.toBinaryString(n).toCharArray();\n List ans = new ArrayList();\n for(int i = 0; i < arr.length ; i++){\n if(arr[i] == '1')\n ans.add(i);\n }\n int res = 0;\n for ( int i = 0 ; i < ans.size() -1 ; i++){\n res =Math.max(res,ans.get(i+1) - ans.get(i));\n }\n return res;\n }\n}", + "title": "868. Binary Gap", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer n , find and return the longest distance between any two adjacent 1 's in the binary representation of n . If there are no two adjacent 1 's, return 0 . Two 1 's are adjacent if there are only 0 's separating them (possibly no 0 's). The distance between two 1 's is the absolute difference between their bit positions. For example, the two 1 's in \"1001\" have a distance of 3. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 22Output:2Explanation:22 in binary is \"10110\".\nThe first adjacent pair of 1's is \"10110\" with a distance of 2.\nThe second adjacent pair of 1's is \"10110\" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 8Output:0Explanation:8 in binary is \"1000\".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.", + "image": null + }, + { + "text": "Example 3: Input:n = 5Output:2Explanation:5 in binary is \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def binaryGap(self, n: int) -> int:\n prev = 0\n res = 0\n for i, d in enumerate(bin(n)[3:]):\n if d == \"1\":\n res = max(res, i-prev+1)\n prev = i + 1\n return res\n", + "title": "868. Binary Gap", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:trueExplanation:The binary representation of 5 is: 101", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:falseExplanation:The binary representation of 7 is: 111.", + "image": null + }, + { + "text": "Example 3: Input:n = 11Output:falseExplanation:The binary representation of 11 is: 1011.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.76 MB (Top 13.5%)\n\nclass Solution {\n public boolean hasAlternatingBits(int n) {\n int flag = 1;\n if(n % 2 == 0) flag = 0;\n return bin(n / 2, flag);\n }\n public boolean bin(int n, int flag) {\n if(flag == n % 2) return false;\n if(n == 0) return true;\n else return bin(n / 2, n % 2);\n }\n}", + "title": "693. Binary Number with Alternating Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:trueExplanation:The binary representation of 5 is: 101", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:falseExplanation:The binary representation of 7 is: 111.", + "image": null + }, + { + "text": "Example 3: Input:n = 11Output:falseExplanation:The binary representation of 11 is: 1011.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n bin_n = bin(n)[2:]\n for i in range(len(bin_n)-1):\n if bin_n[i] == '0' and bin_n[i+1] == '0':\n return False\n \n if bin_n[i] == '1' and bin_n[i+1] == '1':\n return False\n \n return True\n\n", + "title": "693. Binary Number with Alternating Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9Output:4Explanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2Output:-1Explanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int l = 0;\n int r = nums.length - 1;\n return binarySearch(nums, l, r, target);\n }\n \n private int binarySearch(int[] nums, int l, int r, int target) {\n if (l <= r) {\n int mid = (r + l) / 2;\n \n if (nums[mid] == target) {\n return mid;\n } \n \n if (nums[mid] < target) {\n return binarySearch(nums, mid + 1, r, target);\n } else {\n return binarySearch(nums, l, mid - 1, target);\n }\n } \n return -1;\n }\n}\n", + "title": "704. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9Output:4Explanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2Output:-1Explanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 214 ms (Top 71.5%) | Memory: 17.81 MB (Top 65.3%)\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums)-1\n \n while left<=right:\n mid = (left+right)//2\n if nums[mid]==target:\n return mid\n elif nums[mid]>target:\n right = mid-1\n else:\n left = mid+1\n \n return -1", + "title": "704. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. Example 1:", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "class BSTIterator {\n\n TreeNode root;\n TreeNode current;\n Stack st = new Stack<>();\n public BSTIterator(TreeNode root) {\n this.root = root;\n //init(root);\n current = findLeft(root);\n //System.out.println(\"Init: stack is: \"+st);\n }\n\n public int next() {\n \n int val = -1;\n if(current != null)\n val = current.val;\n else\n return -1;\n \n if(current.right != null)\n current = findLeft(current.right);\n else if(!st.isEmpty())\n current = st.pop();\n else \n current = null;\n // System.out.println(\"next: stack is: \"+st);\n return val;\n }\n \n public TreeNode findLeft(TreeNode node) {\n \n if(node == null)\n return null;\n \n if(node.left != null){\n TreeNode next = node.left;\n st.push(node);\n return findLeft(next);\n }\n else\n return node;\n \n }\n \n public boolean hasNext() {\n return current != null;\n }\n}\n", + "title": "173. Binary Search Tree Iterator", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. Example 1:", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass BSTIterator:\n\n def __init__(self, root: Optional[TreeNode]):\n self.root=root\n self.tree=[]#list to store the inorder traversal\n def inorder(node):\n if not node:\n return\n inorder(node.left)\n self.tree.append(node.val)\n inorder(node.right)\n return\n inorder(self.root)\n self.i=0\n \n\n def next(self) -> int:\n self.i+=1\n return self.tree[self.i-1]\n\n def hasNext(self) -> bool:\n return self.i-1 bool:\n ans = set()\n for i in range(len(S)):\n for ii in range(i, i + N.bit_length()): \n x = int(S[i:ii+1], 2)\n if 1 <= x <= N: ans.add(x)\n return len(ans) == N\n", + "title": "1016. Binary String With Substrings Representing 1 To N", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer goal , return the number of non-empty subarrays with a sum goal . A subarray is a contiguous part of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "nums[i] is either 0 or 1 .", + "0 <= goal <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,1,0,1], goal = 2Output:4Explanation:The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,0,0], goal = 0Output:15", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int numSubarraysWithSum(int[] nums, int goal) {\n \n int pre=0,cnt=0;\n HashMap m=new HashMap();\n for(int i:nums){\n \n pre+=i;\n // if(pre-goal<0)continue;\n if(pre-goal==0)cnt++;\n \n if(m.containsKey(pre-goal)){\n cnt+=m.get(pre-goal);\n \n \n }\n m.put(pre,m.getOrDefault(pre,0)+1);\n\n \n \n }\n \n return cnt;\n}\n", + "title": "930. Binary Subarrays With Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary array nums and an integer goal , return the number of non-empty subarrays with a sum goal . A subarray is a contiguous part of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "nums[i] is either 0 or 1 .", + "0 <= goal <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,1,0,1], goal = 2Output:4Explanation:The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,0,0], goal = 0Output:15", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 680 ms (Top 7.52%) | Memory: 17.5 MB (Top 60.81%)\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n my_dict = {0:1}\n accum, res = 0, 0\n for n in nums:\n accum += n\n diff = accum-goal\n if diff in my_dict:\n res += my_dict[diff]\n if accum in my_dict:\n my_dict[accum] +=1\n else:\n my_dict[accum] =1\n return res", + "title": "930. Binary Subarrays With Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "Node.val == 0" + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,0,null,0,0]Output:1Explanation:One camera is enough to monitor all nodes if placed as shown.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" + }, + { + "text": "Example 2: Input:root = [0,0,null,0,null,0,null,null,0]Output:2Explanation:At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n private int count = 0;\n public int minCameraCover(TreeNode root) {\n if(helper(root) == -1)\n count++;\n return count;\n }\n \n //post order\n //0 - have camera\n //1 - covered\n //-1 - not covered\n public int helper(TreeNode root) {\n if(root == null)\n return 1;\n int left = helper(root.left);\n int right = helper(root.right);\n if(left == -1 || right == -1) {\n count++;\n return 0;\n }\n if(left == 0 || right == 0)\n return 1;\n \n return -1;\n }\n}\n", + "title": "968. Binary Tree Cameras", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "Node.val == 0" + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,0,null,0,0]Output:1Explanation:One camera is enough to monitor all nodes if placed as shown.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" + }, + { + "text": "Example 2: Input:root = [0,0,null,0,null,0,null,null,0]Output:2Explanation:At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.", + "image": "https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" + } + ], + "follow_up": null, + "solution": "\nimport itertools\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minCameraHelper(self, root: Optional[TreeNode]) -> (int, int):\n # Return 3 things:\n # cam, uncam, uncov\n # cam(era) is best score for valid tree with camera at root\n # uncam(era) is best score for valid tree without camera at root\n # uncov(ered) is best score for invalid tree, where the only invalidity (i.e. the only uncovered node) is the root node\n \n # Note: maxint (float(\"inf\")) is used to signify situations that don't make sense or can't happen.\n # Anywhere there is a float(\"inf\"), you can safely replace that with a 1 as 1 is as bad or worse than worst practical,\n # but I stick with maxint to highlight the nonsensical cases for the reader!\n \n if not root.left and not root.right:\n # base case: leaf\n # Note: \"Uncam\" setting doesn't make much sense (a leaf with no parents can either have a camera or be uncovered,\n # but not covered with no camera)\n return 1, float(\"inf\"), 0\n \n if root.left:\n left_cam, left_uncam, left_uncov = self.minCameraHelper(root.left)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n left_cam, left_uncam, left_uncov = float(\"inf\"), 0, 0\n \n if root.right:\n right_cam, right_uncam, right_uncov = self.minCameraHelper(root.right)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n right_cam, right_uncam, right_uncov = float(\"inf\"), 0, 0\n \n # Get the possible combinations for each setting \n cam_poss = itertools.product([left_cam, left_uncam, left_uncov], [right_cam, right_uncam, right_uncov])\n uncam_poss = [(left_cam, right_cam), (left_uncam, right_cam), (left_cam, right_uncam)]\n uncov_poss = [(left_uncam, right_uncam)]\n \n # Compute costs for each setting\n cam = min([x + y for x, y in cam_poss]) + 1\n uncam = min([x + y for x, y in uncam_poss])\n uncov = min([x + y for x, y in uncov_poss])\n \n return cam, uncam, uncov\n \n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n cam, uncam, _ = self.minCameraHelper(root)\n return min(cam, uncam)\n\n", + "title": "968. Binary Tree Cameras", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n . Initially, the first player names a value x with 1 <= x <= n , and the second player names a value y with 1 <= y <= n and y != x . The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true . If it is not possible, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= x <= n <= 100", + "n is odd.", + "1 <= Node.val <= n", + "All the values of the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3Output:trueExplanation:The second player can choose the node with value 2.", + "image": "https://assets.leetcode.com/uploads/2019/08/01/1480-binary-tree-coloring-game.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], n = 3, x = 1Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass Solution {\n\tint xkaLeft=0,xkaRight=0;\n\tpublic int size(TreeNode node, int x)\n\t{\n\t\tif(node==null)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tint ls=size(node.left,x);\n\t\tint rs=size(node.right,x);\n\n\t\tif(node.val==x)\n\t\t{\n\t\t\txkaLeft=ls;\n\t\t\txkaRight=rs;\n\t\t}\n\n\t\treturn ls+rs+1;\n\t}\n\tpublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n\n\t\tsize(root,x);\n\t\tint parent=n-(xkaLeft+xkaRight+1);\n\t\tint max=Math.max(parent,Math.max(xkaRight,xkaLeft));\n\t\tif(max>n/2)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}", + "title": "1145. Binary Tree Coloring Game", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n . Initially, the first player names a value x with 1 <= x <= n , and the second player names a value y with 1 <= y <= n and y != x . The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true . If it is not possible, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= x <= n <= 100", + "n is odd.", + "1 <= Node.val <= n", + "All the values of the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3Output:trueExplanation:The second player can choose the node with value 2.", + "image": "https://assets.leetcode.com/uploads/2019/08/01/1480-binary-tree-coloring-game.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], n = 3, x = 1Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findParent(self,node,par = None):\n if node:\n self.parent[node.val] = par\n self.findParent(node.left,node)\n self.findParent(node.right,node)\n \n def traverse(self,node,done):\n if node:\n if node in done: return 0\n done[node] = True\n a = self.traverse(self.parent[node.val],done)\n b = self.traverse(node.left,done)\n c = self.traverse(node.right,done)\n return a + b + c + 1\n return 0\n \n def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n self.parent = {}\n self.findParent(root)\n parent = self.parent[x]\n node = root if root.val == x else parent.left if parent and parent.left and parent.left.val == x else parent.right\n up = self.traverse(parent,{node:True})\n left = self.traverse(node.left,{node:True})\n right = self.traverse(node.right,{node:True})\n return (up > left + right) or (left > up + right) or (right > up + left)\n", + "title": "1145. Binary Tree Coloring Game", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[1,3,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.83 MB (Top 42.1%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List li = new LinkedList();\n public List inorderTraversal(TreeNode root) {\n if(root == null){\n List li = new LinkedList();\n return li ;\n }\n inorderTraversal(root.left); \n li.add(root.val); \n inorderTraversal(root.right);\n return li;\n\n }\n \n}", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[1,3,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tinorder = []\n\t\tstack = []\n\n\t\twhile stack or root is not None:\n\t\t\tif root:\n\t\t\t\tstack.append(root)\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\tnode = stack.pop()\n\t\t\t\tinorder.append(node.val)\n\t\t\t\troot = node.right\n\n\t\treturn inorder\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.inorder_generator(root))\n\n\t@classmethod\n\tdef inorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.inorder_generator(tree.left)\n\t\t\tyield tree.val\n\t\t\tyield from cls.inorder_generator(tree.right)\n", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 39.54%) | Memory: 43.4 MB (Top 69.45%)\nclass Solution {\n public List> levelOrder(TreeNode root) {\n List> result = new ArrayList<>();\n if(root == null)\n return result;\n List rootList = new ArrayList<>();\n rootList.add(root.val);\n result.add(rootList);\n levelOrder(root,1,result);\n return result;\n\n }\n\n private void levelOrder(TreeNode root, int level, List> result) {\n if(root == null)\n return;\n List children = exploreChildren(root);\n if(!children.isEmpty()){\n if(level < result.size())\n result.get(level).addAll(children);\n else\n result.add(children);\n }\n levelOrder(root.left, level + 1, result);\n levelOrder(root.right, level + 1,result);\n }\n\n private List exploreChildren(TreeNode root) {\n List children = new ArrayList<>();\n if(root.left != null)\n children.add(root.left.val);\n if(root.right != null)\n children.add(root.right.val);\n return children;\n }\n}\n", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n \n \n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n \n ret = []\n next_levels = [[root]]\n \n for level in next_levels:\n curr_lv = []\n next_lv = []\n for node in level:\n if not node: \n continue\n curr_lv.append(node.val)\n next_lv.append(node.left)\n next_lv.append(node.right)\n \n if curr_lv: \n ret.append(curr_lv)\n if next_lv: \n next_levels.append(next_lv)\n \n return ret\n", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values . (i.e., from left to right, level by level from leaf to root). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[15,7],[9,20],[3]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> levelOrderBottom(TreeNode root) {\n Queue al=new LinkedList<>();\n List> fal=new LinkedList<>();\n if(root==null) return fal;\n al.offer(root);\n while(!al.isEmpty()){\n List aal=new LinkedList<>();\n int num=al.size();\n for(int i=0;i List[List[int]]:\n def dfs(node, level, result):\n if not node:\n return\n if level >= len(result):\n result.append([])\n result[level].append(node.val)\n dfs(node.left, level+1, result)\n dfs(node.right, level+1, result)\n result = []\n dfs(root, 0, result)\n return result[::-1]", + "title": "107. Binary Tree Level Order Traversal II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:6Explanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]Output:42Explanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.74%) | Memory: 48.6 MB (Top 11.74%)\nclass Solution {\n\n int[] ans = new int[1];\n public int maxPathSum(TreeNode root) {\n ans[0]=root.val; //Handle edge case\n dfs(root);\n return ans[0];\n }\n\n public int dfs(TreeNode root){\n\n if(root==null)\n return 0;\n\n int left=Math.max(0,dfs(root.left)); //Check on the left subtree and if returned negative take 0\n int right=Math.max(0,dfs(root.right)); //Check on the right subtree and if returned negative take 0\n\n int maxInTheNode=root.val+left+right; //Calculating the max while including the root its left and right child.\n ans[0]=Math.max(ans[0],maxInTheNode); //Keeping max globally\n\n return root.val+Math.max(left,right); //Since only one split is allowed returning the one split that returns max value\n }\n}", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:6Explanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]Output:42Explanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n self.res=root.val\n def solving(root):\n if not root:\n return 0\n current=root.val\n sleft,sright=float('-inf'),float('-inf')\n if root.left:\n sleft=solving(root.left)\n if(sleft>=0):\n current+=sleft\n if root.right:\n sright=solving(root.right)\n if(sright>=0):\n current+=sright\n if(current>self.res):\n self.res=current\n return max(root.val, root.val+sleft, root.val+sright)\n solving(root)\n return self.res\n", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order . A leaf is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5]Output:[\"1->2->5\",\"1->3\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[\"1\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.96%) | Memory: 42.40 MB (Top 35.43%)\n\nclass Solution {\n public List binaryTreePaths(TreeNode root) {\n List result = new ArrayList<>();\n dfs(root, new StringBuilder(), result);\n return result;\n }\n\n private void dfs(TreeNode node, StringBuilder path, List result) {\n if (node == null) return;\n int len = path.length();\n if (len > 0) {\n path.append(\"->\");\n }\n path.append(node.val);\n if (node.left == null && node.right == null) {\n result.add(path.toString());\n } else {\n dfs(node.left, path, result);\n dfs(node.right, path, result);\n }\n path.setLength(len); // Backtrack by resetting the StringBuilder\n }\n}\n", + "title": "257. Binary Tree Paths", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return all root-to-leaf paths in any order . A leaf is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5]Output:[\"1->2->5\",\"1->3\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[\"1\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n \n # DFS solution\n output = []\n stack = [(root, '')]\n \n while stack:\n node, path = stack.pop()\n path += str(node.val)\n \n if not node.left and not node.right:\n output.append(path)\n \n path += '->'\n if node.left:\n stack.append((node.left, path))\n if node.right:\n stack.append((node.right, path))\n \n return output\n", + "title": "257. Binary Tree Paths", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[3,2,1]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.3 MB (Top 40.74%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n List res = new ArrayList<>();\n public List postorderTraversal(TreeNode root) {\n traversal(root);\n return res;\n }\n\n public void traversal(TreeNode root){\n if(root == null)\n return;\n traversal(root.left);\n traversal(root.right);\n res.add(root.val);\n }\n}", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[3,2,1]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tif root is None:\n\t\t\treturn []\n\n\t\tpostorder = []\n\t\tstack = [root]\n\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tpostorder.append(node.val)\n\t\t\tif node.left is not None:\n\t\t\t\tstack.append(node.left)\n\t\t\tif node.right is not None:\n\t\t\t\tstack.append(node.right)\n\n\t\treturn postorder[::-1]\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.postorder_generator(root))\n\n\t@classmethod\n\tdef postorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.postorder_generator(tree.left)\n\t\t\tyield from cls.postorder_generator(tree.right)\n\t\t\tyield tree.val", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List preorderTraversal(TreeNode root) {\n List result = new ArrayList<>();\n preorderTraversal2(root, result);\n return result;\n }\n\n\n public List preorderTraversal2(TreeNode root,List result) {\n if(root!=null){\n result.add(root.val);\n if(root.left!=null){\n preorderTraversal2(root.left,result);\n }\n if(root.right!=null){\n preorderTraversal2(root.right,result);\n }\n }\n return result;\n }\n}\n", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,3]Output:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 23.56%) | Memory: 13.9 MB (Top 60.28%)\nfrom collections import deque\nfrom typing import List, Optional\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n\n queue = deque([root])\n preorder = []\n\n while queue:\n node = queue.pop()\n preorder.append(node.val)\n\n if node.right is not None:\n queue.append(node.right)\n if node.left is not None:\n queue.append(node.left)\n\n return preorder\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n return list(self.preorder_generator(root))\n\n @classmethod\n def preorder_generator(cls, tree: Optional[TreeNode]):\n if tree is not None:\n yield tree.val\n yield from cls.preorder_generator(tree.left)\n yield from cls.preorder_generator(tree.right)", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed . A subtree of a node node is node plus every node that is a descendant of node . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 200] .", + "Node.val is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,0,0,1]Output:[1,null,0,null,1]Explanation:Only the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" + }, + { + "text": "Example 2: Input:root = [1,0,1,0,0,0,1]Output:[1,null,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" + }, + { + "text": "Example 3: Input:root = [1,1,0,1,1,0,1,0]Output:[1,1,0,1,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.81 MB (Top 82.6%)\n\nclass Solution {\n public TreeNode pruneTree(TreeNode root) {\n \n if(root == null) return root;\n \n root.left = pruneTree(root.left);\n root.right = pruneTree(root.right);\n \n if(root.left == null && root.right == null && root.val == 0) return null;\n else return root;\n }\n}", + "title": "814. Binary Tree Pruning", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed . A subtree of a node node is node plus every node that is a descendant of node . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 200] .", + "Node.val is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,0,0,1]Output:[1,null,0,null,1]Explanation:Only the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" + }, + { + "text": "Example 2: Input:root = [1,0,1,0,0,0,1]Output:[1,null,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" + }, + { + "text": "Example 3: Input:root = [1,1,0,1,1,0,1,0]Output:[1,1,0,1,1,null,1]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 80.71%) | Memory: 17.30 MB (Top 5.56%)\n\nclass Solution:\n def pruneTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if not root: return root\n root.left, root.right = self.pruneTree(root.left), self.pruneTree(root.right)\n return None if not root.val and not root.left and not root.right else root\n", + "title": "814. Binary Tree Pruning", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5,null,4]Output:[1,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,3]Output:[1,3]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Utility Function of RightSideView\n public void rightView(TreeNode curr, List list, int level) {\n // if, current is null, return\n if(curr == null) {\n return;\n }\n \n // if, level = list size\n // add current val to list\n if(level == list.size()) {\n list.add(curr.val);\n }\n \n // recursive call for right side view\n rightView(curr.right, list, level + 1);\n // recursive call for left side view\n rightView(curr.left, list, level + 1);\n }\n \n // Binary Tree Right Side View Function\n public List rightSideView(TreeNode root) {\n // create a list\n List result = new ArrayList<>();\n // call right view function\n rightView(root, result, 0);\n return result;\n }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(h) h = height of binary tree\n*/\n", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,5,null,4]Output:[1,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,3]Output:[1,3]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 45.43%) | Memory: 13.9 MB (Top 70.59%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n\n def dfs(root, d):\n\n if not root: return\n\n if self.maxi < d:\n self.res.append(root.val)\n self.maxi = d\n\n dfs(root.right, d+1)\n dfs(root.left, d+1)\n\n self.res, self.maxi = [], 0\n dfs(root, 1)\n return self.res\n\n # An Upvote will be encouraging\n", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt . The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values . If a node does not have a left child, then the sum of the left subtree node values is treated as 0 . The rule is similar if the node does not have a right child. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:1Explanation:Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,9,3,5,null,7]Output:15Explanation:Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg" + }, + { + "text": "Example 3: Input:root = [21,7,14,1,1,2,2,3,3]Output:9", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 45.7 MB (Top 24.54%)\nclass Solution {\n int max = 0;\n public int findTilt(TreeNode root) {\n loop(root);\n return max;\n }\n public int loop(TreeNode root){\n if(root==null) return 0;\n int left = loop(root.left);\n int right = loop(root.right);\n max+= Math.abs(left-right);\n return root.val+left+right;\n }\n}", + "title": "563. Binary Tree Tilt", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the sum of every tree node's tilt . The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values . If a node does not have a left child, then the sum of the left subtree node values is treated as 0 . The rule is similar if the node does not have a right child. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:1Explanation:Tilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,9,3,5,null,7]Output:15Explanation:Tilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg" + }, + { + "text": "Example 3: Input:root = [21,7,14,1,1,2,2,3,3]Output:9", + "image": "https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 66 ms (Top 84.95%) | Memory: 16.4 MB (Top 43.30%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findTilt(self, root: Optional[TreeNode]) -> int:\n res = [0]\n def tilt_helper(root,res):\n if not root:\n return 0\n\n left = tilt_helper(root.left,res)\n right = tilt_helper(root.right,res)\n\n res[0] += abs(left-right)\n\n return left + right + root.val\n\n tilt_helper(root,res)\n return res[0]", + "title": "563. Binary Tree Tilt", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values . (i.e., from left to right, then right to left for the next level and alternate between). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[3],[20,9],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> zigzagLevelOrder(TreeNode root) {\n Queue q=new LinkedList();\n List> res=new ArrayList<>();\n if(root==null){\n return res;\n }\n q.offer(root);\n boolean flag=true;\n while(!q.isEmpty()){\n int size=q.size();\n List curr=new ArrayList<>();\n for(int i=0;i dp;\n HashSet set;\n \n public int numFactoredBinaryTrees(int[] arr) {\n long ans = 0;\n dp = new HashMap<>();\n set = new HashSet<>();\n \n for(int val : arr) set.add(val);\n \n for(int val : arr) {\n\t\t\t//giving each unique value a chance to be root node of the tree\n ans += solve(val, arr);\n ans %= mod;\n }\n \n return (int)ans;\n }\n \n public long solve(int val, int[] nums) {\n \n if(dp.containsKey(val)) {\n return dp.get(val);\n }\n \n long ans = 1;\n \n for(int i = 0; i < nums.length; i++) {\n if(val % nums[i] == 0 && set.contains(val / nums[i])) {\n long left = solve(nums[i], nums);\n long right = solve(val / nums[i], nums);\n \n ans += ((left * right) % mod);\n ans %= mod;\n }\n }\n \n dp.put(val, ans);\n \n return ans;\n }\n}\n", + "title": "823. Binary Trees With Factors", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of unique integers, arr , where each integer arr[i] is strictly greater than 1 . We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the number of binary trees we can make . The answer may be too large so return the answer modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "2 <= arr[i] <= 10^9", + "All the values of arr are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,4]Output:3Explanation:We can make these trees:[2], [4], [4, 2, 2]", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,4,5,10]Output:7Explanation:We can make these trees:[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numFactoredBinaryTrees(self, nums: List[int]) -> int:\n nums = set(nums)\n n = len(nums)\n \n @lru_cache(None)\n def helper(num):\n trees = 1\n for factor in nums:\n if not num % factor and num // factor in nums:\n trees += helper(factor) * helper(num // factor)\n\n return trees\n \n return sum(helper(num) for num in nums) % (10 ** 9 + 7)", + "title": "823. Binary Trees With Factors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent . You may return the answer in any order . The hour must not contain a leading zero. The minute must be consist of two digits and may contain a leading zero. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg" + ], + "constraints": [ + "For example, the below binary watch reads \"4:51\" ." + ], + "examples": [ + { + "text": "Example 1: Input:turnedOn = 1Output:[\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]", + "image": null + }, + { + "text": "Example 2: Input:turnedOn = 9Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 44 ms (Top 50.1%) | Memory: 16.36 MB (Top 42.0%)\n\nclass Solution:\n def readBinaryWatch(self, turnedOn: int) -> List[str]:\n output = []\n # Loop through all possible combinations of hours and minutes and count the number of set bits\n for h in range(12):\n for m in range(60):\n if bin(h).count('1') + bin(m).count('1') == turnedOn: # Check if the number of set bits in hours and minutes equals the target number\n output.append(f\"{h}:{m:02d}\") # Add the valid combination of hours and minutes to the output list\n return output\n", + "title": "401. Binary Watch", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7Output:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int rangeBitwiseAnd(int left, int right) {\n int count=0;\n while(left!=right){\n left>>=1;\n right>>=1;\n count++;\n }\n return right<<=count;\n}\n", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7Output:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 17.27%) | Memory: 13.9 MB (Top 25.09%)\nclass Solution:\n def rangeBitwiseAnd(self, left: int, right: int) -> int:\n if not left: return 0\n i = 0\n cur = left\n while cur + (cur & -cur) <= right:\n cur += cur & -cur\n left &= cur\n return left", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have an array arr of non-negative integers. For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j ), we take the bitwise OR of all the elements in sub , obtaining a result arr[i] | arr[i + 1] | ... | arr[j] . Return the number of possible results. Results that occur more than once are only counted once in the final answer Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0]Output:1Explanation:There is only one possible result: 0.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2]Output:3Explanation:The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4]Output:6Explanation:The possible results are 1, 2, 3, 4, 6, and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 454 ms (Top 75.74%) | Memory: 71.3 MB (Top 97.04%)\nclass Solution {\n public int subarrayBitwiseORs(int[] arr) {\n int n = arr.length;\n Set s = new HashSet();\n LinkedList queue = new LinkedList();\n for(int i = 0; i< n; i++){\n int size = queue.size();\n if(!queue.contains(arr[i])){\n queue.offer(arr[i]);\n s.add(arr[i]);\n }\n int j = 0;\n while(j int:\n \n \n ans=set(arr)\n \n # each element is a subarry\n \n \n one = set()\n \n # to get the ans for the subarray of size >1\n # starting from 0th element to the ending element\n \n \n one.add(arr[0])\n \n for i in range(1,len(arr)):\n \n two=set()\n \n for j in one:\n \n two.add(j | arr[i])\n \n # subarray from the element in one set to the current ele(i th one)\n \n ans.add(j| arr[i])\n \n \n two.add(arr[i])\n \n # adding curr element to set two so that from next iteration we can take sub array starting from curr element \n \n one = two\n \n return len(ans)\n \n", + "title": "898. Bitwise ORs of Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array people where people[i] is the weight of the i th person, and an infinite number of boats where each boat can carry a maximum weight of limit . Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit . Return the minimum number of boats to carry every given person . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= people.length <= 5 * 10^4", + "1 <= people[i] <= limit <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:people = [1,2], limit = 3Output:1Explanation:1 boat (1, 2)", + "image": null + }, + { + "text": "Example 2: Input:people = [3,2,2,1], limit = 3Output:3Explanation:3 boats (1, 2), (2) and (3)", + "image": null + }, + { + "text": "Example 3: Input:people = [3,5,3,4], limit = 5Output:4Explanation:4 boats (3), (3), (4), (5)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 38.47%) | Memory: 65.6 MB (Top 33.01%)\nclass Solution {\n public int numRescueBoats(int[] people, int limit) {\n int boatCount = 0;\n Arrays.sort(people);\n\n int left = 0;\n int right = people.length - 1;\n\n while(left <= right){\n int sum = people[left] + people[right];\n if(sum <= limit){\n boatCount++;\n left++;\n right--;\n }\n else{\n boatCount++;\n right--;\n }\n }\n return boatCount;\n }\n}", + "title": "881. Boats to Save People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array people where people[i] is the weight of the i th person, and an infinite number of boats where each boat can carry a maximum weight of limit . Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit . Return the minimum number of boats to carry every given person . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= people.length <= 5 * 10^4", + "1 <= people[i] <= limit <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:people = [1,2], limit = 3Output:1Explanation:1 boat (1, 2)", + "image": null + }, + { + "text": "Example 2: Input:people = [3,2,2,1], limit = 3Output:3Explanation:3 boats (1, 2), (2) and (3)", + "image": null + }, + { + "text": "Example 3: Input:people = [3,5,3,4], limit = 5Output:4Explanation:4 boats (3), (3), (4), (5)", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people)-1\n boats = 0\n while lo <= hi:\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n else:\n hi -= 1\n boats += 1\n return boats\n", + "title": "881. Boats to Save People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A concert hall has n rows numbered from 0 to n - 1 , each with m seats, numbered from 0 to m - 1 . You need to design a ticketing system that can allocate seats in the following cases: Note that the spectators are very picky. Hence: Implement the BookMyShow class: Example 1:", + "description_images": [], + "constraints": [ + "If a group of k spectators can sit together in a row.", + "If every member of a group of k spectators can get a seat. They may or may not sit together." + ], + "examples": [ + { + "text": "Example 1: Input[\"BookMyShow\", \"gather\", \"gather\", \"scatter\", \"scatter\"]\n[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]Output[null, [0, 0], [], true, false]ExplanationBookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \nbms.gather(4, 0); // return [0, 0]\n // The group books seats [0, 3] of row 0. \nbms.gather(2, 0); // return []\n // There is only 1 seat left in row 0,\n // so it is not possible to book 2 consecutive seats. \nbms.scatter(5, 1); // return True\n // The group books seat 4 of row 0 and seats [0, 3] of row 1. \nbms.scatter(5, 1); // return False\n // There is only one seat left in the hall.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 221 ms (Top 91.46%) | Memory: 140.4 MB (Top 35.37%)\nclass BookMyShow {\n /**\n Segment tree class to store sum of a range and maximum available seats in a row\n **/\n static class SegTree{\n long sum[]; // store sum of seats in a range\n long segTree[]; // store maximum seats in a range\n int m, n;\n public SegTree(int n, int m) {\n this.m = m;\n this.n = n;\n segTree = new long[4*n];\n sum = new long[4*n];\n build(0, 0, n-1, m);\n }\n\n private void build(int index, int lo, int hi, long val){\n if(lo == hi){\n segTree[index] = val; // initialize segement tree with initial seat capacity\n sum[index] = val; // initialize \"sum\" with initial seat capacity of a row\n return;\n }\n int mid = (lo + hi)/2;\n build(2*index +1, lo, mid, val); // build left sub tree\n build(2*index +2, mid+1, hi, val); // build right sub tree\n segTree[index] = Math.max(segTree[2*index + 1], segTree[2*index + 2]); // maximum seats in a row for subtrees\n sum[index] = sum[2*index + 1] + sum[2*index + 2]; // sum of seats in a range\n }\n\n private void update(int index, int lo, int hi, int pos, int val){\n /**\n Method to update segment tree based on the available seats in a row\n **/\n if(lo == hi){\n segTree[index] = val;\n sum[index] = val;\n return;\n }\n int mid = (lo + hi) / 2;\n if (pos <= mid) { // position to update is in left\n update(2 * index + 1, lo, mid, pos, val);\n } else { // position to update is in right\n update(2 * index + 2, mid+1, hi, pos, val);\n }\n // update segment tree and \"sum\" based on the update in \"pos\" index\n segTree[index] = Math.max(segTree[2*index + 1] , segTree[2*index + 2]);\n sum[index] = sum[2*index + 1] + sum[2*index + 2];\n }\n\n public void update(int pos, int val){\n update(0, 0, n - 1 , pos, val);\n }\n\n public int gatherQuery(int k, int maxRow){\n return gatherQuery(0, 0, n - 1 , k, maxRow);\n }\n\n private int gatherQuery(int index, int lo, int hi, int k, int maxRow){\n /**\n Method to check if seats are available in a single row\n **/\n if(segTree[index] < k || lo > maxRow)\n return -1;\n if(lo == hi) return lo;\n int mid = (lo + hi) / 2;\n int c = gatherQuery(2*index + 1, lo, mid, k, maxRow);\n if(c == -1){\n c = gatherQuery(2*index + 2, mid +1, hi, k, maxRow);\n }\n return c;\n }\n\n public long sumQuery(int k, int maxRow){\n return sumQuery(0, 0, n-1, k, maxRow);\n }\n\n private long sumQuery(int index, int lo, int hi, int l, int r){\n if(lo > r || hi < l ) return 0; // not in range\n if(lo >= l && hi <= r) return sum[index]; // in range\n int mid = (lo + hi)/2;\n return sumQuery(2*index+1, lo, mid, l, r) + sumQuery(2*index+2, mid+1, hi, l, r);\n }\n }\n\n SegTree segTree;\n int[] rowSeats; // stores avaiable seats in a row, helps to find the vacant seat in a row\n\n public BookMyShow(int n, int m) {\n segTree = new SegTree(n, m);\n rowSeats = new int[n];\n Arrays.fill(rowSeats, m); // initialize vacant seats count to \"m\" for all the rows\n }\n\n public int[] gather(int k, int maxRow) {\n int row = segTree.gatherQuery(k, maxRow); // find row which has k seats\n if(row == -1) return new int[]{}; // can't find a row with k seats\n int col = segTree.m - rowSeats[row]; // find column in the row which has k seats\n rowSeats[row] -= k; // reduce the seats\n segTree.update(row, rowSeats[row]); // update the segment tree\n return new int[]{row, col};\n\n }\n\n public boolean scatter(int k, int maxRow) {\n long sum = segTree.sumQuery(0, maxRow); // find the sum for the given range [0, maxRow]\n if(sum < k) return false; // can't find k seats in [0, maxRow]\n\n for(int i=0; i<=maxRow && k !=0 ; i++){\n if(rowSeats[i] > 0){ // if current row has seats then allocate those seats\n long t = Math.min(rowSeats[i], k);\n rowSeats[i] -= t;\n k -= t;\n segTree.update(i,rowSeats[i]); // update the segment tree\n }\n }\n return true;\n }\n}", + "title": "2286. Booking Concert Tickets in Groups", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A concert hall has n rows numbered from 0 to n - 1 , each with m seats, numbered from 0 to m - 1 . You need to design a ticketing system that can allocate seats in the following cases: Note that the spectators are very picky. Hence: Implement the BookMyShow class: Example 1:", + "description_images": [], + "constraints": [ + "If a group of k spectators can sit together in a row.", + "If every member of a group of k spectators can get a seat. They may or may not sit together." + ], + "examples": [ + { + "text": "Example 1: Input[\"BookMyShow\", \"gather\", \"gather\", \"scatter\", \"scatter\"]\n[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]Output[null, [0, 0], [], true, false]ExplanationBookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \nbms.gather(4, 0); // return [0, 0]\n // The group books seats [0, 3] of row 0. \nbms.gather(2, 0); // return []\n // There is only 1 seat left in row 0,\n // so it is not possible to book 2 consecutive seats. \nbms.scatter(5, 1); // return True\n // The group books seat 4 of row 0 and seats [0, 3] of row 1. \nbms.scatter(5, 1); // return False\n // There is only one seat left in the hall.", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self, start, end):\n self.s = start\n self.e = end\n self.left = None\n self.right = None\n self.total = 0 # for range sum query\n self.mx = 0 # for range max query\n \nclass SegTree:\n def __init__(self, start, end, val):\n \n def build(l, r):\n if l > r:\n return None\n if l == r:\n node = Node(l, r)\n node.total = val\n node.mx = val\n return node\n node = Node(l, r)\n m = (l + r) // 2\n node.left = build(l, m)\n node.right = build(m+1, r)\n node.mx = max(node.left.mx, node.right.mx)\n node.total = node.left.total + node.right.total\n return node\n \n self.root = build(start, end)\n \n\t# update the total remain seats and the max remain seats for each node (range) in the segment tree\n def update(self, index, val):\n \n def updateHelper(node):\n if node.s == node.e == index:\n node.total -= val\n node.mx -= val\n return\n m = (node.s + node.e) // 2\n if index <= m:\n updateHelper(node.left)\n elif index > m:\n updateHelper(node.right)\n node.mx = max(node.left.mx, node.right.mx)\n node.total = node.left.total + node.right.total\n return\n \n updateHelper(self.root)\n \n def maxQuery(self, k, maxRow, seats):\n \n def queryHelper(node):\n if node.s == node.e:\n\t\t\t\t# check if the row number is less than maxRow and the number of remains seats is greater or equal than k\n if node.e > maxRow or node.total < k:\n return []\n if node.e <= maxRow and node.total >= k:\n return [node.e, seats - node.total]\n\t\t\t# we want to greedily search the left subtree to get the smallest row which has enough remain seats\n if node.left.mx >= k:\n return queryHelper(node.left)\n return queryHelper(node.right)\n \n return queryHelper(self.root)\n \n def sumQuery(self, endRow):\n \n def queryHelper(node, left, right):\n if left <= node.s and node.e <= right:\n return node.total\n m = (node.s + node.e) // 2\n if right <= m:\n return queryHelper(node.left, left, right)\n elif left > m:\n return queryHelper(node.right, left, right)\n return queryHelper(node.left, left, m) + queryHelper(node.right, m+1, right)\n \n return queryHelper(self.root, 0, endRow)\n \nclass BookMyShow:\n\n def __init__(self, n: int, m: int):\n self.m = m\n self.seg = SegTree(0, n-1, m)\n\t\t# record the remain seats at each row\n self.seats = [m] * n\n\t\t# record the index of the smallest row that has remain seats > 0\n self.startRow = 0\n \n def gather(self, k: int, maxRow: int) -> List[int]:\n res = self.seg.maxQuery(k, maxRow, self.m)\n if res:\n row = res[0]\n self.seg.update(row, k)\n self.seats[row] -= k\n return res\n\n def scatter(self, k: int, maxRow: int) -> bool:\n if self.seg.sumQuery(maxRow) < k:\n return False\n else:\n i = self.startRow\n total = 0\n while total < k:\n prevTotal = total\n total += self.seats[i]\n if total < k:\n\t\t\t\t\t# use up all the seats at ith row\n self.seg.update(i, self.seats[i])\n self.seats[i] = 0\n i += 1\n self.startRow = i\n elif total >= k:\n\t\t\t\t\t# occupy (k - prevTotal) seats at ith row\n self.seg.update(i, k - prevTotal)\n self.seats[i] -= k - prevTotal\n return True\n", + "title": "2286. Booking Concert Tickets in Groups", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Formally, the three rules for our grammar: Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Single letters represent a singleton set containing that word. R(\"a\") = {\"a\"} R(\"w\") = {\"w\"}", + "R(\"a\") = {\"a\"}", + "R(\"w\") = {\"w\"}", + "When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"} R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}", + "R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"} R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}", + "R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}", + "R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}" + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"{a,b}{c,{d,e}}\"Output:[\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"{{a,z},a{b,c},{ab,z}}\"Output:[\"a\",\"ab\",\"ac\",\"z\"]Explanation:Each distinct word is written only once in the final answer.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 41.79%) | Memory: 50.4 MB (Top 43.28%)\nclass Solution {\n // To Get the value of index traversed in a recursive call.\n int index = 0;\n\n public List braceExpansionII(String expression) {\n List result = util(0, expression);\n Set set = new TreeSet<>();\n set.addAll(result);\n return new ArrayList<>(set);\n }\n\n List util(int startIndex, String expression) {\n // This represents processed List in the current recursion.\n List currentSet = new ArrayList<>();\n boolean isAdditive = false;\n String currentString = \"\";\n // This represents List that is being processed and not yet merged to currentSet.\n List currentList = new ArrayList<>();\n\n for (int i = startIndex; i < expression.length(); ++i) {\n\n if (expression.charAt(i) == ',') {\n isAdditive = true;\n if (currentString != \"\" && currentList.size() == 0) {\n currentSet.add(currentString);\n }\n\n else if (currentList.size() > 0) {\n for (var entry : currentList) {\n currentSet.add(entry);\n }\n }\n\n currentString = \"\";\n currentList = new ArrayList<>();\n } else if (expression.charAt(i) >= 'a' && expression.charAt(i) <= 'z') {\n if (currentList.size() > 0) {\n List tempStringList = new ArrayList<>();\n for (var entry : currentList) {\n tempStringList.add(entry + expression.charAt(i));\n }\n currentList = tempStringList;\n } else {\n currentString = currentString + expression.charAt(i);\n }\n } else if (expression.charAt(i) == '{') {\n List list = util(i + 1, expression);\n // System.out.println(list);\n // Need to merge the returned List. It could be one of the following.\n // 1- ..., {a,b,c}\n // 2- a{a,b,c}\n // 3- {a,b,c}{d,e,f}\n // 3- {a,b,c}d\n if (i > startIndex && expression.charAt(i - 1) == ',') {\n // Case 1\n currentList = list;\n } else {\n if (currentList.size() > 0) {\n List tempList = new ArrayList<>();\n for (var entry1 : currentList) {\n for (var entry2 : list) {\n // CASE 3\n tempList.add(entry1 + currentString + entry2);\n }\n }\n\n // System.out.println(currentList);\n currentList = tempList;\n currentString = \"\";\n }\n\n else if (currentString != \"\") {\n List tempList = new ArrayList<>();\n for (var entry : list) {\n // case 2\n tempList.add(currentString + entry);\n }\n\n currentString = \"\";\n currentList = tempList;\n } else {\n // CASE 1\n currentList = list;\n }\n }\n\n // Increment i to end of next recursion's processing.\n i = index;\n } else if (expression.charAt(i) == '}') {\n if (currentString != \"\") {\n currentSet.add(currentString);\n }\n\n // {a{b,c,d}}\n if (currentList.size() > 0) {\n for (var entry : currentList) {\n\n currentSet.add(entry + currentString);\n }\n currentList = new ArrayList<>();\n }\n\n index = i;\n return new ArrayList<>(currentSet);\n }\n }\n\n if (currentList.size() > 0) {\n\n currentSet.addAll(currentList);\n }\n\n // {...}a\n if (currentString != \"\") {\n\n List tempSet = new ArrayList<>();\n if (currentSet.size() > 0) {\n for (var entry : currentSet) {\n tempSet.add(entry + currentString);\n }\n\n currentSet = tempSet;\n } else {\n currentSet = new ArrayList<>();\n currentSet.add(currentString);\n }\n }\n\n return new ArrayList<>(currentSet);\n }\n}", + "title": "1096. Brace Expansion II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Formally, the three rules for our grammar: Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Single letters represent a singleton set containing that word. R(\"a\") = {\"a\"} R(\"w\") = {\"w\"}", + "R(\"a\") = {\"a\"}", + "R(\"w\") = {\"w\"}", + "When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"} R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}", + "R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)", + "When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"} R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}", + "R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}", + "R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}" + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"{a,b}{c,{d,e}}\"Output:[\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]", + "image": null + }, + { + "text": "Example 2: Input:expression = \"{{a,z},a{b,c},{ab,z}}\"Output:[\"a\",\"ab\",\"ac\",\"z\"]Explanation:Each distinct word is written only once in the final answer.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n s = list(reversed(\"{\" + expression + \"}\"))\n \n def full_word(): \n cur = [] \n while s and s[-1].isalpha(): \n cur.append(s.pop()) \n return \"\".join(cur)\n \n def _expr(): \n res = set() \n if s[-1].isalpha(): \n res.add(full_word()) \n elif s[-1] == \"{\": \n s.pop() # remove open brace\n res.update(_expr()) \n while s and s[-1] == \",\": \n s.pop() # remove comma \n res.update(_expr()) \n s.pop() # remove close brace \n while s and s[-1] not in \"},\": \n res = {e + o for o in _expr() for e in res}\n return res \n \n return sorted(_expr()) \n", + "title": "1096. Brace Expansion II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a palindromic string of lowercase English letters palindrome , replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible. Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b . For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd' . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= palindrome.length <= 1000", + "palindrome consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:palindrome = \"abccba\"Output:\"aaccba\"Explanation:There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.", + "image": null + }, + { + "text": "Example 2: Input:palindrome = \"a\"Output:\"\"Explanation:There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String breakPalindrome(String palindrome) {\n \n int left = 0;\n int right = palindrome.length()-1;\n \n if(palindrome.length()==1)\n return \"\";\n \n while(left> wall) \n {\n HashMap edge_frequency = new HashMap<>(); //HashMap to store the number of common edges among the rows\n int max_frequency = 0; //Variable to store the frequency of most occuring edge\n \n for(int row=0; row int:\n m = len(wall)\n ctr = {}\n res = m\n for i in range(m):\n n = len(wall[i])\n curr = 0\n for j in range(n - 1):\n curr += wall[i][j]\n x = ctr.get(curr, m) - 1\n ctr[curr] = x\n res = min(res, x)\n return res\n", + "title": "554. Brick Wall", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary grid , where each 1 represents a brick and 0 represents an empty space. A brick is stable if: You are also given an array hits , which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (row i , col i ) . The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall . Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result , where each result[i] is the number of bricks that will fall after the i th erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is directly connected to the top of the grid, or", + "At least one other brick in its four adjacent cells is stable ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]Output:[2]Explanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]Output:[0,0]Explanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 84.7%) | Memory: 57.45 MB (Top 26.3%)\n\nclass Solution {\n int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};\n\n public int[] hitBricks(int[][] grid, int[][] hits) {\n //marking all the hits that has a brick with -1\n for(int i=0;i=0;i--){\n int row = hits[i][0];\n int col = hits[i][1];\n \n //hit is at empty space so continue\n if(grid[row][col] == 0)\n continue;\n \n //marking it with 1, this signifies that a brick is present in an unstable state and will be restored in the future\n grid[row][col] = 1;\n // checking brick stability, if it's unstable no need to visit the neighbours\n if(!isStable(grid, row, col))\n continue;\n\t\t\t\n\t\t\t//So now as our brick is stable we can restore all the bricks connected to it\n //mark all the unstable bricks as stable and get the count\n res[i] = markAndCountStableBricks(grid, hits[i][0], hits[i][1])-1; //Subtracting 1 from the total count, as we don't wanna include the starting restored brick\n }\n \n return res;\n }\n \n private int markAndCountStableBricks(int[][] grid, int row, int col){\n if(grid[row][col] == 0 || grid[row][col] == -1)\n return 0;\n \n grid[row][col] = 2;\n int stableBricks = 1;\n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2)\n continue;\n \n stableBricks += markAndCountStableBricks(grid, r, c);\n }\n \n return stableBricks;\n }\n \n private boolean isStable(int[][] grid, int row, int col){\n if(row == 0)\n return true;\n \n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 2)\n return true;\n }\n \n return false;\n }\n}", + "title": "803. Bricks Falling When Hit", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n binary grid , where each 1 represents a brick and 0 represents an empty space. A brick is stable if: You are also given an array hits , which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (row i , col i ) . The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall . Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result , where each result[i] is the number of bricks that will fall after the i th erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is directly connected to the top of the grid, or", + "At least one other brick in its four adjacent cells is stable ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]Output:[2]Explanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]Output:[0,0]Explanation:Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7285 ms (Top 5.13%) | Memory: 29.8 MB (Top 5.13%)\nfrom collections import defaultdict\n\nclass Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n parent = defaultdict()\n sz = defaultdict(lambda:1)\n empty = set()\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n pi = find(i)\n pj = find(j)\n if pi != pj:\n parent[pi] = pj\n sz[pj] += sz[pi]\n row = len(grid)\n col = len(grid[0])\n for r in range(row):\n for c in range(col):\n parent[(r,c)] = (r,c)\n parent[(row,col)] = (row,col)\n for r, c in hits:\n if grid[r][c]:\n grid[r][c] = 0\n else:\n empty.add((r,c))\n for r in range(row):\n for c in range(col):\n if not grid[r][c]:\n continue\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r, c),(r+dr, c+dc))\n if r == 0:\n union((r,c),(row,col))\n res = [0]*len(hits)\n for i in range(len(hits)-1,-1,-1):\n r, c = hits[i]\n if (r,c) in empty:\n continue\n grid[r][c] = 1\n curbricks = sz[find((row,col))]\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r,c),(r+dr,c+dc))\n if r == 0:\n union((r,c),(row,col))\n nextbricks = sz[find((row,col))]\n if nextbricks > curbricks:\n res[i] = nextbricks - curbricks - 1\n return res", + "title": "803. Bricks Falling When Hit", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: Given two integers startValue and target , return the minimum number of operations needed to display target on the calculator . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "multiply the number on display by 2 , or", + "subtract 1 from the number on display." + ], + "examples": [ + { + "text": "Example 1: Input:startValue = 2, target = 3Output:2Explanation:Use double operation and then decrement operation {2 -> 4 -> 3}.", + "image": null + }, + { + "text": "Example 2: Input:startValue = 5, target = 8Output:2Explanation:Use decrement and then double {5 -> 4 -> 8}.", + "image": null + }, + { + "text": "Example 3: Input:startValue = 3, target = 10Output:3Explanation:Use double, decrement and double {3 -> 6 -> 5 -> 10}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 78.77%)\nclass Solution {\n public int brokenCalc(int startValue, int target) {\n if(startValue >= target) return startValue - target;\n if(target % 2 == 0){\n return 1 + brokenCalc(startValue, target / 2);\n }\n return 1 + brokenCalc(startValue, target + 1);\n }\n}", + "title": "991. Broken Calculator", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: Given two integers startValue and target , return the minimum number of operations needed to display target on the calculator . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "multiply the number on display by 2 , or", + "subtract 1 from the number on display." + ], + "examples": [ + { + "text": "Example 1: Input:startValue = 2, target = 3Output:2Explanation:Use double operation and then decrement operation {2 -> 4 -> 3}.", + "image": null + }, + { + "text": "Example 2: Input:startValue = 5, target = 8Output:2Explanation:Use decrement and then double {5 -> 4 -> 8}.", + "image": null + }, + { + "text": "Example 3: Input:startValue = 3, target = 10Output:3Explanation:Use double, decrement and double {3 -> 6 -> 5 -> 10}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def brokenCalc(self, startValue, target):\n \"\"\"\n :type startValue: int\n :type target: int\n :rtype: int\n \"\"\"\n res = 0\n while target > startValue:\n res += 1\n if target % 2:\n target += 1\n else:\n target //= 2\n return res + startValue - target\n", + "title": "991. Broken Calculator", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and goal , return true if you can swap two letters in s so the result is equal to goal , otherwise, return false . Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab\", goal = \"ba\"Output:trueExplanation:You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", goal = \"ab\"Output:falseExplanation:The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\", goal = \"aa\"Output:trueExplanation:You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 90.24%) | Memory: 43 MB (Top 54.79%)\nclass Solution {\n public boolean buddyStrings(String s, String goal) {\n char a = '\\u0000', b = '\\u0000';\n char c = '\\u0000', d = '\\u0000';\n int lenS = s.length();\n int lenGoal = goal.length();\n boolean flag = true;\n HashSet hset = new HashSet<>();\n\n if(lenS != lenGoal)\n return false;\n\n if(s.equals(goal)){\n for(int i = 0; i < lenS; i++){\n if(!hset.contains(s.charAt(i))){\n hset.add(s.charAt(i));\n }\n else\n return true;\n }\n return false;\n }\n else{\n for(int i = 0; i < lenS; i++){\n if(s.charAt(i) == goal.charAt(i)){\n continue;\n }\n if(a == '\\u0000'){\n a = s.charAt(i);\n c = goal.charAt(i);\n continue;\n }\n if(b == '\\u0000'){\n b = s.charAt(i);\n d = goal.charAt(i);\n continue;\n }\n return false;\n }\n\n if(a == d && c == b && a != '\\u0000')\n return true;\n\n return false;\n }\n }\n}", + "title": "859. Buddy Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and goal , return true if you can swap two letters in s so the result is equal to goal , otherwise, return false . Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab\", goal = \"ba\"Output:trueExplanation:You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", goal = \"ab\"Output:falseExplanation:The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\", goal = \"aa\"Output:trueExplanation:You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 48.33%) | Memory: 14.1 MB (Top 96.59%)\n\nfrom collections import Counter\n\nclass Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n if len(s) != len(goal):\n return False\n diffCharactersCount = 0\n diffCharactersInS = []\n diffCharactersInGoal = []\n for i in range(len(s)):\n if s[i] != goal[i]:\n diffCharactersCount += 1\n diffCharactersInS.append(s[i])\n diffCharactersInGoal.append(goal[i])\n if diffCharactersCount == 2:\n # if there are only 2 different characters, then they should be swappable\n if ((diffCharactersInS[0] == diffCharactersInGoal[1]) and (diffCharactersInS[1] == diffCharactersInGoal[0])):\n return True\n return False\n elif diffCharactersCount == 0:\n # if there is atleast one repeating character in the string then its possible for swap\n counts = Counter(s)\n for k,v in counts.items():\n if v > 1:\n return True\n # if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings\n return False\n", + "title": "859. Buddy Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array target and an integer n . You have an empty stack with the two following operations: You also have a stream of the integers in the range [1, n] . Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target . You should follow the following rules: Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"Push\" : pushes an integer to the top of the stack.", + "\"Pop\" : removes the integer on the top of the stack." + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,3], n = 3Output:[\"Push\",\"Push\",\"Pop\",\"Push\"]Explanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].", + "image": null + }, + { + "text": "Example 2: Input:target = [1,2,3], n = 3Output:[\"Push\",\"Push\",\"Push\"]Explanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].", + "image": null + }, + { + "text": "Example 3: Input:target = [1,2], n = 4Output:[\"Push\",\"Push\"]Explanation:Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List buildArray(int[] target, int n) {\n List result=new ArrayList<>();\n int i=1,j=0;\n while(j List[str]:\n temp = []\n result = []\n x = target[-1]\n for i in range(1,x+1):\n temp.append(i)\n for i in range(len(temp)):\n if temp[i] in target:\n result.append(\"Push\")\n elif temp[i] not in target:\n result.append(\"Push\")\n result.append(\"Pop\")\n return result\n", + "title": "1441. Build an Array With Stack Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a zero-based permutation nums ( 0-indexed ), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 ( inclusive ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] < nums.length", + "The elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,2,1,5,3,4]Output:[0,1,2,4,5,3]Explanation:The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,0,1,2,3,4]Output:[4,5,0,1,2,3]Explanation:The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] buildArray(int[] nums) {\n int n=nums.length;\n for(int i=0;i List[int]:\n for i in range(len(nums)): \n if nums[nums[i]] <= len(nums):\n nums[i] = nums[nums[i]] * 1000 + nums[i]\n else:\n nums[i] = mod(nums[nums[i]],1000) * 1000 + nums[i]\n \n for i in range(len(nums)):\n nums[i] = nums[i] // 1000\n \n return nums\n", + "title": "1920. Build Array from Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given three integers n , m and k . Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr has exactly n integers.", + "1 <= arr[i] <= m where (0 <= i < n) .", + "After applying the mentioned algorithm to arr , the value search_cost is equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3, k = 1Output:6Explanation:The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 2, k = 3Output:0Explanation:There are no possible arrays that satisify the mentioned conditions.", + "image": null + }, + { + "text": "Example 3: Input:n = 9, m = 1, k = 1Output:1Explanation:The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfArrays(int n, int m, int k) {\n int M = (int)1e9+7, ans = 0;\n int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side\n for (int i = 1; i <= m; i++){\n dp[i][1]=1; // base case \n }\n for (int i = 2; i <= n; i++){\n int[][] next = new int[m+1][k+1];\n for (int j = 1; j <= m; j++){ // for the current max value\n for (int p = 1; p <= m; p++){ // previous max value\n for (int w = 1; w <= k; w++){ // for all possible k\n if (j>p){ // if current max is larger, update next[j][w] from dp[p][w-1]\n next[j][w]+=dp[p][w-1];\n next[j][w]%=M;\n }else{ // otherwise, update next[p][w] from dp[p][w]\n next[p][w]+=dp[p][w];\n next[p][w]%=M;\n }\n }\n }\n }\n dp=next;\n }\n for (int i = 1; i <= m; i++){ // loop through max that has k and sum them up.\n ans += dp[i][k];\n ans %= M;\n }\n return ans;\n }\n}\n", + "title": "1420. Build Array Where You Can Find The Maximum Exactly K Comparisons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given three integers n , m and k . Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr has exactly n integers.", + "1 <= arr[i] <= m where (0 <= i < n) .", + "After applying the mentioned algorithm to arr , the value search_cost is equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3, k = 1Output:6Explanation:The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 2, k = 3Output:0Explanation:There are no possible arrays that satisify the mentioned conditions.", + "image": null + }, + { + "text": "Example 3: Input:n = 9, m = 1, k = 1Output:1Explanation:The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfArrays(self, n: int, m: int, k: int) -> int:\n @cache\n def dp(a,b,c):\n if a==n: return c==k\n return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1))\n return dp(0,0,0)%(10**9+7)\n", + "title": "1420. Build Array Where You Can Find The Maximum Exactly K Comparisons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: Given an integer n , return the minimum possible number of boxes touching the floor. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/04/3-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/4-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/10-boxes.png" + ], + "constraints": [ + "You can place the boxes anywhere on the floor.", + "If box x is placed on top of the box y , then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3Explanation:The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:3Explanation:The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 3: Input:n = 10Output:6Explanation:The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n static final double ONE_THIRD = 1.0d / 3.0d;\n\n public int minimumBoxes(int n) {\n int k = findLargestTetrahedralNotGreaterThan(n);\n int used = tetrahedral(k);\n int floor = triangular(k);\n int unused = (n - used);\n if (unused == 0) {\n return floor;\n }\n int r = findSmallestTriangularNotLessThan(unused);\n return (floor + r);\n }\n\n private final int findLargestTetrahedralNotGreaterThan(int te) {\n int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD));\n while (tetrahedral(a) > te) {\n a--;\n }\n return a;\n }\n\n private final int findSmallestTriangularNotLessThan(int t) {\n int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2)));\n while (triangular(a) < t) {\n a++;\n }\n return a;\n }\n\n private final int tetrahedral(int a) {\n return (int) ratio(product(a, a + 1, a + 2), 6);\n }\n\n private final int triangular(int a) {\n return (int) ratio(product(a, a + 1), 2);\n }\n\n private final long product(long... vals) {\n long product = 1L;\n for (long val : vals) {\n product *= val;\n }\n return product;\n }\n\n private final long ratio(long a, long b) {\n return (a / b);\n }\n\n}\n", + "title": "1739. Building Boxes", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: Given an integer n , return the minimum possible number of boxes touching the floor. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/04/3-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/4-boxes.png", + "https://assets.leetcode.com/uploads/2021/01/04/10-boxes.png" + ], + "constraints": [ + "You can place the boxes anywhere on the floor.", + "If box x is placed on top of the box y , then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3Explanation:The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:3Explanation:The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.", + "image": null + }, + { + "text": "Example 3: Input:n = 10Output:6Explanation:The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 24.24%) | Memory: 13.9 MB (Top 54.55%)\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n r = 0\n while (n_upper := r*(r+1)*(r+2)//6) < n:\n r += 1\n m = r*(r+1)//2\n for i in range(r, 0, -1):\n if (n_upper - i) < n:\n break\n n_upper -= i\n m -= 1\n return m", + "title": "1739. Building Boxes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i th round, you toggle every i bulb. For the n th round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:1Explanation:At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg" + }, + { + "text": "Example 2: Input:n = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.20 MB (Top 33.55%)\n\nclass Solution {\n public int bulbSwitch(int n) {\n return (int)Math.sqrt(n);\n }\n}\n", + "title": "319. Bulb Switcher", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i th round, you toggle every i bulb. For the n th round, you only toggle the last bulb. Return the number of bulbs that are on after n rounds . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:1Explanation:At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg" + }, + { + "text": "Example 2: Input:n = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n return int(sqrt(n))\n", + "title": "319. Bulb Switcher", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses , return the number of different possible statuses after performing all presses button presses . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Button 1: Flips the status of all the bulbs.", + "Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ... ).", + "Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ... ).", + "Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ... )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, presses = 1Output:2Explanation:Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2", + "image": null + }, + { + "text": "Example 2: Input:n = 2, presses = 1Output:3Explanation:Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3", + "image": null + }, + { + "text": "Example 3: Input:n = 3, presses = 1Output:4Explanation:Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int flipLights(int n, int presses) {\n //1, 2 -> 3\n //1, 3 -> 2\n //2, 3 -> 1\n //all on, all off, even on, odd on, 3k+1 on, 3k+0+2 on, 3k+1 w/ 2, 3k+1 w/ 3\n if (n == 2 && presses == 1) return 3;\n if (presses == 1) return Math.min(1 << Math.min(4, n), 4); //i chose 4 arbitarily, just has to be big enough to cover small number and less than 31\n if (presses == 2) return Math.min(1 << Math.min(4, n), 7);\n if (presses >= 3) return Math.min(1 << Math.min(4, n), 8);\n return 1;\n }\n}\n", + "title": "672. Bulb Switcher II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses , return the number of different possible statuses after performing all presses button presses . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Button 1: Flips the status of all the bulbs.", + "Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ... ).", + "Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ... ).", + "Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ... )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, presses = 1Output:2Explanation:Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2", + "image": null + }, + { + "text": "Example 2: Input:n = 2, presses = 1Output:3Explanation:Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3", + "image": null + }, + { + "text": "Example 3: Input:n = 3, presses = 1Output:4Explanation:Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 30 ms (Top 97.1%) | Memory: 16.43 MB (Top 14.4%)\n\nclass Solution:\n def flipLights(self, n: int, m: int) -> int:\n # Reduce n to at most 3, since any action performed more than 3 times\n # will result in a pattern that has already been counted\n n = min(n, 3)\n if m == 0:\n return 1\n elif m == 1:\n # For m=1, there are only 2 outcomes for n=1, 3 outcomes for n=2, and 4 outcomes for n=3\n return [2, 3, 4][n - 1]\n elif m == 2:\n # For m=2, there are only 2 outcomes for n=1, 4 outcomes for n=2, and 7 outcomes for n=3\n return [2, 4, 7][n - 1]\n else:\n # For m>=3, there are only 2 outcomes for n=1, 4 outcomes for n=2, and 8 outcomes for n=3\n return [2, 4, 8][n - 1]\n", + "title": "672. Bulb Switcher II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: Given the secret number secret and your friend's guess guess , return the hint for your friend's guess . The hint should be formatted as \"xAyB\" , where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of \"bulls\", which are digits in the guess that are in the correct position.", + "The number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"1807\", guess = \"7810\"Output:\"1A3B\"Explanation:Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"", + "image": null + }, + { + "text": "Example 2: Input:secret = \"1123\", guess = \"0111\"Output:\"1A1B\"Explanation:Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.58%) | Memory: 41.90 MB (Top 54.72%)\n\nclass Solution {\n public String getHint(String secret, String guess) {\n int bulls = 0, cows = 0;\n\n int[] secretFreq = new int[10],\n guessFreq = new int[10];\n\n for (int i = 0; i < secret.length(); i++) {\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n\n if (s == g) bulls++;\n else {\n secretFreq[s - '0']++;\n guessFreq[g - '0']++;\n }\n }\n\n for (int i = 0; i < 10; i++) {\n cows += Math.min(secretFreq[i], guessFreq[i]);\n }\n\n return bulls + \"A\" + cows + \"B\";\n }\n}\n\n// TC: O(n), SC: O(1)\n", + "title": "299. Bulls and Cows", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: Given the secret number secret and your friend's guess guess , return the hint for your friend's guess . The hint should be formatted as \"xAyB\" , where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of \"bulls\", which are digits in the guess that are in the correct position.", + "The number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"1807\", guess = \"7810\"Output:\"1A3B\"Explanation:Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"", + "image": null + }, + { + "text": "Example 2: Input:secret = \"1123\", guess = \"0111\"Output:\"1A1B\"Explanation:Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n # Setup counts for bulls and cows\n bulls = cows = 0\n \n # Copy secret and guess into lists that are easier to work with\n secretCopy = list(secret)\n guessCopy = list(guess)\n \n # In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls\n for i in range(len(secret)):\n \n # If they match, bulls += 1 and pop() the letters from the copy lists via their .index()\n if secret[i] == guess[i]:\n bulls += 1\n secretCopy.pop(secretCopy.index(secret[i]))\n guessCopy.pop(guessCopy.index(guess[i]))\n \n \n # Count() the letters remaining in secret and guess lists\n secretCounter = Counter(secretCopy)\n guessCounter = Counter(guessCopy)\n \n # Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed\n # secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters\n # Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters\n dif = secretCounter - (secretCounter - guessCounter)\n \n # The .total() of the dif Counter is the number of cows\n cows = dif.total()\n\n # return the formatted string with req. info\n return f'{bulls}A{cows}B'\n", + "title": "299. Bulls and Cows", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,5,8]Output:167Explanation:nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5]Output:10", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxCoins(int[] nums) {\n int n = nums.length;\n \n// adding 1 to the front and back\n int[] temp = new int[n + 2]; \n temp[0] = 1;\n for(int i = 1; i < temp.length - 1; i++){\n temp[i] = nums[i-1];\n }\n temp[temp.length - 1] = 1;\n nums = temp;\n \n// memoization\n int[][] dp = new int[n+1][n+1];\n for(int[] row : dp){\n Arrays.fill(row, -1);\n }\n \n// result\n return f(1, n, nums, dp);\n }\n \n int f(int i, int j, int[] a, int[][] dp){\n if(i > j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n \n int max = Integer.MIN_VALUE;\n for(int n = i; n <= j; n++){\n int coins = a[i-1] * a[n] * a[j+1] + f(i, n-1, a, dp) + f(n+1, j, a, dp);\n max = Math.max(max, coins);\n }\n return dp[i][j] = max;\n }\n}\n\n// Time Complexity: O(N * N * N) ~ O(N^3);\n// Space Complexity: O(N^2) + O(N);", + "title": "312. Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,5,8]Output:167Explanation:nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5]Output:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3739 ms (Top 77.47%) | Memory: 34.10 MB (Top 46.9%)\n\nclass Solution:\n def maxCoins(self, nums):\n A = [1] + nums + [1]\n \n @lru_cache(None)\n def dfs(i, j):\n return max([A[i]*A[k]*A[j] + dfs(i,k) + dfs(k,j) for k in range(i+1, j)] or [0])\n \n return dfs(0, len(A) - 1)\n", + "title": "312. Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the i th bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target . You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target . Return -1 if it is not possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if routes[0] = [1, 5, 7] , this means that the 0 th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever." + ], + "examples": [ + { + "text": "Example 1: Input:routes = [[1,2,7],[3,6,7]], source = 1, target = 6Output:2Explanation:The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.", + "image": null + }, + { + "text": "Example 2: Input:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 990 ms (Top 43.31%) | Memory: 53.60 MB (Top 12.36%)\n\nclass Solution:\n from collections import defaultdict, deque\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # Base case\n if source == target:\n return 0\n # Creating graph or routes\n graph = defaultdict(set)\n \n # Since index represents bus_number on a route\n # suppose i is bus number and stops are the values present at that index\n for bus_number, stops in enumerate(routes):\n # for each stop adding buses going to that stop\n for stop in stops:\n graph[stop].add(bus_number)\n \n # Using bfs\n bfs = deque([(source, 0)])\n \n # visited stops \n seen_stops = set()\n # visited buses\n seen_buses = set()\n \n while bfs:\n stop, count = bfs.popleft()\n # Resulting case\n if stop == target:\n return count\n \n # Since our graph stores all buses going to a stop\n # We will iterate for every bus\n for bus_number in graph[stop]:\n # We dont want to travel in same bus as we might stuck into loop and reach nowhere\n if bus_number not in seen_buses:\n seen_buses.add(bus_number)\n \n # Now we are in a bus, so we will travel all the stops that bus goes to but again, we only want to go to stops we haven't visited\n for stop in routes[bus_number]:\n if stop not in seen_stops:\n seen_stops.add(stop)\n bfs.append((stop, count + 1))\n return -1\n", + "title": "815. Bus Routes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upper i , percent i ] means that the i th tax bracket has an upper bound of upper i and is taxed at a rate of percent i . The brackets are sorted by upper bound (i.e. upper i-1 < upper i for 0 < i < brackets.length ). Tax is calculated as follows: You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The first upper 0 dollars earned are taxed at a rate of percent 0 .", + "The next upper 1 - upper 0 dollars earned are taxed at a rate of percent 1 .", + "The next upper 2 - upper 1 dollars earned are taxed at a rate of percent 2 .", + "And so on." + ], + "examples": [ + { + "text": "Example 1: Input:brackets = [[3,50],[7,10],[12,25]], income = 10Output:2.65000Explanation:Based on your income, you have 3 dollars in the 1sttax bracket, 4 dollars in the 2ndtax bracket, and 3 dollars in the 3rdtax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.", + "image": null + }, + { + "text": "Example 2: Input:brackets = [[1,0],[4,25],[5,50]], income = 2Output:0.25000Explanation:Based on your income, you have 1 dollar in the 1sttax bracket and 1 dollar in the 2ndtax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.", + "image": null + }, + { + "text": "Example 3: Input:brackets = [[2,50]], income = 0Output:0.00000Explanation:You have no income to tax, so you have to pay a total of $0 in taxes.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 45.10 MB (Top 7.1%)\n\nclass Solution {\n public double calculateTax(int[][] brackets, int income) {\n int prevIncome = 0;\n double res = 0;\n for(int i =0; i income){\n res += (income*brackets[i][1]/100.0);\n income = 0;\n }else{\n res += (diff*brackets[i][1])/100;\n income -= diff;\n }\n prevIncome = brackets[i][0];\n if(income == 0) return res;\n //System.out.println(prevIncome+\" \"+res+ \" \"+ income +\" \"+ diff + \" \"+(diff*brackets[i][1]/100));\n }\n return res;\n }\n}\n", + "title": "2303. Calculate Amount Paid in Taxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upper i , percent i ] means that the i th tax bracket has an upper bound of upper i and is taxed at a rate of percent i . The brackets are sorted by upper bound (i.e. upper i-1 < upper i for 0 < i < brackets.length ). Tax is calculated as follows: You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The first upper 0 dollars earned are taxed at a rate of percent 0 .", + "The next upper 1 - upper 0 dollars earned are taxed at a rate of percent 1 .", + "The next upper 2 - upper 1 dollars earned are taxed at a rate of percent 2 .", + "And so on." + ], + "examples": [ + { + "text": "Example 1: Input:brackets = [[3,50],[7,10],[12,25]], income = 10Output:2.65000Explanation:Based on your income, you have 3 dollars in the 1sttax bracket, 4 dollars in the 2ndtax bracket, and 3 dollars in the 3rdtax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.", + "image": null + }, + { + "text": "Example 2: Input:brackets = [[1,0],[4,25],[5,50]], income = 2Output:0.25000Explanation:Based on your income, you have 1 dollar in the 1sttax bracket and 1 dollar in the 2ndtax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.", + "image": null + }, + { + "text": "Example 3: Input:brackets = [[2,50]], income = 0Output:0.00000Explanation:You have no income to tax, so you have to pay a total of $0 in taxes.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 95.72%) | Memory: 13.9 MB (Top 34.37%)\n\nclass Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n taxtot=0\n if(brackets[0][0]0 and i(brackets[i][0]-brackets[i-1][0])):\n taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]\n income-=brackets[i][0]-brackets[i-1][0]\n else:\n taxtot+=income*brackets[i][1]\n income=0\n i+=1\n return taxtot/100", + "title": "2303. Calculate Amount Paid in Taxes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of digits and an integer k . A round can be completed if the length of s is greater than k . In one round, do the following: Return s after all rounds have been completed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "2 <= k <= 100", + "s consists of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11111222223\", k = 3Output:\"135\"Explanation:- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00000000\", k = 3Output:\"000\"Explanation:We divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 32.40%) | Memory: 40.8 MB (Top 89.31%)\nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k) s = gen(s,k);\n return s;\n }\n public String gen(String s,int k){\n String res = \"\";\n for(int i=0;i < s.length();){\n int count = 0,num=0;\n while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++));\n res+=num;\n }\n return res;\n }\n}", + "title": "2243. Calculate Digit Sum of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting of digits and an integer k . A round can be completed if the length of s is greater than k . In one round, do the following: Return s after all rounds have been completed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "2 <= k <= 100", + "s consists of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11111222223\", k = 3Output:\"135\"Explanation:- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00000000\", k = 3Output:\"000\"Explanation:We divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = ''\n for e in set_3:\n val = 0\n for n in e:\n val += int(n)\n s += str(val)\n return s\n", + "title": "2243. Calculate Digit Sum of a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Hercy wants to save money for his first car. He puts money in the Leetcode bank every day . He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday . Given n , return the total amount of money he will have in the Leetcode bank at the end of the n th day. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:10Explanation:After the 4thday, the total is 1 + 2 + 3 + 4 = 10.", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:37Explanation:After the 10thday, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2ndMonday, Hercy only puts in $2.", + "image": null + }, + { + "text": "Example 3: Input:n = 20Output:96Explanation:After the 20thday, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.1 MB (Top 94.89%)\nclass Solution {\n public int totalMoney(int n) {\n int m=n/7; //(no.of full weeks)\n // first week 1 2 3 4 5 6 7 (sum is 28 i.e. 7*(i+3) if i=1)\n // second week 2 3 4 5 6 7 8 (sum is 35 i.e. 7*(i+3) if i=2)\n //.... so on\n int res=0; //for result\n //calculating full weeks\n for(int i=1;i<=m;i++){\n res+=7*(i+3);\n }\n //calculating left days\n for(int i=7*m;i int:\n return sum(starmap(add,zip(\n starmap(floordiv, zip(range(n), repeat(7, n))),\n cycle((1,2,3,4,5,6,7))\n )))\n\n", + "title": "1716. Calculate Money in Leetcode Bank", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings queries and a string pattern , return a boolean array answer where answer[i] is true if queries[i] matches pattern , and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pattern.length, queries.length <= 100", + "1 <= queries[i].length <= 100", + "queries[i] and pattern consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"Output:[true,false,true,true,false]Explanation:\"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"Output:[true,false,true,false,false]Explanation:\"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".", + "image": null + }, + { + "text": "Example 3: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"Output:[false,true,false,false,false]Explanation:\"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 33.0%) | Memory: 40.70 MB (Top 50.3%)\n\nclass Solution {\n public List camelMatch(String[] queries, String pattern) {\n List list = new ArrayList<>();\n\n for (var q : queries) {\n int index = 0;\n boolean flag = true;\n for (var c : q.toCharArray()) {\n if(index < pattern.length() && c == pattern.charAt(index)){\n index++;\n continue;\n }\n if(c >= 'A' && c <= 'Z'){\n if(index >= pattern.length() || c != pattern.charAt(index)){\n flag = false;\n break;\n }\n }\n }\n flag = flag && index == pattern.length();\n list.add(flag);\n }\n return list;\n }\n}", + "title": "1023. Camelcase Matching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings queries and a string pattern , return a boolean array answer where answer[i] is true if queries[i] matches pattern , and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pattern.length, queries.length <= 100", + "1 <= queries[i].length <= 100", + "queries[i] and pattern consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"Output:[true,false,true,true,false]Explanation:\"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"Output:[true,false,true,false,false]Explanation:\"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".", + "image": null + }, + { + "text": "Example 3: Input:queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"Output:[false,true,false,false,false]Explanation:\"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n res, N = [], len(pattern)\n\t\t\n for query in queries:\n\t\t\n if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N:\n res.append(False)\n \n else:\n res.append(True)\n\t\t\t\t\n return res\n \n \n\t\t\n def LCS(self, A, B):\n N, M = len(A), len(B)\n d = [[0 for _ in range(M+1)] for _ in range(N+1)]\n\n for i in range(1, N+1):\n for j in range(1, M+1):\n\t\t\t\n if A[i - 1] == B[j - 1]:\n d[i][j] = 1 + d[i-1][j-1]\n\n else:\n d[i][j] = max(d[i-1][j], d[i][j-1])\n return d[-1][-1]\n\n\n \n def upLetter(self, w):\n count = 0\n for c in w:\n if c.isupper():\n count += 1\n return count\n\n", + "title": "1023. Camelcase Matching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , your goal is to convert s into t in k moves or less. During the i th ( 1 <= i <= k ) move you can: Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a' ). Shifting a character by i means applying the shift operations i times. Remember that any index j can be picked at most once. Return true if it's possible to convert s into t in no more than k moves, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose any index j (1-indexed) from s , such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.", + "Do nothing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"input\", t = \"ouput\", k = 9Output:trueExplanation:In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\", t = \"bcd\", k = 10Output:falseExplanation:We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\", t = \"bbb\", k = 27Output:trueExplanation:In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 58.97%) | Memory: 54.5 MB (Top 69.23%)\nclass Solution {\n public boolean canConvertString(String s, String t, int k) {\n //if strings lengths not equal return false\n if(s.length()!=t.length())return false;\n //array to count number of times a difference can repeat\n int b[]=new int[26];\n int h=k/26;\n int h1=k%26;\n //count of each number from 1 to 26 from 1 to k\n for(int i=0;i<26;i++){\n b[i]+=h;\n if(i<=h1)b[i]++;\n }\n\n int i=0;\n while(i bool:\n if len(s) != len(t):\n return False\n\n cycles, extra = divmod(k, 26)\n shifts = [cycles + (shift <= extra) for shift in range(26)]\n\n for cs, ct in zip(s, t):\n shift = (ord(ct) - ord(cs)) % 26\n if shift == 0:\n continue\n if not shifts[shift]:\n return False\n shifts[shift] -= 1\n\n return True", + "title": "1540. Can Convert String in K Moves", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the \"100 game\" two players take turns adding, to a running total, any integer from 1 to 10 . The player who first causes the running total to reach or exceed 100 wins. What if we change the game so that players cannot re-use integers? For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100. Given two integers maxChoosableInteger and desiredTotal , return true if the first player to move can force a win, otherwise, return false . Assume both players play optimally . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= maxChoosableInteger <= 20", + "0 <= desiredTotal <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:maxChoosableInteger = 10, desiredTotal = 11Output:falseExplanation:No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.", + "image": null + }, + { + "text": "Example 2: Input:maxChoosableInteger = 10, desiredTotal = 0Output:true", + "image": null + }, + { + "text": "Example 3: Input:maxChoosableInteger = 10, desiredTotal = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int numlimit, tgt;\n public boolean canIWin(int maxChoosableInteger, int desiredTotal) {\n numlimit = maxChoosableInteger;\n tgt = desiredTotal;\n \n int maxsum = (numlimit*(numlimit+1))/2;\n if(maxsum < tgt)\n return false;\n \n int dp[] = new int[(1<= tgt) || !solve((mask|(1<= 100. Given two integers maxChoosableInteger and desiredTotal , return true if the first player to move can force a win, otherwise, return false . Assume both players play optimally . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= maxChoosableInteger <= 20", + "0 <= desiredTotal <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:maxChoosableInteger = 10, desiredTotal = 11Output:falseExplanation:No matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.", + "image": null + }, + { + "text": "Example 2: Input:maxChoosableInteger = 10, desiredTotal = 0Output:true", + "image": null + }, + { + "text": "Example 3: Input:maxChoosableInteger = 10, desiredTotal = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n remainder = [i+1 for i in range(maxChoosableInteger)] # numbers\n @cache\n def can_win(total, remainder):\n if total >= desiredTotal:\n return False # total is already exceed the desiredTotal. Opponent won. \n \n for num in remainder:\n if can_win(total + num, tuple([n for n in remainder if n != num])) == False: # if opponent lose, I win(return True)\n return True\n return False \n \n if desiredTotal == 0: \n return True \n if sum(remainder) < desiredTotal: # Both of two cannot win.\n return False \n return can_win(0, tuple(remainder))\n", + "title": "464. Can I Win", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. Given an array of numbers arr , return true if the array can be rearranged to form an arithmetic progression . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 1000", + "-10^6 <= arr[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1]Output:trueExplanation:We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,4]Output:falseExplanation:There is no way to reorder the elements to obtain an arithmetic progression.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 91.15%) | Memory: 43.1 MB (Top 10.07%)\nclass Solution {\n public boolean canMakeArithmeticProgression(int[] arr) {\n if(arr.length < 1)\n return false;\n Arrays.sort(arr);\n int diff = arr[1]-arr[0];\n for(int i=1;i bool:\n arr.sort()\n check = arr[0] - arr[1]\n for i in range(len(arr)-1):\n if arr[i] - arr[i+1] != check:\n return False\n return True\n", + "title": "1502. Can Make Arithmetic Progression From Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and array queries where queries[i] = [left i , right i , k i ] . We may rearrange the substring s[left i ...right i ] for each query and then choose up to k i of them to replace with any lowercase English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is true . Otherwise, the result is false . Return a boolean array answer where answer[i] is the result of the i th query queries[i] . Note that each letter is counted individually for replacement, so if, for example s[left i ...right i ] = \"aaa\" , and k i = 2 , we can only replace two of the letters. Also, note that no query modifies the initial string s . Example : Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, queries.length <= 10^5", + "0 <= left i <= right i < s.length", + "0 <= k i <= s.length", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example : Input:s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]Output:[true,false,false,true,true]Explanation:queries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"lyb\", queries = [[0,1,0],[2,2,1]]Output:[false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 84.38%) | Memory: 106.10 MB (Top 54.69%)\n\nclass Solution \n{ public List canMakePaliQueries(String s, int[][] queries) \n {\n List list = new ArrayList<>();\n \n int n = s.length();\n // prefix map to count number of time each letters have occured to access in queries in O(1)\n //s= a b c d a\n // a 1 1 1 1 2\n // b 0 1 1 1 1\n // c 0 0 1 1 1\n // d 0 0 0 1 1\n // e\n // f\n // .\n // .\n // .\n int[][] map = new int[n+1][26];\n for(int i=0;i List[bool]:\n hash_map = {s[0]: 1}\n x = hash_map\n prefix = [hash_map]\n for i in range(1, len(s)):\n x = x.copy()\n x[s[i]] = x.get(s[i], 0) + 1\n prefix.append(x)\n \n result = []\n for query in queries:\n cnt = 0\n for key, value in prefix[query[1]].items():\n if query[0] > 0:\n x = value - prefix[query[0]-1].get(key, 0)\n else:\n x = value\n if x % 2:\n cnt+=1\n if cnt - 2 * query[2] > 1:\n result.append(False)\n else:\n result.append(True)\n return result\n", + "title": "1177. Can Make Palindrome from Substring", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1Output:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPlaceFlowers(int[] flowerbed, int n) {\n if(flowerbed[0] != 1){\n n--;\n flowerbed[0] = 1; \n }\n for(int i = 1; i < flowerbed.length; i++){\n if(flowerbed[i - 1] == 1 && flowerbed[i] == 1){\n flowerbed[i - 1] = 0;\n n++;\n }\n if(flowerbed[i - 1] != 1 && flowerbed[i] != 1){\n flowerbed[i] = 1;\n n--;\n }\n }\n return (n <= 0) ? true: false;\n }\n}\n", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1Output:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:\n f = [0] + flowerbed + [0]\n\n i, could_plant = 1, 0\n while could_plant < n and i < len(f) - 1:\n if f[i + 1]:\n # 0 0 1 -> skip 3\n i += 3\n elif f[i]:\n # 0 1 0 -> skip 2\n i += 2\n elif f[i - 1]:\n # 1 0 0 -> skip 1\n i += 1\n else:\n # 0 0 0 -> plant, becomes 0 1 0 -> skip 2\n could_plant += 1\n i += 2\n\n return n <= could_plant\n", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings . You are giving candies to these children subjected to the following requirements: Return the minimum number of candies you need to have to distribute the candies to the children . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each child must have at least one candy.", + "Children with a higher rating get more candies than their neighbors." + ], + "examples": [ + { + "text": "Example 1: Input:ratings = [1,0,2]Output:5Explanation:You can allocate to the first, second and third child with 2, 1, 2 candies respectively.", + "image": null + }, + { + "text": "Example 2: Input:ratings = [1,2,2]Output:4Explanation:You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 14.09%) | Memory: 53.1 MB (Top 8.48%)\nclass Solution {\n public int candy(int[] ratings) {\n\n int[] left = new int[ratings.length];\n Arrays.fill(left, 1);\n\n // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy\n for(int i = 0; i=0; i--){\n if(ratings[i+1] < ratings[i] && right[i] <= right[i+1])\n right[i] = right[i+1]+1;\n }\n int sum = 0;\n for(int i = 0; i int:\n n=len(ratings)\n temp = [1]*n\n\n for i in range(1,n):\n if(ratings[i]>ratings[i-1]):\n temp[i]=temp[i-1]+1\n if(n>1):\n if(ratings[0]>ratings[1]):\n temp[0]=2\n\n for i in range(n-2,-1,-1):\n if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):\n temp[i]=temp[i+1]+1\n\n return sum(temp)", + "title": "135. Candy", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The i th package on the conveyor belt has a weight of weights[i] . Each day, we load the ship with packages on the conveyor belt (in the order given by weights ). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= days <= weights.length <= 5 * 10^4", + "1 <= weights[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:weights = [1,2,3,4,5,6,7,8,9,10], days = 5Output:15Explanation:A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.", + "image": null + }, + { + "text": "Example 2: Input:weights = [3,2,2,4,1,4], days = 3Output:6Explanation:A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4", + "image": null + }, + { + "text": "Example 3: Input:weights = [1,2,3,1,1], days = 4Output:3Explanation:1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shipWithinDays(int[] weights, int days) {\n int left = 0;\n int right = 0;\n // left is the biggest element in the array. It's set as the lower boundary.\n // right is the sum of the array, which is the upper limit. \n for (int weight : weights) {\n left = Math.max(weight, left);\n right += weight;\n }\n int res = 0;\n while (left <= right) {\n int mid = (left + right) / 2;\n // make sure mid is a possible value \n if (isPossible(weights, days, mid)) {\n res = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n return res;\n }\n \n public boolean isPossible(int [] weights, int days, int mid) {\n int totalDays = 1;\n int totalWeight = 0;\n for (int i = 0; i < weights.length; i++) {\n totalWeight += weights[i];\n // increase totalDays if totalWeight is larger than mid\n if (totalWeight > mid) {\n totalDays++;\n totalWeight = weights[i]; \n } \n // the problem states all the packages have to ship within `days` days \n if (totalDays > days) {\n return false;\n }\n }\n return true;\n }\n \n}\n", + "title": "1011. Capacity To Ship Packages Within D Days", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A conveyor belt has packages that must be shipped from one port to another within days days. The i th package on the conveyor belt has a weight of weights[i] . Each day, we load the ship with packages on the conveyor belt (in the order given by weights ). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= days <= weights.length <= 5 * 10^4", + "1 <= weights[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:weights = [1,2,3,4,5,6,7,8,9,10], days = 5Output:15Explanation:A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.", + "image": null + }, + { + "text": "Example 2: Input:weights = [3,2,2,4,1,4], days = 3Output:6Explanation:A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4", + "image": null + }, + { + "text": "Example 3: Input:weights = [1,2,3,1,1], days = 4Output:3Explanation:1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1388 ms (Top 11.51%) | Memory: 17.1 MB (Top 35.27%)\nclass Solution:\n def shipWithinDays(self, weights: List[int], days: int) -> int:\n def calc(m):#function calculate no of days for given weight\n c,s=0,0\n for i in weights:\n if i+s>m:\n c+=1\n s=0\n s+=i\n if s>0:\n c+=1\n return c\n left,right=max(weights),sum(weights)\n while left <=right:\n mid = (left+right)//2\n if calc(mid) > days:\n left = mid+1\n else :\n right = mid -1\n return left", + "title": "1011. Capacity To Ship Packages Within D Days", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the length of the word is 1 or 2 letters, change all letters to lowercase.", + "Otherwise, change the first letter to uppercase and the remaining letters to lowercase." + ], + "examples": [ + { + "text": "Example 1: Input:title = \"capiTalIze tHe titLe\"Output:\"Capitalize The Title\"Explanation:Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 2: Input:title = \"First leTTeR of EACH Word\"Output:\"First Letter of Each Word\"Explanation:The word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 3: Input:title = \"i lOve leetcode\"Output:\"i Love Leetcode\"Explanation:The word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.1%) | Memory: 41.07 MB (Top 90.8%)\n\nclass Solution {\n\tpublic String capitalizeTitle(String title) {\n\n\t\tchar[] ch = title.toCharArray();\n\t\tint len = ch.length;\n\n\t\tfor(int i = 0; i < len; ++i) {\n\n\t\t\tint firstIndex = i; // store the first index of the word\n\n\t\t\twhile(i < len && ch[i] != ' ') {\n\t\t\t\tch[i] = Character.toLowerCase(ch[i]); // converting the character at ith index to lower case ony by one\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t\n\t\t\t// if word is of length greater than 2, then turn the first character of the word to upper case\n\t\t\tif(i - firstIndex > 2) {\n\t\t\t\tch[firstIndex] = Character.toUpperCase(ch[firstIndex]); // converting the first character of the word to upper case\n\t\t\t}\n\t\t}\n\n\t\treturn String.valueOf(ch); // return the final result by converting the char array into string\n\t}\n}", + "title": "2129. Capitalize the Title", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the length of the word is 1 or 2 letters, change all letters to lowercase.", + "Otherwise, change the first letter to uppercase and the remaining letters to lowercase." + ], + "examples": [ + { + "text": "Example 1: Input:title = \"capiTalIze tHe titLe\"Output:\"Capitalize The Title\"Explanation:Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 2: Input:title = \"First leTTeR of EACH Word\"Output:\"First Letter of Each Word\"Explanation:The word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + }, + { + "text": "Example 3: Input:title = \"i lOve leetcode\"Output:\"i Love Leetcode\"Explanation:The word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def capitalizeTitle(self, title: str) -> str:\n li = title.split()\n for i,l in enumerate(li):\n if len(l) <= 2:\n li[i] = l.lower()\n else:\n li[i] = l[0].upper() + l[1:].lower()\n return ' '.join(li)", + "title": "2129. Capitalize the Title", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed , both of length n , where position[i] is the position of the i th car and speed[i] is the speed of the i th car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed . The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination . Example 1: Example 2: Example 3:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]Output:3Explanation:The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\nThe car starting at 0 does not catch up to any other car, so it is a fleet by itself.\nThe 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.\nNote that no other cars meet these fleets before the destination, so the answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 10, position = [3], speed = [3]Output:1Explanation:There is only one car, hence there is only one fleet.", + "image": null + }, + { + "text": "Example 3: Input:target = 100, position = [0,2,4], speed = [4,2,1]Output:1Explanation:The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\nThen, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 186 ms (Top 36.59%) | Memory: 87.4 MB (Top 48.79%)\nclass Solution {\n class pair implements Comparable{\n int pos;\n double time;\n pair(int pos,double time){\n this.pos=pos;\n this.time=time;\n }\n public int compareTo(pair o){\n return o.pos-this.pos;\n }\n }\n public int carFleet(int target, int[] position, int[] speed) {\n double []arr=new double[position.length];\n for(int i=0;ipq=new PriorityQueue<>();\n for(int i=0;i0){\n pair rem=pq.remove();\n if(updatetime int:\n def computeArrivalTime(curr_pos, curr_speed):\n nonlocal target\n return (target - curr_pos) / curr_speed\n # avoid integer division, as a car may arrive at 5.2s and another at 5.6s\n\n cars = list(zip(position, speed))\n cars.sort(key=lambda x: x[0], reverse=True)\n arrival_bound = None # time upper bound\n fleet = 0\n for pos, sp in cars:\n curr_arrival = computeArrivalTime(pos, sp)\n if not arrival_bound or curr_arrival > arrival_bound:\n arrival_bound = curr_arrival\n fleet += 1\n return fleet\n # time O(n logn): sort = (nlogn); loop = (n)\n # space O(n): depend on sort", + "title": "853. Car Fleet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n , where cars[i] = [position i , speed i ] represents: For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer , where answer[i] is the time, in seconds, at which the i th car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10 -5 of the actual answers are accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "position i is the distance between the i th car and the beginning of the road in meters. It is guaranteed that position i < position i+1 .", + "speed i is the initial speed of the i th car in meters per second." + ], + "examples": [ + { + "text": "Example 1: Input:cars = [[1,2],[2,1],[4,3],[7,2]]Output:[1.00000,-1.00000,3.00000,-1.00000]Explanation:After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.", + "image": null + }, + { + "text": "Example 2: Input:cars = [[3,4],[5,4],[6,3],[9,1]]Output:[2.00000,1.00000,1.50000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 65.78%) | Memory: 229.1 MB (Top 68.82%)\nclass Solution {\n public double[] getCollisionTimes(int[][] cars) {\n int n = cars.length;\n double[] res = new double[n];\n Arrays.fill(res, -1.0);\n\n // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that\n // after catching c2, we may view c1 as non-existing (cars before c1 may not catches c1);\n\n /** Define a stack storing the index of cars as follows:\n\n Assuming cars c_0, c_1, c_2, ... , c_k are in the stack, they satisfy:\n 1. v0 > v1 > v2 ... > vk where v_i is the velocity of car c_i\n 2. c_(i+1) is the car that c_i vanishes into\n\n Namely, if only these cars exist, then what will happened is that c_0 vanishes into c_1,\n then c_1 vanishes into c_2, ..., c_(k-1) vanishes into c_k;\n */\n Deque stack = new LinkedList<>();\n for (int i = n-1; i >= 0; i--) {\n int[] c1 = cars[i];\n while (!stack.isEmpty()) {\n int j = stack.peekLast();\n int[] c2 = cars[j];\n\n /** If both conditions are satisfied:\n 1. c1 is faster than c2\n 2. c1 catches c2 before c2 vanishes into other car\n\n Then we know that c2 is the car that c1 catches first (i.e., c1 vanishes into c2)\n ==> get the result for c1\n\n Note neither c1 nor c2 is polled out from the stack considering the rule of stack.\n */\n\n if (c1[1] > c2[1] && (res[j] == -1.0 || catchTime(cars, i, j) <= res[j])) {\n res[i] = catchTime(cars, i, j);\n break;\n }\n\n /** Now we have either one of situations\n 1. c1 is slower than c2\n 2. c1 potentially catches c2 AFTER c2 vanishes\n\n Claim: no car before c1 will vanish into c2\n\n 1. ==> cars before c1 will vanish into c1 first before catching c2\n 2. <==> c2 \"vanishes\" into another car even before c1 catches it\n\n Either way, c2 can not be catched by c1 or cars beofre c1 ==> poll it out from stack\n\n */\n stack.pollLast();\n }\n stack.offerLast(i);\n }\n return res;\n }\n\n // time for cars[i] to catch cars[j]\n private double catchTime(int[][] cars, int i, int j) {\n int dist = cars[j][0] - cars[i][0];\n int v = cars[i][1] - cars[j][1];\n\n return (double)dist / v;\n }\n}", + "title": "1776. Car Fleet II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n , where cars[i] = [position i , speed i ] represents: For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer , where answer[i] is the time, in seconds, at which the i th car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10 -5 of the actual answers are accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "position i is the distance between the i th car and the beginning of the road in meters. It is guaranteed that position i < position i+1 .", + "speed i is the initial speed of the i th car in meters per second." + ], + "examples": [ + { + "text": "Example 1: Input:cars = [[1,2],[2,1],[4,3],[7,2]]Output:[1.00000,-1.00000,3.00000,-1.00000]Explanation:After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.", + "image": null + }, + { + "text": "Example 2: Input:cars = [[3,4],[5,4],[6,3],[9,1]]Output:[2.00000,1.00000,1.50000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Car:\n def __init__(self, pos, speed, idx, prev=None, next=None):\n self.pos = pos\n self.speed = speed\n self.idx = idx\n self.prev = prev\n self.next = next\n\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times\n", + "title": "1776. Car Fleet II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengers i , from i , to i ] indicates that the i th trip has numPassengers i passengers and the locations to pick them up and drop them off are from i and to i respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= trips.length <= 1000", + "trips[i].length == 3", + "1 <= numPassengers i <= 100", + "0 <= from i < to i <= 1000", + "1 <= capacity <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:trips = [[2,1,5],[3,3,7]], capacity = 4Output:false", + "image": null + }, + { + "text": "Example 2: Input:trips = [[2,1,5],[3,3,7]], capacity = 5Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 30.51%) | Memory: 45.4 MB (Top 20.46%)\nclass Solution {\n public boolean carPooling(int[][] trips, int capacity) {\n Map destinationToPassengers = new TreeMap<>();\n for(int[] trip : trips) {\n int currPassengersAtPickup = destinationToPassengers.getOrDefault(trip[1], 0);\n int currPassengersAtDrop = destinationToPassengers.getOrDefault(trip[2], 0);\n destinationToPassengers.put(trip[1], currPassengersAtPickup + trip[0]);\n destinationToPassengers.put(trip[2], currPassengersAtDrop - trip[0]);\n }\n\n int currPassengers = 0;\n for(int passengers : destinationToPassengers.values()) {\n currPassengers += passengers;\n\n if(currPassengers > capacity) {\n return false;\n }\n }\n return true;\n }\n}", + "title": "1094. Car Pooling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengers i , from i , to i ] indicates that the i th trip has numPassengers i passengers and the locations to pick them up and drop them off are from i and to i respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= trips.length <= 1000", + "trips[i].length == 3", + "1 <= numPassengers i <= 100", + "0 <= from i < to i <= 1000", + "1 <= capacity <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:trips = [[2,1,5],[3,3,7]], capacity = 4Output:false", + "image": null + }, + { + "text": "Example 2: Input:trips = [[2,1,5],[3,3,7]], capacity = 5Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n endheap = []\n startheap = []\n \n for i in range(len(trips)):\n endheap.append((trips[i][2],trips[i][0],trips[i][1]))\n startheap.append((trips[i][1],trips[i][0],trips[i][2]))\n heapify(endheap)\n heapify(startheap)\n cur = 0\n while startheap:\n start,num,end = heappop(startheap)\n while start >= endheap[0][0]:\n newend,newnum,newstart = heappop(endheap)\n cur -= newnum\n cur += num\n print(cur)\n if cur >capacity:\n return False\n return True\n \n \n \n \n", + "title": "1094. Car Pooling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 0-indexed integer arrays fronts and backs of length n , where the i th card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero). After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card. Return the minimum possible good integer after flipping the cards . If there are no good integers, return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == fronts.length == backs.length", + "1 <= n <= 1000", + "1 <= fronts[i], backs[i] <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:fronts = [1,2,4,4,7], backs = [1,3,4,1,3]Output:2Explanation:If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.", + "image": null + }, + { + "text": "Example 2: Input:fronts = [1], backs = [1]Output:0Explanation:There are no good integers no matter how we flip the cards, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7624 ms (Top 5.13%) | Memory: 14.1 MB (Top 95.38%)\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n return min([v for v in fronts + backs if v not in set([i for i, j in zip(fronts, backs) if i == j])] or [0])", + "title": "822. Card Flipping Game", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0 . During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1] . Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: Given a graph , and assuming both players play optimally, return Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If ever the Cat occupies the same node as the Mouse, the Cat wins.", + "If ever the Mouse reaches the Hole, the Mouse wins.", + "If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]Output:0", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg" + }, + { + "text": "Example 2: Input:graph = [[1,3],[0],[3],[0,2]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 911 ms (Top 7.06%) | Memory: 70.7 MB (Top 63.53%)\nclass Solution {\n int TIME_MAX = 200;\n int DRAW = 0;\n int MOUSE_WIN = 1;\n int CAT_WIN = 2;\n public int catMouseGame(int[][] graph) {\n return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]);\n }\n\n private int dfs(int time, int[] p, int[][] graph, Integer[][][] memo){ // p[0] -> mouse position, p[1] -> cat position\n Integer old = memo[time][p[0]][p[1]];\n if (old != null) return old; // all the base cases here\n if (time >= TIME_MAX) return DRAW;\n if (p[0]==0) return MOUSE_WIN;\n if (p[0]==p[1]) return CAT_WIN;\n int state = 0;\n int where = p[time&1];\n int res = DRAW;\n for (int i = 0; i < graph[where].length; i++){\n if ((time&1)==0||graph[where][i]>0){ // if mouse turn or cat turn and the dest is not 0, do ...\n p[time&1]=graph[where][i];\n state |= 1 << dfs(time+1, p, graph, memo);\n if ((time&1)>0&&(state&4)>0 || (time&1)==0&&(state&2)>0) // if mouse's turn & mouse win\n break; // or cat's turn & cat win, then we stop.\n }\n }\n p[time&1]=where; // restore p\n if (((time&1)>0 && (state & 4)>0)||((time&1)==0) && state==4){\n res = CAT_WIN; // cat win when (cat's turn & cat win) or (mouse's turn and state = cat)\n }else if (((time&1)==0 && (state & 2)>0)||(time&1)==1 && state==2){\n res = MOUSE_WIN; // mouse win when (mouse's turn and mouse win) or (cat's turn and state = mouse)\n }\n return memo[time][p[0]][p[1]]=res;\n }\n}", + "title": "913. Cat and Mouse", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0 . During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1] . Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: Given a graph , and assuming both players play optimally, return Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If ever the Cat occupies the same node as the Mouse, the Cat wins.", + "If ever the Mouse reaches the Hole, the Mouse wins.", + "If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]Output:0", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg" + }, + { + "text": "Example 2: Input:graph = [[1,3],[0],[3],[0,2]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n \n", + "title": "913. Cat and Mouse", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols , where each element is a wall, floor, player (Cat, Mouse), or food. Mouse and Cat play according to the following rules: The game can end in 4 ways: Given a rows x cols matrix grid and two integers catJump and mouseJump , return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players are represented by the characters 'C' (Cat) ,'M' (Mouse).", + "Floors are represented by the character '.' and can be walked on.", + "Walls are represented by the character '#' and cannot be walked on.", + "Food is represented by the character 'F' and can be walked on.", + "There is only one of each character 'C' , 'M' , and 'F' in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2Output:trueExplanation:Cat cannot catch Mouse on its turn nor can it get the food before Mouse.", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png" + }, + { + "text": "Example 2: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 4Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png" + }, + { + "text": "Example 3: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] dx = new int[]{0, 0, 1 ,-1};\n int[] dy = new int[]{-1, 1, 0, 0};\n int m;\n int n;\n int TIME_MAX = 100;\n public boolean canMouseWin(String[] grid, int catJump, int mouseJump) {\n m = grid.length;\n n = grid[0].length();\n int mouseI = 0, mouseJ = 0;\n int catI = 0, catJ = 0;\n for (int i = 0; i < m; i++){\n for (int j = 0; j < n; j++){\n switch(grid[i].charAt(j)){\n case 'M' -> {mouseI = i; mouseJ = j;}\n case 'C' -> {catI = i; catJ = j;}\n }\n }\n }\n return dfs(0, mouseI, mouseJ, catI, catJ, catJump, mouseJump, grid, new Boolean[TIME_MAX+1][m][n][m][n]);\n }\n\n private boolean dfs(int time, int mI, int mJ, int cI, int cJ, int cJump, int mJump, String[] grid, Boolean[][][][][] memo){\n if (grid[mI].charAt(mJ)=='F'){ // mouse got the food -> mouse won\n return true;\n }\n if (grid[cI].charAt(cJ)=='F' || cI==mI&&cJ==mJ || time > TIME_MAX){\n return false; // cat got the food / draw / cat got the mouse -> cat won.\n }\n if (memo[time][mI][mJ][cI][cJ]!=null){\n return memo[time][mI][mJ][cI][cJ];\n }\n boolean mT = time % 2 == 0;\n int jump = mT? mJump : cJump;\n int x = mT? mI : cI;\n int y = mT? mJ : cJ;\n if (!mT&&!dfs(time+1,mI,mJ,cI,cJ,cJump,mJump,grid,memo)){\n return memo[time][mI][mJ][cI][cJ]=false; // cat's turn and cat stays still and cat won\n }\n for (int i = 0; i < 4; i++){\n for (int j = 1; j <= jump; j++){\n int nx = x + dx[i]*j;\n int ny = y + dy[i]*j;\n if (nx < 0 || ny < 0 || nx == m || ny == n || grid[nx].charAt(ny)=='#'){\n break; // note that cat & mouse can't jump over #. I got a WA thinking they can jump over it.\n }\n boolean res = dfs(time+1, mT? nx : mI, mT? ny : mJ, mT? cI : nx, mT? cJ : ny, cJump, mJump, grid, memo);\n if (mT&&res){ // if it is mouse's turn and it can find ONE way to win, then mouse win.\n return memo[time][mI][mJ][cI][cJ]=true;\n }\n if (!mT&&!res){ // if it is cat's turn and it can find ONE way to a draw or cat win, then cat win\n return memo[time][mI][mJ][cI][cJ]=false;\n }\n }\n }\n return memo[time][mI][mJ][cI][cJ]=!mT; // otherwise, return !mT\n }\n}\n", + "title": "1728. Cat and Mouse II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols , where each element is a wall, floor, player (Cat, Mouse), or food. Mouse and Cat play according to the following rules: The game can end in 4 ways: Given a rows x cols matrix grid and two integers catJump and mouseJump , return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players are represented by the characters 'C' (Cat) ,'M' (Mouse).", + "Floors are represented by the character '.' and can be walked on.", + "Walls are represented by the character '#' and cannot be walked on.", + "Food is represented by the character 'F' and can be walked on.", + "There is only one of each character 'C' , 'M' , and 'F' in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2Output:trueExplanation:Cat cannot catch Mouse on its turn nor can it get the food before Mouse.", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png" + }, + { + "text": "Example 2: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 4Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png" + }, + { + "text": "Example 3: Input:grid = [\"M.C...F\"], catJump = 1, mouseJump = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canMouseWin(self, A: List[str], cj: int, mj: int) -> bool:\n # some helper functions:\n xy2i = lambda x, y: x * n + y\n i2xy = lambda i: (i // n, i % n)\n def adj_grid(x0, y0, jump=1):\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n for step in range(jump):\n x, y = x0 + (step+1) * dx, y0 + (step+1) * dy\n if not(0<=x\" where: You are given a string s in the format \":\" , where represents the column c1 , represents the row r1 , represents the column c2 , and represents the row r2 , such that r1 <= r2 and c1 <= c2 . Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2 . The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. Example 1: Example 2:", + "description_images": [], + "constraints": [ + " denotes the column number c of the cell. It is represented by alphabetical letters . For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + "For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + " is the row number r of the cell. The r th row is represented by the integer r ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"K1:L2\"Output:[\"K1\",\"K2\",\"L1\",\"L2\"]Explanation:The above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/08/ex1drawio.png" + }, + { + "text": "Example 2: Input:s = \"A1:F1\"Output:[\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]Explanation:The above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/exam2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List cellsInRange(String s) {\n char sc = s.charAt(0), ec = s.charAt(3);\n char sr = s.charAt(1), er = s.charAt(4);\n List res = new ArrayList<>();\n \n for (char i = sc; i <= ec; ++i){\n for (char j = sr; j <= er; ++j){\n res.add(new String(new char[]{i, j}));\n }\n }\n \n return res;\n }\n}\n", + "title": "2194. Cells in a Range on an Excel Sheet", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A cell (r, c) of an excel sheet is represented as a string \"\" where: You are given a string s in the format \":\" , where represents the column c1 , represents the row r1 , represents the column c2 , and represents the row r2 , such that r1 <= r2 and c1 <= c2 . Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2 . The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. Example 1: Example 2:", + "description_images": [], + "constraints": [ + " denotes the column number c of the cell. It is represented by alphabetical letters . For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + "For example, the 1 st column is denoted by 'A' , the 2 nd by 'B' , the 3 rd by 'C' , and so on.", + " is the row number r of the cell. The r th row is represented by the integer r ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"K1:L2\"Output:[\"K1\",\"K2\",\"L1\",\"L2\"]Explanation:The above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/08/ex1drawio.png" + }, + { + "text": "Example 2: Input:s = \"A1:F1\"Output:[\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]Explanation:The above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/exam2drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 33.3%) | Memory: 16.43 MB (Top 7.2%)\n\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n start, end = s.split(':')\n start_letter, start_num = start[0], int(start[-1])\n end_letter, end_num = end[0], int(end[1])\n alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n alphabet_slice = \\\n alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1]\n res = list()\n for el in alphabet_slice:\n res += [el + str(num) for num in range(start_num, end_num + 1)]\n return res", + "title": "2194. Cells in a Range on an Excel Sheet", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n matrix that is initialized to all 0 's. There is also a 2D array indices where each indices[i] = [r i , c i ] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i] , do both of the following: Given m , n , and indices , return the number of odd-valued cells in the matrix after applying the increment to all locations in indices . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "1 <= indices.length <= 100", + "0 <= r i < m", + "0 <= c i < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, indices = [[0,1],[1,1]]Output:6Explanation:Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e1.png" + }, + { + "text": "Example 2: Input:m = 2, n = 2, indices = [[1,1],[0,0]]Output:0Explanation:Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e2.png" + } + ], + "follow_up": null, + "solution": "// --------------------- Solution 1 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[][] matrix = new int[m][n];\n \n for(int i = 0; i < indices.length; i++) {\n int row = indices[i][0];\n int col = indices[i][1];\n \n for(int j = 0; j < n; j++) {\n matrix[row][j]++;\n }\n for(int j = 0; j < m; j++) {\n matrix[j][col]++;\n }\n }\n \n int counter = 0;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if(matrix[i][j] % 2 != 0) {\n counter++;\n }\n }\n }\n \n return counter;\n }\n}\n\n// --------------------- Solution 2 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[] row = new int[m];\n int[] col = new int[n];\n \n for(int i = 0; i < indices.length; i++) {\n row[indices[i][0]]++;\n col[indices[i][1]]++;\n }\n \n int counter = 0;\n for(int i : row) {\n for(int j : col) {\n counter += (i + j) % 2 == 0 ? 0 : 1;\n }\n }\n \n return counter;\n }\n}\n", + "title": "1252. Cells with Odd Values in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an m x n matrix that is initialized to all 0 's. There is also a 2D array indices where each indices[i] = [r i , c i ] represents a 0-indexed location to perform some increment operations on the matrix. For each location indices[i] , do both of the following: Given m , n , and indices , return the number of odd-valued cells in the matrix after applying the increment to all locations in indices . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "1 <= indices.length <= 100", + "0 <= r i < m", + "0 <= c i < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, indices = [[0,1],[1,1]]Output:6Explanation:Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e1.png" + }, + { + "text": "Example 2: Input:m = 2, n = 2, indices = [[1,1],[0,0]]Output:0Explanation:Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.", + "image": "https://assets.leetcode.com/uploads/2019/10/30/e2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 40.72%) | Memory: 13.9 MB (Top 91.29%)\nclass Solution:\n def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:\n rows, cols = [False] * row, [False] * col\n\n for index in indices:\n rows[index[0]] = not rows[index[0]]\n cols[index[1]] = not cols[index[1]]\n\n count = 0\n for i in rows:\n for j in cols:\n count += i ^ j\n\n return count", + "title": "1252. Cells with Odd Values in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0 , then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0 . Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0 , then that player wins. Return true if and only if Alice wins the game, assuming both players play optimally . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] < 2 16" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]Output:falseExplanation:Alice has two choices: erase 1 or erase 2. \nIf she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean xorGame(int[] nums) {\n int x = 0;\n for(int i=0;i bool:\n return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0\n", + "title": "810. Chalkboard XOR Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100 th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the j th glass in the i th row is (both i and j are 0-indexed.) Example 1: Example 2: Example 3:", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png" + ], + "constraints": [ + "0 <= poured <= 10^9", + "0 <= query_glass <= query_row < 100" + ], + "examples": [ + { + "text": "Example 1: Input:poured = 1, query_row = 1, query_glass = 1Output:0.00000Explanation:We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.", + "image": null + }, + { + "text": "Example 2: Input:poured = 2, query_row = 1, query_glass = 1Output:0.50000Explanation:We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.", + "image": null + }, + { + "text": "Example 3: Input:poured = 100000009, query_row = 33, query_glass = 17Output:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "// Champagne Tower\n// Leetcode: https://leetcode.com/problems/champagne-tower/\n\nclass Solution {\n public double champagneTower(int poured, int query_row, int query_glass) {\n if (poured == 0) return 0;\n double[] memo = new double[101];\n memo[0] = poured;\n for (int i=0; i<100; i++) {\n for (int j=i; j>=0; j--) {\n if (memo[j] > 1) {\n if (i == query_row && j == query_glass) return 1;\n double val = (memo[j] - 1) / 2;\n memo[j+1] += val;\n memo[j] = val;\n } else {\n if (i == query_row && j == query_glass) return memo[query_glass];\n memo[j+1] += 0;\n memo[j] = 0;\n }\n }\n }\n return memo[query_glass];\n }\n}\n", + "title": "799. Champagne Tower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100 th row.  Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the j th glass in the i th row is (both i and j are 0-indexed.) Example 1: Example 2: Example 3:", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png" + ], + "constraints": [ + "0 <= poured <= 10^9", + "0 <= query_glass <= query_row < 100" + ], + "examples": [ + { + "text": "Example 1: Input:poured = 1, query_row = 1, query_glass = 1Output:0.00000Explanation:We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.", + "image": null + }, + { + "text": "Example 2: Input:poured = 2, query_row = 1, query_glass = 1Output:0.50000Explanation:We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.", + "image": null + }, + { + "text": "Example 3: Input:poured = 100000009, query_row = 33, query_glass = 17Output:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 392 ms (Top 9.30%) | Memory: 14.4 MB (Top 11.38%)\nclass Solution:\n def champagneTower(self, poured: int, r: int, c: int) -> float:\n quantity=defaultdict(int)\n quantity[(0,0)]=poured\n for i in range(r+1):\n flag=False\n for j in range(i+1):\n prev_flow=quantity[(i,j)]-1\n if prev_flow<=0:\n continue\n flag=True\n quantity[(i,j)]=1\n quantity[(i+1,j)]+=prev_flow/2\n quantity[(i+1,j+1)]+=prev_flow/2\n if not flag: break\n return quantity[(r,c)]\n", + "title": "799. Champagne Tower", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter . Your goal is to satisfy one of the following three conditions: Return the minimum number of operations needed to achieve your goal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every letter in a is strictly less than every letter in b in the alphabet.", + "Every letter in b is strictly less than every letter in a in the alphabet.", + "Both a and b consist of only one distinct letter." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"caa\"Output:2Explanation:Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).", + "image": null + }, + { + "text": "Example 2: Input:a = \"dabadd\", b = \"cda\"Output:3Explanation:The best way is to make condition 1 true by changing b to \"eee\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 27.1%) | Memory: 44.54 MB (Top 34.2%)\n\nclass Solution {\n public int minCharacters(String a, String b) {\n int[] aCount = new int[26];\n int aMax = 0;\n for (int i = 0; i < a.length(); i++) {\n aCount[a.charAt(i) - 'a']++;\n aMax = Math.max(aMax, aCount[a.charAt(i) - 'a']);\n }\n \n int[] bCount = new int[26];\n int bMax = 0;\n for (int i = 0; i < b.length(); i++) {\n bCount[b.charAt(i) - 'a']++;\n bMax = Math.max(bMax, bCount[b.charAt(i) - 'a']);\n }\n int condition3 = a.length() - aMax + b.length() - bMax;\n \n int globalMin = condition3;\n \n int aTillCurrent = 0;\n int bTillCurrent = 0;\n for (int i = 0; i < 25; i++) {\n aTillCurrent += aCount[i];\n bTillCurrent += bCount[i];\n globalMin = Math.min(globalMin, bTillCurrent + a.length() - aTillCurrent);\n globalMin = Math.min(globalMin, aTillCurrent + b.length() - bTillCurrent);\n }\n \n \n \n return globalMin;\n }\n}", + "title": "1737. Change Minimum Characters to Satisfy One of Three Conditions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter . Your goal is to satisfy one of the following three conditions: Return the minimum number of operations needed to achieve your goal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every letter in a is strictly less than every letter in b in the alphabet.", + "Every letter in b is strictly less than every letter in a in the alphabet.", + "Both a and b consist of only one distinct letter." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"caa\"Output:2Explanation:Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).", + "image": null + }, + { + "text": "Example 2: Input:a = \"dabadd\", b = \"cda\"Output:3Explanation:The best way is to make condition 1 true by changing b to \"eee\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 115 ms (Top 83.64%) | Memory: 17.50 MB (Top 38.79%)\n\nclass Solution:\n def minCharacters(self, a: str, b: str) -> int:\n pa, pb = [0]*26, [0]*26\n for x in a: pa[ord(x)-97] += 1\n for x in b: pb[ord(x)-97] += 1\n \n ans = len(a) - max(pa) + len(b) - max(pb) # condition 3\n for i in range(25): \n pa[i+1] += pa[i]\n pb[i+1] += pb[i]\n ans = min(ans, pa[i] + len(b) - pb[i]) # condition 2\n ans = min(ans, len(a) - pa[i] + pb[i]) # condition 1\n return ans \n", + "title": "1737. Change Minimum Characters to Satisfy One of Three Conditions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= 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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1Output:700Explanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png" + }, + { + "text": "Example 2: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1Output:200Explanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png" + }, + { + "text": "Example 3: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0Output:500Explanation:The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n // Initialize Prices arr with infinity & src 0\n int[] prices = new int[n];\n for(int i = 0; i < n; i++)\n prices[i] = Integer.MAX_VALUE;\n prices[src] = 0;\n \n // Build Adj list {key: src | val: dst+price}\n Map> flightsMap = new HashMap<>();\n for(int[] flight : flights){\n int flightSrc = flight[0];\n int flightDst = flight[1];\n int flightPrice = flight[2];\n \n List flightsList = flightsMap.getOrDefault(flightSrc, new ArrayList<>());\n flightsList.add(new int[]{flightDst, flightPrice});\n flightsMap.put(flightSrc, flightsList);\n }\n \n // Start Bellman ford Algo\n Queue q = new LinkedList<>();\n q.offer(src);\n while(k >= 0 && !q.isEmpty()){\n int[] tempPrices = new int[n]; // Temporary Prices Arr\n for(int i = 0; i < n; i++)\n tempPrices[i] = prices[i];\n \n int size = q.size();\n for(int i = 0; i < size; i++){\n int curSrc = q.poll();\n int curPrice = prices[curSrc];\n List curFlightsList = flightsMap.getOrDefault(curSrc, new ArrayList<>());\n for(int[] flight : curFlightsList){\n int flightDst = flight[0];\n int flightPrice = flight[1];\n int newPrice = curPrice + flightPrice;\n if(newPrice < tempPrices[flightDst]){\n tempPrices[flightDst] = newPrice;\n q.offer(flightDst);\n }\n }\n }\n for(int i = 0; i < n; i++) // Copy Temp Prices to Original Price Arr\n prices[i] = tempPrices[i];\n k--;\n }\n int totalPrice = prices[dst];\n return totalPrice == Integer.MAX_VALUE? -1 : totalPrice;\n }\n}\n", + "title": "787. Cheapest Flights Within K Stops", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= 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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1Output:700Explanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png" + }, + { + "text": "Example 2: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1Output:200Explanation:The graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png" + }, + { + "text": "Example 3: Input:n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0Output:500Explanation:The graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.", + "image": "https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n\t\tgraph = defaultdict(list)\n\t\tfor u,v,w in flights: graph[u].append((v,w))\n\n\t\tpq = [(0,src,0)]\n\t\tdis = [float('inf')]*n\n\n\t\twhile pq:\n\t\t\tc,n,l = heappop(pq)\n\t\t\tif n==dst: return c\n\t\t\tif l > k or l>= dis[n]: continue\n\t\t\tdis[n] = l\n\t\t\tfor v,w in graph[n]:\n\t\t\t\theappush(pq,(c+w,v,l+1))\n\t\treturn -1\n", + "title": "787. Cheapest Flights Within K Stops", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces , where the integers in pieces are distinct . Your goal is to form arr by concatenating the arrays in pieces in any order . However, you are not allowed to reorder the integers in each array pieces[i] . Return true if it is possible to form the array arr from pieces . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pieces.length <= arr.length <= 100", + "sum(pieces[i].length) == arr.length", + "1 <= pieces[i].length <= arr.length", + "1 <= arr[i], pieces[i][j] <= 100", + "The integers in arr are distinct .", + "The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [15,88], pieces = [[88],[15]]Output:trueExplanation:Concatenate [15] then [88]", + "image": null + }, + { + "text": "Example 2: Input:arr = [49,18,16], pieces = [[16,18,49]]Output:falseExplanation:Even though the numbers match, we cannot reorder pieces[0].", + "image": null + }, + { + "text": "Example 3: Input:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]Output:trueExplanation:Concatenate [91] then [4,64] then [78]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFormArray(int[] arr, int[][] pieces) {\n HashMap hm = new HashMap();\n for(int[] list:pieces)\n hm.put(list[0],list);\n \n int index = 0;\n while(index=arr.length || val!=arr[index])\n return false;\n index++;\n }\n }\n return true;\n }\n}\n", + "title": "1640. Check Array Formation Through Concatenation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of distinct integers arr and an array of integer arrays pieces , where the integers in pieces are distinct . Your goal is to form arr by concatenating the arrays in pieces in any order . However, you are not allowed to reorder the integers in each array pieces[i] . Return true if it is possible to form the array arr from pieces . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pieces.length <= arr.length <= 100", + "sum(pieces[i].length) == arr.length", + "1 <= pieces[i].length <= arr.length", + "1 <= arr[i], pieces[i][j] <= 100", + "The integers in arr are distinct .", + "The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [15,88], pieces = [[88],[15]]Output:trueExplanation:Concatenate [15] then [88]", + "image": null + }, + { + "text": "Example 2: Input:arr = [49,18,16], pieces = [[16,18,49]]Output:falseExplanation:Even though the numbers match, we cannot reorder pieces[0].", + "image": null + }, + { + "text": "Example 3: Input:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]Output:trueExplanation:Concatenate [91] then [4,64] then [78]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n keys, ans = {}, []\n for piece in pieces:\n keys[piece[0]] = piece\n for a in arr:\n if a in keys:\n ans.extend(keys[a])\n return ''.join(map(str, arr)) == ''.join(map(str, ans))\n", + "title": "1640. Check Array Formation Through Concatenation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a complete binary tree . In a complete binary tree , every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:trueExplanation:Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,null,7]Output:falseExplanation:The node with value 7 isn't as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 49.17%) | Memory: 42.4 MB (Top 73.50%)\nclass Solution {\n public boolean isCompleteTree(TreeNode root) {\n boolean end = false;\n Queue queue = new LinkedList<>();\n queue.offer(root);\n while(!queue.isEmpty()) {\n TreeNode currentNode = queue.poll();\n if(currentNode == null) {\n end = true;\n } else {\n if(end) {\n return false;\n }\n queue.offer(currentNode.left);\n queue.offer(currentNode.right);\n }\n }\n return true;\n }\n}", + "title": "958. Check Completeness of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, determine if it is a complete binary tree . In a complete binary tree , every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 100] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:trueExplanation:Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,null,7]Output:falseExplanation:The node with value 7 isn't as far left as possible.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n\t\t# if not root: return True\n\t\tdef node_count(root):\n\t\t\tif not root: return 0\n\t\t\treturn 1 + node_count(root.left) + node_count(root.right)\n\n\t\tdef isCBT(root,i,count):\n\t\t\tif not root: return True\n\t\t\tif i>=count: return False\n\t\t\treturn isCBT(root.left,2*i+1,count) and isCBT(root.right,2*i+2,count)\n\n\n\t\treturn isCBT(root,0,node_count(root))", + "title": "958. Check Completeness of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"Output:trueExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"Output:trueExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"Output:falseExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 30.84%) | Memory: 44.80 MB (Top 40.5%)\n\nclass Solution {\n public boolean canBeValid(String s, String locked) {\n int n = s.length();\n if (n % 2 != 0) return false;\n \n int possibleOpens = 0;\n int fixedCloses = 0;\n \n for (int i = 0; i < n; i ++) {\n if (s.charAt(i) == '(' || locked.charAt(i) == '0') {\n possibleOpens++;\n } else {\n fixedCloses++;\n }\n \n if (fixedCloses > possibleOpens) return false;\n }\n \n int possibleCloses = 0;\n int fixedOpens = 0;\n \n for (int i = n - 1; i >= 0; i--) {\n if (s.charAt(i) == ')' || locked.charAt(i) == '0') {\n possibleCloses++;\n } else {\n fixedOpens++;\n }\n \n if (fixedOpens > possibleCloses) return false;\n }\n \n return true;\n }\n}\n", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"Output:trueExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"Output:trueExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"Output:falseExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canBeValid(String s, String locked) {\n int n = s.length();\n if (n % 2 != 0) return false;\n \n int possibleOpens = 0;\n int fixedCloses = 0;\n \n for (int i = 0; i < n; i ++) {\n if (s.charAt(i) == '(' || locked.charAt(i) == '0') {\n possibleOpens++;\n } else {\n fixedCloses++;\n }\n \n if (fixedCloses > possibleOpens) return false;\n }\n \n int possibleCloses = 0;\n int fixedOpens = 0;\n \n for (int i = n - 1; i >= 0; i--) {\n if (s.charAt(i) == ')' || locked.charAt(i) == '0') {\n possibleCloses++;\n } else {\n fixedOpens++;\n }\n \n if (fixedOpens > possibleCloses) return false;\n }\n \n return true;\n }\n}\n", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given a parentheses string s and a string locked , both of length n . locked is a binary string consisting only of '0' s and '1' s. For each index i of locked , Return true if you can make s a valid parentheses string . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"))()))\", locked = \"010100\"Output:trueExplanation:locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/eg1.png" + }, + { + "text": "Example 2: Input:s = \"()()\", locked = \"0000\"Output:trueExplanation:We do not need to make any changes because s is already valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \")\", locked = \"0\"Output:falseExplanation:locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 460 ms (Top 26.24%) | Memory: 15.4 MB (Top 86.61%)\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n def validate(s: str, locked: str, op: str) -> bool:\n bal, wild = 0, 0\n for i in range(len(s)):\n if locked[i] == \"1\":\n bal += 1 if s[i] == op else -1\n else:\n wild += 1\n if wild + bal < 0:\n return False\n return bal <= wild\n return len(s) % 2 == 0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')')", + "title": "2116. Check if a Parentheses String Can Be Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n ) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "1 <= n <= 10^5", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"abc\", s2 = \"xya\"Output:trueExplanation:\"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abe\", s2 = \"acd\"Output:falseExplanation:All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"leetcodee\", s2 = \"interview\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkIfCanBreak(String s1, String s2) {\n int n = s1.length();\n char[] one = s1.toCharArray();\n char[] two = s2.toCharArray();\n Arrays.sort(one);\n Arrays.sort(two);\n if(check(one,two,n) || check(two,one,n)){\n return true;\n }\n return false;\n }\n public boolean check(char[] one,char[] two,int n){\n for(int i=0;itwo[i]-'a'){\n return false;\n }\n }\n return true;\n }\n}", + "title": "1433. Check If a String Can Break Another String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa. A string x can break string y (both of size n ) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "1 <= n <= 10^5", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"abc\", s2 = \"xya\"Output:trueExplanation:\"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abe\", s2 = \"acd\"Output:falseExplanation:All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"leetcodee\", s2 = \"interview\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n s1, s2 = sorted(s1), sorted(s2)\n return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2))\n", + "title": "1433. Check If a String Can Break Another String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s and an integer k , return true if every binary code of length k is a substring of s . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s[i] is either '0' or '1' .", + "1 <= k <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110110\", k = 2Output:trueExplanation:The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0110\", k = 1Output:trueExplanation:The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"0110\", k = 2Output:falseExplanation:The binary code \"00\" is of length 2 and does not exist in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean hasAllCodes(String s, int k) {\n HashSet hs=new HashSet();\n for(int i=0;i<=s.length()-k;i++){\n hs.add(s.substring(i,i+k));\n }\n if(hs.size() == Math.pow(2,k))return true;\n return false;\n }\n}\n", + "title": "1461. Check If a String Contains All Binary Codes of Size K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary string s and an integer k , return true if every binary code of length k is a substring of s . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s[i] is either '0' or '1' .", + "1 <= k <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110110\", k = 2Output:trueExplanation:The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0110\", k = 1Output:trueExplanation:The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"0110\", k = 2Output:falseExplanation:The binary code \"00\" is of length 2 and does not exist in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n \n Z = set()\n\n for i in range(len(s)-k+1):\n Z.add(s[i:i+k])\n \n if len(Z) == 2**k:\n return True\n\n return False", + "title": "1461. Check If a String Contains All Binary Codes of Size K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sentence that consists of some words separated by a single space , and a searchWord , check if searchWord is a prefix of any word in sentence . Return the index of the word in sentence ( 1-indexed ) where searchWord is a prefix of this word . If searchWord is a prefix of more than one word, return the index of the first word (minimum index) . If there is no such word return -1 . A prefix of a string s is any leading contiguous substring of s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 100", + "1 <= searchWord.length <= 10", + "sentence consists of lowercase English letters and spaces.", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"i love eating burger\", searchWord = \"burg\"Output:4Explanation:\"burg\" is prefix of \"burger\" which is the 4th word in the sentence.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"this problem is an easy problem\", searchWord = \"pro\"Output:2Explanation:\"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"i am tired\", searchWord = \"you\"Output:-1Explanation:\"you\" is not a prefix of any word in the sentence.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 44.68%) | Memory: 41.8 MB (Top 51.62%)\nclass Solution {\n public int isPrefixOfWord(String sentence, String searchWord) {\n if(!sentence.contains(searchWord))\n return -1;\n boolean y=false;\n String[] str=sentence.split(\" \");\n\n for(int i=0;i bool:\n pre = -k - 1\n for i, v in enumerate(nums):\n if v:\n if i - pre < k + 1:\n return False\n else:\n pre = i\n return True\n \n", + "title": "1437. Check If All 1's Are at Least Length K Places Away", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of only the characters 'a' and 'b' , return true if every 'a' appears before every 'b' in the string . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"Output:trueExplanation:The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\"Output:falseExplanation:There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbb\"Output:trueExplanation:There are no 'a's, hence, every 'a' appears before every 'b' and we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkString(String s) {\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'b'){\n for(int j = i+1; j < s.length(); j++){\n if(s.charAt(j) == 'a'){\n return false;\n }\n }\n }\n }\n return true;\n }\n}\n", + "title": "2124. Check if All A's Appears Before All B's", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s consisting of only the characters 'a' and 'b' , return true if every 'a' appears before every 'b' in the string . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"Output:trueExplanation:The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\"Output:falseExplanation:There is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbb\"Output:trueExplanation:There are no 'a's, hence, every 'a' appears before every 'b' and we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkString(self, s: str) -> bool:\n if \"ba\" in s:\n return False\n else:\n return True\n", + "title": "2124. Check if All A's Appears Before All B's", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return true if s is a good string, or false otherwise . A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abacbc\"Output:trueExplanation:The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabb\"Output:falseExplanation:The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean areOccurrencesEqual(String s) {\n int[] freq = new int[26];\n \n for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++;\n\n int val = freq[s.charAt(0) - 'a'];\n for (int i = 0; i < 26; i++)\n if (freq[i] != 0 && freq[i] != val) return false; \n\n return true;\n }\n}\n", + "title": "1941. Check if All Characters Have Equal Number of Occurrences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return true if s is a good string, or false otherwise . A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abacbc\"Output:trueExplanation:The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabb\"Output:falseExplanation:The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n", + "title": "1941. Check if All Characters Have Equal Number of Occurrences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array ranges and two integers left and right . Each ranges[i] = [start i , end i ] represents an inclusive interval between start i and end i . Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges . Return false otherwise . An integer x is covered by an interval ranges[i] = [start i , end i ] if start i <= x <= end i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= ranges.length <= 50", + "1 <= start i <= end i <= 50", + "1 <= left <= right <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5Output:trueExplanation:Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.", + "image": null + }, + { + "text": "Example 2: Input:ranges = [[1,10],[10,20]], left = 21, right = 21Output:falseExplanation:21 is not covered by any range.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 85.31%) | Memory: 41.7 MB (Top 83.50%)\nclass Solution {\n public boolean isCovered(int[][] ranges, int left, int right) {\n boolean flag = false;\n for (int i=left; i<=right; i++) {\n for (int[] arr: ranges) {\n if (i >= arr[0] && i <= arr[1]) {\n flag = true;\n break;\n }\n }\n if (!flag) return false;\n flag = false;\n }\n\n return true;\n }\n}", + "title": "1893. Check if All the Integers in a Range Are Covered", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array ranges and two integers left and right . Each ranges[i] = [start i , end i ] represents an inclusive interval between start i and end i . Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges . Return false otherwise . An integer x is covered by an interval ranges[i] = [start i , end i ] if start i <= x <= end i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= ranges.length <= 50", + "1 <= start i <= end i <= 50", + "1 <= left <= right <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5Output:trueExplanation:Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.", + "image": null + }, + { + "text": "Example 2: Input:ranges = [[1,10],[10,20]], left = 21, right = 21Output:falseExplanation:21 is not covered by any range.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n \n \n t=[0]*(60)\n \n for i in ranges:\n \n t[i[0]]+=1\n t[i[1]+1]-=1\n \n for i in range(1,len(t)):\n t[i] += t[i-1]\n \n return min(t[left:right+1])>=1\n \n \n \n \n \n", + "title": "1893. Check if All the Integers in a Range Are Covered", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An original string, consisting of lowercase English letters, can be encoded by the following steps: For example, one way to encode an original string \"abcdefghijklmnop\" might be: Given two encoded strings s1 and s2 , consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2 . Otherwise, return false . Note : The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Arbitrarily split it into a sequence of some number of non-empty substrings.", + "Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).", + "Concatenate the sequence as the encoded string." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"internationalization\", s2 = \"i18n\"Output:trueExplanation:It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n -> Split: [\"internationalization\"]\n -> Do not replace any element\n -> Concatenate: \"internationalization\", which is s1.\n- \"internationalization\"\n -> Split: [\"i\", \"nternationalizatio\", \"n\"]\n -> Replace: [\"i\", \"18\", \"n\"]\n -> Concatenate: \"i18n\", which is s2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"l123e\", s2 = \"44\"Output:trueExplanation:It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n -> Split: [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n -> Replace: [\"l\", \"1\", \"2\", \"3\", \"e\"]\n -> Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n -> Split: [\"leet\", \"code\"]\n -> Replace: [\"4\", \"4\"]\n -> Concatenate: \"44\", which is s2.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a5b\", s2 = \"c5b\"Output:falseExplanation:It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 624 ms (Top 51.93%) | Memory: 473.4 MB (Top 35.91%)\n/**\nCases:\n\ndiff > 0 meaning we need to pick more chars in s1\ndiff < 0 meaning we need to pick more chars in s2\n\n-1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999\n\n1. s1[i] == s2[j] and diff = 0\n increment i+1 and j+1\n\n2. if s1[i] is not digit and diff > 0 then increment i i+1, diff\n3. if s2[j] is not digit and diff < 0 then increment j j+1, diff\n4. if s1[i] is digit then get digit value and decrement diff val as we have covered such chars in the s1 string\n and increment i i+1, diff-val\n5. if s2[j] is digit then get digit value and increment diff val as we need to cover such chars in the s2 string and\n increment j, j+1, diff+val\n\n 01234\ns1 = l123e\ns2 = 44\n\ni: 0\nj: 0\ndiff: 0\n // Wildcard matching on s2[j]\n val = 4, diff = 0+4 j = 1\n\n i: 0\n j: 1\n diff: 4\n // Literal matching on s1[i]\n increment ith pointer as ith is a literal and we can move on to next char in s1 and decrement diff\n\n i: 1\n j: 1\n diff: 3\n // Wildcard matching on s1[i]\n val = 1 diff = 3-1 = 2 increment i\n\n i: 2\n j: 1\n diff: 2\n // Wildcard matching on s1[i]\n val = 2 diff = 2-2 = 0 increment i\n\n i: 3\n j: 1\n diff: 0\n // Wildcard matching on s1[i]\n val=3 diff = 0-3 = -3, increment i\n\n i: 4\n j: 1\n diff: -3\n // Wildcard matching on s2[j]\n val = 4 diff = -3+4 =1 increment j\n\n i: 4\n j: 2\n diff: 1\n // Literal matching on s1[i]\n decrement i-1 and increment i\n\n i=5\n j=2\n diff==0 return true\n dp[4][2][1] = true\n return true\n return dp[4][1][1000-3] = true\n return dp[3][1][0] = true\n\n i: 2\n j: 1\n diff: 2\n return dp[2][1][2] = true\n return true\n\n i: 0\n j: 1\n diff: 4\n return dp[0][1][4] = true\n return true\n*/\n\nclass Solution {\n //112ms\n public boolean possiblyEquals(String s1, String s2) {\n return helper(s1.toCharArray(), s2.toCharArray(), 0, 0, 0, new Boolean[s1.length()+1][s2.length()+1][2001]);\n }\n\n boolean helper(char[] s1, char[] s2, int i, int j, int diff, Boolean[][][] dp) {\n if(i == s1.length && j == s2.length) {\n return diff == 0;\n }\n\n if(dp[i][j][diff+1000] != null)\n return dp[i][j][diff+1000];\n\n // if both i and j are at the same location and chars are same then simply increment both pointers\n if(i < s1.length && j < s2.length && diff == 0 && s1[i] == s2[j]) {\n if(helper(s1, s2, i+1, j+1, diff, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // if s1[i] is literal and diff > 0 then increment i and decrement diff by 1\n if(i < s1.length && !Character.isDigit(s1[i]) && diff > 0 && helper(s1, s2, i+1, j, diff-1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // if s2[j] is literal and diff < 0 then increment j and increment diff by 1\n // as we are done with the current jth char\n if(j < s2.length && !Character.isDigit(s2[j]) && diff < 0 && helper(s1, s2, i, j+1, diff+1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // wildcard matching in s1\n // if s1 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = i, val = 0; k < i + 4 && k < s1.length && Character.isDigit(s1[k]); k++) {\n val = val * 10 + s1[k] -'0';\n if(helper(s1, s2, k+1, j, diff-val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // wildcard matching in s2\n // if s2 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = j, val = 0; k < j + 4 && k < s2.length && Character.isDigit(s2[k]); k++) {\n val = val * 10 + s2[k] -'0';\n if(helper(s1, s2, i, k+1, diff+val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n return dp[i][j][diff+1000] = false;\n }\n}", + "title": "2060. Check if an Original String Exists Given Two Encoded Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An original string, consisting of lowercase English letters, can be encoded by the following steps: For example, one way to encode an original string \"abcdefghijklmnop\" might be: Given two encoded strings s1 and s2 , consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2 . Otherwise, return false . Note : The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Arbitrarily split it into a sequence of some number of non-empty substrings.", + "Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).", + "Concatenate the sequence as the encoded string." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"internationalization\", s2 = \"i18n\"Output:trueExplanation:It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n -> Split: [\"internationalization\"]\n -> Do not replace any element\n -> Concatenate: \"internationalization\", which is s1.\n- \"internationalization\"\n -> Split: [\"i\", \"nternationalizatio\", \"n\"]\n -> Replace: [\"i\", \"18\", \"n\"]\n -> Concatenate: \"i18n\", which is s2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"l123e\", s2 = \"44\"Output:trueExplanation:It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n -> Split: [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n -> Replace: [\"l\", \"1\", \"2\", \"3\", \"e\"]\n -> Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n -> Split: [\"leet\", \"code\"]\n -> Replace: [\"4\", \"4\"]\n -> Concatenate: \"44\", which is s2.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a5b\", s2 = \"c5b\"Output:falseExplanation:It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1026 ms (Top 83.52%) | Memory: 55.5 MB (Top 82.18%)\nfrom functools import lru_cache\nclass Solution:\n def possiblyEquals(self, s1: str, s2: str) -> bool:\n\n def getValidPrefixLength(s,start):\n end = start\n while end < len(s) and s[end].isdigit(): end += 1\n return end\n\n @lru_cache(None)\n def possibleLengths(s):\n \"\"\"Return all possible lengths represented by numeric string s.\"\"\"\n ans = {int(s)}\n for i in range(1, len(s)):\n # add all lengths by splitting numeric string s at i\n ans |= {x+y for x in possibleLengths(s[:i]) for y in possibleLengths(s[i:])}\n return ans\n\n @lru_cache(None)\n def dp(i, j, diff):\n \"\"\"Return True if s1[i:] matches s2[j:] with given differences.\"\"\"\n\n # If both have reached end return true if none of them are leading\n if i == len(s1) and j == len(s2): return diff == 0\n\n # s1 has not reached end and s1 starts with a digit\n if i < len(s1) and s1[i].isdigit():\n i2 = getValidPrefixLength(s1,i)\n for L in possibleLengths(s1[i:i2]):\n # substract since lead of s2 decreases by L\n if dp(i2, j, diff-L): return True\n\n # s2 has not reached end and s2 starts with a digit\n elif j < len(s2) and s2[j].isdigit():\n j2 = getValidPrefixLength(s2,j)\n for L in possibleLengths(s2[j:j2]):\n # add since lead of s2 increase by L\n if dp(i, j2, diff+L): return True\n\n # if none of them have integer prefix or a lead over the other\n elif diff == 0:\n # if only one of them has reached end or current alphabets are not the same\n if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False\n # skip same alphabets\n return dp(i+1, j+1, 0)\n\n # if none of them have integer prefix & s2 lead over s1\n elif diff > 0:\n # no s1 to balance s2's lead\n if i == len(s1): return False\n # move s1 pointer forward and reduce diff\n return dp(i+1, j, diff-1)\n\n # if none of them have integer prefix & s1 lead over s2\n else:\n # no s2 to balance s1's lead\n if j == len(s2): return False\n # move s2 pointer forward and increase diff\n return dp(i, j+1, diff+1)\n\n # start with starts of both s1 and s2 with no lead by any of them\n return dp(0, 0, 0)", + "title": "2060. Check if an Original String Exists Given Two Encoded Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:trueExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]Output:falseExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:trueExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 54.56%)\nclass Solution {\n public boolean check(int[] nums) {\n // here we compare all the neighbouring elemnts and check whether they are in somewhat sorted\n // there will be a small change due to rotation in the array at only one place.\n // so if there are irregularities more than once, return false\n // else return true;\n int irregularities = 0;\n int length = nums.length;\n for (int i=0; i nums[(i + 1) % length])\n irregularities += 1;\n }\n return irregularities > 1 ? false : true;\n }\n}", + "title": "1752. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:trueExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]Output:falseExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:trueExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def check(self, num: List[int]) -> bool:\n ct=0\n for i in range(1,len(num)):\n if num[i-1]>num[i]:\n ct+=1\n if num[len(num)-1]>num[0]:\n ct+=1\n return ct<=1", + "title": "1752. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr of even length n and an integer k . We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k . Return true If you can find a way to do that or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length == n", + "1 <= n <= 10^5", + "n is even.", + "-10^9 <= arr[i] <= 10^9", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,10,6,7,8,9], k = 5Output:trueExplanation:Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5,6], k = 7Output:trueExplanation:Pairs are (1,6),(2,5) and(3,4).", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6], k = 10Output:falseExplanation:You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 78.2%) | Memory: 60.02 MB (Top 5.2%)\n\nclass Solution {\n public boolean canArrange(int[] arr, int k) {\n int[] frequency = new int[k];\n for(int num : arr){\n num %= k;\n if(num < 0) num += k;\n frequency[num]++;\n }\n if(frequency[0]%2 != 0) return false;\n \n for(int i = 1; i <= k/2; i++)\n if(frequency[i] != frequency[k-i]) return false;\n\t\t\t\n return true;\n }\n}", + "title": "1497. Check If Array Pairs Are Divisible by k", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of integers arr of even length n and an integer k . We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k . Return true If you can find a way to do that or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length == n", + "1 <= n <= 10^5", + "n is even.", + "-10^9 <= arr[i] <= 10^9", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,10,6,7,8,9], k = 5Output:trueExplanation:Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5,6], k = 7Output:trueExplanation:Pairs are (1,6),(2,5) and(3,4).", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6], k = 10Output:falseExplanation:You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 556 ms (Top 81.4%) | Memory: 30.00 MB (Top 97.8%)\n\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[1]\n #since we have odd number of complimenting residues,\n #we should also care about residue=0 and residue=k//2\n \n i,j =1,k-1\n pairs = 0\n while i0 and i==j:\n pairs+=count[i]/2\n pairs+= count[0]/2\n n = len(arr)\n return pairs == n//2", + "title": "1497. Check If Array Pairs Are Divisible by k", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s ​​​​​without leading zeros , return true ​​​ if s contains at most one contiguous segment of ones . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] ​​​​ is either '0' or '1' .", + "s[0] is '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001\"Output:falseExplanation:The ones do not form a contiguous segment.", + "image": null + }, + { + "text": "Example 2: Input:s = \"110\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkOnesSegment(String s) {\n return !s.contains(\"01\");\n }\n}\n", + "title": "1784. Check if Binary String Has at Most One Segment of Ones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary string s ​​​​​without leading zeros , return true ​​​ if s contains at most one contiguous segment of ones . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s[i] ​​​​ is either '0' or '1' .", + "s[0] is '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001\"Output:falseExplanation:The ones do not form a contiguous segment.", + "image": null + }, + { + "text": "Example 2: Input:s = \"110\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 66.03%) | Memory: 13.8 MB (Top 52.02%)\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return \"01\" not in s", + "title": "1784. Check if Binary String Has at Most One Segment of Ones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n ( inclusive ). Given an n x n integer matrix matrix , return true if the matrix is valid . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 100", + "1 <= matrix[i][j] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[3,1,2],[2,3,1]]Output:trueExplanation:In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/example1drawio.png" + }, + { + "text": "Example 2: Input:matrix = [[1,1,1],[1,2,3],[1,2,3]]Output:falseExplanation:In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 50.77%) | Memory: 92.4 MB (Top 46.57%)\nclass Solution {\n public boolean checkValid(int[][] matrix) {\n int n = matrix.length;\n int num = (n*(n+1))/2; // SUM of n number 1 to n;\n\n for(int i=0; i hs = new HashSet();\n HashSet hs1 = new HashSet();\n\n int m = num; int k = num;\n\n for(int j = 0; j bool:\n lst = [0]*len(matrix)\n for i in matrix:\n if len(set(i)) != len(matrix):\n return False\n for j in range(len(i)):\n lst[j] += i[j]\n return len(set(lst)) == 1\n", + "title": "2133. Check if Every Row and Column Contains All Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of positive integers. Your task is to select some subset of nums , multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [12,5,7,23]Output:trueExplanation:Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [29,6,10]Output:trueExplanation:Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,6]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isGoodArray(int[] nums) {\n int gcd = nums[0];\n for(int i =1; i bool:\n def gcd(a,b):\n while a:\n a, b = b%a, a\n return b\n return reduce(gcd,nums)==1", + "title": "1250. Check If It Is a Good Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array coordinates , coordinates[i] = [x, y] , where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/15/untitled-diagram-2.jpg", + "https://assets.leetcode.com/uploads/2019/10/09/untitled-diagram-1.jpg" + ], + "constraints": [ + "2 <= coordinates.length <= 1000", + "coordinates[i].length == 2", + "-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4", + "coordinates contains no duplicate point." + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]Output:true", + "image": null + }, + { + "text": "Example 2: Input:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkStraightLine(int[][] coordinates) {\n int x1=coordinates[0][0];\n int y1=coordinates[0][1];\n \n int x2=coordinates[1][0];\n int y2=coordinates[1][1];\n \n float slope;\n if(x2-x1 == 0)\n {\n slope=Integer.MAX_VALUE;\n }\n else\n {\n slope=(y2-y1)/(float)(x2-x1);\n }\n for(int i=0;i bool:\n n = len(grid)\n for i in range(n):\n for j in range(n):\n if i==j or (i+j) ==n-1:\n if grid[i][j] == 0:\n return False\n elif grid[i][j] != 0: \n return False\n return True;\n", + "title": "2319. Check if Matrix Is X-Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 8 x 8 grid board , where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.' , white cells are represented by 'W' , and black cells are represented by 'B' . Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color , and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "board.length == board[r].length == 8", + "0 <= rMove, cMove < 8", + "board[rMove][cMove] == '.'", + "color is either 'B' or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"Output:trueExplanation:'.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid11.png" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"Output:falseExplanation:While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.24 MB (Top 69.6%)\n\nclass Solution {\n public boolean checkMove(char[][] board, int rMove, int cMove, char color) {\n\n int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};\n\n for(int[] d : direction)\n {\n if(dfs(board,rMove,cMove,color,d,1))\n return true;\n }\n return false;\n }\n\n public boolean dfs(char[][] board, int r, int c, char color,int[] direcn,int len)\n {\n\n int nr = r + direcn[0];\n int nc = c + direcn[1];\n\n if( nr<0 || nc<0 || nr>7 || nc>7) return false;\n\n if(board[nr][nc] == color)\n {\n if(len>=2) return true;\n else\n return false;\n }\n else\n {\n if(board[nr][nc] == '.')\n { \n return false;\n }\n return dfs(board,nr,nc,color,direcn,len+1);\n }\n }\n}", + "title": "1958. Check if Move is Legal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 8 x 8 grid board , where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.' , white cells are represented by 'W' , and black cells are represented by 'B' . Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color , and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "board.length == board[r].length == 8", + "0 <= rMove, cMove < 8", + "board[rMove][cMove] == '.'", + "color is either 'B' or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"Output:trueExplanation:'.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid11.png" + }, + { + "text": "Example 2: Input:board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"Output:falseExplanation:While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.", + "image": "https://assets.leetcode.com/uploads/2021/07/10/grid2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 82 ms (Top 35.62%) | Memory: 14 MB (Top 54.79%)\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n directions = [False] * 8\n moves = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),\n (-1, -1), (0, -1), (1, -1)]\n opposite_color = \"W\" if color == \"B\" else \"B\"\n\n for d in range(8):\n r, c = rMove + moves[d][0], cMove + moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite_color:\n directions[d] = True\n\n for step in range(2, 8):\n if not any(d for d in directions):\n return False\n for d in range(8):\n if directions[d]:\n r, c = rMove + step * moves[d][0], cMove + step * moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8:\n if board[r][c] == color:\n return True\n elif board[r][c] == \".\":\n directions[d] = False\n else:\n directions[d] = False\n return False", + "title": "1958. Check if Move is Legal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M ). More formally check if there exists two indices i and j such that : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i != j", + "0 <= i, j < arr.length", + "arr[i] == 2 * arr[j]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,2,5,3]Output:trueExplanation:N= 10is the double of M= 5,that is,10 = 2 * 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,1,14,11]Output:trueExplanation:N= 14is the double of M= 7,that is,14 = 2 * 7.", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,1,7,11]Output:falseExplanation:In this case does not exist N and M, such that N = 2 * M.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 76.57%) | Memory: 42.30 MB (Top 45.56%)\n\nclass Solution {\n public boolean checkIfExist(int[] arr) {\n\t int n = arr.length;\n for (int i = 0; i < n; i++) \n for (int j = 0; j < n; j++) \n if (i != j && arr[i] == 2 * arr[j]) \n return true;\n\n return false;\n }\n}\n\n// TC: O(n ^ 2), SC: O(1)\n", + "title": "1346. Check If N and Its Double Exist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M ). More formally check if there exists two indices i and j such that : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i != j", + "0 <= i, j < arr.length", + "arr[i] == 2 * arr[j]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,2,5,3]Output:trueExplanation:N= 10is the double of M= 5,that is,10 = 2 * 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,1,14,11]Output:trueExplanation:N= 14is the double of M= 7,that is,14 = 2 * 7.", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,1,7,11]Output:falseExplanation:In this case does not exist N and M, such that N = 2 * M.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def checkIfExist(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n '''\n 执行用时:24 ms, 在所有 Python 提交中击败了59.63%的用户\n 内存消耗:13 MB, 在所有 Python 提交中击败了58.72%的用户\n '''\n arr = sorted(arr) # 排序\n for i in range(len(arr) - 1): # 只要搜寻 n - 1 个,因为最后一个数不会有倍数出现\n l = 0\n r = len(arr) - 1\n while (l <= r):\n mid = int((l + r) / 2) # 目前位置\n val1 = arr[mid] # 目前位置的数值\n val2 = arr[i] * 2 # 要寻找的目标\n if(val1 == val2 and mid != i): # arr[mid] 必須和 arr[i] * 2 且不同位置\n return True\n elif(val2 < val1): # 目标在目前位置的左边,所以要往左边找\n r = mid - 1\n else: # 目标在目前位置的右边,所以要往右边找\n l = mid + 1\n return False\n", + "title": "1346. Check If N and Its Double Exist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n , the digit i occurs num[i] times in num , otherwise return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == num.length", + "1 <= n <= 10", + "num consists of digits." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1210\"Output:trueExplanation:num[0] = '1'. The digit 0 occurs once in num.\nnum[1] = '2'. The digit 1 occurs twice in num.\nnum[2] = '1'. The digit 2 occurs once in num.\nnum[3] = '0'. The digit 3 occurs zero times in num.\nThe condition holds true for every index in \"1210\", so return true.", + "image": null + }, + { + "text": "Example 2: Input:num = \"030\"Output:falseExplanation:num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\nnum[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\nnum[2] = '0'. The digit 2 occurs zero times in num.\nThe indices 0 and 1 both violate the condition, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean digitCount(String num) {\n int[] freqArr = new int[10]; // n = 10 given in constraints;\n \n \n for(char ch : num.toCharArray()){\n freqArr[ch-'0']++;\n }\n \n for(int i=0;i bool:\n d = Counter(num)\n for i in range(len(num)):\n if int(num[i])!=d.get(str(i), 0):\n return False\n return True\n", + "title": "2283. Check if Number Has Equal Digit Count and Digit Value", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:trueExplanation:12 = 31+ 32", + "image": null + }, + { + "text": "Example 2: Input:n = 91Output:trueExplanation:91 = 30+ 32+ 34", + "image": null + }, + { + "text": "Example 3: Input:n = 21Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 41.31%) | Memory: 41.4 MB (Top 27.03%)\n\nclass Solution {\n public boolean checkPowersOfThree(int n) {\n //max power of 3\n int maxPower = (int)(Math.log(n) / Math.log(3));\n\n //save all the power of 3 from 0 to maxPower\n // 3^0, 3^1, 3^2 .... 3^maxPower\n int[] threePower = new int[maxPower + 1];\n threePower[0] = 1;\n for(int i = 1; i <= maxPower; i++){\n threePower[i] = threePower[i - 1] * 3;\n }\n\n //Intuition\n //if we subtract n with every power of 3\n //at the end if n is zero, then it is sum of power 3\n\n //subtract n with power of 3,\n //if n is graeter than power\n for(int i = maxPower; i >= 0; i--){\n //n is greater/equal to power 3\n if(n >= threePower[i]){\n n -= threePower[i];\n }\n }\n\n return n == 0;\n }\n}", + "title": "1780. Check if Number is a Sum of Powers of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:trueExplanation:12 = 31+ 32", + "image": null + }, + { + "text": "Example 2: Input:n = 91Output:trueExplanation:91 = 30+ 32+ 34", + "image": null + }, + { + "text": "Example 3: Input:n = 21Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 10.08%) | Memory: 17.20 MB (Top 9.7%)\n\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while n > 1:\n n, r = divmod(n, 3)\n if r == 2: return False\n return True\n", + "title": "1780. Check if Number is a Sum of Powers of Three", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s ). Return true if so, or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"Output:trueExplanation:The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example1.png" + }, + { + "text": "Example 2: Input:s = \"hello world 5 x 5\"Output:falseExplanation:The numbers in s are:5,5. They are not strictly increasing.", + "image": null + }, + { + "text": "Example 3: Input:s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"Output:falseExplanation:The numbers in s are: 7,51,50, 60. They are not strictly increasing.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 29.63%) | Memory: 43.3 MB (Top 11.10%)\n// Space Complexity: O(1)\n// Time Complexity: O(n)\nclass Solution {\n public boolean areNumbersAscending(String s) {\n int prev = 0;\n\n for(String token: s.split(\" \")) {\n try {\n int number = Integer.parseInt(token);\n if(number <= prev)\n return false;\n prev = number;\n }\n catch(Exception e) {}\n }\n\n return true;\n }\n}", + "title": "2042. Check if Numbers Are Ascending in a Sentence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s ). Return true if so, or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"Output:trueExplanation:The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example1.png" + }, + { + "text": "Example 2: Input:s = \"hello world 5 x 5\"Output:falseExplanation:The numbers in s are:5,5. They are not strictly increasing.", + "image": null + }, + { + "text": "Example 3: Input:s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"Output:falseExplanation:The numbers in s are: 7,51,50, 60. They are not strictly increasing.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/example3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 38.18%) | Memory: 13.8 MB (Top 55.89%)\nclass Solution:\n def areNumbersAscending(self, s):\n nums = re.findall(r'\\d+', s)\n return nums == sorted(set(nums), key=int)", + "title": "2042. Check if Numbers Are Ascending in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 100", + "s1.length == s2.length", + "s1 and s2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"bank\", s2 = \"kanb\"Output:trueExplanation:For example, swap the first character with the last character of s2 to make \"bank\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"attack\", s2 = \"defend\"Output:falseExplanation:It is impossible to make them equal with one string swap.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"kelb\", s2 = \"kelb\"Output:trueExplanation:The two strings are already equal, so no string swap operation is required.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean areAlmostEqual(String s1, String s2) {\n \n int[] s1Array = new int[26];\n int[] s2Array = new int[26];\n int counter = 0;\n for(int i = 0;i 2)\n return false;\n s1Array[s -'a']++;\n s2Array[ss -'a']++;\n }\n return Arrays.equals(s1Array, s2Array);\n }\n}", + "title": "1790. Check if One String Swap Can Make Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 100", + "s1.length == s2.length", + "s1 and s2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"bank\", s2 = \"kanb\"Output:trueExplanation:For example, swap the first character with the last character of s2 to make \"bank\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"attack\", s2 = \"defend\"Output:falseExplanation:It is impossible to make them equal with one string swap.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"kelb\", s2 = \"kelb\"Output:trueExplanation:The two strings are already equal, so no string swap operation is required.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 36 ms (Top 83.5%) | Memory: 16.25 MB (Top 70.5%)\n\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]", + "title": "1790. Check if One String Swap Can Make Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an array of strings words , determine whether s is a prefix string of words . A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length . Return true if s is a prefix string of words , or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "1 <= s.length <= 1000", + "words[i] and s consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]Output:trueExplanation:s can be made by concatenating \"i\", \"love\", and \"leetcode\" together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]Output:falseExplanation:It is impossible to make s using a prefix of arr.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.41%) | Memory: 42.90 MB (Top 8.98%)\n\nclass Solution {\n public boolean isPrefixString(String s, String[] words) {\n StringBuilder res = new StringBuilder (\"\");\n for (String word : words) {\n res.append (word);\n if (s.equals (res.toString()))\n return true;\n if (s.indexOf (res.toString()) == -1)\n return false;\n }\n return false;\n }\n}\n", + "title": "1961. Check If String Is a Prefix of Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s and an array of strings words , determine whether s is a prefix string of words . A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length . Return true if s is a prefix string of words , or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "1 <= s.length <= 1000", + "words[i] and s consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]Output:trueExplanation:s can be made by concatenating \"i\", \"love\", and \"leetcode\" together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]Output:falseExplanation:It is impossible to make s using a prefix of arr.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \n a = ''\n \n for i in words:\n \n a += i\n \n if a == s:\n return True\n if not s.startswith(a):\n break\n \n return False \n", + "title": "1961. Check If String Is a Prefix of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , transform string s into string t using the following operation any number of times: Return true if it is possible to transform s into t . Otherwise, return false . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose a non-empty substring in s and sort it in place so the characters are in ascending order . For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" .", + "For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"84532\", t = \"34852\"Output:trueExplanation:You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"34521\", t = \"23415\"Output:trueExplanation:You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"12345\", t = \"12435\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isTransformable(String s, String t) {\n if (!equal(s, t)) return false;\n int[] countS = new int[10];\n int[] countT = new int[10];\n int[][] prev = new int[10][10];\n int[][] after = new int[10][10];\n \n for (int i = 0; i < s.length(); i++) {\n int s1 = s.charAt(i) - '0';\n int t1 = t.charAt(i) - '0';\n countS[s1]++;\n countT[t1]++;\n \n\t\t\t// This step is to calculate how many digit less than s1/t1 occur before time i\n\t\t\t// Store the frequency pair into 2-d array\n for (int j = 0; j < s1; j++) {\n if (countS[j] == 0) continue;\n prev[j][s1] += countS[j];\n\n }\n \n for (int j = 0; j < t1; j++) {\n if (countT[j] == 0) continue; \n after[j][t1] += countT[j];\n }\n \n }\n \n for (int i = 0; i <= 8; i++) {\n for (int j = i + 1; j <= 9; j++) {\n if (prev[i][j] == 0) continue;\n\t\t\t\t// Check if any ascending pair's frequency has been reduced after modified.\n if (after[i][j] < prev[i][j]) return false;\n }\n }\n \n return true;\n }\n \n\t// Judge whether the two strings has the same digits\n public boolean equal(String s, String t) {\n char[] sc = s.toCharArray();\n char[] tc = t.toCharArray();\n Arrays.sort(sc);\n Arrays.sort(tc);\n \n for (int i = 0; i < s.length(); i++) {\n if (sc[i] != tc[i]) return false;\n }\n \n return true;\n }\n}\n", + "title": "1585. Check If String Is Transformable With Substring Sort Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , transform string s into string t using the following operation any number of times: Return true if it is possible to transform s into t . Otherwise, return false . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose a non-empty substring in s and sort it in place so the characters are in ascending order . For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" .", + "For example, applying the operation on the underlined substring in \"1 4234 \" results in \"1 2344 \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"84532\", t = \"34852\"Output:trueExplanation:You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"34521\", t = \"23415\"Output:trueExplanation:You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"12345\", t = \"12435\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n index = defaultdict(list)\n for i, c in enumerate(s):\n index[c].append(i)\n curpos = defaultdict(int)\n for c in t:\n if curpos[c] == len(index[c]): return False\n for i in range(int(c)):\n i = str(i)\n if curpos[i] < len(index[i]) and index[i][curpos[i]] < index[c][curpos[c]]:\n return False\n curpos[c] += 1\n return True", + "title": "1585. Check If String Is Transformable With Substring Sort Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram , or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 1000", + "sentence consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"thequickbrownfoxjumpsoverthelazydog\"Output:trueExplanation:sentence contains at least one of every letter of the English alphabet.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"leetcode\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkIfPangram(String sentence) {\n int seen = 0;\n for(char c : sentence.toCharArray()) {\n int ci = c - 'a';\n seen = seen | (1 << ci);\n }\n return seen == ((1 << 26) - 1);\n }\n}", + "title": "1832. Check if the Sentence Is Pangram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram , or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= sentence.length <= 1000", + "sentence consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"thequickbrownfoxjumpsoverthelazydog\"Output:trueExplanation:sentence contains at least one of every letter of the English alphabet.", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"leetcode\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n return len(set(sentence))==26", + "title": "1832. Check if the Sentence Is Pangram", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given an m x n matrix of parentheses grid . A valid parentheses string path in the grid is a path satisfying all of the following conditions: Return true if there exists a valid parentheses string path in the grid. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]Output:trueExplanation:The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string \"()(())\".\nThe second path shown results in the valid parentheses string \"((()))\".\nNote that there may be other valid parentheses string paths.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[\")\",\")\"],[\"(\",\"(\"]]Output:falseExplanation:The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 538 ms (Top 16.66%) | Memory: 372.3 MB (Top 5.18%)\nclass Solution {\n static Boolean[][][] dp;\n public boolean hasValidPath(char[][] grid) {\n int m = grid.length, n = grid[0].length;\n dp = new Boolean[101][101][201]; // [row][col][open-close]\n if(grid[0][0] == ')'){ // cannot start with ')'\n return false;\n }\n if(grid[m-1][n-1] == '('){ // cannot end with '('\n return false;\n }\n return solve(grid,0,0,m,n,0,0);\n }\n public static boolean solve(char[][] grid,int i,int j,int m,int n,int open,int close){\n if(grid[i][j] == '('){\n open++;\n }\n else{\n close++;\n }\n if(close > open){ // at any point if closeBracket count exceeds openBracket count then return false since this path can never lead to valid paranthesis string\n return false;\n }\n if(i == m-1 && j == n-1){ // on reaching bottom right cell if openCount == closeCount return true else return false\n return open == close;\n }\n if(dp[i][j][open-close] != null){ // check for precomputed overlapping subproblem\n return dp[i][j][open-close];\n }\n if(i == m-1){ // make sure to not go out of the grid in last row\n return dp[i][j][open-close] = solve(grid,i,j+1,m,n,open,close);\n }\n if(j == n-1){ // make sure to not go out of the grid in last col\n return dp[i][j][open-close] = solve(grid,i+1,j,m,n,open,close);\n }\n boolean op = solve(grid,i+1,j,m,n,open,close) || solve(grid,i,j+1,m,n,open,close); // we have two choices to move forward, [i+1][j] or [i][j+1]\n return dp[i][j][open-close] = op;\n }\n}", + "title": "2267. Check if There Is a Valid Parentheses String Path", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A parentheses string is a non-empty string consisting only of '(' and ')' . It is valid if any of the following conditions is true : You are given an m x n matrix of parentheses grid . A valid parentheses string path in the grid is a path satisfying all of the following conditions: Return true if there exists a valid parentheses string path in the grid. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is () .", + "It can be written as AB ( A concatenated with B ), where A and B are valid parentheses strings.", + "It can be written as (A) , where A is a valid parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]Output:trueExplanation:The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string \"()(())\".\nThe second path shown results in the valid parentheses string \"((()))\".\nNote that there may be other valid parentheses string paths.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[\")\",\")\"],[\"(\",\"(\"]]Output:falseExplanation:The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1143 ms (Top 75.31%) | Memory: 238.70 MB (Top 9.88%)\n\nclass Solution:\n def hasValidPath(self, grid: List[List[str]]) -> bool: \n m = len(grid)\n n = len(grid[0])\n @lru_cache(maxsize=None)\n def hasValidPathInner(x, y, cnt):\n # cnt variable would act as a counter to track \n # the balance of parantheses sequence\n if x == m or y == n or cnt < 0:\n return False\n \n # logic to check the balance of sequence\n cnt += 1 if grid[x][y] == '(' else -1\n \n # if balanced and end of grid, return True\n if x == m - 1 and y == n - 1 and not cnt:\n return True\n \n return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt)\n\n return hasValidPathInner(0, 0, 0)\n", + "title": "2267. Check if There Is a Valid Parentheses String Path", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: Return true if the array has at least one valid partition . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,4,4,5,6]Output:trueExplanation:The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2]Output:falseExplanation:There is no valid partition for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 12.25%) | Memory: 82.9 MB (Top 64.19%)\n// Time O(n)\n// Space O(n)\nclass Solution {\n public boolean validPartition(int[] nums) {\n boolean[] dp = new boolean[nums.length+1];\n dp[0]=true; // base case\n for (int i = 2; i <= nums.length; i++){\n dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1\n dp[i]|= i>2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] && dp[i-3]; // cond 2\n dp[i]|= i>2 && nums[i-1]-nums[i-2]==1 && nums[i-2]-nums[i-3]==1 && dp[i-3]; // cond 3\n }\n return dp[nums.length];\n }\n}", + "title": "2369. Check if There is a Valid Partition For The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: Return true if the array has at least one valid partition . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,4,4,5,6]Output:trueExplanation:The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2]Output:falseExplanation:There is no valid partition for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 920 ms (Top 32.4%) | Memory: 30.14 MB (Top 95.0%)\n\nclass Solution:\n def validPartition(self, nums: List[int]) -> bool:\n n = len(nums)\n \n dp = [False] * 3\n dp[0] = True # An empty partition is always valid\n\n for i in range(2, n + 1):\n ans = False\n\n if nums[i - 1] == nums[i - 2]:\n ans = ans or dp[(i - 2) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]:\n ans = ans or dp[(i - 3) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2:\n ans = ans or dp[(i - 3) % 3]\n\n dp[i % 3] = ans\n\n return dp[n % 3]", + "title": "2369. Check if There is a Valid Partition For The Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n grid . Each cell of grid represents a street. The street of grid[i][j] can be: You will initially start at the street of the upper-left cell (0, 0) . A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) . The path should only follow the streets . Notice that you are not allowed to change any street. Return true if there is a valid path in the grid or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 which means a street connecting the left cell and the right cell.", + "2 which means a street connecting the upper cell and the lower cell.", + "3 which means a street connecting the left cell and the lower cell.", + "4 which means a street connecting the right cell and the lower cell.", + "5 which means a street connecting the left cell and the upper cell.", + "6 which means a street connecting the right cell and the upper cell." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4,3],[6,5,2]]Output:trueExplanation:As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).", + "image": "https://assets.leetcode.com/uploads/2020/03/05/e1.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,1],[1,2,1]]Output:falseExplanation:As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)", + "image": "https://assets.leetcode.com/uploads/2020/03/05/e2.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,2]]Output:falseExplanation:You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 82.7%) | Memory: 66.95 MB (Top 46.9%)\n\nclass Solution {\n public boolean hasValidPath(int[][] grid) {\n int m=grid.length, n=grid[0].length;\n int[][] visited=new int[m][n];\n return dfs(grid, 0, 0, m, n, visited);\n }\n public boolean dfs(int[][] grid, int i, int j, int m, int n, int[][] visited){\n if(i==m-1 && j==n-1) return true;\n if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==1) return false;\n visited[i][j]=1;\n if(grid[i][j]==1){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (j0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else if(grid[i][j]==3){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else{\n if( (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited)) || \n\t\t\t (j bool:\n r,c=len(grid),len(grid[0])\n dic={\n 2:[(-1,0),(1,0)],\n 1:[(0,1),(0,-1)],\n 5:[(-1,0),(0,-1)],\n 3:[(1,0),(0,-1)],\n 6:[(0,1),(-1,0)],\n 4:[(0,1),(1,0)]\n \n }\n q=collections.deque([(0,0)])\n visit=set()\n while q:\n i,j=q.popleft()\n visit.add((i,j))\n if i==r-1 and j==c-1:\n return True\n for x,y in dic[grid[i][j]]:\n nx=i+x\n ny=j+y\n if nx>=0 and nx=0 and ny \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.", + "image": null + }, + { + "text": "Example 2: Input:word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]Output:false", + "image": null + }, + { + "text": "Example 3: Input:word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 57.48%) | Memory: 41.5 MB (Top 82.47%)\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2)\n {\n return(String.join(\"\", word1).equals(String.join(\"\", word2)));\n }\n}", + "title": "1662. Check If Two String Arrays are Equivalent", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two string arrays word1 and word2 , return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 10^3", + "1 <= word1[i].length, word2[i].length <= 10^3", + "1 <= sum(word1[i].length), sum(word2[i].length) <= 10^3", + "word1[i] and word2[i] consist of lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]Output:trueExplanation:word1 represents string \"ab\" + \"c\" -> \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.", + "image": null + }, + { + "text": "Example 2: Input:word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]Output:false", + "image": null + }, + { + "text": "Example 3: Input:word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return True if \"\".join(word1) == \"\".join(word2) else False", + "title": "1662. Check If Two String Arrays are Equivalent", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix board , representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: Given a string word , return true if word can be placed in board , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It does not occupy a cell containing the character '#' .", + "The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board .", + "There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally .", + "There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"Output:trueExplanation:The word \"abc\" can be placed as shown above (top to bottom).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png" + }, + { + "text": "Example 2: Input:board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"Output:falseExplanation:It is impossible to place the word because there will always be a space/letter above or below it.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png" + }, + { + "text": "Example 3: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"Output:trueExplanation:The word \"ca\" can be placed as shown above (right to left).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 522 ms (Top 5.97%) | Memory: 200.3 MB (Top 5.41%)\nclass Solution {\n public boolean placeWordInCrossword(char[][] board, String word) {\n String curr = \"\";\n\n Trie trie = new Trie();\n\n // Insert all horizontal strings\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n if (board[i][j] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[i][j];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n // Insert all vertical strings\n for (int i = 0; i < board[0].length; i++) {\n for (int j = 0; j < board.length; j++) {\n if (board[j][i] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[j][i];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n return trie.isPresent(word);\n }\n\n // Insert string and reverse of string into the trie\n private void insertIntoTrie(Trie trie, String s) {\n trie.insert(s);\n StringBuilder sb = new StringBuilder(s);\n sb.reverse();\n trie.insert(sb.toString());\n }\n\n class TrieNode {\n Map children;\n boolean isEnd;\n\n TrieNode() {\n children = new HashMap<>();\n isEnd = false;\n }\n\n }\n\n class Trie {\n TrieNode root;\n\n Trie() {\n root = new TrieNode();\n }\n\n void insert(String s) {\n TrieNode curr = root;\n\n for (int i = 0; i < s.length(); i++)\n {\n char c = s.charAt(i);\n if (!curr.children.containsKey(c)) {\n curr.children.put(c, new TrieNode());\n }\n\n curr = curr.children.get(c);\n }\n\n curr.isEnd = true;\n }\n\n boolean isPresent(String key) {\n TrieNode curr = root;\n return helper(key, 0, root);\n\n }\n\n boolean helper(String key, int i, TrieNode curr) {\n if (curr == null)\n return false;\n\n if (i == key.length())\n return curr.isEnd;\n\n char c = key.charAt(i);\n return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));\n\n }\n }\n}", + "title": "2018. Check if Word Can Be Placed In Crossword", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n matrix board , representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells. A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: Given a string word , return true if word can be placed in board , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It does not occupy a cell containing the character '#' .", + "The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board .", + "There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally .", + "There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"Output:trueExplanation:The word \"abc\" can be placed as shown above (top to bottom).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex1-1.png" + }, + { + "text": "Example 2: Input:board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"Output:falseExplanation:It is impossible to place the word because there will always be a space/letter above or below it.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex2-1.png" + }, + { + "text": "Example 3: Input:board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"Output:trueExplanation:The word \"ca\" can be placed as shown above (right to left).", + "image": "https://assets.leetcode.com/uploads/2021/10/04/crossword-ex3-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n m, n = len(board), len(board[0])\n W = len(word)\n \n def valid(x, y):\n return 0 <= x < m and 0 <= y < n\n \n def place(x, y, word, direction):\n dx, dy = direction\n for c in word:\n if not valid(x, y) or board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != c):\n return False\n x, y = x+dx, y+dy\n return True\n \n \n for x in range(m):\n for y in range(n):\n if board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != word[0]):\n continue\n \n # left to right\n if (not valid(x, y-1) or board[x][y-1] == '#') and (not valid(x, y+W) or board[x][y+W] == '#') and place(x, y, word, [0, 1]):\n return True\n \n # right to left\n if (not valid(x, y+1) or board[x][y+1] == '#') and (not valid(x, y-W) or board[x][y-W] == '#') and place(x, y, word, [0, -1]):\n return True\n \n # top to bottom\n if (not valid(x-1, y) or board[x-1][y] == '#') and (not valid(x+W, y) or board[x+W][y] == '#') and place(x, y, word, [1, 0]):\n return True\n \n\t\t\t\t# bottom to top\n if (not valid(x+1, y) or board[x+1][y] == '#') and (not valid(x-W, y) or board[x-W][y] == '#') and place(x, y, word, [-1, 0]):\n return True\n \n return False\n", + "title": "2018. Check if Word Can Be Placed In Crossword", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0 , 'b' -> 1 , 'c' -> 2 , etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s , which is then converted into an integer. You are given three strings firstWord , secondWord , and targetWord , each consisting of lowercase English letters 'a' through 'j' inclusive . Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if s = \"acb\" , we concatenate each letter's letter value, resulting in \"021\" . After converting it, we get 21 ." + ], + "examples": [ + { + "text": "Example 1: Input:firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"Output:trueExplanation:The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.", + "image": null + }, + { + "text": "Example 2: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"Output:falseExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.", + "image": null + }, + { + "text": "Example 3: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"Output:trueExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {\n int sumfirst=0, sumsecond=0, sumtarget=0;\n for(char c : firstWord.toCharArray()){\n sumfirst += c-'a';\n sumfirst *= 10;\n }\n for(char c : secondWord.toCharArray()){\n sumsecond += c-'a';\n sumsecond *= 10;\n }\n for(char c : targetWord.toCharArray()){\n sumtarget += c-'a';\n sumtarget *= 10;\n }\n \n return (sumfirst + sumsecond) == sumtarget;\n }\n}", + "title": "1880. Check if Word Equals Summation of Two Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0 , 'b' -> 1 , 'c' -> 2 , etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s , which is then converted into an integer. You are given three strings firstWord , secondWord , and targetWord , each consisting of lowercase English letters 'a' through 'j' inclusive . Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if s = \"acb\" , we concatenate each letter's letter value, resulting in \"021\" . After converting it, we get 21 ." + ], + "examples": [ + { + "text": "Example 1: Input:firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"Output:trueExplanation:The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.", + "image": null + }, + { + "text": "Example 2: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"Output:falseExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.", + "image": null + }, + { + "text": "Example 3: Input:firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"Output:trueExplanation:The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 58.1%) | Memory: 16.21 MB (Top 73.9%)\n\nclass Solution:\n def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n x=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n a=\"\"\n for i in firstWord:\n a=a+str(x.index(i))\n \n b=\"\"\n for i in secondWord:\n b=b+str(x.index(i))\n\n c=\"\"\n for i in targetWord:\n c=c+str(x.index(i))\n if int(a)+int(b)==int(c):\n return True\n return False", + "title": "1880. Check if Word Equals Summation of Two Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , determine if it is valid . A string s is valid if, starting with an empty string t = \"\" , you can transform t into s after performing the following operation any number of times : Return true if s is a valid string, otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Insert string \"abc\" into any position in t . More formally, t becomes t left + \"abc\" + t right , where t == t left + t right . Note that t left and t right may be empty ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcbc\"Output:trueExplanation:\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcabcababcc\"Output:trueExplanation:\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abccba\"Output:falseExplanation:It is impossible to get \"abccba\" using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValid(String s) {\n \n //Lets see how we can solve that as we know we have only abc in string.\n //Like aabcbc\n // See as that ((b)b) Think a is '(' and c is ')'.\n // If a string is made by using abc only we can remove abc to make it empty also.\n \n //Think in Reverse Way.\n \n \n \n Stack stack = new Stack<>();\n char[] arr = s.toCharArray();\n for (int i = 0; i < arr.length; i++) {\n \n // We have to work only when we get ')' means c.\n \n if(arr[i] == 'c')\n {\n // If we at c means we have 2 elements before us a and b.\n // When we first pop we get b at second pop we get a\n \n // If this all hold true we will delete a and b we are not adding c so c also\n \n if(stack.size()>=2 && stack.pop() == 'b' && stack.pop() == 'a')\n {\n\n }\n else\n {\n \n // If anywhere we get false in any condition that means this is not a valid set i.e. abc pattern is not present.\n \n return false;\n }\n }\n else\n {\n // For a and b we simply add.\n \n stack.push(arr[i]);\n }\n }\n \n //If we have only abc pattern the stack will become empty.\n \n return stack.size()==0;\n }\n}\n", + "title": "1003. Check If Word Is Valid After Substitutions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , determine if it is valid . A string s is valid if, starting with an empty string t = \"\" , you can transform t into s after performing the following operation any number of times : Return true if s is a valid string, otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Insert string \"abc\" into any position in t . More formally, t becomes t left + \"abc\" + t right , where t == t left + t right . Note that t left and t right may be empty ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcbc\"Output:trueExplanation:\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcabcababcc\"Output:trueExplanation:\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abccba\"Output:falseExplanation:It is impossible to get \"abccba\" using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, s: str) -> bool:\n \n \n ans = ''\n for i in s:\n ans+=i\n while len(ans)>=3:\n if ans[-3:]==\"abc\":\n ans=ans[0:-3]\n else:\n break\n \n if ans=='':\n return True\n else:\n return False", + "title": "1003. Check If Word Is Valid After Substitutions", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3 . Given two strings word1 and word2 , each of length n , return true if word1 and word2 are almost equivalent , or false otherwise . The frequency of a letter x is the number of times it occurs in the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == word1.length == word2.length", + "1 <= n <= 100", + "word1 and word2 consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"aaaa\", word2 = \"bccb\"Output:falseExplanation:There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcdeef\", word2 = \"abaaacc\"Output:trueExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cccddabba\", word2 = \"babababab\"Output:trueExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n public boolean checkAlmostEquivalent(String word1, String word2) {\n Map map = new HashMap();\n for (int i = 0; i < word1.length(); i++) {\n map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1);\n map.put(word2.charAt(i), map.getOrDefault(word2.charAt(i), 0) - 1);\n }\n for (int i : map.values()) { //get value set\n if (i > 3 || i < -3) { \n return false;\n }\n }\n return true;\n }\n}", + "title": "2068. Check Whether Two Strings are Almost Equivalent", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3 . Given two strings word1 and word2 , each of length n , return true if word1 and word2 are almost equivalent , or false otherwise . The frequency of a letter x is the number of times it occurs in the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == word1.length == word2.length", + "1 <= n <= 100", + "word1 and word2 consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"aaaa\", word2 = \"bccb\"Output:falseExplanation:There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcdeef\", word2 = \"abaaacc\"Output:trueExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cccddabba\", word2 = \"babababab\"Output:trueExplanation:The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkAlmostEquivalent(self, w1: str, w2: str) -> bool:\n\t\treturn all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())\n", + "title": "2068. Check Whether Two Strings are Almost Equivalent", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An undirected graph of n nodes is defined by edgeList , where edgeList[i] = [u i , v i , dis i ] denotes an edge between nodes u i and v i with distance dis i . Note that there may be multiple edges between two nodes. Given an array queries , where queries[j] = [p j , q j , limit j ] , your task is to determine for each queries[j] whether there is a path between p j and q j such that each edge on the path has a distance strictly less than limit j . Return a boolean array answer , where answer.length == queries.length and the j th value of answer is true if there is a path for queries[j] is true , and false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "1 <= edgeList.length, queries.length <= 10^5", + "edgeList[i].length == 3", + "queries[j].length == 3", + "0 <= u i , v i , p j , q j <= n - 1", + "u i != v i", + "p j != q j", + "1 <= dis i , limit j <= 10^9", + "There may be multiple edges between two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]Output:[false,true]Explanation:The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.", + "image": "https://assets.leetcode.com/uploads/2020/12/08/h.png" + }, + { + "text": "Example 2: Input:n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]Output:[true,false]Exaplanation:The above figure shows the given graph.", + "image": "https://assets.leetcode.com/uploads/2020/12/08/q.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n private int[] parents;\n public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {\n this.parents = new int[n];\n for (int i = 0; i < n; i++) parents[i] = i;\n \n int m = queries.length;\n \n // storing {u, v, weight, original idx} by increasing weight\n int[][] sortedQueries = new int[m][4];\n for (int i = 0; i < m; i++) {\n sortedQueries[i] = new int[]{queries[i][0], queries[i][1], queries[i][2], i};\n }\n Arrays.sort(sortedQueries, (a,b) -> a[2] - b[2]);\n \n \n // sort edgeList by increasing weight \n Arrays.sort(edgeList, (a,b) -> a[2] - b[2]);\n int idx = 0;\n \n boolean[] res = new boolean[m];\n \n for (int i = 0; i < m; i++) {\n int[] q = sortedQueries[i];\n int w = q[2];\n \n // union all edges with weight less than current query\n while (idx < edgeList.length && edgeList[idx][2] < w) {\n int[] e = edgeList[idx++];\n int u = e[0], v = e[1];\n union(u, v);\n }\n \n int uQuery = q[0], vQuery = q[1], id = q[3];\n res[id] = (find(uQuery) == find(vQuery));\n }\n \n return res;\n }\n \n private void union(int u, int v) {\n int uParent = find(u);\n int vParent = find(v);\n parents[uParent] = vParent;\n }\n \n private int find(int u) {\n while (u != parents[u]) {\n parents[u] = parents[parents[u]];\n u = parents[u];\n }\n return u;\n } \n}\n", + "title": "1697. Checking Existence of Edge Length Limited Paths", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. Return the maximum number of cherries you can collect by following the rules below : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 means the cell is empty, so you can pass through,", + "1 means the cell contains a cherry that you can pick up and pass through, or", + "-1 means the cell contains a thorn that blocks your way." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,-1],[1,0,-1],[1,1,1]]Output:5Explanation:The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.", + "image": "https://assets.leetcode.com/uploads/2020/12/14/grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,-1],[1,-1,1],[-1,1,1]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.2%) | Memory: 44.42 MB (Top 46.1%)\n\nclass Solution {\n public int cherryPickup(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n //For O(N^3) Dp sapce solution\n dp2 = new Integer[m][n][m];\n int ans=solve2(0,0,0,grid,0,m,n);\n if(ans==Integer.MIN_VALUE) return 0;\n return ans;\n }\n \n private Integer[][][] dp2;\n private int solve2(int x1, int y1, int x2, int[][] g, int cpsf, int m, int n){\n int y2 = x1+y1+-x2;\n if(x1>=m||x2>=m||y1>=n||y2>=n||g[x1][y1]==-1||g[x2][y2]==-1) return Integer.MIN_VALUE;\n if(x1==m-1&&y1==n-1) return g[x1][y1];\n //If both p1 and p2 reach (m-1,n-1)\n if(dp2[x1][y1][x2]!=null) return dp2[x1][y1][x2];\n int cherries=0;\n //If both p1 and p2 are at same position then we need to add the cherry only once.\n if(x1==x2&&y1==y2){\n cherries+=g[x1][y1];\n }\n //If p1 and p2 are at different positions then repective cherries can be added.\n else{\n cherries+=g[x1][y1]+g[x2][y2];\n }\n //4 possibilites for p1 and p2 from each point\n int dd=solve2(x1+1,y1,x2+1,g,cpsf+cherries,m,n); //both moves down\n int dr=solve2(x1+1,y1,x2,g,cpsf+cherries,m,n); //p1 moves down and p2 moves right\n int rr=solve2(x1,y1+1,x2,g,cpsf+cherries,m,n); //both moves right \n int rd=solve2(x1,y1+1,x2+1,g,cpsf+cherries,m,n); //p1 moves right and p2 moves down\n \n //We take maximum of 4 possiblities\n int max=Math.max(Math.max(dd,dr), Math.max(rr,rd));\n if(max==Integer.MIN_VALUE) return dp2[x1][y1][x2]=max;\n return dp2[x1][y1][x2]=cherries+=max;\n }\n}\n", + "title": "741. Cherry Pickup", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers. Return the maximum number of cherries you can collect by following the rules below : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 means the cell is empty, so you can pass through,", + "1 means the cell contains a cherry that you can pick up and pass through, or", + "-1 means the cell contains a thorn that blocks your way." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,-1],[1,0,-1],[1,1,1]]Output:5Explanation:The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.", + "image": "https://assets.leetcode.com/uploads/2020/12/14/grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,-1],[1,-1,1],[-1,1,1]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 360 ms (Top 100.00%) | Memory: 14 MB (Top 98.73%)\nclass Solution:\n def cherryPickup(self, grid):\n n = len(grid)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n dp[1][1] = grid[0][0]\n for m in range(1, (n << 1) - 1):\n for i in range(min(m, n - 1), max(-1, m - n), -1):\n for p in range(i, max(-1, m - n), -1):\n j, q = m - i, m - p\n if grid[i][j] == -1 or grid[p][q] == -1:\n dp[i + 1][p + 1] = -1\n else:\n dp[i + 1][p + 1] = max(dp[i + 1][p + 1], dp[i][p + 1], dp[i + 1][p], dp[i][p])\n if dp[i + 1][p + 1] != -1: dp[i + 1][p + 1] += grid[i][j] + (grid[p][q] if i != p else 0)\n return max(0, dp[-1][-1])", + "title": "741. Cherry Pickup", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell. You have two robots that can collect cherries for you: Return the maximum number of cherries collection using both robots by following the rules below : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Robot #1 is located at the top-left corner (0, 0) , and", + "Robot #2 is located at the top-right corner (0, cols - 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]Output:24Explanation:Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\nCherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\nTotal of cherries: 12 + 12 = 24.", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_1_1802.png" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]Output:28Explanation:Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\nCherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\nTotal of cherries: 17 + 11 = 28.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/sample_2_1802.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 609 ms (Top 95.65%) | Memory: 24.30 MB (Top 75.94%)\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n \n dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]\n \n def get_next_max(row, col_r1, col_r2):\n res = 0\n for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):\n for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):\n res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])\n\n return res\n \n for row in reversed(range(rows)):\n for col_r1 in range(min(cols, row + 2)):\n for col_r2 in range(max(0, cols - row - 1), cols):\n\n reward = grid[row][col_r1] + grid[row][col_r2]\n if col_r1 == col_r2:\n reward /= 2\n \n dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)\n \n return dp[0][1][cols]\n", + "title": "1463. Cherry Pickup II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row . Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_1.png", + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_3.png" + ], + "constraints": [ + "1 <= n <= 10^9", + "1 <= reservedSeats.length <= min(10*n, 10^4)", + "reservedSeats[i].length == 2", + "1 <= reservedSeats[i][0] <= n", + "1 <= reservedSeats[i][1] <= 10", + "All reservedSeats[i] are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]Output:4Explanation:The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 37 ms (Top 66.38%) | Memory: 70.8 MB (Top 57.25%)\nclass Solution {\n public int maxNumberOfFamilies(int n, int[][] reservedSeats) {\n Map seats = new HashMap<>();\n int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots\n\n for (int[] seat: reservedSeats) {\n int row = seat[0];\n int col = seat[1];\n int[] slots = seats.getOrDefault(row, new int[3]);\n\n if (col >= 2 && col <= 5) { // left slot\n slots[0] = 1;\n }\n if (col >= 4 && col <= 7) { // middle slot\n slots[1] = 1;\n }\n if (col >= 6 && col <= 9) { // right slot\n slots[2] = 1;\n }\n\n seats.put(seat[0], slots);\n }\n\n for (int[] slots: seats.values()) {\n int taken = slots[0] + slots[2];\n\n if (taken == 2) { // both slots at either ends are taken\n if (slots[1] == 0) { // check if middle slot not taken\n availableSlots--; // reduce availableslots by 1 since middle slot is available\n } else {\n availableSlots -= 2; // entire row not available - reduce by 2\n }\n } else if (taken == 1) { // one of the slots at either ends are taken\n availableSlots--; // reduce by 1 since either side of the slots not available\n } else {\n continue; // entire row is available - no need to reduce the available slots\n }\n }\n\n return availableSlots;\n }\n}", + "title": "1386. Cinema Seat Allocation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row . Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_1.png", + "https://assets.leetcode.com/uploads/2020/02/14/cinema_seats_3.png" + ], + "constraints": [ + "1 <= n <= 10^9", + "1 <= reservedSeats.length <= min(10*n, 10^4)", + "reservedSeats[i].length == 2", + "1 <= reservedSeats[i][0] <= n", + "1 <= reservedSeats[i][1] <= 10", + "All reservedSeats[i] are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]Output:4Explanation:The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxNumberOfFamilies(self, n, reservedSeats):\n \"\"\"\n :type n: int\n :type reservedSeats: List[List[int]]\n :rtype: int\n \"\"\"\n d = defaultdict(set)\n for row,seat in reservedSeats:\n d[row].add(seat)\n \n def row(i):\n a1 = not set((2,3,4,5)).intersection(d[i])\n a2 = not set((6,7,8,9)).intersection(d[i])\n if a1 and a2:\n return 2\n if a1 or a2:\n return 1\n return 1 if not set((4,5,6,7)).intersection(d[i]) else 0\n \n return sum((row(i) for i in d.keys())) + (n-len(d)) * 2\n\n", + "title": "1386. Cinema Seat Allocation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2) , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false . In other words, check if there is any point (x i , y i ) that belongs to the circle and the rectangle at the same time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= radius <= 2000", + "-10^4 <= xCenter, yCenter <= 10^4", + "-10^4 <= x1 < x2 <= 10^4", + "-10^4 <= y1 < y2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1Output:trueExplanation:Circle and rectangle share the point (1,0).", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_4_1728.png" + }, + { + "text": "Example 2: Input:radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1Output:false", + "image": null + }, + { + "text": "Example 3: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1Output:true", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_2_1728.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 38.18%) | Memory: 41.1 MB (Top 21.82%)\nclass Solution\n{\n public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2)\n {\n return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2)\n + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius;\n }\n}", + "title": "1401. Circle and Rectangle Overlapping", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2) , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return true if the circle and rectangle are overlapped otherwise return false . In other words, check if there is any point (x i , y i ) that belongs to the circle and the rectangle at the same time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= radius <= 2000", + "-10^4 <= xCenter, yCenter <= 10^4", + "-10^4 <= x1 < x2 <= 10^4", + "-10^4 <= y1 < y2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1Output:trueExplanation:Circle and rectangle share the point (1,0).", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_4_1728.png" + }, + { + "text": "Example 2: Input:radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1Output:false", + "image": null + }, + { + "text": "Example 3: Input:radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1Output:true", + "image": "https://assets.leetcode.com/uploads/2020/02/20/sample_2_1728.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n \n def find(a1, a2, aCenter):\n if a1 <= aCenter and aCenter <= a2:\n return 0 \n elif a1 > aCenter:\n return a1 - aCenter\n else:\n return aCenter - a2\n\n return (find(x1, x2, xCenter))**2 + (find(y1, y2, yCenter))**2 <= radius**2 \n\t```", + "title": "1401. Circle and Rectangle Overlapping", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a game involving a circular array of non-zero integers nums . Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i : Since the array is circular , you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Return true if there is a cycle in nums , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If nums[i] is positive, move nums[i] steps forward , and", + "If nums[i] is negative, move nums[i] steps backward ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,1,2,2]Output:trueExplanation:There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...\nThe cycle's length is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,2]Output:falseExplanation:The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-2,1,-1,-2,-2]Output:falseExplanation:The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 46.1%) | Memory: 40.11 MB (Top 41.3%)\n\nclass Solution {\n public boolean circularArrayLoop(int[] nums) {\n for (int i=0; i 0;\n int slow = i;\n int fast = i; \n do {\n slow = findNextIndex(nums, isForward, slow);\n fast = findNextIndex(nums, isForward, fast);\n if (fast != -1) {\n fast = findNextIndex(nums, isForward, fast);\n }\n } while (slow != -1 && fast != -1 && slow != fast);\n if (slow != -1 && slow == fast) {\n return true;\n }\n }\n return false;\n }\n private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {\n boolean direction = arr[currentIndex] >= 0;\n if (isForward != direction) {\n return -1;\n }\n int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;\n if (nextIndex < 0) {\n nextIndex += arr.length;\n }\n if (nextIndex == currentIndex) {\n nextIndex = -1;\n }\n return nextIndex;\n }\n}", + "title": "457. Circular Array Loop", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a game involving a circular array of non-zero integers nums . Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i : Since the array is circular , you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Return true if there is a cycle in nums , or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If nums[i] is positive, move nums[i] steps forward , and", + "If nums[i] is negative, move nums[i] steps backward ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,1,2,2]Output:trueExplanation:There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...\nThe cycle's length is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,2]Output:falseExplanation:The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-2,1,-1,-2,-2]Output:falseExplanation:The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n n = len(nums)\n for i in range(n):\n seen = set()\n minval = float('inf')\n maxval = float('-inf')\n j = i\n while j not in seen:\n seen.add(j)\n minval = min(minval, nums[j])\n maxval = max(maxval, nums[j])\n k = 1 + abs(nums[j]) // n\n j = (k * n + j + nums[j]) % n\n if j == i and len(seen) > 1 and (minval > 0 or maxval < 0):\n return True\n return False\n", + "title": "457. Circular Array Loop", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given 2 integers n and start . Your task is return any permutation p of (0,1,2.....,2^n -1) such that : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "p[0] = start", + "p[i] and p[i+1] differ by only one bit in their binary representation.", + "p[0] and p[2^n -1] must also differ by only one bit in their binary representation." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, start = 3Output:[3,2,0,1]Explanation:The binary representation of the permutation is (11,10,00,01). \nAll the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]", + "image": null + }, + { + "text": "Example 2: Input:n = 3, start = 2Output:[2,6,7,5,4,0,1,3]Explanation:The binary representation of the permutation is (010,110,111,101,100,000,001,011).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List circularPermutation(int n, int start) {\n List l = new ArrayList();\n int i=0;\n int len = (int)Math.pow(2,n);\n int[] arr = new int[len];\n while(i List[int]:\n gray_code = [x ^ (x >> 1) for x in range(2 ** n)]\n start_i = gray_code.index(start)\n return gray_code[start_i:] + gray_code[:start_i]", + "title": "1238. Circular Permutation in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:3Explanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.00 MB (Top 80.9%)\n\nclass Solution {\n public int climbStairs(int n) {\n int[] memo = new int[n + 1];\n return calculateWays(n, memo);\n }\n \n private int calculateWays(int n, int[] memo) {\n if (n == 1 || n == 2) {\n return n;\n }\n \n if (memo[n] != 0) {\n return memo[n];\n }\n \n memo[n] = calculateWays(n - 1, memo) + calculateWays(n - 2, memo);\n return memo[n];\n }\n}", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:3Explanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n memo ={}\n memo[1] = 1\n memo[2] = 2\n \n def climb(n):\n if n in memo: # if the recurssion already done before first take a look-up in the look-up table\n return memo[n]\n else: # Store the recurssion function in the look-up table and reuturn the stored look-up table function\n memo[n] = climb(n-1) + climb(n-2)\n return memo[n]\n \n return climb(n)", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: 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.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: 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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []Output:[]Explanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public void dfs(Node node , Node copy , Node[] visited){\n visited[copy.val] = copy;// store the current node at it's val index which will tell us that this node is now visited\n \n// now traverse for the adjacent nodes of root node\n for(Node n : node.neighbors){\n// check whether that node is visited or not\n// if it is not visited, there must be null\n if(visited[n.val] == null){\n// so now if it not visited, create a new node\n Node newNode = new Node(n.val);\n// add this node as the neighbor of the prev copied node\n copy.neighbors.add(newNode);\n// make dfs call for this unvisited node to discover whether it's adjacent nodes are explored or not\n dfs(n , newNode , visited);\n }else{\n// if that node is already visited, retrieve that node from visited array and add it as the adjacent node of prev copied node\n// THIS IS THE POINT WHY WE USED NODE[] INSTEAD OF BOOLEAN[] ARRAY\n copy.neighbors.add(visited[n.val]);\n }\n }\n \n }\n public Node cloneGraph(Node node) {\n if(node == null) return null; // if the actual node is empty there is nothing to copy, so return null\n Node copy = new Node(node.val); // create a new node , with same value as the root node(given node)\n Node[] visited = new Node[101]; // in this question we will create an array of Node(not boolean) why ? , because i have to add all the adjacent nodes of particular vertex, whether it's visited or not, so in the Node[] initially null is stored, if that node is visited, we will store the respective node at the index, and can retrieve that easily.\n Arrays.fill(visited , null); // initially store null at all places\n dfs(node , copy , visited); // make a dfs call for traversing all the vertices of the root node\n return copy; // in the end return the copy node\n }\n}\n", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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. 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: 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.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: 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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []Output:[]Explanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": " def cloneGraph(self, node: 'Node') -> 'Node':\n \n if node == None:\n return None\n \n new_node = Node(node.val, [])\n \n visited = set()\n \n q = [[node, new_node]]\n visited.add(node.val)\n \n adj_map = {}\n \n adj_map[node] = new_node\n \n while len(q) != 0:\n \n curr = q.pop(0)\n \n \n for n in curr[0].neighbors:\n \n # if n.val not in visited:\n if n not in adj_map and n is not None:\n new = Node(n.val, [])\n curr[1].neighbors.append(new)\n adj_map[n] = new\n else:\n curr[1].neighbors.append(adj_map[n])\n \n if n.val not in visited:\n q.append([n, adj_map[n]])\n visited.add(n.val) \n \n \n return new_node\n\n", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target . If there are multiple, return the lower one. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There must be exactly one ice cream base.", + "You can add one or more types of topping or have no toppings at all.", + "There are at most two of each type of topping." + ], + "examples": [ + { + "text": "Example 1: Input:baseCosts = [1,7], toppingCosts = [3,4], target = 10Output:10Explanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.", + "image": null + }, + { + "text": "Example 2: Input:baseCosts = [2,3], toppingCosts = [4,5,100], target = 18Output:17Explanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.", + "image": null + }, + { + "text": "Example 3: Input:baseCosts = [3,10], toppingCosts = [2,5], target = 9Output:8Explanation:It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.0%) | Memory: 39.60 MB (Top 90.1%)\n\nclass Solution {\n /** Closest cost result */\n int closestCost = Integer.MAX_VALUE;\n /** Difference between closest cost result and target so far */\n int closestCostDiff = Integer.MAX_VALUE;\n\n public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {\n for (int base : baseCosts) {\n dfs(toppingCosts, 0, base, target);\n }\n return closestCost;\n }\n\n public void dfs(int[] toppingCosts, int toppingIndex, int cost, int target) {\n int costDiff = Math.abs(target - cost);\n if (costDiff < closestCostDiff || (costDiff == closestCostDiff && cost < closestCost)) {\n closestCostDiff = costDiff;\n closestCost = cost;\n }\n \n // Since toppings are all positive cost, stop dfs early if cost exceeds target\n if (toppingIndex >= toppingCosts.length || cost > target)\n return;\n\n dfs(toppingCosts, toppingIndex + 1, cost, target);\n dfs(toppingCosts, toppingIndex + 1, cost + toppingCosts[toppingIndex], target);\n dfs(toppingCosts, toppingIndex + 1, cost + 2 * toppingCosts[toppingIndex], target);\n }\n}", + "title": "1774. Closest Dessert Cost", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target . If there are multiple, return the lower one. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There must be exactly one ice cream base.", + "You can add one or more types of topping or have no toppings at all.", + "There are at most two of each type of topping." + ], + "examples": [ + { + "text": "Example 1: Input:baseCosts = [1,7], toppingCosts = [3,4], target = 10Output:10Explanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.", + "image": null + }, + { + "text": "Example 2: Input:baseCosts = [2,3], toppingCosts = [4,5,100], target = 18Output:17Explanation:Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.", + "image": null + }, + { + "text": "Example 3: Input:baseCosts = [3,10], toppingCosts = [2,5], target = 9Output:8Explanation:It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n self.ans = self.diff = float('inf')\n \n n = len(baseCosts)\n m = len(toppingCosts)\n \n \n def solve(sum, target, indx):\n if abs(sum - target) < self.diff:\n self.diff = abs(sum - target)\n self.ans = sum\n elif abs(sum - target) == self.diff:\n self.ans = min(self.ans, sum)\n \n \n if indx == m:\n return\n \n i = indx\n for count in range(3):\n sum += toppingCosts[i]*count\n solve(sum,target,i+1)\n sum -= toppingCosts[i]*count\n \n for i in baseCosts:\n solve(i, target, 0)\n return self.ans\n", + "title": "1774. Closest Dessert Cost", + "topic": "Stack" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer num , find the closest two integers in absolute difference whose product equals num + 1 or num + 2 . Return the two integers in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 8Output:[3,3]Explanation:For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.", + "image": null + }, + { + "text": "Example 2: Input:num = 123Output:[5,25]", + "image": null + }, + { + "text": "Example 3: Input:num = 999Output:[40,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] closestDivisors(int num) {\n int ans[]=new int[2];\n double a=Math.sqrt(num+1);\n double b=Math.sqrt(num+2);\n if(num==1){\n ans[0]=1;\n ans[1]=2;\n return ans;\n }\n else if(a%1==0){\n ans[0]=(int)a;\n ans[1]=(int)b;\n return ans;\n }\n else if(b%1==0){\n ans[0]=(int)b;\n ans[1]=(int)b;\n return ans;\n }\n else{\n int m=(int)Math.sqrt(num);\n int diff1=Integer.MAX_VALUE;\n int y=0,z=0,w=0,f=0;\n for(int i=2;i<=m;i++){\n if((num+1)%i==0){\n y=i;\n z=(num+1)/y;\n int r=Math.abs(y-z);\n if(r List[int]:\n\t\tfor i in range(int((num+2) ** (0.5)), 0, -1): \n\t\t\tif not (num+1) % i: return [i, (num+1)//i] \n\t\t\tif not (num+2) % i: return [i, (num+2)//i] \n\t\treturn []\n", + "title": "1362. Closest Divisors", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomId i , size i ] denotes that there is a room with room number roomId i and size equal to size i . Each roomId i is guaranteed to be unique . You are also given k queries in a 2D array queries where queries[j] = [preferred j , minSize j ] . The answer to the j th query is the room number id of a room such that: If there is a tie in the absolute difference, then use the room with the smallest such id . If there is no such room , the answer is -1 . Return an array answer of length k where answer[j] contains the answer to the j th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The room has a size of at least minSize j , and", + "abs(id - preferred j ) is minimized , where abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]Output:[3,-1,3]Explanation:The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]Output:[2,1,3]Explanation:The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 164 ms (Top 39.53%) | Memory: 127.2 MB (Top 83.72%)\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decreasing order of room size\n Arrays.sort(indexes, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); // Sort by decreasing order of query minSize\n TreeSet roomIdsSoFar = new TreeSet<>();\n int[] ans = new int[k];\n int i = 0;\n for (int index : indexes) {\n while (i < n && rooms[i][1] >= queries[index][1]) { // Add id of the room which its size >= query minSize\n roomIdsSoFar.add(rooms[i++][0]);\n }\n ans[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0]);\n }\n return ans;\n }\n int searchClosetRoomId(TreeSet treeSet, int preferredId) {\n Integer floor = treeSet.floor(preferredId);\n Integer ceiling = treeSet.ceiling(preferredId);\n int ansAbs = Integer.MAX_VALUE, ans = -1;\n if (floor != null) {\n ans = floor;\n ansAbs = Math.abs(preferredId - floor);\n }\n if (ceiling != null && ansAbs > Math.abs(preferredId - ceiling)) {\n ans = ceiling;\n }\n return ans;\n }\n}", + "title": "1847. Closest Room", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomId i , size i ] denotes that there is a room with room number roomId i and size equal to size i . Each roomId i is guaranteed to be unique . You are also given k queries in a 2D array queries where queries[j] = [preferred j , minSize j ] . The answer to the j th query is the room number id of a room such that: If there is a tie in the absolute difference, then use the room with the smallest such id . If there is no such room , the answer is -1 . Return an array answer of length k where answer[j] contains the answer to the j th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The room has a size of at least minSize j , and", + "abs(id - preferred j ) is minimized , where abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]Output:[3,-1,3]Explanation:The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]Output:[2,1,3]Explanation:The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1741 ms (Top 100.0%) | Memory: 67.86 MB (Top 93.7%)\n\nclass Solution:\n def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:\n ans = [0] * len(queries)\n \n # sort queries to handle largest size queries first\n q = deque(sorted([(size, room, i) for i, (room, size) in enumerate(queries)], key=lambda a: (-a[0], a[1], a[2])))\n\n # sort rooms by descending size\n rooms = deque(sorted(rooms, key=lambda x: -x[1]))\n\n # current available room ids\n cands = []\n \n \n while q:\n size, room, i = q.popleft()\n # add room ids to candidates as long as top of room size meet the requirements\n while rooms and rooms[0][1] >= size:\n bisect.insort(cands, rooms.popleft()[0])\n \n # if no room size available, return -1\n if not cands: ans[i] = -1\n \n # else use bisect to find optimal room ids\n else:\n loc = bisect.bisect_left(cands, room)\n if loc == 0: ans[i] = cands[loc]\n elif loc == len(cands): ans[i] = cands[-1]\n else: ans[i] = cands[loc - 1] if room - cands[loc - 1] <= cands[loc] - room else cands[loc]\n \n return ans", + "title": "1847. Closest Room", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums and an integer goal . You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal . That is, if the sum of the subsequence's elements is sum , then you want to minimize the absolute difference abs(sum - goal) . Return the minimum possible value of abs(sum - goal) . Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 40", + "-10^7 <= nums[i] <= 10^7", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,-7,3,5], goal = 6Output:0Explanation:Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,-9,15,-2], goal = -5Output:1Explanation:Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], goal = -7Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] arr;\n public int minAbsDifference(int[] nums, int goal) {\n arr = nums;\n int n = nums.length;\n \n \n List first = new ArrayList<>();\n List second = new ArrayList<>();\n \n generate(0,n/2,0, first); //generate all possible subset sums from half the array\n generate(n/2, n , 0, second);//generate all possible subset sums from the second half of the array\n \n \n Collections.sort(first);\n int ans = Integer.MAX_VALUE;\n \n \n for(int secondSetSum : second ) {\n int left = goal - secondSetSum; // How far off are we from the desired goal?\n \n if(first.get(0) > left) { // all subset sums from first half are too big => Choose the smallest\n ans = (int)(Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal)));\n continue;\n }\n if(first.get(first.size() - 1) < left) { // all subset sums from first half are too small => Choose the largest\n ans = (int)(Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal)));\n continue;\n }\n int pos = Collections.binarySearch(first, left);\n if(pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal\n return 0;\n else // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1)\n pos = -1 * (pos + 1);\n int low = pos - 1;\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(low) - goal)); // Checking for the floor value (largest sum < goal)\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(pos) - goal)); //Checking for the ceiling value (smallest sum > goal)\n }\n return ans;\n }\n\n /**\n * Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick \n */\n void generate(int i, int end, int sum, List listOfSubsetSums) {\n if (i == end) {\n listOfSubsetSums.add(sum); //add\n return;\n }\n generate(i + 1, end, sum + arr[i], set);\n generate(i + 1, end, sum, set);\n \n }\n \n \n \n}\n", + "title": "1755. Closest Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer goal . You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal . That is, if the sum of the subsequence's elements is sum , then you want to minimize the absolute difference abs(sum - goal) . Return the minimum possible value of abs(sum - goal) . Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 40", + "-10^7 <= nums[i] <= 10^7", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,-7,3,5], goal = 6Output:0Explanation:Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,-9,15,-2], goal = -5Output:1Explanation:Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], goal = -7Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n\n # When goal 0 we can just choose no elements \n if goal == 0: return 0\n\n n = len(nums)\n mid = n // 2\n # Split the list in 2 parts and then find all possible subset sums \n # T = O(2^n/2) to build all subset sums\n leftList = nums[:mid]\n leftSums = []\n rightList = nums[mid:]\n rightSums = []\n\n # T = O(2^n/2) to build all subset sums (we only consider half list)\n def buildSubsetSums(usedNums, numsToChooseFrom, ind, storeIn):\n if ind == len(numsToChooseFrom):\n # We also keep elements with sum 0 to deal with cases like this where we don't select nums\n # List: [1,2,3], Target: -7 (choosing no elements will give a sum close to goal)\n # We can also have cases where we want to take only 1 element from the list\n # so sum 0 for left and right list needs to be an option\n storeIn.append(sum(usedNums))\n return \n\n usedNums.append(numsToChooseFrom[ind])\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n usedNums.pop()\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n\n\n buildSubsetSums([], leftList, 0, leftSums)\n buildSubsetSums([], rightList, 0, rightSums)\n # 2^n/2 log(2^n/2) = n/2 * 2^n/2 time to sort\n rightSums.sort()\n\n diff = float('inf')\n\n # Loop runs 2^n/2 times and inside binary search tale n/2 time \n # So total time is n/2 * 2^n/2\n for leftSum in leftSums:\n complement = goal - leftSum\n # Bisect left takes log(2^n/2) = n/2 search time\n idx = bisect.bisect_left(rightSums, complement)\n\n for i in [idx - 1, idx, idx + 1]:\n if 0 <= i < len(rightSums):\n finalSum = leftSum + rightSums[i]\n diff = min(diff, abs(goal - finalSum))\n \n # Over all time complexity is - n/2 * 2^n/2\n # 1. Making subset sums will take - 2^n/2\n # 2. Sorting right list takes - 2^n/2 * n/2\n # 3. Iterating one list and finding closest complement in other \n # takes n/2 * 2^n/2\n # Space will be O(n/2) for the list and call stack for building subset \n return diff\n\n", + "title": "1755. Closest Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The factorial of a positive integer n is the product of all positive integers less than or equal to n . We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*' , divide '/' , add '+' , and subtract '-' in this order. However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11 . Given an integer n , return the clumsy factorial of n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:7Explanation:7 = 4 * 3 / 2 + 1", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:12Explanation:12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 67.15%) | Memory: 13.9 MB (Top 59.65%)\nclass Solution:\n def clumsy(self, n: int) -> int:\n if(n>2):\n sum=n*(n-1)//(n-2)+(n-3)\n else:\n sum=n\n for i in range(n-4,0,-4):\n if(i<3):\n sum=sum-i\n break;\n sum=sum-(i)*(i-1)//(i-2)+(i-3)\n\n return sum", + "title": "1006. Clumsy Factorial", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 300", + "1 <= coins[i] <= 5000", + "All the values of coins are unique .", + "0 <= amount <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:amount = 5, coins = [1,2,5]Output:4Explanation:there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1", + "image": null + }, + { + "text": "Example 2: Input:amount = 3, coins = [2]Output:0Explanation:the amount of 3 cannot be made up just with coins of 2.", + "image": null + }, + { + "text": "Example 3: Input:amount = 10, coins = [10]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 47.6%) | Memory: 43.93 MB (Top 22.2%)\n\nclass Solution {\n public int coinChange(int[] coins, int amount) {\n int m=coins.length,n=amount;\n int dp[][]=new int[m+1][n+1];\n for(int j=0;j<=n;j++){\n dp[0][j]=0;\n }\n for(int i=0;i<=m;i++){\n dp[i][0]=0;\n }\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n int t1 = Integer.MAX_VALUE;\n if ((i-1) == 0) {\n if (j % coins[i-1] == 0) {\n dp[i][j]= j / coins[i-1];\n } else {\n dp[i][j]= (int)1e9;\n }\n } \n else {\n int t2 = dp[i-1][j];\n if (coins[i-1] <= j) {\n t1 = dp[i][j-coins[i-1]] + 1; \n }\n dp[i][j]= Math.min(t1, t2);\n }\n }\n }\n if(dp[m][n]>=1e9)\n return -1;\n else\n return dp[m][n];\n }\n }\n \n ", + "title": "518. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 300", + "1 <= coins[i] <= 5000", + "All the values of coins are unique .", + "0 <= amount <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:amount = 5, coins = [1,2,5]Output:4Explanation:there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1", + "image": null + }, + { + "text": "Example 2: Input:amount = 3, coins = [2]Output:0Explanation:the amount of 3 cannot be made up just with coins of 2.", + "image": null + }, + { + "text": "Example 3: Input:amount = 10, coins = [10]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 724 ms (Top 91.98%) | Memory: 17.70 MB (Top 44.11%)\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n numCoins = len(coins)\n \n # Values in this array equal the number of coins needed to achieve the cost of the index\n minCoins = [amount + 1] * (amount + 1)\n minCoins[0] = 0\n \n # Loop through every needed amount\n for i in range(amount + 1):\n # Loop through every coin value\n for coin in coins:\n # Check that the coin is not bigger than the current amount\n if coin <= i:\n # minCoins[i]: number of coins needed to make amount i\n # minCoins[i-coin]: number of coins needed to make the amount before adding \n # the current coin to it (+1 to add the current coin)\n minCoins[i] = min(minCoins[i], minCoins[i-coin] + 1)\n \n # Check if any combination of coins was found to create the amount\n if minCoins[amount] == amount + 1:\n return -1\n \n # Return the optimal number of coins to create the amount\n return minCoins[amount]\n", + "title": "518. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid , and three integers row , col , and color . Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color . Return the final grid . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j], color <= 1000", + "0 <= row < m", + "0 <= col < n" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3Output:[[3,3],[3,2]]", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3Output:[[1,3,3],[2,3,3]]", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2Output:[[2,2,2],[2,1,2],[2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] colorBorder(int[][] grid, int row, int col, int color) {\n dfs(grid,row,col,grid[row][col]);\n for(int i = 0;i=grid.length||coldash>=grid[0].length||\n Math.abs(grid[rowdash][coldash])!=color)\n {\n continue;\n }\n count++;\n \n if(grid[rowdash][coldash]==color)\n {\n dfs(grid,rowdash,coldash,color);\n }\n \n }\n if(count==4)\n {\n grid[row][col] = color;\n }\n \n }\n}\n", + "title": "1034. Coloring A Border", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid , and three integers row , col , and color . Each value in the grid represents the color of the grid square at that location. Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions. The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color . Return the final grid . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j], color <= 1000", + "0 <= row < m", + "0 <= col < n" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3Output:[[3,3],[3,2]]", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3Output:[[1,3,3],[2,3,3]]", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2Output:[[2,2,2],[2,1,2],[2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 136 ms (Top 91.96%) | Memory: 14.4 MB (Top 28.67%)\n\nclass Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n\n rows, cols = len(grid), len(grid[0])\n border_color = grid[row][col]\n border = []\n\n # Check if a node is a border node or not\n def is_border(r, c):\n if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n return True\n\n for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n nr, nc = r + dr, c + dc\n if grid[nr][nc] != border_color:\n return True\n return False\n\n def dfs(r, c):\n if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color:\n return\n visited.add((r, c))\n\n if is_border(r, c):\n border.append((r, c))\n\n dfs(r + 1, c)\n dfs(r - 1, c)\n dfs(r, c + 1)\n dfs(r, c - 1)\n\n visited = set()\n dfs(row, col)\n for r, c in border:\n grid[r][c] = color\n return grid", + "title": "1034. Coloring A Border", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "1 <= candidates[i] <= 200", + "All elements of candidates are distinct .", + "1 <= target <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7Output:[[2,2,3],[7]]Explanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8Output:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 69.68%) | Memory: 45.9 MB (Top 24.67%)\nclass Solution {\n public List> combinationSum(int[] candidates, int target) {\n List cur = new ArrayList<>();\n List> result = new ArrayList<>();\n Arrays.sort(candidates);\n dfs(0, candidates, target, 0, cur, result);\n return result;\n }\n public void dfs(int start, int[] candidates, int target, int sum, List cur, List> result){\n if(sum == target){\n result.add(new ArrayList<>(cur));\n return;\n }\n for(int i = start; i < candidates.length; i++) {\n if(sum + candidates[i] <= target) {\n cur.add(candidates[i]);\n dfs(i, candidates, target, sum + candidates[i], cur, result);\n cur.remove((cur.size()- 1));\n }\n }\n return;\n }\n}", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "1 <= candidates[i] <= 200", + "All elements of candidates are distinct .", + "1 <= target <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7Output:[[2,2,3],[7]]Explanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8Output:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 82.54%) | Memory: 14.1 MB (Top 72.96%)\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n\n path = []\n answer = []\n def dp(idx, total):\n if total == target:\n answer.append(path[:])\n return\n if total > target:\n return\n\n for i in range(idx, len(candidates)):\n path.append(candidates[i])\n dp(i, total + candidates[i])\n path.pop()\n\n dp(0, 0)\n return answer\n", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8Output:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5Output:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 12.41%) | Memory: 43.5 MB (Top 81.01%)\nclass Solution {\n public List> combinationSum2(int[] candidates, int target) {\n List> res = new ArrayList<>();\n List path = new ArrayList<>();\n // O(nlogn)\n Arrays.sort(candidates);\n boolean[] visited = new boolean[candidates.length];\n helper(res, path, candidates, visited, target, 0);\n return res;\n }\n private void helper(List> res,\n List path, int[] candidates,\n boolean[] visited, int remain, int currIndex\n ){\n if (remain == 0){\n res.add(new ArrayList<>(path));\n return;\n }\n if (remain < 0){\n return;\n }\n\n for(int i = currIndex; i < candidates.length; i++){\n if (visited[i]){\n continue;\n }\n if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){\n continue;\n }\n int curr = candidates[i];\n path.add(curr);\n visited[i] = true;\n helper(res, path, candidates, visited, remain - curr, i + 1);\n path.remove(path.size() - 1);\n\n visited[i] = false;\n }\n }\n}", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8Output:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5Output:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 204 ms (Top 15.17%) | Memory: 14.1 MB (Top 23.77%)\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n res = []\n def dfs(nums,summ,curr):\n if summ>=target:\n if summ == target:\n res.append(curr)\n return\n for i in range(len(nums)):\n if i !=0 and nums[i]==nums[i-1]:\n continue\n dfs(nums[i+1:],summ+nums[i],curr+[nums[i]])\n dfs(sorted(candidates),0,[])\n return res", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7Output:[[1,2,4]]Explanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9Output:[[1,2,6],[1,3,5],[2,3,4]]Explanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1Output:[]Explanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.54%) | Memory: 41.2 MB (Top 80.80%)\n\n//Recursion\n\nclass Solution {\n public List> combinationSum3(int k, int n) {\n List> ans = new ArrayList>();\n //int[] arr = new int{1,2,3,4,5,6,7,8,9};\n List ds = new ArrayList<>();\n helper(1, n, k, ds, ans);\n return ans;\n }\n private static void helper(int i, int tar, int k, List ds, List> ans){\n //base\n if(k == 0) {\n if(tar == 0){\n ans.add(new ArrayList<>(ds));\n }\n return;\n }\n if(tar == 0) return; //bcz if k is not zero and tar is zero then no possible valid combination\n if(i > tar) return;\n if(i > 9) return;\n\n //Take\n if(i <= tar) {\n ds.add(i);\n helper(i+1, tar - i, k-1 , ds, ans);\n ds.remove(ds.size()-1);\n }\n // Not take\n helper(i+1 , tar, k , ds, ans);\n\n return;\n }\n}", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7Output:[[1,2,4]]Explanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9Output:[[1,2,6],[1,3,5],[2,3,4]]Explanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1Output:[]Explanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n \n def solve(self,k,target,ans,temp,idx,nums):\n \n if idx==len(nums):\n if target==0 and k==0:\n ans.append(list(temp))\n return\n \n if nums[idx]<=target:\n \n temp.append(nums[idx])\n self.solve(k-1,target-nums[idx],ans,temp,idx+1,nums)\n temp.pop()\n \n self.solve(k,target,ans,temp,idx+1,nums)\n \n\n \n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n \n ans = []\n temp = []\n idx = 0\n nums = list(range(1,10))\n \n self.solve(k,n,ans,temp,idx,nums)\n return ans\n \n", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of distinct integers nums and a target integer target , return the number of possible combinations that add up to target . The test cases are generated so that the answer can fit in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 1000", + "All the elements of nums are unique .", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], target = 4Output:7Explanation:The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9], target = 3Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int combinationSum4(int[] nums, int target) {\n Integer[] memo = new Integer[target + 1];\n return recurse(nums, target, memo);\n }\n \n public int recurse(int[] nums, int remain, Integer[] memo){\n \n if(remain < 0) return 0;\n if(memo[remain] != null) return memo[remain];\n if(remain == 0) return 1;\n \n int ans = 0;\n for(int i = 0; i < nums.length; i++){\n ans += recurse(nums, remain - nums[i], memo);\n }\n \n memo[remain] = ans;\n return memo[remain];\n }\n}\n", + "title": "377. Combination Sum IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of distinct integers nums and a target integer target , return the number of possible combinations that add up to target . The test cases are generated so that the answer can fit in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 1000", + "All the elements of nums are unique .", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], target = 4Output:7Explanation:The possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9], target = 3Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n dp = [0] * (target+1)\n dp[0] = 1\n for i in range(1, target+1):\n for num in nums: \n num_before = i - num\n if num_before >= 0:\n dp[i] += dp[num_before]\n return dp[target]\n", + "title": "377. Combination Sum IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2Output:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Explanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1Output:[[1]]Explanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combine(int n, int k) {\n List> subsets=new ArrayList<>();\n generatesubsets(1,n,new ArrayList(),subsets,k);\n return subsets;\n }\n void generatesubsets(int start,int n,List current,List> subsets,int k){\n if(current.size()==k){\n subsets.add(new ArrayList(current));\n }\n for(int i=start;i<=n;i++){\n current.add(i);\n generatesubsets(i+1,n,current,subsets,k);\n current.remove(current.size()-1);\n }\n }\n}\n", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2Output:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Explanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1Output:[[1]]Explanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return itertools.combinations(range(1, n+1), k)", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s . For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c' , which has a frequency of 2. You are given an array of strings words and another array of query strings queries . For each query queries[i] , count the number of words in words such that f(queries[i]) < f(W) for each W in words . Return an integer array answer , where each answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 2000", + "1 <= words.length <= 2000", + "1 <= queries[i].length, words[i].length <= 10", + "queries[i][j] , words[i][j] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"cbd\"], words = [\"zaaaz\"]Output:[1]Explanation:On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]Output:[1,2]Explanation:On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.83%) | Memory: 46.8 MB (Top 47.53%)\nclass Solution {\n public int[] numSmallerByFrequency(String[] queries, String[] words) {\n int[] ans = new int[queries.length];\n int[] freq = new int[words.length];\n for (int i = 0; i < words.length; i++) {\n freq[i] = freqOfSmallest(words[i]);\n }\n Arrays.sort(freq);\n int k = 0;\n for (String query : queries) {\n int target = freqOfSmallest(query);\n ans[k++] = binarySearch(freq, target);\n }\n return ans;\n }\n public int freqOfSmallest(String s) {\n int[] freq = new int[26];\n char min = 'z';\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n freq[c - 'a'] += 1;\n if (c < min) {\n min = c;\n }\n }\n return freq[min - 'a'];\n }\n public int binarySearch(int[] arr, int target) {\n int idx = arr.length;\n int lo = 0;\n int hi = idx - 1;\n int mid;\n while (lo <= hi) {\n mid = (lo + hi) / 2;\n if (arr[mid] <= target) {\n lo = mid + 1;\n } else {\n idx = mid;\n hi = mid - 1;\n }\n }\n return arr.length - idx;\n }\n}", + "title": "1170. Compare Strings by Frequency of the Smallest Character", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s . For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c' , which has a frequency of 2. You are given an array of strings words and another array of query strings queries . For each query queries[i] , count the number of words in words such that f(queries[i]) < f(W) for each W in words . Return an integer array answer , where each answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 2000", + "1 <= words.length <= 2000", + "1 <= queries[i].length, words[i].length <= 10", + "queries[i][j] , words[i][j] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [\"cbd\"], words = [\"zaaaz\"]Output:[1]Explanation:On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").", + "image": null + }, + { + "text": "Example 2: Input:queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]Output:[1,2]Explanation:On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n def _f(s):\n d = Counter(s)\n d =dict(sorted(d.items(), key=lambda item: item[0]))\n for x in d:\n return d[x]\n \n freq = []\n for w in words:\n n1 = _f(w)\n freq.append(n1)\n \n freq.sort(reverse=True)\n\n res = []\n for q in queries:\n n = _f(q)\n c=0\n for n1 in freq:\n if n < n1:\n c+=1\n else:\n break\n res.append(c)\n \n return res\n", + "title": "1170. Compare Strings by Frequency of the Smallest Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two version numbers, version1 and version2 , compare them. Version numbers consist of one or more revisions joined by a dot '.' . Each revision consists of digits and may contain leading zeros . Every revision contains at least one character . Revisions are 0-indexed from left to right , with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order . Revisions are compared using their integer value ignoring any leading zeros . This means that revisions 1 and 001 are considered equal . If a version number does not specify a revision at an index, then treat the revision as 0 . For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1 . Return the following: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [], + "examples": [ + { + "text": "Example 1: Input:version1 = \"1.01\", version2 = \"1.001\"Output:0Explanation:Ignoring leading zeroes, both \"01\" and \"001\" represent the same integer \"1\".", + "image": null + }, + { + "text": "Example 2: Input:version1 = \"1.0\", version2 = \"1.0.0\"Output:0Explanation:version1 does not specify revision 2, which means it is treated as \"0\".", + "image": null + }, + { + "text": "Example 3: Input:version1 = \"0.1\", version2 = \"1.1\"Output:-1Explanation:version1's revision 0 is \"0\", while version2's revision 0 is \"1\". 0 < 1, so version1 < version2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compareVersion(String version1, String version2) {\n\t//Here we are going to Split the numbers by . but since we cannot do that in java we will replace . with # and then do it \n version1=version1.replace('.', '#');\n version2=version2.replace('.', '#');\n \n String v1[]=version1.split(\"#\");\n String v2[]=version2.split(\"#\");\n \n int i=0;\n \n\t\t\n while(ii2){\n return 1;\n }\n i++;\n }\n\t\t//if all the statments are false then at last we can say that they are equal\n return 0;\n }\n String removezero(String s){\n String result =\"\";\n int i =0;\n while(i int:\n v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.'))) \n for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):\n if rev1 == rev2:\n continue\n\n return -1 if rev1 < rev2 else 1 \n\n return 0", + "title": "165. Compare Version Numbers", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer n , return its complement . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:0Explanation:7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.", + "image": null + }, + { + "text": "Example 3: Input:n = 10Output:5Explanation:10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 20.2%) | Memory: 39.34 MB (Top 43.8%)\n\nclass Solution {\n public int bitwiseComplement(int n) {\n String bin = Integer.toBinaryString(n);\n String res = \"\";\n for(char c :bin.toCharArray())\n {\n if( c == '1')\n res += \"0\";\n else\n res += \"1\";\n }\n return Integer.parseInt(res, 2);\n }\n}", + "title": "1009. Complement of Base 10 Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer n , return its complement . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:0Explanation:7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.", + "image": null + }, + { + "text": "Example 3: Input:n = 10Output:5Explanation:10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 52.6%) | Memory: 17.10 MB (Top 12.47%)\n\nclass Solution:\n def bitwiseComplement(self, n: int) -> int:\n cnt=0\n ans=0\n if n==0:\n return 1\n while n>0:\n if n&1:\n cnt+=1\n else:\n ans =ans +(2**cnt)\n cnt+=1\n n=n>>1\n return ans\n", + "title": "1009. Complement of Base 10 Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class: Example 1:", + "description_images": [], + "constraints": [ + "CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.", + "int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode .", + "TreeNode get_root() Returns the root node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n[[[1, 2]], [3], [4], []]Output[null, 1, 2, [1, 2, 3, 4]]ExplanationCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3); // return 1\ncBTInserter.insert(4); // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]", + "image": "https://assets.leetcode.com/uploads/2021/08/03/lc-treeinsert.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 23.02%) | Memory: 47.3 MB (Top 32.61%)\nclass CBTInserter {\n\n private TreeNode root;\n private int total;\n\n private int count(TreeNode root) {\n if (root == null) return 0;\n return 1+count(root.left)+count(root.right);\n }\n\n public CBTInserter(TreeNode root) {\n this.root = root;\n total = count(root);\n }\n\n private int insertBinary(int val, int k, int right) {\n int left = 0;\n var ptr = root;\n while (left < right) {\n if (left == right -1) {\n if (ptr.left == null) ptr.left = new TreeNode(val);\n else ptr.right = new TreeNode(val);\n return ptr.val;\n }\n int mid = (right-left) / 2 + left;\n if (mid >= k ) {\n ptr = ptr.left;\n right = mid;\n } else if (mid < k) {\n left = mid+1;\n ptr = ptr.right;\n }\n }\n return 0;\n }\n\n public int insert(int val) {\n int depth = 0;\n int n = total;\n while(n > 0) {\n depth++;\n n /= 2;\n }\n if ((1< int:\n \n parent = self.parent_keeper[0]\n \n\t\t# Insert with leftward compact, to meet the definition of complete binary tree\n\t\t\n if not parent.left:\n parent.left = TreeNode( v )\n self.parent_keeper.append( parent.left )\n else:\n parent.right = TreeNode( v )\n self.parent_keeper.append( parent.right )\n \n # current parent is completed with two child now, pop parent from parent keeper on the head\n self.parent_keeper.popleft()\n \n return parent.val\n \n\n def get_root(self) -> TreeNode:\n \n return self.root\n", + "title": "919. Complete Binary Tree Inserter", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A complex number can be represented as a string on the form \" real + imaginary i\" where: Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "real is the real part and is an integer in the range [-100, 100] .", + "imaginary is the imaginary part and is an integer in the range [-100, 100] .", + "i 2 == -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"1+1i\", num2 = \"1+1i\"Output:\"0+2i\"Explanation:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"1+-1i\", num2 = \"1+-1i\"Output:\"0+-2i\"Explanation:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String complexNumberMultiply(String num1, String num2) {\n int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+')));\n int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1));\n int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+')));\n int val4 = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1));\n \n return \"\" + (val1*val3 - val2*val4) + \"+\" + (val1*val4 + val3*val2) + \"i\";\n }\n}\n", + "title": "537. Complex Number Multiplication", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A complex number can be represented as a string on the form \" real + imaginary i\" where: Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "real is the real part and is an integer in the range [-100, 100] .", + "imaginary is the imaginary part and is an integer in the range [-100, 100] .", + "i 2 == -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"1+1i\", num2 = \"1+1i\"Output:\"0+2i\"Explanation:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"1+-1i\", num2 = \"1+-1i\"Output:\"0+-2i\"Explanation:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n i1=num1.index('+')\n i2=num2.index('+')\n a=int(num1[0:i1])\n x=int(num2[0:i2])\n b=int(num1[i1+1:len(num1)-1])\n y=int(num2[i2+1:len(num2)-1])\n ans1=a*x+(-1)*b*y\n ans2=a*y+b*x\n return str(ans1)+'+'+(str(ans2)+'i')", + "title": "537. Complex Number Multiplication", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words ( without duplicates ), return all the concatenated words in the given list of words . A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= words[i].length <= 30", + "words[i] consists of only lowercase English letters.", + "All the strings of words are unique .", + "1 <= sum(words[i].length) <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]Output:[\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]Explanation:\"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cat\",\"dog\",\"catdog\"]Output:[\"catdog\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 46.55%) | Memory: 48.10 MB (Top 75.28%)\n\nclass Solution {\npublic List findAllConcatenatedWordsInADict(String[] words) {\n //sort the array in asc order of word length, since longer words are formed by shorter words.\n Arrays.sort(words, (a,b) -> a.length() - b.length());\n\n List result = new ArrayList<>();\n\n //list of shorter words \n HashSet preWords = new HashSet<>();\n\n for(int i=0; i< words.length; i++){\n //Word Break-I problem.\n if(topDown(words[i], preWords, 0, new Boolean[words[i].length()])) {\n result.add(words[i]);\n }\n preWords.add(words[i]);\n }\n return result;\n }\n\nprivate boolean topDown(String s, HashSet wordDict, int startIndex, Boolean[] memo) {\n if(wordDict.isEmpty()) {\n return false;\n }\n // if we reach the beyond the string, then return true\n // s = \"leetcode\" when \"code\" is being checked in the IF() of the loop, we reach endIndex == s.length(), \n // and wordDict.contains(\"code\") => true and topDown(s, wordDict, endIndex, memo) needs to return true. \n if(startIndex == s.length()) {\n return true;\n }\n \n // memo[i] = true means => that the substring from index i can be segmented. \n // memo[startIndex] means => wordDict contains substring from startIndex and it can be segemented.\n if(memo[startIndex] != null) { //Boolean[] array's default value is \"null\"\n return memo[startIndex];\n }\n \n for(int endIndex = startIndex + 1; endIndex <= s.length(); endIndex++) {\n if(wordDict.contains(s.substring(startIndex, endIndex)) && topDown(s, wordDict, endIndex, memo)) {\n memo[startIndex] = true;\n return true;\n }\n }\n memo[startIndex] = false;\n return false;\n}\n} \n", + "title": "472. Concatenated Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings words ( without duplicates ), return all the concatenated words in the given list of words . A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= words[i].length <= 30", + "words[i] consists of only lowercase English letters.", + "All the strings of words are unique .", + "1 <= sum(words[i].length) <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]Output:[\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]Explanation:\"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cat\",\"dog\",\"catdog\"]Output:[\"catdog\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n \n set_words = set(words)\n\n def check(word, seen):\n if word == '':\n return True\n for i in range(len(word) if seen else len(word) - 1):\n if word[:i+1] in set_words:\n if check(word[i+1:], seen | {word[:i+1]}):\n return True\n return False\n\n return [word for word in words if check(word, set())]\n", + "title": "472. Concatenated Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums of length n , you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n ( 0-indexed ). Specifically, ans is the concatenation of two nums arrays. Return the array ans . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]Output:[1,2,1,1,2,1]Explanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,1]Output:[1,3,2,1,1,3,2,1]Explanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 7.82%) | Memory: 50.1 MB (Top 50.44%)\nclass Solution {\n public int[] getConcatenation(int[] nums) {\n int[] ans = new int[2 * nums.length];\n for(int i = 0; i < nums.length; i++){\n ans[i] = ans[i + nums.length] = nums[i];\n }\n\n return ans;\n }\n}", + "title": "1929. Concatenation of Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums of length n , you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n ( 0-indexed ). Specifically, ans is the concatenation of two nums arrays. Return the array ans . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]Output:[1,2,1,1,2,1]Explanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,1]Output:[1,3,2,1,1,3,2,1]Explanation:The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 139 ms (Top 57.29%) | Memory: 14.1 MB (Top 65.51%)\nclass Solution(object):\n def getConcatenation(self, nums):\n return nums * 2", + "title": "1929. Concatenation of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:1Explanation:\"1\" in binary corresponds to the decimal value 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:27Explanation:In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.", + "image": null + }, + { + "text": "Example 3: Input:n = 12Output:505379714Explanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109+ 7, the result is 505379714.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 613 ms (Top 30.00%) | Memory: 117.4 MB (Top 18.57%)\nclass Solution {\n public int concatenatedBinary(int n) {\n long res = 0;\n for (int i = 1; i <= n; i++) {\n res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007;\n }\n return (int) res;\n }\n}", + "title": "1680. Concatenation of Consecutive Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:1Explanation:\"1\" in binary corresponds to the decimal value 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:27Explanation:In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.", + "image": null + }, + { + "text": "Example 3: Input:n = 12Output:505379714Explanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109+ 7, the result is 505379714.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def concatenatedBinary(self, n: int) -> int:\n modulo = 10 ** 9 + 7\n shift = 0 # tracking power of 2\n res = 0\n \n for i in range(1, n+1):\n if i & (i - 1) == 0: # see if num reaches a greater power of 2\n shift += 1\n res = ((res << shift) + i) % modulo # do the simulation\n \n return res", + "title": "1680. Concatenation of Consecutive Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s , return the power of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"Output:2Explanation:The substring \"ee\" is of length 2 with the character 'e' only.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbcccddddeeeeedcba\"Output:5Explanation:The substring \"eeeee\" is of length 5 with the character 'e' only.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 40.49%) | Memory: 42.4 MB (Top 68.55%)\nclass Solution {\n public int maxPower(String s) {\n // O(n), assuming the access to every char is O(1)\n // iterate through characters\n // if char(n) == char(n+1) counter++\n // if counter > max, max = counter\n // else counter = 1 // 1 is init value because otherwise the compared char itself is not counted\n\n int maxConsecutive = 1; // 1 is init value because otherwise the compared char itself is not counted\n int counterConsecutive = 1;\n for(int i = 0; i< s.length()-1; i++){\n if(s.charAt(i) == s.charAt(i+1)){\n counterConsecutive++;\n maxConsecutive = Math.max(counterConsecutive, maxConsecutive);\n } else {\n counterConsecutive = 1;\n }\n }\n\n return maxConsecutive;\n }\n}", + "title": "1446. Consecutive Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The power of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string s , return the power of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"Output:2Explanation:The substring \"ee\" is of length 2 with the character 'e' only.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbcccddddeeeeedcba\"Output:5Explanation:The substring \"eeeee\" is of length 5 with the character 'e' only.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 30 ms (Top 32.1%) | Memory: 13.25 MB (Top 75.9%)\n\nclass Solution(object):\n def maxPower(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n stack=[]\n mxpow=0\n for i in s:\n if stack and stack[-1]!=i:\n mxpow=max(mxpow,len(stack))\n stack=[]\n stack.append(i)\n else:\n stack.append(i)\n mxpow=max(mxpow,len(stack))\n return mxpow", + "title": "1446. Consecutive Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of ways you can write n as the sum of consecutive positive integers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:5 = 2 + 3", + "image": null + }, + { + "text": "Example 2: Input:n = 9Output:3Explanation:9 = 4 + 5 = 2 + 3 + 4", + "image": null + }, + { + "text": "Example 3: Input:n = 15Output:4Explanation:15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 75.69%) | Memory: 41.1 MB (Top 34.74%)\nclass Solution {\n\n public int consecutiveNumbersSum(int n) {\n final double eightN = (8d * ((double) n)); // convert to double because 8n can overflow int\n final int maxTriangular = (int) Math.floor((-1d + Math.sqrt(1d + eightN)) / 2d);\n int ways = 1;\n int triangular = 1;\n for (int m = 2; m <= maxTriangular; ++m) {\n triangular += m;\n final int difference = n - triangular;\n if ((difference % m) == 0) {\n ways++;\n }\n }\n return ways;\n }\n\n}", + "title": "829. Consecutive Numbers Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of ways you can write n as the sum of consecutive positive integers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation:5 = 2 + 3", + "image": null + }, + { + "text": "Example 2: Input:n = 9Output:3Explanation:9 = 4 + 5 = 2 + 3 + 4", + "image": null + }, + { + "text": "Example 3: Input:n = 15Output:4Explanation:15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 82.13%) | Memory: 16.60 MB (Top 56.38%)\n\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n csum=0\n result=0\n for i in range(1,n+1):\n csum+=i-1\n if csum>=n:\n break\n if (n-csum)%i==0:\n result+=1\n return result\n", + "title": "829. Consecutive Numbers Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j] , where i < j , the condition j - i <= k is satisfied. A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2,-10,5,20], k = 2Output:37Explanation:The subsequence is [10, 2, 5, 20].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-2,-3], k = 1Output:-1Explanation:The subsequence must be non-empty, so we choose the largest number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,-2,-10,-5,20], k = 2Output:23Explanation:The subsequence is [10, -2, -5, 20].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 172 ms (Top 12.84%) | Memory: 123.7 MB (Top 41.81%)\nclass Solution {\n public int constrainedSubsetSum(int[] nums, int k) {\n int n=nums.length;\n int[] dp=new int[n];\n int res=nums[0];\n Queue queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap\n\n Arrays.fill(dp,Integer.MIN_VALUE);\n dp[0]=nums[0];\n queue.offer(0);\n\n for(int j=1;j int:\n deque = []\n for i, num in enumerate(nums):\n \n while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i]\n deque.pop(0)\n \n if deque: # compute the max sum we can get at index i\n nums[i] = nums[deque[0]] + num\n \n while(deque and nums[deque[-1]] < nums[i]): \n # delet all the sequence that smaller than current sum, becaus there will never be\n # considers ==> smaller than current sequence, and end before current sequence\n deque.pop()\n \n if nums[i] > 0: # if nums[i] < 0, it can't be a useful prefix sum \n \tdeque.append(i)\n \n return max(nums)", + "title": "1425. Constrained Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree ), construct the tree and return its root . It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val , and any descendant of Node.right has a value strictly greater than Node.val . A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left , then traverses Node.right . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 100", + "1 <= preorder[i] <= 1000", + "All the values of preorder are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [8,5,1,7,10,12]Output:[8,5,10,1,7,null,12]", + "image": "https://assets.leetcode.com/uploads/2019/03/06/1266.png" + }, + { + "text": "Example 2: Input:preorder = [1,3]Output:[1,null,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 66.41%) | Memory: 42.3 MB (Top 45.67%)\nclass Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n return bst(preorder, 0, preorder.length-1);\n }\n\n public TreeNode bst(int[] preorder, int start, int end){\n if(start > end) return null;\n\n TreeNode root = new TreeNode(preorder[start]);\n int breakPoint = start+1;\n while(breakPoint <= end && preorder[breakPoint] < preorder[start]){\n breakPoint++;\n }\n\n root.left = bst(preorder, start+1, breakPoint-1);\n root.right = bst(preorder, breakPoint, end);\n return root;\n }\n}", + "title": "1008. Construct Binary Search Tree from Preorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree ), construct the tree and return its root . It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val , and any descendant of Node.right has a value strictly greater than Node.val . A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left , then traverses Node.right . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 100", + "1 <= preorder[i] <= 1000", + "All the values of preorder are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [8,5,1,7,10,12]Output:[8,5,10,1,7,null,12]", + "image": "https://assets.leetcode.com/uploads/2019/03/06/1266.png" + }, + { + "text": "Example 2: Input:preorder = [1,3]Output:[1,null,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n\t\tif not preorder:\n\t\t\treturn None\n\t\tnode = preorder.pop(0)\n\t\troot = TreeNode(node)\n\t\tl = []\n\t\tr = []\n\n\t\tfor val in preorder:\n\t\t\tif val < node:\n\t\t\t\tl.append(val)\n\t\t\telse:\n\t\t\t\tr.append(val)\n\n\t\troot.left = self.bstFromPreorder(l)\n\t\troot.right = self.bstFromPreorder(r)\n\t\treturn root", + "title": "1008. Construct Binary Search Tree from Preorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] io; int[] po;\n int n; // nth post order node \n public TreeNode buildTree(int[] inorder, int[] postorder) {\n this.n = inorder.length-1; this.io = inorder; this.po = postorder; \n return buildTree(0, n); \n }\n public TreeNode buildTree(int low, int high) {\n if(n < 0 || low > high) return null;\n int currNode = po[n--];\n int idxInInorder = low;\n TreeNode root = new TreeNode(currNode); \n if(low == high) return root; // no more nodes\n \n while(io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder\n root.right = buildTree(idxInInorder+1, high);\n root.left = buildTree(low, idxInInorder-1);\n return root; \n }\n}\n", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n\n def buildTree(self, inorder, postorder):\n \"\"\"\n 7\n 2\n -8 \n :type inorder: List[int]\n :type postorder: List[int]\n :rtype: TreeNode\n ([-4,-10,3,-1], [7]) ((11,-8,2), [7])\n \"\"\"\n currentSplits = [(inorder, [], [])]\n nodeDirectory = {}\n finalSplits = []\n for nodeVal in reversed(postorder):\n nodeDirectory[nodeVal] = TreeNode(nodeVal)\n for splits, nodes, directions in reversed(currentSplits):\n removing = None\n if nodeVal in splits:\n removing = (splits, nodes, directions)\n left = splits[:splits.index(nodeVal)]\n right = splits[splits.index(nodeVal)+1:]\n currentSplits.append((left, nodes+[nodeVal], directions + ['left']))\n if len(left) <= 1:\n finalSplits.append((left, nodes+[nodeVal], directions + ['left']))\n currentSplits.append((right, nodes+[nodeVal], directions + ['right']))\n if len(right) <= 1:\n finalSplits.append((right, nodes+[nodeVal], directions + ['right']))\n break\n if removing:\n currentSplits.remove(removing)\n finalSplits = [splits for splits in finalSplits if splits[0]]\n\n while finalSplits:\n nodeVal, nodes, directions = finalSplits.pop()\n bottomNode = nodeDirectory[nodeVal[0]] if nodeVal else None\n while nodes:\n attachingNode = nodeDirectory[nodes.pop()]\n attachingDir = directions.pop()\n if attachingDir == 'left':\n attachingNode.left = bottomNode\n else:\n attachingNode.right = bottomNode\n bottomNode = attachingNode\n return nodeDirectory[postorder[-1]]\n", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Map inMap;\n int curIndex = 0;\n int[] preOrder;\n public TreeNode buildTree(int[] preorder, int[] inorder) {\n preOrder = preorder;\n inMap = new HashMap<>();\n for(int i=0; i e) return null;\n int curNode = preOrder[curIndex++];\n TreeNode root = new TreeNode(curNode);\n int inRoot = inMap.get(curNode);\n root.left = dfs(s, inRoot-1);\n root.right = dfs(inRoot+1, e);\n return root;\n }\n}\n", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 274 ms (Top 36.07%) | Memory: 88.6 MB (Top 22.22%)\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n if not preorder or not inorder:\n return None\n\n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1:mid+1], inorder[:mid])\n root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])\n return root", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree . If there exist multiple answers, you can return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 30", + "1 <= preorder[i] <= preorder.length", + "All the values of preorder are unique .", + "postorder.length == preorder.length", + "1 <= postorder[i] <= postorder.length", + "All the values of postorder are unique .", + "It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]Output:[1,2,3,4,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg" + }, + { + "text": "Example 2: Input:preorder = [1], postorder = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 63.11%) | Memory: 44.6 MB (Top 8.84%)\nclass Solution\n{\n public TreeNode constructFromPrePost(int[] preorder, int[] postorder)\n {\n // O(n) time | O(h) space\n if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null;\n\n TreeNode root = new TreeNode(preorder[0]);\n int mid = 0;\n\n if(preorder.length == 1) return root;\n\n // update mid\n for(int i = 0; i < postorder.length; i++)\n {\n if(preorder[1] == postorder[i])\n {\n mid = i;\n break;\n }\n }\n\n root.left = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1, 1 + mid + 1),\n Arrays.copyOfRange(postorder, 0, mid + 1));\n\n root.right = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1 + mid + 1, preorder.length),\n Arrays.copyOfRange(postorder, mid + 1, postorder.length - 1));\n return root;\n }\n}", + "title": "889. Construct Binary Tree from Preorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree . If there exist multiple answers, you can return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= preorder.length <= 30", + "1 <= preorder[i] <= preorder.length", + "All the values of preorder are unique .", + "postorder.length == preorder.length", + "1 <= postorder[i] <= postorder.length", + "All the values of postorder are unique .", + "It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]Output:[1,2,3,4,5,6,7]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg" + }, + { + "text": "Example 2: Input:preorder = [1], postorder = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n\n def build(preorder, preStart, preEnd, postorder, postStart, postEnd):\n if preStart > preEnd:\n return\n elif preStart == preEnd:\n return TreeNode(preorder[preStart])\n \n rootVal = preorder[preStart]\n leftRootVal = preorder[preStart + 1]\n index = valToIndex[leftRootVal]\n root = TreeNode(rootVal)\n leftSize = index - postStart + 1\n \n root.left = build(preorder, preStart + 1, preStart + leftSize,\npostorder, postStart, index)\n root.right = build(preorder, preStart + leftSize + 1, preEnd,\npostorder, index + 1, postEnd - 1)\n \n return root\n \n valToIndex = {}\n for i in range(len(postorder)):\n valToIndex[postorder[i]] = i\n \n return build(preorder, 0, len(preorder) - 1, postorder, 0, len(postorder) - 1)\n", + "title": "889. Construct Binary Tree from Preorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s and an integer k , return true if you can use all the characters in s to construct k palindrome strings or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"annabelle\", k = 2Output:trueExplanation:You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 3Output:falseExplanation:It is impossible to construct 3 palindromes using all the characters of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"true\", k = 4Output:trueExplanation:The only possible solution is to put each character in a separate string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 25.64%) | Memory: 42.9 MB (Top 94.32%)\nclass Solution {\n public boolean canConstruct(String s, int k) {\n if(k==s.length())\n {\n return true;\n }\n else if(k>s.length())\n {\n return false;\n }\n Map map=new HashMap();\n for(int i=0;iele:map.entrySet())\n {\n if((ele.getValue()%2)==1)\n {\n odd++;\n }\n }\n return (odd<=k);\n }\n}", + "title": "1400. Construct K Palindrome Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and an integer k , return true if you can use all the characters in s to construct k palindrome strings or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"annabelle\", k = 2Output:trueExplanation:You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 3Output:falseExplanation:It is impossible to construct 3 palindromes using all the characters of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"true\", k = 4Output:trueExplanation:The only possible solution is to put each character in a separate string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 67.79%) | Memory: 17.30 MB (Top 13.48%)\n\nfrom collections import Counter\n\nclass Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n if k > len(s):\n return False\n h = Counter(s)\n countOdd = 0\n for value in h.values():\n if value % 2:\n countOdd += 1\n if countOdd > k:\n return False\n return True\n", + "title": "1400. Construct K Palindrome Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree. Return the root of the Quad-Tree representing the grid . Notice that you can assign the value of a node to True or False when isLeaf is False , and both are accepted in the answer. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's.", + "isLeaf : True if the node is leaf node on the tree or False if the node has the four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:[[0,1],[1,0],[1,1],[1,1],[1,0]]Explanation:The explanation of this example is shown below:\nNotice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]Output:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]Explanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a QuadTree node.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n \n public Node() {\n this.val = false;\n this.isLeaf = false;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = topLeft;\n this.topRight = topRight;\n this.bottomLeft = bottomLeft;\n this.bottomRight = bottomRight;\n }\n};\n*/\n\nclass Solution {\n public Node construct(int[][] grid) {\n return helper(grid,0,grid.length-1,0,grid.length-1);\n }\n Node helper(int[][] grid,int l,int r,int t,int b){\n if(l==r){\n if(grid[t][l]==1)return new Node(true,true);\n else return new Node(false,true);\n }\n if(allOnes(grid,l,r,t,b)){\n Node res=new Node(true,true);\n return res;\n }\n if(allZeros(grid,l,r,t,b)){\n Node res=new Node(false,true);\n return res;\n }\n Node tl=helper(grid,l,(l+r)/2,t,(t+b)/2);\n Node tr=helper(grid,((l+r+1)/2),r,t,(t+b)/2);\n Node bl=helper(grid,l,(l+r)/2,(t+b+1)/2,b);\n Node br=helper(grid,((l+r+1)/2),r,(t+b+1)/2,b);\n return new Node(true,false,tl,tr,bl,br);\n }\n boolean allOnes(int[][] grid,int l,int r,int t,int b){\n //System.out.println(l+\" \"+r+\" \"+t+\" \"+b);\n for(int i=t;i<=b;i++){\n for(int j=l;j<=r;j++){\n if(grid[i][j]!=1){return false;}\n }\n \n }\n \n return true;\n }\n boolean allZeros(int[][] grid,int l,int r,int t,int b){\n for(int i=t;i<=b;i++){\n for(int j=l;j<=r;j++){\n if(grid[i][j]!=0)return false;\n }\n }\n return true;\n }\n}\n", + "title": "427. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree. Return the root of the Quad-Tree representing the grid . Notice that you can assign the value of a node to True or False when isLeaf is False , and both are accepted in the answer. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's.", + "isLeaf : True if the node is leaf node on the tree or False if the node has the four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:[[0,1],[1,0],[1,1],[1,1],[1,0]]Explanation:The explanation of this example is shown below:\nNotice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]Output:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]Explanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a QuadTree node.\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n\"\"\"\n\nclass Solution:\n def construct(self, grid: List[List[int]]) -> 'Node':\n def is_grid_a_leaf(mylist, n):\n x = mylist[0][0]\n for i in range(n):\n for j in range(n):\n if mylist[i][j] != x:\n return (0,0)\n return (1,x)\n \n def tree_builder(currlist) -> 'Node':\n node = Node()\n n = len(currlist)\n node.isLeaf, node.val = is_grid_a_leaf(currlist, n)\n \n if node.isLeaf:\n node.topLeft = node.topRight = node.bottomLeft = node.bottomRight = None\n else:\n top_left = [[row[i] for i in range(n//2)] for row in currlist[0:n//2]]\n top_right= [[row[i] for i in range(n//2,n)] for row in currlist[0:n//2]]\n bot_left = [[row[i] for i in range(n//2)] for row in currlist[n//2:n]]\n bot_right= [[row[i] for i in range(n//2,n)] for row in currlist[n//2:n]]\n node.topLeft = tree_builder(top_left)\n node.topRight = tree_builder(top_right)\n node.bottomLeft = tree_builder(bot_left)\n node.bottomRight = tree_builder(bot_right)\n return node\n \n return tree_builder(grid)", + "title": "427. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4]Output:\"1(2(4))(3)\"Explanation:Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the unnecessary empty parenthesis pairs. And it will be \"1(2(4))(3)\"", + "image": "https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]Output:\"1(2()(4))(3)\"Explanation:Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.", + "image": "https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n void tree2str(TreeNode* root,string &s) {\n if(!root) return;\n \n s+=to_string(root->val);\n \n if(!root->left && !root->right) return;\n \n s.push_back('('); tree2str(root->left,s); s.push_back(')');\n \n if(root->right){\n s.push_back('('); tree2str(root->right,s); s.push_back(')');\n }\n } \npublic:\n string tree2str(TreeNode* root) {\n string ans = \"\";\n tree2str(root,ans);\n return ans;\n }\n};\n", + "title": "606. Construct String from Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and an integer repeatLimit . Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row . You do not have to use all characters from s . Return the lexicographically largest repeatLimitedString possible . A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b . If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= repeatLimit <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cczazcc\", repeatLimit = 3Output:\"zzcccac\"Explanation:We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\nNote that the string \"zzcccca\" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababab\", repeatLimit = 2Output:\"bbabaa\"Explanation:We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\nNote that the string \"bbabaaa\" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 93.53%) | Memory: 64.8 MB (Top 62.59%)\nclass Solution {\n public String repeatLimitedString(String s, int repeatLimit) {\n int[] counter = new int[26];\n int max = 0;\n for (char ch : s.toCharArray()) {\n int curr = ch - 'a';\n max = Math.max(max, curr);\n counter[curr]++;\n }\n int repeated = 0;\n StringBuilder builder = new StringBuilder();\n while (max >= 0) {\n builder.append((char)('a' + max));\n counter[max]--;\n repeated++;\n if (counter[max] == 0) {\n max = findNextMax(counter, max - 1);\n repeated = 0;\n continue;\n }\n if (repeated == repeatLimit) {\n // Greedy, use the next possible char once and get back to curr.\n // if no other char available, the curr word is the largest subsequence.\n int lower = findNextMax(counter, max - 1);\n if (lower < 0) {\n return builder.toString();\n }\n builder.append((char)('a' + lower));\n counter[lower]--;\n repeated = 0;\n }\n }\n return builder.toString();\n }\n\n private int findNextMax(int[] counter, int from) {\n int curr = from;\n while (curr >= 0) {\n if (counter[curr] > 0) {\n return curr;\n }\n curr--;\n }\n return curr;\n }\n}", + "title": "2182. Construct String With Repeat Limit", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s and an integer repeatLimit . Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row . You do not have to use all characters from s . Return the lexicographically largest repeatLimitedString possible . A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b . If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= repeatLimit <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cczazcc\", repeatLimit = 3Output:\"zzcccac\"Explanation:We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\nNote that the string \"zzcccca\" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababab\", repeatLimit = 2Output:\"bbabaa\"Explanation:We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\nNote that the string \"bbabaaa\" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heappush, heappop\nfrom collections import defaultdict\n\nclass Solution:\n def repeatLimitedString(self, string: str, k: int) -> str:\n \"\"\"\n look close to the problem:\n it's lexicographically largest \n not \"longest\"\n \"\"\"\n appear, times = defaultdict(), defaultdict()\n pq, stack = [], []\n for s in string:\n appear[s] = appear.get(s, 0) + 1\n \n for s in appear:\n pq.append((-ord(s), appear[s]))\n \n heapify(pq)\n appear.clear()\n \n while pq:\n char, num = heappop(pq)\n s = chr(-char)\n if s in times and times[s] == k: # if reach the repeatedLimit\n if not pq:\n return ''.join(stack)\n char2, num2 = heappop(pq)\n token = chr(-char2)\n stack.append(token)\n if num2 - 1 > 0:\n heappush(pq, (char2, num2 - 1))\n heappush(pq, (char, num))\n del times[s]\n times[token] = 1\n continue\n if stack and stack[-1] != s:\n # reset times\n del times[stack[-1]]\n stack.append(s)\n times[s] = times.get(s, 0) + 1\n \n if num - 1 > 0:\n heappush(pq, (char, num - 1))\n return ''.join(stack) \n", + "title": "2182. Construct String With Repeat Limit", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : Return true if it is possible to construct the target array from arr , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "let x be the sum of all elements currently in your array.", + "choose index i , such that 0 <= i < n and set the value of arr at index i to x .", + "You may repeat this procedure as many times as needed." + ], + "examples": [ + { + "text": "Example 1: Input:target = [9,3,5]Output:trueExplanation:Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done", + "image": null + }, + { + "text": "Example 2: Input:target = [1,1,1,2]Output:falseExplanation:Impossible to create target array from [1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:target = [8,5]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 47.45%) | Memory: 56.9 MB (Top 77.47%)\n\nclass Solution {\n public boolean isPossible(int[] target) {\n if(target.length==1) return target[0]==1;\n\n PriorityQueue que = new PriorityQueue(Collections.reverseOrder());\n int totsum = 0;\n\n for(int i=0;i bool:\n if len(target) == 1:\n return target == [1]\n res = sum(target)\n heap = [-elem for elem in target]\n heapify(heap)\n while heap[0]<-1:\n maximum = -heappop(heap)\n res -= maximum\n\n if res == 1:\n return True\n x = maximum % res\n if x == 0 or (x != 1 and x == maximum):\n return False\n\n res += x\n heappush(heap,-x)\n return True", + "title": "1354. Construct Target Array With Multiple Sums", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer n , find a sequence that satisfies all of the following: The distance between two numbers on the sequence, a[i] and a[j] , is the absolute difference of their indices, |j - i| . Return the lexicographically largest sequence . It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b . For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The integer 1 occurs once in the sequence.", + "Each integer between 2 and n occurs twice in the sequence.", + "For every integer i between 2 and n , the distance between the two occurrences of i is exactly i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[3,1,2,3,2]Explanation:[2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[5,3,1,4,3,5,2,4,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.69%) | Memory: 42.2 MB (Top 11.27%)\nclass Solution {\n\n public int[] constructDistancedSequence(int n) {\n int[] ans = new int[n * 2 - 1];\n boolean[] visited = new boolean[n + 1];\n calc(0, ans, visited, n);\n return ans;\n }\n\n private boolean calc(int index, int[] ans, boolean[] visited, int n) {\n if (index == ans.length) {\n return true;\n }\n if (ans[index] != 0) return calc(index + 1, ans, visited, n); // value already assigned in this position. So go ahead with the next index.\n else {\n // we start from n to 1 since we need to find out the lexicographically largest sequence.\n for (int i = n; i >= 1; i--) {\n if (visited[i]) continue;\n visited[i] = true;\n ans[index] = i;\n if (i == 1) {\n if (calc(index + 1, ans, visited, n)) return true;\n } else if (index + i < ans.length && ans[index + i] == 0) {\n ans[i + index] = i; // assigning the second occurence of i in the desired position i.e, (current index + i )\n if (calc(index + 1, ans, visited, n)) return true; // largest possible sequence satisfying the given conditions found.\n ans[index + i] = 0;\n }\n ans[index] = 0;\n visited[i] = false;\n }\n\n }\n return false;\n }\n }\n", + "title": "1718. Construct the Lexicographically Largest Valid Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , find a sequence that satisfies all of the following: The distance between two numbers on the sequence, a[i] and a[j] , is the absolute difference of their indices, |j - i| . Return the lexicographically largest sequence . It is guaranteed that under the given constraints, there is always a solution. A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b . For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The integer 1 occurs once in the sequence.", + "Each integer between 2 and n occurs twice in the sequence.", + "For every integer i between 2 and n , the distance between the two occurrences of i is exactly i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[3,1,2,3,2]Explanation:[2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[5,3,1,4,3,5,2,4,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n self.ans = None\n def dfs(path, used, i):\n self.steps += 1\n if i == len(path):\n self.ans = path[:]\n return True\n if path[i] != 0:\n return dfs(path, used, i + 1)\n my_ans = [0]\n for x in range(n, 0, -1):\n if x in used:\n continue\n if x == 1:\n path[i] = x\n used.add(1)\n \n if dfs(path, used, i + 1):\n return True\n \n path[i] = 0\n used.remove(1)\n if i + x < len(path) and path[i + x] == 0:\n path[i + x] = path[i] = x\n used.add(x)\n \n if dfs(path, used, i + 1):\n return True\n \n path[i + x] = path[i] = 0\n used.remove(x)\n\n return False\n\n dfs([0] * (1 + 2 * (n - 1)), set(), 0)\n \n return self.ans\n", + "title": "1718. Construct the Lexicographically Largest Valid Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: Return an array [L, W] where L and W are the length and width of the web page you designed in sequence. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= area <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:area = 4Output:[2,2]Explanation:The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.", + "image": null + }, + { + "text": "Example 2: Input:area = 37Output:[37,1]", + "image": null + }, + { + "text": "Example 3: Input:area = 122122Output:[427,286]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] constructRectangle(int area) {\n int minDiff = Integer.MAX_VALUE;\n int[] result = new int[2];\n \n for (int w = 1; w*w <= area; w++) {\n if (area % w == 0) {\n int l = area / w;\n int diff = l - w;\n if (diff < minDiff) {\n result[0] = l;\n result[1] = w;\n minDiff = diff;\n }\n }\n }\n \n return result;\n }\n}\n", + "title": "492. Construct the Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: Return an array [L, W] where L and W are the length and width of the web page you designed in sequence. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= area <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:area = 4Output:[2,2]Explanation:The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.", + "image": null + }, + { + "text": "Example 2: Input:area = 37Output:[37,1]", + "image": null + }, + { + "text": "Example 3: Input:area = 122122Output:[427,286]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 39 ms (Top 86.68%) | Memory: 13.9 MB (Top 58.98%)\nclass Solution:\n def constructRectangle(self, area: int):\n y = Solution.mySqrt(area)\n for i in range(y, 0, -1):\n if not area%i:\n return [int(area/i), i]\n\n def mySqrt(x):\n if x == 0:\n return 0\n n = x\n count = 0\n while True:\n count += 1\n root = 0.5 * (n + (x / n))\n if abs(root - n) < 0.9:\n break\n n = root\n return int(root)", + "title": "492. Construct the Rectangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected , where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie . Return the number of walls used to quarantine all the infected regions . If the world will become fully infected, return the number of walls used. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == isInfected.length", + "n == isInfected[i].length", + "1 <= m, n <= 50", + "isInfected[i][j] is either 0 or 1 .", + "There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round." + ], + "examples": [ + { + "text": "Example 1: Input:isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]Output:10Explanation:There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" + }, + { + "text": "Example 2: Input:isInfected = [[1,1,1],[1,0,1],[1,1,1]]Output:4Explanation:Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" + }, + { + "text": "Example 3: Input:isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]Output:13Explanation:The region on the left only builds two new walls.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[][] DIR = new int[][]{\n {1, 0}, {-1, 0}, {0, 1}, {0, -1}\n };\n \n public int containVirus(int[][] isInfected) {\n int m = isInfected.length, n = isInfected[0].length;\n int ans = 0;\n \n while( true ) {\n // infected regions, sorted desc according to the number of nearby \n // uninfected nodes\n PriorityQueue pq = new PriorityQueue();\n // already visited cells\n boolean[][] visited = new boolean[m][n];\n \n // find regions\n for(int i=0; i {\n public List infected;\n public List uninfected;\n public int wallsRequired;\n \n public Region() {\n infected = new ArrayList();\n uninfected = new ArrayList();\n }\n \n public void addInfected(int row, int col) {\n infected.add(new int[]{ row, col });\n }\n \n public void addUninfected(int row, int col) {\n uninfected.add(new int[]{ row, col });\n }\n \n @Override\n public int compareTo(Region r2) {\n return Integer.compare(r2.uninfected.size(), uninfected.size());\n }\n}\n\n", + "title": "749. Contain Virus", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected , where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie . Return the number of walls used to quarantine all the infected regions . If the world will become fully infected, return the number of walls used. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == isInfected.length", + "n == isInfected[i].length", + "1 <= m, n <= 50", + "isInfected[i][j] is either 0 or 1 .", + "There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round." + ], + "examples": [ + { + "text": "Example 1: Input:isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]Output:10Explanation:There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" + }, + { + "text": "Example 2: Input:isInfected = [[1,1,1],[1,0,1],[1,1,1]]Output:4Explanation:Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" + }, + { + "text": "Example 3: Input:isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]Output:13Explanation:The region on the left only builds two new walls.", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area\n if 0<=i int:\n ans, i, j = 0, 0, len(H)-1\n while (i < j):\n if H[i] <= H[j]:\n res = H[i] * (j - i)\n i += 1\n else:\n res = H[j] * (j - i)\n j -= 1\n if res > ans: ans = res\n return ans\n\n", + "title": "11. Container With Most Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:false", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,3,4,3,2,4,2]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 27.66%) | Memory: 57.30 MB (Top 21.08%)\n\nclass Solution {\n public boolean containsDuplicate(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int i = 1; i < n; i++) {\n if (nums[i] == nums[i - 1])\n return true;\n }\n return false;\n }\n}\n", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:false", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,3,4,3,2,4,2]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 714 ms (Top 44.74%) | Memory: 26.1 MB (Top 5.18%)\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return len(nums) != len(set(nums))", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsNearbyDuplicate(int[] nums, int k) {\n HashMap map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) {\n return true;\n }\n map.put(nums[i], i);\n }\n return false;\n }\n}\n", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 632 ms (Top 95.72%) | Memory: 27.2 MB (Top 74.47%)\nclass Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n seen = {}\n for i, n in enumerate(nums):\n if n in seen and i - seen[n] <= k:\n return True\n seen[n] = i\n return False", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and two integers k and t , return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^4", + "0 <= t <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3, t = 0Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1, t = 2Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,9,1,5,9], k = 2, t = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 75.62%) | Memory: 55.00 MB (Top 92.14%)\n\n/**\n * Sliding Window solution using Buckets\n *\n * Time Complexity: O(N)\n *\n * Space Complexity: O(min(N, K+1))\n *\n * N = Length of input array. K = Input difference between indexes.\n */\nclass Solution {\n public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {\n if (nums == null || nums.length < 2 || k < 1 || t < 0) {\n return false;\n }\n\n HashMap buckets = new HashMap<>();\n // The bucket size is t+1 as the ranges are from 0..t, t+1..2t+1, ..\n long bucketSize = (long) t + 1;\n\n for (int i = 0; i < nums.length; i++) {\n // Making sure only K buckets exists in map.\n if (i > k) {\n long lastBucket = ((long) nums[i - k - 1] - Integer.MIN_VALUE) / bucketSize;\n buckets.remove(lastBucket);\n }\n\n long remappedNum = (long) nums[i] - Integer.MIN_VALUE;\n long bucket = remappedNum / bucketSize;\n\n // If 2 numbers belong to same bucket\n if (buckets.containsKey(bucket)) {\n return true;\n }\n\n // If numbers are in adjacent buckets and the difference between them is at most\n // t.\n if (buckets.containsKey(bucket - 1) && remappedNum - buckets.get(bucket - 1) <= t) {\n return true;\n }\n if (buckets.containsKey(bucket + 1) && buckets.get(bucket + 1) - remappedNum <= t) {\n return true;\n }\n\n buckets.put(bucket, remappedNum);\n }\n\n return false;\n }\n}\n", + "title": "220. Contains Duplicate III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and two integers k and t , return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^4", + "0 <= t <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3, t = 0Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1, t = 2Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,9,1,5,9], k = 2, t = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 779 ms (Top 16.27%) | Memory: 17.7 MB (Top 35.86%)\nfrom sortedcontainers import SortedList\nclass Solution:\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n sl = SortedList()\n for i in range(len(nums)):\n if i > k: sl.remove(nums[i-k-1])\n idxl = sl.bisect_left(nums[i]-t)\n idxr = sl.bisect_right(nums[i]+t)\n if idxl != idxr: return True\n sl.add(nums[i])\n return False", + "title": "220. Contains Duplicate III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums , return the maximum length of a contiguous subarray with an equal number of 0 and 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1]Output:2Explanation:[0, 1] is the longest contiguous subarray with an equal number of 0 and 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0]Output:2Explanation:[0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n # dictionary\n prefixSum = {0: -1}\n total = 0\n maxlength = 0\n \n for index, value in enumerate(nums):\n if value == 0:\n total -= 1\n else:\n total += 1\n if total not in prefixSum.keys():\n prefixSum[total] = index\n else:\n maxlength = max(maxlength, index-prefixSum[total]) \n return maxlength\n", + "title": "525. Contiguous Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k , or false otherwise . An integer x is a multiple of k if there exists an integer n such that x = n * k . 0 is always a multiple of k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= sum(nums[i]) <= 2 31 - 1", + "1 <= k <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [23,2,4,6,7], k = 6Output:trueExplanation:[2, 4] is a continuous subarray of size 2 whose elements sum up to 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [23,2,6,4,7], k = 6Output:trueExplanation:[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.", + "image": null + }, + { + "text": "Example 3: Input:nums = [23,2,6,4,7], k = 13Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n boolean t[]=new boolean[nums.length+1];\n Arrays.fill(t,false);\n return help(nums.length,nums,k,0,0,t);\n }\n public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){\n if(size>=2&&sum%k==0){\n return true;\n }\n if(i==0){\n return false;\n }\n if(t[i-1]!=false){\n return t[i-1];\n }\n if(size>0){\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t);\n }\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t)||help(i-1,nums,k,sum,size,t);\n }\n}\n---------------------------------------------------------------------------------------------\nclass Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n int sum=0;\n HashMaph=new HashMap<>();\n h.put(0,-1);\n for(int i=0;i=2){\n return true;\n }\n h.put(sum,h.getOrDefault(sum,i));\n } \n return false;\n }\n}\n", + "title": "523. Continuous Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k , or false otherwise . An integer x is a multiple of k if there exists an integer n such that x = n * k . 0 is always a multiple of k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= sum(nums[i]) <= 2 31 - 1", + "1 <= k <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [23,2,4,6,7], k = 6Output:trueExplanation:[2, 4] is a continuous subarray of size 2 whose elements sum up to 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [23,2,6,4,7], k = 6Output:trueExplanation:[23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.", + "image": null + }, + { + "text": "Example 3: Input:nums = [23,2,6,4,7], k = 13Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n psum = {0:-1}\n currentSum = 0\n for i in range(len(nums)):\n currentSum += nums[i]\n remainder = currentSum % k\n if remainder not in psum:\n psum[remainder] = i\n else:\n if i - psum[remainder] > 1:\n return True\n return False\n", + "title": "523. Continuous Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original , and two integers, m and n . You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original . The elements from indices 0 to n - 1 ( inclusive ) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 ( inclusive ) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= original.length <= 5 * 10^4", + "1 <= original[i] <= 10^5", + "1 <= m, n <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:original = [1,2,3,4], m = 2, n = 2Output:[[1,2],[3,4]]Explanation:The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png" + }, + { + "text": "Example 2: Input:original = [1,2,3], m = 1, n = 3Output:[[1,2,3]]Explanation:The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.", + "image": null + }, + { + "text": "Example 3: Input:original = [1,2], m = 1, n = 1Output:[]Explanation:There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 59.22%) | Memory: 55.50 MB (Top 5.02%)\n\nclass Solution {\n public int[][] construct2DArray(int[] original, int m, int n) { \n if (original.length != m * n) return new int[0][];\n \n int[][] ans = new int[m][n];\n int currRow = 0, currCol = 0;\n \n for (int num : original) {\n ans[currRow][currCol++] = num;\n \n if (currCol == n) {\n currCol = 0;\n currRow++;\n }\n }\n \n return ans;\n }\n}\n\n// TC: O(n), SC: O(m * n)\n", + "title": "2022. Convert 1D Array Into 2D Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 1-dimensional (1D) integer array original , and two integers, m and n . You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original . The elements from indices 0 to n - 1 ( inclusive ) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 ( inclusive ) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= original.length <= 5 * 10^4", + "1 <= original[i] <= 10^5", + "1 <= m, n <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:original = [1,2,3,4], m = 2, n = 2Output:[[1,2],[3,4]]Explanation:The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png" + }, + { + "text": "Example 2: Input:original = [1,2,3], m = 1, n = 3Output:[[1,2,3]]Explanation:The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.", + "image": null + }, + { + "text": "Example 3: Input:original = [1,2], m = 1, n = 1Output:[]Explanation:There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] construct2DArray(int[] original, int m, int n) {\n if(m * n != original.length) {\n return new int[0][0];\n }\n int[][] answer = new int[m][n];\n int rCount = 0, cCount = 0, len = original.length;\n for(int i=0;i List[List[int]]:\n ans = []\n if len(original) == m*n: \n for i in range(0, len(original), n): \n ans.append(original[i:i+n])\n return ans \n", + "title": "2022. Convert 1D Array Into 2D Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer num , return a string representing its hexadecimal representation . For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-2 31 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 26Output:\"1a\"", + "image": null + }, + { + "text": "Example 2: Input:num = -1Output:\"ffffffff\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 60.13%)\nclass Solution {\n public String toHex(int num) {\n if(num == 0) return \"0\";\n\n boolean start = true;\n\n StringBuilder sb = new StringBuilder();\n\n for(int i = 28; i >= 0; i -= 4) {\n int digit = (num >> i) & 15;\n if(digit > 9) {\n char curr = (char)(digit%10 + 'a');\n sb.append(curr);\n start = false;\n } else if(digit != 0) {\n char curr = (char)(digit + '0');\n sb.append(curr);\n start = false;\n } else {//digit == 0\n if(start == false) { //avoid case: 00001a\n sb.append('0');\n }\n }\n\n }\n return sb.toString();\n }\n}", + "title": "405. Convert a Number to Hexadecimal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return a string representing its hexadecimal representation . For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. Note: You are not allowed to use any built-in library method to directly solve this problem. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-2 31 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 26Output:\"1a\"", + "image": null + }, + { + "text": "Example 2: Input:num = -1Output:\"ffffffff\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 33 ms (Top 88.95%) | Memory: 13.8 MB (Top 62.28%)\nclass Solution:\n def toHex(self, num: int) -> str:\n ret = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n ans = \"\"\n\n if num < 0:\n num = pow(2,32) +num\n\n if num == 0:\n return \"0\"\n while num > 0:\n ans = ret[num%16] +ans\n num = num//16\n\n return ans", + "title": "405. Convert a Number to Hexadecimal", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1 . The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The Linked List is not empty.", + "Number of nodes will not exceed 30 .", + "Each node's value is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,0,1]Output:5Explanation:(101) in base 2 = (5) in base 10", + "image": "https://assets.leetcode.com/uploads/2019/12/05/graph-1.png" + }, + { + "text": "Example 2: Input:head = [0]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 64.79%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int getDecimalValue(ListNode head) {\n head = reverse(head);\n int ans = 0;\n int pow = 0;\n ListNode temp = head;\n while(temp != null){\n ans = ans + temp.val * (int) Math.pow(2,pow++);\n temp = temp.next;\n }\n\n return ans;\n }\n public ListNode reverse(ListNode head){\n ListNode prev = null;\n ListNode pres = head;\n ListNode Next = pres.next;\n\n while(pres != null){\n pres.next = prev;\n prev = pres;\n pres = Next;\n if(Next != null){\n Next = Next.next;\n }\n }\n\n head = prev;\n return head;\n }\n}", + "title": "1290. Convert Binary Number in a Linked List to Integer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1 . The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The Linked List is not empty.", + "Number of nodes will not exceed 30 .", + "Each node's value is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,0,1]Output:5Explanation:(101) in base 2 = (5) in base 10", + "image": "https://assets.leetcode.com/uploads/2019/12/05/graph-1.png" + }, + { + "text": "Example 2: Input:head = [0]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def getDecimalValue(self, head: ListNode) -> int:\n res = 0\n po = 0\n stack = []\n node = head\n while node:\n stack.append(node.val)\n node = node.next\n res = 0\n for i in reversed(stack):\n res += i*(2**po)\n po += 1\n return res\n", + "title": "1290. Convert Binary Number in a Linked List to Integer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]Output:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]", + "image": "https://assets.leetcode.com/uploads/2019/05/02/tree.png" + }, + { + "text": "Example 2: Input:root = [0,null,1]Output:[1,null,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode convertBST(TreeNode root) {\n if(root!=null) {\n\n\n List nodesValues = new ArrayList<>();\n helperNodesVales(root, nodesValues);\n traverseAndAdd(root, nodesValues);\n\n return root;\n }\n return null;\n }\n\n private void helperNodesVales(TreeNode root, List nodesValues) {\n if (root != null) {\n nodesValues.add(root.val);\n }\n if (root.right != null) {\n helperNodesVales(root.right, nodesValues);\n }\n if (root.left != null) {\n helperNodesVales(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n\n private void traverseAndAdd(TreeNode root, List nodesValues) {\n if (root != null) {\n int rootVal = root.val;\n for (int i = 0; i < nodesValues.size(); i++) {\n if (nodesValues.get(i) > rootVal)\n root.val += nodesValues.get(i);\n }\n }\n if (root.right != null) {\n traverseAndAdd(root.right, nodesValues);\n }\n if (root.left != null) {\n traverseAndAdd(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n}\n\n\n\n", + "title": "538. Convert BST to Greater Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]Output:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]", + "image": "https://assets.leetcode.com/uploads/2019/05/02/tree.png" + }, + { + "text": "Example 2: Input:root = [0,null,1]Output:[1,null,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n ans = []\n def inorder(node):\n if not node:\n return node\n inorder(node.left)\n ans.append(node.val)\n inorder(node.right)\n def dfs(node):\n if not node:\n return None\n idx = ans.index(node.val)\n node.val = node.val + sum(ans[idx+1:])\n dfs(node.left)\n dfs(node.right)\n\n inorder(root)\n dfs(root)\n return root\n \n", + "title": "538. Convert BST to Greater Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n , return a list of two integers [A, B] where : The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A and B are No-Zero integers .", + "A + B = n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[1,1]Explanation:A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.", + "image": null + }, + { + "text": "Example 2: Input:n = 11Output:[2,9]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] getNoZeroIntegers(int n) {\n int B;\n for (int A = 1; A < n; ++A) {\n B = n - A;\n if (!(A + \"\").contains(\"0\") && !(B + \"\").contains(\"0\"))\n return new int[] {A, B};\n }\n return new int[]{};\n}\n}\n", + "title": "1317. Convert Integer to the Sum of Two No-Zero Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation. Given an integer n , return a list of two integers [A, B] where : The test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A and B are No-Zero integers .", + "A + B = n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[1,1]Explanation:A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.", + "image": null + }, + { + "text": "Example 2: Input:n = 11Output:[2,9]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(1,n//2+1):\n first = str(i)\n second = str(n-i)\n if \"0\" not in first and \"0\" not in second:\n return [i, n-i]\n", + "title": "1317. Convert Integer to the Sum of Two No-Zero Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree . A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]Output:[3,1]Explanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 33.54%) | Memory: 45.2 MB (Top 7.46%)\nclass Solution {\n public TreeNode sortedArrayToBST(int[] nums) {\n if (nums.length == 0) return null;\n var mid = nums.length / 2;\n var root = new TreeNode(nums[mid]);\n var left_array = Arrays.copyOfRange(nums, 0, mid);\n var right_array = Arrays.copyOfRange(nums, mid + 1, nums.length);\n root.left = sortedArrayToBST(left_array);\n root.right = sortedArrayToBST(right_array);\n return root;\n }\n}", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree . A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]Output:[3,1]Explanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def formNodes(self,nums, l,r):\n if l > r:\n return None\n else:\n mid = l+(r-l)//2\n node = TreeNode(nums[mid])\n node.left = self.formNodes(nums, l,mid-1)\n node.right = self.formNodes(nums, mid+1,r)\n return node\n \n \n def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:\n return self.formNodes(nums, 0,len(nums)-1)\n", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list where elements are sorted in ascending order , convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in head is in the range [0, 2 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" + }, + { + "text": "Example 2: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public TreeNode sortedListToBST(ListNode head) {\n \n ListNode tmp = head;\n ArrayList treelist = new ArrayList<>();\n \n while(tmp != null) {\n treelist.add(tmp.val);\n tmp = tmp.next;\n }\n \n return createTree(treelist, 0, treelist.size()-1);\n }\n \n public TreeNode createTree(ArrayList treelist, int start, int end) {\n \n if(start > end)\n return null;\n \n int mid = start + (end-start)/2;\n \n TreeNode node = new TreeNode(treelist.get(mid));//getNode(treelist.get(mid));\n \n node.left = createTree(treelist, start, mid-1);\n node.right = createTree(treelist, mid+1, end);\n return node;\n }\n}\n", + "title": "109. Convert Sorted List to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the head of a singly linked list where elements are sorted in ascending order , convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in head is in the range [0, 2 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" + }, + { + "text": "Example 2: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:\n arr = []\n while head:\n arr.append(head.val)\n head = head.next\n def dfs(left, right):\n if left > right: return\n m = (left + right)//2\n return TreeNode(arr[m], dfs(left, m-1), dfs(m+1, right))\n return dfs(0, len(arr)-1)", + "title": "109. Convert Sorted List to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of network towers towers , where towers[i] = [x i , y i , q i ] denotes the i th network tower with location (x i , y i ) and quality factor q i . All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance . You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius . Outside that distance, the signal becomes garbled, and the tower is not reachable . The signal quality of the i th tower at a coordinate (x, y) is calculated with the formula ⌊q i / (1 + d)⌋ , where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. Return the array [c x , c y ] representing the integral coordinate (c x , c y ) where the network quality is maximum. If there are multiple coordinates with the same network quality , return the lexicographically minimum non-negative coordinate. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: x1 < x2 , or x1 == x2 and y1 < y2 .", + "x1 < x2 , or", + "x1 == x2 and y1 < y2 .", + "⌊val⌋ is the greatest integer less than or equal to val (the floor function)." + ], + "examples": [ + { + "text": "Example 1: Input:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2Output:[2,1]Explanation:At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/untitled-diagram.png" + }, + { + "text": "Example 2: Input:towers = [[23,11,21]], radius = 9Output:[23,11]Explanation:Since there is only one tower, the network quality is highest right at the tower's location.", + "image": null + }, + { + "text": "Example 3: Input:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2Output:[1,2]Explanation:Coordinate (1, 2) has the highest network quality.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 84.85%) | Memory: 41.90 MB (Top 33.33%)\n\nclass Solution {\n public int[] bestCoordinate(int[][] towers, int radius) {\n int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0;\n int[] res = new int[2];\n for(int[] t : towers) {\n minX = Math.min(minX, t[0]);\n maxX = Math.max(maxX, t[0]);\n minY = Math.min(minY, t[1]);\n maxY = Math.max(maxY, t[1]);\n }\n for(int i = minX; i <= maxX; i++) {\n for(int j = minY; j <= maxY; j++) {\n int sum = 0;\n for(int[] t : towers) {\n int d = (t[0] - i) *(t[0] - i) + (t[1] - j) *(t[1] - j);\n if(d <= radius * radius) {\n sum += t[2] /(1+ Math.sqrt(d)); \n }\n }\n if(sum > max) {\n max = sum;\n res = new int[]{i,j};\n }\n }\n }\n return res;\n }\n}\n", + "title": "1620. Coordinate With Maximum Network Quality", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of network towers towers , where towers[i] = [x i , y i , q i ] denotes the i th network tower with location (x i , y i ) and quality factor q i . All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance . You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius . Outside that distance, the signal becomes garbled, and the tower is not reachable . The signal quality of the i th tower at a coordinate (x, y) is calculated with the formula ⌊q i / (1 + d)⌋ , where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers. Return the array [c x , c y ] representing the integral coordinate (c x , c y ) where the network quality is maximum. If there are multiple coordinates with the same network quality , return the lexicographically minimum non-negative coordinate. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: x1 < x2 , or x1 == x2 and y1 < y2 .", + "x1 < x2 , or", + "x1 == x2 and y1 < y2 .", + "⌊val⌋ is the greatest integer less than or equal to val (the floor function)." + ], + "examples": [ + { + "text": "Example 1: Input:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2Output:[2,1]Explanation:At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/untitled-diagram.png" + }, + { + "text": "Example 2: Input:towers = [[23,11,21]], radius = 9Output:[23,11]Explanation:Since there is only one tower, the network quality is highest right at the tower's location.", + "image": null + }, + { + "text": "Example 3: Input:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2Output:[1,2]Explanation:Coordinate (1, 2) has the highest network quality.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n return max(\n (\n (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius),\n [x, y]) for x in range(51) for y in range(51)\n ),\n key=lambda x: (x[0], -x[1][0], -x[1][1])\n )[1]\n", + "title": "1620. Coordinate With Maximum Network Quality", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Your code will only be given the head of the original linked list. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]Output:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]Output:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]Output:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public Node copyRandomList(Node head) {\n \n if(head == null)\n return null;\n \n HashMap map = new HashMap<>();\n \n //node to be returned\n Node ans = new Node(head.val);\n \n //temproary pointer to the ans node\n Node tempAns = ans;\n \n Node temp = head;\n \n map.put(head,ans);\n temp = temp.next;\n \n \n //loop to store the lookalike new nodes of the original ones\n //create the new list side by side\n while(temp != null){\n Node x = new Node(temp.val);\n map.put(temp,x);\n tempAns.next = x;\n tempAns = x;\n temp = temp.next;\n }\n \n //repointing them to the start\n temp = head;\n tempAns = ans;\n \n //will have lookup of O(1) for the random nodes;\n while(temp!=null){\n tempAns.random = map.get(temp.random);\n tempAns = tempAns.next;\n temp = temp.next;\n }\n \n return ans;\n \n }\n}\n", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Your code will only be given the head of the original linked list. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]Output:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]Output:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]Output:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\nclass Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n \n \n \n # ll=res\n # k=0\n # ind=0\n # kmk=1\n jj=None\n g=defaultdict(lambda:-1)\n k=0\n hh=head\n while(head):\n res=Node(head.val)\n if k==0:\n jj=res\n\n if k==1:\n prev.next=res\n \n g[head]=res\n prev=res\n k=1\n head=head.next\n \n # print(g)\n \n # for i in g:\n # print(i.val,g[i].val)\n \n kk=jj\n mm=jj\n # print(head)\n while(hh):\n if hh.random!=None:\n \n jj.random=g[hh.random]\n else:\n jj.random=None\n hh=hh.next\n \n jj=jj.next \n # head=head.next\n kkk=kk\n # while(kk):\n # print(kk.val)\n # kk=kk.next\n \n return kkk\n# if g[ind]!=-1:\n# g[ind].random=res\n \n# res=Node(head.val)\n# if kmk==1:\n# ll=res\n# kmk=0\n# mm=head.next\n# if mm:\n \n# jk=Node(mm.val)\n# res.next=jk\n# if head.random !=None:\n# g[head.random]=res\n# else:\n# res.random=None\n# head=head.next\n# ind+=1\n# # res=res.next\n \n# return ll\n \n # if k==0:\n # res.val=head.val\n # mm=head.next\n \n \n \n \n \n", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n flights that are labeled from 1 to n . You are given an array of flight bookings bookings , where bookings[i] = [first i , last i , seats i ] represents a booking for flights first i through last i ( inclusive ) with seats i seats reserved for each flight in the range. Return an array answer of length n , where answer[i] is the total number of seats reserved for flight i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "1 <= bookings.length <= 2 * 10^4", + "bookings[i].length == 3", + "1 <= first i <= last i <= n", + "1 <= seats i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5Output:[10,55,45,25,25]Explanation:Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]", + "image": null + }, + { + "text": "Example 2: Input:bookings = [[1,2,10],[2,2,15]], n = 2Output:[10,25]Explanation:Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] corpFlightBookings(int[][] bookings, int n) {\n // nums all equals to zero\n int[] nums = new int[n];\n // construct the diffs\n Difference df = new Difference(nums);\n\n for (int[] booking : bookings) {\n // pay attention to the index\n int i = booking[0] - 1;\n int j = booking[1] - 1;\n int val = booking[2];\n // increase nums[i..j] by val\n df.increment(i, j, val);\n }\n // return the final array\n return df.result();\n }\n\n class Difference {\n // diff array\n private int[] diff;\n\n public Difference(int[] nums) {\n assert nums.length > 0;\n diff = new int[nums.length];\n // construct the diffs\n diff[0] = nums[0];\n for (int i = 1; i < nums.length; i++) {\n diff[i] = nums[i] - nums[i - 1];\n }\n }\n\n // increase nums[i..j] by val\n public void increment(int i, int j, int val) {\n diff[i] += val;\n if (j + 1 < diff.length) {\n diff[j + 1] -= val;\n }\n }\n\n public int[] result() {\n int[] res = new int[diff.length];\n // contract the diff array based on the result\n res[0] = diff[0];\n for (int i = 1; i < diff.length; i++) {\n res[i] = res[i - 1] + diff[i];\n }\n return res;\n }\n }\n\n}\n", + "title": "1109. Corporate Flight Bookings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n flights that are labeled from 1 to n . You are given an array of flight bookings bookings , where bookings[i] = [first i , last i , seats i ] represents a booking for flights first i through last i ( inclusive ) with seats i seats reserved for each flight in the range. Return an array answer of length n , where answer[i] is the total number of seats reserved for flight i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "1 <= bookings.length <= 2 * 10^4", + "bookings[i].length == 3", + "1 <= first i <= last i <= n", + "1 <= seats i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5Output:[10,55,45,25,25]Explanation:Flight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]", + "image": null + }, + { + "text": "Example 2: Input:bookings = [[1,2,10],[2,2,15]], n = 2Output:[10,25]Explanation:Flight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n\t\tflights = [0]*n\n\t\tfor start,end,seats in bookings:\n\t\t\tflights[start-1] += seats\n\t\t\tif end < n: flights[end] -= seats\n\t\tfor i in range(n-1):\n\t\t\tflights[i+1] += flights[i]\n\t\treturn flights", + "title": "1109. Corporate Flight Bookings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of distinct positive integers locations where locations[i] represents the position of city i . You are also given integers start , finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city i , you can pick any city j such that j != i and 0 <= j < locations.length and move to city j . Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]| . Please notice that |x| denotes the absolute value of x . Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish ). Return the count of all possible routes from start to finish . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= locations.length <= 100", + "1 <= locations[i] <= 10^9", + "All integers in locations are distinct .", + "0 <= start, finish < locations.length", + "1 <= fuel <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5Output:4Explanation:The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3", + "image": null + }, + { + "text": "Example 2: Input:locations = [4,3,1], start = 1, finish = 0, fuel = 6Output:5Explanation:The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5", + "image": null + }, + { + "text": "Example 3: Input:locations = [5,2,1], start = 0, finish = 2, fuel = 3Output:0Explanation:It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 78.44%) | Memory: 41.8 MB (Top 95.21%)\n\n/*\n\nUsing DFS and Memo :\n\n1. We will start from start pos provided and will dfs travel to each other location .\n2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling\n3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path\n4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing .\n\n*/\n\nclass Solution {\n\n int mod = (int)Math.pow(10,9) + 7 ;\n int[][] dp ;\n\n public int countRoutes(int[] locations, int start, int finish, int fuel) {\n\n dp = new int[locations.length][fuel+1] ;\n\n for(int[] row : dp){\n Arrays.fill(row , -1) ;\n }\n\n return dfs(locations , start , finish , fuel);\n }\n\n public int dfs(int[] locations , int cur_location , int finish , int fuel){\n\n if(fuel < 0){\n return 0 ;\n }\n\n if(dp[cur_location][fuel] != -1){\n return dp[cur_location][fuel] ;\n }\n\n int result = 0 ;\n\n if(cur_location == finish){\n result++ ;\n }\n\n for(int i=0 ; i 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3", + "image": null + }, + { + "text": "Example 2: Input:locations = [4,3,1], start = 1, finish = 0, fuel = 6Output:5Explanation:The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5", + "image": null + }, + { + "text": "Example 3: Input:locations = [5,2,1], start = 0, finish = 2, fuel = 3Output:0Explanation:It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3516 ms (Top 53.70%) | Memory: 22.1 MB (Top 43.52%)\n\nfrom bisect import bisect_left\nfrom functools import lru_cache\nclass Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n start = locations[start]\n end = locations[finish]\n locations.sort()\n start = bisect_left(locations, start)\n end = bisect_left(locations, end)\n @lru_cache(None)\n def dfs(i, fuel):\n if fuel == 0 and i == end: return 1\n res = 0\n if i == end: res += 1\n j = i-1\n while j>=0 and abs(locations[j]-locations[i]) <= fuel:\n res += dfs(j, fuel-abs(locations[j]-locations[i]))\n j -= 1\n j = i+1\n while j int:\n total = 1\n mod = 10 ** 9 + 7\n for k in reversed(range(2, n + 1)):\n total = total * ((2 * k - 1) * (2 * k - 2) // 2 + 2 * k - 1)\n total = total % mod\n return total\n", + "title": "1359. Count All Valid Pickup and Delivery Options", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you \"say\" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. For example, the saying and conversion for digit string \"3322251\" : Given a positive integer n , return the n th term of the count-and-say sequence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "countAndSay(1) = \"1\"", + "countAndSay(n) is the way you would \"say\" the digit string from countAndSay(n-1) , which is then converted into a different digit string." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:\"1\"Explanation:This is the base case.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:\"1211\"Explanation:countAndSay(1) = \"1\"\ncountAndSay(2) = say \"1\" = one 1 = \"11\"\ncountAndSay(3) = say \"11\" = two 1's = \"21\"\ncountAndSay(4) = say \"21\" = one 2 + one 1 = \"12\" + \"11\" = \"1211\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String countSay(int n, String[] mapper) {\n if (n == 1) return mapper[1];\n else {\n String say = \"\";\n if (mapper[n-1] != null) say += mapper[n-1];\n else say += countSay(n-1, mapper);\n String count = \"\";\n int cache = Integer.parseInt(say.substring(0, 1));\n int cntr = 1;\n if (say.length() < 2) {\n count += \"1\" + Integer.toString(cache);\n } else {\n for(int i=1;i str:\n if n==1:\n return \"1\"\n \n x=self.countAndSay(n-1)\n count=1\n cur=x[0]\n res=\"\"\n for i in range(1,len(x)):\n if cur==x[i]:\n count+=1\n else:\n res+=str(count)+str(cur)\n count=1\n cur=x[i]\n \n res+=str(count)+str(cur)\n return res\n", + "title": "38. Count and Say", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums of length n and an integer k , return the number of pairs (i, j) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j <= n - 1 and", + "nums[i] * nums[j] is divisible by k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], k = 2Output:7Explanation:The 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 5Output:0Explanation:There does not exist any pair of indices whose corresponding product is divisible by 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 282 ms (Top 52.2%) | Memory: 55.61 MB (Top 63.3%)\n\n//The condition given to us is (a*b % k==0)\n// So we can rewrite the above condition that if any factor of k is present in a and any other factor of k is present in b then their multiplication will be divisble by k\n\n// so gcd(a,k) * gcd(b,k) % k==0 \n\n\nclass Solution {\n public long countPairs(int[] nums, int k) {\n long ans=0;\n HashMap hm=new HashMap<>();\n for(int val:nums){\n int gcd1=gcd(val,k);\n \n for(int gcd2:hm.keySet()){\n if((long)gcd1*gcd2 % k==0){\n ans+=hm.get(gcd2);\n }\n }\n \n hm.put(gcd1,hm.getOrDefault(gcd1,0)+1);\n }\n \n return ans;\n }\n \n //function to calculate gcd \n \n public int gcd(int n1,int n2)\n {\n while(n1%n2!=0){\n int rem=n1%n2;\n n1=n2;\n n2=rem;\n }\n return n2;\n }\n}", + "title": "2183. Count Array Pairs Divisible by K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums of length n and an integer k , return the number of pairs (i, j) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j <= n - 1 and", + "nums[i] * nums[j] is divisible by k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], k = 2Output:7Explanation:The 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 5Output:0Explanation:There does not exist any pair of indices whose corresponding product is divisible by 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n counter = Counter() #hashmap dicitionary of python\n ans = 0\n n = len(nums)\n \n for i in range(n):\n x = math.gcd(k,nums[i]) #ex: 10 = k and we have nums[i] as 12 so gcd will be 2\n want = k // x #what do we want from upper ex: we need 5\n for num in counter:\n if num % want == 0: #so if we find a number that is divisible by 5 then we can multiply it to 12 and make it a factor of 10 for ex we find 20 so it will be 240 which is divisible by 10 hence we will add it to answer\n ans += counter[num] #we are adding the freq as we can find no of numbers that have same factor\n counter[x] += 1 #here we are increasing the freq of 2 so that if we find 5 next time we can add these to the answer\n return ans\n\t\t```", + "title": "2183. Count Array Pairs Divisible by K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1 i , c1 i , r2 i , c2 i ] denotes that the i th artifact is buried in the subgrid where: You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it. Given a 0-indexed 2D integer array dig where dig[i] = [r i , c i ] indicates that you will excavate the cell (r i , c i ) , return the number of artifacts that you can extract . The test cases are generated such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "(r1 i , c1 i ) is the coordinate of the top-left cell of the i th artifact and", + "(r2 i , c2 i ) is the coordinate of the bottom-right cell of the i th artifact." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]Output:1Explanation:The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.\nThere is 1 artifact that can be extracted, namely the red artifact.\nThe blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.\nThus, we return 1.", + "image": "https://assets.leetcode.com/uploads/2019/09/16/untitled-diagram.jpg" + }, + { + "text": "Example 2: Input:n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]Output:2Explanation:Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2019/09/16/untitled-diagram-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 198 ms (Top 10.48%) | Memory: 160.5 MB (Top 45.16%)\nclass Solution {\n public int digArtifacts(int n, int[][] artifacts, int[][] dig) {\n HashSet set = new HashSet<>();\n for (int d[] : dig) set.add(d[0] + \" \" + d[1]);\n int c = 0;\n for (int a[] : artifacts) {\n boolean done = true;\n for (int i = a[0]; i <= a[2]; i++) {\n for (int j = a[1]; j <= a[3]; j++) {\n if (!set.contains(i + \" \" + j)) done = false;\n }\n }\n if (done) c++;\n }\n return c;\n }\n}\n//TC = O(DIG + N^2)", + "title": "2201. Count Artifacts That Can Be Extracted", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , where every two consecutive vertical bars '|' are grouped into a pair . In other words, the 1 st and 2 nd '|' make a pair, the 3 rd and 4 th '|' make a pair, and so forth. Return the number of '*' in s , excluding the '*' between each pair of '|' . Note that each '|' will belong to exactly one pair. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters, vertical bars '|' , and asterisks '*' .", + "s contains an even number of vertical bars '|' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"l|*e*et|c**o|*de|\"Output:2Explanation:The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iamprogrammer\"Output:0Explanation:In this example, there are no asterisks in s. Therefore, we return 0.", + "image": null + }, + { + "text": "Example 3: Input:s = \"yo|uar|e**|b|e***au|tifu|l\"Output:5Explanation:The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 7.47%) | Memory: 42.1 MB (Top 50.88%)\nclass Solution {\n public int countAsterisks(String s) {\n boolean insidePipe = false;\n int count = 0;\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == '|'){\n insidePipe = !insidePipe;\n }\n if(!insidePipe && s.charAt(i) == '*'){\n count++;\n }\n }\n return count;\n }\n}", + "title": "2315. Count Asterisks", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , where every two consecutive vertical bars '|' are grouped into a pair . In other words, the 1 st and 2 nd '|' make a pair, the 3 rd and 4 th '|' make a pair, and so forth. Return the number of '*' in s , excluding the '*' between each pair of '|' . Note that each '|' will belong to exactly one pair. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters, vertical bars '|' , and asterisks '*' .", + "s contains an even number of vertical bars '|' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"l|*e*et|c**o|*de|\"Output:2Explanation:The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"iamprogrammer\"Output:0Explanation:In this example, there are no asterisks in s. Therefore, we return 0.", + "image": null + }, + { + "text": "Example 3: Input:s = \"yo|uar|e**|b|e***au|tifu|l\"Output:5Explanation:The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Added on 2022-08-18 15:51:55.040392\n\nvar countAsterisks = function(s) {\n let green=true, count=0;\n for(let i=0; i= curRunLength)\n {\n count++ ;\n }\n }\n return count ;\n }\n}", + "title": "696. Count Binary Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary string s , return the number of non-empty substrings that have the same number of 0 's and 1 's, and all the 0 's and all the 1 's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110011\"Output:6Explanation:There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10101\"Output:4Explanation:There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 133 ms (Top 63.3%) | Memory: 16.65 MB (Top 94.0%)\n\nclass Solution:\n def countBinarySubstrings(self, s: str) -> int:\n \n # previous continuous occurrence, current continuous occurrence\n pre_cont_occ, cur_cont_occ = 0, 1\n \n # counter for binary substrings with equal 0s and 1s\n counter = 0\n \n\t\t# scan each character pair in s\n for idx in range(1, len(s)):\n \n if s[idx] == s[idx-1]:\n \n # update current continuous occurrence\n cur_cont_occ += 1\n \n else:\n # update counter of binary substrings between prevous character group and current character group\n counter += min(pre_cont_occ, cur_cont_occ)\n\n # update previous as current's continuous occurrence\n pre_cont_occ = cur_cont_occ\n \n # reset current continuous occurrence to 1\n cur_cont_occ = 1\n \n # update for last time\n counter += min(pre_cont_occ, cur_cont_occ)\n \n return counter", + "title": "696. Count Binary Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n . directions[i] can be either 'L' , 'R' , or 'S' denoting whether the i th car is moving towards the left , towards the right , or staying at its current point respectively. Each moving car has the same speed . The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "When two cars moving in opposite directions collide with each other, the number of collisions increases by 2 .", + "When a moving car collides with a stationary car, the number of collisions increases by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:directions = \"RLRSLL\"Output:5Explanation:The collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5.", + "image": null + }, + { + "text": "Example 2: Input:directions = \"LLRR\"Output:0Explanation:No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 59.94%) | Memory: 54.1 MB (Top 76.37%)\n/*\ncars on left side which are moving in left direction are never going to collide,\nSimilarly, cars on right side which are moving right side are never going to collide.\n\nIn between them every car is going to collide.\n*/\n\nclass Solution {\n public int countCollisions(String directions) {\n int left = 0, right = directions.length() - 1;\n\n while (left < directions.length() && directions.charAt(left) == 'L') {\n left++;\n }\n\n while (right >= 0 && directions.charAt(right) == 'R') {\n right--;\n }\n\n int count = 0;\n for (int i = left; i <= right; i++) {\n if (directions.charAt(i) != 'S') {\n count++;\n }\n }\n //combining these three loops - TC : O(N).\n\n return count;\n }\n}", + "title": "2211. Count Collisions on a Road", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n . directions[i] can be either 'L' , 'R' , or 'S' denoting whether the i th car is moving towards the left , towards the right , or staying at its current point respectively. Each moving car has the same speed . The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "When two cars moving in opposite directions collide with each other, the number of collisions increases by 2 .", + "When a moving car collides with a stationary car, the number of collisions increases by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:directions = \"RLRSLL\"Output:5Explanation:The collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5.", + "image": null + }, + { + "text": "Example 2: Input:directions = \"LLRR\"Output:0Explanation:No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countCollisions(self, directions: str) -> int:\n return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))\n", + "title": "2211. Count Collisions on a Road", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two string arrays words1 and words2 , return the number of strings that appear exactly once in each of the two arrays. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words1.length, words2.length <= 1000", + "1 <= words1[i].length, words2[j].length <= 30", + "words1[i] and words2[j] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]Output:2Explanation:- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]Output:0Explanation:There are no strings that appear in each of the two arrays.", + "image": null + }, + { + "text": "Example 3: Input:words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]Output:1Explanation:The only string that appears exactly once in each of the two arrays is \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countWords(String[] words1, String[] words2)\n {\n HashMap map1 = new HashMap<>();\n HashMap map2 = new HashMap<>();\n\t\t\n for(String word : words1)\n map1.put(word,map1.getOrDefault(word,0)+1);\n for(String word : words2)\n map2.put(word,map2.getOrDefault(word,0)+1);\n\t\t\t\n int count = 0;\n for(String word : words1)\n if(map1.get(word) == 1 && map2.getOrDefault(word,0) == 1)\n count++;\n return count;\n }\n}\n", + "title": "2085. Count Common Words With One Occurrence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two string arrays words1 and words2 , return the number of strings that appear exactly once in each of the two arrays. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words1.length, words2.length <= 1000", + "1 <= words1[i].length, words2[j].length <= 30", + "words1[i] and words2[j] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]Output:2Explanation:- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]Output:0Explanation:There are no strings that appear in each of the two arrays.", + "image": null + }, + { + "text": "Example 3: Input:words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]Output:1Explanation:The only string that appears exactly once in each of the two arrays is \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef countWords(self, words1: List[str], words2: List[str]) -> int:\n\t\tcount = Counter(words1 + words2)\n\t\treturn len([word for word in count if count[word] == 2 and word in words1 and word in words2])\n", + "title": "2085. Count Common Words With One Occurrence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []Output:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 50.7 MB (Top 10.84%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n static int count = 0;\n\n static void Postorder(TreeNode root){\n if(root == null){\n return;\n }\n Postorder(root.left);\n Postorder(root.right);\n count++;\n }\n\n public int countNodes(TreeNode root) {\n count = 0;\n Postorder(root);\n return count;\n }\n}", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []Output:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 73 ms (Top 66.36%) | Memory: 23.80 MB (Top 18.91%)\n\nclass Solution:\n # @param {TreeNode} root\n # @return {integer}\n def countNodes(self, root):\n if not root:\n return 0\n leftDepth = self.getDepth(root.left)\n rightDepth = self.getDepth(root.right)\n if leftDepth == rightDepth:\n return pow(2, leftDepth) + self.countNodes(root.right)\n else:\n return pow(2, rightDepth) + self.countNodes(root.left)\n \n def getDepth(self, root):\n if not root:\n return 0\n return 1 + self.getDepth(root.left)", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a 1 , a 2 , ... and b 1 , b 2 , ... are different if there is some i for which a i != b i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' , 'b' , 'c' , or 'd' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bccb\"Output:6Explanation:The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"Output:104860361Explanation:There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 61.21%) | Memory: 50.70 MB (Top 75.86%)\n\nclass Solution {\n public int countPalindromicSubsequences(String str) {\n int[] pre = new int[str.length()];\n\t\tHashMap map = new HashMap<>();\n\t\tint mod = 1000000007;\n\t\tfor(int i = 0; i < str.length(); i++) {\n\t\t\tchar ch = str.charAt(i);\n\t\t\tif(map.containsKey(ch))\n\t\t\t\tpre[i] = map.get(ch);\n\t\t\telse\n\t\t\t\tpre[i] = -1;\n\t\t\tmap.put(ch, i);\n\t\t}\n\t\t\n\t\tint[] next = new int[str.length()];\n\t\tmap = new HashMap<>();\n\t\tfor(int i = str.length() - 1; i >= 0; i--) {\n\t\t\tchar ch = str.charAt(i);\n\t\t\tif(map.containsKey(ch))\n\t\t\t\tnext[i] = map.get(ch);\n\t\t\telse\n\t\t\t\tnext[i] = Integer.MAX_VALUE;\n\t\t\tmap.put(ch, i);\n\t\t}\n\t\t\n\t\tint[][] dp = new int[str.length()][str.length()];\n\t\t\n\t\tfor(int g = 0; g < dp.length; g++) {\n\t\t\tfor(int i = 0, j = g; j < dp[0].length; i++, j++) {\n\t\t\t\tif(g == 0)\n\t\t\t\t\tdp[i][j] = 1;\n\t\t\t\telse if(g == 1)\n\t\t\t\t\tdp[i][j] = 2;\n\t\t\t\telse {\n\t\t\t\t\tif(str.charAt(i) == str.charAt(j)) {\n\t\t\t\t\t\tint n = next[i];\n\t\t\t\t\t\tint p = pre[j];\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(n > p)\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) + 2) % mod;\n\t\t\t\t\t\telse if(n == p)\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) + 1) % mod;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tdp[i][j] = ((2 * dp[i+1][j-1]) - dp[n+1][p-1]) % mod;\n\t\t\t\t\t}else\n\t\t\t\t\t\tdp[i][j] = (dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]) % mod;\n\t\t\t\t}\n if(dp[i][j] < 0)\n dp[i][j] += mod;\n\t\t\t}\n\t\t}\n\t\treturn dp[0][dp[0].length - 1] % mod;\n }\n}\n", + "title": "730. Count Different Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s, return the number of different non-empty palindromic subsequences in s . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a 1 , a 2 , ... and b 1 , b 2 , ... are different if there is some i for which a i != b i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' , 'b' , 'c' , or 'd' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bccb\"Output:6Explanation:The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"Output:104860361Explanation:There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n \n N = len(s)\n mod = 10**9 + 7\n memo = {}\n \n def backTrack(start,end):\n \n if start >= N or end < 0: return 0\n \n key = (start,end) \n \n if key in memo: return memo[key]\n \n strn = s[start:end+1]\n\n memo[key] = 0\n\n for char in \"abcd\":\n if not char in strn: continue\n i = start + strn.index(char)\n j = start + strn.rindex(char)\n memo[key] += backTrack(i+1,j-1) + 2 if i != j else 1\n \n memo[key] %= mod\n \n return memo[key]\n \n return backTrack(0,N-1)\n\n", + "title": "730. Count Different Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of elements that have both a strictly smaller and a strictly greater element appear in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [11,7,2,15]Output:2Explanation:The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear innums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,3,3,90]Output:2Explanation:The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear innums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countElements(int[] nums) {\n int nmin=Integer.MAX_VALUE;\n int nmax=Integer.MIN_VALUE;\n for(int a:nums)\n {\n nmin=Math.min(a,nmin);\n nmax=Math.max(a,nmax);\n }\n int count=0;\n for(int a:nums)\n {\n if(a>nmin && a int:\n M = max(nums)\n m = min(nums)\n return sum(1 for i in nums if m> hMap = new HashMap<>();\n int count = 0;\n for(int i = 0 ; i < nums.length ; i++){\n if(!hMap.containsKey(nums[i])){\n List l = new ArrayList<>();\n l.add(i);\n hMap.put(nums[i],l);\n }else{\n List v = hMap.get(nums[i]);\n for(Integer j : v){\n if((i*j)%k == 0) count++;\n }\n v.add(i);\n hMap.put(nums[i],v);\n }\n }\n return count;\n }\n}", + "title": "2176. Count Equal and Divisible Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,2,2,1,3], k = 2Output:4Explanation:There are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 1Output:0Explanation:Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c\n", + "title": "2176. Count Equal and Divisible Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1 ) or barren (represented by a 0 ). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[1,1,1,1]]Output:2Explanation:The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,1,1]]Output:2Explanation:The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/2.JPG" + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]Output:13Explanation:There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/3.JPG" + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 60.00%) | Memory: 67.7 MB (Top 80.00%)\nclass Solution {\n public int countPyramids(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n int[][] rev = new int[m][n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) rev[m - i - 1][j] = grid[i][j];\n }\n return cal(grid) + cal(rev);\n }\n private int cal(int[][] grid) {\n int m = grid.length, n = grid[0].length, res = 0;\n for (int i = 1; i < m; ++i) {\n for (int j = 0, cnt = 0; j < n; ++j) {\n if (0 != grid[i][j]) cnt++;\n else cnt = 0;\n if (0 == cnt || 0 == j) continue;\n grid[i][j] = Math.min(grid[i - 1][j - 1] + 1, (cnt + 1) >> 1);\n res += grid[i][j] - 1;\n }\n }\n return res;\n }\n}", + "title": "2088. Count Fertile Pyramids in a Land", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1 ) or barren (represented by a 0 ). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[1,1,1,1]]Output:2Explanation:The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/1.JPG" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,1,1]]Output:2Explanation:The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/2.JPG" + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]Output:13Explanation:There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/12/22/3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPyramids(self, grid): \n # dp[i][j] represents the number of layers of the largest pyramid with (i, j) as the vertex.\n # Note that the 1-level pyramid is invalid in the problem, so it should be removed when summing.\n # Note that if grid[i][j] is 0, dp[i][j] will always be 0.\n # The dp recurrence formula is dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 1\n m, n, dp, cnt = len(grid), len(grid[0]), copy.deepcopy(grid), 0\n # triangle\n for i in range(m - 2, -1, -1):\n for j in range(1, n - 1):\n if dp[i][j] > 0 and dp[i + 1][j] > 0:\n dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j + 1]) + 1\n cnt += dp[i][j] - 1\n # inverted triangle\n dp = grid\n for i in range(1, m):\n for j in range(1, n - 1):\n if dp[i][j] > 0 and dp[i - 1][j] > 0:\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j + 1]) + 1\n cnt += dp[i][j] - 1\n return cnt\n", + "title": "2088. Count Fertile Pyramids in a Land", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i ​​​​​​th ​​​​ ​​​​ item of food, return the number of different good meals you can make from this list modulo 10^9 + 7 . Note that items with different indices are considered different even if they have the same deliciousness value. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= deliciousness.length <= 10^5", + "0 <= deliciousness[i] <= 2 20" + ], + "examples": [ + { + "text": "Example 1: Input:deliciousness = [1,3,5,7,9]Output:4Explanation:The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "image": null + }, + { + "text": "Example 2: Input:deliciousness = [1,1,1,3,3,3,7]Output:15Explanation:The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 160 ms (Top 78.2%) | Memory: 55.21 MB (Top 66.3%)\n\nclass Solution {\n int mod = 1000000007;\n public int countPairs(int[] arr) {\n Map map = new HashMap<>();\n int n = arr.length;\n long res = 0;\n for (int num : arr) {\n int power = 1;\n for (int i = 0; i < 22; i++) {\n if (map.containsKey(power - num)) {\n res += map.get(power - num);\n res %= mod;\n }\n power *= 2;\n }\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n return (int) res;\n }\n}", + "title": "1711. Count Good Meals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i ​​​​​​th ​​​​ ​​​​ item of food, return the number of different good meals you can make from this list modulo 10^9 + 7 . Note that items with different indices are considered different even if they have the same deliciousness value. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= deliciousness.length <= 10^5", + "0 <= deliciousness[i] <= 2 20" + ], + "examples": [ + { + "text": "Example 1: Input:deliciousness = [1,3,5,7,9]Output:4Explanation:The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.", + "image": null + }, + { + "text": "Example 2: Input:deliciousness = [1,1,1,3,3,3,7]Output:15Explanation:The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n pows = [2 ** i for i in range(0,22)] # form our list of powers of 2\n dp_seen = {} # dict to store what we've seen - dynamic programming solution for time requirement\n count = 0 # to store the answer\n\n for j in range(0, len(deliciousness)):\n for i in range(0, len(pows)):\n if pows[i] - deliciousness[j] in dp_seen: # \"if we find a previous deliciousness[j] as pows[i] - deliciousness[j], then we will add dp_seen[deliciousness[j]] to count\"\n count += dp_seen[pows[i] - deliciousness[j]]\n if deliciousness[j] in dp_seen:\n dp_seen[deliciousness[j]] += 1 \n else:\n dp_seen[deliciousness[j]] = 1\n \n return count % (10**9 + 7) # the arbitrary modulo, presumably to reduce the answer size\n\t\t```", + "title": "1711. Count Good Meals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]Output:4Explanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]Output:3Explanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1Explanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 50.3 MB (Top 97.37%)\nclass Solution {\n int ans = 0;\n public int goodNodes(TreeNode root) {\n if (root == null) return 0;\n dfs(root, root.val);\n return ans;\n }\n\n void dfs(TreeNode root, int mx) {\n if (root == null) return;\n\n mx = Math.max(mx, root.val);\n if(mx <= root.val) ans++;\n\n dfs(root.left, mx);\n dfs(root.right, mx);\n\n }\n}", + "title": "1448. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]Output:4Explanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]Output:3Explanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1Explanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 132 ms (Top 87.49%) | Memory: 31.70 MB (Top 89.21%)\n\nclass Solution:\n def goodNodes(self, root: TreeNode) -> int:\n # Our counter for the good nodes.\n count = 0\n \n def helper(node, m):\n nonlocal count\n\t\t\t# If we run out of nodes return.\n if not node:\n return\n\t\t\t# If the current node val is >= the largest observed in the path thus far.\n if node.val >= m:\n\t\t\t # Add 1 to the count and update the max observed value.\n count += 1\n m = max(m, node.val)\n\t\t\t# Traverse l and r subtrees.\n helper(node.left, m)\n helper(node.right, m)\n \n helper(root, root.val)\n return count\n", + "title": "1448. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime ( 2 , 3 , 5 , or 7 ). Given an integer n , return the total number of good digit strings of length n . Since the answer may be large, return it modulo 10^9 + 7 . A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"2582\" is good because the digits ( 2 and 8 ) at even positions are even and the digits ( 5 and 2 ) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:5Explanation:The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:400", + "image": null + }, + { + "text": "Example 3: Input:n = 50Output:564908303", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod=(int)1e9+7;\n public int countGoodNumbers(long n) {\n long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd\n long second=n/2;//second power would be n/2 only irrespective of even or odd\n long mul1=power(5,first)%mod;//5 power n/2\n long mul2=power(4,second)%mod;//4 power n/2\n long ans=1;\n ans=(ans*mul1)%mod;//computing total product\n ans=(second!=0)?(ans*mul2)%mod:ans;//computing total product\n return (int)(ans%mod);\n }\n public long power(long x,long y){// this method computes pow(x,y) in O(logn) using divide & conquer\n long temp;\n if(y==0) return 1;//base case (x power 0 = 1)\n temp=power(x,y/2);//computing power for pow(x,y/2) -> divide & conquer step\n if(y%2==0) return (temp*temp)%mod; //using that result of subproblem (2 power 2 = 2 power 1 * 2 power 1)\n else return (x*temp*temp)%mod;//using that result of subproblem (2 power 3 = 2 power 1 * 2 power 1 * 2)\n\t\t// if y is odd, x power y = x power y/2 * x power y/2 * x\n\t\t// if y is even, x power y = x power y/2 * x power y/2\n }\n}\n", + "title": "1922. Count Good Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime ( 2 , 3 , 5 , or 7 ). Given an integer n , return the total number of good digit strings of length n . Since the answer may be large, return it modulo 10^9 + 7 . A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"2582\" is good because the digits ( 2 and 8 ) at even positions are even and the digits ( 5 and 2 ) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:5Explanation:The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:400", + "image": null + }, + { + "text": "Example 3: Input:n = 50Output:564908303", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countGoodNumbers(self, n: int) -> int:\n ans = 1\n rem = n % 2\n n -= rem\n ans = pow(20, n//2, 10**9 + 7)\n if rem == 1:\n ans *= 5\n return ans % (10**9 + 7)\n", + "title": "1922. Count Good Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , and three integers a , b and c . You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: Where |x| denotes the absolute value of x . Return the number of good triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j < k < arr.length", + "|arr[i] - arr[j]| <= a", + "|arr[j] - arr[k]| <= b", + "|arr[i] - arr[k]| <= c" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3Output:4Explanation:There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,3], a = 0, b = 0, c = 1Output:0Explanation:No triplet satisfies all conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 25.39%) | Memory: 41.4 MB (Top 78.10%)\nclass Solution {\n public int countGoodTriplets(int[] arr, int a, int b, int c) {\n int total = 0;\n for (int i = 0; i < arr.length - 2; i++){\n for (int j = i+1; j < arr.length - 1; j++){\n for (int k = j+1; k < arr.length; k++){\n if (helper(arr[i], arr[j]) <= a &&\n helper(arr[j], arr[k]) <= b &&\n helper(arr[k], arr[i]) <= c)\n total++;\n }\n }\n }\n return total;\n }\n\n private static int helper(int x, int y) {\n return Math.abs(x - y);\n }\n}", + "title": "1534. Count Good Triplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , and three integers a , b and c . You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: Where |x| denotes the absolute value of x . Return the number of good triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j < k < arr.length", + "|arr[i] - arr[j]| <= a", + "|arr[j] - arr[k]| <= b", + "|arr[i] - arr[k]| <= c" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3Output:4Explanation:There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,2,2,3], a = 0, b = 0, c = 1Output:0Explanation:No triplet satisfies all conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1794 ms (Top 11.20%) | Memory: 13.8 MB (Top 87.90%)\nclass Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n count = 0\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n for k in range(j+1,len(arr)):\n if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k]-arr[i])<=c:\n count+=1\n return count", + "title": "1534. Count Good Triplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n , both of which are permutations of [0, 1, ..., n - 1] . A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2 . In other words, if we consider pos1 v as the index of the value v in nums1 and pos2 v as the index of the value v in nums2 , then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1 , such that pos1 x < pos1 y < pos1 z and pos2 x < pos2 y < pos2 z . Return the total number of good triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "3 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= n - 1", + "nums1 and nums2 are permutations of [0, 1, ..., n - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,0,1,3], nums2 = [0,1,2,3]Output:1Explanation:There are 4 triplets (x,y,z) such that pos1x< pos1y< pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x< pos2y< pos2z. Hence, there is only 1 good triplet.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]Output:4Explanation:The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long goodTriplets(int[] nums1, int[] nums2) {\n int n= nums1.length;\n int indices[]= new int[n];\n for(int i=0;i0;i--)\n {\n right[i]=R.sum(n)-R.sum(B[i-1]);\n R.update(B[i-1],1);\n }\n long ans=0l;\n for(int i=0;i<=n;i++)\n {\n ans+=left[i]*right[i];\n }\n return ans;\n }\n}\nclass Fenw\n{\n long[]farr;\n int n;\n Fenw(int n)\n {\n this.n=n;\n farr=new long[n+1];\n }\n void update(int index, int val)\n {\n int c=0;\n for(int i=index;i<=n;i+=(i&-i))\n {\n c++;\n farr[i]+=val;\n }\n }\n \n long sum(int index)\n {\n long ans=0l;\n for(int i=index;i>0;i-=(i&-i))\n {\n ans+=farr[i];\n }\n return ans;\n }\n}", + "title": "2179. Count Good Triplets in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed arrays nums1 and nums2 of length n , both of which are permutations of [0, 1, ..., n - 1] . A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2 . In other words, if we consider pos1 v as the index of the value v in nums1 and pos2 v as the index of the value v in nums2 , then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1 , such that pos1 x < pos1 y < pos1 z and pos2 x < pos2 y < pos2 z . Return the total number of good triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "3 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= n - 1", + "nums1 and nums2 are permutations of [0, 1, ..., n - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,0,1,3], nums2 = [0,1,2,3]Output:1Explanation:There are 4 triplets (x,y,z) such that pos1x< pos1y< pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x< pos2y< pos2z. Hence, there is only 1 good triplet.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]Output:4Explanation:The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\nclass Solution:\n def goodTriplets(self, A: List[int], B: List[int]) -> int:\n # Index of a (from A) in B.\n pos = [0] * len(A) \n for idx, b in enumerate(B):\n pos[b] = idx\n \n # Build pre_a[i]: number of elements on a[i]'s left in both A and B.\n # pos_in_b: sorted indexes (in B) of all the visited elements in A.\n pos_in_b, pre_a = SortedList([pos[A[0]]]), [0] \n for a in A[1:]: \n pos_in_b.add(pos[a])\n pre_a.append(pos_in_b.bisect_left(pos[a]))\n \n # Build suf_a[i]: number of elements on a[i]'s right in both A and B.\n pos_in_b, suf_a = SortedList([pos[A[-1]]]), [0]\n for a in reversed(A[:len(A)-1]):\n idx = pos_in_b.bisect(pos[a])\n suf_a.append(len(pos_in_b) - idx)\n pos_in_b.add(pos[a])\n suf_a.reverse()\n \n # Sum up all unique triplets centered on A[i].\n ans = 0\n for x, y in zip(pre_a, suf_a):\n ans += x * y\n return ans\n", + "title": "2179. Count Good Triplets in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i] . Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i] . Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j] . Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,1,1,6,5]Output:3Explanation:At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,6,5,5,4,1]Output:0Explanation:At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countHillValley(int[] nums) {\n int result = 0;\n \n\t\t// Get head start. Find first index for which nums[index] != nums[index-1]\n\t\tint start = 1;\n\t\twhile(start < nums.length && nums[start] == nums[start-1])\n\t\t\tstart++;\n\n\t\tint prev = start-1; //index of prev different value num\n\t\tfor(int i=start; i nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number\n\t\t\t\t\tresult++;\n\t\t\t\tif(nums[i] < nums[prev] && nums[i] < nums[i+1])\n\t\t\t\t\tresult++;\n\t\t\t\tprev = i; // Now your current number will become prev number.\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}", + "title": "2210. Count Hills and Valleys in an Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed integer array nums . An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i] . Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i] . Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j] . Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,1,1,6,5]Output:3Explanation:At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,6,5,5,4,1]Output:0Explanation:At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHillValley(self, nums: List[int]) -> int:\n c = 0\n i = 1\n while i nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):\n c += 1\n i = j\n return c\n", + "title": "2210. Count Hills and Valleys in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an empty set of intervals, implement a data structure that can: Implement the CountIntervals class: Note that an interval [left, right] denotes all the integers x where left <= x <= right . Example 1:", + "description_images": [], + "constraints": [ + "Add an interval to the set of intervals.", + "Count the number of integers that are present in at least one interval." + ], + "examples": [ + { + "text": "Example 1: Input[\"CountIntervals\", \"add\", \"add\", \"count\", \"add\", \"count\"]\n[[], [2, 3], [7, 10], [], [5, 8], []]Output[null, null, null, 6, null, 8]ExplanationCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3); // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count(); // return 6\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8); // add [5, 8] to the set of intervals.\ncountIntervals.count(); // return 8\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 5 and 6 are present in the interval [5, 8].\n // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n // the integers 9 and 10 are present in the interval [7, 10].", + "image": null + } + ], + "follow_up": null, + "solution": "class CountIntervals {\n \n //for storing intervals\n TreeMap map=new TreeMap<>();\n int count=0;\n public CountIntervals() {\n }\n \n public void add(int left, int right) {\n //we are taking left side as reference and calculating ans\n \n //this is the current length\n int add=right-left+1;\n \n //var is the default data type\n //lowerentry gives the value of smaller(smaller largest) entry compared to (left+1)\n //we added +1 bcz there may be a case where left is present in a map\n //lowerentry gives the value(that is)=left){\n //positions are map.left <= left <= min(map.right,right) <= max(map.right,right)\n \n//examples: (1) (2) (3)\n// ____________ _________ _______________ (map)\n// ___________ ________ ____ (our)\n \n //now, left become the smallest value which in this case is map.left\n left=left_bound.getKey();\n \n //same as right become the maximum value\n right=Math.max(left_bound.getValue(),right);\n \n //value overlap means curr answer(add) also change\n //we already calculated the map value (covered area) and added into ans variable\n //calculate/add the new uncovered value\n // right - map.right\n //max(right,map.right) - map.right\n //we are not adding +1 bcz that is already handled by overlaping area\n add=right-left_bound.getValue();\n \n //this is taken so we have to remove\n //at last we added the largest area (which is stored int left,right)\n map.remove(left_bound.getKey());\n }\n \n //check is right overlaping\n //if yes then take the correct values\n //higherEntry gives the largest(largest smallest) value in map\n //we are not taking left+1 bcz that condition is already been satisfied\n //eg. left=5 map contains (5,value)\n //condition is checked in left_bound\n //i.getKey()<=right means curr is beneath our map.left and covering area(overlaping)\n for(var i=map.higherEntry(left); i!=null && i.getKey()<=right; i=map.higherEntry(left)){\n //left <= map.left <= min(right,map.right) <= max(right,map.right)\n \n \n//examples: (1) (2) (3)\n// ____________ _________ _______ (map)\n// ___________ ________ _________________ (our)\n \n \n //now we have our add which is current ans but some area is overlaping\n //so we have to subtract overlaping area\n //+1 bcz [2,5] we have 4 position (2,3,4,5) ; 5-2=>3 ; we ned to add 1\n add-=Math.min(right,i.getValue())-i.getKey()+1;\n \n //right value become the largest among them\n right=Math.max(right,i.getValue());\n \n //we have taken care this entry and calculated left and right now we don't need\n map.remove(i.getKey());\n }\n \n //we pushed the values\n //this entry can be essential for next calls\n map.put(left,right);\n \n //add the current ans\n count+=add;\n \n \n }\n \n public int count() {\n return count;\n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = new CountIntervals();\n * obj.add(left,right);\n * int param_2 = obj.count();\n */\n", + "title": "2276. Count Integers in Intervals", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an empty set of intervals, implement a data structure that can: Implement the CountIntervals class: Note that an interval [left, right] denotes all the integers x where left <= x <= right . Example 1:", + "description_images": [], + "constraints": [ + "Add an interval to the set of intervals.", + "Count the number of integers that are present in at least one interval." + ], + "examples": [ + { + "text": "Example 1: Input[\"CountIntervals\", \"add\", \"add\", \"count\", \"add\", \"count\"]\n[[], [2, 3], [7, 10], [], [5, 8], []]Output[null, null, null, 6, null, 8]ExplanationCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3); // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count(); // return 6\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8); // add [5, 8] to the set of intervals.\ncountIntervals.count(); // return 8\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 5 and 6 are present in the interval [5, 8].\n // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n // the integers 9 and 10 are present in the interval [7, 10].", + "image": null + } + ], + "follow_up": null, + "solution": "class CountIntervals:\n\n def __init__(self):\n\t# initialize the merged intervals list as below to handle edge cases\n self.interv = [(-inf, -inf), (inf, inf)]\n self.cov = 0 \n\n def add(self, left: int, right: int) -> None:\n \n interv = self.interv\n \n\t\t# find the left most position for inserting of the new potentially merged interval\n\t\t# we use `left - 1` because the interval coverage is inclusive\n li = bisect.bisect_left(interv, left - 1, key=itemgetter(1))\n lval = min(interv[li][0], left)\n\t\t\n\t\t# find the right most position for inserting the new potentially merged interval\n\t\t# we use `right + 1` because the interval coverage is inclusive\n ri = bisect.bisect_right(interv, right + 1, key=itemgetter(0))\n rval = max(interv[ri - 1][1], right)\n\n\t\t# find the coverage of the intervals that will be replaced by the new interval\n to_delete = 0\n for _ in range(li, ri):\n to_delete += interv[_][1] - interv[_][0] + 1\n \n\t\t# udpate the coverage\n self.cov += rval - lval + 1 - to_delete\n interv[li: ri] = [(lval, rval)]\n\n def count(self) -> int:\n return self.cov\n", + "title": "2276. Count Integers in Intervals", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer num , return the number of positive integers less than or equal to num whose digit sums are even . The digit sum of a positive integer is the sum of all its digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:num = 4Output:2Explanation:The only integers less than or equal to 4 whose digit sums are even are 2 and 4.", + "image": null + }, + { + "text": "Example 2: Input:num = 30Output:14Explanation:The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.76%) | Memory: 40.70 MB (Top 10.24%)\n\nclass Solution\n{\n public int countEven(int num)\n {\n int count = 0;\n for(int i = 1; i <= num; i++)\n if(sumDig(i))\n count++;\n return count;\n }\n private boolean sumDig(int n)\n {\n int sum = 0;\n while(n > 0)\n {\n sum += n % 10;\n n /= 10;\n }\n\t\treturn (sum&1) == 0 ? true : false;\n }\n}\n", + "title": "2180. Count Integers With Even Digit Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer num , return the number of positive integers less than or equal to num whose digit sums are even . The digit sum of a positive integer is the sum of all its digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:num = 4Output:2Explanation:The only integers less than or equal to 4 whose digit sums are even are 2 and 4.", + "image": null + }, + { + "text": "Example 2: Input:num = 30Output:14Explanation:The 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countEven(self, num: int) -> int:\n if num%2!=0:\n return (num//2)\n s=0\n t=num\n while t:\n s=s+(t%10)\n t=t//10\n if s%2==0:\n return num//2\n else:\n return (num//2)-1\n", + "title": "2180. Count Integers With Even Digit Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array items , where each items[i] = [type i , color i , name i ] describes the type, color, and name of the i th item. You are also given a rule represented by two strings, ruleKey and ruleValue . The i th item is said to match the rule if one of the following is true: Return the number of items that match the given rule . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "ruleKey == \"type\" and ruleValue == type i .", + "ruleKey == \"color\" and ruleValue == color i .", + "ruleKey == \"name\" and ruleValue == name i ." + ], + "examples": [ + { + "text": "Example 1: Input:items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"Output:1Explanation:There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].", + "image": null + }, + { + "text": "Example 2: Input:items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"Output:2Explanation:There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 61.48%) | Memory: 56.3 MB (Top 75.54%)\nclass Solution {\n public int countMatches(List> items, String ruleKey, String ruleValue) {\n int res = 0;\n\n for(int i = 0 ;i int:\n d = {'type': 0, 'color': 1, 'name': 2}\n return sum(1 for item in items if item[d[ruleKey]] == ruleValue)\n", + "title": "1773. Count Items Matching a Rule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:4Explanation:There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:2Explanation:There are 2 groups [1], [2] of size 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countLargestGroup(int n) {\n Map map=new HashMap<>();\n for(int i=1;i<=n;i++){\n int x=sum(i);\n map.put(x,map.getOrDefault(x,0)+1);\n }\n int max=Collections.max(map.values());\n int c=0;\n for(int i:map.values()){\n if(i==max) c++;\n }\n return c;\n }\n public int sum(int g){\n int summ=0;\n while(g!=0){\n int rem=g%10;\n summ+=rem;\n g/=10;\n }\n return summ;\n }\n}```", + "title": "1399. Count Largest Group", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . Each number from 1 to n is grouped according to the sum of its digits. Return the number of groups that have the largest size . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:4Explanation:There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:2Explanation:There are 2 groups [1], [2] of size 1.", + "image": null + } + ], + "follow_up": null, + "solution": "def compute(num):\n\tif num < 10:\n\t\treturn num\n\n\tnewVal = 0\n\n\twhile num > 0:\n\t\tlast = num % 10\n\t\tnewVal += last\n\t\tnum /= 10\n\n\treturn newVal\n\nclass Solution(object):\n\tdef countLargestGroup(self, n):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tmyMap = {}\n\n\t\tfor i in range(1, n + 1):\n\t\t\tval = compute(i)\n\n\t\t\tif val in myMap.keys():\n\t\t\t\tmyMap.get(val).append(i)\n\t\t\telse:\n\t\t\t\tmyMap[val] = [i]\n\n\t\tmaxLen = 0\n\n\t\tfor n in myMap.values():\n\t\t\tmaxLen = max(maxLen, len(n))\n\n\t\tans = 0\n\n\t\tfor n in myMap.values():\n\t\t\tif len(n) == maxLen:\n\t\t\t\tans += 1\n\n\t\treturn ans\n", + "title": "1399. Count Largest Group", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array circles where circles[i] = [x i , y i , r i ] represents the center (x i , y i ) and radius r i of the i th circle drawn on a grid, return the number of lattice points that are present inside at least one circle . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A lattice point is a point with integer coordinates.", + "Points that lie on the circumference of a circle are also considered to be inside it." + ], + "examples": [ + { + "text": "Example 1: Input:circles = [[2,2,1]]Output:5Explanation:The figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-11.png" + }, + { + "text": "Example 2: Input:circles = [[2,2,2],[3,4,1]]Output:16Explanation:The figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-22.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countLatticePoints(int[][] circles) {\n Set answer = new HashSet();\n \n for (int[] c : circles) {\n int x = c[0], y = c[1], r = c[2];\n \n // traversing over all the points that lie inside the smallest square capable of containing the whole circle\n for (int xx = x - r; xx <= x + r; xx++)\n for (int yy = y - r; yy <= y + r; yy++)\n if ((r * r) >= ((x - xx) * (x - xx)) + ((y - yy) * (y - yy)))\n answer.add(xx + \":\" + yy);\n }\n \n return answer.size();\n }\n}\n", + "title": "2249. Count Lattice Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D integer array circles where circles[i] = [x i , y i , r i ] represents the center (x i , y i ) and radius r i of the i th circle drawn on a grid, return the number of lattice points that are present inside at least one circle . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A lattice point is a point with integer coordinates.", + "Points that lie on the circumference of a circle are also considered to be inside it." + ], + "examples": [ + { + "text": "Example 1: Input:circles = [[2,2,1]]Output:5Explanation:The figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-11.png" + }, + { + "text": "Example 2: Input:circles = [[2,2,2],[3,4,1]]Output:16Explanation:The figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).", + "image": "https://assets.leetcode.com/uploads/2022/03/02/exa-22.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countLatticePoints(self, c: List[List[int]]) -> int:\n ans,m=0,[0]*40401\n c=set(((x,y,r) for x,y,r in c))\n for x, y, r in c:\n for i in range(x-r, x+r+1):\n d=int(sqrt(r*r-(x-i)*(x-i)))\n m[i*201+y-d:i*201+y+d+1]=[1]*(d+d+1)\n return sum(m)\n", + "title": "2249. Count Lattice Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 100", + "-100 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]Output:8Explanation:There are 8 negatives number in the matrix.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[3,2],[1,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countNegatives(int[][] grid) {\n int m = grid.length ;\n int n = grid[0].length ;\n int c = 0;\n int count = 0;\n int r = m-1;\n while( r >= 0 && c < n ) {\n if (grid[r][c] < 0 ) {\n r--;\n count += n - c;\n } else{\n c++;\n }\n }\n return count;\n }\n}\n\n", + "title": "1351. Count Negative Numbers in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 100", + "-100 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]Output:8Explanation:There are 8 negatives number in the matrix.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[3,2],[1,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 252 ms (Top 17.18%) | Memory: 15.1 MB (Top 10.42%)\nclass Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n count = 0\n\n for i in grid:\n low = 0\n high = len(i) - 1\n\n while low <= high:\n mid = (low+high)//2\n if i[mid] < 0:\n high = mid - 1\n elif i[mid] >= 0:\n low = mid + 1\n count += (len(i) - low)\n return count", + "title": "1351. Count Negative Numbers in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x . For example, rev(123) = 321 , and rev(120) = 21 . A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices . Since that number can be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j < nums.length", + "nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [42,11,1,97]Output:2Explanation:The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [13,10,35,24,76]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 85.52%) | Memory: 58.10 MB (Top 25.69%)\n\nclass Solution {\n public int countNicePairs(int[] nums) {\n final int mod = 1000000007;\n int len = nums.length;\n for (int i = 0; i < len; i++) {\n nums[i] = nums[i] - reverse(nums[i]);\n }\n Arrays.sort(nums);\n long res = 0;\n for (int i = 0; i < len - 1; i++) {\n long count = 1;\n while (i < len - 1 && nums[i] == nums[i + 1]) {\n count++;\n i++;\n }\n res = (res % mod + (count * (count - 1)) / 2) % mod;\n }\n\n return (int) (res % mod);\n }\n private int reverse(int num) {\n int rev = 0;\n while (num > 0) {\n rev = rev * 10 + num % 10;\n num /= 10;\n }\n return rev;\n }\n}\n", + "title": "1814. Count Nice Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x . For example, rev(123) = 321 , and rev(120) = 21 . A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices . Since that number can be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j < nums.length", + "nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [42,11,1,97]Output:2Explanation:The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [13,10,35,24,76]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 500 ms (Top 94.22%) | Memory: 26.90 MB (Top 76.37%)\n\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n res = 0\n count = {}\n mod = 10**9 + 7\n \n for n in nums:\n rev = int(str(n)[::-1])\n cur = count.get(n - rev, 0)\n res += cur\n count[n - rev] = 1 + cur\n\n return res % mod\n", + "title": "1814. Count Nice Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.", + "A subtree of root is a tree consisting of root and all of its descendants." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,8,5,0,1,null,6]Output:5Explanation:For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:1Explanation:For the node with value 1: The average of its subtree is 1 / 1 = 1.", + "image": "https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int res = 0;\n public int averageOfSubtree(TreeNode root) {\n dfs(root);\n return res;\n }\n \n private int[] dfs(TreeNode node) {\n if(node == null) {\n return new int[] {0,0};\n }\n \n int[] left = dfs(node.left);\n int[] right = dfs(node.right);\n \n int currSum = left[0] + right[0] + node.val;\n int currCount = left[1] + right[1] + 1;\n \n if(currSum / currCount == node.val) {\n res++;\n }\n \n return new int[] {currSum, currCount};\n }\n}\n", + "title": "2265. Count Nodes Equal to Average of Subtree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.", + "A subtree of root is a tree consisting of root and all of its descendants." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,8,5,0,1,null,6]Output:5Explanation:For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.", + "image": "https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:1Explanation:For the node with value 1: The average of its subtree is 1 / 1 = 1.", + "image": "https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n \n \n def calculate_average(root):\n if root:\n self.summ+=root.val\n self.nodecount+=1\n calculate_average(root.left)\n calculate_average(root.right)\n \n \n def calculate_for_each_node(root):\n if root:\n self.summ = 0\n self.nodecount = 0\n calculate_average(root)\n if ((self.summ)//(self.nodecount)) == root.val:\n self.count+=1 \n calculate_for_each_node(root.left)\n calculate_for_each_node(root.right)\n \n \n self.count = 0\n calculate_for_each_node(root) \n return self.count\n\n", + "title": "2265. Count Nodes Equal to Average of Subtree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1 . You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i . Since node 0 is the root, parents[0] == -1 . Each node has a score . To find the score of a node, consider if the node and the edges connected to it were removed . The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == parents.length", + "2 <= n <= 10^5", + "parents[0] == -1", + "0 <= parents[i] <= n - 1 for i != 0", + "parents represents a valid binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,2,0,2,0]Output:3Explanation:- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,2,0]Output:2Explanation:- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 95.33%) | Memory: 67.90 MB (Top 73.63%)\n\nclass Solution {\n /** Algorithm/Theory\n 1. An efficient first step is to build the tree. This way, we can post-order traverse it and determine the product of non-empty subtrees\n 2. Use a simple Node[] array to map node order/value to Node content.\n set node[0] to be the parent.\n loop from 1 to n and if the current node[i] is null, set it as new node. If the parent is null, initialize node[parent[i]].\n set node[parent[i]].left or .right to node[i], depending if left or right is already set.\n 3. Continue post-order traversal. \n - if on a leaf, that leaf will make a score of total -1. Check against the current highest score and set. Return 1 as that leaft has only 1 node\n - if not on a leaf, apply post-oder to left and right.\n 4. After 3b) for each parent node, determine its number of nodes from its subtree: 1 + left + right.\n 6. Once 5 is done, determine the highest score that node will generate.\n This will be Math.max(1, onLeft) * Math.max(1, onRight) * Math.max(1, (totalNodes - nrOfNodesFromSubtree)).\n Basically we are multiplying the remaining 3 groups of nodes that are formed from the removal of that node (left, right, above).\n Pay attention to multiply with 1 (not with 0). The root will have no \"above\" nodes so total - nodesOnSubtree will return 0.\n */\n public int countHighestScoreNodes(int[] parents) {\n Node[] nodes = buildTree(parents);\n long[] highestScore = {0,0};\n countHighestScore(nodes[0], highestScore, parents.length);\n return (int)highestScore[1];\n }\n\n private int countHighestScore(Node node, long[] highestScore, int total) {\n if (node != null) {\n if (node.left == null && node.right == null) {\n // a leaf will have 1 node under(itself) and will produce a total nodes - 1 score.\n if (highestScore[0] == total - 1) {\n highestScore[1]++;\n } else if (highestScore[0] < total - 1) {\n highestScore[0] = total - 1;\n highestScore[1] = 1;\n }\n return 1;\n } else {\n // apply post-order and see how many nodes are left and right\n int onLeft = countHighestScore(node.left, highestScore, total);\n int onRight = countHighestScore(node.right, highestScore, total);\n int totalSubtree = onLeft + onRight + 1;\n // if left or right is null, replace it with 1, multiplication by 1\n long possibleScore = (long) (Math.max(1, onLeft)) * Math.max(onRight, 1)\n * Math.max(1, total - totalSubtree);\n if (highestScore[0] == possibleScore) {\n highestScore[1]++;\n } else if (highestScore[0] < possibleScore) {\n highestScore[0] = possibleScore;\n highestScore[1] = 1;\n }\n return totalSubtree;\n }\n }\n return 0;\n }\n\n private Node[] buildTree(int[] parents) {\n Node[] nodes = new Node[parents.length];\n nodes[0] = new Node();\n for (int i = 1; i < parents.length; i++) {\n // create current node\n if (nodes[i] == null) {\n nodes[i] = new Node();\n }\n // create parent node\n if (nodes[parents[i]] == null) {\n nodes[parents[i]] = new Node();\n }\n // link parent node left or right to this child node.\n if (nodes[parents[i]].left == null) {\n nodes[parents[i]].left = nodes[i];\n } else {\n nodes[parents[i]].right = nodes[i];\n }\n }\n return nodes;\n }\n\n private static class Node {\n Node left;\n Node right;\n }\n}\n", + "title": "2049. Count Nodes With the Highest Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1 . You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i . Since node 0 is the root, parents[0] == -1 . Each node has a score . To find the score of a node, consider if the node and the edges connected to it were removed . The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees. Return the number of nodes that have the highest score . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == parents.length", + "2 <= n <= 10^5", + "parents[0] == -1", + "0 <= parents[i] <= n - 1 for i != 0", + "parents represents a valid binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,2,0,2,0]Output:3Explanation:- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,2,0]Output:2Explanation:- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.", + "image": "https://assets.leetcode.com/uploads/2021/10/03/example-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n graph = collections.defaultdict(list)\n for node, parent in enumerate(parents): # build graph\n graph[parent].append(node)\n n = len(parents) # total number of nodes\n d = collections.Counter()\n def count_nodes(node): # number of children node + self\n p, s = 1, 0 # p: product, s: sum\n for child in graph[node]: # for each child (only 2 at maximum)\n res = count_nodes(child) # get its nodes count\n p *= res # take the product\n s += res # take the sum\n p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)\n d[p] += 1 # count the product\n return s + 1 # return number of children node + 1 (self)\n count_nodes(0) # starting from root (0)\n return d[max(d.keys())] # return max count\n", + "title": "2049. Count Nodes With the Highest Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i] . Return the total number of bad pairs in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,3,3]Output:5Explanation:The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]Output:0Explanation:There are no bad pairs.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 94.02%) | Memory: 55.7 MB (Top 95.47%)\nclass Solution {\n public long countBadPairs(int[] nums) {\n HashMap seen = new HashMap<>();\n long count = 0;\n for(int i = 0; i < nums.length; i++){\n int diff = i - nums[i];\n if(seen.containsKey(diff)){\n count += (i - seen.get(diff));\n }else{\n count += i;\n }\n seen.put(diff, seen.getOrDefault(diff, 0) + 1);\n }\n return count;\n }\n}", + "title": "2364. Count Number of Bad Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i] . Return the total number of bad pairs in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,3,3]Output:5Explanation:The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]Output:0Explanation:There are no bad pairs.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBadPairs(self, nums: List[int]) -> int:\n nums_len = len(nums)\n count_dict = dict()\n for i in range(nums_len):\n nums[i] -= i\n if nums[i] not in count_dict:\n count_dict[nums[i]] = 0\n count_dict[nums[i]] += 1\n \n count = 0\n for key in count_dict:\n count += math.comb(count_dict[key], 2)\n return math.comb(nums_len, 2) - count\n", + "title": "2364. Count Number of Bad Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return the number of homogenous substrings of s . Since the answer may be too large, return it modulo 10^9 + 7 . A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbcccaa\"Output:13Explanation:The homogenous substrings are listed as below:\n\"a\" appears 3 times.\n\"aa\" appears 1 time.\n\"b\" appears 2 times.\n\"bb\" appears 1 time.\n\"c\" appears 3 times.\n\"cc\" appears 2 times.\n\"ccc\" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.", + "image": null + }, + { + "text": "Example 2: Input:s = \"xy\"Output:2Explanation:The homogenous substrings are \"x\" and \"y\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"zzzzz\"Output:15", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 22.57%) | Memory: 50.5 MB (Top 79.00%)\nclass Solution {\n public int countHomogenous(String s) {\n int res = 1;\n int carry = 1;\n int mod = 1000000007;\n for(int i =1;i int:\n res, count, n = 0, 1, len(s)\n for i in range(1,n):\n if s[i]==s[i-1]:\n count+=1\n else:\n if count>1:\n res+=(count*(count-1)//2)\n count=1 \n if count>1:\n res+=(count*(count-1)//2)\n return (res+n)%(10**9+7)", + "title": "1759. Count Number of Homogenous Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR . An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] ( 0-indexed ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 16", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1]Output:2Explanation:The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]Output:7Explanation:All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23- 1 = 7 total subsets.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5]Output:6Explanation:The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countMaxOrSubsets(int[] nums) {\n \n subsets(nums, 0, 0);\n return count;\n }\n \n int count = 0;\n int maxOR = 0;\n \n private void subsets(int[] arr, int vidx, int OR){\n \n if(vidx == arr.length){\n \n if(OR == maxOR){\n count ++;\n }else if(OR > maxOR){\n count = 1;\n maxOR = OR;\n }\n \n return;\n }\n \n // include\n subsets(arr, vidx+1, OR | arr[vidx]);\n \n // exclude\n subsets(arr, vidx+1, OR);\n }\n}\n", + "title": "2044. Count Number of Maximum Bitwise-OR Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR . An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Two subsets are considered different if the indices of the elements chosen are different. The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] ( 0-indexed ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 16", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1]Output:2Explanation:The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]Output:7Explanation:All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23- 1 = 7 total subsets.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5]Output:6Explanation:The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \n def dfs(i,val):\n if maxBit == val : return 1<<(len(nums)-i)\n if i == len(nums): return 0\n return dfs(i+1,val|nums[i]) + dfs(i+1,val)\n maxBit = 0\n for i in nums: maxBit |= i\n return dfs(0,0)\n", + "title": "2044. Count Number of Maximum Bitwise-OR Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3Output:2Explanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1Output:0Explanation:There is no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.36%) | Memory: 75.4 MB (Top 41.15%)\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int i = 0;\n int j = 0;\n int odd = 0;\n int result = 0;\n int temp = 0;\n\n /*\n Approach : two pointer + sliding window technique\n\n step 1 : we have fix i and moving j until our count of odd numbers == k\n step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i\n\n why temp?\n from reducing the size of subarray we will count all the possible subarray from between i and j\n but when i encounter a odd element the odd count will reduce and that while will stop executing\n\n now there are two possible cases\n 1.The leftover elements have a odd number\n 2.The leftover elements do not have any odd number\n\n 1. if our leftover elements have a odd number\n then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed\n that's why temp = 0;\n\n 2. if out leftover elements do not have any odd element left\n then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays\n */\n while(j< nums.length){\n if(nums[j]%2 != 0)\n {\n odd++;\n //if leftover elements have odd element then new window is formed so we set temp = 0;\n temp = 0;\n }\n while(odd ==k){\n temp++;\n if(nums[i] %2 != 0)\n odd--;\n i++;\n }\n //if no leftover elements is odd, each element will part in forming subarray\n //so include them\n result += temp;\n j++;\n\n }\n return result;\n }\n}", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3Output:2Explanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1Output:0Explanation:There is no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 628 ms (Top 69.2%) | Memory: 18.88 MB (Top 60.5%)\n\nclass Solution(object):\n\tdef numberOfSubarrays(self, nums, k):\n\t\t\"\"\"\n\t\te.g. k = 2\n\t\tnums = [2, 2, 1, 2, 1, 2, 2]\n\t\tindex= 0 1 2 3 4 5 6\n\t\t2 even numbers to left of first 1\n\t\t2 even numbers to right of last 1\n\t\ttotal number of subarrays = pick between 0-2 numbers on left, then, pick between 0-2 numbers on right\n\t\ti.e (left+1) (right+1)\n\t\tThen slide window to next set of 2 odd numbers\n\t\t\"\"\"\n\n\t\todds = []\n\n\t\tfor i in range(len(nums)):\n\t\t\tif nums[i] & 1:\n\t\t\t\todds.append(i) #' Find index of all odd numbers '\n\n\t\todds = [-1] + odds + [len(nums)] #' Handle edge cases '\n\t\tnice = 0\n\n\t\tfor i in range(1, len(odds)-k):\n\t\t\tleft = odds[i] - odds[i-1] - 1 #' Number of 'left' even numbers '\n\t\t\tright = odds[i+k] - odds[i+k-1] - 1 #' Number of 'right' even numbers '\n\t\t\tnice += (left+1)*(right+1) #' Total sub-arrays in current window '\n\n\t\treturn nice\n ", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k . The value of |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0 .", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,1], k = 1Output:4Explanation:The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3], k = 3Output:0Explanation:There are no pairs with an absolute difference of 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5,4], k = 2Output:3Explanation:The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 51.83%) | Memory: 44.1 MB (Top 44.46%)\nclass Solution {\n public int countKDifference(int[] nums, int k) {\n Map map = new HashMap<>();\n int res = 0;\n\n for(int i = 0;i< nums.length;i++){\n if(map.containsKey(nums[i]-k)){\n res+= map.get(nums[i]-k);\n }\n if(map.containsKey(nums[i]+k)){\n res+= map.get(nums[i]+k);\n }\n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n\n return res;\n }\n}", + "title": "2006. Count Number of Pairs With Absolute Difference K", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array nums and an integer k , return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k . The value of |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0 .", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,1], k = 1Output:4Explanation:The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3], k = 3Output:0Explanation:There are no pairs with an absolute difference of 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1,5,4], k = 2Output:3Explanation:The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n counter += seen[tmp2]\n \n seen[num] += 1\n \n return counter\n", + "title": "2006. Count Number of Pairs With Absolute Difference K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array rectangles where rectangles[i] = [l i , h i ] indicates that i th rectangle has a length of l i and a height of h i . You are also given a 2D integer array points where points[j] = [x j , y j ] is a point with coordinates (x j , y j ) . The i th rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (l i , h i ) . Return an integer array count of length points.length where count[j] is the number of rectangles that contain the j th point. The i th rectangle contains the j th point if 0 <= x j <= l i and 0 <= y j <= h i . Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length, points.length <= 5 * 10^4", + "rectangles[i].length == points[j].length == 2", + "1 <= l i , x j <= 10^9", + "1 <= h i , y j <= 100", + "All the rectangles are unique .", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]Output:[2,1]Explanation:The first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example1.png" + }, + { + "text": "Example 2: Input:rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]Output:[1,3]Explanation:The first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1094 ms (Top 10.04%) | Memory: 110.7 MB (Top 25.95%)\nclass Solution {\n public int[] countRectangles(int[][] rectangles, int[][] points) {\n int max = Integer.MIN_VALUE;\n\n TreeMap> rects = new TreeMap<>();\n for(int[] rect : rectangles) {\n if (!rects.containsKey(rect[1])) {\n rects.put(rect[1], new ArrayList());\n }\n\n rects.get(rect[1]).add(rect[0]);\n max = Math.max(max, rect[1]);\n }\n\n for(int k : rects.keySet()) {\n Collections.sort(rects.get(k));\n }\n\n int[] ans = new int[points.length];\n for(int i = 0; i < points.length; i++) {\n if (points[i][1] > max) {\n continue;\n }\n\n int count = 0;\n\n for(int key : rects.subMap(points[i][1], max + 1).keySet()) {\n List y = rects.get(key);\n\n count += binarySearch(y, points[i][0]);\n }\n\n ans[i] = count;\n }\n\n return ans;\n }\n\n private int binarySearch(List vals, int val) {\n int lo = 0;\n int hi = vals.size() - 1;\n int id = -1;\n\n while(lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n\n if (vals.get(mid) < val) {\n lo = mid + 1;\n } else {\n id = mid;\n hi = mid - 1;\n }\n }\n\n if (id < 0) {\n return 0;\n }\n\n return vals.size() - id;\n }\n}", + "title": "2250. Count Number of Rectangles Containing Each Point", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array rectangles where rectangles[i] = [l i , h i ] indicates that i th rectangle has a length of l i and a height of h i . You are also given a 2D integer array points where points[j] = [x j , y j ] is a point with coordinates (x j , y j ) . The i th rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (l i , h i ) . Return an integer array count of length points.length where count[j] is the number of rectangles that contain the j th point. The i th rectangle contains the j th point if 0 <= x j <= l i and 0 <= y j <= h i . Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length, points.length <= 5 * 10^4", + "rectangles[i].length == points[j].length == 2", + "1 <= l i , x j <= 10^9", + "1 <= h i , y j <= 100", + "All the rectangles are unique .", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]Output:[2,1]Explanation:The first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example1.png" + }, + { + "text": "Example 2: Input:rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]Output:[1,3]Explanation:The first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].", + "image": "https://assets.leetcode.com/uploads/2022/03/02/example2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def binarySearch(self, arr, target):\n left, right = 0, len(arr)\n ans = None\n while left < right:\n mid = left + ((right-left)//2)\n if arr[mid] >= target:\n # Potential answer found! Now try to minimize it iff possible.\n ans = mid\n right = mid\n else:\n left = mid + 1\n return ans\n \n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n # Sort rectangles based on the lengths\n rectangles.sort() \n # Group rectangles by their height in increasing order of their length\n lengths = {}\n for x,y in rectangles:\n if y in lengths:\n lengths[y].append(x)\n else:\n lengths[y] = [x]\n \n heights = sorted(list(lengths.keys()))\n \n count = [0] * len(points)\n \n for idx, point in enumerate(points):\n x, y = point\n # Get the min height rectangle that would accommodate the y coordinate of current point.\n minHeightRectIdx = self.binarySearch(heights, y)\n if minHeightRectIdx is not None:\n for h in heights[minHeightRectIdx:]:\n # Get the Min length rectangle that would accommodate the x coordinate of current point for all h height rectangles.\n minLenRectIdx = self.binarySearch(lengths[h], x)\n if minLenRectIdx is not None:\n count[idx] += len(lengths[h]) - minLenRectIdx\n \n return count\n", + "title": "2250. Count Number of Rectangles Containing Each Point", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sequence is special if it consists of a positive number of 0 s, followed by a positive number of 1 s, then a positive number of 2 s. Given an array nums (consisting of only integers 0 , 1 , and 2 ), return the number of different subsequences that are special . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, [0,1,2] and [0,0,1,1,1,2] are special.", + "In contrast, [2,1,0] , [1] , and [0,1,2,0] are not special." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,2]Output:3Explanation:The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,0,0]Output:0Explanation:There are no special subsequences in [2,2,0,0].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,0,1,2]Output:7Explanation:The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 81 ms (Top 33.85%) | Memory: 118.7 MB (Top 84.62%)\nclass Solution {\n public int countSpecialSubsequences(int[] nums) {\n long z = 0; //starting and ending with zero\n long zo = 0; //starting with zero and ending with One\n long zot = 0;//starting with zero and ending Two\n int mod = 1000000007;\n for (int i : nums) {\n if (i == 0) {\n z = ((2*z) % mod + 1) % mod; //zero = 2*zero+1\n } else if (i == 1) {\n zo = ((2 * zo) % mod + z % mod) % mod; //zero = 2*zeroOne+zero\n } else {\n zot = ((2 * zot) % mod + zo % mod) % mod; //zeroOneTwo = 2*zeroOneTwo+zeroOne\n }\n }\n return (int)(zot%mod);\n }\n}", + "title": "1955. Count Number of Special Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sequence is special if it consists of a positive number of 0 s, followed by a positive number of 1 s, then a positive number of 2 s. Given an array nums (consisting of only integers 0 , 1 , and 2 ), return the number of different subsequences that are special . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, [0,1,2] and [0,0,1,1,1,2] are special.", + "In contrast, [2,1,0] , [1] , and [0,1,2,0] are not special." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,2]Output:3Explanation:The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,0,0]Output:0Explanation:There are no special subsequences in [2,2,0,0].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,0,1,2]Output:7Explanation:The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4322 ms (Top 46.43%) | Memory: 18 MB (Top 47.62%)\nclass Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n if not nums:\n return 0\n\n last_0 = 0\n last_1 = 0\n last_2 = 0\n\n for i in nums:\n if i == 0:\n last_0 = (2*last_0 + 1)% 1000000007\n elif i == 1:\n last_1 = (last_0 + 2*last_1) % 1000000007\n elif i == 2:\n last_2 = (last_1 + 2*last_2) % 1000000007\n return last_2 % 1000000007", + "title": "1955. Count Number of Special Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose 3 soldiers with index ( i , j , k ) with rating ( rating[i] , rating[j] , rating[k] ).", + "A team is valid if: ( rating[i] < rating[j] < rating[k] ) or ( rating[i] > rating[j] > rating[k] ) where ( 0 <= i < j < k < n )." + ], + "examples": [ + { + "text": "Example 1: Input:rating = [2,5,3,4,1]Output:3Explanation:We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).", + "image": null + }, + { + "text": "Example 2: Input:rating = [2,1,3]Output:0Explanation:We can't form any team given the conditions.", + "image": null + }, + { + "text": "Example 3: Input:rating = [1,2,3,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Smaller * Larger Solution\n// sum of #smaller * #larger\n// Time complexity: O(N^2)\n// Space complexity: O(1)\nclass Solution {\n public int numTeams(int[] rating) {\n final int N = rating.length;\n int res = 0;\n for (int i = 1; i < N; i++) {\n res += smaller(rating, i, -1) * larger(rating, i, 1);\n res += larger(rating, i, -1) * smaller(rating, i, 1);\n }\n return res;\n }\n \n private int smaller(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] < t) count++;\n i += diff;\n }\n return count;\n }\n \n private int larger(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] > t) count++;\n i += diff;\n }\n return count;\n }\n}\n", + "title": "1395. Count Number of Teams", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose 3 soldiers with index ( i , j , k ) with rating ( rating[i] , rating[j] , rating[k] ).", + "A team is valid if: ( rating[i] < rating[j] < rating[k] ) or ( rating[i] > rating[j] > rating[k] ) where ( 0 <= i < j < k < n )." + ], + "examples": [ + { + "text": "Example 1: Input:rating = [2,5,3,4,1]Output:3Explanation:We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).", + "image": null + }, + { + "text": "Example 2: Input:rating = [2,1,3]Output:0Explanation:We can't form any team given the conditions.", + "image": null + }, + { + "text": "Example 3: Input:rating = [1,2,3,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numTeams(self, ratings: List[int]) -> int:\n upper_dps = [0 for _ in range(len(ratings))]\n lower_dps = [0 for _ in range(len(ratings))]\n \n count = 0\n for i in range(len(ratings)):\n for j in range(i):\n if ratings[j] < ratings[i]:\n count += upper_dps[j]\n upper_dps[i] += 1\n else:\n count += lower_dps[j]\n lower_dps[i] += 1\n \n return count\n", + "title": "1395. Count Number of Teams", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, to add the letter 's' , Alice has to press '7' four times. Similarly, to add the letter 'k' , Alice has to press '5' twice.", + "Note that the digits '0' and '1' do not map to any letters, so Alice does not use them." + ], + "examples": [ + { + "text": "Example 1: Input:pressedKeys = \"22233\"Output:8Explanation:The possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.", + "image": null + }, + { + "text": "Example 2: Input:pressedKeys = \"222222222222222222222222222222222222\"Output:82876089Explanation:There are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109+ 7, we return 2082876103 % (109+ 7) = 82876089.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 90.12%) | Memory: 45.20 MB (Top 64.2%)\n\nclass Solution {\n int mod = (1000000007);\n\n public int countTexts(String pressedKeys) {\n int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 };\n int n = pressedKeys.length();\n int[] dp = new int[n + 1];\n dp[n] = 1;\n\n for (int ind = n - 1; ind >= 0; ind--) {\n int count = 0;\n int num = pressedKeys.charAt(ind) - '0';\n int rep = key[num];\n for (int i = 0; i < rep && ind + i < pressedKeys.length() && pressedKeys.charAt(ind) == pressedKeys.charAt(ind + i); i++) {\n count += dp[ind+i+1];\n count %= mod;\n }\n dp[ind] = count;\n }\n return dp[0];\n }\n}\n", + "title": "2266. Count Number of Texts", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, to add the letter 's' , Alice has to press '7' four times. Similarly, to add the letter 'k' , Alice has to press '5' twice.", + "Note that the digits '0' and '1' do not map to any letters, so Alice does not use them." + ], + "examples": [ + { + "text": "Example 1: Input:pressedKeys = \"22233\"Output:8Explanation:The possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.", + "image": null + }, + { + "text": "Example 2: Input:pressedKeys = \"222222222222222222222222222222222222\"Output:82876089Explanation:There are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109+ 7, we return 2082876103 % (109+ 7) = 82876089.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2740 ms (Top 30.44%) | Memory: 19.5 MB (Top 65.22%)\nclass Solution(object):\n def countTexts(self, pressedKeys):\n \"\"\"\n :type pressedKeys: str\n :rtype: int\n \"\"\"\n dp = [1] + [0]*len(pressedKeys)\n mod = 10**9 + 7\n for i, n in enumerate(pressedKeys):\n dp[i+1] = dp[i]\n # check if is continous\n if i >= 1 and pressedKeys[i-1] == n:\n dp[i+1] += dp[i-1]\n dp[i+1] %= mod\n if i >= 2 and pressedKeys[i-2] == n:\n dp[i+1] += dp[i-2]\n dp[i+1] %= mod\n # Special case for '7' and '9' that can have 4 characters combination\n if i >= 3 and pressedKeys[i-3] == n and (n == \"7\" or n == \"9\"):\n dp[i+1] += dp[i-3]\n dp[i+1] %= mod\n return dp[-1]", + "title": "2266. Count Number of Texts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a street with n * 2 plots , where there are n plots on each side of the street. The plots on each side are numbered from 1 to n . On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street . Since the answer may be very large, return it modulo 10^9 + 7 . Note that if a house is placed on the i th plot on one side of the street, a house can also be placed on the i th plot on the other side of the street. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:4Explanation:Possible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:9Explanation:The 9 possible arrangements are shown in the diagram above.", + "image": "https://assets.leetcode.com/uploads/2022/05/12/arrangements.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod = (int)1e9+7;\n public int countHousePlacements(int n) {\n \n if(n == 1)\n return 4;\n if(n == 2)\n return 9;\n long a = 2;\n long b = 3;\n if(n==1)\n return (int)(a%mod);\n if(n==2)\n return (int)(b%mod);\n long c=0;\n for(int i=3;i<=n;i++)\n {\n c = (a+b)%mod;\n a=b%mod;\n b=c%mod;\n }\n \n return (int)((c*c)%mod);\n }\n}\n", + "title": "2320. Count Number of Ways to Place Houses", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a street with n * 2 plots , where there are n plots on each side of the street. The plots on each side are numbered from 1 to n . On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street . Since the answer may be very large, return it modulo 10^9 + 7 . Note that if a house is placed on the i th plot on one side of the street, a house can also be placed on the i th plot on the other side of the street. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:4Explanation:Possible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:9Explanation:The 9 possible arrangements are shown in the diagram above.", + "image": "https://assets.leetcode.com/uploads/2022/05/12/arrangements.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countHousePlacements(self, n: int) -> int:\n \n \n @lru_cache(None)\n def rec(i, k):\n \n # i is the index of the house \n # k is the state of last house, 1 if there was a house on the last index else 0\n \n if i>=n:\n return 1\n \n elif k==0:\n return rec(i+1,1) + rec(i+1,0)\n \n else:\n return rec(i+1,0)\n \n \n \n #l1 are the combinations possible in lane 1, the final answer will be the square \n\t\t#of of l1 as for every combination of l1 there will be \"l1\" combinations in lane2.\n \n l1 = rec(1,0) + rec(1,1)\n \n \n mod = 10**9 +7\n return pow(l1, 2, mod) #use this when there is mod involved along with power \n \n", + "title": "2320. Count Number of Ways to Place Houses", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the count of all numbers with unique digits, x , where 0 <= x < 10 n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:91Explanation:The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.90 MB (Top 52.99%)\n\nclass Solution {\n public int countNumbersWithUniqueDigits(int n) \n {\n\t/*\n\t 9 * 9 + 10 for n = 2\n 9 * 9 * 8 + 10 for n = 3\n 9 * 9 * 8 * 7 + 10 for n = 4\n 9 * 9 * 8 * 7 * 6 + 10 for n = 5\n\t*/\t\n if(n == 0)\n return 1;\n \n if(n == 1)\n return 10;\n \n int product =9;\n int result = 10;\n \n for(int i=2; i<=n; i++)\n {\n product = product * (11-i);\n result += product;\n }\n \n return result;\n }\n}\n", + "title": "357. Count Numbers with Unique Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the count of all numbers with unique digits, x , where 0 <= x < 10 n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:91Explanation:The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n \n if n == 0:\n return 1\n \n table = [0]*(n+1)\n \n table[0] = 1\n table[1] = 9\n \n for i in range(2, n+1):\n table[i] = table[i-1]*(11-i)\n \n return sum(table)\n", + "title": "357. Count Numbers with Unique Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two non-negative integers low and high . Return the count of odd numbers between low and high (inclusive) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 3, high = 7Output:3Explanation:The odd numbers between 3 and 7 are [3,5,7].", + "image": null + }, + { + "text": "Example 2: Input:low = 8, high = 10Output:1Explanation:The odd numbers between 8 and 10 are [9].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 5.10%)\nclass Solution {\n public int countOdds(int low, int high) {\n if(low%2==0 && high%2==0){\n return (high-low)/2;\n }\n return (high-low)/2+1;\n }\n}", + "title": "1523. Count Odd Numbers in an Interval Range", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two non-negative integers low and high . Return the count of odd numbers between low and high (inclusive) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 3, high = 7Output:3Explanation:The odd numbers between 3 and 7 are [3,5,7].", + "image": null + }, + { + "text": "Example 2: Input:low = 8, high = 10Output:1Explanation:The odd numbers between 8 and 10 are [9].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countOdds(self, low: int, high: int) -> int: \n total_nums = high - low\n \n answer = total_nums // 2\n \n if low % 2 == 1 and high % 2 == 1:\n return answer + 1\n \n if low % 2 == 1:\n answer = answer + 1\n \n if high % 2 == 1:\n answer = answer + 1\n \n return answer\n", + "title": "1523. Count Odd Numbers in an Interval Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer n , the number of teams in a tournament that has strange rules: Return the number of matches played in the tournament until a winner is decided. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the current number of teams is even , each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.", + "If the current number of teams is odd , one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:6Explanation:Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.", + "image": null + }, + { + "text": "Example 2: Input:n = 14Output:13Explanation:Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfMatches(int n) {\n\t\t// This is the problem's base case; we know that if n == 1,\n\t\t// the number of matches played must be 0, since the last team left\n\t\t// can't play a match against themselves.\n if (n == 1) return 0;\n \n\t\t// We declare an int to hold our recursive solution.\n int res;\n\t\t\n\t\t// We initialize res using a recursive call, reducing n \n\t\t// as described in the problem.\n if (n % 2 == 0) {\n res = numberOfMatches(n / 2);\n\t\t\t// After the recursive call is executed, we add the appropriate value to \n\t\t\t// our solution variable.\n res += n / 2;\n }\n else {\n res = numberOfMatches((n - 1) / 2 + 1);\n res += (n - 1) / 2;\n }\n \n\t\t// Our initial call to numberOfMatches()\n\t\t// will return the total number of matches \n\t\t// added to res in each recursive call.\n return res;\n }\n}\n", + "title": "1688. Count of Matches in Tournament", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n , the number of teams in a tournament that has strange rules: Return the number of matches played in the tournament until a winner is decided. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the current number of teams is even , each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.", + "If the current number of teams is odd , one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:6Explanation:Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.", + "image": null + }, + { + "text": "Example 2: Input:n = 14Output:13Explanation:Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef numberOfMatches(self, n: int) -> int:\n\t\treturn n - 1", + "title": "1688. Count of Matches in Tournament", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and two integers lower and upper , return the number of range sums that lie in [lower, upper] inclusive . Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "-10^5 <= lower <= upper <= 10^5", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,5,-1], lower = -2, upper = 2Output:3Explanation:The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0], lower = 0, upper = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 26.64%) | Memory: 76.2 MB (Top 86.68%)\nclass Solution {\n public int countRangeSum(int[] nums, int lower, int upper) {\n int n = nums.length, ans = 0;\n long[] pre = new long[n+1];\n for (int i = 0; i < n; i++){\n pre[i+1] = nums[i] + pre[i];\n }\n Arrays.sort(pre);\n int[] bit = new int[pre.length+2];\n long sum = 0;\n for (int i = 0; i < n; i++){\n update(bit, bs(sum, pre), 1);\n sum += nums[i];\n ans += sum(bit, bs(sum-lower, pre)) - sum(bit, bs(sum-upper-1, pre));\n }\n return ans;\n }\n\n private int bs(long sum, long[] pre){ // return the index of first number bigger than sum\n int lo = 0, hi = pre.length;\n while(lo < hi){\n int mid = (lo+hi) >> 1;\n if (pre[mid]>sum){\n hi=mid;\n }else{\n lo=mid+1;\n }\n }\n return lo;\n }\n\n private void update(int[] bit, int idx, int inc){\n for (++idx; idx < bit.length; idx += idx & -idx){\n bit[idx] += inc;\n }\n }\n\n private int sum(int[] bit, int idx){\n int ans = 0;\n for (++idx; idx > 0; idx -= idx & -idx){\n ans += bit[idx];\n }\n return ans;\n }\n}", + "title": "327. Count of Range Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and two integers lower and upper , return the number of range sums that lie in [lower, upper] inclusive . Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "-10^5 <= lower <= upper <= 10^5", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,5,-1], lower = -2, upper = 2Output:3Explanation:The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0], lower = 0, upper = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n acc = list(accumulate(nums))\n ans = a = 0\n for n in nums:\n a += n\n ans += sum(1 for x in acc if lower <= x <= upper)\n acc.pop(0)\n lower += n\n upper += n\n return ans\n", + "title": "327. Count of Range Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,6,1]Output:[2,1,1,0]Explanation:To the right of 5 there are2smaller elements (2 and 1).\nTo the right of 2 there is only1smaller element (1).\nTo the right of 6 there is1smaller element (1).\nTo the right of 1 there is0smaller element.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-1]Output:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 97.6%) | Memory: 57.69 MB (Top 69.7%)\n\nclass Solution { \n public List countSmaller(int[] nums) {\n int min = 20001;\n int max = -1;\n for (int num : nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n \n min--;\n int[] count = new int[max-min+1];\n Integer[] result = new Integer[nums.length];\n for (int i = nums.length-1; i >=0; i--) {\n int k = nums[i]-min-1;\n int c = 0;\n do {\n c += count[k];\n k -= (-k&k);\n } while (k > 0);\n result[i] = c;\n \n k = nums[i]-min;\n while (k < count.length) {\n count[k]++;\n k += (-k&k);\n }\n }\n \n return Arrays.asList(result);\n }\n}", + "title": "315. Count of Smaller Numbers After Self", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,6,1]Output:[2,1,1,0]Explanation:To the right of 5 there are2smaller elements (2 and 1).\nTo the right of 2 there is only1smaller element (1).\nTo the right of 6 there is1smaller element (1).\nTo the right of 1 there is0smaller element.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-1]Output:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6019 ms (Top 15.52%) | Memory: 35.5 MB (Top 33.31%)\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n # build the binary indexed tree\n num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0\n tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1\n\n result = [0] * len(nums)\n\n # iterate from right to left\n for result_index in range(len(nums) - 1, -1, -1):\n n = nums[result_index]\n # add 10**4 to n to account for negative numbers\n i = n + 10 ** 4\n\n # convert to 1-based index for the tree\n i += 1\n # perform range sum query of buckets [-inf, n-1], where n is current number\n # because we want n - 1 for range sum query of [-inf, n-1], not n, subtract 1 from i:\n i -= 1\n\n val = 0\n while i != 0:\n val += tree[i]\n # get parent node by subtracting least significant set bit\n i -= i & -i\n\n result[result_index] = val\n\n # update the binary indexed tree with new bucket\n i = n + 10 ** 4\n i += 1\n while i < len(tree):\n tree[i] += 1\n # get next node to update by adding the least significant set bit\n i += i & -i\n\n return result", + "title": "315. Count of Smaller Numbers After Self", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two non-negative integers num1 and num2 . In one operation , if num1 >= num2 , you must subtract num2 from num1 , otherwise subtract num1 from num2 . Return the number of operations required to make either num1 = 0 or num2 = 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if num1 = 5 and num2 = 4 , subtract num2 from num1 , thus obtaining num1 = 1 and num2 = 4 . However, if num1 = 4 and num2 = 5 , after one operation, num1 = 4 and num2 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 2, num2 = 3Output:3Explanation:- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.", + "image": null + }, + { + "text": "Example 2: Input:num1 = 10, num2 = 10Output:1Explanation:- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 69.19%)\nclass Solution {\n public int countOperations(int num1, int num2) {\n int count=0;\n while(num1!=0 && num2!=0){\n if(num1= num2 , you must subtract num2 from num1 , otherwise subtract num1 from num2 . Return the number of operations required to make either num1 = 0 or num2 = 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if num1 = 5 and num2 = 4 , subtract num2 from num1 , thus obtaining num1 = 1 and num2 = 4 . However, if num1 = 4 and num2 = 5 , after one operation, num1 = 4 and num2 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = 2, num2 = 3Output:3Explanation:- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.", + "image": null + }, + { + "text": "Example 2: Input:num1 = 10, num2 = 10Output:1Explanation:- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 87.66%) | Memory: 17.40 MB (Top 8.01%)\n\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n count = 0\n while num1 != 0 and num2 != 0:\n if num1 >= num2:\n num1 -= num2\n else:\n num2 -= num1\n count +=1\n return count\n", + "title": "2169. Count Operations to Obtain Zero", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an undirected graph defined by an integer n , the number of nodes, and a 2D integer array edges , the edges in the graph, where edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . You are also given an integer array queries . Let incident(a, b) be defined as the number of edges that are connected to either node a or b . The answer to the j th query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: Return an array answers such that answers.length == queries.length and answers[j] is the answer of the j th query . Note that there can be multiple edges between the same two nodes. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "a < b", + "incident(a, b) > queries[j]" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]Output:[6,5]Explanation:The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/winword_2021-06-08_00-58-39.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]Output:[10,10,9,8,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 80.0%) | Memory: 92.30 MB (Top 62.86%)\n\nclass Solution {\n // Time : O(E + N + Q)\n // Space : O(N + E)\n public int[] countPairs(int n, int[][] edges, int[] queries) {\n // Key: edge ID Value: count of duplicate edge\n Map edgeCount = new HashMap<>();\n // degree[i] : number of edge for node i (0-indexed)\n int[] degree = new int[n];\n \n for (int[] e : edges) { // recording all edges ==> O(E) Time / Space\n int u = e[0] - 1;\n int v = e[1] - 1;\n degree[u]++;\n degree[v]++;\n \n int eId = Math.min(u, v) * n + Math.max(u, v);\n edgeCount.put(eId, edgeCount.getOrDefault(eId, 0) + 1);\n }\n \n // Key: Degree Value: Frequency (number of nodes with that degree)\n Map degreeCount = new HashMap<>(); // ==> O(U) Time / Space\n int maxDegree = 0;\n for (int d : degree) {\n degreeCount.put(d, degreeCount.getOrDefault(d, 0) + 1);\n maxDegree = Math.max(maxDegree, d);\n }\n \n \n int[] count = new int[2 * maxDegree + 1]; \n \n for (int d1 : degreeCount.keySet()) { // O(E)-time (seems to be O(U ^ 2))\n for (int d2 : degreeCount.keySet()) {\n count[d1 + d2] += (d1 == d2) ? degreeCount.get(d1) * (degreeCount.get(d1)- 1) \n : degreeCount.get(d1) * degreeCount.get(d2);\n }\n }\n for (int i = 0; i < count.length; i++) count[i] /= 2; // each pair is counted twice\n \n \n for (int e : edgeCount.keySet()) { // O(E)-time\n int u = e / n;\n int v = e % n; \n \n count[degree[u] + degree[v]]--;\n count[degree[u] + degree[v] - edgeCount.get(e)]++;\n }\n \n for (int i = count.length - 2; i >= 0; i--) { // O(U)-time \n count[i] += count[i+1];\n }\n \n \n int[] res = new int[queries.length]; // O(Q)-time\n for (int q = 0; q < queries.length; q++) {\n res[q] = ((queries[q] + 1) >= count.length) ? 0 : count[queries[q] + 1];\n }\n return res;\n }\n}\n", + "title": "1782. Count Pairs Of Nodes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an undirected graph defined by an integer n , the number of nodes, and a 2D integer array edges , the edges in the graph, where edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . You are also given an integer array queries . Let incident(a, b) be defined as the number of edges that are connected to either node a or b . The answer to the j th query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: Return an array answers such that answers.length == queries.length and answers[j] is the answer of the j th query . Note that there can be multiple edges between the same two nodes. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "a < b", + "incident(a, b) > queries[j]" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]Output:[6,5]Explanation:The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/winword_2021-06-08_00-58-39.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]Output:[10,10,9,8,6]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n p_c = [0] * (n+1) # point counter\n e_c = defaultdict(int) # edge counter\n \n for a,b in edges:\n p_c[a] += 1\n p_c[b] += 1\n if a=0;i--){\n // count all the element whose xor is less the low\n int cnt1=trie.maxXor(nums[i],low);\n // count all the element whose xor is less the high+1\n int cnt2=trie.maxXor(nums[i],high+1);\n trie.add(nums[i]);\n cnt+=cnt2-cnt1;\n }\n return cnt;\n }\n}\nclass Trie{\n private Node root;\n Trie(){\n root=new Node();\n }\n public void add(int x){\n Node cur=root;\n for(int i=31;i>=0;i--){\n int bit=(x>>i)&1;\n if(!cur.contains(bit)){\n cur.put(bit);\n }\n cur.inc(bit);\n cur=cur.get(bit);\n }\n }\n public int maxXor(int x,int limit){\n int low_cnt=0;\n Node cur=root;\n for(int i=31;i>=0 && cur!=null;i--){\n int bit=(x>>i)&(1);\n int req=(limit>>i)&1;\n if(req==1){\n if(cur.contains(bit)){\n low_cnt+=cur.get(bit).cnt;\n }\n cur=cur.get(1-bit);\n }else{\n cur=cur.get(bit);\n }\n\n }\n return low_cnt;\n\n }\n}\nclass Node{\n private Node links[];\n int cnt;\n Node(){\n links=new Node[2];\n cnt=0;\n }\n public void put(int bit){\n links[bit]=new Node();\n }\n public Node get(int bit){\n return links[bit];\n }\n public boolean contains(int bit){\n return links[bit]!=null;\n }\n public void inc(int bit){\n links[bit].cnt++;\n }\n}", + "title": "1803. Count Pairs With XOR in a Range", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a (0-indexed) integer array nums and two integers low and high , return the number of nice pairs . A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] <= 2 * 10^4", + "1 <= low <= high <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,2,7], low = 2, high = 6Output:6Explanation:All nice pairs (i, j) are as follows:\n - (0, 1): nums[0] XOR nums[1] = 5 \n - (0, 2): nums[0] XOR nums[2] = 3\n - (0, 3): nums[0] XOR nums[3] = 6\n - (1, 2): nums[1] XOR nums[2] = 6\n - (1, 3): nums[1] XOR nums[3] = 3\n - (2, 3): nums[2] XOR nums[3] = 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,4,2,1], low = 5, high = 14Output:8Explanation:All nice pairs (i, j) are as follows:\n​​​​​ - (0, 2): nums[0] XOR nums[2] = 13\n  - (0, 3): nums[0] XOR nums[3] = 11\n  - (0, 4): nums[0] XOR nums[4] = 8\n  - (1, 2): nums[1] XOR nums[2] = 12\n  - (1, 3): nums[1] XOR nums[3] = 10\n  - (1, 4): nums[1] XOR nums[4] = 9\n  - (2, 3): nums[2] XOR nums[3] = 6\n  - (2, 4): nums[2] XOR nums[4] = 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1588 ms (Top 85.61%) | Memory: 20.60 MB (Top 80.3%)\n\nclass Solution:\n def countPairs(self, nums, low, high):\n return self._countPairs(nums, high + 1) - self._countPairs(nums, low)\n \n def _countPairs(self, nums, high):\n res = 0\n for k in range(31, -1, -1):\n target = high >> k\n if target & 1 == 0:\n continue\n target -= 1\n counter = Counter(num >> k for num in nums)\n for mask in counter:\n res += counter[mask] * counter[target ^ mask]\n if mask == target ^ mask:\n res -= counter[mask]\n return res // 2\n", + "title": "1803. Count Pairs With XOR in a Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string array words and a string s , where words[i] and s comprise only of lowercase English letters . Return the number of strings in words that are a prefix of s . A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, s.length <= 10", + "words[i] and s consist of lowercase English letters only ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"Output:3Explanation:The strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"a\"], s = \"aa\"Output:2Explanation:Both of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPrefixes(String[] words, String s) {\n int i = 0;\n int j = 0;\n int count = 0;\n for(int k = 0; k < words.length; k++){\n if(words[k].length() > s.length()){\n continue;\n }\n \n while(i < words[k].length() && words[k].charAt(i) == s.charAt(j)){\n i++;\n j++;\n }\n if(i == words[k].length()){\n count++;\n }\n i = 0;\n j = 0;\n }\n return count;\n }\n}\n", + "title": "2255. Count Prefixes of a Given String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string array words and a string s , where words[i] and s comprise only of lowercase English letters . Return the number of strings in words that are a prefix of s . A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, s.length <= 10", + "words[i] and s consist of lowercase English letters only ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"Output:3Explanation:The strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"a\"], s = \"aa\"Output:2Explanation:Both of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 25.9%) | Memory: 16.47 MB (Top 86.6%)\n\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n return len([i for i in words if s.startswith(i)])", + "title": "2255. Count Prefixes of a Given String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of prime numbers that are strictly less than n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 5 * 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:4Explanation:There are 4 prime numbers less than 10, they are 2, 3, 5, 7.", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPrimes(int n) {\n boolean check[]=new boolean[n];int count=0;\n for(int i=2;i int:\n # Prerequisite:\n # What is prime number. What are they just the starting. \n \n truth = [True]*n # making a list of lenght n. And keep all the values as True.\n if n<2: # as 0 & 1 are not prime numbers. \n return 0\n truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.\n \n i=2 # As we know 0 & 1 are not prime.\n while i*i0){\n count++;\n }\n }\n return count;\n }\n public void check(int sr,int sc,int [][]grid){\n int mbox=sr*grid[0].length+sc;\n for(int i=sr;irank[y]){\n parent[y]=x;\n }else if(rank[y]>rank[x]){\n parent[x]=y;\n }else{\n parent[x]=y;\n rank[y]++;\n }\n }\n}", + "title": "1267. Count Servers that Communicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a map of a server center, represented as a m * n integer matrix grid , where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-6.jpg", + "https://assets.leetcode.com/uploads/2019/11/13/untitled-diagram-4.jpg", + "https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-1-3.jpg" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m <= 250", + "1 <= n <= 250", + "grid[i][j] == 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]Output:0Explanation:No servers can communicate with others.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0],[1,1]]Output:3Explanation:All three servers can communicate with at least one other server.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]Output:4Explanation:The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n def helper(row,col,count):\n for c in range(len(grid[0])):\n if c == col:\n continue\n if grid[row][c] == 1:\n count += 1\n return count\n for r in range(len(grid)):\n if r == row:\n continue\n if grid[r][col] == 1:\n count += 1\n return count\n return count\n count = 0\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 1:\n count = helper(row,col,count)\n return count\n", + "title": "1267. Count Servers that Communicate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of strings of length n that consist only of vowels ( a , e , i , o , u ) and are lexicographically sorted . A string s is lexicographically sorted if for all valid i , s[i] is the same as or comes before s[i+1] in the alphabet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:5Explanation:The 5 sorted strings that consist of vowels only are[\"a\",\"e\",\"i\",\"o\",\"u\"].", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:15Explanation:The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.", + "image": null + }, + { + "text": "Example 3: Input:n = 33Output:66045", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.04 MB (Top 74.4%)\n\nclass Solution {\n public int countVowelStrings(int n) {\n int a=1,e=1,i=1,o=1,u=1;\n for(int k=1;k int:\n dp = [[0] * 6 for _ in range(n+1)]\n for i in range(1, 6):\n dp[1][i] = i\n\n for i in range(2, n+1):\n dp[i][1]=1\n for j in range(2, 6):\n dp[i][j] = dp[i][j-1] + dp[i-1][j]\n\n return dp[n][5]", + "title": "1641. Count Sorted Vowel Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums , return the number of distinct quadruplets (a, b, c, d) such that: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums[a] + nums[b] + nums[c] == nums[d] , and", + "a < b < c < d" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,6]Output:1Explanation:The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,4,5]Output:0Explanation:There are no such quadruplets in [3,3,6,4,5].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,5]Output:4Explanation:The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countQuadruplets(int[] nums) {\n int res = 0;\n int len = nums.length;\n \n Map count = new HashMap<>();\n count.put(nums[len-1] - nums[len-2], 1);\n \n for (int b = len - 3; b >= 1; b--) {\n for (int a = b - 1; a >= 0; a--) {\n res += count.getOrDefault(nums[a] + nums[b], 0);\n }\n \n for (int x = len - 1; x > b; x--) {\n count.put(nums[x] - nums[b], count.getOrDefault(nums[x] - nums[b], 0) + 1);\n }\n }\n \n return res;\n }\n}\n", + "title": "1995. Count Special Quadruplets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a 0-indexed integer array nums , return the number of distinct quadruplets (a, b, c, d) such that: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums[a] + nums[b] + nums[c] == nums[d] , and", + "a < b < c < d" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,6]Output:1Explanation:The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,4,5]Output:0Explanation:There are no such quadruplets in [3,3,6,4,5].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,3,5]Output:4Explanation:The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 640 ms (Top 64.4%) | Memory: 17.10 MB (Top 9.2%)\n\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n return sum([1 for a, b, c, d in combinations(nums, 4) if a + b + c == d])", + "title": "1995. Count Special Quadruplets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 300", + "1 <= arr[0].length <= 300", + "0 <= arr[i][j] <= 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix =\n[\n  [0,1,1,1],\n  [1,1,1,1],\n  [0,1,1,1]\n]Output:15Explanation:There are10squares of side 1.\nThere are4squares of side 2.\nThere is1square of side 3.\nTotal number of squares = 10 + 4 + 1 =15.", + "image": null + }, + { + "text": "Example 2: Input:matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]Output:7Explanation:There are6squares of side 1. \nThere is1square of side 2. \nTotal number of squares = 6 + 1 =7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 97.02%) | Memory: 55.30 MB (Top 24.22%)\n\nclass Solution \n{\n public int countSquares(int[][] matrix)\n {\n int n=matrix.length;\n int m=matrix[0].length;\n int dp[][]=new int[n][m];\n for(int i=0;i int:\n\n m = len(matrix)\n n = len(matrix[0])\n\n dp = [[0 for _ in range(n)] for _ in range(m)]\n total = 0\n\n for i in range(m):\n for j in range(n):\n\n if i == 0:\n dp[i][j] = matrix[0][j]\n\n elif j == 0:\n dp[i][j] = matrix[i][0]\n\n else:\n if matrix[i][j] == 1:\n dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j])\n\n total += dp[i][j]\n\n return total", + "title": "1277. Count Square Submatrices with All Ones", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A square triple (a,b,c) is a triple where a , b , and c are integers and a 2 + b 2 = c 2 . Given an integer n , return the number of square triples such that 1 <= a, b, c <= n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 250" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation: The square triples are (3,4,5) and (4,3,5).", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:4Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countTriples(int n) {\n int c = 0;\n for(int i=1 ; i<=n ; i++){\n for(int j=i+1 ; j<=n ; j++){\n int sq = ( i * i) + ( j * j);\n int r = (int) Math.sqrt(sq);\n if( r*r == sq && r <= n )\n c += 2;\n }\n }\n return c;\n }\n}\n", + "title": "1925. Count Square Sum Triples", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A square triple (a,b,c) is a triple where a , b , and c are integers and a 2 + b 2 = c 2 . Given an integer n , return the number of square triples such that 1 <= a, b, c <= n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 250" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:2Explanation: The square triples are (3,4,5) and (4,3,5).", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:4Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countTriples(self, n: int) -> int:\n c = 0\n for i in range(1, n+1):\n for j in range(i+1, n+1):\n sq = i*i + j*j\n r = int(sq ** 0.5)\n if ( r*r == sq and r <= n ):\n c +=2\n return c\n", + "title": "1925. Count Square Sum Triples", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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:3Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/10/test1.png" + }, + { + "text": "Example 2: 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:2Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 10.84%) | Memory: 133.6 MB (Top 38.64%)\nclass Solution {\n public int countSubIslands(int[][] grid1, int[][] grid2) {\n int m = grid1.length;\n int n = grid1[0].length;\n boolean[][] vis = new boolean[m][n];\n int count = 0;\n int[] dir = {1, 0, -1, 0, 1};\n\n for(int i = 0; i < m; ++i) {\n for(int j = 0; j < n; ++j) {\n if(grid2[i][j] == 0 || vis[i][j])\n continue;\n\n Queue queue = new LinkedList<>();\n boolean flag = true;\n vis[i][j] = true;\n\n queue.add(new int[] {i, j});\n\n while(!queue.isEmpty()) {\n int[] vtx = queue.remove();\n\n if(grid1[vtx[0]][vtx[1]] == 0)\n flag = false;\n\n for(int k = 0; k < 4; ++k) {\n int x = vtx[0] + dir[k];\n int y = vtx[1] + dir[k + 1];\n\n if(x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && !vis[x][y]) {\n vis[x][y] = true;\n\n queue.add(new int[] {x, y});\n }\n }\n }\n\n if(flag)\n ++count;\n }\n }\n\n return count;\n }\n}", + "title": "1905. Count Sub Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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:3Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/10/test1.png" + }, + { + "text": "Example 2: 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:2Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.", + "image": "https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countSubIslands(self, grid1, grid2):\n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n return \n grid2[i][j]=0\n dfs(i+1,j)\n dfs(i-1,j)\n dfs(i,j+1)\n dfs(i,j-1)\n # here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed \n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1 and grid1[i][j]==0:\n dfs(i,j)\n\t\t#now we just need to count the islands left over \t\t\t\n count=0\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1:\n \n dfs(i,j)\n count+=1\n return count \n\t\t", + "title": "1905. Count Sub Islands", + "topic": "Graph" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The score of an array is defined as the product of its sum and its length. Given a positive integer array nums and an integer k , return the number of non-empty subarrays of nums whose score is strictly less than k . A subarray is a contiguous sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3,5], k = 10Output:6Explanation:The 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 5Output:5Explanation:Every subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.0%) | Memory: 61.40 MB (Top 26.22%)\n\nclass Solution {\n public long countSubarrays(int[] nums, long k) {\n int i=0;\n int j=0;\n long max = 0;\n long operation = 0;\n\n while(j < nums.length){\n operation += nums[j];\n while(operation*(j-i+1) >= k){\n operation -= nums[i];\n i++;\n }\n max += j-i+1;\n j++;\n }\n return max;\n\n }\n}\n", + "title": "2302. Count Subarrays With Score Less Than K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The score of an array is defined as the product of its sum and its length. Given a positive integer array nums and an integer k , return the number of non-empty subarrays of nums whose score is strictly less than k . A subarray is a contiguous sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3,5], k = 10Output:6Explanation:The 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 5Output:5Explanation:Every subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1779 ms (Top 5.03%) | Memory: 31.30 MB (Top 6.6%)\n\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n sum, res, j = 0, 0, 0\n for i, n in enumerate(nums):\n sum += n\n while sum * (i - j + 1) >= k:\n sum -= nums[j]\n j += 1\n res += i - j + 1\n return res\n", + "title": "2302. Count Subarrays With Score Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the number of submatrices that have all ones . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 150", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,1],[1,1,0],[1,1,0]]Output:13Explanation:There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]Output:24Explanation:There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 78.37%) | Memory: 45.40 MB (Top 34.13%)\n\nclass Solution {\n private int n;\n private int res = 0;\n \n public int numSubmat(int[][] mat) {\n this.n = mat[0].length;\n \n // dp[j] : the height (number of consecutive '1's) of column j \n int[] dp = new int[n];\n for (int i = 0; i < mat.length; i++) {\n // calculating (updating) heights\n for (int j = 0; j < n; j++) {\n dp[j] = mat[i][j] == 1 ? dp[j] + 1 : 0;\n }\n enumerateRowByMinHeight(dp);\n }\n return res;\n }\n\n public void enumerateRowByMinHeight(int[] dp) {\n // monotonic stack storing indices : for index p < q in stack, dp[p] < dp[q]\n Deque stack = new LinkedList<>();\n stack.offerLast(-1);\n\n for (int j = 0; j < n; j++) {\n while (stack.peekLast() != -1 && dp[stack.peekLast()] >= dp[j]) {\n int idx = stack.pollLast();\n res += dp[idx] * (idx - stack.peekLast()) * (j - idx);\n }\n stack.offerLast(j);\n }\n while (stack.peekLast() != -1) {\n int idx = stack.pollLast();\n res += dp[idx] * (idx - stack.peekLast()) * (n - idx);\n }\n }\n}\n", + "title": "1504. Count Submatrices With All Ones", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an m x n binary matrix mat , return the number of submatrices that have all ones . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 150", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,1],[1,1,0],[1,1,0]]Output:13Explanation:There are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]Output:24Explanation:There are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.", + "image": "https://assets.leetcode.com/uploads/2021/10/27/ones2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n from dataclasses import dataclass\n @dataclass\n class Cell:\n left: int = 0\n top: int = 0\n \n n = len(mat)\n m = len(mat[0]) \n dp = [[Cell() for _ in range(m + 1)] for _ in range(n + 1)]\n \n ans = 0\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n if mat[i - 1][j - 1]: \n dp[i][j].top = 1 + dp[i - 1][j].top\n dp[i][j].left = 1 + dp[i][j - 1].left\n \n min_height = dp[i][j].top\n for k in range(dp[i][j].left):\n min_height = min(min_height, dp[i][j-k].top)\n ans += min_height \n return ans\n", + "title": "1504. Count Submatrices With All Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t . In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \" compute r\" and \" computa tion\" only differ by the 'e' / 'a' , so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. Example 1:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 100", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\", t = \"baba\"Output:6Explanation:The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", t = \"bb\"Output:3Explanation:The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.", + "image": null + } + ], + "follow_up": null, + "solution": "// version 1 : O(mn) space\nclass Solution {\n public int countSubstrings(String s, String t) {\n int m = s.length(), n = t.length();\n\n int[][][] dp = new int[m][n][2];\n \n int res = 0;\n // first col s[0:i] match t[0:0]\n for (int i = 0; i < m; i++) {\n dp[i][0][0] = (s.charAt(i) == t.charAt(0)) ? 1 : 0;\n dp[i][0][1] = (s.charAt(i) == t.charAt(0)) ? 0 : 1;\n res += dp[i][0][1];\n }\n \n \n // first row s[0:0] match t[0:j]\n for (int j = 1; j < n; j++) {\n dp[0][j][0] = (s.charAt(0) == t.charAt(j)) ? 1 : 0;\n dp[0][j][1] = (s.charAt(0) == t.charAt(j)) ? 0 : 1;\n res += dp[0][j][1];\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j][0] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][0] + 1 : 0;\n dp[i][j][1] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][1] : dp[i-1][j-1][0] + 1;\n res += dp[i][j][1];\n }\n }\n\n return res;\n }\n}\n", + "title": "1638. Count Substrings That Differ by One Character", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s and t , find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t . In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in \" compute r\" and \" computa tion\" only differ by the 'e' / 'a' , so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. Example 1:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 100", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\", t = \"baba\"Output:6Explanation:The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ab\", t = \"bb\"Output:3Explanation:The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n res = 0\n for i in range(len(s)):\n for j in range(len(t)):\n miss, pos = 0, 0\n while i + pos < len(s) and j + pos < len(t) and miss < 2:\n miss += s[i + pos] != t[j + pos]\n res += miss == 1\n pos += 1\n return res\n", + "title": "1638. Count Substrings That Differ by One Character", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n cities numbered from 1 to n . You are given an array edges of size n-1 , where edges[i] = [u i , v i ] represents a bidirectional edge between cities u i and v i . There exists a unique path between each pair of cities. In other words, the cities form a tree . A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1 , find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d . Return an array of size n-1 where the d th element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d . Notice that the distance between the two cities is the number of edges in the path between them. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/p1.png" + ], + "constraints": [ + "2 <= n <= 15", + "edges.length == n-1", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "All pairs (u i , v i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,2],[2,3],[2,4]]Output:[3,4,0]Explanation:The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\nNo subtree has two nodes where the max distance between them is 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]]Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[1,2],[2,3]]Output:[2,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 232 ms (Top 14.5%) | Memory: 44.30 MB (Top 38.1%)\n\nclass Solution {\n public int[] countSubgraphsForEachDiameter(int n, int[][] edges) {\n \n \n ArrayList[] graph = (ArrayList[]) new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(int i=0;i0)\n {\n darr[d-1]++;\n }\n }\n \n return darr;\n \n }\n \n int getmax(int mask , ArrayList[] graph)\n {\n \n int maxd = -1;\n \n for(int i=0;i<15;i++)\n { \n if( (mask & (1<[] graph , int mask)\n {\n \n \n Queue q\n = new LinkedList<>();\n q.add(node);\n int dist = -1;\n int curr = mask;\n \n while(!q.isEmpty())\n {\n dist++;\n \n for(int l=q.size()-1;l>=0;l--) { \n int z1 = q.peek();\n curr = curr ^ (1< List[int]:\n def floydwarshall(n, edges):\n D = [[float('inf')]*n for _ in range(n)]\n for u, v in edges:\n D[u-1][v-1] = 1\n D[v-1][u-1] = 1\n for v in range(n):\n D[v][v] = 0\n for k in range(n):\n for i in range(n):\n for j in range(n):\n D[i][j] = min(D[i][j],D[i][k]+D[k][j])\n return D\n\n G = defaultdict(list)\n for v, w in edges:\n G[v-1].append(w-1)\n G[w-1].append(v-1)\n\n def dfs(G, v, V, visited):\n if v in visited: return\n visited.add(v)\n for w in G[v]:\n if w in V:\n dfs(G, w, V, visited)\n\n def check_connected(G, V):\n if not V: return False\n root = next(iter(V))\n visited = set()\n dfs(G, root, V, visited)\n return visited == V\n\n def max_distance(D, V):\n res = 0\n for v in V:\n for w in V:\n res = max(res, D[v][w])\n return res\n\n def solve(include, idx, ans, G, D):\n if idx == n:\n V = set(v for v in range(n) if include[v])\n if check_connected(G, V):\n d = max_distance(D, V)\n if d >= 1:\n ans[d-1] += 1\n else:\n solve(include, idx+1, ans, G, D)\n include[idx] = True\n solve(include, idx+1, ans, G, D)\n include[idx] = False\n\n D = floydwarshall(n, edges)\n include = [False] * n\n ans = [0]*(n-1)\n solve(include, 0, ans, G, D)\n return ans\n", + "title": "1617. Count Subtrees With Max Distance Between Cities", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of n integers differences , which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1) . More formally, call the hidden sequence hidden , then we have that differences[i] = hidden[i + 1] - hidden[i] . You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given differences = [1, -3, 4] , lower = 1 , upper = 6 , the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 ( inclusive ). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6 . [1, 2, 3, 4] is not possible since the differences are not correct.", + "[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.", + "[5, 6, 3, 7] is not possible since it contains an element greater than 6 .", + "[1, 2, 3, 4] is not possible since the differences are not correct." + ], + "examples": [ + { + "text": "Example 1: Input:differences = [1,-3,4], lower = 1, upper = 6Output:2Explanation:The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:differences = [3,-4,5,1,-2], lower = -4, upper = 5Output:4Explanation:The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.", + "image": null + }, + { + "text": "Example 3: Input:differences = [4,-7,2], lower = 3, upper = 6Output:0Explanation:There are no possible hidden sequences. Thus, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfArrays(int[] differences, int lower, int upper) {\n ArrayList ans = new ArrayList<>();\n ans.add(lower); \n int mn = lower;\n int mx = lower;\n \n for (int i = 0; i < differences.length; i++) {\n int d = differences[i];\n ans.add(d + ans.get(ans.size() - 1));\n mn = Math.min(mn, ans.get(ans.size() - 1));\n mx = Math.max(mx, ans.get(ans.size() - 1));\n }\n\n int add = lower - mn;\n \n for (int i = 0; i < ans.size(); i++) {\n ans.set(i, ans.get(i) + add);\n }\n \n for (int i = 0; i < ans.size(); i++) {\n if (ans.get(i) < lower || upper < ans.get(i)) {\n return 0;\n }\n }\n \n int add2 = upper - mx;\n \n return add2 - add + 1;\n }\n}\n", + "title": "2145. Count the Hidden Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of n integers differences , which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1) . More formally, call the hidden sequence hidden , then we have that differences[i] = hidden[i + 1] - hidden[i] . You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given differences = [1, -3, 4] , lower = 1 , upper = 6 , the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 ( inclusive ). [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences. [5, 6, 3, 7] is not possible since it contains an element greater than 6 . [1, 2, 3, 4] is not possible since the differences are not correct.", + "[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.", + "[5, 6, 3, 7] is not possible since it contains an element greater than 6 .", + "[1, 2, 3, 4] is not possible since the differences are not correct." + ], + "examples": [ + { + "text": "Example 1: Input:differences = [1,-3,4], lower = 1, upper = 6Output:2Explanation:The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:differences = [3,-4,5,1,-2], lower = -4, upper = 5Output:4Explanation:The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.", + "image": null + }, + { + "text": "Example 3: Input:differences = [4,-7,2], lower = 3, upper = 6Output:0Explanation:There are no possible hidden sequences. Thus, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n l = [0]\n for i in differences:\n l.append(l[-1]+i)\n return max(0,(upper-lower+1)-(max(l)-min(l)))\n", + "title": "2145. Count the Hidden Sequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words . A string is consistent if all characters in the string appear in the string allowed . Return the number of consistent strings in the array words . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= allowed.length <= 26", + "1 <= words[i].length <= 10", + "The characters in allowed are distinct .", + "words[i] and allowed contain only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]Output:2Explanation:Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.", + "image": null + }, + { + "text": "Example 2: Input:allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]Output:7Explanation:All strings are consistent.", + "image": null + }, + { + "text": "Example 3: Input:allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]Output:4Explanation:Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 73.10%) | Memory: 54.7 MB (Top 46.20%)\nclass Solution {\n public int countConsistentStrings(String allowed, String[] words) {\n Set allowedSet = new HashSet<>();\n for(int i=0;i allowedSet, String word){\n for (int i = 0; i < word.length(); i++){\n if(!allowedSet.contains(word.charAt(i))) return false;\n }\n return true;\n }\n}", + "title": "1684. Count the Number of Consistent Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string allowed consisting of distinct characters and an array of strings words . A string is consistent if all characters in the string appear in the string allowed . Return the number of consistent strings in the array words . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^4", + "1 <= allowed.length <= 26", + "1 <= words[i].length <= 10", + "The characters in allowed are distinct .", + "words[i] and allowed contain only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]Output:2Explanation:Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.", + "image": null + }, + { + "text": "Example 2: Input:allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]Output:7Explanation:All strings are consistent.", + "image": null + }, + { + "text": "Example 3: Input:allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]Output:4Explanation:Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 236 ms (Top 95.16%) | Memory: 16 MB (Top 85.69%)\nclass Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n allowed = set(allowed)\n count = 0\n\n for word in words:\n for letter in word:\n if letter not in allowed:\n count += 1\n break\n\n return len(words) - count", + "title": "1684. Count the Number of Consistent Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers n and maxValue , which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Return the number of distinct ideal arrays of length n . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every arr[i] is a value from 1 to maxValue , for 0 <= i < n .", + "Every arr[i] is divisible by arr[i - 1] , for 0 < i < n ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, maxValue = 5Output:10Explanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, maxValue = 3Output:11Explanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nddistinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nddistinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int M =(int)1e9+7;\n public int idealArrays(int n, int maxValue) {\n long ans = 0;\n int N = n+maxValue;\n long[] inv = new long[N];\n long[] fact = new long[N];\n long[] factinv = new long[N];\n inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1;\n for (int i = 2; i < N; i++){ // mod inverse\n inv[i]=M-M/i*inv[M%i]%M;\n fact[i]=fact[i-1]*i%M;\n factinv[i]=factinv[i-1]*inv[i]%M;\n }\n for (int i = 1; i <= maxValue; i++){\n int tmp = i;\n Map map = new HashMap<>();\n for (int j = 2; j*j<= tmp; j++){\n while(tmp%j==0){ // prime factorization.\n tmp/=j;\n map.merge(j, 1, Integer::sum);\n }\n }\n if (tmp>1){\n map.merge(tmp, 1, Integer::sum);\n }\n long gain=1;\n for (int val : map.values()){ // arranges all the primes.\n gain *= comb(n+val-1, val, fact, factinv);\n gain %= M;\n }\n ans += gain;\n ans %= M;\n }\n\n return (int)ans;\n }\n\n private long comb(int a, int b, long[] fact, long[] factinv){\n return fact[a]*factinv[b]%M*factinv[a-b]%M;\n }\n}\n", + "title": "2338. Count the Number of Ideal Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers n and maxValue , which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Return the number of distinct ideal arrays of length n . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every arr[i] is a value from 1 to maxValue , for 0 <= i < n .", + "Every arr[i] is divisible by arr[i - 1] , for 0 < i < n ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, maxValue = 5Output:10Explanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, maxValue = 3Output:11Explanation:The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nddistinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nddistinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "from math import sqrt\n\nclass Solution:\n def primesUpTo(self, n):\n primes = set(range(2, n + 1))\n for i in range(2, n):\n if i in primes:\n it = i * 2\n while it <= n:\n if it in primes:\n primes.remove(it)\n it += i\n\n return primes\n\n def getPrimeFactors(self, n, primes):\n ret = {}\n sq = int(math.sqrt(n))\n\n for p in primes:\n if n in primes:\n ret[n] = 1\n break\n\n while n % p == 0:\n ret[p] = ret.get(p, 0) + 1\n n //= p\n\n if n <= 1:\n break\n\n return ret\n \n def idealArrays(self, n: int, maxValue: int) -> int:\n mod = 10**9 + 7\n ret = 0\n primes = self.primesUpTo(maxValue)\n \n for num in range(1, maxValue + 1):\n # find number of arrays that can end with num\n # for each prime factor, we can add it at any index i that we want\n pf = self.getPrimeFactors(num, primes)\n cur = 1\n for d in pf:\n ct = pf[d]\n v = n\n # there are (n + 1) choose k ways to add k prime factors\n for add in range(1, ct):\n v *= (n + add)\n v //= (add + 1)\n \n cur = (cur * v) % mod\n \n ret = (ret + cur) % mod\n \n return ret\n", + "title": "2338. Count the Number of Ideal Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We define str = [s, n] as the string str which consists of the string s concatenated n times. We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1 . You are given two strings s1 and s2 and two integers n1 and n2 . You have the two strings str1 = [s1, n1] and str2 = [s2, n2] . Return the maximum integer m such that str = [str2, m] can be obtained from str1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, str == [\"abc\", 3] ==\"abcabcabc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2Output:2", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n dp = []\n for i in range(len(s2)):\n start = i\n cnt = 0\n for j in range(len(s1)):\n if s1[j] == s2[start]:\n start += 1\n if start == len(s2):\n start = 0\n cnt += 1\n dp.append((start,cnt))\n res = 0\n next = 0\n for _ in range(n1):\n res += dp[next][1]\n next = dp[next][0]\n return res // n2\n\t\t\n", + "title": "466. Count The Repetitions", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr . We want to select three indices i , j and k where (0 <= i < j <= k < arr.length) . Let's define a and b as follows: Note that ^ denotes the bitwise-xor operation. Return the number of triplets ( i , j and k ) Where a == b . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]", + "b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,3,1,6,7]Output:4Explanation:The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,1,1,1]Output:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 85.89%) | Memory: 41.5 MB (Top 67.63%)\nclass Solution {\n public int countTriplets(int[] arr) {\n int count=0;\n\n for(int i=0;i int:\n s = [0]\n n = len(arr)\n if n <= 1:\n return 0 \n for i in range(n):\n s.append(s[-1]^arr[i])\n # a = s[i] ^ s[j], b = s[j] ^ s[k+1] \n count = defaultdict(int)\n # a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0 \n # <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1])\n # <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1]\n \n res = 0 \n # len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k\n for i in range(n-1):\n for k in range(i+1, n):\n if s[i] == s[k+1]:\n res += (k-i)\n return res \n", + "title": "1442. Count Triplets That Can Form Two Arrays of Equal XOR", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [row i , col i ] and walls[j] = [row j , col j ] represent the positions of the i th guard and j th wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 10^5", + "2 <= m * n <= 10^5", + "1 <= guards.length, walls.length <= 5 * 10^4", + "2 <= guards.length + walls.length <= m * n", + "guards[i].length == walls[j].length == 2", + "0 <= row i , row j < m", + "0 <= col i , col j < n", + "All the positions in guards and walls are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]Output:7Explanation:The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example1drawio2.png" + }, + { + "text": "Example 2: Input:m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]Output:4Explanation:The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countUnguarded(int m, int n, int[][] guards, int[][] walls)\n {\n int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};\n char[][] grid= new char[m][n];\n int count = m*n - guards.length - walls.length;\n for(int[] wall : walls)\n {\n int x = wall[0], y = wall[1];\n grid[x][y] = 'W';\n }\n for(int[] guard : guards)\n {\n int x = guard[0], y = guard[1];\n grid[x][y] = 'G';\n }\n for(int[] point : guards)\n {\n for(int dir[] : dirs)\n {\n int x = point[0] + dir[0];\n int y = point[1] + dir[1];\n while(!(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 'G' || grid[x][y] == 'W'))\n {\n if(grid[x][y] != 'P')\n count--;\n grid[x][y] = 'P';\n x += dir[0];\n y += dir[1];\n }\n }\n }\n return count;\n }\n}\n", + "title": "2257. Count Unguarded Cells in the Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [row i , col i ] and walls[j] = [row j , col j ] represent the positions of the i th guard and j th wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 10^5", + "2 <= m * n <= 10^5", + "1 <= guards.length, walls.length <= 5 * 10^4", + "2 <= guards.length + walls.length <= m * n", + "guards[i].length == walls[j].length == 2", + "0 <= row i , row j < m", + "0 <= col i , col j < n", + "All the positions in guards and walls are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]Output:7Explanation:The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example1drawio2.png" + }, + { + "text": "Example 2: Input:m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]Output:4Explanation:The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n dp = [[0] * n for _ in range(m)]\n for x, y in guards+walls:\n dp[x][y] = 1\n \n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n \n for x, y in guards:\n for dx, dy in directions:\n curr_x = x\n curr_y = y\n \n while 0 <= curr_x+dx < m and 0 <= curr_y+dy < n and dp[curr_x+dx][curr_y+dy] != 1:\n curr_x += dx\n curr_y += dy\n dp[curr_x][curr_y] = 2\n \n return sum(1 for i in range(m) for j in range(n) if dp[i][j] == 0) \n", + "title": "2257. Count Unguarded Cells in the Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a list of preferences for n friends, where n is always even . For each person i , preferences[i] contains a list of friends sorted in the order of preference . In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1 . All the friends are divided into pairs. The pairings are given in a list pairs , where pairs[i] = [x i , y i ] denotes x i is paired with y i and y i is paired with x i . However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but: Return the number of unhappy friends . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x prefers u over y , and", + "u prefers x over v ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]Output:2Explanation:Friend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]Output:0Explanation:Both friends 0 and 1 are happy.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.12%) | Memory: 64.00 MB (Top 67.65%)\n\nclass Solution {\n public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {\n int[][] rankings = new int[n][n]; // smaller the value, higher the preference\n int[] pairedWith = new int[n];\n for (int i = 0; i < n; i++) {\n for (int rank = 0; rank < n - 1; rank++) {\n int j = preferences[i][rank];\n rankings[i][j] = rank; // person \"i\" views person \"j\" with rank\n }\n }\n int unhappy = 0;\n for (int[] pair : pairs) {\n int a = pair[0], b = pair[1];\n pairedWith[a] = b;\n pairedWith[b] = a;\n }\n for (int a = 0; a < n; a++) {\n // \"a\" prefers someone else\n if (rankings[a][pairedWith[a]] != 0) {\n for (int b = 0; b < n; b++) {\n // \"b\" prefers to be with \"a\" over their current partner\n // \"a\" prefers to be with \"b\" over their current partner\n if (b != a\n && rankings[b][a] < rankings[b][pairedWith[b]]\n && rankings[a][b] < rankings[a][pairedWith[a]]) {\n unhappy++;\n break;\n }\n }\n }\n }\n return unhappy;\n }\n}\n", + "title": "1583. Count Unhappy Friends", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of preferences for n friends, where n is always even . For each person i , preferences[i] contains a list of friends sorted in the order of preference . In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1 . All the friends are divided into pairs. The pairings are given in a list pairs , where pairs[i] = [x i , y i ] denotes x i is paired with y i and y i is paired with x i . However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but: Return the number of unhappy friends . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x prefers u over y , and", + "u prefers x over v ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]Output:2Explanation:Friend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]Output:0Explanation:Both friends 0 and 1 are happy.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n dd = {}\n \n for i,x in pairs:\n dd[i] = preferences[i][:preferences[i].index(x)]\n dd[x] = preferences[x][:preferences[x].index(i)]\n \n ans = 0\n \n for i in dd:\n for x in dd[i]:\n if i in dd[x]:\n ans += 1\n break\n \n return ans\n", + "title": "1583. Count Unhappy Friends", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let's define a function countUniqueChars(s) that returns the number of unique characters on s . Given a string s , return the sum of countUniqueChars(t) where t is a substring of s . The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, calling countUniqueChars(s) if s = \"LEETCODE\" then \"L\" , \"T\" , \"C\" , \"O\" , \"D\" are the unique characters since they appear only once in s , therefore countUniqueChars(s) = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABC\"Output:10Explanation:All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10", + "image": null + }, + { + "text": "Example 2: Input:s = \"ABA\"Output:8Explanation:The same as example 1, exceptcountUniqueChars(\"ABA\") = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LEETCODE\"Output:92", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n ans = 0\n idx_recorder = collections.defaultdict(list)\n n = len(s)\n \n # record the index for every character\n # s = \"ABCA\"\n # {\n # \"A\": [0, 3],\n # \"B\": [1],\n # \"C\": [2],\n # }\n for idx in range(len(s)):\n c = s[idx]\n idx_recorder[c].append(idx)\n \n \n def helper(idxes):\n ans = 0\n\n for i in range(len(idxes)):\n # Count the number of substring which contain the character without duplicating\n # get the left, right value to compute the result.\n # \n # Take the middle A (idx=3) as example\n # s = 'AxxAxxxAxx'\n # -\n # left = 3 - 0 = 3 \n # right = 7 - 3 = 4\n #\n # The number of substring which contain this A (idx=3) without containing\n # other A is 3 * 4 = 12\n \n if i == 0:\n # If it is a first one: it means that there is\n # no duplicate character in left\n left = idxes[i] + 1\n else:\n left = idxes[i] - idxes[i-1]\n \n if i == len(idxes) - 1:\n # If it is a last one: it means that there is\n # no duplicate character in right side\n right = n - idxes[i]\n else:\n right = idxes[i+1] - idxes[i]\n \n ans += left * right\n \n return ans\n \n ans = 0\n for c in idx_recorder:\n ans += helper(idx_recorder[c])\n return ans\n", + "title": "828. Count Unique Characters of All Substrings of a Given String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . Return the number of pairs of different nodes that are unreachable from each other . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[0,2],[1,2]]Output:0Explanation:There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-3.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]Output:14Explanation:There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 56.92%) | Memory: 193.9 MB (Top 33.32%)\nclass Solution {\n public long countPairs(int n, int[][] edges) {\n //Building Graph\n ArrayList < ArrayList < Integer >> graph = new ArrayList < > ();\n for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ());\n for (int arr[]: edges) {\n graph.get(arr[0]).add(arr[1]);\n graph.get(arr[1]).add(arr[0]);\n }\n boolean visited[] = new boolean[n];\n long res = 0;\n int prev = 0;\n int count[] = {\n 0\n };\n for (int i = 0; i < graph.size(); i++) { // Running for loop on all connected components of graph\n if (visited[i] == true) continue; // if the node is alredy reached by any of other vertex then we don't need to terverse it again\n dfs(graph, i, visited, count);\n long a = n - count[0]; // (total - current count)\n long b = count[0] - prev; // (current count - prev )\n prev = count[0]; // Now Store count to prev\n res += (a * b);\n }\n return res;\n }\n void dfs(ArrayList < ArrayList < Integer >> graph, int v, boolean vis[], int count[]) {\n vis[v] = true;\n count[0]++; //for counting connected nodes\n for (int child: graph.get(v)) {\n if (!vis[child]) {\n dfs(graph, child, vis, count);\n }\n }\n }\n}", + "title": "2316. Count Unreachable Pairs of Nodes in an Undirected Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . Return the number of pairs of different nodes that are unreachable from each other . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[0,2],[1,2]]Output:0Explanation:There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-3.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]Output:14Explanation:There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.", + "image": "https://assets.leetcode.com/uploads/2022/05/05/tc-2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2311 ms (Top 90.13%) | Memory: 73.8 MB (Top 86.18%)\n'''\n* Make groups of nodes which are connected\n eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\n\n 0 ---- 2 1 --- 6 3\n | |\n | |\n 5 ---- 4\n\n groups will be {0: 4, 1: 2, 3: 1},\n i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3\n\n* Now, we have [4, 2, 1] as no of nodes in each group, we have to multiply each of no. with remaining\n ans = (4 * 2 + 4 * 1) + (2 * 1)\n but calculating ans this way will give TLE.\n\n* if we notice, (4 * 2 + 4 * 1) + (2 * 1), we can combine, equation like this,\n 4 * 2 + (4 + 2) * 1, using this, we can reduce complexity.\n so, if we have count of groups array as [a, b, c, d], ans will be,\n ans = a * b + (a + b) * c + (a + b + c) * d\n\n* will use, union for generating groups.\n* ps, you can modify UnionFind class as per your need. Have implemented full union-find for beginners.\n'''\n\nclass UnionFind:\n def __init__(self, size):\n self.root = [i for i in range(size)]\n self.rank = [1] * size\n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootX] < self.rank[rootY]:\n self.root[rootX] = rootY\n else:\n self.root[rootY] = rootX\n self.rank[rootX] += 1\n\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]]) -> int:\n dsu = UnionFind(n)\n for u, v in edges:\n dsu.union(u, v)\n C = Counter([dsu.find(i) for i in range(n)])\n groupCounts = list(C.values())\n ans = 0\n firstGroupCount = groupCounts[0]\n for i in range(1, len(groupCounts)):\n ans += firstGroupCount * groupCounts[i]\n firstGroupCount += groupCounts[i]\n return ans", + "title": "2316. Count Unreachable Pairs of Nodes in an Undirected Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) and has all five vowels present in it. Given a string word , return the number of vowel substrings in word . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 100", + "word consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiouu\"Output:2Explanation:The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"unicornarihan\"Output:0Explanation:Not all 5 vowels are present, so there are no vowel substrings.", + "image": null + }, + { + "text": "Example 3: Input:word = \"cuaieuouac\"Output:7Explanation:The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int countVowelSubstrings(String word)\n {\n int vow = 0;\n int n = word.length();\n Set set = new HashSet<>();\n for(int i = 0; i < n-4; i++)\n {\n set.clear();\n for(int j = i; j < n; j++)\n {\n char ch = word.charAt(j);\n if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')\n {\n set.add(ch);\n if(set.size() == 5)\n vow++;\n }\n else\n break;\n }\n }\n return vow;\n }\n}\n", + "title": "2062. Count Vowel Substrings of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A substring is a contiguous (non-empty) sequence of characters within a string. A vowel substring is a substring that only consists of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) and has all five vowels present in it. Given a string word , return the number of vowel substrings in word . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 100", + "word consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiouu\"Output:2Explanation:The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"unicornarihan\"Output:0Explanation:Not all 5 vowels are present, so there are no vowel substrings.", + "image": null + }, + { + "text": "Example 3: Input:word = \"cuaieuouac\"Output:7Explanation:The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countVowelSubstrings(self, word: str) -> int:\n vowels = {'a','e','i','o','u'}\n pointer = 0\n res = 0\n if len(word) <= 4:\n return 0\n while pointer != len(word)-4:\n # if set(list(word[pointer:pointer+5])) == vowels:\n # temp = 1\n # res += 1\n # while set(list(word[pointer:pointer+temp+5])) == vowels and pointer+temp+4 != len(word):\n # res += 1\n # temp += 1\n # elif word[pointer] in vowels:\n # temp = 1\n # while set(list(word[pointer:pointer+5+temp])) != vowels:\n # temp += 1\n # res += 1\n # pointer += 1\n temp = 0\n if word[pointer] in vowels:\n while temp+pointer != len(word)-4:\n test_1 = set(list(word[pointer:pointer+temp+5]))\n test_2 = word[pointer:pointer+temp+5]\n if set(list(word[pointer:pointer+temp+5])).issubset(vowels): \n if set(list(word[pointer:pointer+temp+5])) == vowels:\n res += 1\n temp+=1\n else:\n break\n \n pointer += 1\n return res\n\n ", + "title": "2062. Count Vowel Substrings of a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , your task is to count how many strings of length n can be formed under the following rules: Since the answer may be too large, return it modulo 10^9 + 7. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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'." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:5Explanation:All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:10Explanation:All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".", + "image": null + }, + { + "text": "Example 3: Input:n = 5Output:68", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 32.30%) | Memory: 52.8 MB (Top 39.76%)\nclass Solution {\n private long[][] dp;\n private int mod = (int)1e9 + 7;\n\n public int countVowelPermutation(int n) {\n dp = new long[6][n+1];\n if(n == 1) return 5;\n\n for(int i = 0; i < 5; i++)\n dp[i][0] = 1;\n\n helper(n,'z');\n return (int)dp[5][n];\n }\n\n private long helper(int n, char vowel)\n {\n long ans = 0;\n if(n == 0) return 1;\n\n if(vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels\n {\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'i') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[5][n] = ans;\n }\n // from here as per our assumptions of Vowels we will make calls & store results\n else if(vowel == 'a') // for Nth number we would store Result for \"a\" in dp[0][n]\n {\n if(dp[0][n] != 0) return dp[0][n];\n ans = (ans + helper(n-1,'e'))%mod;\n dp[0][n] = ans;\n }\n\n else if(vowel == 'e') // for Nth number we would store Result for \"e\" in dp[1][n]\n {\n if(dp[1][n] != 0) return dp[1][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'i'))%mod;\n dp[1][n] = ans;\n }\n\n else if(vowel == 'i') // for Nth number we would store Result for \"i\" in dp[2][n]\n {\n if(dp[2][n] != 0) return dp[2][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[2][n] = ans;\n }\n\n else if(vowel == 'o') // for Nth number we would store Result for \"o\" in dp[3][n]\n {\n if(dp[3][n] != 0) return dp[3][n];\n ans = (ans + helper(n-1,'i') + helper(n-1,'u'))%mod;\n dp[3][n] = ans;\n }\n\n else // for Nth number we would store Result for \"u\" in dp[4][n]\n {\n if(dp[4][n] != 0) return dp[4][n];\n ans = (ans + helper(n-1,'a'))%mod;\n dp[4][n] = ans;\n }\n\n return ans;\n }\n}", + "title": "1220. Count Vowels Permutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , your task is to count how many strings of length n can be formed under the following rules: Since the answer may be too large, return it modulo 10^9 + 7. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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'." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:5Explanation:All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:10Explanation:All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".", + "image": null + }, + { + "text": "Example 3: Input:n = 5Output:68", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 249 ms (Top 78.97%) | Memory: 19.8 MB (Top 29.73%)\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n # dp[i][j] means the number of strings of length i that ends with the j-th vowel.\n dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]\n moduler = math.pow(10, 9) + 7\n for i in range(1, n):\n # For vowel a\n dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler\n # For vowel e\n dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler\n # For vowel i\n dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler\n # For vowel o\n dp[i][3] = (dp[i - 1][2]) % moduler\n # For vowel u\n dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler\n\n return int(sum(dp[-1]) % moduler)", + "title": "1220. Count Vowels Permutation", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n , prevRoom , where prevRoom[i] indicates that you must build room prevRoom[i] before building room i , and these two rooms must be connected directly . Room 0 is already built, so prevRoom[0] = -1 . The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0 . You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected . You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == prevRoom.length", + "2 <= n <= 10^5", + "prevRoom[0] == -1", + "0 <= prevRoom[i] < n for all 1 <= i < n", + "Every room is reachable from room 0 once all the rooms are built." + ], + "examples": [ + { + "text": "Example 1: Input:prevRoom = [-1,0,1]Output:1Explanation:There is only one way to build the additional rooms: 0 → 1 → 2", + "image": "https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" + }, + { + "text": "Example 2: Input:prevRoom = [-1,0,0,1,2]Output:6Explanation:The 6 ways are:\n0 → 1 → 3 → 2 → 4\n0 → 2 → 4 → 1 → 3\n0 → 1 → 2 → 3 → 4\n0 → 1 → 2 → 4 → 3\n0 → 2 → 1 → 3 → 4\n0 → 2 → 1 → 4 → 3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int M = (int)1e9+7;\n public int waysToBuildRooms(int[] prevRoom) {\n int n = prevRoom.length;\n long[] fact = new long[n];\n long[] invFact = new long[n];\n long[] inv = new long[n];\n fact[1]=fact[0]=invFact[0]=invFact[1]=inv[1]=1;\n for (int i = 2; i < n; i++){ // modInverse \n fact[i] = fact[i-1]*i%M;\n inv[i] = M-M/i*inv[M%i]%M;\n invFact[i] = invFact[i-1]*inv[i]%M;\n }\n\n Map> map = new HashMap<>();\n for (int i = 0; i < n; i++){ // add an edge from parent to child\n map.computeIfAbsent(prevRoom[i], o -> new ArrayList<>()).add(i);\n }\n\n long[] ans = new long[]{1};\n solve(0, fact, invFact, map, ans);\n return (int)ans[0];\n }\n\n private int solve(int i, long[] fact, long[] invFact, Map> map, long[] ans){\n int sum = 0;\n for (int next : map.getOrDefault(i, List.of())){\n int cur = solve(next, fact, invFact, map, ans);\n ans[0] = ans[0] * invFact[cur] % M; // divide fact[cur] -> multiply invFact[cur]\n sum += cur;\n }\n ans[0] = ans[0] * fact[sum] % M;\n return sum+1;\n }\n}\n", + "title": "1916. Count Ways to Build Rooms in an Ant Colony", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n , prevRoom , where prevRoom[i] indicates that you must build room prevRoom[i] before building room i , and these two rooms must be connected directly . Room 0 is already built, so prevRoom[0] = -1 . The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0 . You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected . You can choose to build any room as long as its previous room is already built. Return the number of different orders you can build all the rooms in . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == prevRoom.length", + "2 <= n <= 10^5", + "prevRoom[0] == -1", + "0 <= prevRoom[i] < n for all 1 <= i < n", + "Every room is reachable from room 0 once all the rooms are built." + ], + "examples": [ + { + "text": "Example 1: Input:prevRoom = [-1,0,1]Output:1Explanation:There is only one way to build the additional rooms: 0 → 1 → 2", + "image": "https://assets.leetcode.com/uploads/2021/06/19/d1.JPG" + }, + { + "text": "Example 2: Input:prevRoom = [-1,0,0,1,2]Output:6Explanation:The 6 ways are:\n0 → 1 → 3 → 2 → 4\n0 → 2 → 4 → 1 → 3\n0 → 1 → 2 → 3 → 4\n0 → 1 → 2 → 4 → 3\n0 → 2 → 1 → 3 → 4\n0 → 2 → 1 → 4 → 3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4732 ms (Top 93.33%) | Memory: 177.5 MB (Top 6.67%)\nclass Solution:\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(prevRoom)\n\n mod_inverses = [1] * (n + 1)\n factorials = [1] * (n + 1)\n inverse_factorials = [1] * (n + 1)\n\n for x in range(2, n + 1): # Precompute all factorials and inverse factorials needed in O(1) time each\n mod_inverses[x] = mod - mod // x * mod_inverses[mod % x] % mod\n factorials[x] = (x * factorials[x - 1]) % mod\n inverse_factorials[x] = (mod_inverses[x] * inverse_factorials[x - 1]) % mod\n\n children = collections.defaultdict(list) # Convert parent list to children lists\n for i, x in enumerate(prevRoom[1:], 1):\n children[x].append(i)\n\n def postorder(curr: int) -> Tuple[int, int]:\n if curr not in children: # Leaf has ways, size both 1\n return 1, 1\n tot_size = 1\n tot_ways = 1\n for child in children[curr]:\n ways, size_of = postorder(child)\n tot_ways *= ways * inverse_factorials[size_of]\n tot_size += size_of\n tot_ways *= factorials[tot_size-1]\n return tot_ways % mod, tot_size\n\n return postorder(0)[0]", + "title": "1916. Count Ways to Build Rooms in an Ant Colony", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D integer array, queries . For each queries[i] , where queries[i] = [n i , k i ] , find the number of different ways you can place positive integers into an array of size n i such that the product of the integers is k i . As the number of ways may be too large, the answer to the i th query is the number of ways modulo 10^9 + 7 . Return an integer array answer where answer.length == queries.length , and answer[i] is the answer to the i th query. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 10^4", + "1 <= n i , k i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [[2,6],[5,1],[73,660]]Output:[4,1,50734910]Explanation:Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109+ 7 = 50734910.", + "image": null + }, + { + "text": "Example 2: Input:queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]Output:[1,2,3,10,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 72.7%) | Memory: 45.86 MB (Top 86.3%)\n\nclass Solution {\n // List of primes upto sqrt(10e4)\n int[] PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };\n // Factors of integers upto 13\n int[][] SMALL_INT_FACTORS = { null, {1}, {2}, {3}, {2,2}, {5}, {2,3}, {7}, {2,2,2}, {3,3}, {2,5}, {11}, {2,2,3}, {13} };\n \n public int[] waysToFillArray(int[][] queries) {\n int n = queries.length;\n int[] ans = new int[n];\n for(int i=0; i 1) // If any prime greater than sqrt(10e4) is a remaining factor of num\n ans = multiply(ans, k);\n return (int) ans;\n }\n \n // In how many ways can we split an integer n into k non-negative numbers?\n // Answer = combin(n+k-1, k-1) (11th grade math; non-trivial but google-able)\n // combin(n+k-1, k-1) smoothly turns into combin(n+k-1, n)\n private long getSplitCount(int n, int k) {\n int a = n+k-1, b = k-1;\n if((b << 1) > a) b = a - b;\n return comb(a, b);\n }\n \n \n // combin(n, r) = (n . n-1 . n-2 . n-3 ... n-r+1)/(1 . 2 . 3 ... r)\n // Brute force division:\n // We exploit the fact that r in this problem is at max 13\n // We try to cancel common prime factors of numerator and denominator terms\n // This leaves us with numerator elements alone (thus avoiding mod related issues wrt division)\n private long comb(int n, int r) {\n int[] numerators = new int[r];\n for(int i=0, j=n; i List[int]:\n mod = 10 ** 9 + 7\n \n def dfs(n, val):\n if (n, val) not in self.dp:\n if n == 1: return 1\n temp = 1\n for k in range(val//2, 0, -1):\n if val % k == 0:\n temp += dfs(n-1, val // k)\n self.dp[n, val] = temp % mod\n return self.dp[n, val]\n \n res = []\n for n, val in queries:\n res.append(dfs(n, val))\n return res\n", + "title": "1735. Count Ways to Make Array With Product", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed arrays of strings startWords and targetWords . Each string consists of lowercase English letters only. For each string in targetWords , check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords . The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords . Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the string is \"abc\" , the letters 'd' , 'e' , or 'y' can be added to it, but not 'a' . If 'd' is added, the resulting string will be \"abcd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]Output:2Explanation:- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n Note that \"act\" does exist in startWords, but wemustappend one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.", + "image": null + }, + { + "text": "Example 2: Input:startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]Output:1Explanation:- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int wordCount(String[] startWords, String[] targetWords) {\n int n = startWords.length;\n int count = 0;\n Set set = new HashSet<>();\n \n //1. store lexicographically sorted letters of startword in set\n for(String start: startWords){\n char[] sAr = start.toCharArray();\n Arrays.sort(sAr);\n set.add(new String(sAr));\n }\n int m = targetWords.length;\n boolean ans = false;\n for(int i = 0; i < m; i++){\n //2. sort lexicographically letters of targetword and store in new string s\n char[] tAr = targetWords[i].toCharArray();\n Arrays.sort(tAr);\n int k = tAr.length;\n String s = String.valueOf(tAr);\n \n ans = false;\n for(int j = 0; j < k; j++){\n //3. make a new string by omitting one letter from word and check if it is present in set than increase count value\n String str = s.substring(0,j) + s.substring(j+1);\n if(set.contains(str)){\n count++;\n break;\n }\n }\n }\n return count; \n }\n \n}\n", + "title": "2135. Count Words Obtained After Adding a Letter", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed arrays of strings startWords and targetWords . Each string consists of lowercase English letters only. For each string in targetWords , check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords . The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords . Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the string is \"abc\" , the letters 'd' , 'e' , or 'y' can be added to it, but not 'a' . If 'd' is added, the resulting string will be \"abcd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]Output:2Explanation:- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n Note that \"act\" does exist in startWords, but wemustappend one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.", + "image": null + }, + { + "text": "Example 2: Input:startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]Output:1Explanation:- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Brute Force\n# O(S * T); S := len(startWors); T := len(targetWords)\n# TLE\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n cnt = 0\n for target in targetWords:\n for start in startWords:\n if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1:\n cnt += 1\n break\n return cnt\n\n# Sort + HashSet Lookup\n# O(S + T) Time\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n # Sort each start word and add it to a hash set\n startWords_sorted = set()\n # O(S*26*log(26))\n for word in startWords:\n startWords_sorted.add(\"\".join(sorted(list(word))))\n \n # sort each target word and add it to a list\n # O(T*26*log(26))\n targetWords_sorted = []\n for word in targetWords:\n targetWords_sorted.append(sorted(list(word)))\n \n # for each sorted target word, we remove a single character and \n # check if the resulting word is in the startWords_sorted\n # if it is, we increment cnt and break the inner loop\n # otherwise we keep removing until we either find a hit or reach the\n # end of the string\n # O(T*26) = O(T)\n cnt = 0\n for target in targetWords_sorted:\n for i in range(len(target)):\n w = target[:i] + target[i+1:]\n w = \"\".join(w)\n if w in startWords_sorted:\n cnt += 1\n break\n \n return cnt\n\n# Using Bit Mask\n# O(S + T) Time\n# Similar algorithm as the one above, implemented using a bit mask to avoid the sorts\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n start_set = set()\n # O(S * 26)\n for word in startWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n start_set.add(m)\n \n # O(T * 2 * 26)\n cnt = 0\n for word in targetWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n \n for ch in word:\n i = ord(ch) - ord('a')\n if m ^ (1 << i) in start_set:\n cnt += 1\n break\n return cnt\n", + "title": "2135. Count Words Obtained After Adding a Letter", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[0,1,1]Explanation:0 --> 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[0,1,1,2,1,2]Explanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.97%) | Memory: 46.2 MB (Top 98.87%)\n\nclass Solution {\n\n public void count(int n, int[] a, int k)\n {\n int i;\n for(i=k ; i 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[0,1,1,2,1,2]Explanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBits(self, n: int) -> List[int]:\n # We know that all exponential values of two have 1 bit turned on, the rest are turned off.\n # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed \n # into smaller numbers where we already have found the # of 1s, for example.\n # F(3) = F(2^1) + F(1) = 1 + 1 = 3\n # F(4) = F(2^2) + F(0) = 1 + 0. ( Even thought we havent defined F(4) = F(2^2), by the previous established)\n # comment, we can safely say that all F(2^X) has only 1 bit so thats where F(4) would be = 1\n # F(5) = F(2^2) + F(1) = 1 + 1 = 2\n # F(6) = F(2^2) + F(2) = F(4) + F(2) = 1 + 1\n # The relation countinues for all following numbers\n \n # This solution is O(N)\n # With O(1) extra space ( considering dp is the returned answer )\n \n dp = [0]\n\t\t\n for i in range(1, n + 1):\n exponent = int(math.log(i) / math.log(2))\n num = 2**exponent\n decimal = i % (num)\n if num == i:\n dp.append(1)\n else:\n dp.append(dp[num] + dp[decimal])\n return(dp)\n", + "title": "338. Counting Bits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings words and a string pref . Return the number of strings in words that contain pref as a prefix . A prefix of a string s is any leading contiguous substring of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length, pref.length <= 100", + "words[i] and pref consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"pay\",\"attention\",\"practice\",\"attend\"],pref= \"at\"Output:2Explanation:The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"win\",\"loops\",\"success\"],pref= \"code\"Output:0Explanation:There are no strings that contain \"code\" as a prefix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int prefixCount(String[] words, String pref) {\n int c = 0;\n for(String s : words) {\n if(s.indexOf(pref)==0) \n c++;\n }\n return c; \n }\n}\n", + "title": "2185. Counting Words With a Given Prefix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words and a string pref . Return the number of strings in words that contain pref as a prefix . A prefix of a string s is any leading contiguous substring of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length, pref.length <= 100", + "words[i] and pref consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"pay\",\"attention\",\"practice\",\"attend\"],pref= \"at\"Output:2Explanation:The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"win\",\"loops\",\"success\"],pref= \"code\"Output:0Explanation:There are no strings that contain \"code\" as a prefix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(word.find(pref) == 0 for word in words)\n", + "title": "2185. Counting Words With a Given Prefix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the i th seat. The couples are numbered in order, the first couple being (0, 1) , the second couple being (2, 3) , and so on with the last couple being (2n - 2, 2n - 1) . Return the minimum number of swaps so that every couple is sitting side by side . A swap consists of choosing any two people, then they stand up and switch seats. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2n == row.length", + "2 <= n <= 30", + "n is even.", + "0 <= row[i] < 2n", + "All the elements of row are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = [0,2,1,3]Output:1Explanation:We only need to swap the second (row[1]) and third (row[2]) person.", + "image": null + }, + { + "text": "Example 2: Input:row = [3,2,0,1]Output:0Explanation:All couples are already seated side by side.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwapsCouples(int[] row) { // Union -Find pairs for 2\n Map parents=new HashMap<>();\n int count=0;\n for(int i=0;i7 , also place smaller number as parent for eg)//0,4 ; 1,3\n parents.put(i,i+1);\n }\n return count;\n }\n}\n", + "title": "765. Couples Holding Hands", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n couples sitting in 2n seats arranged in a row and want to hold hands. The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the i th seat. The couples are numbered in order, the first couple being (0, 1) , the second couple being (2, 3) , and so on with the last couple being (2n - 2, 2n - 1) . Return the minimum number of swaps so that every couple is sitting side by side . A swap consists of choosing any two people, then they stand up and switch seats. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2n == row.length", + "2 <= n <= 30", + "n is even.", + "0 <= row[i] < 2n", + "All the elements of row are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = [0,2,1,3]Output:1Explanation:We only need to swap the second (row[1]) and third (row[2]) person.", + "image": null + }, + { + "text": "Example 2: Input:row = [3,2,0,1]Output:0Explanation:All couples are already seated side by side.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 84.03%) | Memory: 17.30 MB (Top 39.5%)\n\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n loc = {x: i for i, x in enumerate(row)}\n ans = 0\n for i in range(0, len(row), 2): \n p = row[i] - 1 if row[i]&1 else row[i]+1\n if row[i+1] != p: \n ans += 1\n ii = loc[p]\n loc[row[i+1]], loc[row[ii]] = loc[row[ii]], loc[row[i+1]] # swap mappings\n row[i+1], row[ii] = row[ii], row[i+1] # swap values \n return ans \n", + "title": "765. Couples Holding Hands", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Return true if you can finish all courses. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]Output:trueExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]Output:falseExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFinish(int numCourses, int[][] prerequisites) {\n int n = numCourses;\n boolean [] visited = new boolean[n];\n boolean [] dfsVisited = new boolean[n];\n \n List> adj = createAdjList(n,prerequisites);\n for(int i=0;i> adj,boolean [] visited,boolean[] dfsVisited){\n \n visited[s]=true;\n dfsVisited[s]=true;\n \n for(int v:adj.get(s)){\n if(visited[v]==false){\n if(isCycle(v,adj,visited,dfsVisited)){\n return true;\n } \n }else if(visited[v]==true && dfsVisited[v]==true) {\n return true;\n } \n }\n dfsVisited[s]=false;\n return false;\n }\n \n private List> createAdjList(int n,int[][] prerequisites){\n List> adj = new ArrayList();\n \n for(int i=0;i());\n }\n for(int[] e : prerequisites){\n adj.get(e[1]).add(e[0]);\n }\n return adj;\n }\n}\n", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . Return true if you can finish all courses. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]Output:trueExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]Output:falseExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n \n pre = {} # course: list of prerequisites\n dep = {} # course: list of dependents\n for p in prerequisites:\n if p[0] not in pre:\n pre[p[0]] = set()\n if p[1] not in dep:\n dep[p[1]] = set()\n pre[p[0]].add(p[1])\n dep[p[1]].add(p[0])\n\n # Kahn's algorithm\n l = []\n s = set()\n for i in range(numCourses):\n if i not in dep: # if no dependents (incoming edge)\n s.add(i) \n while s:\n n = s.pop()\n l.append(n)\n if n in pre: # if n has prerequisites\n for m in pre[n]: # for each prerequisites m\n dep[m].remove(n) # remove n from m's dependents list\n if not dep[m]: # if m has no more dependents\n s.add(m)\n \n return len(l) == numCourses", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: 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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] findOrder(int numCourses, int[][] prerequisites) {\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n for (int i = 0; i < numCourses; i++) {\n graph.put(i, new HashSet());\n }\n \n for (int[] pair : prerequisites) {\n graph.get(pair[1]).add(pair[0]);\n inDegree[pair[0]]++;\n }\n \n // BFS - Kahn's Algorithm - Topological Sort\n Queue bfsContainer = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0) {\n bfsContainer.add(i); \n }\n }\n \n int count = 0;\n int[] ans = new int[numCourses];\n while (!bfsContainer.isEmpty()) {\n int curr = bfsContainer.poll();\n ans[count++] = curr;\n for (Integer num : graph.get(curr)) {\n inDegree[num]--;\n if (inDegree[num] == 0) {\n bfsContainer.add(num);\n }\n }\n }\n \n if (count < numCourses) {\n return new int[] {};\n } else {\n return ans;\n }\n }\n}\n", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: 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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n d = {i:[] for i in range(numCourses)}\n \n for crs, prereq in prerequisites:\n d[crs].append(prereq)\n \n visit, cycle = set(), set()\n output = []\n def dfs(crs):\n if crs in cycle:\n return False\n if crs in visit:\n return True\n \n cycle.add(crs)\n for nei in d[crs]:\n if not dfs(nei):\n return False\n cycle.remove(crs)\n visit.add(crs)\n output.append(crs)\n return True\n \n for crs in range(numCourses):\n if not dfs(crs):\n return []\n return output\n \n", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n different online courses numbered from 1 to n . You are given an array courses where courses[i] = [duration i , lastDay i ] indicate that the i th course should be taken continuously for duration i days and must be finished before or on lastDay i . You will start on the 1 st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= courses.length <= 10^4", + "1 <= duration i , lastDay i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]Output:3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1stcourse, it costs 100 days so you will finish it on the 100thday, and ready to take the next course on the 101stday.\nSecond, take the 3rdcourse, it costs 1000 days so you will finish it on the 1100thday, and ready to take the next course on the 1101stday. \nThird, take the 2ndcourse, it costs 200 days so you will finish it on the 1300thday. \nThe 4thcourse cannot be taken now, since you will finish it on the 3300thday, which exceeds the closed date.", + "image": null + }, + { + "text": "Example 2: Input:courses = [[1,2]]Output:1", + "image": null + }, + { + "text": "Example 3: Input:courses = [[3,2],[4,3]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 83.06%) | Memory: 54.60 MB (Top 52.82%)\n\nclass Solution {\n public int scheduleCourse(int[][] C) {\n Arrays.sort(C, (a,b) -> a[1] - b[1]);\n PriorityQueue pq = new PriorityQueue<>((a,b) -> b - a);\n int total = 0;\n for (int[] course : C) {\n int dur = course[0], end = course[1];\n if (dur + total <= end) {\n total += dur;\n pq.add(dur);\n } else if (pq.size() > 0 && pq.peek() > dur) {\n total += dur - pq.poll();\n pq.add(dur);\n }\n }\n return pq.size();\n }\n}\n", + "title": "630. Course Schedule III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n different online courses numbered from 1 to n . You are given an array courses where courses[i] = [duration i , lastDay i ] indicate that the i th course should be taken continuously for duration i days and must be finished before or on lastDay i . You will start on the 1 st day and you cannot take two or more courses simultaneously. Return the maximum number of courses that you can take . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= courses.length <= 10^4", + "1 <= duration i , lastDay i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]Output:3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1stcourse, it costs 100 days so you will finish it on the 100thday, and ready to take the next course on the 101stday.\nSecond, take the 3rdcourse, it costs 1000 days so you will finish it on the 1100thday, and ready to take the next course on the 1101stday. \nThird, take the 2ndcourse, it costs 200 days so you will finish it on the 1300thday. \nThe 4thcourse cannot be taken now, since you will finish it on the 3300thday, which exceeds the closed date.", + "image": null + }, + { + "text": "Example 2: Input:courses = [[1,2]]Output:1", + "image": null + }, + { + "text": "Example 3: Input:courses = [[3,2],[4,3]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n bool static cmp(vector &a,vector&b) {\n return a[1] < b[1];\n }\n int scheduleCourse(vector>& courses) {\n sort(courses.begin(),courses.end(),cmp);\n int sm = 0;\n priority_queue pq;\n for(int i=0; icourses[i][1]) { \n sm-=pq.top(); // remove the biggest invalid course duration!\n pq.pop();\n }\n }\n return pq.size();\n }\n};\n", + "title": "630. Course Schedule III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 a i first if you want to take course b i . Prerequisites can also be indirect . If course a is a prerequisite of course b , and course b is a prerequisite of course c , then course a is a prerequisite of course c . You are also given an array queries where queries[j] = [u j , v j ] . For the j th query, you should answer whether course u j is a prerequisite of course v j or not. Return a boolean array answer , where answer[j] is the answer to the j th query. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]Output:[false,true]Explanation:The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-1-graph.jpg" + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]Output:[false,false]Explanation:There are no prerequisites, and each course is independent.", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]Output:[true,true]", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-3-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1518 ms (Top 5.07%) | Memory: 118.7 MB (Top 6.29%)\nclass Solution {\n public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {\n // Generating Map\n Map> graph = new HashMap<>();\n for(int e[]: prerequisites){\n graph.putIfAbsent(e[0], new ArrayList<>());\n graph.get(e[0]).add(e[1]);\n }\n\n List list = new ArrayList<>();\n // Appling DFS for every query to get result\n for(int[] q: queries){\n list.add(isPre(q[0], q[1], graph, new HashSet<>()));\n }\n return list;\n }\n // Check if src comes before dst using DFS\n private boolean isPre(int src, int dst, Map> adj, Set visited){\n if(visited.contains(src)) return false;\n visited.add(src);\n for(int neigh: adj.getOrDefault(src, new ArrayList<>())){\n if(neigh == dst || isPre(neigh, dst, adj, visited)) return true;\n }\n return false;\n }\n}", + "title": "1462. Course Schedule IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 a i first if you want to take course b i . Prerequisites can also be indirect . If course a is a prerequisite of course b , and course b is a prerequisite of course c , then course a is a prerequisite of course c . You are also given an array queries where queries[j] = [u j , v j ] . For the j th query, you should answer whether course u j is a prerequisite of course v j or not. Return a boolean array answer , where answer[j] is the answer to the j th query. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]Output:[false,true]Explanation:The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-1-graph.jpg" + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]Output:[false,false]Explanation:There are no prerequisites, and each course is independent.", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]Output:[true,true]", + "image": "https://assets.leetcode.com/uploads/2021/05/01/courses4-3-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n one approach I can think of is, given a graph, \n the query[a, b] will be true if there exists a path from a to b in the graph\n else a will not be a prerequisite of b\n but this approach may not scale as the # of queries will increase\n \"\"\"\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n graph = {node: set() for node in range(numCourses)}\n for pre in prerequisites:\n graph[pre[0]].add(pre[1])\n \n def path(cur_node, node_b):\n if cur_node == node_b:\n return True\n for neighbor in graph[cur_node]:\n if path(neighbor, node_b):\n return True\n return False\n \n ans = []\n for query in queries:\n # see if there is a path from query[0] to query[1]\n ans.append(path(query[0], query[1]))\n return ans\n", + "title": "1462. Course Schedule IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y , return true if the nodes corresponding to the values x and y in the tree are cousins , or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0 , and children of each depth k node are at the depth k + 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "1 <= Node.val <= 100", + "Each node has a unique value.", + "x != y", + "x and y are exist in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4], x = 4, y = 3Output:false", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4,null,5], x = 5, y = 4Output:true", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3,null,4], x = 2, y = 3Output:false", + "image": "https://assets.leetcode.com/uploads/2019/02/13/q1248-03.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 42.36%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isCousins(TreeNode root, int x, int y) {\n \n //If any of x or y is at root, it means they can't be at same depth. Return false.\n if(root.val == x || root.val == y) return false;\n \n \n Deque queue = new LinkedList<>();\n queue.offer(root);\n \n boolean xFound = false;\n boolean yFound = false;\n \n int parentX = 0;\n int parentY = 0;\n \n //Do level-order traversal until x or y is found or queue is empty.\n while(!queue.isEmpty() && !xFound && !yFound){\n \n int size = queue.size();\n\t\t\t\n //Traverse that level.\n while(size-- > 0){\n TreeNode node = queue.poll();\n\t\t\t\t\n //if x or y is found at left/right, save the parent and set the \"found\" flag to true.\n //This flag will break the loop as soon as any one (x or y) is found. \n\t\t\t\t//we don't need to go deeper to find second if it isn't found at this level.\n\t\t\t\t\n if(node.left != null) {\n queue.offer(node.left);\n \n if(node.left.val == x){\n parentX = node.val;\n xFound = true;\n }\n if(node.left.val == y){\n parentY = node.val;\n yFound = true;\n }\n \n }\n\n if(node.right != null) {\n queue.offer(node.right);\n \n if(node.right.val == x){\n parentX = node.val;\n xFound = true;\n }\n if(node.right.val == y){\n parentY = node.val;\n yFound = true;\n }\n }\n }\n \n }\n return xFound && yFound && parentX != parentY;\n }\n}\n", + "title": "993. Cousins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y , return true if the nodes corresponding to the values x and y in the tree are cousins , or false otherwise. Two nodes of a binary tree are cousins if they have the same depth with different parents. Note that in a binary tree, the root node is at the depth 0 , and children of each depth k node are at the depth k + 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "1 <= Node.val <= 100", + "Each node has a unique value.", + "x != y", + "x and y are exist in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4], x = 4, y = 3Output:false", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4,null,5], x = 5, y = 4Output:true", + "image": "https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3,null,4], x = 2, y = 3Output:false", + "image": "https://assets.leetcode.com/uploads/2019/02/13/q1248-03.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n ans = False\n def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:\n def dfs(node, depth):\n if self.ans or not node: return 0\n if node.val == x or node.val == y: return depth\n l = dfs(node.left, depth+1)\n r = dfs(node.right, depth+1)\n if not (l and r): return l or r\n if l == r and l != depth + 1: self.ans = True\n return 0\n \n dfs(root, 0)\n return self.ans\n", + "title": "993. Cousins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1] . The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the correct password is \"345\" and you enter in \"012345\" : After typing 0 , the most recent 3 digits is \"0\" , which is incorrect. After typing 1 , the most recent 3 digits is \"01\" , which is incorrect. After typing 2 , the most recent 3 digits is \"012\" , which is incorrect. After typing 3 , the most recent 3 digits is \"123\" , which is incorrect. After typing 4 , the most recent 3 digits is \"234\" , which is incorrect. After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks.", + "After typing 0 , the most recent 3 digits is \"0\" , which is incorrect.", + "After typing 1 , the most recent 3 digits is \"01\" , which is incorrect.", + "After typing 2 , the most recent 3 digits is \"012\" , which is incorrect.", + "After typing 3 , the most recent 3 digits is \"123\" , which is incorrect.", + "After typing 4 , the most recent 3 digits is \"234\" , which is incorrect.", + "After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 2Output:\"10\"Explanation:The password is a single digit, so enter each digit. \"01\" would also unlock the safe.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 2Output:\"01100\"Explanation:For each possible password:\n- \"00\" is typed in starting from the 4thdigit.\n- \"01\" is typed in starting from the 1stdigit.\n- \"10\" is typed in starting from the 3rddigit.\n- \"11\" is typed in starting from the 2nddigit.\nThus \"01100\" will unlock the safe. \"01100\", \"10011\", and \"11001\" would also unlock the safe.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 5.23%) | Memory: 124.1 MB (Top 5.06%)\n\nclass Solution {\n String ans;\n public String crackSafe(int n, int k) {\n int minLen = (int)Math.pow(k, n) + (n -1);\n\n dfs(\"\", n ,k, new HashSet(),minLen);\n return ans;\n }\n\n private void dfs(String s, int n, int k, HashSetvisited,int minLen){\n if (s.length() == minLen){\n ans = s;\n return;\n }\n if (s.length() > minLen){return;}\n\n for (int i = 0; i < k; i++){\n s += String.valueOf(i);\n String lastN = s.substring(Math.max(0,s.length() - n), s.length());\n //If already in hashset, rollback and continue;\n if (visited.contains(lastN)){\n s = s.substring(0, s.length() - 1);\n continue;}\n if(lastN.length() == n){ // only put n length string in hashset\n visited.add(lastN);\n }\n\n dfs(s,n,k,visited,minLen);\n if (visited.size() == minLen - n + 1){return;} // if hashset contains all possible combinations just return\n visited.remove(lastN);\n s = s.substring(0, s.length() - 1);\n }\n\n }\n}\n", + "title": "753. Cracking the Safe", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1] . The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. Return any string of minimum length that will unlock the safe at some point of entering it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the correct password is \"345\" and you enter in \"012345\" : After typing 0 , the most recent 3 digits is \"0\" , which is incorrect. After typing 1 , the most recent 3 digits is \"01\" , which is incorrect. After typing 2 , the most recent 3 digits is \"012\" , which is incorrect. After typing 3 , the most recent 3 digits is \"123\" , which is incorrect. After typing 4 , the most recent 3 digits is \"234\" , which is incorrect. After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks.", + "After typing 0 , the most recent 3 digits is \"0\" , which is incorrect.", + "After typing 1 , the most recent 3 digits is \"01\" , which is incorrect.", + "After typing 2 , the most recent 3 digits is \"012\" , which is incorrect.", + "After typing 3 , the most recent 3 digits is \"123\" , which is incorrect.", + "After typing 4 , the most recent 3 digits is \"234\" , which is incorrect.", + "After typing 5 , the most recent 3 digits is \"345\" , which is correct and the safe unlocks." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 2Output:\"10\"Explanation:The password is a single digit, so enter each digit. \"01\" would also unlock the safe.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 2Output:\"01100\"Explanation:For each possible password:\n- \"00\" is typed in starting from the 4thdigit.\n- \"01\" is typed in starting from the 1stdigit.\n- \"10\" is typed in starting from the 3rddigit.\n- \"11\" is typed in starting from the 2nddigit.\nThus \"01100\" will unlock the safe. \"01100\", \"10011\", and \"11001\" would also unlock the safe.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 121 ms (Top 27.97%) | Memory: 27.9 MB (Top 17.84%)\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n seen=set()\n def dfs(s,last_n):\n if len(seen)==(k**n): return s\n if len(last_n)();\n for(var log : logs){\n if(log.equals(\"../\")){\n if(!stack.empty())\n stack.pop();\n }else if(log.equals(\"./\")){\n\n }else{\n stack.push(log);\n }\n }\n return stack.size();\n }\n}", + "title": "1598. Crawler Log Folder", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: You are given a list of strings logs where logs[i] is the operation performed by the user at the i th step. The file system starts in the main folder, then the operations in logs are performed. Return the minimum number of operations needed to go back to the main folder after the change folder operations. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/09/sample_11_1957.png", + "https://assets.leetcode.com/uploads/2020/09/09/sample_22_1957.png" + ], + "constraints": [ + "\"../\" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder ).", + "\"./\" : Remain in the same folder.", + "\"x/\" : Move to the child folder named x (This folder is guaranteed to always exist )." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]Output:2Explanation:Use this change folder operation \"../\" 2 times and go back to the main folder.", + "image": null + }, + { + "text": "Example 2: Input:logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]Output:3", + "image": null + }, + { + "text": "Example 3: Input:logs = [\"d1/\",\"../\",\"../\",\"../\"]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n m='../'\n r='./'\n\t\t#create an empty stack\n stk=[]\n\t\t#iterate through the list\n for i in logs:\n\t\t\t#if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack\n if(i==m):\n if(len(stk)>0):\n stk.pop()\n\t\t\t#else if Remain in the same folder (./) operator occurs, do nothing and move to next element in list\n elif(i==r):\n continue\n\t\t\t#else add element to the stack\n else:\n stk.append(i)\n\t\t#now return the size of the stack which would be the minimum number of operations needed to go back to the main folder\n return(len(stk))\n\t\t```", + "title": "1598. Crawler Log Folder", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parent i , child i , isLeft i ] indicates that parent i is the parent of child i in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root . The test cases will be generated such that the binary tree is valid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If isLeft i == 1 , then child i is the left child of parent i .", + "If isLeft i == 0 , then child i is the right child of parent i ." + ], + "examples": [ + { + "text": "Example 1: Input:descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]Output:[50,20,80,15,17,19]Explanation:The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png" + }, + { + "text": "Example 2: Input:descriptions = [[1,2,1],[2,3,0],[3,4,1]]Output:[1,2,null,null,3,4]Explanation:The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode createBinaryTree(int[][] descriptions) {\n HashMap map=new HashMap<>();\n HashSet children=new HashSet<>();\n for(int[] info:descriptions)\n {\n int parent=info[0],child=info[1];\n boolean isLeft=info[2]==1?true:false;\n TreeNode parentNode=null;\n TreeNode childNode=null;\n if(map.containsKey(parent))\n parentNode=map.get(parent);\n else\n parentNode=new TreeNode(parent);\n if(map.containsKey(child))\n childNode=map.get(child);\n else\n childNode=new TreeNode(child);\n if(isLeft)\n parentNode.left=childNode;\n else\n parentNode.right=childNode;\n map.put(parent,parentNode);\n map.put(child,childNode);\n children.add(child);\n \n }\n TreeNode root=null;\n for(int info[]:descriptions)\n {\n if(!children.contains(info[0]))\n {\n root=map.get(info[0]);\n break;\n }\n }\n return root;\n }\n \n \n}", + "title": "2196. Create Binary Tree From Descriptions", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 2D integer array descriptions where descriptions[i] = [parent i , child i , isLeft i ] indicates that parent i is the parent of child i in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root . The test cases will be generated such that the binary tree is valid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If isLeft i == 1 , then child i is the left child of parent i .", + "If isLeft i == 0 , then child i is the right child of parent i ." + ], + "examples": [ + { + "text": "Example 1: Input:descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]Output:[50,20,80,15,17,19]Explanation:The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png" + }, + { + "text": "Example 2: Input:descriptions = [[1,2,1],[2,3,0],[3,4,1]]Output:[1,2,null,null,3,4]Explanation:The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.", + "image": "https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n hashmap = {}\n nodes = set()\n children = set()\n for parent,child,isLeft in descriptions:\n nodes.add(parent)\n nodes.add(child)\n children.add(child)\n if parent not in hashmap:\n hashmap[parent] = TreeNode(parent)\n if child not in hashmap:\n hashmap[child] = TreeNode(child)\n if isLeft:\n hashmap[parent].left = hashmap[child]\n if not isLeft:\n hashmap[parent].right = hashmap[child]\n \n for node in nodes:\n if node not in children:\n return hashmap[node]\n\n\n\n", + "title": "2196. Create Binary Tree From Descriptions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k . Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == nums1.length", + "n == nums2.length", + "1 <= m, n <= 500", + "0 <= nums1[i], nums2[i] <= 9", + "1 <= k <= m + n" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5Output:[9,8,6,5,3]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [6,7], nums2 = [6,0,4], k = 5Output:[6,7,6,0,4]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [3,9], nums2 = [8,9], k = 3Output:[9,8,9]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 39.80%) | Memory: 117.7 MB (Top 6.97%)\nclass Solution {\n public int[] maxNumber(int[] nums1, int[] nums2, int k) {\n String ans=\"\";\n for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq\n String one = solve(nums1, i); // find the best seq matching len of i\n String two = solve(nums2, k-i); // len of k-i\n StringBuilder sb = new StringBuilder();\n int a = 0, b = 0;\n while(a < i || b < k-i){ // merge it to the max\n sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));\n }\n if (sb.toString().compareTo(ans)>0){ // if better, we replace.\n ans=sb.toString();\n }\n }\n int[] res = new int[k];\n for (int i = 0; i < k;++i){\n res[i]=ans.charAt(i)-'0';\n }\n return res;\n }\n\n private String solve(int[] arr, int k){\n Deque stack = new ArrayDeque<>();\n for (int i = 0;ik&&stack.peek() List[int]:\n m = len(nums1)\n n = len(nums2)\n dp = {}\n \n # get the max number string with \"length\" from index \"i\" in nums1 and index \"j\" in nums2\n # using number string to easy to compare\n def getMaxNumberString(i, j, length):\n if length == 0:\n return \"\"\n \n # using memoization to optimize for the overlapping subproblems\n key = (i, j, length)\n if key in dp:\n return dp[key]\n \n # greedy to find the possible max digit from nums1 and nums2\n # 1) bigger digit in the higher position of the number will get bigger number\n # 2) at the same time, we need to ensure that we still have enough digits to form a number with \"length\" digits\n \n # try to find the possible max digit from index i in nums1\n index1 = None\n for ii in range(i, m):\n if (m - ii + n - j) < length:\n break\n if index1 is None or nums1[index1] < nums1[ii]:\n index1 = ii\n \n # try to find the possible max digit from index j in nums2\n index2 = None\n for jj in range(j, n):\n if (m - i + n - jj) < length:\n break\n if index2 is None or nums2[index2] < nums2[jj]:\n index2 = jj\n \n maxNumberStr = None\n if index1 is not None and index2 is not None:\n if nums1[index1] > nums2[index2]:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif nums1[index1] < nums2[index2]:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n else:\n # get the same digit from nums1 and nums2, so need to try two cases and get the max one \n maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1))\n elif index1 is not None:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif index2 is not None:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n \n dp[key] = maxNumberStr\n return maxNumberStr\n\n result_str = getMaxNumberString(0, 0, k)\n \n # number string to digit array\n result = []\n for c in result_str:\n result.append(int(c))\n \n return result", + "title": "321. Create Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array instructions , you are asked to create a sorted array from the elements in instructions . You start with an empty container nums . For each element from left to right in instructions , insert it into nums . The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5] , the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3 , element 5 is greater than 3 ) and nums will become [1,2,3,3,5] . Return the total cost to insert all elements from instructions into nums . Since the answer may be large, return it modulo 10^9 + 7 Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of elements currently in nums that are strictly less than instructions[i] .", + "The number of elements currently in nums that are strictly greater than instructions[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = [1,5,6,2]Output:1Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\nThe total cost is 0 + 0 + 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:instructions = [1,2,3,6,5,4]Output:3Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:instructions = [1,3,3,3,2,4,2,1,2]Output:4Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 90.0%) | Memory: 59.11 MB (Top 43.3%)\n\nclass Fenwick {\n public int[] tree; //Binary indexed Tree array\n \n //initialize a new Fenwick tree of size length\n public Fenwick(int length) {\n tree = new int[length];\n }\n \n //Returns the sum of values in an array from range [0, i]\n public int sum(int i) {\n int sum = 0;\n while(i > 0) {\n sum += tree[i];\n i = i - (i & -i); //flip the last set bit using 2's compliment\n }\n return sum;\n }\n \n //Returns sum of values in the given range [start, end]\n public int sumRange(int start, int end) {\n return sum(end) - sum(start - 1);\n }\n \n //updates the value at index i by \"k\" in tree\n public void update(int i, int k) {\n while(i < tree.length) {\n tree[i] += k;\n i = i + (i & -i); //add last set bit\n }\n }\n}\nclass Solution {\n public int createSortedArray(int[] instructions) {\n //check for valid instructions\n if(instructions.length == 0) {\n return 0;\n }\n \n /*\n to check for values strictly greater than any ith value in the instructions, we \n need to find the largest value in the instructions, this will denote the range \n\t\t\tof values in the Fenwick tree\n */\n int max = 0;\n for(int value : instructions) {\n if(value > max) {\n max = value;\n }\n }\n \n /*\n initialize a Fenwick Tree structure to allow for the search of all values strictly less than and \n strictly greater than instructions[i].\n \n since we need the tree to be 1 indexed, we add 1 to max\n */\n Fenwick tree = new Fenwick(max + 1);\n int cost = 0;\n \n for(int i = 0; i < instructions.length;i++) {\n int current_value = instructions[i];\n \n //get all the values less and greater than current_value\n int strictly_less = tree.sumRange(0, current_value - 1);\n int strictly_greater = tree.sumRange(current_value + 1, max);\n \n //update cost\n cost += Math.min(strictly_less, strictly_greater);\n \n //cost may be large so we mod it with 10^9 + 7\n cost = cost % ((int)1e9 + 7);\n \n //update the current_value's count in the FW tree\n tree.update(current_value, 1);\n }\n \n return cost;\n }\n}", + "title": "1649. Create Sorted Array through Instructions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array instructions , you are asked to create a sorted array from the elements in instructions . You start with an empty container nums . For each element from left to right in instructions , insert it into nums . The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5] , the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3 , element 5 is greater than 3 ) and nums will become [1,2,3,3,5] . Return the total cost to insert all elements from instructions into nums . Since the answer may be large, return it modulo 10^9 + 7 Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of elements currently in nums that are strictly less than instructions[i] .", + "The number of elements currently in nums that are strictly greater than instructions[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = [1,5,6,2]Output:1Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\nThe total cost is 0 + 0 + 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:instructions = [1,2,3,6,5,4]Output:3Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:instructions = [1,3,3,3,2,4,2,1,2]Output:4Explanation:Begin with nums = [].\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\n​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\n​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5781 ms (Top 22.88%) | Memory: 36.00 MB (Top 13.56%)\n\nclass Fenwick:\n \"\"\"Fenwick tree aka binary indexed tree\"\"\"\n def __init__(self, n):\n self.nums = [0]*(n+1)\n \n def sum(self, k): \n ans = 0\n while k: \n ans += self.nums[k]\n k &= k-1\n return ans \n \n def add(self, i, x): \n i += 1\n while i < len(self.nums): \n self.nums[i] += x\n i += i & -i\n\n\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n ans = 0\n fen = Fenwick(10**5)\n freq = {} # frequency of each instructions\n for i, x in enumerate(instructions): \n less = fen.sum(x)\n more = i - freq.get(x, 0) - less\n ans += min(less, more)\n fen.add(x, 1)\n freq[x] = 1 + freq.get(x, 0)\n return ans % 1_000_000_007\n", + "title": "1649. Create Sorted Array through Instructions", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two arrays of integers nums and index . Your task is to create target array under the following rules: Return the target array. It is guaranteed that the insertion operations will be valid. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Initially target array is empty.", + "From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.", + "Repeat the previous step until there are no elements to read in nums and index." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,3,4], index = [0,1,2,2,1]Output:[0,4,1,3,2]Explanation:nums index target\n0 0 [0]\n1 1 [0,1]\n2 2 [0,1,2]\n3 2 [0,1,3,2]\n4 1 [0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,0], index = [0,1,2,3,0]Output:[0,1,2,3,4]Explanation:nums index target\n1 0 [1]\n2 1 [1,2]\n3 2 [1,2,3]\n4 3 [1,2,3,4]\n0 0 [0,1,2,3,4]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], index = [0]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def createTargetArray(self, nums, index):\n \n def merge(arr, low, mid, high):\n L, R = arr[low:mid+1], arr[mid+1:high+1]\n i = j = 0\n k = low\n \n while i < len(L) and j < len(R):\n if L[i][0] + j >= R[j][0]:\n arr[k] = R[j]\n j += 1\n else:\n L[i][0] += j\n arr[k] = L[i]\n i += 1\n k += 1\n \n while i < len(L):\n L[i][0] += j\n arr[k] = L[i]\n i += 1; k += 1\n \n while j < len(R):\n arr[k] = R[j]\n j += 1; k += 1\n \n \n def mergeSort(arr, low, high):\n if low < high:\n mid = (low + high) // 2\n mergeSort(arr, low, mid)\n mergeSort(arr, mid + 1, high)\n merge(arr, low, mid, high)\n \n arr = [[index[i], nums[i]] for i in range(len(nums))]\n mergeSort(arr, 0, len(nums) - 1)\n \n for x in arr:\n nums[x[0]] = x[1]\n \n return nums", + "title": "1389. Create Target Array in the Given Order", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [a i , b i ] represents a connection between servers a i and b i . Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "n - 1 <= connections.length <= 10^5", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no repeated connections." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]Output:[[1,3]]Explanation:[[3,1]] is also accepted.", + "image": "https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png" + }, + { + "text": "Example 2: Input:n = 2, connections = [[0,1]]Output:[[0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 74.61%) | Memory: 107.90 MB (Top 55.73%)\n\nclass Solution {\n // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection\n public List> criticalConnections(int n, List> connections) {\n List[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(List oneConnection :connections) {\n graph[oneConnection.get(0)].add(oneConnection.get(1));\n graph[oneConnection.get(1)].add(oneConnection.get(0));\n }\n int timer[] = new int[1];\n List> results = new ArrayList<>();\n boolean[] visited = new boolean[n];\n int []timeStampAtThatNode = new int[n]; \n criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode);\n return results;\n }\n \n \n public void criticalConnectionsUtil(List[] graph, int parent, int node, int timer[], boolean[] visited, List> results, int []timeStampAtThatNode) {\n visited[node] = true;\n timeStampAtThatNode[node] = timer[0]++;\n int currentTimeStamp = timeStampAtThatNode[node];\n \n for(int oneNeighbour : graph[node]) {\n if(oneNeighbour == parent) continue;\n if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode);\n timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]);\n if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour));\n }\n \n \n }\n \n}\n", + "title": "1192. Critical Connections in a Network", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [a i , b i ] represents a connection between servers a i and b i . Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "n - 1 <= connections.length <= 10^5", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no repeated connections." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]Output:[[1,3]]Explanation:[[3,1]] is also accepted.", + "image": "https://assets.leetcode.com/uploads/2019/09/03/1537_ex1_2.png" + }, + { + "text": "Example 2: Input:n = 2, connections = [[0,1]]Output:[[0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \n dic = collections.defaultdict(list)\n for c in connections:\n u, v = c\n dic[u].append(v)\n dic[v].append(u)\n \n \n timer = 0\n \n depth, lowest, parent, visited = [float(\"inf\")]*n, [float(\"inf\")]*n, [float(\"inf\")]*n, [False]*n\n res = []\n \n def find(u):\n \n nonlocal timer\n \n visited[u] = True\n depth[u], lowest[u] = timer, timer\n timer += 1\n \n for v in dic[u]: \n \n if not visited[v]:\n parent[v] = u\n find(v)\n if lowest[v]>depth[u]:\n res.append([u,v])\n \n if parent[u]!=v:\n lowest[u] = min(lowest[u], lowest[v])\n \n find(0)\n return res\n ", + "title": "1192. Critical Connections in a Network", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order , then x should occur before y in the permuted string. Return any permutation of s that satisfies this property . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= order.length <= 26", + "1 <= s.length <= 200", + "order and s consist of lowercase English letters.", + "All the characters of order are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:order = \"cba\", s = \"abcd\"Output:\"cbad\"Explanation:\"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.", + "image": null + }, + { + "text": "Example 2: Input:order = \"cbafg\", s = \"abcd\"Output:\"cbad\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 38.18%)\n\nclass Solution {\n public String customSortString(String X, String Y) {\n //char count of string Y\n int[] charCount = new int[26];\n for(char c : Y.toCharArray()){\n charCount[c - 'a']++;\n }\n \n StringBuilder sb = new StringBuilder();\n \n //first store char in same order of String X\n for(char c : X.toCharArray()){\n while(charCount[c - 'a'] --> 0){\n sb.append(c);\n }\n }\n \n //now store remaining char of string Y\n for(int i = 0; i < 26; i++){\n char c = (char)('a' + i);\n while(charCount[i] --> 0){\n sb.append(c);\n }\n }\n \n return sb.toString();\n }\n}\n", + "title": "791. Custom Sort String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order , then x should occur before y in the permuted string. Return any permutation of s that satisfies this property . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= order.length <= 26", + "1 <= s.length <= 200", + "order and s consist of lowercase English letters.", + "All the characters of order are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:order = \"cba\", s = \"abcd\"Output:\"cbad\"Explanation:\"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.", + "image": null + }, + { + "text": "Example 2: Input:order = \"cbafg\", s = \"abcd\"Output:\"cbad\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 328 ms (Top 5.22%) | Memory: 13.9 MB (Top 17.87%)\nclass Solution:\n def customSortString(self, order: str, s: str) -> str:\n charValue = [0] * 26\n for i in range(len(order)):\n idx = ord(order[i]) - ord('a')\n charValue[idx] = 26 - i\n\n arrS = []\n n = 0\n for c in s:\n arrS.append(c)\n n += 1\n\n sorted = False\n while not sorted:\n sorted = True\n for i in range(n - 1):\n if charValue[ord(arrS[i]) - ord('a')] < charValue[ord(arrS[i + 1]) - ord('a')]:\n sorted = False\n arrS[i], arrS[i + 1] = arrS[i + 1], arrS[i]\n\n return ''.join(arrS)", + "title": "791. Custom Sort String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix: In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off. You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell). Starting from the point (0, 0) , return the minimum steps you need to walk to cut off all the trees . If you cannot cut off all the trees, return -1 . Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 means the cell cannot be walked through.", + "1 represents an empty cell that can be walked through.", + "A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height." + ], + "examples": [ + { + "text": "Example 1: Input:forest = [[1,2,3],[0,0,4],[7,6,5]]Output:6Explanation:Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.", + "image": "https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg" + }, + { + "text": "Example 2: Input:forest = [[1,2,3],[0,0,0],[7,6,5]]Output:-1Explanation:The trees in the bottom row cannot be accessed as the middle row is blocked.", + "image": "https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg" + }, + { + "text": "Example 3: Input:forest = [[2,3,4],[0,0,5],[8,7,6]]Output:6Explanation:You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 273 ms (Top 92.8%) | Memory: 44.58 MB (Top 18.0%)\n\nclass Solution {\n //approach: 1st store all the positions in the min heap acc. to their height\n //now start removing the elements from the heap and calculate their dis using bfs\n // if at any point we cann't reach at the next position return -1;\n // else keep on adding the distances and return;\n public int cutOffTree(List> forest) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n for(int i=0;i1)\n pq.add(new int[]{i,j});\n }\n }\n int ans=0;\n int curr[]={0,0};\n while(pq.size()>0){\n int[] temp=pq.poll();\n int dis=calcDis(forest,curr,temp);\n //System.out.println(dis+\" \"+temp.height);\n if(dis==-1)\n return -1;\n ans+=dis;\n curr=temp;\n }\n return ans;\n }\n int calcDis(List> forest,int start[],int end[]){\n int n=forest.size(),m=forest.get(0).size();\n boolean vis[][]=new boolean[n][m];\n Queue queue=new LinkedList<>();\n queue.add(start);\n vis[start[0]][start[1]]=true;\n int dis=0;\n while(queue.size()>0){\n int len =queue.size();\n while(len-->0){\n int temp[]=queue.remove();\n int r=temp[0],c=temp[1];\n if(r==end[0] && c==end[1])\n return dis;\n if(r+1=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n queue.add(new int[]{r-1,c});\n vis[r-1][c]=true;\n }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n queue.add(new int[]{r,c-1});\n vis[r][c-1]=true;\n }if(c+1 int:\n a = []\n n = len(forest)\n m = len(forest[0])\n for i in range(n):\n for j in range(m):\n if forest[i][j] > 1:\n a.append(forest[i][j])\n a.sort()\n \n s = 0\n ux = 0\n uy = 0\n for h in a:\n dist = [[None] * m for i in range(n)]\n q = deque()\n q.append((ux, uy))\n dist[ux][uy] = 0\n while q:\n ux, uy = q.popleft()\n if forest[ux][uy] == h:\n break\n d = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n for dx, dy in d:\n vx = ux + dx\n vy = uy + dy\n if vx < 0 or vx >= n or vy < 0 or vy >= m:\n continue\n if forest[vx][vy] == 0:\n continue\n if dist[vx][vy] is None:\n q.append((vx, vy))\n dist[vx][vy] = dist[ux][uy] + 1\n if forest[ux][uy] == h:\n s += dist[ux][uy]\n else:\n return -1\n return s\n", + "title": "675. Cut Off Trees for Golf Event", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid ​​​, where m and n are both even integers, and an integer k . The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "Both m and n are even integers.", + "1 <= grid[i][j] <= 5000", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[40,10],[30,20]], k = 1Output:[[10,20],[40,30]]Explanation:The figures above represent the grid at every state.", + "image": "https://assets.leetcode.com/uploads/2021/06/19/rod2.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2Output:[[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]Explanation:The figures above represent the grid at every state.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] rotateGrid(int[][] grid, int k) {\n int m = grid.length, n = grid[0].length, noOfLayers = Math.min(m/2, n/2); \n // Peeling each layer one by one\n for(int layerNo = 0; layerNo < noOfLayers; layerNo++){\n // Please suggest if you have better way to find perimeter of matrix on a given layer!\n int perimeter = (m-(2*layerNo)) + (n-(2*layerNo)-1) + (m-(2*layerNo)-1) + (n-(2*layerNo)-2); \n int[] layer = new int[perimeter]; // this out be use to store that particular layer\n readLayer(grid, layer, layerNo, m, n); // this will read the layer\n writeLayer(grid, layer, layerNo, m, n, k); // this will rotate it by k and write back the layer \n }\n return grid;\n }\n \n public void readLayer(int[][] grid, int[] layer, int layerNo, int m, int n){\n int count = 0, r = layerNo, c = layerNo;\n m--; n--;\n // read left a -> c\n for(int i = layerNo; i < n - layerNo; i++) layer[count++] = grid[layerNo][i];\n // read down c -> i\n for(int i = layerNo; i < m - layerNo; i++) layer[count++] = grid[i][n-layerNo];\n // read right i -> g\n for(int i = n-layerNo; i > layerNo; i--) layer[count++] = grid[m-layerNo][i];\n // read up g -> a\n for(int i = m-layerNo; i > layerNo; i--) layer[count++] = grid[i][layerNo];\n }\n \n public void writeLayer(int[][] grid, int[] layer, int layerNo, int m, int n, int k){\n m--; n--;\n int len = layer.length, count = k; \n // write left a -> c\n for(int i = layerNo; i < n - layerNo; i++){\n count %= len; // reason if goes out of length start back from 0\n grid[layerNo][i] = layer[count++];\n }\n // write down c -> i\n for(int i = layerNo; i < m - layerNo; i++){\n count %= len;\n grid[i][n-layerNo] = layer[count++];\n } \n // write right i -> g\n for(int i = n-layerNo; i > layerNo; i--){\n count %= len;\n grid[m-layerNo][i] = layer[count++];\n }\n // write up g -> a\n for(int i = m-layerNo; i > layerNo; i--){\n count %= len;\n grid[i][layerNo] = layer[count++];\n } \n }\n \n \n}\n", + "title": "1914. Cyclically Rotating a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n integer matrix grid ​​​, where m and n are both even integers, and an integer k . The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/10/ringofgrid.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "Both m and n are even integers.", + "1 <= grid[i][j] <= 5000", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[40,10],[30,20]], k = 1Output:[[10,20],[40,30]]Explanation:The figures above represent the grid at every state.", + "image": "https://assets.leetcode.com/uploads/2021/06/19/rod2.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2Output:[[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]Explanation:The figures above represent the grid at every state.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n n = len(grid)\n m = len(grid[0])\n \n i, j = 0, 0\n bottom, right = n-1, m-1 \n while i < n//2 and j < m//2:\n temp = []\n for x in range(j, right):\n temp.append(grid[i][x])\n for x in range(i, bottom):\n temp.append(grid[x][right])\n for x in range(right, j, -1):\n temp.append(grid[bottom][x])\n for x in range(bottom, i, -1):\n temp.append(grid[x][j])\n \n \n indx = 0\n for x in range(j, right):\n grid[i][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(i, bottom):\n grid[x][right] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(right, j, -1):\n grid[bottom][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(bottom, i, -1):\n grid[x][j] = temp[(k + indx)%len(temp)]\n indx += 1\n \n i += 1\n j += 1\n bottom -= 1\n right -= 1\n return grid\n", + "title": "1914. Cyclically Rotating a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= temperatures.length <= 10^5", + "30 <= temperatures[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:temperatures = [73,74,75,71,69,72,76,73]Output:[1,1,4,2,1,1,0,0]", + "image": null + }, + { + "text": "Example 2: Input:temperatures = [30,40,50,60]Output:[1,1,1,0]", + "image": null + }, + { + "text": "Example 3: Input:temperatures = [30,60,90]Output:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 207 ms (Top 22.03%) | Memory: 127.9 MB (Top 72.12%)\nclass Solution {\n public int[] dailyTemperatures(int[] temperatures) {\n HashMaphm=new HashMap<>();\n Stackst=new Stack<>();\n for(int i=0;i0&&temperatures[i]>temperatures[st.peek()]){\n hm.put(st.pop(),i);\n }\n st.push(i);\n }\n int []ans=new int[temperatures.length];\n for(int i=0;i T[s[-1]]:\n ans[s[-1]] = cur - s[-1]\n s.pop()\n s.append(cur)\n return ans\n", + "title": "739. Daily Temperatures", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a data stream input of non-negative integers a 1 , a 2 , ..., a n , summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class: Example 1:", + "description_images": [], + "constraints": [ + "SummaryRanges() Initializes the object with an empty stream.", + "void addNum(int val) Adds the integer val to the stream.", + "int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start i , end i ] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]Output[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]ExplanationSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1); // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3); // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7); // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2); // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 169 ms (Top 23.71%) | Memory: 73.9 MB (Top 52.59%)\nclass SummaryRanges {\n\n Map st;\n Map end;\n Set pending;\n int[][] prev = new int[0][];\n Set seen = new HashSet<>();\n int INVALID = -1;\n public SummaryRanges() {\n st = new HashMap<>();\n end= new HashMap<>();\n pending = new HashSet<>();\n }\n\n public void addNum(int val) { // [TC: O(1)]\n if (!seen.contains(val)){ // only add if not seen.\n pending.add(val); // pending processing list\n }\n }\n\n public int[][] getIntervals() { // [TC: O(pending list length (= k)) best case (all merges), O(n)+O(klogk) worst case (all inserts)]\n Set addSet = new HashSet<>();\n for (int n : pending){\n if (st.containsKey(n+1)&&end.containsKey(n-1)){ // merge intervals on both ends, a new interval form -> add to addSet\n int[] s = st.get(n+1);\n int[] e = end.get(n-1);\n int[] m = new int[]{e[0], s[1]};\n st.remove(n+1);\n end.remove(n-1);\n st.put(m[0], m);\n end.put(m[1], m);\n s[0]=e[0]=INVALID;\n addSet.remove(s); // may be in addSet, remove them\n addSet.remove(e);\n addSet.add(m);\n }else if (st.containsKey(n+1)){ // merge with the next interval, no other action required.\n st.get(n+1)[0]--;\n st.put(n, st.get(n+1));\n st.remove(n+1);\n }else if (end.containsKey(n-1)){ // merge with the previous interval, no other action required.\n end.get(n-1)[1]++;\n end.put(n, end.get(n-1));\n end.remove(n-1);\n }else{ // new interval -> add to AddSet\n int[] m = new int[]{n, n};\n addSet.add(m);\n st.put(n, m);\n end.put(n, m);\n }\n }\n\n seen.addAll(pending);\n pending.clear(); // remember to clear the pending list.\n\n if (!addSet.isEmpty()){ // IF there is no new intervals to insert, we SKIP this.\n List addList = new ArrayList<>(addSet);\n addList.sort(Comparator.comparingInt(o -> o[0]));\n int i = 0, j = 0; // two pointers because both prev & addList are sorted.\n List ans = new ArrayList<>();\n while(i < prev.length || j < addList.size()){\n if (i < prev.length && prev[i][0]==INVALID){\n i++;\n }else if (j == addList.size() || i < prev.length && prev[i][0]addList.get(j)[0]){\n ans.add(addList.get(j++));\n }\n }\n prev = ans.toArray(new int[0][]);\n }\n\n return prev;\n }\n}", + "title": "352. Data Stream as Disjoint Intervals", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a data stream input of non-negative integers a 1 , a 2 , ..., a n , summarize the numbers seen so far as a list of disjoint intervals. Implement the SummaryRanges class: Example 1:", + "description_images": [], + "constraints": [ + "SummaryRanges() Initializes the object with an empty stream.", + "void addNum(int val) Adds the integer val to the stream.", + "int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start i , end i ] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]Output[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]ExplanationSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1); // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3); // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7); // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2); // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]", + "image": null + } + ], + "follow_up": null, + "solution": "class SummaryRanges:\n def __init__(self):\n self.intervals = []\n def addNum(self, val: int) -> None:\n left, right = 0, len(self.intervals) - 1\n while left <= right:\n mid = (left + right) // 2\n e = self.intervals[mid]\n if e[0] <= val <= e[1]: return\n elif val < e[0]:right = mid - 1\n else:left = mid + 1\n pos = left\n self.intervals.insert(pos, [val, val])\n if pos + 1 < len(self.intervals) and val + 1 == self.intervals[pos+1][0]:\n self.intervals[pos][1] = self.intervals[pos+1][1]\n del self.intervals[pos+1]\n if pos - 1 >= 0 and val - 1 == self.intervals[pos-1][1]:\n self.intervals[pos-1][1] = self.intervals[pos][1]\n del self.intervals[pos]\n\n def getIntervals(self) -> List[List[int]]:\n return self.intervals\n", + "title": "352. Data Stream as Disjoint Intervals", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day , month and year respectively. Return the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"} . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:day = 31, month = 8, year = 2019Output:\"Saturday\"", + "image": null + }, + { + "text": "Example 2: Input:day = 18, month = 7, year = 1999Output:\"Sunday\"", + "image": null + }, + { + "text": "Example 3: Input:day = 15, month = 8, year = 1993Output:\"Sunday\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String dayOfTheWeek(int day, int month, int year) {\n String[] week = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n year--;\n int total = (year/4)*366+(year-year/4)*365;\n int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n year++;\n if(year%4==0 && year!=2100){\n months[1]++;\n }\n for(int i=0;i str:\n LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5\n DAYS = (\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\n difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR), (day, month, year))\n return DAYS[(difference + DAY) % 7]\n\n def daysBetweenDates(self, date1: tuple, date2: tuple) -> int:\n LOWEST_YEAR = 1971\n\n def daysSinceLowest(date: tuple) -> int:\n day, month, year = date\n\n isLeapYear = lambda x: 1 if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else 0\n\n days: int = 0\n # days between the LOWEST_YEAR and year\n days += 365 * (year - LOWEST_YEAR) + sum(map(isLeapYear, range(LOWEST_YEAR, year)))\n # days between year and exact date\n daysInMonth = (31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n days += sum(daysInMonth[:month - 1]) + day\n return days\n\n return abs(daysSinceLowest(date1) - daysSinceLowest(date2))", + "title": "1185. Day of the Week", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"Output:9Explanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"Output:41", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 18.15%) | Memory: 44.20 MB (Top 65.48%)\n\nclass Solution {\n public int dayOfYear(String date) {\n int days = 0;\n int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};\n String[] year = date.split(\"-\");\n int y = Integer.valueOf(year[0]);\n int month = Integer.valueOf(year[1]);\n int day = Integer.valueOf(year[2]);\n boolean leap = false;\n for(int i = 0; i < month-1; i++){\n days = days+arr[i];\n }\n days = days+day;\n if(y%4==0){\n if(y%100==0){\n if(y%400==0){\n leap = true;\n }\n else{\n leap = false;\n }\n }\n else{\n leap = true;\n }\n }\n else{\n leap = false;\n }\n if(leap==true && month>2){\n System.out.println(\"Leap Year\");\n days = days+1;\n }\n return days;\n }\n}\n", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"Output:9Explanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"Output:41", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int dayOfYear(String date) {\n int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n int year = (date.charAt(0)-48)*1000+(date.charAt(1)-48)*100+(date.charAt(2)-48)*10+date.charAt(3)-48;\n if(year%4==0 && year!=1900){\n months[1]++;\n }\n int ans = 0;\n for(int i=0;i<((date.charAt(5)-48)*10)+date.charAt(6)-48-1;i++){\n ans += months[i];\n }\n ans += (date.charAt(8)-48)*10+date.charAt(9)-48;\n return ans;\n }\n}", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD , return the day number of the year . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "date.length == 10", + "date[4] == date[7] == '-' , and all other date[i] 's are digits", + "date represents a calendar date between Jan 1 st , 1900 and Dec 31 th , 2019." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"2019-01-09\"Output:9Explanation:Given date is the 9th day of the year in 2019.", + "image": null + }, + { + "text": "Example 2: Input:date = \"2019-02-10\"Output:41", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 123 ms (Top 44.98%) | Memory: 14 MB (Top 32.35%)\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}\n year=int(date[:4])\n if year%4==0:\n if year%100==0:\n if year%400==0:\n d[2]=29\n else:\n d[2]=29\n month=int(date[5:7])\n day=int(date[8:])\n ans=0\n for i in range(1,month+1):\n ans+=d[i]\n return ans-(d[month]-day)", + "title": "1154. Day of the Year", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"Output:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"Output:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"Output:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 46.14%) | Memory: 16.20 MB (Top 85.67%)\n\nclass Solution:\n def decodeString(self, s):\n it, num, stack = 0, 0, [\"\"]\n while it < len(s):\n if s[it].isdigit():\n num = num * 10 + int(s[it])\n elif s[it] == \"[\":\n stack.append(num)\n num = 0\n stack.append(\"\")\n elif s[it] == \"]\":\n str1 = stack.pop()\n rep = stack.pop()\n str2 = stack.pop()\n stack.append(str2 + str1 * rep)\n else:\n stack[-1] += s[it] \n it += 1 \n return \"\".join(stack)\n", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"Output:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"Output:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"Output:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.88%) | Memory: 41.8 MB (Top 72.85%)\nclass Solution {\n public String decodeString(String s) {\n\n int bb = s.indexOf('['); // location of beginning bracket\n int nbb = s.indexOf('[', bb + 1); // location of next beginning bracket\n int eb = s.indexOf(']'); // location of ending bracket\n\n int n = 0; // number of times to repeat\n int nl = 1; // number of digits for n\n char nd; // next digit\n\n String insert = \"\"; // repeated string\n String end = \"\"; // remainder of string after repeated portion\n\n while (bb != -1) { // while the string contains a beginning bracket\n\n while (nbb < eb && nbb > bb) { // while the next beginning bracket is before the ending bracket\n bb = nbb; // update location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // update location of next beginning bracket\n }\n\n nl = 1; // reset length of n\n while (bb - nl >= 0) { // while there are characters in front of the beginning bracket\n nd = s.charAt(bb - nl); // next digit\n if (nd <= '9' && nd >= '0') { // if next digit is an integer\n n += (int)(nd - '0') * Math.pow(10, nl - 1); // update value of n\n nl++; // increment length of n\n }\n else break; // not an integer\n }\n\n insert = s.substring(bb + 1, eb); // set repeated string\n end = s.substring(eb + 1); // set remainder of string\n s = s.substring(0, bb - nl + 1); // remove everything after the digits\n\n while (n > 0) {\n s += insert; // add repeated string n times\n n--;\n }\n s += end; // add remainder of string\n\n bb = s.indexOf('['); // new location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // new location of next beginning bracket\n eb = s.indexOf(']'); // new location of ending bracket\n }\n return s;\n }\n}", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"Output:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"Output:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"Output:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeString(self, s: str) -> str:\n stk = []\n \n for i in range(len(s)):\n \n if s[i] != ']':\n stk.append(s[i]) \n else:\n strr = ''\n while stk[-1] != '[':\n strr = stk.pop() + strr\n stk.pop()\n \n num = ''\n while stk and stk[-1].isdigit():\n num = stk.pop() + num\n \n stk.append(int(num) * strr)\n \n return ''.join(stk)\n \n \n ", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the strings key and message , which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Return the decoded message . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, given key = \" hap p y bo y\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ( 'h' -> 'a' , 'a' -> 'b' , 'p' -> 'c' , 'y' -> 'd' , 'b' -> 'e' , 'o' -> 'f' )." + ], + "examples": [ + { + "text": "Example 1: Input:key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"Output:\"this is a secret\"Explanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"thequickbrownfoxjumpsover thelazydog\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex1new4.jpg" + }, + { + "text": "Example 2: Input:key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"Output:\"the five boxing wizards jump quickly\"Explanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 48.65%) | Memory: 44.7 MB (Top 35.73%)\nclass Solution {\n public String decodeMessage(String key, String message) {\n StringBuilder ans = new StringBuilder();//Using String Builder to append the string\n key = key.replaceAll(\" \", \"\");\n //Removing the spaces\n HashMap letters = new HashMap<>();\n //Mapping the key into a hashmap.\n char original = 'a';\n for (int i = 0; i < key.length() ; i++) {\n if (!letters.containsKey(key.charAt(i))){\n letters.put(key.charAt(i),original++);\n }\n }\n //After the first pass all the letters of the key will be mapped with their respective original letters.\n for (int i = 0; i < message.length(); i++) {\n if (letters.containsKey(message.charAt(i))){\n //Now replacing the letters of the message with appropriate letter according to the key\n ans.append(letters.get(message.charAt(i)));\n }else{\n ans.append(message.charAt(i));\n //This is for characters other than the letters in the key example a space \" \"\n //They will not be replaced by any letters hence original letter is appended into the StringBuilder\n }\n }\n return ans.toString();\n }\n}", + "title": "2325. Decode the Message", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the strings key and message , which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Return the decoded message . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, given key = \" hap p y bo y\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ( 'h' -> 'a' , 'a' -> 'b' , 'p' -> 'c' , 'y' -> 'd' , 'b' -> 'e' , 'o' -> 'f' )." + ], + "examples": [ + { + "text": "Example 1: Input:key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"Output:\"this is a secret\"Explanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"thequickbrownfoxjumpsover thelazydog\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex1new4.jpg" + }, + { + "text": "Example 2: Input:key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"Output:\"the five boxing wizards jump quickly\"Explanation:The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".", + "image": "https://assets.leetcode.com/uploads/2022/05/08/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 94.64%) | Memory: 17.30 MB (Top 36.34%)\n\nclass Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n mapping = {' ': ' '}\n i = 0\n res = ''\n letters = 'abcdefghijklmnopqrstuvwxyz'\n \n for char in key:\n if char not in mapping:\n mapping[char] = letters[i]\n i += 1\n \n for char in message:\n res += mapping[char]\n \n return res", + "title": "2325. Decode the Message", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows . originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText . The arrow indicates the order in which the cells are filled. All empty cells are filled with ' ' . The number of columns is chosen such that the rightmost column will not be empty after filling in originalText . encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText , then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = \"cipher\" and rows = 3 , then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\" . Given the encoded string encodedText and number of rows rows , return the original string originalText . Note: originalText does not have any trailing spaces ' ' . The test cases are generated such that there is only one possible originalText . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= encodedText.length <= 10^6", + "encodedText consists of lowercase English letters and ' ' only.", + "encodedText is a valid encoding of some originalText that does not have trailing spaces.", + "1 <= rows <= 1000", + "The testcases are generated such that there is only one possible originalText ." + ], + "examples": [ + { + "text": "Example 1: Input:encodedText = \"ch ie pr\", rows = 3Output:\"cipher\"Explanation:This is the same example described in the problem description.", + "image": null + }, + { + "text": "Example 2: Input:encodedText = \"iveo eed l te olc\", rows = 4Output:\"i love leetcode\"Explanation:The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/exam1.png" + }, + { + "text": "Example 3: Input:encodedText = \"coding\", rows = 1Output:\"coding\"Explanation:Since there is only 1 row, both originalText and encodedText are the same.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/eg2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 15.7%) | Memory: 54.11 MB (Top 92.9%)\n\nclass Solution {\n public String decodeCiphertext(String str, int rows) {\n\n //first find column size!!\n \tint cols=str.length()/rows;\n \tStringBuilder res=new StringBuilder(),new_res=new StringBuilder();;\n \tfor(int i=0;i=0;i--) {\n \n if(fg==0&&res.charAt(i)==' ')\n continue;\n fg=1;\n new_res.append(res.charAt(i));\n }\n return new_res.reverse().toString();\n }\n}", + "title": "2075. Decode the Slanted Ciphertext", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows . originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText . The arrow indicates the order in which the cells are filled. All empty cells are filled with ' ' . The number of columns is chosen such that the rightmost column will not be empty after filling in originalText . encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText , then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = \"cipher\" and rows = 3 , then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\" . Given the encoded string encodedText and number of rows rows , return the original string originalText . Note: originalText does not have any trailing spaces ' ' . The test cases are generated such that there is only one possible originalText . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= encodedText.length <= 10^6", + "encodedText consists of lowercase English letters and ' ' only.", + "encodedText is a valid encoding of some originalText that does not have trailing spaces.", + "1 <= rows <= 1000", + "The testcases are generated such that there is only one possible originalText ." + ], + "examples": [ + { + "text": "Example 1: Input:encodedText = \"ch ie pr\", rows = 3Output:\"cipher\"Explanation:This is the same example described in the problem description.", + "image": null + }, + { + "text": "Example 2: Input:encodedText = \"iveo eed l te olc\", rows = 4Output:\"i love leetcode\"Explanation:The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/exam1.png" + }, + { + "text": "Example 3: Input:encodedText = \"coding\", rows = 1Output:\"coding\"Explanation:Since there is only 1 row, both originalText and encodedText are the same.", + "image": "https://assets.leetcode.com/uploads/2021/10/26/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n n = len(encodedText)\n cols = n // rows\n step = cols + 1\n res = \"\"\n \n for i in range(cols):\n for j in range(i, n, step):\n res += encodedText[j]\n \n return res.rstrip()", + "title": "2075. Decode the Slanted Ciphertext", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . Given a string s containing only digits, return the number of ways to decode it . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"12\"Output:2Explanation:\"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).", + "image": null + }, + { + "text": "Example 2: Input:s = \"226\"Output:3Explanation:\"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).", + "image": null + }, + { + "text": "Example 3: Input:s = \"06\"Output:0Explanation:\"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numDecodings(String s) {\n int[]dp = new int[s.length() + 1];\n dp[0] = 1;\n dp[1] = s.charAt(0) == '0' ? 0 : 1;\n \n for(int i = 2;i<=s.length();i++) {\n int oneDigit = Integer.valueOf(s.substring(i-1,i));\n int twoDigit = Integer.valueOf(s.substring(i-2,i));\n \n if(oneDigit >= 1) {\n dp[i] += dp[i - 1];\n }\n if(twoDigit >= 10 && twoDigit <= 26) {\n dp[i] += dp[i - 2];\n }\n }\n return dp[s.length()];\n }\n}\n", + "title": "91. Decode Ways", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . Given a string s containing only digits, return the number of ways to decode it . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"12\"Output:2Explanation:\"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).", + "image": null + }, + { + "text": "Example 2: Input:s = \"226\"Output:3Explanation:\"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).", + "image": null + }, + { + "text": "Example 3: Input:s = \"06\"Output:0Explanation:\"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 48 ms (Top 59.57%) | Memory: 14.1 MB (Top 30.54%)\nclass Solution:\n def numDecodings(self, s: str) -> int:\n if s[0] == '0' or '00' in s:\n return 0\n l = len(s)\n if l == 1:\n return 1\n elif l == 2:\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n return 1\n else:\n return 0\n else:\n if int(s) <= 26:\n return 2\n else:\n return 1\n dp = [1]\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n dp.append(1)\n else:\n return 0\n else:\n if int(s[:2]) <= 26:\n dp.append(2)\n else:\n dp.append(1)\n for i in range(2, l):\n num = 0\n if s[i] == '0':\n if s[i-1] != '1' and s[i-1] != '2':\n return 0\n else:\n num = dp[i-2]\n elif s[i-1] == '1' or (s[i-1] == '2' and int(f'{s[i-1]}{s[i]}') <= 26):\n num = dp[i-1]+dp[i-2]\n else:\n num = dp[i-1]\n dp.append(num)\n return dp[l-1]", + "title": "91. Decode Ways", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ( '0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\" , \"12\" , \"13\" , \"14\" , \"15\" , \"16\" , \"17\" , \"18\" , or \"19\" . Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent. Given a string s consisting of digits and '*' characters, return the number of ways to decode it . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"*\"Output:9Explanation:The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1*\"Output:18Explanation:The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"2*\"Output:15Explanation:The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1171 ms (Top 5.16%) | Memory: 49 MB (Top 90.58%)\nclass Solution {\n public int numDecodings(String s) {\n int[] dp = new int[s.length()+1];\n dp[0]=1;\n int M = (int)1e9+7;\n for (int i = 1; i <= s.length(); i++){\n for (int j = 1; j <= 26; j++){\n if (j<10 && (s.charAt(i-1)-'0'==j||s.charAt(i-1)=='*')){ // 1 digit -> if they are equal or if *\n dp[i]+=dp[i-1];\n dp[i]%=M;\n }\n if (i>1&&j>=10&&ok(j,s.substring(i-2,i))){ // ok() function handles 2 digits\n dp[i]+=dp[i-2];\n dp[i]%=M;\n }\n }\n }\n return dp[s.length()];\n }\n\n private boolean ok(int val, String s){ // TRUE if the value s represents can equal to val.\n return (s.equals(\"**\") && val%10 > 0\n || s.charAt(0)=='*' && val%10==s.charAt(1)-'0'\n || s.charAt(1)=='*' && val/10==s.charAt(0)-'0' && val % 10 > 0\n || !s.contains(\"*\") && Integer.parseInt(s)==val);\n }\n}", + "title": "639. Decode Ways II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A message containing letters from A-Z can be encoded into numbers using the following mapping: To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into: Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\" . In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ( '0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\" , \"12\" , \"13\" , \"14\" , \"15\" , \"16\" , \"17\" , \"18\" , or \"19\" . Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent. Given a string s consisting of digits and '*' characters, return the number of ways to decode it . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"AAJF\" with the grouping (1 1 10^6)", + "\"KJF\" with the grouping (11 10^6)" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"*\"Output:9Explanation:The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1*\"Output:18Explanation:The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"2*\"Output:15Explanation:The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".", + "image": null + }, + { + "text": "'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 180 ms (Top 97.4%) | Memory: 21.20 MB (Top 53.7%)\n\nclass Solution:\n def numDecodings(self, s: str):\n if s[0] == '0': return 0\n cMap = {'0':0, '*': 9, '**': 15, '1*': 9, '2*': 6} #{char(s) : multiplier} mapping\n for i in range(1, 27): cMap[str(i)] = 1\n for i in range(0, 7): cMap['*'+str(i)] = 2\n for i in range(7, 10): cMap['*'+str(i)] = 1\n \n dp = [0]*(len(s)+1)\n dp[0], dp[-1] = cMap[s[0]] , 1\n \n for i in range(1, len(s)):\n dp[i] += (cMap[s[i]]*dp[i-1] + cMap.get(s[i-1:i+1],0)*dp[i-2])%(10**9 + 7)\n if not dp[i]: return 0\n \n return dp[-2]", + "title": "639. Decode Ways II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = arr[i] XOR arr[i + 1] . For example, if arr = [1,0,2,1] , then encoded = [1,2,3] . You are given the encoded array. You are also given an integer first , that is the first element of arr , i.e. arr[0] . Return the original array arr . It can be proved that the answer exists and is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^4", + "encoded.length == n - 1", + "0 <= encoded[i] <= 10^5", + "0 <= first <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [1,2,3], first = 1Output:[1,0,2,1]Explanation:If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,2,7,3], first = 4Output:[4,2,0,7,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 83.89%) | Memory: 55.1 MB (Top 84.00%)\nclass Solution {\n public int[] decode(int[] encoded, int first) {\n int[] ans = new int[encoded.length + 1];\n ans[0] = first;\n for (int i = 0; i < encoded.length; i++) {\n ans[i + 1] = ans[i] ^ encoded[i];\n }\n return ans;\n }\n}", + "title": "1720. Decode XORed Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = arr[i] XOR arr[i + 1] . For example, if arr = [1,0,2,1] , then encoded = [1,2,3] . You are given the encoded array. You are also given an integer first , that is the first element of arr , i.e. arr[0] . Return the original array arr . It can be proved that the answer exists and is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^4", + "encoded.length == n - 1", + "0 <= encoded[i] <= 10^5", + "0 <= first <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [1,2,3], first = 1Output:[1,0,2,1]Explanation:If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,2,7,3], first = 4Output:[4,2,0,7,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]\n", + "title": "1720. Decode XORed Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd . It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = perm[i] XOR perm[i + 1] . For example, if perm = [1,3,2] , then encoded = [2,1] . Given the encoded array, return the original array perm . It is guaranteed that the answer exists and is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= n < 10^5", + "n is odd.", + "encoded.length == n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [3,1]Output:[1,2,3]Explanation:If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,5,4,6]Output:[2,4,1,5,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decode(int[] encoded) {\n int n = encoded.length+1, all = 0;\n for(int i = 1; i <= n; ++i){//a^b^c^d^e^f^g^h^i\n all ^= i;\n }\n int x = 0;\n for(int v : encoded){//a^b b^c c^d d^e e^f f^g g^h h^i = a^i\n x ^= v;\n }\n int mid = all^x; //a^b^c^d^e^f^g^h^i ^ a^i = b^c^d^e^f^g^h\n for(int i = 1, j = encoded.length-2; i < j;i += 2, j -= 2){\n //(b^c^d^e^f^g^h) ^ (b^c ^ g^h ^ d^e ^ e^f) = e\n mid ^= encoded[i]^encoded[j];\n }\n int[] ans = new int[n];\n ans[n/2] = mid;\n //a b c d e f g h i\n //a^b b^c c^d d^e e^f f^g g^h h^i\n for(int i = n/2+1; i < n; ++i){\n ans[i] = encoded[i-1]^ans[i-1];\n }\n for(int i = n/2-1; i >= 0; --i){\n ans[i] = encoded[i]^ans[i+1];\n }\n return ans;\n }\n}\n", + "title": "1734. Decode XORed Permutation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd . It was encoded into another integer array encoded of length n - 1 , such that encoded[i] = perm[i] XOR perm[i + 1] . For example, if perm = [1,3,2] , then encoded = [2,1] . Given the encoded array, return the original array perm . It is guaranteed that the answer exists and is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= n < 10^5", + "n is odd.", + "encoded.length == n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:encoded = [3,1]Output:[1,2,3]Explanation:If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]", + "image": null + }, + { + "text": "Example 2: Input:encoded = [6,5,4,6]Output:[2,4,1,5,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1921 ms (Top 32.18%) | Memory: 33.8 MB (Top 16.09%)\n\nfrom functools import reduce\nfrom operator import xor\n\nclass Solution:\n\n def decode(self, encoded: List[int]) -> List[int]:\n n = len(encoded) + 1\n a = reduce(xor, range(1, n+1))\n b = reduce(xor, encoded[1::2])\n result = [a ^ b]\n for y in encoded:\n result.append(result[-1] ^ y)\n return result", + "title": "1734. Decode XORed Permutation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an encoded string s . To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: Given an integer k , return the k th letter ( 1-indexed) in the decoded string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the character read is a letter, that letter is written onto the tape.", + "If the character read is a digit d , the entire current tape is repeatedly written d - 1 more times in total." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet2code3\", k = 10Output:\"o\"Explanation:The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10thletter in the string is \"o\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ha22\", k = 5Output:\"h\"Explanation:The decoded string is \"hahahaha\".\nThe 5thletter is \"h\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a2345678999999999999999\", k = 1Output:\"a\"Explanation:The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1stletter is \"a\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String decodeAtIndex(String s, int k) {\n long sz = 0;\n for (char ch : s.toCharArray()){ // total length\n sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;\n }\n --k; // make it 0 index based.\n for (int i = s.length() - 1; true; i--){\n if (Character.isLetter(s.charAt(i)) && --sz == k){ // found!\n return \"\"+s.charAt(i);\n }else if(Character.isDigit(s.charAt(i))){\n sz /= (s.charAt(i) - '0');\n k %= sz; // we are at the end of a multplied string, we can mod k with sz.\n }\n }\n }\n}\n", + "title": "880. Decoded String at Index", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an encoded string s . To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: Given an integer k , return the k th letter ( 1-indexed) in the decoded string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the character read is a letter, that letter is written onto the tape.", + "If the character read is a digit d , the entire current tape is repeatedly written d - 1 more times in total." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet2code3\", k = 10Output:\"o\"Explanation:The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10thletter in the string is \"o\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ha22\", k = 5Output:\"h\"Explanation:The decoded string is \"hahahaha\".\nThe 5thletter is \"h\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"a2345678999999999999999\", k = 1Output:\"a\"Explanation:The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1stletter is \"a\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n idx = {}\n acclens = [0]\n prevd = 1\n j = 0\n for i, c in enumerate(S + '1'):\n if c.isalpha():\n idx[acclens[-1] * prevd + j] = i\n j += 1\n else:\n acclens.append(acclens[-1] * prevd + j)\n prevd = int(c)\n j = 0\n k = K - 1\n for al in reversed(acclens[1:]):\n k %= al\n if k in idx:\n return S[idx[k]]\n return None # should never reach this\n", + "title": "880. Decoded String at Index", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0 ).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "nums.length % 2 == 0", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[2,4,4,4]Explanation:The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,3]Output:[1,3,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decompressRLElist(int[] nums) {\n ArrayList arr = new ArrayList<>();\n for (int i = 0; i+1 < nums.length; i += 2) {\n for (int j = 0; j < nums[i]; ++j) {\n arr.add(nums[i+1]);\n }\n }\n int[] res = new int[arr.size()];\n for (int i = 0; i < res.length; ++i) res[i] = arr.get(i);\n return res;\n }\n}\n", + "title": "1313. Decompress Run-Length Encoded List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0 ).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "nums.length % 2 == 0", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[2,4,4,4]Explanation:The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,3]Output:[1,3,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def decompressRLElist(self, nums: List[int]) -> List[int]:\n answer = []\n \n for i in range(0, len(nums), 2):\n for j in range(0, nums[i]):\n answer.append(nums[i + 1])\n \n return answer\n", + "title": "1313. Decompress Run-Length Encoded List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1 . An array A is a zigzag array if either: Return the minimum number of moves to transform the given array nums into a zigzag array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...", + "OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ..." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:2Explanation:We can decrease 2 to 0 or 3 to 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,6,1,6,2]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /*\n firstly, check elements in odd indices are greater than its neighbours.\n if not, decrease its neigbours and update the cost.\n \n do same thing for even indices, because there can be two combinations as indicated in question.\n */\n \n private int calculateCost(int[] nums, int start){\n int res = 0;\n int n = nums.length;\n int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.\n \n for(int i=start;i= cur){\n res += prev-cur +1;\n arr[i-1] = cur-1;\n } \n \n if(next >= cur){\n res += next-cur +1;\n arr[i+1] = cur-1;\n }\n }\n return res;\n }\n \n public int movesToMakeZigzag(int[] nums) {\n return Math.min(calculateCost(nums, 0), calculateCost(nums,1));\n }\n}\n", + "title": "1144. Decrease Elements To Make Array Zigzag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1 . An array A is a zigzag array if either: Return the minimum number of moves to transform the given array nums into a zigzag array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...", + "OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ..." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:2Explanation:We can decrease 2 to 0 or 3 to 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,6,1,6,2]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solve(self,arr,n,x):\n idx = 1\n ans = 0\n while idx < n:\n if idx == 0: idx += 1\n if idx % 2 == x:\n if arr[idx-1] >= arr[idx]:\n ans += arr[idx-1] - arr[idx] + 1\n arr[idx-1] = arr[idx] - 1\n idx = idx-1\n else:\n idx = idx+1\n else:\n if arr[idx-1] <= arr[idx]:\n ans += arr[idx] - arr[idx - 1] + 1\n arr[idx] = arr[idx-1] - 1\n idx += 1 \n return ans\n \n def movesToMakeZigzag(self, nums: List[int]) -> int:\n ans1 = self.solve([x for x in nums],len(nums),0)\n ans2 = self.solve([x for x in nums],len(nums),1)\n return min(ans1,ans2)\n", + "title": "1144. Decrease Elements To Make Array Zigzag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s formed by digits and '#' . We want to map s to English lowercase characters as follows: Return the string formed after mapping . The test cases are generated so that a unique mapping will always exist. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Characters ( 'a' to 'i' ) are represented by ( '1' to '9' ) respectively.", + "Characters ( 'j' to 'z' ) are represented by ( '10#' to '26#' ) respectively." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10#11#12\"Output:\"jkab\"Explanation:\"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1326#\"Output:\"acz\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.3%) | Memory: 40.72 MB (Top 56.6%)\n\nclass Solution {\n public String freqAlphabets(String str) {\n HashMap map = new HashMap<>();\n int k = 1;\n for (char ch = 'a'; ch <= 'z'; ch++) {\n if (ch < 'j')\n map.put(String.valueOf(k++), ch);\n else\n map.put(String.valueOf(k++)+\"#\", ch);\n }\n \n StringBuilder sb = new StringBuilder();\n int i = str.length() - 1;\n while (i >= 0) {\n if (str.charAt(i) == '#') {\n sb.append(map.get(str.substring(i - 2, i+1)));\n i -= 3;\n } else {\n sb.append(map.get(str.substring(i, i + 1)));\n i--;\n }\n }\n \n return sb.reverse().toString();\n }\n}", + "title": "1309. Decrypt String from Alphabet to Integer Mapping", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s formed by digits and '#' . We want to map s to English lowercase characters as follows: Return the string formed after mapping . The test cases are generated so that a unique mapping will always exist. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Characters ( 'a' to 'i' ) are represented by ( '1' to '9' ) respectively.", + "Characters ( 'j' to 'z' ) are represented by ( '10#' to '26#' ) respectively." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10#11#12\"Output:\"jkab\"Explanation:\"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"1326#\"Output:\"acz\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n for i in range(26,0,-1): s = s.replace(str(i)+\"#\"*(i>9),chr(96+i))\n return s", + "title": "1309. Decrypt String from Alphabet to Integer Mapping", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]Output:15", + "image": "https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" + }, + { + "text": "Example 2: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output:19", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 8.75%) | Memory: 59.3 MB (Top 36.23%)\nclass Solution {\n public int height(TreeNode root)\n {\n if(root == null)\n return 0;\n return Math.max(height(root.left), height(root.right)) + 1;\n }\n public int deepestLeavesSum(TreeNode root) {\n if(root == null) return 0;\n if(root.left == null && root.right == null) return root.val;\n Queue q = new LinkedList<>();\n q.add(root);\n q.add(null);\n int hght = height(root);\n int sum = 0;\n while(q.size()>0 && q.peek()!=null)\n {\n TreeNode temp = q.remove();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n if(q.peek() == null)\n {\n q.remove();\n q.add(null);\n hght--;\n }\n if(hght == 1)\n {\n while(q.size()>0 && q.peek()!=null)\n {\n sum+=q.remove().val;\n }\n }\n\n }\n return sum;\n }\n}", + "title": "1302. Deepest Leaves Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]Output:15", + "image": "https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" + }, + { + "text": "Example 2: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output:19", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n \n \"\"\"\n THOUGHT PROCESS:\n 1) find the height of the tree, this way we would know how deep we need to go.\n 2) we need a counter to check how deep we are and this is not available in deepestLeavesSum so we create a new function deepestLeave.\n 3) now we go in depth, if we are at bottom, we return the value, we recursively visit both left and right nodes.\n \n \"\"\"\n \n def height(self, root):\n if root is None:\n return 0\n else:\n x, y = 1, 1\n if root.left:\n x = self.height(root.left)+1\n if root.right:\n y = self.height(root.right)+1\n \n return max(x, y)\n \n \n def deepestLeave(self, root, depth):\n \n if root is None:\n return 0\n \n if root.left is None and root.right is None:\n if depth == 1:\n return root.val\n \n return self.deepestLeave(root.left, depth-1) + self.deepestLeave(root.right, depth-1)\n \n def deepestLeavesSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.deepestLeave(root, self.height(root))\n \n \n \n \n \n", + "title": "1302. Deepest Leaves Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a valid (IPv4) IP address , return a defanged version of that IP address. A defanged IP address replaces every period \".\" with \"[.]\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The given address is a valid IPv4 address." + ], + "examples": [ + { + "text": "Example 1: Input:address = \"1.1.1.1\"Output:\"1[.]1[.]1[.]1\"", + "image": null + }, + { + "text": "Example 2: Input:address = \"255.100.50.0\"Output:\"255[.]100[.]50[.]0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String defangIPaddr(String address) {\n return address.replace(\".\",\"[.]\");\n }\n}\n", + "title": "1108. Defanging an IP Address", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a valid (IPv4) IP address , return a defanged version of that IP address. A defanged IP address replaces every period \".\" with \"[.]\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The given address is a valid IPv4 address." + ], + "examples": [ + { + "text": "Example 1: Input:address = \"1.1.1.1\"Output:\"1[.]1[.]1[.]1\"", + "image": null + }, + { + "text": "Example 2: Input:address = \"255.100.50.0\"Output:\"255[.]100[.]50[.]0\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 6.11%) | Memory: 16.10 MB (Top 75.91%)\n\nclass Solution:\n\tdef defangIPaddr(self, address: str) -> str:\n\t\treturn address.replace('.', '[.]')\n", + "title": "1108. Defanging an IP Address", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k . To decrypt the code, you must replace every number. All the numbers are replaced simultaneously . As code is circular, the next element of code[n-1] is code[0] , and the previous element of code[0] is code[n-1] . Given the circular array code and an integer key k , return the decrypted code to defuse the bomb ! Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If k > 0 , replace the i th number with the sum of the next k numbers.", + "If k < 0 , replace the i th number with the sum of the previous k numbers.", + "If k == 0 , replace the i th number with 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:code = [5,7,1,4], k = 3Output:[12,10,16,13]Explanation:Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.", + "image": null + }, + { + "text": "Example 2: Input:code = [1,2,3,4], k = 0Output:[0,0,0,0]Explanation:When k is zero, the numbers are replaced by 0.", + "image": null + }, + { + "text": "Example 3: Input:code = [2,4,9,3], k = -2Output:[12,5,6,13]Explanation:The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of thepreviousnumbers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] decrypt(int[] code, int k) {\n int[] res = new int[code.length];\n if (k == 0) return res;\n //Define the initial window and initial sum\n int start = 1, end = k, sum = 0;\n if (k < 0) {//If k < 0, the starting point will be end of the array.\n k = -k;\n start = code.length - k;\n end = code.length - 1;\n }\n for (int i = start; i <= end; i++) sum += code[i];\n //Scan through the code array as i moving to the right, update the window sum.\n for (int i = 0; i < code.length; i++) {\n res[i] = sum;\n sum -= code[(start++) % code.length];\n sum += code[(++end) % code.length];\n }\n return res;\n }\n}\n", + "title": "1652. Defuse the Bomb", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty array of non-negative integers nums , the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums , that has the same degree as nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length will be between 1 and 50,000.", + "nums[i] will be an integer between 0 and 49,999." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3,1]Output:2Explanation:The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,3,1,4,2]Output:6Explanation:The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 84.55%) | Memory: 49.70 MB (Top 5.99%)\n\nclass Solution {\n public int findShortestSubArray(int[] nums) {\n // The int is an array of [firstEncounter, lastEncounter, frequency]\n HashMap map = new HashMap<>();\n for(int i = 0; i < nums.length; i++){\n\n // If the key does not exist in the map, we put it with the first encounter and last encounter set to the current position, 'i', and the freqency 1\n if(!map.containsKey(nums[i])){\n map.put(nums[i], new int[]{i, i, 1});\n } \n\n // If it does exist, we update the last encounter to the current position and we increase the frequency by 1\n else {\n int[] arr = map.get(nums[i]);\n arr[1] = i;\n arr[2]++;\n map.put(nums[i], arr);\n }\n }\n // Maximim frequency\n int maxFreq = Integer.MIN_VALUE;\n\n // Minimum distance\n int minDist = Integer.MAX_VALUE;\n\n // Going through all the values of the HashMap\n for(int[] value : map.values()){\n // value[0] = the first encounter index\n // value[1] = the last encounter index\n // value[2] = frequency\n\n // If the frecuency is greater than the maxFreq, then we update it and also set the minDist\n if(value[2] > maxFreq){\n maxFreq = value[2];\n minDist = value[1] - value[0] + 1;\n } \n\n // If the frecuency is equal to the current max, we take the minimum between the exiting minDist and the minimum distance for the current value\n else if(value[2] == maxFreq){\n minDist = Math.min(minDist, value[1] - value[0] + 1);\n }\n }\n return minDist;\n }\n}\n", + "title": "697. Degree of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a non-empty array of non-negative integers nums , the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums , that has the same degree as nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length will be between 1 and 50,000.", + "nums[i] will be an integer between 0 and 49,999." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3,1]Output:2Explanation:The input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,3,1,4,2]Output:6Explanation:The degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 198 ms (Top 78.1%) | Memory: 18.99 MB (Top 16.6%)\n\nclass Solution:\n def findShortestSubArray(self, nums):\n # Group indexes by element type\n d = defaultdict(list)\n for i,x in enumerate(nums):\n d[x].append(i)\n #\n # Find highest Degree\n m = max([ len(v) for v in d.values() ])\n #\n # Find shortest span for max. degree\n best = len(nums)\n for v in d.values():\n if len(v)==m:\n best = min(best,v[-1]-v[0]+1)\n return best", + "title": "697. Degree of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You want to maximize the number of points you get by performing the following operation any number of times: Return the maximum number of points you can earn by applying the above operation some number of times . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,2]Output:6Explanation:You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,3,3,3,4]Output:9Explanation:You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 44.61%) | Memory: 44.9 MB (Top 82.96%)\nclass Solution {\n public int deleteAndEarn(int[] nums) {\n Arrays.sort(nums);\n int onePreviousAgo = 0;\n int previous = 0;\n for(int i = 0; i < nums.length; i++) {\n int sum = 0;\n // On hop there's no constraint to add the previous value\n if(i > 0 && nums[i-1] < nums[i] - 1) {\n onePreviousAgo = previous;\n }\n // Accumulate equal values\n while(i < nums.length - 1 && nums[i] == nums[i+1]) {\n sum += nums[i];\n i++;\n }\n int currentPrevious = previous;\n previous = Math.max(\n onePreviousAgo + nums[i] + sum,\n previous\n );\n onePreviousAgo = currentPrevious;\n // System.out.println(nums[i] + \":\" + previous);\n }\n return previous;\n }\n}", + "title": "740. Delete and Earn", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . You want to maximize the number of points you get by performing the following operation any number of times: Return the maximum number of points you can earn by applying the above operation some number of times . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,2]Output:6Explanation:You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,3,3,3,4]Output:9Explanation:You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n count = Counter(nums)\n m = max(nums)\n memo = {}\n def choose(num):\n if num > m:\n return 0\n if num not in count:\n count[num] = 0\n if num in memo:\n return memo[num]\n memo[num] = max(choose(num + 1), num * count[num] + choose(num + 2))\n return memo[num]\n \n return choose(1)\n\n# time and space complexity\n# n = max(nums)\n# time: O(n)\n# space: O(n)\n \n \n", + "title": "740. Delete and Earn", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s , delete the minimum possible number of characters from s to make it fancy . Return the final string after the deletion . It can be shown that the answer will always be unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leeetcode\"Output:\"leetcode\"Explanation:Remove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabaaaa\"Output:\"aabaa\"Explanation:Remove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\"Output:\"aab\"Explanation:No three consecutive characters are equal, so return \"aab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String makeFancyString(String s) {\n char prev = s.charAt (0);\n int freq = 1;\n StringBuilder res = new StringBuilder ();\n res.append (s.charAt (0));\n for (int i = 1; i < s.length (); i++) {\n if (s.charAt (i) == prev)\n freq++;\n else {\n prev = s.charAt (i);\n freq = 1;\n }\n if (freq < 3)\n res.append (s.charAt (i));\n }\n return res.toString ();\n }\n}\n", + "title": "1957. Delete Characters to Make Fancy String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A fancy string is a string where no three consecutive characters are equal. Given a string s , delete the minimum possible number of characters from s to make it fancy . Return the final string after the deletion . It can be shown that the answer will always be unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leeetcode\"Output:\"leetcode\"Explanation:Remove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabaaaa\"Output:\"aabaa\"Explanation:Remove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aab\"Output:\"aab\"Explanation:No three consecutive characters are equal, so return \"aab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeFancyString(self, s: str) -> str:\n if len(s) < 3:\n return s\n ans = ''\n ans += s[0]\n ans += s[1]\n for i in range(2,len(s)):\n if s[i] != ans[-1] or s[i] != ans[-2]:\n ans += s[i]\n return ans\n", + "title": "1957. Delete Characters to Make Fancy String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of n strings strs , all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as: You want to delete the columns that are not sorted lexicographically . In the above example (0-indexed), columns 0 ( 'a' , 'b' , 'c' ) and 2 ( 'c' , 'e' , 'e' ) are sorted while column 1 ( 'b' , 'c' , 'a' ) is not, so you would delete column 1. Return the number of columns that you will delete . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 1000", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"cba\",\"daf\",\"ghi\"]Output:1Explanation:The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"a\",\"b\"]Output:0Explanation:The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]Output:3Explanation:The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.", + "image": null + }, + { + "text": "abc\nbce\ncae", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 91.77%) | Memory: 42.4 MB (Top 94.00%)\nclass Solution {\n public int minDeletionSize(String[] strs) {\n int count = 0;\n for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column\n for(int j = 0; j < strs.length-1; j++){\n if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(i)){\n continue;\n }else{\n count++;\n break;\n }\n }\n }\n return count;\n }\n}", + "title": "944. Delete Columns to Make Sorted", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of n strings strs , all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as: You want to delete the columns that are not sorted lexicographically . In the above example (0-indexed), columns 0 ( 'a' , 'b' , 'c' ) and 2 ( 'c' , 'e' , 'e' ) are sorted while column 1 ( 'b' , 'c' , 'a' ) is not, so you would delete column 1. Return the number of columns that you will delete . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 1000", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"cba\",\"daf\",\"ghi\"]Output:1Explanation:The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"a\",\"b\"]Output:0Explanation:The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]Output:3Explanation:The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.", + "image": null + }, + { + "text": "abc\nbce\ncae", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 330 ms (Top 23.27%) | Memory: 14.6 MB (Top 66.82%)\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n cols={}\n l=len(strs)\n l_s = len(strs[0])\n delete = set()\n for i in range(l):\n for col in range(l_s):\n if col in cols:\n if cols[col]>strs[i][col]:\n delete.add(col)\n cols[col] = strs[i][col]\n return len(delete)", + "title": "944. Delete Columns to Make Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of n strings strs , all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3} , then the final array after deletions is [\"bef\", \"vyz\"] . Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1] ). Return the minimum possible value of answer.length . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"ca\",\"bb\",\"ac\"]Output:1Explanation:After deleting the first column, strs = [\"a\", \"b\", \"c\"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"xc\",\"yb\",\"za\"]Output:0Explanation:strs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"zyx\",\"wvu\",\"tsr\"]Output:3Explanation:We have to delete every column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDeletionSize(String[] strs) {\n boolean[] sorted = new boolean[strs.length];\n int res = 0;\n for(int i = 0;istrs[j+1].charAt(i)){\n res++;\n break;\n } \n }\n if(j int:\n n = len(strs)\n col_size = len(strs[0])\n # a b c d e f g h i j k l m n o p q r s t u v w x y z\n \n i = 0\n ans = 0\n \n def getRemoved(idx):\n # removing the idx column \n for x in range(n): \n strs[x] = strs[x][:idx] + strs[x][idx+1:]\n \n while i < col_size:\n tmp = strs[0][:i+1]\n flag = True\n similar = False\n \n for j in range(1,n): \n if strs[j][:i+1] < tmp :\n # previous element is larger ( unsorted )\n flag = False\n break\n \n elif strs[j][:i+1] > tmp : \n # previous element is smaller ( sorted )\n tmp = strs[j][:i+1]\n \n else:\n # previous element is equal ( not clear )\n tmp = strs[j][:i+1]\n similar = True\n \n if flag == True and similar == False:\n # all are sorted and we are ready to return ans\n return ans\n \n elif flag == True and similar == True:\n # all are sorted but can't be decided for further columns. check for next col\n i += 1\n \n elif flag == False:\n # unsorted column = removal\n getRemoved(i)\n # increment the answer and since we removed i th col decrement col_size\n ans += 1\n col_size -= 1\n \n return ans\n", + "title": "955. Delete Columns to Make Sorted II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n strings strs , all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3} , then the final array after deletions is [\"bef\", \"vyz\"] . Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]) , and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]) , and so on). Return the minimum possible value of answer.length . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == strs.length", + "1 <= n <= 100", + "1 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"babca\",\"bbazb\"]Output:3Explanation:After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"edcba\"]Output:4Explanation:If we delete less than 4 columns, the only row will not be lexicographically sorted.", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"ghi\",\"def\",\"abc\"]Output:0Explanation:All rows are already lexicographically sorted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 95.45%) | Memory: 16.80 MB (Top 79.55%)\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n n = len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n valid = True\n for a in strs:\n if a[j] > a[i]: \n valid = False\n break\n if valid:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n", + "title": "960. Delete Columns to Make Sorted III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths , where paths[i] is an array representing an absolute path to the i th folder in the file system. Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical , then mark the folders as well as all their subfolders. Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted. Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, [\"one\", \"two\", \"three\"] represents the path \"/one/two/three\" ." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"a\"],[\"c\"],[\"d\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"d\",\"a\"]]Output:[[\"d\"],[\"d\",\"a\"]]Explanation:The file structure is as shown.\nFolders \"/a\" and \"/c\" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named \"b\".", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder1.jpg" + }, + { + "text": "Example 2: Input:paths = [[\"a\"],[\"c\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"a\",\"b\",\"x\"],[\"a\",\"b\",\"x\",\"y\"],[\"w\"],[\"w\",\"y\"]]Output:[[\"c\"],[\"c\",\"b\"],[\"a\"],[\"a\",\"b\"]]Explanation:The file structure is as shown. \nFolders \"/a/b/x\" and \"/w\" (and their subfolders) are marked for deletion because they both contain an empty folder named \"y\".\nNote that folders \"/a\" and \"/c\" are identical after the deletion, but they are not deleted because they were not marked beforehand.", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder2.jpg" + }, + { + "text": "Example 3: Input:paths = [[\"a\",\"b\"],[\"c\",\"d\"],[\"c\"],[\"a\"]]Output:[[\"c\"],[\"c\",\"d\"],[\"a\"],[\"a\",\"b\"]]Explanation:All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter.", + "image": "https://assets.leetcode.com/uploads/2021/07/19/lc-dupfolder3.jpg" + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self):\n self.children = defaultdict(Node)\n self.hash = ''\n self.deleted = False\n \n def add(self, path, i=0):\n if i != len(path):\n self.children[path[i]].add(path, i + 1)\n \n def calc_hash(self, hashes, name='root'):\n for child_name, child in sorted(self.children.items()):\n self.hash += f'{child.calc_hash(hashes, child_name)}+'\n if self.hash:\n hashes[self.hash].append(self)\n return f'{name}({self.hash})'\n \n def to_list(self, lst, path=[]):\n for name, node in self.children.items():\n if not node.deleted:\n lst.append(path + [name])\n node.to_list(lst, path + [name])\n\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n root = Node()\n for path in paths:\n root.add(path)\n hash_to_nodes = defaultdict(list)\n root.calc_hash(hash_to_nodes)\n for nodes in hash_to_nodes.values():\n if len(nodes) > 1:\n for node in nodes:\n node.deleted = True\n res = []\n root.to_list(res)\n return res\n", + "title": "1948. Delete Duplicate Folders in System", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a binary tree root and an integer target , delete all the leaf nodes with value target . Note that once you delete a leaf node with value target , if its parent node becomes a leaf node and has the value target , it should also be deleted (you need to continue doing that until you cannot). Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png", + "https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png", + "https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3000] .", + "1 <= Node.val, target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,2,null,2,4], target = 2Output:[1,null,3,null,4]Explanation:Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).", + "image": null + }, + { + "text": "Example 2: Input:root = [1,3,3,3,2], target = 3Output:[1,3,null,null,2]", + "image": null + }, + { + "text": "Example 3: Input:root = [1,2,null,2,null,2], target = 2Output:[1]Explanation:Leaf nodes in green with value (target = 2) are removed at each step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode removeLeafNodes(TreeNode root, int target) {\n if(root==null)\n return root;\n root.left = removeLeafNodes(root.left,target);\n root.right = removeLeafNodes(root.right,target);\n if(root.left == null && root.right == null && root.val == target)\n root = null;\n return root;\n }\n}", + "title": "1325. Delete Leaves With a Given Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root and an integer target , delete all the leaf nodes with value target . Note that once you delete a leaf node with value target , if its parent node becomes a leaf node and has the value target , it should also be deleted (you need to continue doing that until you cannot). Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png", + "https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png", + "https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3000] .", + "1 <= Node.val, target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,2,null,2,4], target = 2Output:[1,null,3,null,4]Explanation:Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).", + "image": null + }, + { + "text": "Example 2: Input:root = [1,3,3,3,2], target = 3Output:[1,3,null,null,2]", + "image": null + }, + { + "text": "Example 3: Input:root = [1,2,null,2,null,2], target = 2Output:[1]Explanation:Leaf nodes in green with value (target = 2) are removed at each step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:\n if not root:\n return None\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target)\n if not root.left and not root.right and root.val == target:\n return None\n return root\n", + "title": "1325. Delete Leaves With a Given Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3Output:[5,4,6,2,null,null,7]Explanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0Output:[5,3,6,2,4,null,7]Explanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.92 MB (Top 83.3%)\n\nclass Solution {\n public TreeNode deleteNode(TreeNode root, int key) {\n if(root==null) return null;\n \n if(keyroot.val){\n root.right = deleteNode(root.right,key);\n return root;\n }\n \n else{\n if(root.left==null){\n return root.right;\n }\n else if(root.right==null){\n return root.left;\n }\n else{\n TreeNode min = root.right;\n while(min.left!=null){\n min = min.left;\n }\n \n root.val = min.val;\n root.right = deleteNode(root.right,min.val);\n return root;\n }\n }\n }\n}", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3Output:[5,4,6,2,null,null,7]Explanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0Output:[5,3,6,2,4,null,7]Explanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\ndef deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n\ndef find_inorder(root, key):\n\n\tif root is None :\n\t\treturn []\n\n\treturn find_inorder(root.left, key) + [root.val] + find_inorder(root.right, key)\n\ndef find_preorder(root, key):\n\n\tif root is None:\n\t\treturn []\n\n\treturn [root.val] + find_preorder(root.left,key) + find_preorder(root.right, key)\n\npreorder = find_preorder(root, key)\n\ntry:\n\tpreorder.remove(key)\nexcept:\n\treturn root\n\ninorder = find_inorder(root, key)\n\ninorder.remove(key)\n\n\n\n\nhashmap = {}\n\nfor i in range(len(inorder)):\n\tkey = inorder[i]\n\thashmap[key] = i\n\ndef buildTree(left, right):\n\n\tif left > right:\n\t\treturn \n\n\tval = inorder[left]\n\troot = TreeNode(val)\n\n\tindex = hashmap[val]\n\n\troot.left = buildTree(left, index-1)\n\troot.right = buildTree(index+1, right)\n\n\treturn root\n\nN = len(inorder)\nnew_tree = buildTree(0,N-1)\n\nreturn new_tree\n\n\n", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of the nodes in the given list is in the range [2, 1000] .", + "-1000 <= Node.val <= 1000", + "The value of each node in the list is unique .", + "The node to be deleted is in the list and is not a tail node" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,5,1,9], node = 5Output:[4,1,9]Explanation:You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node1.jpg" + }, + { + "text": "Example 2: Input:head = [4,5,1,9], node = 1Output:[4,5,9]Explanation:You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 44.5 MB (Top 10.41%)\nclass Solution {\n public void deleteNode(ListNode node) {\n\n // 4 5 1 9 : Node = 5\n\n node.val = node.next.val;\n\n //Copy next node val to current node.\n //4 1 1 9\n // ------------\n\n //Point node.next = node.next.next\n // 4 -----> 1 ----> 9\n\n node.next = node.next.next;\n // 4 1 9\n }\n}", + "title": "237. Delete Node in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of the nodes in the given list is in the range [2, 1000] .", + "-1000 <= Node.val <= 1000", + "The value of each node in the list is unique .", + "The node to be deleted is in the list and is not a tail node" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,5,1,9], node = 5Output:[4,1,9]Explanation:You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node1.jpg" + }, + { + "text": "Example 2: Input:head = [4,5,1,9], node = 1Output:[4,5,9]Explanation:You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/node2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 87.58%) | Memory: 17.70 MB (Top 6.02%)\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteNode(self, node):\n node.val = node.next.val\n node.next = node.next.next\n", + "title": "237. Delete Node in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete , we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree is at most 1000 .", + "Each node has a distinct value between 1 and 1000 .", + "to_delete.length <= 1000", + "to_delete contains distinct values between 1 and 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7], to_delete = [3,5]Output:[[1,2,null,4],[6],[7]]", + "image": "https://assets.leetcode.com/uploads/2019/07/01/screen-shot-2019-07-01-at-53836-pm.png" + }, + { + "text": "Example 2: Input:root = [1,2,4,null,3], to_delete = [3]Output:[[1,2,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 5.29%) | Memory: 51.1 MB (Top 5.85%)\nclass Solution {\n\n HashMap> parent_val_child_nodes_map;\n HashMap child_val_parent_node_map;\n\n public List delNodes(TreeNode root, int[] to_delete) {\n\n // initialize map\n parent_val_child_nodes_map = new HashMap<> ();\n child_val_parent_node_map = new HashMap<> ();\n\n // fill map\n dfsFillMap(root);\n\n // traverse to_delete to find those that do not have parent after deleting it\n List res = new ArrayList<> ();\n\n // actually deleting nodes\n for (int delete_val : to_delete) {\n\n // if the node has parent\n if (child_val_parent_node_map.containsKey(delete_val)) {\n TreeNode parent_node = child_val_parent_node_map.get(delete_val);\n if (parent_node.left != null && parent_node.left.val == delete_val) {\n parent_node.left = null;\n }\n\n if (parent_node.right != null && parent_node.right.val == delete_val) {\n parent_node.right = null;\n }\n }\n }\n\n // add root to the list first because root has no parent\n // only if root.val is not in to_delete\n if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) {\n res.add(root);\n }\n\n // add other nodes that do not have parent\n for (int delete_val : to_delete) {\n if (parent_val_child_nodes_map.containsKey(delete_val)) {\n for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) {\n\n // make sure the add node is not in to_delete\n int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val;\n if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) {\n res.add(parent_val_child_nodes_map.get(delete_val).get(i));\n }\n }\n }\n }\n\n return res;\n }\n\n public void dfsFillMap(TreeNode root) {\n\n if (root == null) {\n return;\n }\n\n if (root.left != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.left);\n\n child_val_parent_node_map.putIfAbsent(root.left.val, root);\n dfsFillMap(root.left);\n }\n\n if (root.right != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.right);\n\n child_val_parent_node_map.putIfAbsent(root.right.val, root);\n dfsFillMap(root.right);\n }\n\n return;\n }\n}", + "title": "1110. Delete Nodes And Return Forest", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete , we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree is at most 1000 .", + "Each node has a distinct value between 1 and 1000 .", + "to_delete.length <= 1000", + "to_delete contains distinct values between 1 and 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7], to_delete = [3,5]Output:[[1,2,null,4],[6],[7]]", + "image": "https://assets.leetcode.com/uploads/2019/07/01/screen-shot-2019-07-01-at-53836-pm.png" + }, + { + "text": "Example 2: Input:root = [1,2,4,null,3], to_delete = [3]Output:[[1,2,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traverse(self,node,par):\n if node:\n self.parent[node.val] = par\n self.traverse(node.left,node)\n self.traverse(node.right,node)\n \n def deleteNode(self,toDelete):\n node = None\n par = self.parent[toDelete]\n if par.val == toDelete:\n node = par\n elif par.left and par.left.val == toDelete:\n node = par.left\n elif par.right and par.right.val == toDelete:\n node = par.right\n if node.left: \n self.unique[node.left] = True\n if node.right: \n self.unique[node.right] = True\n \n if node in self.unique: self.unique.pop(node)\n if node != self.parent[toDelete]:\n if par.left == node: par.left = None\n else: par.right = None\n\n \n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n self.parent = {}\n self.traverse(root,root)\n self.unique = {root:True}\n for node in to_delete:\n self.deleteNode(node)\n return self.unique\n", + "title": "1110. Delete Nodes And Return Forest", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings word1 and word2 , return the minimum number of steps required to make word1 and word2 the same . In one step , you can delete exactly one character in either string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 500", + "word1 and word2 consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"sea\", word2 = \"eat\"Output:2Explanation:You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"leetcode\", word2 = \"etco\"Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 23.73%) | Memory: 46.5 MB (Top 77.36%)\nclass Solution {\n public int minDistance(String word1, String word2) {\n int n = word1.length();\n int m = word2.length();\n\n int[][]dp = new int[n+1][m+1];\n\n for(int i = 0; i int:\n m = len(word1)\n n = len(word2)\n a = []\n for i in range(m+1):\n a.append([])\n for j in range(n+1):\n a[-1].append(0)\n \n for i in range(m):\n for j in range(n):\n if word1[i]==word2[j]:\n a[i+1][j+1] = 1 + a[i][j]\n else:\n a[i+1][j+1] = max( a[i][j+1], a[i+1][j])\n\t\t\t\t\t\n return m + n - ( 2 * a [-1][-1] )", + "title": "583. Delete Operation for Two Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]Output:[1,3,4,1,2,6]Explanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]Output:[1,2,4]Explanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]Output:[2]Explanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 31.33%) | Memory: 218.3 MB (Top 51.88%)\nclass Solution {\n public ListNode deleteMiddle(ListNode head) {\n // Base Condition\n if(head == null || head.next == null) return null;\n // Pointers Created\n ListNode fast = head;\n ListNode slow = head;\n ListNode prev = head;\n\n while(fast != null && fast.next != null){\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n }\n prev.next = slow.next;\n return head;\n }\n}", + "title": "2095. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]Output:[1,3,4,1,2,6]Explanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]Output:[1,2,4]Explanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]Output:[2]Explanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2948 ms (Top 45.50%) | Memory: 60.7 MB (Top 40.45%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head: return head\n if head and not head.next: return None\n\n prev = ListNode(0, head)\n slow = fast = head\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n\n prev.next = slow.next\n return head", + "title": "2095. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes , where boxes[i] = [ports ​​i ​, weight i ] , and three integers portsCount , maxBoxes , and maxWeight . The boxes need to be delivered in the order they are given . The ship will follow these steps: The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "ports ​​i is the port where you need to deliver the i th box and weights i is the weight of the i th box.", + "portsCount is the number of ports.", + "maxBoxes and maxWeight are the respective box and weight limits of the ship." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3Output:4Explanation:The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).", + "image": null + }, + { + "text": "Example 2: Input:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6Output:6Explanation:The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7Output:6Explanation:The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {\n int[] diffCity = new int[boxes.length+1];\n int[] weights = new int[boxes.length+1];\n \n for (int i = 0; i < boxes.length; i++) {\n diffCity[i+1] = diffCity[i] + ((i != 0 && boxes[i][0] == boxes[i-1][0]) ? 0 : 1);\n weights[i+1] = weights[i] + boxes[i][1];\n }\n int[] dp = new int[boxes.length+1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n diffCity[0] = 1;\n for (int i = 1; i <= boxes.length; i++) { // offset by 1 since our above logic reaches dp[-1]\n for (int j = i - 1; j >= 0; j--) {\n int dC= diffCity[i] - diffCity[j+1]; // computes # of different cities from i to j. (add 1 to j is necessary here)\n int w = weights[i] - weights[j]; \n int b = i - j;\n if (b <= maxBoxes && w <= maxWeight) {\n dp[i] = Math.min(dp[i], 2 + dC + dp[j]); \n }\n }\n }\n return dp[boxes.length];\n }\n}\n", + "title": "1687. Delivering Boxes from Storage to Ports", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array boxes , where boxes[i] = [ports ​​i ​, weight i ] , and three integers portsCount , maxBoxes , and maxWeight . The boxes need to be delivered in the order they are given . The ship will follow these steps: The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "ports ​​i is the port where you need to deliver the i th box and weights i is the weight of the i th box.", + "portsCount is the number of ports.", + "maxBoxes and maxWeight are the respective box and weight limits of the ship." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3Output:4Explanation:The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).", + "image": null + }, + { + "text": "Example 2: Input:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6Output:6Explanation:The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7Output:6Explanation:The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2593 ms (Top 36.11%) | Memory: 66.70 MB (Top 22.22%)\n\nfrom sortedcontainers import SortedList as MonoQueue\nclass Solution:\n def boxDelivering(self, A, __, B, W):\n n = len(A)\n def slidingWindow():\n l=0\n cW = 0\n for r in range(n):\n cW+=A[r][1]\n while cW>W or r-l+1>B:\n cW-=A[l][1]\n l+=1\n yield l,r\n Seg=MonoQueue(key=lambda t:t[1])\n addAll = 0\n olddp = 0\n for l,r in slidingWindow():\n if r!=0:\n addAll+= ( A[r][0]!=A[r-1][0] )\n Seg.add((r, olddp-addAll+2))\n while Seg[0][0]> splitPainting(int[][] segments) {\n // Create a TreeMap to store the segment start and end points as keys\n // and the accumulated color values as values\n TreeMap tm = new TreeMap<>();\n \n // Process each segment\n for (int[] seg : segments) {\n // Increment the color value at the segment start point\n tm.put((long) seg[0], tm.getOrDefault((long) seg[0], 0L) + (long) seg[2]);\n \n // Decrement the color value at the segment end point\n tm.put((long) seg[1], tm.getOrDefault((long) seg[1], 0L) - (long) seg[2]);\n }\n \n // Create a list to store the non-overlapping segments of mixed colors\n List> ans = new ArrayList<>();\n \n // Variables to keep track of accumulated color value and segment state\n long acc = 0L;\n boolean st = true;\n List currentSegment = null;\n \n // Traverse the TreeMap entries\n for (var entry : tm.entrySet()) {\n // Update the accumulated color value\n acc += entry.getValue();\n \n // If the previous segment was not starting, update its end point\n if (!st) {\n currentSegment.set(1, entry.getKey());\n st = !st;\n }\n \n // If the current segment is starting and has a positive accumulated color value,\n // create a new segment and add it to the answer list\n if (st && acc > 0) {\n currentSegment = new ArrayList<>();\n currentSegment.add(entry.getKey());\n currentSegment.add(-1L);\n currentSegment.add(acc);\n ans.add(currentSegment);\n st = !st;\n }\n }\n \n return ans;\n }\n}\n\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments , where segments[i] = [start i , end i , color i ] represents the half-closed segment [start i , end i ) with color i as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [left j , right j , mix j ] describes a half-closed segment [left j , right j ) with the mixed color sum of mix j . Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order . A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if colors 2 , 4 , and 6 are mixed, then the resulting mixed color is {2,4,6} ." + ], + "examples": [ + { + "text": "Example 1: Input:segments = [[1,4,5],[4,7,7],[1,7,9]]Output:[[1,4,14],[4,7,16]]Explanation:The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/1.png" + }, + { + "text": "Example 2: Input:segments = [[1,7,9],[6,8,15],[8,10,7]]Output:[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]Explanation:The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/2.png" + }, + { + "text": "Example 3: Input:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]Output:[[1,4,12],[4,7,12]]Explanation:The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "image": "https://assets.leetcode.com/uploads/2021/07/04/c1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n //class for segments \n class Seg{\n int val,end;\n int color;\n boolean isStart;\n public Seg(int val,int end,int color, boolean isStart){\n this.val = val;\n this.end = end;\n this.color = color;\n this.isStart = isStart; \n }\n public String toString(){\n return \"[\" + val+\" \"+end+\" \"+color+\" \"+isStart+\"]\";\n }\n }\n public List> splitPainting(int[][] segments) {\n List> res = new ArrayList();\n \n List list = new ArrayList();\n \n //making a list of segments\n for(int[] segment : segments){\n list.add(new Seg(segment[0],segment[1],segment[2],true));\n list.add(new Seg(segment[1],segment[1],segment[2],false)); \n }\n \n //Sorting the segments\n Collections.sort(list,(a,b)->{return a.val-b.val;});\n \n //System.out.println(list);\n \n //Iterating over list to combine the elements\n for(Seg curr: list){\n int len = res.size();\n if(curr.isStart){\n //if the segment is starting there could be three ways \n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if starting point of two things is same\n List temp = res.get(len-1);\n temp.set(1,Math.max(temp.get(1),curr.end));\n temp.set(2,(long)(temp.get(2)+curr.color));\n }else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a start in between create a new segment of different color \n List prev = res.get(len-1);\n prev.set(1,(long)curr.val);\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)(prev.get(2)+curr.color));\n res.add(temp);\n }else{\n //Add a new value if nothing is present in result\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)curr.color);\n res.add(temp);\n }\n }else{\n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if ending point of 2 segments is same\n Long prevColor = res.get(len-1).get(2);\n res.get(len-1).set(2,(long)(prevColor-curr.color));\n }\n else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a ending in between create a new segment of different color \n Long prevColor = res.get(len-1).get(2);\n Long prevEnd = res.get(len-1).get(1);\n res.get(len-1).set(1,(long)curr.val);\n \n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)prevEnd); temp.add((long)(prevColor-curr.color));\n res.add(temp);\n }\n }\n //System.out.println(res+\" \"+curr);\n \n }\n //System.out.println(res);\n return res; \n \n }\n}\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments , where segments[i] = [start i , end i , color i ] represents the half-closed segment [start i , end i ) with color i as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [left j , right j , mix j ] describes a half-closed segment [left j , right j ) with the mixed color sum of mix j . Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order . A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if colors 2 , 4 , and 6 are mixed, then the resulting mixed color is {2,4,6} ." + ], + "examples": [ + { + "text": "Example 1: Input:segments = [[1,4,5],[4,7,7],[1,7,9]]Output:[[1,4,14],[4,7,16]]Explanation:The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/1.png" + }, + { + "text": "Example 2: Input:segments = [[1,7,9],[6,8,15],[8,10,7]]Output:[[1,6,9],[6,7,24],[7,8,15],[8,10,7]]Explanation:The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.", + "image": "https://assets.leetcode.com/uploads/2021/06/18/2.png" + }, + { + "text": "Example 3: Input:segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]Output:[[1,4,12],[4,7,12]]Explanation:The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.", + "image": "https://assets.leetcode.com/uploads/2021/07/04/c1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n mix, res, last_i = DefaultDict(int), [], 0\n for start, end, color in segments:\n mix[start] += color\n mix[end] -= color\n for i in sorted(mix.keys()):\n if last_i in mix and mix[last_i]:\n res.append([last_i, i, mix[last_i]])\n mix[i] += mix[last_i]\n last_i = i\n return res\n", + "title": "1943. Describe the Painting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a food rating system that can do the following: Implement the FoodRatings class: Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order. Example 1:", + "description_images": [], + "constraints": [ + "Modify the rating of a food item listed in the system.", + "Return the highest-rated food item for a type of cuisine in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]Output[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]ExplanationFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // Both \"sushi\" and \"ramen\" have a rating of 16.\n // However, \"ramen\" is lexicographically smaller than \"sushi\".", + "image": null + } + ], + "follow_up": null, + "solution": "class FoodRatings {\n HashMap> cuiToFood = new HashMap();\n HashMap foodToRat = new HashMap();\n HashMap foodToCui = new HashMap();\n public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {\n for(int i = 0; i < foods.length; i++){\n TreeSet foodOfThisCuisine = cuiToFood.getOrDefault(cuisines[i], new TreeSet ((a,b)->\n foodToRat.get(a).equals(foodToRat.get(b)) ? a.compareTo(b) : foodToRat.get(b)-foodToRat.get(a)));\n\t\t\t\n\t\t\t// Both comparators are equal\n\t\t\t/* new Comparator(){\n @Override\n public int compare(String a, String b){\n int aRat = foodToRat.get(a);\n int bRat = foodToRat.get(b);\n \n if(aRat != bRat) return bRat - aRat; // largest rating first\n for(int i = 0; i < Math.min(a.length(), b.length()); i++){\n if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i);\n }\n return a.length() - b.length();\n }\n })\n\t\t\t*/\n \n foodToRat.put(foods[i], ratings[i]);\n foodOfThisCuisine.add(foods[i]);\n foodToCui.put(foods[i], cuisines[i]); \n \n cuiToFood.put(cuisines[i], foodOfThisCuisine);\n }\n }\n \n // CompareTo() is used to compare whether 2 strings are equal in hashSet! So remove, change value of key in HashMap, then insert again\n public void changeRating(String food, int newRating) {\n String cui = foodToCui.get(food);\n TreeSet foodOfThisCui = cuiToFood.get(cui);\n foodOfThisCui.remove(food);\n foodToRat.put(food, newRating);\n \n foodOfThisCui.add(food);\n cuiToFood.put(cui, foodOfThisCui);\n }\n \n public String highestRated(String cuisine) {\n return cuiToFood.get(cuisine).first();\n }\n}\n", + "title": "2353. Design a Food Rating System", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a food rating system that can do the following: Implement the FoodRatings class: Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order. Example 1:", + "description_images": [], + "constraints": [ + "Modify the rating of a food item listed in the system.", + "Return the highest-rated food item for a type of cuisine in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]Output[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]ExplanationFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // Both \"sushi\" and \"ramen\" have a rating of 16.\n // However, \"ramen\" is lexicographically smaller than \"sushi\".", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heappop, heappush\n\nclass RatedFood:\n def __init__(self, rating, food):\n self.rating = rating\n self.food = food\n \n def __lt__(self, other):\n if other.rating == self.rating:\n return self.food < other.food\n return self.rating < other.rating\n\nclass FoodRatings:\n def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n self.cuis_to_score_heap = defaultdict(list)\n self.food_to_latest_ratings = defaultdict(int)\n self.food_to_cuis = defaultdict(str)\n \n for food, cuis, rating in zip(foods, cuisines, ratings):\n self.food_to_cuis[food] = cuis\n self.food_to_latest_ratings[food] = rating\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food))\n \n \n\n def changeRating(self, food: str, newRating: int) -> None:\n self.food_to_latest_ratings[food] = newRating\n cuis = self.food_to_cuis[food]\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food))\n \n\n def highestRated(self, cuisine: str) -> str:\n while True:\n ratedFood = heappop(self.cuis_to_score_heap[cuisine])\n if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating):\n\t\t\t\n\t\t\t\t# because the food item is still valid, we put it back into the heap\n heappush(self.cuis_to_score_heap[cuisine], ratedFood)\n\t\t\t\t\n return ratedFood.food\n", + "title": "2353. Design a Food Rating System", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a number container system that can do the following: Implement the NumberContainers class: Example 1:", + "description_images": [], + "constraints": [ + "Insert or Replace a number at the given index in the system.", + "Return the smallest index for the given number in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]Output[null, -1, null, null, null, null, 1, null, 2]ExplanationNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class NumberContainers {\n \n Map> map;\n Map m;\n public NumberContainers() {\n map=new HashMap<>();\n m=new HashMap<>();\n \n }\n public void change(int index, int number) {\n m.put(index,number);\n if(!map.containsKey(number)) map.put(number,new TreeSet<>());\n map.get(number).add(index);\n }\n \n public int find(int number) {\n if(!map.containsKey(number)) return -1;\n for(Integer a:map.get(number)){\n if(m.get(a)==number) return a;\n }\n return -1;\n }\n}\n", + "title": "2349. Design a Number Container System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a number container system that can do the following: Implement the NumberContainers class: Example 1:", + "description_images": [], + "constraints": [ + "Insert or Replace a number at the given index in the system.", + "Return the smallest index for the given number in the system." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]Output[null, -1, null, null, null, null, 1, null, 2]ExplanationNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class NumberContainers:\n def __init__(self):\n self.numbersByIndex = {}\n self.numberIndexes = defaultdict(set)\n self.numberIndexesHeap = defaultdict(list)\n\n def change(self, index: int, number: int) -> None:\n if index in self.numbersByIndex:\n if number != self.numbersByIndex[index]:\n self.numberIndexes[self.numbersByIndex[index]].remove(index)\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n else:\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n\n def find(self, number: int) -> int:\n while self.numberIndexesHeap[number] and self.numberIndexesHeap[number][0] not in self.numberIndexes[number]:\n heappop(self.numberIndexesHeap[number]) # make sure the smallest index in heap is still an index for number\n return self.numberIndexesHeap[number][0] if self.numberIndexesHeap[number] else -1\n\n", + "title": "2349. Design a Number Container System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a stack which supports the following operations. Implement the CustomStack class: Example 1:", + "description_images": [], + "constraints": [ + "CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize .", + "void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize .", + "int pop() Pops and returns the top of stack or -1 if the stack is empty.", + "void inc(int k, int val) Increments the bottom k elements of the stack by val . If there are less than k elements in the stack, just increment all the elements in the stack." + ], + "examples": [ + { + "text": "Example 1: Input[\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]Output[null,null,null,2,null,null,null,null,null,103,202,201,-1]ExplanationCustomStack customStack = new CustomStack(3); // Stack is Empty []\ncustomStack.push(1); // stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.push(3); // stack becomes [1, 2, 3]\ncustomStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100); // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100); // stack becomes [201, 202, 103]\ncustomStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]\ncustomStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []\ncustomStack.pop(); // return -1 --> Stack is empty return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 70.94%) | Memory: 50.6 MB (Top 37.77%)\n\nclass CustomStack {\n\n int[] stack;\n int top;\n\n public CustomStack(int maxSize) {\n\n //intialise the stack and the top\n stack= new int[maxSize];\n top=-1;\n }\n\n public void push(int x) {\n\n // if the stack is full just skip\n if( top==stack.length-1) return;\n\n //add to the stack\n top++;\n stack[top]=x;\n }\n\n public int pop() {\n\n //if stack is empty return -1\n if( top==-1) return -1;\n\n //remove/pop the top element\n top--;\n return stack[top+1];\n\n }\n\n public void increment(int k, int val) {\n\n //got to increment the min of the elements present in the stack and k\n int n= Math.min(top+1,k);\n\n for( int i=0; i Return top of the stack 2, stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.push(3); // stack becomes [1, 2, 3]\ncustomStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100); // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100); // stack becomes [201, 202, 103]\ncustomStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]\ncustomStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []\ncustomStack.pop(); // return -1 --> Stack is empty return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass CustomStack:\n\n\t\tdef __init__(self, maxSize: int):\n\t\t\tself.size = maxSize\n\t\t\tself.stack = []\n\n\t\tdef push(self, x: int) -> None:\n\t\t\tif self.size > len(self.stack):\n\t\t\t\tself.stack.append(x)\n\n\t\tdef pop(self) -> int:\n\t\t\tif self.stack:\n\t\t\t\treturn self.stack.pop()\n\t\t\treturn -1\n\n\t\tdef increment(self, k: int, val: int) -> None:\n\t\t\tlen_stack = len(self.stack)\n\n\t\t\tif len_stack < k:\n\t\t\t\tself.stack[:] = [i + val for i in self.stack]\n\t\t\t\treturn\n\n\t\t\tfor i in range(k):\n\t\t\t\tself.stack[i] += val\n", + "title": "1381. Design a Stack With Increment Operation", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a text editor with a cursor that can do the following: When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds. Implement the TextEditor class: Example 1:", + "description_images": [], + "constraints": [ + "Add text to where the cursor is.", + "Delete text from where the cursor is (simulating the backspace key).", + "Move the cursor either left or right." + ], + "examples": [ + { + "text": "Example 1: Input[\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n[[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]Output[null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]ExplanationTextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\ntextEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\ntextEditor.deleteText(4); // return 4\n // The current text is \"leet|\". \n // 4 characters were deleted.\ntextEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \ntextEditor.cursorRight(3); // return \"etpractice\"\n // The current text is \"leetpractice|\". \n // The cursor cannot be moved beyond the actual text and thus did not move.\n // \"etpractice\" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return \"leet\"\n // The current text is \"leet|practice\".\n // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n // The current text is \"|practice\".\n // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return \"\"\n // The current text is \"|practice\".\n // The cursor cannot be moved beyond the actual text and thus did not move. \n // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return \"practi\"\n // The current text is \"practi|ce\".\n // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 380 ms (Top 41.73%) | Memory: 138.9 MB (Top 59.95%)\nclass TextEditor {\n StringBuilder res;\n int pos=0;\n\n public TextEditor() {\n res = new StringBuilder();\n }\n\n public void addText(String text) {\n res.insert(pos,text);\n pos += text.length();\n }\n\n public int deleteText(int k) {\n int tmp = pos;\n pos -= k;\n if(pos<0) pos=0;\n res.delete(pos,tmp);\n return tmp-pos;\n }\n\n public String cursorLeft(int k) {\n pos-=k;\n if(pos<0) pos = 0;\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n\n public String cursorRight(int k) {\n pos+=k;\n if(pos>res.length()) pos = res.length();\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n}\n", + "title": "2296. Design a Text Editor", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a text editor with a cursor that can do the following: When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds. Implement the TextEditor class: Example 1:", + "description_images": [], + "constraints": [ + "Add text to where the cursor is.", + "Delete text from where the cursor is (simulating the backspace key).", + "Move the cursor either left or right." + ], + "examples": [ + { + "text": "Example 1: Input[\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n[[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]Output[null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]ExplanationTextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\ntextEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\ntextEditor.deleteText(4); // return 4\n // The current text is \"leet|\". \n // 4 characters were deleted.\ntextEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \ntextEditor.cursorRight(3); // return \"etpractice\"\n // The current text is \"leetpractice|\". \n // The cursor cannot be moved beyond the actual text and thus did not move.\n // \"etpractice\" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return \"leet\"\n // The current text is \"leet|practice\".\n // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n // The current text is \"|practice\".\n // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return \"\"\n // The current text is \"|practice\".\n // The cursor cannot be moved beyond the actual text and thus did not move. \n // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return \"practi\"\n // The current text is \"practi|ce\".\n // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 1865 ms (Top 50.36%) | Memory: 27.8 MB (Top 82.98%)\nclass TextEditor:\n\n def __init__(self):\n self.s = ''\n self.cursor = 0\n\n def addText(self, text: str) -> None:\n self.s = self.s[:self.cursor] + text + self.s[self.cursor:]\n self.cursor += len(text)\n\n def deleteText(self, k: int) -> int:\n new_cursor = max(0, self.cursor - k)\n noOfChars = k if self.cursor - k >= 0 else self.cursor\n self.s = self.s[:new_cursor] + self.s[self.cursor:]\n self.cursor = new_cursor\n return noOfChars\n\n def cursorLeft(self, k: int) -> str:\n self.cursor = max(0, self.cursor - k)\n start = max(0, self.cursor-10)\n return self.s[start:self.cursor]\n\n def cursorRight(self, k: int) -> str:\n self.cursor = min(len(self.s), self.cursor + k)\n start = max(0, self.cursor - 10)\n return self.s[start:self.cursor]", + "title": "2296. Design a Text Editor", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class WordDictionary {\n private class Node{\n boolean last;\n Node[] sub;\n Node(){\n last = false;\n sub = new Node[26];\n }\n }\n Node root;\n public WordDictionary() {\n root = new Node();\n \n }\n \n public void addWord(String word) {\n Node temp = root;\n for(char c : word.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n temp.sub[index] = new Node();\n temp = temp.sub[index];\n }\n temp.last = true;\n }\n \n public boolean search(String word) {\n Node temp = root;\n return dfs(temp, word, 0);\n }\n private boolean dfs(Node node, String word, int i){\n if(i == word.length())\n return node.last; \n \n int index = word.charAt(i)-'a';\n if(word.charAt(i) == '.'){\n for(int j = 0; j < 26; j++){\n if(node.sub[j] != null)\n if(dfs(node.sub[j], word, i+1))\n return true;\n }\n return false;\n }\n else if(node.sub[index] == null)\n return false;\n return dfs(node.sub[index], word, i+1);\n }\n}\n", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode:\n \n def __init__(self, val):\n self.val = val\n self.children = {}\n self.isEnd = False\n\n\nclass WordDictionary:\n\n def __init__(self):\n self.root = TrieNode(\"*\")\n \n def addWord(self, word: str) -> None:\n \n curr = self.root\n \n for c in word:\n \n if c not in curr.children:\n curr.children[c] = TrieNode(c)\n \n curr = curr.children[c]\n \n curr.isEnd = True\n \n def search(self, word: str) -> bool:\n \n def dfs(root, word):\n curr = root\n\n for i in range(len(word)):\n\n if word[i] == \".\":\n for l in curr.children.values():\n if dfs(l, word[i+1:]) == True:\n return True\n \n return False\n\n if word[i] not in curr.children:\n return False\n\n curr = curr.children[word[i]]\n\n return curr.isEnd\n \n return dfs(self.root, word)\n", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is an ATM machine that stores banknotes of 5 denominations: 20 , 50 , 100 , 200 , and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. Implement the ATM class: Example 1:", + "description_images": [], + "constraints": [ + "For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.", + "However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100 . Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote." + ], + "examples": [ + { + "text": "Example 1: Input[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]Output[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]ExplanationATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.", + "image": null + } + ], + "follow_up": null, + "solution": "class ATM {\n\tlong[] notes = new long[5]; // Note: use long[] instead of int[] to avoid getting error in large testcases\n\tint[] denoms;\n\tpublic ATM() {\n\t\tdenoms = new int[]{ 20,50,100,200,500 }; // create an array to represent money value.\n\t}\n\n\tpublic void deposit(int[] banknotesCount) {\n\t\tfor(int i = 0; i < banknotesCount.length; i++){\n\t\t\tnotes[i] += banknotesCount[i]; // add new deposit money to existing\n\t\t}\n\t}\n\n\tpublic int[] withdraw(int amount) { \n\t\tint[] result = new int[5]; // create result array to store quantity of each notes we will be using to withdraw \"amount\"\n\t\tfor(int i = 4; i >= 0; i--){\n\t\t\tif(amount >= denoms[i] ){ \n\t\t\t\tint quantity = (int) Math.min(notes[i], amount / denoms[i]); // pick the minimum quanity. because if say, amount/denoms[i] gives 3 but you only have 1 note. so you have to use 1 only instead of 3 \n\t\t\t\tamount -= denoms[i] * quantity; // amount left = 100\n\t\t\t\tresult[i] = quantity;\n\t\t\t}\n\t\t}\n\t\tif(amount != 0){ return new int[]{-1}; }\n\t\tfor(int i = 0; i < 5; i++){ notes[i] -= result[i]; } // deduct the quantity we have used.\n\t\treturn result;\n\t}\n}\n", + "title": "2241. Design an ATM Machine", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an ATM machine that stores banknotes of 5 denominations: 20 , 50 , 100 , 200 , and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. Implement the ATM class: Example 1:", + "description_images": [], + "constraints": [ + "For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.", + "However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100 . Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote." + ], + "examples": [ + { + "text": "Example 1: Input[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]Output[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]ExplanationATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 906 ms (Top 67.28%) | Memory: 18 MB (Top 21.66%)\nclass ATM:\n def __init__(self):\n self.cash = [0] * 5\n self.values = [20, 50, 100, 200, 500]\n\n def deposit(self, banknotes_count: List[int]) -> None:\n for i, n in enumerate(banknotes_count):\n self.cash[i] += n\n\n def withdraw(self, amount: int) -> List[int]:\n res = []\n for val, n in zip(self.values[::-1], self.cash[::-1]):\n need = min(n, amount // val)\n res = [need] + res\n amount -= (need * val)\n if amount == 0:\n self.deposit([-x for x in res])\n return res\n else:\n return [-1]\n", + "title": "2241. Design an ATM Machine", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id . Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/11/10/q1.gif" + ], + "constraints": [ + "OrderedStream(int n) Constructs the stream to take n values.", + "String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order." + ], + "examples": [ + { + "text": "Example: Input[\"OrderedStream\", \"insert\", \"insert\", \"insert\", \"insert\", \"insert\"]\n[[5], [3, \"ccccc\"], [1, \"aaaaa\"], [2, \"bbbbb\"], [5, \"eeeee\"], [4, \"ddddd\"]]Output[null, [], [\"aaaaa\"], [\"bbbbb\", \"ccccc\"], [], [\"ddddd\", \"eeeee\"]]Explanation// Note that the values ordered by ID is [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"].\nOrderedStream os = new OrderedStream(5);\nos.insert(3, \"ccccc\"); // Inserts (3, \"ccccc\"), returns [].\nos.insert(1, \"aaaaa\"); // Inserts (1, \"aaaaa\"), returns [\"aaaaa\"].\nos.insert(2, \"bbbbb\"); // Inserts (2, \"bbbbb\"), returns [\"bbbbb\", \"ccccc\"].\nos.insert(5, \"eeeee\"); // Inserts (5, \"eeeee\"), returns [].\nos.insert(4, \"ddddd\"); // Inserts (4, \"ddddd\"), returns [\"ddddd\", \"eeeee\"].\n// Concatentating all the chunks returned:\n// [] + [\"aaaaa\"] + [\"bbbbb\", \"ccccc\"] + [] + [\"ddddd\", \"eeeee\"] = [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"]\n// The resulting order is the same as the order above.", + "image": null + } + ], + "follow_up": null, + "solution": "class OrderedStream:\n\n def __init__(self, n: int):\n self.seen = {}\n self.ptr = 1\n\n def insert(self, id: int, value: str) -> List[str]:\n seen, ptr = self.seen, self.ptr\n \n seen[id] = value\n result = []\n while ptr in seen:\n result.append(seen[ptr])\n del seen[ptr]\n ptr += 1\n \n self.ptr = ptr\n return result\n\n\n# Your OrderedStream object will be instantiated and called as such:\n# obj = OrderedStream(n)\n# param_1 = obj.insert(id,value)\n", + "title": "1656. Design an Ordered Stream", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime . If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime . Implement the AuthenticationManager class: Note that if a token expires at time t , and another action happens on time t ( renew or countUnexpiredTokens ), the expiration takes place before the other actions. Example 1:", + "description_images": [], + "constraints": [ + "AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive .", + "generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.", + "renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId , the request is ignored, and nothing happens.", + "countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime." + ], + "examples": [ + { + "text": "Example 1: Input[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]Output[null, null, null, 1, null, null, null, 0]ExplanationAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager withtimeToLive= 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 therenewrequest is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so therenewrequest is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/copy-of-pc68_q2.png" + } + ], + "follow_up": null, + "solution": "class AuthenticationManager {\n private int ttl;\n private Map map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n this.map = new HashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + this.ttl);\n }\n \n public void renew(String tokenId, int currentTime) {\n Integer expirationTime = this.map.getOrDefault(tokenId, null);\n if (expirationTime == null || expirationTime <= currentTime)\n return;\n \n generate(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (Map.Entry entry: this.map.entrySet())\n if (entry.getValue() > currentTime)\n count++;\n \n return count;\n }\n}\n\n", + "title": "1797. Design Authentication Manager", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime . If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime . Implement the AuthenticationManager class: Note that if a token expires at time t , and another action happens on time t ( renew or countUnexpiredTokens ), the expiration takes place before the other actions. Example 1:", + "description_images": [], + "constraints": [ + "AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive .", + "generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.", + "renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId , the request is ignored, and nothing happens.", + "countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime." + ], + "examples": [ + { + "text": "Example 1: Input[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]Output[null, null, null, 1, null, null, null, 0]ExplanationAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager withtimeToLive= 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 therenewrequest is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so therenewrequest is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/copy-of-pc68_q2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 732 ms (Top 5.07%) | Memory: 15.5 MB (Top 65.88%)\nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive and create dictionary\n\n def generate(self, tokenId, currentTime):\n self.token[tokenId] = currentTime # store tokenId with currentTime\n\n def renew(self, tokenId, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n self.token[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n c = 0\n for i in self.token:\n if self.token[i]>limit: # count unexpired tokens\n c+=1\n return c", + "title": "1797. Design Authentication Manager", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A Bitset is a data structure that compactly stores bits. Implement the Bitset class: Example 1:", + "description_images": [], + "constraints": [ + "Bitset(int size) Initializes the Bitset with size bits, all of which are 0 .", + "void fix(int idx) Updates the value of the bit at the index idx to 1 . If the value was already 1 , no change occurs.", + "void unfix(int idx) Updates the value of the bit at the index idx to 0 . If the value was already 0 , no change occurs.", + "void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.", + "boolean all() Checks if the value of each bit in the Bitset is 1 . Returns true if it satisfies the condition, false otherwise.", + "boolean one() Checks if there is at least one bit in the Bitset with value 1 . Returns true if it satisfies the condition, false otherwise.", + "int count() Returns the total number of bits in the Bitset which have value 1 .", + "String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the i th index should coincide with the value at the i th bit of the Bitset." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bitset\", \"fix\", \"fix\", \"flip\", \"all\", \"unfix\", \"flip\", \"one\", \"unfix\", \"count\", \"toString\"]\n[[5], [3], [1], [], [], [0], [], [], [0], [], []]Output[null, null, null, null, false, null, null, true, null, 2, \"01010\"]ExplanationBitset bs = new Bitset(5); // bitset = \"00000\".\nbs.fix(3); // the value at idx = 3 is updated to 1, so bitset = \"00010\".\nbs.fix(1); // the value at idx = 1 is updated to 1, so bitset = \"01010\". \nbs.flip(); // the value of each bit is flipped, so bitset = \"10101\". \nbs.all(); // return False, as not all values of the bitset are 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"00101\".\nbs.flip(); // the value of each bit is flipped, so bitset = \"11010\". \nbs.one(); // return True, as there is at least 1 index with value 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"01010\".\nbs.count(); // return 2, as there are 2 bits with value 1.\nbs.toString(); // return \"01010\", which is the composition of bitset.", + "image": null + } + ], + "follow_up": null, + "solution": "class Bitset {\n int size;\n Set one = new HashSet<>();\n Set zero = new HashSet<>();\n public Bitset(int size) {\n this.size = size;\n for(int i=0;i s = one;\n one = zero;\n zero = s;\n }\n \n public boolean all() {\n return one.size() == size;\n }\n \n public boolean one() {\n return one.size()>=1;\n }\n \n public int count() {\n return one.size();\n }\n \n public String toString() {\n StringBuilder sb= new StringBuilder();\n for(int i=0;i 0\n\n def count(self):\n return self.cnt\n\n def toString(self):\n a = bin(self.a)[2:]\n return a[::-1] + '0' * (self.size - len(a))", + "title": "2166. Design Bitset", + "topic": "Hash Table" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example: Input:[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"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\");\nbrowserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 122 ms (Top 39.97%) | Memory: 81.7 MB (Top 80.48%)\nclass BrowserHistory {\n int current;\n ArrayList history;\n public BrowserHistory(String homepage) {\n this.history = new ArrayList<>();\n history.add(homepage);\n this.current = 0;\n }\n\n public void visit(String url) {\n while (history.size()-1 > current) {//delete forward history\n history.remove(history.size()-1);//which means delete everything beyond our current website\n }\n history.add(url);\n ++current;\n }\n\n public String back(int steps) {\n if (steps>current) current = 0;//if we can't get enough back, we return first thing in our history\n else current -= steps;//if there will be no arrayindexoutofrange error, go back\n return history.get(current);//return current webpage\n }\n\n public String forward(int steps) {\n //if we are going to move more than our arraylist, then we will return the last element\n if (steps+current>=history.size()) current = history.size() - 1;\n else current += steps;//if there will be no arrayindexoutofrange error, go forward!\n return history.get(current);//return the current webpage\n }\n}\n\n/**\n * Your BrowserHistory object will be instantiated and called as such:\n * BrowserHistory obj = new BrowserHistory(homepage);\n * obj.visit(url);\n * String param_2 = obj.back(steps);\n * String param_3 = obj.forward(steps);\n */", + "title": "1472. Design Browser History", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example: Input:[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"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\");\nbrowserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 702 ms (Top 9.12%) | Memory: 16.8 MB (Top 36.03%)\nclass Node:\n def __init__(self, val):\n self.val = val\n self.prev = None\n self.next = None\n\nclass BrowserHistory:\n def __init__(self, web):\n self.Node = Node(web)\n self.ptr = self.Node\n\n def visit(self, web):\n self.newWeb = Node(web)\n self.newWeb.prev = self.ptr\n self.ptr.next = self.newWeb\n self.ptr = self.ptr.next\n\n def back(self, steps):\n i = 0\n while i < steps:\n if self.ptr.prev:\n self.ptr = self.ptr.prev\n else:\n break\n i += 1\n return self.ptr.val\n\n def forward(self, steps):\n i = 0\n while i < steps:\n if self.ptr.next:\n self.ptr = self.ptr.next\n else:\n break\n i += 1\n return self.ptr.val", + "title": "1472. Design Browser History", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: Example 1:", + "description_images": [], + "constraints": [ + "MyCircularDeque(int k) Initializes the deque with a maximum size of k .", + "boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.", + "int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.", + "boolean isEmpty() Returns true if the deque is empty, or false otherwise.", + "boolean isFull() Returns true if the deque is full, or false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 2, true, true, true, 4]ExplanationMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCircularDeque {\npublic:\n \n deque dq;\n \n int max_size;\n \n MyCircularDeque(int k) {\n \n max_size = k; \n }\n \n bool insertFront(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_front(value);\n \n return true;\n }\n \n return false;\n }\n \n bool insertLast(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_back(value);\n \n return true;\n }\n \n return false;\n }\n \n bool deleteFront() {\n \n if(dq.size() > 0)\n {\n dq.pop_front();\n \n return true;\n }\n \n return false;\n }\n \n bool deleteLast() {\n \n if(dq.size() > 0)\n {\n dq.pop_back();\n \n return true;\n }\n \n return false; \n }\n \n int getFront() {\n \n if(dq.size() > 0)\n return dq.front();\n \n return -1;\n }\n \n int getRear() {\n \n if(dq.size() > 0)\n return dq.back();\n \n return -1;\n }\n \n bool isEmpty() {\n \n return dq.empty();\n }\n \n bool isFull() {\n \n return dq.size() == max_size;\n }\n};\n", + "title": "641. Design Circular Deque", + "topic": "Queue" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design your implementation of the circular double-ended queue (deque). Implement the MyCircularDeque class: Example 1:", + "description_images": [], + "constraints": [ + "MyCircularDeque(int k) Initializes the deque with a maximum size of k .", + "boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.", + "boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.", + "int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.", + "int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.", + "boolean isEmpty() Returns true if the deque is empty, or false otherwise.", + "boolean isFull() Returns true if the deque is full, or false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 2, true, true, true, 4]ExplanationMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 91.39%) | Memory: 18.00 MB (Top 39.07%)\n\nclass MyCircularDeque:\n def __init__(self, k: int):\n self.queue = [None] * k\n self.max_size = k\n self.head = 0\n self.tail = 0\n self.size = 0\n\n def insertFront(self, value: int) -> bool:\n if self.isFull():\n return False\n self.head = (self.head - 1) % self.max_size\n self.queue[self.head] = value\n self.size += 1\n return True\n\n def insertLast(self, value: int) -> bool:\n if self.isFull():\n return False\n self.queue[self.tail] = value\n self.tail = (self.tail + 1) % self.max_size\n self.size += 1\n return True\n\n def deleteFront(self) -> bool:\n if self.isEmpty():\n return False\n self.head = (self.head + 1) % self.max_size\n self.size -= 1\n return True\n\n def deleteLast(self) -> bool:\n if self.isEmpty():\n return False\n self.tail = (self.tail - 1) % self.max_size\n self.size -= 1\n return True\n\n def getFront(self) -> int:\n if self.isEmpty():\n return -1\n return self.queue[self.head]\n\n def getRear(self) -> int:\n if self.isEmpty():\n return -1\n return self.queue[(self.tail - 1) % self.max_size]\n\n def isEmpty(self) -> bool:\n return self.size == 0\n\n def isFull(self) -> bool:\n return self.size == self.max_size\n\n", + "title": "641. Design Circular Deque", + "topic": "Queue" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implementation the MyCircularQueue class: You must solve the problem without using the built-in queue data structure in your programming language. Example 1:", + "description_images": [], + "constraints": [ + "MyCircularQueue(k) Initializes the object with the size of the queue to be k .", + "int Front() Gets the front item from the queue. If the queue is empty, return -1 .", + "int Rear() Gets the last item from the queue. If the queue is empty, return -1 .", + "boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.", + "boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.", + "boolean isEmpty() Checks whether the circular queue is empty or not.", + "boolean isFull() Checks whether the circular queue is full or not." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 3, true, true, true, 4]ExplanationMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 38.7%) | Memory: 44.24 MB (Top 53.3%)\n\nclass MyCircularQueue {\n\n private int front;\n private int rear;\n private int[] arr;\n private int cap;\n \n private int next(int i){ // to get next idx after i in circular queue\n return (i+1)%cap;\n }\n private int prev(int i){ // to get prev idx before i in circular queue\n return (i+cap-1)%cap;\n }\n \n\t// rest is as simple as implmenting a normal queue using array.\n public MyCircularQueue(int k) {\n arr = new int[k];\n cap=k;\n front=-1;\n rear=-1;\n }\n \n public boolean enQueue(int value) {\n if(isFull())return false;\n if(front==-1){\n front=0;\n rear=0;\n arr[rear]=value;\n return true;\n }\n rear = next(rear);\n arr[rear]=value;\n return true;\n }\n \n public boolean deQueue() {\n if(isEmpty())return false;\n if(front==rear){\n front=-1;\n rear=-1;\n return true;\n }\n front=next(front);\n return true;\n }\n \n public int Front() {\n if(front==-1)return -1;\n return arr[front];\n }\n \n public int Rear() {\n if(rear==-1)return -1;\n return arr[rear];\n }\n \n public boolean isEmpty() {\n return front==-1;\n }\n \n public boolean isFull() {\n return front!=-1 && next(rear)==front;\n }\n}", + "title": "622. Design Circular Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implementation the MyCircularQueue class: You must solve the problem without using the built-in queue data structure in your programming language. Example 1:", + "description_images": [], + "constraints": [ + "MyCircularQueue(k) Initializes the object with the size of the queue to be k .", + "int Front() Gets the front item from the queue. If the queue is empty, return -1 .", + "int Rear() Gets the last item from the queue. If the queue is empty, return -1 .", + "boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.", + "boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.", + "boolean isEmpty() Checks whether the circular queue is empty or not.", + "boolean isFull() Checks whether the circular queue is full or not." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]Output[null, true, true, true, false, 3, true, true, true, 4]ExplanationMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 66 ms (Top 68.44%) | Memory: 18.10 MB (Top 5.6%)\n\nclass MyCircularQueue:\n def __init__(self, k: int):\n self.data = [0] * k\n self.maxSize = k\n self.head = 0\n self.tail = -1\n def enQueue(self, val: int) -> bool:\n if self.isFull(): return False\n self.tail = (self.tail + 1) % self.maxSize\n self.data[self.tail] = val\n return True\n def deQueue(self) -> bool:\n if self.isEmpty(): return False\n if self.head == self.tail: self.head, self.tail = 0, -1\n else: self.head = (self.head + 1) % self.maxSize\n return True\n def Front(self) -> int:\n return -1 if self.isEmpty() else self.data[self.head]\n def Rear(self) -> int:\n return -1 if self.isEmpty() else self.data[self.tail]\n def isEmpty(self) -> bool:\n return self.tail == -1\n def isFull(self) -> bool:\n return not self.isEmpty() and (self.tail + 1) % self.maxSize == self.head\n", + "title": "622. Design Circular Queue", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: Example 1:", + "description_images": [], + "constraints": [ + "FrontMiddleBack() Initializes the queue.", + "void pushFront(int val) Adds val to the front of the queue.", + "void pushMiddle(int val) Adds val to the middle of the queue.", + "void pushBack(int val) Adds val to the back of the queue.", + "int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1 .", + "int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1 .", + "int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]Output:[null, null, null, null, null, 1, 3, 4, 2, -1]Explanation:FrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1,2]\nq.pushMiddle(3); // [1,3, 2]\nq.pushMiddle(4); // [1,4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 73.3%) | Memory: 44.18 MB (Top 74.0%)\n\nclass FrontMiddleBackQueue {\n\n Deque dq1, dq2;\n public FrontMiddleBackQueue() { \n dq1 = new ArrayDeque();\n dq2 = new ArrayDeque();\n }\n \n public void pushFront(int val) {\n dq1.addFirst(val);\n } \n \n public void pushBack(int val) {\n dq2.addLast(val);\n } \n \n public void pushMiddle(int val) {\n while(dq1.size() + 1 < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size())\n dq2.addFirst(dq1.removeLast()); \n dq1.addLast(val); \n } \n \n public int popFront() {\n if(!dq1.isEmpty())\n return dq1.removeFirst();\n if(!dq2.isEmpty())\n return dq2.removeFirst();\n return -1; \n } \n \n public int popMiddle() {\n if(dq1.isEmpty() && dq2.isEmpty())\n return -1; \n while(dq1.size() < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size() + 1)\n dq2.addFirst(dq1.removeLast());\n return !dq1.isEmpty() ? dq1.removeLast() : dq2.removeFirst();\n } \n \n public int popBack() {\n if(!dq2.isEmpty())\n return dq2.removeLast();\n if(!dq1.isEmpty())\n return dq1.removeLast();\n return -1; \n } \n}", + "title": "1670. Design Front Middle Back Queue", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a queue that supports push and pop operations in the front, middle, and back. Implement the FrontMiddleBack class: Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: Example 1:", + "description_images": [], + "constraints": [ + "FrontMiddleBack() Initializes the queue.", + "void pushFront(int val) Adds val to the front of the queue.", + "void pushMiddle(int val) Adds val to the middle of the queue.", + "void pushBack(int val) Adds val to the back of the queue.", + "int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1 .", + "int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1 .", + "int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:[\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n[[], [1], [2], [3], [4], [], [], [], [], []]Output:[null, null, null, null, null, 1, 3, 4, 2, -1]Explanation:FrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1,2]\nq.pushMiddle(3); // [1,3, 2]\nq.pushMiddle(4); // [1,4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 176 ms (Top 11.57%) | Memory: 14.6 MB (Top 46.27%)\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.front = deque()\n self.back = deque()\n\n def _correct_size(self):\n while len(self.back) > len(self.front):\n self.front.append(self.back.popleft())\n\n while len(self.front) > len(self.back) + 1:\n self.back.appendleft(self.front.pop())\n\n def pushFront(self, val: int) -> None:\n self.front.appendleft(val)\n self._correct_size()\n\n def pushMiddle(self, val: int) -> None:\n if len(self.front) > len(self.back):\n self.back.appendleft(self.front.pop())\n self.front.append(val)\n self._correct_size()\n\n def pushBack(self, val: int) -> None:\n self.back.append(val)\n self._correct_size()\n\n def popFront(self) -> int:\n front = self.front if self.front else self.back\n ret = front.popleft() if front else -1\n self._correct_size()\n return ret\n\n def popMiddle(self) -> int:\n ret = self.front.pop() if self.front else -1\n self._correct_size()\n return ret\n\n def popBack(self) -> int:\n back = self.back if self.back else self.front\n ret = back.pop() if back else -1\n self._correct_size()\n return ret", + "title": "1670. Design Front Middle Back Queue", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: Example 1:", + "description_images": [], + "constraints": [ + "MyHashMap() initializes the object with an empty map.", + "void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value .", + "int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key .", + "void remove(key) removes the key and its corresponding value if the map contains the mapping for the key ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]Output[null, null, null, 1, -1, null, 1, null, -1]ExplanationMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class MyHashMap {\n\n\t/** Initialize your data structure here. */\n\tLinkedList[] map;\n\tpublic static int SIZE = 769;\n\tpublic MyHashMap() {\n\t\tmap = new LinkedList[SIZE];\n\t}\n\n\t/** value will always be non-negative. */\n\tpublic void put(int key, int value) {\n\t\tint bucket = key % SIZE;\n\t\tif(map[bucket] == null) {\n\t\t\tmap[bucket] = new LinkedList();\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key){\n\t\t\t\t\tentry.val = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tpublic int get(int key) {\n\t\tint bucket = key % SIZE;\n\t\tLinkedList entries = map[bucket];\n\t\tif(entries == null) return -1;\n\t\tfor(Entry entry : entries) {\n\t\t\tif(entry.key == key) return entry.val;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tpublic void remove(int key) {\n\t\tint bucket = key % SIZE;\n\t\tEntry toRemove = null;\n\t\tif(map[bucket] == null) return;\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key) {\n\t\t\t\t\ttoRemove = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(toRemove == null) return;\n\t\t\tmap[bucket].remove(toRemove);\n\t\t}\n\t}\n}\n\nclass Entry {\n\tpublic int key;\n\tpublic int val;\n\n\tpublic Entry(int key, int val){\n\t\tthis.key = key;\n\t\tthis.val = val;\n\t}\n}", + "title": "706. Design HashMap", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: Example 1:", + "description_images": [], + "constraints": [ + "MyHashMap() initializes the object with an empty map.", + "void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value .", + "int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key .", + "void remove(key) removes the key and its corresponding value if the map contains the mapping for the key ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]Output[null, null, null, 1, -1, null, 1, null, -1]ExplanationMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 285 ms (Top 33.03%) | Memory: 43.10 MB (Top 5.35%)\n\nclass MyHashMap:\n def __init__(self):\n self.data = [None] * 1000001\n def put(self, key: int, val: int) -> None:\n self.data[key] = val\n def get(self, key: int) -> int:\n val = self.data[key]\n return val if val != None else -1\n def remove(self, key: int) -> None:\n self.data[key] = None\n", + "title": "706. Design HashMap", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: Example 1:", + "description_images": [], + "constraints": [ + "void add(key) Inserts the value key into the HashSet.", + "bool contains(key) Returns whether the value key exists in the HashSet or not.", + "void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]Output[null, null, null, true, false, null, true, null, false]ExplanationMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)", + "image": null + } + ], + "follow_up": null, + "solution": "class MyHashSet {\n\tArrayList> list;\n\tint size = 100;\n\n\tpublic MyHashSet() {\n\t\tlist = new ArrayList<>(size);\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tlist.add(new LinkedList());\n\t\t}\n\t}\n\n\tpublic int hash(int key) {\n\t\treturn key % list.size();\n\t}\n\n\tpublic int search(int key) {\n\t\tint i = hash(key);\n\n\t\tLinkedList temp = list.get(i);\n\t\tint ans = -1;\n\n\t\tfor (int j = 0; j < temp.size(); j++) {\n\t\t\tif (key == temp.get(j)) {\n\t\t\t\treturn j;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\n\tpublic void add(int key) {\n\t\tif (search(key) == -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).add(key);\n\t\t}\n\t}\n\n\tpublic void remove(int key) {\n\t\tif (search(key) != -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).remove(Integer.valueOf(key));\n\t\t}\n\t}\n\n\tpublic boolean contains(int key) {\n\t\treturn search(key) != -1;\n\t}\n}", + "title": "705. Design HashSet", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: Example 1:", + "description_images": [], + "constraints": [ + "void add(key) Inserts the value key into the HashSet.", + "bool contains(key) Returns whether the value key exists in the HashSet or not.", + "void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]Output[null, null, null, true, false, null, true, null, false]ExplanationMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1864 ms (Top 22.23%) | Memory: 174.5 MB (Top 5.09%)\nclass MyHashSet:\n\n def __init__(self):\n self.hash_list = [0]*10000000\n\n def add(self, key: int) -> None:\n self.hash_list[key]+=1\n\n def remove(self, key: int) -> None:\n self.hash_list[key] = 0\n\n def contains(self, key: int) -> bool:\n if self.hash_list[key] > 0:\n return True\n return False", + "title": "705. Design HashSet", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next . val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed . Implement the MyLinkedList class: Example 1:", + "description_images": [], + "constraints": [ + "MyLinkedList() Initializes the MyLinkedList object.", + "int get(int index) Get the value of the index th node in the linked list. If the index is invalid, return -1 .", + "void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.", + "void addAtTail(int val) Append a node of value val as the last element of the linked list.", + "void addAtIndex(int index, int val) Add a node of value val before the index th node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted .", + "void deleteAtIndex(int index) Delete the index th node in the linked list, if the index is valid." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]Output[null, null, null, null, 2, null, 3]ExplanationMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 41.30%) | Memory: 50.4 MB (Top 74.99%)\nclass MyLinkedList {\n\n public class ListNode {\n public int val;\n public ListNode next;\n\n public ListNode() {\n\n }\n\n public ListNode(int val) {\n this.val = val;\n }\n\n public ListNode(int val, ListNode next) {\n this.val = val;\n this.next = next;\n }\n }\n\n private ListNode head;\n private ListNode tail;\n private int length;\n\n public MyLinkedList() {\n length = 0;\n }\n\n public int get(int index) {\n if (index > length - 1 || index < 0) return -1;\n int thisIndex = 0;\n ListNode temp = head;\n while (thisIndex != index) {\n temp = temp.next;\n thisIndex++;\n }\n return temp.val;\n }\n\n public void addAtHead(int val) {\n head = new ListNode(val, head);\n length++;\n if (length == 1) tail = head;\n }\n\n public void addAtTail(int val) {\n length++;\n if (length == 1) {\n ListNode onlyNode = new ListNode(val);\n head = onlyNode;\n tail = head;\n return;\n }\n tail.next = new ListNode(val);\n tail = tail.next;\n }\n\n public void addAtIndex(int index, int val) {\n if (index <= length) {\n if (index == 0) {\n addAtHead(val);\n return;\n }\n if (index == length) {\n addAtTail(val);\n return;\n }\n length++;\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n temp.next = new ListNode(val, temp.next);\n }\n }\n\n public void deleteAtIndex(int index) {\n if (index >= length || index < 0) return;\n length--;\n if (index == 0) {\n head = head.next;\n return;\n }\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n if (index == length) {\n tail = temp;\n temp.next = null;\n }\n else temp.next = temp.next.next;\n }\n}", + "title": "707. Design Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next . val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed . Implement the MyLinkedList class: Example 1:", + "description_images": [], + "constraints": [ + "MyLinkedList() Initializes the MyLinkedList object.", + "int get(int index) Get the value of the index th node in the linked list. If the index is invalid, return -1 .", + "void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.", + "void addAtTail(int val) Append a node of value val as the last element of the linked list.", + "void addAtIndex(int index, int val) Add a node of value val before the index th node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted .", + "void deleteAtIndex(int index) Delete the index th node in the linked list, if the index is valid." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]Output[null, null, null, null, 2, null, 3]ExplanationMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n def __init__(self, val: int):\n self.val = val\n self.next = None\n self.prev = None\n \nclass MyLinkedList:\n def __init__(self):\n self.head = Node(0)\n self.tail = Node(0)\n self.head.next = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n def get(self, index: int) -> int:\n if index < 0 or index >= self.size:\n return -1\n # Distance of index is closer to head\n if index + 1 < self.size - index:\n curr = self.head\n for i in range(index + 1):\n curr = curr.next\n # Distance of index is closer to tail\n else:\n curr = self.tail\n for i in range(self.size - index):\n curr = curr.prev\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.head\n nextNode = self.head.next\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtTail(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.tail.prev\n nextNode = self.tail\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtIndex(self, index: int, val: int) -> None:\n curr = Node(val)\n if index > self.size:\n return\n if index < 0:\n index = 0\n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next\n else:\n nextNode = self.tail\n for i in range(self.size - index):\n nextNode = nextNode.prev\n prevNode = nextNode.prev\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n \n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.size:\n return \n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next.next\n else:\n nextNode = self.tail\n for i in range(self.size - index - 1):\n nextNode = nextNode.prev\n prevNode = nextNode.prev.prev\n self.size -= 1\n prevNode.next = nextNode\n nextNode.prev = prevNode\n\n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)", + "title": "707. Design Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shop i , movie i , price i ] indicates that there is a copy of movie movie i at shop shop i with a rental price of price i . Each shop carries at most one copy of a movie movie i . The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie. Example 1:", + "description_images": [], + "constraints": [ + "Search : Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop i should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.", + "Rent : Rents an unrented copy of a given movie from a given shop.", + "Drop : Drops off a previously rented copy of a given movie at a given shop.", + "Report : Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shop j , movie j ] describes that the j th cheapest rented movie movie j was rented from the shop shop j . The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop j should appear first, and if there is still tie, the one with the smaller movie j should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]Output[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]ExplanationMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class MovieRentingSystem {\n \n Map> map = new HashMap<>();\n\nTreeSet rented = new TreeSet<>(new rcomp());\n\npublic MovieRentingSystem(int n, int[][] entries) {\n for(int entry[] : entries){\n Map map1 = map.getOrDefault(entry[1],new HashMap<>());\n Pair p = new Pair(entry[0],entry[1],entry[2]);\n map1.put(entry[0],p);\n map.put(entry[1],map1);\n }\n}\n\npublic List search(int movie) {\n \n PriorityQueue pq = new PriorityQueue<>(new scomp());\n \n Map map1 = map.getOrDefault(movie,new HashMap<>());\n \n for(Pair p : map1.values()){\n if(p.rent == true){continue;}\n if(pq.size() < 5){pq.add(p);}\n else{\n if(pq.peek().price > p.price){\n pq.poll();\n pq.add(p);\n }else if(pq.peek().price == p.price && pq.peek().shop > p.shop){\n pq.poll();\n pq.add(p);\n }\n }\n }\n \n List ans = new ArrayList<>();\n \n while(!pq.isEmpty()){\n \n Pair p = pq.poll();\n ans.add(0,p.shop);\n }\n \n return ans;\n \n \n}\n\npublic void rent(int shop, int movie) {\n \n Pair p = map.get(movie).get(shop);\n p.rent = true;\n rented.add(p);\n}\n\npublic void drop(int shop, int movie) {\n Pair p = map.get(movie).get(shop);\n p.rent = false;\n rented.remove(p);\n}\n\npublic List> report() {\n List> ans = new ArrayList<>();\n \n for(Pair p : rented){\n List t = new ArrayList<>();\n t.add(p.shop);t.add(p.movie);\n ans.add(t);\n if(ans.size()==5){break;}\n }\n \n return ans;\n }\n}\n\nclass scomp implements Comparator{\n\npublic int compare(Pair a , Pair b){\n if(a.price == b.price){\n return b.shop - a.shop;\n }\n return b.price - a.price;\n }\n}\n\n class rcomp implements Comparator{\n public int compare(Pair a,Pair b){\n if(a.price == b.price){\n if(a.shop == b.shop){\n return a.movie - b.movie;\n }\n return a.shop - b.shop;\n }\n return a.price - b.price;\n }\n} \n\n\nclass Pair{\n\nint shop;\nint movie;\nint price;\nboolean rent;\n\nPair(int shop,int movie,int price){\n this.shop = shop;\n this.movie = movie;\n this.price = price;\n this.rent = false;\n}\n\npublic int hashCode() {\nreturn Objects.hash(shop,movie,price);\n}\n\npublic boolean equals(Object obj)\n{\n Pair obj1 = (Pair)obj;\n if(obj1.shop == shop && obj1.movie==movie && obj1.price == price){\n return true;\n }\n return false;\n }\n}\n", + "title": "1912. Design Movie Rental System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shop i , movie i , price i ] indicates that there is a copy of movie movie i at shop shop i with a rental price of price i . Each shop carries at most one copy of a movie movie i . The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie. Example 1:", + "description_images": [], + "constraints": [ + "Search : Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop i should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.", + "Rent : Rents an unrented copy of a given movie from a given shop.", + "Drop : Drops off a previously rented copy of a given movie at a given shop.", + "Report : Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shop j , movie j ] describes that the j th cheapest rented movie movie j was rented from the shop shop j . The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shop j should appear first, and if there is still tie, the one with the smaller movie j should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]Output[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]ExplanationMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4131 ms (Top 50.00%) | Memory: 98.7 MB (Top 51.92%)\nimport sortedcontainers as sc\nclass MovieRentingSystem:\n def __init__(self, n: int, entries: List[List[int]]):\n self.rented = sc.SortedList() # Triples of price, shop, movie\n self.movies = {} # Dictionary mapping movie -> sorted list of (price, shop)\n self.movie_and_shop_to_price = {} # Dictionary mapping (movie, shop) -> price\n\n for shop, movie, price in entries:\n if movie not in self.movies:\n self.movies[movie] = sc.SortedList()\n self.movies[movie].add((price, shop))\n self.movie_and_shop_to_price[movie, shop] = price\n\n def search(self, movie: int) -> List[int]:\n if movie not in self.movies:\n return []\n return [x[1] for x in self.movies[movie][:5]] # Returning the shop numbers\n\n def rent(self, shop: int, movie: int) -> None:\n my_price = self.movie_and_shop_to_price[movie, shop]\n self.rented.add((my_price, shop, movie))\n self.movies[movie].remove((my_price, shop))\n\n def drop(self, shop: int, movie: int) -> None:\n my_price = self.movie_and_shop_to_price[movie, shop]\n self.rented.remove((my_price, shop, movie))\n self.movies[movie].add((my_price, shop))\n\n def report(self) -> List[List[int]]:\n return [x[1:] for x in self.rented[:5]] # Returning the (shop, movie) pairs", + "title": "1912. Design Movie Rental System", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the ParkingSystem class: Example 1:", + "description_images": [], + "constraints": [ + "ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.", + "bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1 , 2 , and 3 respectively. A car can only park in a parking space of its carType . If there is no space available, return false , else park the car in that size space and return true ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]Output[null, true, true, false, false]ExplanationParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 99.5%) | Memory: 45.00 MB (Top 40.87%)\n\nclass ParkingSystem {\n private int slots[] = new int[3];\n public ParkingSystem(int big, int medium, int small) {\n slots[0] = big;\n slots[1] = medium;\n slots[2] = small;\n }\n \n public boolean addCar(int carType) {\n if(slots[carType-1]>0)\n { \n slots[carType-1]--;\n return true;\n \n }\n return false;\n }\n}\n", + "title": "1603. Design Parking System", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the ParkingSystem class: Example 1:", + "description_images": [], + "constraints": [ + "ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.", + "bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1 , 2 , and 3 respectively. A car can only park in a parking space of its carType . If there is no space available, return false , else park the car in that size space and return true ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]Output[null, true, true, false, false]ExplanationParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 111 ms (Top 92.4%) | Memory: 16.70 MB (Top 96.9%)\n\nclass ParkingSystem:\n def __init__(self, big: int, medium: int, small: int):\n self.vehicle =[big,medium,small]\n\n def addCar(self, carType: int) -> bool:\n if carType == 1 :\n if self.vehicle[0] > 0:\n self.vehicle[0]-=1\n return True\n elif carType == 2:\n if self.vehicle[1] > 0:\n self.vehicle[1]-=1\n return True\n elif carType == 3:\n if self.vehicle[2] > 0:\n self.vehicle[2]-=1\n return True\n return False", + "title": "1603. Design Parking System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a Skiplist without using any built-in libraries. A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way: Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n) . It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n) . See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list Implement the Skiplist class: Note that duplicates may exist in the Skiplist, your code needs to handle this situation. Example 1:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/27/1506_skiplist.gif" + ], + "constraints": [ + "Skiplist() Initializes the object of the skiplist.", + "bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.", + "void add(int num) Inserts the value num into the SkipList.", + "bool erase(int num) Removes the value num from the Skiplist and returns true . If num does not exist in the Skiplist, do nothing and return false . If there exist multiple num values, removing any one of them is fine." + ], + "examples": [ + { + "text": "Example 1: Input[\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]Output[null, null, null, null, false, null, true, false, true, false]ExplanationSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 17.56%) | Memory: 57.1 MB (Top 16.13%)\nclass Skiplist {\n\n public static final int MAX_LEVEL = 4;\n\n private final int levels;\n\n private SkipListEntry head;\n\n private SkipListEntry tail;\n\n public Skiplist() {\n this(MAX_LEVEL);\n }\n\n public Skiplist(int levels) {\n this.levels = levels;\n\n //init new SkipList with defined level\n //Firstly, create the root level (level = 0) entry for left (min) and right (max)\n // and linked it\n // LEFT <------------------------------------------------> RIGHT\n SkipListEntry left = new SkipListEntry(Integer.MIN_VALUE, Integer.MIN_VALUE);\n SkipListEntry right = new SkipListEntry(Integer.MAX_VALUE, Integer.MAX_VALUE);\n left.right = right;\n right.left = left;\n\n // After, we can define left and right as the head and tail nodes\n // HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n this.head = left;\n this.tail = right;\n\n // Next, we can define left and right nodes for other levels and linked it\n // 0 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 1 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 2 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // 3 HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n // ^ ^\n // | |\n // v v\n // N HEAD = LEFT <------------------------------------------------> RIGHT = TAIL\n for (int i = 1; i < this.levels; i++) {\n left.down = new SkipListEntry(\n Integer.MIN_VALUE,\n Integer.MIN_VALUE,\n null,\n null,\n left,\n null\n );\n left = left.down;\n\n right.down = new SkipListEntry(\n Integer.MAX_VALUE,\n Integer.MAX_VALUE,\n null,\n null,\n right,\n null\n );\n right = right.down;\n\n left.right = right;\n right.left = left;\n }\n }\n\n public boolean search(int target) {\n return this.find(target).key == target;\n }\n\n public void add(int num) {\n // We have to always start from head\n SkipListEntry current = this.head;\n\n // For the searching newNode we have to:\n // 1 - start from the head\n // 2 - go down the bottom level\n while (current.hasDown()) {\n current = current.down;\n }\n\n // 3 - try to find newNode\n while (current.hasRight() && num > current.right.key) {\n current = current.right;\n }\n\n // 4 - if we found newNode on the step 3, we have to do nothing (return;)\n if (num == current.key) {\n return;\n }\n\n // 5 - otherwise, we have to a put new newNode on the right\n SkipListEntry newNode = new SkipListEntry(num, num, current, current.right);\n current.right.left = newNode;\n current.right = newNode;\n\n // 6 - have to go up one level\n // 7 - flip the coin\n // 8 - if on the step 8 true - repeat step 5\n for (int level = this.levels - 2; level >= 0; level--) {\n if (!this.coinFlip(level)) {\n return;\n }\n\n // go up one level and find left node for new level\n while (!current.hasUp() && current.hasLeft()) {\n current = current.left;\n }\n current = current.up;\n\n newNode.up = new SkipListEntry(\n num,\n num,\n current,\n current.right,\n null,\n newNode\n );\n newNode = newNode.up;\n\n current.right.left = newNode;\n current.right = newNode;\n }\n }\n\n public boolean erase(int num) {\n SkipListEntry entry = this.find(num);\n if (entry.key != num) {\n return false;\n }\n\n entry.left.right = entry.right;\n entry.right.left = entry.left;\n\n while ((entry = entry.up) != null) {\n entry.left.right = entry.right;\n entry.right.left = entry.left;\n }\n\n return true;\n }\n\n private SkipListEntry find(int key) {\n // We have to always start from head\n SkipListEntry current = this.head;\n\n // while node has right or down we can go down a level or right\n // 1 - we have to go right and try to find element\n // 2 - if element is not presented at this level, we have to go down a level\n // and repeat step 1\n // 3 - if we found element we have to go down to the bottom\n // if we found element we have to return it, otherwise - return last visited\n while (current != null && current.hasRight()) {\n while (current.hasRight() && key > current.right.key) {\n current = current.right;\n }\n\n if (key == current.right.key) {\n current = current.right;\n while (current.hasDown()) {\n current = current.down;\n }\n\n return current;\n }\n\n current = current.down;\n }\n\n return this.head;\n }\n\n private boolean coinFlip(int level) {\n return ThreadLocalRandom.current().nextInt(this.levels - level) == 0;\n }\n\n public static class SkipListEntry {\n\n private final int key;\n\n private final int value;\n\n private SkipListEntry up;\n\n private SkipListEntry down;\n\n private SkipListEntry left;\n\n private SkipListEntry right;\n\n public SkipListEntry(int key, int value) {\n this(key, value, null, null, null, null);\n }\n\n public SkipListEntry(int key,\n int value,\n SkipListEntry left,\n SkipListEntry right) {\n this(key, value, left, right, null, null);\n }\n\n public SkipListEntry(int key,\n int value,\n SkipListEntry left,\n SkipListEntry right,\n SkipListEntry up,\n SkipListEntry down) {\n this.key = key;\n this.value = value;\n this.left = left;\n this.right = right;\n this.up = up;\n this.down = down;\n }\n\n public int getKey() {\n return this.key;\n }\n\n public int getValue() {\n return this.value;\n }\n\n public SkipListEntry left() {\n if (!this.hasLeft()) {\n return null;\n }\n\n return this.left;\n }\n\n public void setLeft(SkipListEntry entry) {\n this.left = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry right() {\n if (!this.hasRight()) {\n return null;\n }\n\n return this.right;\n }\n\n public void setRight(SkipListEntry entry) {\n this.right = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry up() {\n if (!this.hasUp()) {\n return null;\n }\n\n return this.up;\n }\n\n public void setUp(SkipListEntry entry) {\n this.up = Objects.requireNonNull(entry);\n }\n\n public SkipListEntry getDown() {\n return this.down;\n }\n\n public SkipListEntry down() {\n if (!this.hasDown()) {\n return null;\n }\n\n return this.down;\n }\n\n public void setDown(SkipListEntry entry) {\n this.down = Objects.requireNonNull(entry);\n }\n\n public boolean hasLeft() {\n return this.left != null;\n }\n\n public boolean hasRight() {\n return this.right != null;\n }\n\n public boolean hasUp() {\n return this.up != null;\n }\n\n public boolean hasDown() {\n return this.down != null;\n }\n }\n }", + "title": "1206. Design Skiplist", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a Skiplist without using any built-in libraries. A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way: Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n) . It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n) . See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list Implement the Skiplist class: Note that duplicates may exist in the Skiplist, your code needs to handle this situation. Example 1:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/27/1506_skiplist.gif" + ], + "constraints": [ + "Skiplist() Initializes the object of the skiplist.", + "bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.", + "void add(int num) Inserts the value num into the SkipList.", + "bool erase(int num) Removes the value num from the Skiplist and returns true . If num does not exist in the Skiplist, do nothing and return false . If there exist multiple num values, removing any one of them is fine." + ], + "examples": [ + { + "text": "Example 1: Input[\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]Output[null, null, null, null, false, null, true, false, true, false]ExplanationSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3867 ms (Top 5.16%) | Memory: 20.8 MB (Top 90.23%)\nclass Skiplist:\n def __init__(self):\n self.data = []\n def search(self, target: int) -> bool:\n if target in self.data:\n return True\n else:\n return False\n def add(self, num: int) -> None:\n self.data.append(num)\n def erase(self, num: int) -> bool:\n for i in range(len(self.data)):\n if self.data[i] == num:\n self.data.pop(i)\n return True\n if num not in self.data:\n return False", + "title": "1206. Design Skiplist", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Twitter\", \"postTweet\", \"getNewsFeed\", \"follow\", \"postTweet\", \"getNewsFeed\", \"unfollow\", \"getNewsFeed\"]\n[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]Output[null, null, [5], null, null, [6, 5], null, [5]]ExplanationTwitter twitter = new Twitter();\ntwitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).\ntwitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]\ntwitter.follow(1, 2); // User 1 follows user 2.\ntwitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).\ntwitter.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.\ntwitter.unfollow(1, 2); // User 1 unfollows user 2.\ntwitter.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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Twitter:\n\n def __init__(self):\n self.tweets = []\n self.friends = defaultdict(list)\n\n def postTweet(self, userId: int, tweetId: int) -> None:\n self.tweets.append([userId, tweetId]) \n\n def getNewsFeed(self, userId: int) -> List[int]:\n try:\n tweets = [x[1] for x in self.tweets if x[0] in [userId]+self.friends[userId]]\n return list(reversed(tweets))[:10]\n except:\n return \n\n def follow(self, followerId: int, followeeId: int) -> None:\n self.friends[followerId].append(followeeId) \n\n def unfollow(self, followerId: int, followeeId: int) -> None:\n try:\n self.friends[followerId].remove(followeeId)\n except:\n pass\n", + "title": "355. Design Twitter", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t 1 then checks out at time t 2 , then t 1 < t 2 . All events happen in chronological order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "void checkIn(int id, string stationName, int t) A customer with a card ID equal to id , checks in at the station stationName at time t . A customer can only be checked into one place at a time.", + "A customer with a card ID equal to id , checks in at the station stationName at time t .", + "A customer can only be checked into one place at a time.", + "void checkOut(int id, string stationName, int t) A customer with a card ID equal to id , checks out from the station stationName at time t .", + "A customer with a card ID equal to id , checks out from the station stationName at time t .", + "double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation . The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation . The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation . There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.", + "Returns the average time it takes to travel from startStation to endStation .", + "The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation .", + "The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation .", + "There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called." + ], + "examples": [ + { + "text": "Example 1: Input[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]Output[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12", + "image": null + }, + { + "text": "Example 2: Input[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]Output[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 92 ms (Top 65.05%) | Memory: 55.90 MB (Top 20.97%)\n\nclass Passenger {\n int checkinTime;\n int checkoutTime;\n String checkinLocation;\n String checkoutLocation;\n\n public Passenger(String checkinLocation, int checkinTime) {\n this.checkinLocation = checkinLocation;\n this.checkinTime = checkinTime;\n }\n\n void checkout(String checkoutLocation, int checkoutTime) {\n this.checkoutLocation = checkoutLocation;\n this.checkoutTime = checkoutTime;\n }\n\n}\n\nclass Route {\n String startStation;\n String endStation;\n int totalNumberOfTrips;\n long totalTimeSpentInTrips;\n\n public Route(String startStation, String endStation) {\n this.startStation = startStation;\n this.endStation = endStation;\n }\n\n double getAverageTime() {\n return (double) totalTimeSpentInTrips / totalNumberOfTrips;\n }\n\n void addTrip(int startTime, int endTime) {\n totalTimeSpentInTrips += endTime - startTime;\n totalNumberOfTrips++;\n }\n}\n\nclass UndergroundSystem {\n\n Map currentPassengerMap;\n Map routeMap;\n\n public UndergroundSystem() {\n currentPassengerMap = new HashMap<>();\n routeMap = new HashMap<>();\n }\n\n public void checkIn(int id, String stationName, int t) {\n if (!currentPassengerMap.containsKey(id)) {\n Passenger passenger = new Passenger(stationName, t);\n currentPassengerMap.put(id, passenger);\n }\n }\n\n public void checkOut(int id, String stationName, int t) {\n if (currentPassengerMap.containsKey(id)) {\n Passenger passenger = currentPassengerMap.get(id);\n passenger.checkout(stationName, t);\n String routeKey = passenger.checkinLocation + \",\" + passenger.checkoutLocation;\n Route route = routeMap.getOrDefault(routeKey, new Route(passenger.checkinLocation, passenger.checkoutLocation));\n route.addTrip(passenger.checkinTime, passenger.checkoutTime);\n routeMap.put(routeKey, route);\n currentPassengerMap.remove(id);\n }\n }\n\n public double getAverageTime(String startStation, String endStation) {\n return routeMap.get(startStation + \",\" + endStation).getAverageTime();\n }\n}\n", + "title": "1396. Design Underground System", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t 1 then checks out at time t 2 , then t 1 < t 2 . All events happen in chronological order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "void checkIn(int id, string stationName, int t) A customer with a card ID equal to id , checks in at the station stationName at time t . A customer can only be checked into one place at a time.", + "A customer with a card ID equal to id , checks in at the station stationName at time t .", + "A customer can only be checked into one place at a time.", + "void checkOut(int id, string stationName, int t) A customer with a card ID equal to id , checks out from the station stationName at time t .", + "A customer with a card ID equal to id , checks out from the station stationName at time t .", + "double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation . The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation . The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation . There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.", + "Returns the average time it takes to travel from startStation to endStation .", + "The average time is computed from all the previous traveling times from startStation to endStation that happened directly , meaning a check in at startStation followed by a check out from endStation .", + "The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation .", + "There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called." + ], + "examples": [ + { + "text": "Example 1: Input[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]Output[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12", + "image": null + }, + { + "text": "Example 2: Input[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]Output[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]ExplanationUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 441 ms (Top 30.19%) | Memory: 23.9 MB (Top 87.19%)\nfrom collections import defaultdict\nclass UndergroundSystem:\n def __init__(self):\n self.checkin = {}\n self.traveltime = defaultdict(dict)\n\n def checkIn(self, id: int, stationName: str, t: int) -> None:\n self.checkin[id] = (stationName, t)\n\n def checkOut(self, id: int, stationName: str, t: int) -> None:\n startStation, startTime = self.checkin[id]\n del self.checkin[id]\n if stationName not in self.traveltime[startStation]:\n self.traveltime[startStation][stationName] = []\n self.traveltime[startStation][stationName].append(t-startTime)\n\n def getAverageTime(self, startStation: str, endStation: str) -> float:\n return sum(self.traveltime[startStation][endStation])/len(self.traveltime[startStation][endStation])", + "title": "1396. Design Underground System", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the array paths , where paths[i] = [cityA i , cityB i ] means there exists a direct path going from cityA i to cityB i . Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= paths.length <= 100", + "paths[i].length == 2", + "1 <= cityA i .length, cityB i .length <= 10", + "cityA i != cityB i", + "All strings consist of lowercase and uppercase English letters and the space character." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]Output:\"Sao Paulo\"Explanation:Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".", + "image": null + }, + { + "text": "Example 2: Input:paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]Output:\"A\"Explanation:All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".", + "image": null + }, + { + "text": "Example 3: Input:paths = [[\"A\",\"Z\"]]Output:\"Z\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 58.98%) | Memory: 44 MB (Top 40.73%)\nclass Solution {\n public String destCity(List> paths) {\n HashSet set1 = new HashSet<>();\n\n for (int i = 0; i < paths.size(); ++i) {\n set1.add(paths.get(i).get(0));\n }\n for (int i = 0; i < paths.size(); ++i) {\n if (!set1.contains(paths.get(i).get(1))) return paths.get(i).get(1);\n }\n return \"placeholder\";\n }\n}", + "title": "1436. Destination City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the array paths , where paths[i] = [cityA i , cityB i ] means there exists a direct path going from cityA i to cityB i . Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= paths.length <= 100", + "paths[i].length == 2", + "1 <= cityA i .length, cityB i .length <= 10", + "cityA i != cityB i", + "All strings consist of lowercase and uppercase English letters and the space character." + ], + "examples": [ + { + "text": "Example 1: Input:paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]Output:\"Sao Paulo\"Explanation:Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".", + "image": null + }, + { + "text": "Example 2: Input:paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]Output:\"A\"Explanation:All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".", + "image": null + }, + { + "text": "Example 3: Input:paths = [[\"A\",\"Z\"]]Output:\"Z\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 101 ms (Top 25.06%) | Memory: 13.8 MB (Top 81.64%)\nfrom collections import defaultdict\nclass Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n deg = defaultdict(int)\n for v, w in paths:\n deg[v] += 1\n deg[w]\n for v in deg:\n if not deg[v]: return v", + "title": "1436. Destination City", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer mass , which represents the original mass of a planet. You are further given an integer array asteroids , where asteroids[i] is the mass of the i th asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order . If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= mass <= 10^5", + "1 <= asteroids.length <= 10^5", + "1 <= asteroids[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mass = 10, asteroids = [3,9,19,5,21]Output:trueExplanation:One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.", + "image": null + }, + { + "text": "Example 2: Input:mass = 5, asteroids = [4,9,23,4]Output:falseExplanation:The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 476 ms (Top 5.23%) | Memory: 135.2 MB (Top 5.23%)\nclass Solution {\n public boolean asteroidsDestroyed(int mass, int[] asteroids) {\n PriorityQueue maxHeap = new PriorityQueue<>((a,b)->b-a);\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for(int val:asteroids)\n maxHeap.add(val);\n\n long bigMass = mass;\n\n while(maxHeap.size()>0){\n int curr = maxHeap.poll();\n\n if(bigMass>=curr){\n bigMass+=curr;\n while(minHeap.size()>0 && bigMass>=minHeap.peek()){\n bigMass+=minHeap.poll();\n }\n }\n else{\n minHeap.add(curr);\n }\n }\n\n return minHeap.size()==0 && maxHeap.size()==0;\n }\n}", + "title": "2126. Destroying Asteroids", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer mass , which represents the original mass of a planet. You are further given an integer array asteroids , where asteroids[i] is the mass of the i th asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order . If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= mass <= 10^5", + "1 <= asteroids.length <= 10^5", + "1 <= asteroids[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mass = 10, asteroids = [3,9,19,5,21]Output:trueExplanation:One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.", + "image": null + }, + { + "text": "Example 2: Input:mass = 5, asteroids = [4,9,23,4]Output:falseExplanation:The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2207 ms (Top 14.71%) | Memory: 27.8 MB (Top 42.78%)\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n asteroids = sorted(asteroids)\n for i in asteroids:\n if i <= mass:\n mass += i\n else:\n return False\n return True", + "title": "2126. Destroying Asteroids", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We define the usage of capitals in a word to be right when one of the following cases holds: Given a string word , return true if the usage of capitals in it is right. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "All letters in this word are capitals, like \"USA\" .", + "All letters in this word are not capitals, like \"leetcode\" .", + "Only the first letter in this word is capital, like \"Google\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"USA\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:word = \"FlaG\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 29.72%) | Memory: 41.4 MB (Top 86.57%)\nclass Solution {\n public boolean detectCapitalUse(String word) {\n int count = 0;\n for(int i=0; i < word.length(); i++){\n if('A' <= word.charAt(i) && word.charAt(i) <= 'Z')\n count++;\n }\n if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt(0) && word.charAt(0) <= 'Z')))\n return true;\n else\n return false;\n }\n}", + "title": "520. Detect Capital", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We define the usage of capitals in a word to be right when one of the following cases holds: Given a string word , return true if the usage of capitals in it is right. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "All letters in this word are capitals, like \"USA\" .", + "All letters in this word are not capitals, like \"leetcode\" .", + "Only the first letter in this word is capital, like \"Google\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"USA\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:word = \"FlaG\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def detectCapitalUse(self, word: str) -> bool:\n l=len(word)\n if l==1:\n return True\n if word[0]==word[0].lower() and word[1]==word[1].upper():\n return False\n \n u=False\n if word[0]==word[0].upper():\n if word[1]==word[1].upper():\n u=True\n \n for i in word[2:]:\n if i==i.upper() and u==False:\n return False\n elif i==i.lower() and u==True:\n return False\n return True\n", + "title": "520. Detect Capital", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D array of characters grid of size m x n , you need to find if there exists any cycle consisting of the same value in grid . A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/15/1.png", + "https://assets.leetcode.com/uploads/2020/07/15/22.png", + "https://assets.leetcode.com/uploads/2020/07/15/3.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]Output:trueExplanation:There are two valid cycles shown in different colors in the image below:", + "image": null + }, + { + "text": "Example 2: Input:grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]Output:trueExplanation:There is only one valid cycle highlighted in the image below:", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsCycle(char[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n\n\t\t// Create a boolean array of same dimensions to keep track of visited cells\n boolean[][] visited = new boolean[rows][cols];\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {\n return true;\n }\n }\n }\n\n return false;\n }\n \n public boolean dfs(\n char[][] grid,\n boolean[][] visited,\n int i,\n int j,\n int prevI,\n int prevJ,\n char c\n ) {\n\t\t// Check for out of bounds\n if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;\n\n\t\t// Check whether the current char matches the previous char\n if (grid[i][j] != c) return false;\n\t\t\n\t\t// If we stumble upon the same cell, we're guaranteed to have found a cycle!\n if (visited[i][j]) {\n return true;\n }\n \n\t\t// Mark the cell as visited\n visited[i][j] = true;\n \n\t\t// We want to search in the south direction ONLY IF we didn't come from north\n\t\t// Do the same for all four directions\n boolean south = i - prevI != -1;\n boolean north = i - prevI != 1;\n boolean east = j - prevJ != -1;\n boolean west = j - prevJ != 1;\n return\n (south && dfs(grid, visited, i + 1, j, i, j, c)) ||\n (north && dfs(grid, visited, i - 1, j, i, j, c)) ||\n (east && dfs(grid, visited, i, j + 1, i, j, c)) ||\n (west && dfs(grid, visited, i, j - 1, i, j, c));\n }\n}\n", + "title": "1559. Detect Cycles in 2D Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D array of characters grid of size m x n , you need to find if there exists any cycle consisting of the same value in grid . A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/15/1.png", + "https://assets.leetcode.com/uploads/2020/07/15/22.png", + "https://assets.leetcode.com/uploads/2020/07/15/3.png" + ], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]Output:trueExplanation:There are two valid cycles shown in different colors in the image below:", + "image": null + }, + { + "text": "Example 2: Input:grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]Output:trueExplanation:There is only one valid cycle highlighted in the image below:", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n \n def getNeighbours(row,col,char):\n neighbours = []\n if row > 0 and grid[row-1][col] == char and not visited[row-1][col]:\n neighbours.append([row-1,col])\n if col > 0 and grid[row][col-1] == char and not visited[row][col-1]:\n neighbours.append([row,col-1])\n if row < len(grid)-1 and grid[row+1][col] == char and not visited[row+1][col]:\n neighbours.append([row+1,col])\n if col < len(grid[0])-1 and grid[row][col+1] == char and not visited[row][col+1]:\n neighbours.append([row,col+1])\n return neighbours\n \n def dfs(row,col,char,cyclePresent):\n if visited[row][col] or cyclePresent:\n cyclePresent = True\n return cyclePresent\n visited[row][col] = True\n neighbours = getNeighbours(row,col,char)\n for r,c in neighbours:\n cyclePresent = dfs(r,c,char,cyclePresent)\n return cyclePresent\n \n visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\n cyclePresent = False\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if cyclePresent:\n return True\n if visited[row][col]:\n continue\n cyclePresent = dfs(row,col,grid[row][col],cyclePresent)\n \n return cyclePresent\n", + "title": "1559. Detect Cycles in 2D Grid", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of positive integers arr , find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 100", + "1 <= arr[i] <= 100", + "1 <= m <= 100", + "2 <= k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,4,4,4,4], m = 1, k = 3Output:trueExplanation:The pattern(4)of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2Output:trueExplanation:The pattern(1,2)of length 2 is repeated 2 consecutive times. Another valid pattern(2,1) isalso repeated 2 times.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,1,2,1,3], m = 2, k = 3Output:falseExplanation:The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public boolean containsPattern(int[] arr, int m, int k) {\n int count = 0;\n for (int i = 0; i < arr.length - m; i++) {\n if (arr[i] == arr[i + m]) {\n count++;\n } else {\n count = 0;\n }\n if (count == m * (k-1)) {\n return true;\n }\n }\n return false;\n }\n}\n", + "title": "1566. Detect Pattern of Length M Repeated K or More Times", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers arr , find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 100", + "1 <= arr[i] <= 100", + "1 <= m <= 100", + "2 <= k <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,4,4,4,4], m = 1, k = 3Output:trueExplanation:The pattern(4)of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2Output:trueExplanation:The pattern(1,2)of length 2 is repeated 2 consecutive times. Another valid pattern(2,1) isalso repeated 2 times.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,1,2,1,3], m = 2, k = 3Output:falseExplanation:The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n if len(arr) < k*m:\n return False\n \n n = len(arr)\n pattern = arr[0:m]\n repeats = 1\n for i in range(m, n - m + 1, m):\n if arr[i:i+m] != pattern:\n break\n \n repeats += 1\n if repeats >= k:\n return True\n \n return self.containsPattern(arr[1:], m, k)", + "title": "1566. Detect Pattern of Length M Repeated K or More Times", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a stream of points on the X-Y plane. Design an algorithm that: 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: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]Output[null, null, null, null, 1, 0, null, 2]ExplanationDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points", + "image": "https://assets.leetcode.com/uploads/2021/09/01/image.png" + } + ], + "follow_up": null, + "solution": "class DetectSquares {\n List coordinates;\n Map counts;\n \n public DetectSquares() {\n coordinates = new ArrayList<>();\n counts = new HashMap<>();\n }\n \n public void add(int[] point) {\n coordinates.add(point);\n String key = point[0] + \"@\" + point[1];\n counts.put(key, counts.getOrDefault(key, 0) + 1);\n }\n \n public int count(int[] point) {\n int sum = 0, px = point[0], py = point[1];\n for (int[] coordinate : coordinates) {\n int x = coordinate[0], y = coordinate[1];\n if (px == x || py == y || (Math.abs(px - x) != Math.abs(py - y)))\n continue;\n sum += counts.getOrDefault(x + \"@\" + py, 0) * counts.getOrDefault(px + \"@\" + y, 0);\n }\n \n return sum;\n }\n}\n", + "title": "2013. Detect Squares", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a stream of points on the X-Y plane. Design an algorithm that: 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: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]Output[null, null, null, null, 1, 0, null, 2]ExplanationDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points", + "image": "https://assets.leetcode.com/uploads/2021/09/01/image.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 658 ms (Top 42.61%) | Memory: 16 MB (Top 39.48%)\n\"\"\"\nStore every points and number of their appearance\nGroup the points by their x value\n\nGiven a point(x1,y1) to count, try to find p2(x1,y2),p3(x2,y2),p4(x2,y1)\nand add product of their appearances\n\nGo through every points that has same x1(except the point that is the same as (x1,y1), the length of the side of the square is decided by abd(y2-y1).\n\nUse the decided side length to calculate p3 and p4, see if they are in the dict. If do, add product of their appearances.\n\np3 p2 p3`\n\np4 p1 p4`\n\nNotice that p3 and p4 can be on both left side and right side of side (p2,p1)\n\n\"\"\"\nfrom collections import defaultdict\nclass DetectSquares:\n\n def __init__(self):\n self.pts=defaultdict(int)\n self.by_x=defaultdict(set)\n\n def add(self, point: List[int]) -> None:\n self.pts[(point[0],point[1])]+=1\n self.by_x[point[0]].add((point[0],point[1]))\n\n def count(self, p1: List[int]) -> int:\n res=0\n x1,y1=p1[0],p1[1]\n if x1 in self.by_x:\n #p2:x1,y2\n for p2 in self.by_x[x1]:\n x2,y2=p2\n if y1==y2:\n continue\n #length of side of square\n b=abs(y1-y2)\n #left side\n p3=(x1-b,y2)\n p4=(x1-b,y1)\n if p3 in self.pts and p4 in self.pts:\n res+=self.pts[p2]*self.pts[p3]*self.pts[p4]\n #right side\n p3=(x1+b,y2)\n p4=(x1+b,y1)\n if p3 in self.pts and p4 in self.pts:\n res+=self.pts[p2]*self.pts[p3]*self.pts[p4]\n return res\n\n# Your DetectSquares object will be instantiated and called as such:\n# obj = DetectSquares()\n# obj.add(point)\n# param_2 = obj.count(point)", + "title": "2013. Detect Squares", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given coordinates , a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black . The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png" + ], + "constraints": [ + "coordinates.length == 2", + "'a' <= coordinates[0] <= 'h'", + "'1' <= coordinates[1] <= '8'" + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = \"a1\"Output:falseExplanation:From the chessboard above, the square with coordinates \"a1\" is black, so return false.", + "image": null + }, + { + "text": "Example 2: Input:coordinates = \"h3\"Output:trueExplanation:From the chessboard above, the square with coordinates \"h3\" is white, so return true.", + "image": null + }, + { + "text": "Example 3: Input:coordinates = \"c7\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean squareIsWhite(String coordinates) {\n return (coordinates.charAt(0) - 'a'+ coordinates.charAt(1) - '0')%2==0 ;\n }\n}\n", + "title": "1812. Determine Color of a Chessboard Square", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given coordinates , a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return true if the square is white, and false if the square is black . The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png" + ], + "constraints": [ + "coordinates.length == 2", + "'a' <= coordinates[0] <= 'h'", + "'1' <= coordinates[1] <= '8'" + ], + "examples": [ + { + "text": "Example 1: Input:coordinates = \"a1\"Output:falseExplanation:From the chessboard above, the square with coordinates \"a1\" is black, so return false.", + "image": null + }, + { + "text": "Example 2: Input:coordinates = \"h3\"Output:trueExplanation:From the chessboard above, the square with coordinates \"h3\" is white, so return true.", + "image": null + }, + { + "text": "Example 3: Input:coordinates = \"c7\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 10.11%) | Memory: 13.8 MB (Top 56.37%)\nclass Solution:\n def squareIsWhite(self, coordinates: str) -> bool:\n return (ord(coordinates[0])+ord(coordinates[1]))%2", + "title": "1812. Determine Color of a Chessboard Square", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' ). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 1000", + "s.length is even.", + "s consists of uppercase and lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"book\"Output:trueExplanation:a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.", + "image": null + }, + { + "text": "Example 2: Input:s = \"textbook\"Output:falseExplanation:a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 23.59%) | Memory: 42.5 MB (Top 46.22%)\nclass Solution {\n public boolean halvesAreAlike(String s) {\n //add vowels to the set\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n\n //find the mid\n int mid = s.length() / 2;\n int count = 0;\n //increment the count for left half, decrement count for the second half if its a vowel\n for (int i = 0; i < s.length(); i++)\n count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0;\n //finally count should be 0 to match left and right half\n return count == 0;\n }\n}", + "title": "1704. Determine if String Halves Are Alike", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ( 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' ). Notice that s contains uppercase and lowercase letters. Return true if a and b are alike . Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 1000", + "s.length is even.", + "s consists of uppercase and lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"book\"Output:trueExplanation:a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.", + "image": null + }, + { + "text": "Example 2: Input:s = \"textbook\"Output:falseExplanation:a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.", + "image": null + } + ], + "follow_up": null, + "solution": "vowels = \"aeiouAEIOU\"\n\nclass Solution:\n def halvesAreAlike(self, S: str) -> bool:\n mid, ans = len(S) // 2, 0\n for i in range(mid):\n if S[i] in vowels: ans += 1\n if S[mid+i] in vowels: ans -=1\n return ans == 0\n", + "title": "1704. Determine if String Halves Are Alike", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"Output:trueExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"Output:falseExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"Output:trueExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"Apply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 51.63%) | Memory: 58.9 MB (Top 49.30%)\nclass Solution {\n private int N = 26;\n public boolean closeStrings(String word1, String word2) {\n // count the English letters\n int[] arr1 = new int[N], arr2 = new int[N];\n for (char ch : word1.toCharArray())\n arr1[ch - 'a']++;\n for (char ch : word2.toCharArray())\n arr2[ch - 'a']++;\n\n // if one has a letter which another one doesn't have, dont exist\n for (int i = 0; i < N; i++) {\n if (arr1[i] == arr2[i]) {\n continue;\n }\n if (arr1[i] == 0 || arr2[i] == 0) {\n return false;\n }\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n for (int i = 0; i < N; i++) {\n if (arr1[i] != arr2[i]) {\n return false;\n }\n }\n return true;\n }\n}", + "title": "1657. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"Output:trueExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"Output:falseExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"Output:trueExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"Apply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 70.4%) | Memory: 17.77 MB (Top 49.0%)\n\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())", + "title": "1657. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two n x n binary matrices mat and target , return true if it is possible to make mat equal to target by rotating mat in 90-degree increments , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == mat.length == target.length", + "n == mat[i].length == target[i].length", + "1 <= n <= 10", + "mat[i][j] and target[i][j] are either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,1],[1,0]], target = [[1,0],[0,1]]Output:trueExplanation:We can rotate mat 90 degrees clockwise to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid3.png" + }, + { + "text": "Example 2: Input:mat = [[0,1],[1,1]], target = [[1,0],[0,1]]Output:falseExplanation:It is impossible to make mat equal to target by rotating mat.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid4.png" + }, + { + "text": "Example 3: Input:mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]Output:trueExplanation:We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/26/grid4.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 6.49%) | Memory: 42.9 MB (Top 12.04%)\nclass Solution {\n public boolean findRotation(int[][] mat, int[][] target) {\n if (mat == target) return true;\n int n = mat.length;\n int[] res[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 90\n for (int j = 0; j < n; j++) {\n res[i][j] = mat[n - 1 - j][i];\n }\n }\n\n int[] res2[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 180\n for (int j = 0; j < n; j++) {\n res2[i][j] = res[n - 1 - j][i];\n }\n }\n\n int[] res3[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 270\n for (int j = 0; j < n; j++) {\n res3[i][j] = res2[n - 1 - j][i];\n }\n }\n\n //compare to 90,180,270 and itself\n if(Arrays.deepEquals(target, res) || Arrays.deepEquals(target, res2) || Arrays.deepEquals(target, res3) || Arrays.deepEquals(target, mat) ){\n return true;\n }\n return false;\n }\n}\n\n// Arrays.deepEquals() use for matrix", + "title": "1886. Determine Whether Matrix Can Be Obtained By Rotation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two n x n binary matrices mat and target , return true if it is possible to make mat equal to target by rotating mat in 90-degree increments , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == mat.length == target.length", + "n == mat[i].length == target[i].length", + "1 <= n <= 10", + "mat[i][j] and target[i][j] are either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,1],[1,0]], target = [[1,0],[0,1]]Output:trueExplanation:We can rotate mat 90 degrees clockwise to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid3.png" + }, + { + "text": "Example 2: Input:mat = [[0,1],[1,1]], target = [[1,0],[0,1]]Output:falseExplanation:It is impossible to make mat equal to target by rotating mat.", + "image": "https://assets.leetcode.com/uploads/2021/05/20/grid4.png" + }, + { + "text": "Example 3: Input:mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]Output:trueExplanation:We can rotate mat 90 degrees clockwise two times to make mat equal target.", + "image": "https://assets.leetcode.com/uploads/2021/05/26/grid4.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n \n # if already equal\n if target == mat:\n return True\n # there are 4 different rotation with 90 deg. \n # We need to check at most 3 more rotation.\n for i in range(3):\n # transpose the matrix by swap row and col values.\n for j in range(len(mat)):\n for k in range(j+1, len(mat)):\n mat[j][k], mat[k][j] = mat[k][j], mat[j][k]\n # Reflect the row by reverse it.\n mat[j] = mat[j][::-1]\n # now the matrix is roteted; check if they're alike.\n if target == mat:\n return True\n return False\n", + "title": "1886. Determine Whether Matrix Can Be Obtained By Rotation", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [x i , y i , r i ] . x i and y i denote the X-coordinate and Y-coordinate of the location of the i th bomb, whereas r i denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs , return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= bombs.length <= 100", + "bombs[i].length == 3", + "1 <= x i , y i , r i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:bombs = [[2,1,3],[6,1,4]]Output:2Explanation:The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-3.png" + }, + { + "text": "Example 2: Input:bombs = [[1,1,5],[10,10,5]]Output:1Explanation:Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-2.png" + }, + { + "text": "Example 3: Input:bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]Output:5Explanation:The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/desmos-eg1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 234 ms (Top 36.67%) | Memory: 42.3 MB (Top 94.92%)\nclass Solution {\n /*\n Make directed graph\n u -> v means, v is in the range of u\n check from which node maximum nodes can be reached and return the number of nodes reached\n */\n public int maximumDetonation(int[][] bombs) {\n Map> graph = new HashMap<>();\n\n int n = bombs.length;\n for(int i = 0; i< n; i++){\n graph.put(i, new ArrayList<>());\n for(int j = 0; j< n; j++){\n if(i == j) continue;\n if(inRange(bombs[i], bombs[j]))\n graph.get(i).add(j);\n }\n }\n\n int max = 0;\n for(int i = 0; i< n; i++){\n max = Math.max(max, dfs(i, graph, new HashSet<>()));\n }\n return max;\n }\n\n private boolean inRange(int[] u, int[] v){\n // (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border\n // (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle\n // (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle\n return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);\n }\n\n private int dfs(int node, Map> graph, Set visited){\n if(visited.contains(node)) return 0;\n visited.add(node);\n int res = 0;\n for(int neigh: graph.get(node)){\n res += dfs(neigh, graph, visited);\n }\n return res + 1;\n }\n}", + "title": "2101. Detonate the Maximum Bombs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [x i , y i , r i ] . x i and y i denote the X-coordinate and Y-coordinate of the location of the i th bomb, whereas r i denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges. Given the list of bombs , return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= bombs.length <= 100", + "bombs[i].length == 3", + "1 <= x i , y i , r i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:bombs = [[2,1,3],[6,1,4]]Output:2Explanation:The above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-3.png" + }, + { + "text": "Example 2: Input:bombs = [[1,1,5],[10,10,5]]Output:1Explanation:Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/06/desmos-eg-2.png" + }, + { + "text": "Example 3: Input:bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]Output:5Explanation:The best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/desmos-eg1.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maximumDetonation(self, bombs):\n def count(i):\n dq, ret = [i], [i]\n while len(dq) > 0:\n i = dq.pop()\n for j in adj[i]:\n if j not in ret and j not in dq:\n dq.append(j)\n ret.append(j)\n return len(ret)\n\n adj = collections.defaultdict(list)\n for i in range(len(bombs)):\n for j in range(i + 1, len(bombs)):\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:\n adj[i].append(j)\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:\n adj[j].append(i)\n ret = 0\n for i in range(len(bombs)):\n ret = max(ret, count(i))\n return ret\n", + "title": "2101. Detonate the Maximum Bombs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: Given a string s , reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s[i] == 'I' if perm[i] < perm[i + 1] , and", + "s[i] == 'D' if perm[i] > perm[i + 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"IDID\"Output:[0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:s = \"III\"Output:[0,1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:s = \"DDI\"Output:[3,2,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 7.32%) | Memory: 48.4 MB (Top 38.52%)\nclass Solution {\n public int[] diStringMatch(String s) {\n int low = 0;\n int high = s.length();\n int[] ans = new int[s.length() + 1];\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'I'){\n ans[i] = low++;\n } else{\n ans[i] = high--;\n }\n }\n ans[s.length()] = high;\n return ans;\n }\n}", + "title": "942. DI String Match", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: Given a string s , reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s[i] == 'I' if perm[i] < perm[i + 1] , and", + "s[i] == 'D' if perm[i] > perm[i + 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"IDID\"Output:[0,4,1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:s = \"III\"Output:[0,1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:s = \"DDI\"Output:[3,2,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n result = []\n min_ = 0\n max_ = len(s)\n for x in s:\n if x==\"I\":\n result.append(min_)\n min_ += 1\n elif x==\"D\":\n result.append(max_)\n max_ -= 1\n result.append(min_)\n return result\n", + "title": "942. DI String Match", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix mat , return an array of all the elements of the array in a diagonal order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "-10^5 <= mat[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,2,4,7,5,3,6,8,9]", + "image": "https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]]Output:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 98.1%) | Memory: 45.96 MB (Top 86.5%)\n\n/**\n * Simulate Diagonal Order Traversal\n *\n * r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all\n * on same diagonal with r+c =2. If you check the directions of diagonals, first\n * diagonal is up, second diagonal is down, third one is up and so on..\n * Therefore (r+c)%2 simply determines direction. Even is UP direction. Odd is\n * DOWN direction.\n *\n * Time Complexity: O(M*N)\n *\n * Space Complexity: O(1) without considering result space.\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n public int[] findDiagonalOrder(int[][] matrix) {\n if (matrix == null) {\n throw new IllegalArgumentException(\"Input matrix is null\");\n }\n if (matrix.length == 0 || matrix[0].length == 0) {\n return new int[0];\n }\n\n int rows = matrix.length;\n int cols = matrix[0].length;\n int[] result = new int[rows * cols];\n int r = 0;\n int c = 0;\n\n for (int i = 0; i < result.length; i++) {\n result[i] = matrix[r][c];\n if ((r + c) % 2 == 0) { // Move Up\n if (c == cols - 1) {\n // Reached last column. Now move to below cell in the same column.\n // This condition needs to be checked first due to top right corner cell.\n r++;\n } else if (r == 0) {\n // Reached first row. Now move to next cell in the same row.\n c++;\n } else {\n // Somewhere in middle. Keep going up diagonally.\n r--;\n c++;\n }\n } else { // Move Down\n if (r == rows - 1) {\n // Reached last row. Now move to next cell in same row.\n // This condition needs to be checked first due to bottom left corner cell.\n c++;\n } else if (c == 0) {\n // Reached first columns. Now move to below cell in the same column.\n r++;\n } else {\n // Somewhere in middle. Keep going down diagonally.\n r++;\n c--;\n }\n }\n }\n\n return result;\n }\n}", + "title": "498. Diagonal Traverse", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix mat , return an array of all the elements of the array in a diagonal order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "-10^5 <= mat[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,2,4,7,5,3,6,8,9]", + "image": "https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]]Output:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:\n flag, rowNum, colNum = True, len(mat), len(mat[0])\n\n total, ans = 0, []\n while total <= rowNum + colNum - 2:\n iLimited = rowNum - 1 if flag else colNum - 1 \n jLimited = colNum - 1 if flag else rowNum - 1\n i = total if total < iLimited else iLimited\n j = total - i\n while i >= 0 and j <= jLimited:\n if flag:\n ans.append(mat[i][j])\n else:\n ans.append(mat[j][i])\n i -= 1\n j += 1\n total += 1\n flag = not flag\n return ans\n", + "title": "498. Diagonal Traverse", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array nums , return all elements of nums in diagonal order as shown in the below images . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i].length <= 10^5", + "1 <= sum(nums[i].length) <= 10^5", + "1 <= nums[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,4,2,7,5,3,8,6,9]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" + }, + { + "text": "Example 2: Input:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]Output:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" + } + ], + "follow_up": null, + "solution": "\tclass Solution {\npublic int[] findDiagonalOrder(List> nums) {\n HashMap> map = new HashMap();\n \n for(int i = 0 ; i < nums.size() ; i++){\n for(int j = 0 ; j < nums.get(i).size() ; j++){\n int z = i + j;\n if(map.containsKey(z)){\n map.get(z).add(nums.get(i).get(j));\n }else{\n Stack stk = new Stack<>();\n stk.push(nums.get(i).get(j));\n map.put(z , stk);\n }\n }\n }\n ArrayList arr = new ArrayList<>();\n int k = 0;\n while(true){\n if(map.containsKey(k)){\n int size = map.get(k).size();\n while(size-- > 0){\n arr.add(map.get(k).pop());\n }\n k++;\n }else{\n break;\n }\n }\n int[] res = new int[arr.size()];\n for(int i = 0 ; i < res.length ; i++){\n res[i] = arr.get(i);\n }\n \n return res;\n}}\n", + "title": "1424. Diagonal Traverse II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D integer array nums , return all elements of nums in diagonal order as shown in the below images . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i].length <= 10^5", + "1 <= sum(nums[i].length) <= 10^5", + "1 <= nums[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,4,2,7,5,3,8,6,9]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" + }, + { + "text": "Example 2: Input:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]Output:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]", + "image": "https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t# sort the index of element\n heap = list()\n n = len(nums)\n for i in range(n):\n m = len(nums[i])\n for j in range(m):\n heapq.heappush(heap,[i+j,j,i])\n\t\t\t\t\n\t\t# append the element one by one\n ans = []\n while heap:\n temp = heapq.heappop(heap)\n ans.append(nums[temp[2]][temp[1]])\n return ans\n", + "title": "1424. Diagonal Traverse II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]Output:3Explanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.91%) | Memory: 42.9 MB (Top 74.91%)\nclass Solution {\n // Declare Global Variable ans to 0\n int ans = 0;\n // Depth First Search Function\n public int dfs(TreeNode root) {\n if(root == null) return 0;\n // recursive call for left height\n int lh = dfs(root.left);\n // recursive call for right height\n int rh = dfs(root.right);\n\n // update ans\n ans = Math.max(ans, lh + rh);\n\n // return max value\n return Math.max(lh, rh) + 1;\n }\n\n // Diameter of Binary Tree Function\n public int diameterOfBinaryTree(TreeNode root) {\n // Call dfs Function\n dfs(root);\n return ans;\n }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(n)\n*/", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]Output:3Explanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 16.95%) | Memory: 16.5 MB (Top 10.21%)\nclass Solution:\n \"\"\"\n Top Down recursion approach: it is sub optimal\n \"\"\"\n def __init__(self):\n self.max_diameter = 0\n def diameter(self, root):\n if root is None:\n return 0\n return self.max_depth(root.left) + self.max_depth(root.right)\n\n def max_depth(self, root):\n if root is None:\n return 0\n return 1 + max(self.max_depth(root.left), self.max_depth(root.right))\n\n def func(self, root):\n if root is not None:\n diameter = self.diameter(root)\n if self.max_diameter < diameter:\n self.max_diameter = diameter\n self.diameterOfBinaryTree(root.left)\n self.diameterOfBinaryTree(root.right)\n\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.func(root)\n return self.max_diameter\n\n \"\"\"\n Better Approach: I can try to approach this problem using bottom up recursion\n \"\"\"\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.diameter = 0\n def fun(root):\n if root is None:\n return 0\n left = fun(root.left)\n right = fun(root.right)\n if left + right > self.diameter:\n self.diameter = left + right\n return max(left, right) + 1\n fun(root)\n return self.diameter", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] ( 1-indexed ) consecutive times. Given an array of integers rollMax and an integer n , return the number of distinct sequences that can be obtained with exact n rolls . Since the answer may be too large, return it modulo 10^9 + 7 . Two sequences are considered different if at least one element differs from each other. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 5000", + "rollMax.length == 6", + "1 <= rollMax[i] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, rollMax = [1,1,2,2,2,3]Output:34Explanation:There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, rollMax = [1,1,1,1,1,1]Output:30", + "image": null + }, + { + "text": "Example 3: Input:n = 3, rollMax = [1,1,1,2,2,3]Output:181", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 149 ms (Top 22.45%) | Memory: 56.7 MB (Top 20.41%)\nclass Solution {\n long[][][] dp;\n int mod = 1_000_000_007;\n public int dieSimulator(int n, int[] rollMax) {\n dp = new long[n + 1][7][16];\n for(long[][] row: dp)\n for(long[] col: row)\n Arrays.fill(col, -1);\n\n return (int)helper(n, 0, 0, rollMax, 0);\n }\n\n private long helper(int n, int dice, int prev, int[] rollMax, int runs)\n {\n if(n == dice)\n return 1;\n\n if(dp[dice][prev][runs] != -1)\n return dp[dice][prev][runs];\n\n long ans = 0;\n int[] temp = rollMax;\n for(int i = 1; i <= 6; i++)\n {\n if(prev != 0 && i == prev && rollMax[i-1] <= runs)\n continue;\n if(i == prev)\n ans = (ans + helper(n, dice + 1, i, rollMax, runs + 1)) % mod;\n else\n ans = (ans + helper(n, dice + 1, i, rollMax, 1)) % mod;\n }\n\n dp[dice][prev][runs] = ans;\n return ans;\n }\n}", + "title": "1223. Dice Roll Simulation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] ( 1-indexed ) consecutive times. Given an array of integers rollMax and an integer n , return the number of distinct sequences that can be obtained with exact n rolls . Since the answer may be too large, return it modulo 10^9 + 7 . Two sequences are considered different if at least one element differs from each other. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 5000", + "rollMax.length == 6", + "1 <= rollMax[i] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, rollMax = [1,1,2,2,2,3]Output:34Explanation:There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, rollMax = [1,1,1,1,1,1]Output:30", + "image": null + }, + { + "text": "Example 3: Input:n = 3, rollMax = [1,1,1,2,2,3]Output:181", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n dp = {}\n def solve(n,last,count):\n if n == 0: return 1\n if (n,last,count) in dp: return dp[(n,last,count)]\n ans = 0\n for i in range(6):\n if last == i:\n if count == rollMax[i]: continue\n ans += solve(n-1,last,count + 1)\n else:\n ans += solve(n-1,i,1)\n dp[(n,last,count)] = ans\n return ans\n \n return solve(n,None,0) % 1000000007\n", + "title": "1223. Dice Roll Simulation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators . You may return the answer in any order . The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 10^4 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= expression.length <= 20", + "expression consists of digits and the operator '+' , '-' , and '*' .", + "All the integer values in the input expression are in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"2-1-1\"Output:[0,2]Explanation:((2-1)-1) = 0 \n(2-(1-1)) = 2", + "image": null + }, + { + "text": "Example 2: Input:expression = \"2*3-4*5\"Output:[-34,-14,-10,-10,10]Explanation:(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 79.5%) | Memory: 41.16 MB (Top 75.1%)\n\nclass Solution {\n Map> memo = new HashMap<>();\n public List diffWaysToCompute(String expression) {\n List res = new LinkedList<>();\n if(memo.containsKey(expression)) return memo.get(expression);\n\n for(int i = 0; i left = diffWaysToCompute(expression.substring(0, i));\n List right = diffWaysToCompute(expression.substring(i+1));\n\n //conquer\n for(int a : left){\n for(int b : right){\n if(c == '+'){\n res.add(a+b);\n }else if(c == '-'){\n res.add(a - b);\n }else if(c == '*'){\n res.add(a * b);\n }\n }\n }\n \n }\n }\n //base case, when there is no operator\n if(res.isEmpty()){\n res.add(Integer.parseInt(expression));\n }\n memo.put(expression, res);\n return res; \n }\n}", + "title": "241. Different Ways to Add Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators . You may return the answer in any order . The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 10^4 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= expression.length <= 20", + "expression consists of digits and the operator '+' , '-' , and '*' .", + "All the integer values in the input expression are in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"2-1-1\"Output:[0,2]Explanation:((2-1)-1) = 0 \n(2-(1-1)) = 2", + "image": null + }, + { + "text": "Example 2: Input:expression = \"2*3-4*5\"Output:[-34,-14,-10,-10,10]Explanation:(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 49 ms (Top 17.3%) | Memory: 13.54 MB (Top 39.1%)\n\nclass Solution(object):\n def diffWaysToCompute(self, input):\n m = {}\n return self.dfs(input, m)\n \n def dfs(self, input, m):\n if input in m:\n return m[input]\n if input.isdigit():\n m[input] = int(input)\n return [int(input)]\n ret = []\n for i, c in enumerate(input):\n if c in \"+-*\":\n l = self.diffWaysToCompute(input[:i])\n r = self.diffWaysToCompute(input[i+1:])\n ret.extend(eval(str(x)+c+str(y)) for x in l for y in r)\n m[input] = ret\n return ret", + "title": "241. Different Ways to Add Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0 , each of the stacks has the same maximum capacity. Implement the DinnerPlates class: Example 1:", + "description_images": [], + "constraints": [ + "DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity .", + "void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity .", + "int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.", + "int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty." + ], + "examples": [ + { + "text": "Example 1: Input[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]Output[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]Explanation:DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.", + "image": null + } + ], + "follow_up": null, + "solution": "class DinnerPlates {\n \n List> stack;\n PriorityQueue leftEmpty;\n PriorityQueue rightNonEmpty;\n int cap;\n public DinnerPlates(int capacity) {\n this.cap = capacity;\n this.stack = new ArrayList<>();\n this.leftEmpty = new PriorityQueue<>();\n this.rightNonEmpty = new PriorityQueue<>(Collections.reverseOrder());\n stack.add(new Stack<>());\n leftEmpty.offer(0);\n }\n \n public void push(int val) {\n while(!leftEmpty.isEmpty() && stack.get(leftEmpty.peek()).size() == cap) leftEmpty.poll();\n if(leftEmpty.isEmpty()) {\n stack.add(new Stack<>());\n leftEmpty.offer(stack.size() - 1);\n }\n Stack s = stack.get(leftEmpty.peek());\n if(s.isEmpty()) rightNonEmpty.offer(leftEmpty.peek());\n s.push(val);\n }\n \n public int pop() {\n while(!rightNonEmpty.isEmpty() && stack.get(rightNonEmpty.peek()).isEmpty()) rightNonEmpty.poll();\n if(rightNonEmpty.isEmpty()) {\n return -1;\n } \n Stack s = stack.get(rightNonEmpty.peek());\n if(s.size() == cap) leftEmpty.offer(rightNonEmpty.peek());\n return s.pop();\n }\n \n public int popAtStack(int index) {\n if(index >= stack.size()) return -1;\n Stack s = stack.get(index);\n if(s.isEmpty()) return -1;\n if(s.size() == cap) leftEmpty.offer(index);\n return s.pop();\n }\n}\n\n/**\n * Your DinnerPlates object will be instantiated and called as such:\n * DinnerPlates obj = new DinnerPlates(capacity);\n * obj.push(val);\n * int param_2 = obj.pop();\n * int param_3 = obj.popAtStack(index);\n */", + "title": "1172. Dinner Plate Stacks", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0 , each of the stacks has the same maximum capacity. Implement the DinnerPlates class: Example 1:", + "description_images": [], + "constraints": [ + "DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity .", + "void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity .", + "int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.", + "int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty." + ], + "examples": [ + { + "text": "Example 1: Input[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]Output[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]Explanation:DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.", + "image": null + } + ], + "follow_up": null, + "solution": "class DinnerPlates:\n\n def __init__(self, capacity: int):\n self.heap = []\n self.stacks = []\n self.capacity = capacity\n\n def push(self, val: int) -> None:\n if self.heap:\n index = heapq.heappop(self.heap)\n if index < len(self.stacks):\n self.stacks[index].append(val)\n else:\n self.push(val)\n elif self.stacks:\n lastStack = self.stacks[-1]\n if len(lastStack) != self.capacity:\n lastStack.append(val)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n \n def pop(self) -> int:\n while self.stacks:\n lastStack = self.stacks[-1]\n if lastStack:\n val = lastStack.pop()\n if not lastStack:\n self.stacks.pop()\n return val\n else:\n self.stacks.pop()\n return -1\n\n def popAtStack(self, index: int) -> int:\n if index == len(self.stacks) - 1:\n return self.pop()\n if index < len(self.stacks):\n stack = self.stacks[index]\n if stack:\n val = stack.pop()\n heapq.heappush(self.heap, index)\n return val\n return -1\n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)\n", + "title": "1172. Dinner Plate Stacks", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the array orders , which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerName i ,tableNumber i ,foodItem i ] where customerName i is the name of the customer, tableNumber i is the table customer sit at, and foodItem i is the item customer orders. Return the restaurant's “ display table ” . The “ display table ” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= orders.length <= 5 * 10^4", + "orders[i].length == 3", + "1 <= customerName i .length, foodItem i .length <= 20", + "customerName i and foodItem i consist of lowercase and uppercase English letters and the space character.", + "tableNumber i is a valid integer between 1 and 500 ." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]Output:[[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]]Explanation:The displaying table looks like:Table,Beef Burrito,Ceviche,Fried Chicken,Water3 ,0 ,2 ,1 ,0\n5 ,0 ,1 ,0 ,1\n10 ,1 ,0 ,0 ,0\nFor the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\nFor the table 5: Carla orders \"Water\" and \"Ceviche\".\nFor the table 10: Corina orders \"Beef Burrito\".", + "image": null + }, + { + "text": "Example 2: Input:orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]Output:[[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]]Explanation:For the table 1: Adam and Brianna order \"Canadian Waffles\".\nFor the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".", + "image": null + }, + { + "text": "Example 3: Input:orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]Output:[[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 157 ms (Top 14.06%) | Memory: 126.7 MB (Top 62.50%)\nclass Solution {\n public List> displayTable(List> orders) {\n List> ans = new ArrayList<>();\n List head = new ArrayList<>();\n head.add(\"Table\");\n Map> map = new TreeMap<>();\n for(List s: orders){\n if(!head.contains(s.get(2))) head.add(s.get(2));\n int tbl = Integer.parseInt(s.get(1));\n map.putIfAbsent(tbl, new TreeMap<>());\n if(map.get(tbl).containsKey(s.get(2))){\n Map m = map.get(tbl);\n m.put(s.get(2), m.getOrDefault(s.get(2), 0)+1);\n }else{\n map.get(tbl).put(s.get(2), 1);\n }\n }\n String[] arr = head.toArray(new String[0]);\n Arrays.sort(arr, 1, head.size());\n head = Arrays.asList(arr);\n ans.add(head);\n\n for(Map.Entry> entry: map.entrySet()){\n List l = new ArrayList<>();\n l.add(entry.getKey() + \"\");\n Map m = entry.getValue();\n for(int i=1; i List[List[str]]:\n column = ['Table']\n dish = []\n table_dict = {}\n for order_row in orders : \n if order_row[-1] not in dish :\n dish.append(order_row[-1])\n \n for order_row in orders :\n if order_row[1] not in table_dict.keys() :\n table_dict[order_row[1]] = {}\n for food in dish : \n table_dict[order_row[1]][food] = 0 \n table_dict[order_row[1]][order_row[-1]] += 1\n else : \n table_dict[order_row[1]][order_row[-1]] += 1 \n \n dish.sort()\n column = column + dish \n ans = [column]\n table = []\n childDict = {}\n for key in sorted(table_dict.keys()) : \n table.append(int(key))\n childDict[key] = []\n for value in column : \n if value != 'Table' :\n childDict[key].append(str(table_dict[key][value]))\n table.sort()\n output = [ans[0]]\n for table_num in table : \n childList = [str(table_num)]\n output.append(childList + childDict[str(table_num)])\n return output \n", + "title": "1418. Display Table of Food Orders in a Restaurant", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n . The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg" + ], + "constraints": [ + "1 <= n <= 10^4", + "distance.length == n", + "0 <= start, destination < n", + "0 <= distance[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [1,2,3,4], start = 0, destination = 1Output:1Explanation:Distance between 0 and 1 is 1 or 9, minimum is 1.", + "image": null + }, + { + "text": "Example 2: Input:distance = [1,2,3,4], start = 0, destination = 2Output:3Explanation:Distance between 0 and 2 is 3 or 7, minimum is 3.", + "image": null + }, + { + "text": "Example 3: Input:distance = [1,2,3,4], start = 0, destination = 3Output:4Explanation:Distance between 0 and 3 is 6 or 4, minimum is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 7.93%) | Memory: 42.8 MB (Top 57.93%)\nclass Solution {\n public int distanceBetweenBusStops(int[] distance, int start, int destination) {\n int firstDistance = 0;\n int secondDistance = 0;\n if (start < destination) {\n //check clockwise rotation\n for (int i = start; i < destination; i++)\n firstDistance += distance[i];\n //check clockwise rotation from destination to end\n for (int i = destination; i < distance.length; i++)\n secondDistance += distance[i];\n //continues checking till start (if needed)\n for (int i = 0; i < start; i++)\n secondDistance += distance[i];\n }\n else {\n for (int i = start; i < distance.length; i++)\n firstDistance += distance[i];\n for (int i = 0; i < destination; i++)\n firstDistance += distance[i];\n for (int i = start - 1; i >= destination; i--)\n secondDistance += distance[i];\n }\n return Math.min(firstDistance, secondDistance);\n }\n}", + "title": "1184. Distance Between Bus Stops", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n . The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg", + "https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg" + ], + "constraints": [ + "1 <= n <= 10^4", + "distance.length == n", + "0 <= start, destination < n", + "0 <= distance[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [1,2,3,4], start = 0, destination = 1Output:1Explanation:Distance between 0 and 1 is 1 or 9, minimum is 1.", + "image": null + }, + { + "text": "Example 2: Input:distance = [1,2,3,4], start = 0, destination = 2Output:3Explanation:Distance between 0 and 2 is 3 or 7, minimum is 3.", + "image": null + }, + { + "text": "Example 3: Input:distance = [1,2,3,4], start = 0, destination = 3Output:4Explanation:Distance between 0 and 3 is 6 or 4, minimum is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n # switch start and destination if destination is before start\n if start>destination: \n start,destination=destination,start\n #find minimum for clockwise and counterclockwise direction\n return min(sum(distance[start:destination]),sum(distance[:start]+distance[destination:]))", + "title": "1184. Distance Between Bus Stops", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a warehouse, there is a row of barcodes, where the i th barcode is barcodes[i] . Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= barcodes.length <= 10000", + "1 <= barcodes[i] <= 10000" + ], + "examples": [ + { + "text": "Example 1: Input:barcodes = [1,1,1,2,2,2]Output:[2,1,2,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:barcodes = [1,1,1,1,2,2,3,3]Output:[1,3,1,3,1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] rearrangeBarcodes(int[] barcodes) {\n \n if(barcodes.length <= 2){\n return barcodes ; //Problem says solution always exist.\n }\n \n Map count = new HashMap<>();\n Integer maxKey = null; // Character having max frequency\n \n for(int i: barcodes){\n count.put(i, count.getOrDefault(i, 0) + 1);\n if(maxKey == null || count.get(i) > count.get(maxKey)){\n maxKey = i;\n }\n }\n \n int pos = 0;\n \n //Fill maxChar\n int curr = count.get(maxKey);\n while(curr-- > 0){\n barcodes[pos] = maxKey;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n \n count.remove(maxKey); // Since that character is done, we don't need to fill it again\n \n //Fill the remaining Characters.\n for(int key: count.keySet()){\n curr = count.get(key);\n \n while(curr-- > 0){\n barcodes[pos] = key;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n }\n \n return barcodes;\n }\n}\n", + "title": "1054. Distant Barcodes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a warehouse, there is a row of barcodes, where the i th barcode is barcodes[i] . Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= barcodes.length <= 10000", + "1 <= barcodes[i] <= 10000" + ], + "examples": [ + { + "text": "Example 1: Input:barcodes = [1,1,1,2,2,2]Output:[2,1,2,1,2,1]", + "image": null + }, + { + "text": "Example 2: Input:barcodes = [1,1,1,1,2,2,3,3]Output:[1,3,1,3,1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1287 ms (Top 5.56%) | Memory: 16.2 MB (Top 67.41%)\n\nimport heapq\n\nclass Solution:\n\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n barcodes_counter = Counter(barcodes)\n if len(barcodes_counter) == len(barcodes):\n return barcodes\n\n barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ]\n heapq.heapify(barcodes_heapq)\n\n idx, prev_count, prev_barcode = 0, 0, 0\n while barcodes_heapq:\n (curr_count, curr_barcode) = heapq.heappop(barcodes_heapq)\n\n barcodes[idx] = curr_barcode\n idx += 1\n curr_count += 1\n\n if prev_count:\n heapq.heappush(barcodes_heapq, (prev_count, prev_barcode))\n\n prev_count, prev_barcode = curr_count, curr_barcode\n\n return barcodes\n", + "title": "1054. Distant Barcodes", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2000", + "text has only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abcabcabc\"Output:3Explanation:The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"leetcodeleetcode\"Output:2Explanation:The 2 substrings are \"ee\" and \"leetcodeleetcode\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int PRIME = 101;\n private static final int MOD = 1_000_000_007;\n public int distinctEchoSubstrings(String text) {\n int n = text.length();\n \n // dp[i][j] : hash value of text[i:j]\n int[][] dp = new int[n][n];\n for (int i = 0; i < n; i++) {\n long hash = 0;\n for (int j = i; j < n; j++) {\n hash = hash * PRIME + (text.charAt(j) - 'a' + 1);\n hash %= MOD;\n dp[i][j] = (int) hash;\n }\n }\n \n Set set = new HashSet<>();\n int res = 0;\n for (int i = 0; i < n-1; i++) {\n // compare text[i:j] with text[j+1: 2j-i+1]\n for (int j = i; 2*j - i + 1 < n; j++) {\n if (dp[i][j] == dp[j+1][2*j - i+1] && set.add(dp[i][j])) res++;\n }\n }\n \n return res;\n }\n}\n", + "title": "1316. Distinct Echo Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2000", + "text has only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abcabcabc\"Output:3Explanation:The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"leetcodeleetcode\"Output:2Explanation:The 2 substrings are \"ee\" and \"leetcodeleetcode\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctEchoSubstrings(self, s: str) -> int:\n hash=set()\n n=len(s)\n for i in range(n):\n for j in range(i):\n \n if (i-j)&1==1:\n \n k=(i-j)//2\n \n if s[j:j+k+1]==s[j+k+1:i+1]:\n hash.add(s[j:j+k+1]+s[j+k+1:i+1])\n return len(hash)\n \n \n \n \n", + "title": "1316. Distinct Echo Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return the number of distinct subsequences of s which equals t . A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not). The test cases are generated so that the answer fits on a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 1000", + "s and t consist of English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"rabbbit\", t = \"rabbit\"Output:3Explanation:As shown below, there are 3 ways you can generate \"rabbit\" from S.rabbbitrabbbitrabbbit", + "image": null + }, + { + "text": "Example 2: Input:s = \"babgbag\", t = \"bag\"Output:5Explanation:As shown below, there are 5 ways you can generate \"bag\" from S.babgbagbabgbagbabgbagbabgbagbabgbag", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]\n int f(int i,int j,String s,String t,int dp[][]){\n //If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found a subsequence)\n if(j<0)\n return 1;\n // if s gets exhausted then there are characters remaining in t which are yet to be matched as s got exhausted they could not be matched so there is no distinct subsequence\n if(i<0){\n return 0;\n }\n if(dp[i][j]!=-1)\n return dp[i][j];\n //If both the characters in s[i] and t[j] match then we have two case\n //1) Either consider the i'th character of s and find the remaining distinct subsequences of s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)\n //2) Do not consider s[i] so we are still at the same j'th character of t as we had not been considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1] i.e. f(i-1,j)\n if(s.charAt(i)==t.charAt(j)){\n dp[i][j]= f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp);\n }\n // If both of them do not match then we consider the 2nd case of matching characters\n else{\n dp[i][j]=f(i-1,j,s,t,dp);\n } \n return dp[i][j];\n }\n public int numDistinct(String s, String t) {\n int n=s.length();\n int m=t.length();\n int dp[][]=new int[n][m];\n for(int i=0;i int:\n if len(t) > len(s):\n return 0\n ls, lt = len(s), len(t)\n res = 0\n dp = [[0] * (ls + 1) for _ in range(lt + 1)]\n for j in range(ls + 1):\n dp[-1][j] = 1\n for i in range(lt - 1, -1, -1):\n for j in range(ls -1 , -1, -1):\n dp[i][j] = dp[i][j + 1]\n if s[j] == t[i]:\n\n dp[i][j] += dp[i + 1][j + 1]\n return dp[0][0]", + "title": "115. Distinct Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s, return the number of distinct non-empty subsequences of s . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"Output:7Explanation:The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:6Explanation:The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaa\"Output:3Explanation:The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 61.84%) | Memory: 42.7 MB (Top 63.49%)\nclass Solution {\n public int distinctSubseqII(String s) {\n int mod = (int)1e9+7;\n //For storing the last occurred index of a character.\n Integer li[] = new Integer[26];\n int n = s.length();\n int[] dp = new int[n+1];\n //one empty string possible for a string of length 0.\n dp[0]=1;\n char[] c = s.toCharArray();\n for(int i=1;i<=n;i++){\n //If the character is first occurred then 2 cases\n //Case 1 : we will not concat the character with previous subsequences\n //Case 2 : we will concat it.\n //Therefore, we multiply 2 with previous count.\n int curr = (2 * (dp[i - 1] % mod)) % mod;\n //Getting the int index from char for checking the previous occurrence in li[]\n int idx=c[i-1]-'a';\n //If previously occurred then we have to subtract the subsequences which are made\n //till li[idx-1] because they would be duplicated and counted twice unnecessarily\n if(li[idx]!=null) dp[i]=(curr -dp[li[idx]-1] +mod)%mod;\n else dp[i]= curr;\n li[idx]=i;\n }\n //Doing -1 because we don't have to count the empty string.\n return dp[n]-1;\n }\n }", + "title": "940. Distinct Subsequences II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s, return the number of distinct non-empty subsequences of s . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"Output:7Explanation:The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:6Explanation:The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaa\"Output:3Explanation:The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctSubseqII(self, s: str) -> int:\n #number of subsequences that startwith each alphabet\n startwith = [0]*26\n for c in s[::-1]:\n startwith[ord(c)-ord('a')] = sum(startwith) + 1\n return sum(startwith)%(10**9+7)\n", + "title": "940. Distinct Subsequences II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice has n candies, where the i th candy is of type candyType[i] . Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has ( n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n , return the maximum number of different types of candies she can eat if she only eats n / 2 of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == candyType.length", + "2 <= n <= 10^4", + "n is even.", + "-10^5 <= candyType[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:candyType = [1,1,2,2,3,3]Output:3Explanation:Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.", + "image": null + }, + { + "text": "Example 2: Input:candyType = [1,1,2,3]Output:2Explanation:Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.", + "image": null + }, + { + "text": "Example 3: Input:candyType = [6,6,6,6]Output:1Explanation:Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int distributeCandies(int[] candyType) {\n Set set = new HashSet<>();\n for (int type : candyType) set.add(type);\n return Math.min(set.size(), candyType.length / 2);\n }\n}\n", + "title": "575. Distribute Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice has n candies, where the i th candy is of type candyType[i] . Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat n / 2 of the candies she has ( n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array candyType of length n , return the maximum number of different types of candies she can eat if she only eats n / 2 of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == candyType.length", + "2 <= n <= 10^4", + "n is even.", + "-10^5 <= candyType[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:candyType = [1,1,2,2,3,3]Output:3Explanation:Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.", + "image": null + }, + { + "text": "Example 2: Input:candyType = [1,1,2,3]Output:2Explanation:Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.", + "image": null + }, + { + "text": "Example 3: Input:candyType = [6,6,6,6]Output:1Explanation:Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1728 ms (Top 12.88%) | Memory: 16.4 MB (Top 8.29%)\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(set(candyType)), (len(candyType)//2))", + "title": "575. Distribute Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We distribute some number of candies , to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies ) that represents the final distribution of candies. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candies <= 10^9", + "1 <= num_people <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:candies = 7, num_people = 4Output:[1,2,3,1]Explanation:On the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].", + "image": null + }, + { + "text": "Example 2: Input:candies = 10, num_people = 3Output:[5,2,3]Explanation:On the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] distributeCandies(int candies, int num_people) {\n int n=num_people;\n int a[]=new int[n];\n int k=1;\n while(candies>0){\n for(int i=0;i=k){\n a[i]+=k;\n candies-=k;\n k++;\n }\n else{\n a[i]+=candies;\n candies=0;\n break;\n }\n }\n }\n return a;\n }\n}", + "title": "1103. Distribute Candies to People", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We distribute some number of candies , to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies ) that represents the final distribution of candies. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candies <= 10^9", + "1 <= num_people <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:candies = 7, num_people = 4Output:[1,2,3,1]Explanation:On the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].", + "image": null + }, + { + "text": "Example 2: Input:candies = 10, num_people = 3Output:[5,2,3]Explanation:On the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n candy_dict = {}\n for i in range(num_people) : \n candy_dict[i] = 0 \n \n candy, i, totalCandy = 1, 0, 0\n while totalCandy < candies : \n if i >= num_people : \n i = 0\n if candies - totalCandy >= candy : \n candy_dict[i] += candy \n totalCandy += candy\n else : \n candy_dict[i] += candies - totalCandy\n totalCandy += candies - totalCandy\n i += 1 \n candy += 1 \n return candy_dict.values()\n", + "title": "1103. Distribute Candies to People", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= n <= 100", + "0 <= Node.val <= n", + "The sum of all Node.val is n ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,0,0]Output:2Explanation:From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree1.png" + }, + { + "text": "Example 2: Input:root = [0,3,0]Output:3Explanation:From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 58.67%) | Memory: 43.1 MB (Top 15.04%)\nclass Solution {\n int count = 0;\n public int helper(TreeNode root)\n {\n if(root == null)\n return 0;\n int left = helper(root.left);\n int right = helper(root.right);\n count+= Math.abs(left)+Math.abs(right);\n return (left+right+root.val-1);\n }\n public int distributeCoins(TreeNode root) {\n helper(root);\n return count;\n }\n}", + "title": "979. Distribute Coins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= n <= 100", + "0 <= Node.val <= n", + "The sum of all Node.val is n ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,0,0]Output:2Explanation:From the root of the tree, we move one coin to its left child, and one coin to its right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree1.png" + }, + { + "text": "Example 2: Input:root = [0,3,0]Output:3Explanation:From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.", + "image": "https://assets.leetcode.com/uploads/2019/01/18/tree2.png" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def distributeCoins(self, root: Optional[TreeNode]) -> int:\n \n def dfs(root):\n if not root:\n return 0,0\n \n net_left,left_walk = dfs(root.left)\n net_right,right_walk = dfs(root.right)\n \n\t\t\t# if any node has extra or deficiency in both cases there has to be a walk of abs(extra) or abs(deficiency)\n\t\t\t\n return net_left+net_right+(root.val-1), left_walk+right_walk+abs(net_left)+abs(net_right)\n return dfs(root)[1]\n", + "title": "979. Distribute Coins in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of n integers, nums , where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity , where quantity[i] is the amount of integers the i th customer ordered. Determine if it is possible to distribute nums such that: Return true if it is possible to distribute nums according to the above conditions . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The i th customer gets exactly quantity[i] integers,", + "The integers the i th customer gets are all equal , and", + "Every customer is satisfied." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], quantity = [2]Output:falseExplanation:The 0thcustomer cannot be given two different integers.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3], quantity = [2]Output:trueExplanation:The 0thcustomer is given [3,3]. The integers [1,2] are not used.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], quantity = [2,2]Output:trueExplanation:The 0thcustomer is given [1,1], and the 1st customer is given [2,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 89.01%) | Memory: 60.70 MB (Top 18.68%)\n\nclass Solution {\n public boolean canDistribute(int[] nums, int[] quantity) {\n \n // Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}\n Map freq = new HashMap<>();\n for (int num : nums)\n freq.put(num, freq.getOrDefault(num, 0)+1);\n \n // Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]\n int[] dist = new int[freq.size()];\n int idx = 0;\n for (int f : freq.values())\n dist[idx++] = f;\n \n\t\t// Fullfill the quantities from the biggest quantity to the smallest.\n // If the bigger quantity can't be filled, the program will stop as early as possible.\n Arrays.sort(quantity);\n return rec(dist, quantity, quantity.length-1);\n }\n \n // try to fullfill the j-th order quantity\n private boolean rec(int[] dist, int[] quantity, int j) {\n \n // stop condition. We've fulfilled all the order quantities.\n if (j == -1)\n return true;\n \n Set used = new HashSet<>();\n for (int i = 0 ; i < dist.length ; ++i) {\n\t\t\n\t\t\t// Use a set to make sure that \n\t\t\t// we don't distribute from the same amount to this j-th order for more than once.\n // With this check, the program reduces from 97ms to 25 ms.\n if (dist[i] >= quantity[j] && used.add(dist[i])) {\n dist[i] -= quantity[j];\n if (rec(dist, quantity, j-1))\n return true;\n dist[i] += quantity[j];\n }\n }\n return false;\n }\n}\n", + "title": "1655. Distribute Repeating Integers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n integers, nums , where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity , where quantity[i] is the amount of integers the i th customer ordered. Determine if it is possible to distribute nums such that: Return true if it is possible to distribute nums according to the above conditions . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The i th customer gets exactly quantity[i] integers,", + "The integers the i th customer gets are all equal , and", + "Every customer is satisfied." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], quantity = [2]Output:falseExplanation:The 0thcustomer cannot be given two different integers.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3], quantity = [2]Output:trueExplanation:The 0thcustomer is given [3,3]. The integers [1,2] are not used.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], quantity = [2,2]Output:trueExplanation:The 0thcustomer is given [1,1], and the 1st customer is given [2,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 584 ms (Top 98.04%) | Memory: 28.70 MB (Top 26.47%)\n\nfrom collections import Counter, defaultdict\n\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n quantity.sort(reverse=True)\n freqCounts = defaultdict(int, Counter(Counter(nums).values()))\n def backtrack(i: int = 0) -> bool:\n if i == len(quantity):\n return True\n \n for freq, count in list(freqCounts.items()):\n if freq >= quantity[i] and count > 0:\n freqCounts[freq] -= 1\n freqCounts[freq - quantity[i]] += 1\n if backtrack(i + 1):\n return True\n freqCounts[freq] += 1\n freqCounts[freq - quantity[i]] -= 1\n \n return False\n \n return backtrack()\n", + "title": "1655. Distribute Repeating Integers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s . Given the string s , the size of each group k and the character fill , return a string array denoting the composition of every group s has been divided into, using the above procedure . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.", + "For the last group, if the string does not have k characters remaining, a character fill is used to complete the group." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcdefghi\", k = 3, fill = \"x\"Output:[\"abc\",\"def\",\"ghi\"]Explanation:The first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdefghij\", k = 3, fill = \"x\"Output:[\"abc\",\"def\",\"ghi\",\"jxx\"]Explanation:Similar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 96.0%) | Memory: 42.30 MB (Top 49.23%)\n\nclass Solution {\n public String[] divideString(String s, int k, char fill) {\n //the size of result array\n String[] r = new String[(int) Math.ceil((s.length() * 1.0) / k)];\n int idx;\n //if the last one needs to be filled, then I do it\n if (s.length() % k != 0) {\n idx = s.length() - (s.length() % k);\n StringBuilder sb = new StringBuilder();\n sb.append(s.substring(idx));\n for (int i = sb.length(); i < k; i++) {\n sb.append(fill);\n }\n r[r.length - 1] = sb.toString();\n } else {\n //no need to fill the last, \n //that's why idx is equal to s length\n idx = s.length();\n }\n for (int i = 0; i < idx; i+=k) {\n r[i / k] = s.substring(i, i + k);\n }\n \n return r;\n }\n}\n", + "title": "2138. Divide a String Into Groups of Size k", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s . Given the string s , the size of each group k and the character fill , return a string array denoting the composition of every group s has been divided into, using the above procedure . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.", + "For the last group, if the string does not have k characters remaining, a character fill is used to complete the group." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcdefghi\", k = 3, fill = \"x\"Output:[\"abc\",\"def\",\"ghi\"]Explanation:The first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdefghij\", k = 3, fill = \"x\"Output:[\"abc\",\"def\",\"ghi\",\"jxx\"]Explanation:Similar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 66.92%) | Memory: 17.30 MB (Top 6.27%)\n\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n return [(s+k*fill)[i:i+k] for i in range(0,len(s),k)]\n", + "title": "2138. Divide a String Into Groups of Size k", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and a positive integer k , check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,4,5,6], k = 4Output:trueExplanation:Array can be divided into [1,2,3,4] and [3,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3Output:trueExplanation:Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], k = 3Output:falseExplanation:Each array should be divided in subarrays of size 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 127 ms (Top 67.88%) | Memory: 81.5 MB (Top 9.11%)\nclass Solution {\n public boolean isPossibleDivide(int[] nums, int k) {\n if (nums.length % k != 0) return false;\n Map countMap = new HashMap<>();\n for (int num : nums) {\n int count = countMap.getOrDefault(num, 0);\n countMap.put(num , count + 1);\n }\n Arrays.sort(nums);\n for (int num : nums) {\n if (!countMap.containsKey(num)) continue;\n int count = countMap.get(num);\n if (count == 1) countMap.remove(num);\n else countMap.put(num, count - 1);\n for (int i = 1; i < k; i++) {\n int next = num + i;\n if (!countMap.containsKey(next)) return false;\n count = countMap.get(next);\n if (count == 1) countMap.remove(next);\n else countMap.put(next, count - 1);\n }\n }\n return true;\n }\n}", + "title": "1296. Divide Array in Sets of K Consecutive Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums and a positive integer k , check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,4,5,6], k = 4Output:trueExplanation:Array can be divided into [1,2,3,4] and [3,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3Output:trueExplanation:Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], k = 3Output:falseExplanation:Each array should be divided in subarrays of size 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 304 ms (Top 99.22%) | Memory: 27.60 MB (Top 95.6%)\n\nclass Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n # if we see x, we expect to see x+1 later\n # and then x+2 after that\n # and then x+3 after that\n\n # so maybe we can enqueue (x+1, k-2) === (next number expected, count after x+1)\n # e.g. k == 2: find x, enqueue (x+1, 0)\n \n # for each x:\n # if front of queue has x, pop it. Re-enqueue with rem-1 if rem, else we finished a length k sequence\n # if front of queue has x' < x, we have a gap. return False\n # otherwise we found the start of a new sequence: append (x+1, k-2)\n # meaning we found x (1), we're looking for x+1 (another 1), and after that we should find another k-2 numbers\n\n if k == 1: return True # length 1 sequences are trivial\n\n nums.sort()\n q = deque()\n for n in nums:\n if not q or q[0][0] > n:\n q.append((n+1, k-2))\n elif q[0][0] == n:\n _, rem = q.popleft()\n if rem:\n q.append((n+1, rem-1))\n # else: end of len k sequence\n else:\n return False # found n > next expected, so we can't complete an earlier sequence\n\n if q:\n return False # expected at least one more element to finish a sequence\n else:\n return True\n", + "title": "1296. Divide Array in Sets of K Consecutive Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each element belongs to exactly one pair.", + "The elements present in a pair are equal ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3,2,2,2]Output:trueExplanation:There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:falseExplanation:There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 41.3%) | Memory: 44.12 MB (Top 6.5%)\n\nclass Solution {\n public boolean divideArray(int[] arr) {\n HashMap map = new HashMap<>();\n\n for (int i : arr) map.put(i, map.getOrDefault(i, 0) + 1);\n for (int i : map.keySet()) {\n if (map.get(i) % 2 != 0) return false;\n }\n return true;\n }\n}", + "title": "2206. Divide Array Into Equal Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each element belongs to exactly one pair.", + "The elements present in a pair are equal ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3,2,2,2]Output:trueExplanation:There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:falseExplanation:There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 213 ms (Top 19.18%) | Memory: 14.1 MB (Top 63.60%)\nclass Solution:\n\n def divideArray(self, nums: List[int]) -> bool:\n lena = len(nums)\n count = sum(num//2 for num in Counter(nums).values())\n return (lena/2 == count)\n", + "title": "2206. Divide Array Into Equal Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8 , and -2.7335 would be truncated to -2 . Return the quotient after dividing dividend by divisor . Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1] . For this problem, if the quotient is strictly greater than 2 31 - 1 , then return 2 31 - 1 , and if the quotient is strictly less than -2 31 , then return -2 31 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-2 31 <= dividend, divisor <= 2 31 - 1", + "divisor != 0" + ], + "examples": [ + { + "text": "Example 1: Input:dividend = 10, divisor = 3Output:3Explanation:10/3 = 3.33333.. which is truncated to 3.", + "image": null + }, + { + "text": "Example 2: Input:dividend = 7, divisor = -3Output:-2Explanation:7/-3 = -2.33333.. which is truncated to -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divide(int dividend, int divisor) {\n if(dividend == 1<<31 && divisor == -1){\n return Integer.MAX_VALUE;\n }\n boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false;\n \n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n \n int result = 0;\n while(dividend - divisor >= 0){\n int count = 0;\n while(dividend - (divisor << 1 << count) >= 0){\n count++;\n }\n result += 1 < int:\n # Solution 1 - bitwise operator << \n \"\"\"\n positive = (dividend < 0) is (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n\t\tif divisor == 1:\n quotient = dividend\n else: \n\t\t\tquotient = 0\n\t\t\twhile dividend >= divisor:\n\t\t\t\ttemp, i = divisor, 1\n\t\t\t\twhile dividend >= temp:\n\t\t\t\t\tdividend -= temp\n\t\t\t\t\tquotient += i\n\t\t\t\t\ti <<= 1\n\t\t\t\t\ttemp <<= 1\n\n\t\tif not positive:\n\t\t\treturn max(-2147483648, -quotient)\n\t\telse:\n\t\t\treturn min(quotient, 2147483647) \n \"\"\"\n # Solution 2 - cumulative sum - faster than bitwise \n positive = (dividend < 0) == (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor) \n if divisor == 1:\n quotient = dividend\n else: \n quotient = 0\n _sum = divisor\n\n while _sum <= dividend:\n current_quotient = 1\n while (_sum + _sum) <= dividend:\n _sum += _sum\n current_quotient += current_quotient\n dividend -= _sum\n _sum = divisor\n quotient += current_quotient \n if not positive:\n return max(-2147483648, -quotient)\n else:\n return min(quotient, 2147483647) \n", + "title": "29. Divide Two Integers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choosing any x with 0 < x < n and n % x == 0 .", + "Replacing the number n on the chalkboard with n - x ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:trueExplanation:Alice chooses 1, and Bob has no more moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:falseExplanation:Alice chooses 1, Bob chooses 1, and Alice has no more moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean divisorGame(int n) {\n return n%2==0;\n }\n}\n", + "title": "1025. Divisor Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choosing any x with 0 < x < n and n % x == 0 .", + "Replacing the number n on the chalkboard with n - x ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:trueExplanation:Alice chooses 1, and Bob has no more moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:falseExplanation:Alice chooses 1, Bob chooses 1, and Alice has no more moves.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 78.15%) | Memory: 16.60 MB (Top 64.13%)\n\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return n%2 == 0\n", + "title": "1025. Divisor Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:5Explanation:The five different ways are show above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.50 MB (Top 29.41%)\n\nclass Solution {\n public int numTilings(int n) {\n long[] dp = new long[n + 3]; dp[0] = 1; dp[1] = 2; dp[2] = 5;\n for (int i = 3; i < n; i ++) {\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007;\n }\n return (int)dp[n - 1];\n }\n}\n", + "title": "790. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:5Explanation:The five different ways are show above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 35 ms (Top 93.5%) | Memory: 16.27 MB (Top 85.2%)\n\nclass Solution(object):\n def numTilings(self, n):\n dp = [1, 2, 5] + [0] * n\n for i in range(3, n):\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007\n return dp[n - 1]", + "title": "790. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"Output:\"Radiant\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"Output:\"Dire\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Two Queues Solution\n// Two queues to store the R index and D index.\n// If the senate can execute his right, the senate is alive and can execute in the next round.\n// Then we can add the senate back to the queue and process in the next round (idx + N).\n// Time complexity: O(N), each loop we add/remove 1 senate in the queue.\n// Space complexity: O(N)\nclass Solution {\n public String predictPartyVictory(String senate) {\n if (senate == null || senate.length() == 0) throw new IllegalArgumentException(\"Invalid input.\");\n final int N = senate.length();\n Queue queR = new ArrayDeque<>(); // store the R index\n Queue queD = new ArrayDeque<>(); // store the D index\n for (int i = 0; i < N; i++) {\n if (senate.charAt(i) == 'R') {\n queR.add(i);\n } else {\n queD.add(i);\n }\n }\n while (!queR.isEmpty() && !queD.isEmpty()) {\n int r = queR.poll();\n int d = queD.poll();\n if (r < d) { // R is alive in the next round.\n queR.add(r + N);\n } else { // D is alive in the next round.\n queD.add(d + N);\n }\n }\n return queR.isEmpty() ? \"Dire\" : \"Radiant\";\n }\n}\n", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"Output:\"Radiant\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"Output:\"Dire\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 92.53%) | Memory: 16.90 MB (Top 59.64%)\n\nfrom collections import deque\n\nclass Solution:\n def predictPartyVictory(self, senate: str) -> str:\n n = len(senate)\n radiant = deque()\n dire = deque()\n for i, s in enumerate(senate):\n if s == 'R':\n radiant.append(i)\n else:\n dire.append(i)\n while radiant and dire:\n r_idx = radiant.popleft()\n d_idx = dire.popleft()\n if r_idx < d_idx:\n radiant.append(r_idx + n)\n else:\n dire.append(d_idx + n)\n return \"Radiant\" if radiant else \"Dire\"\n\n", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon . The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess . Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == dungeon.length", + "n == dungeon[i].length", + "1 <= m, n <= 200", + "-1000 <= dungeon[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]Output:7Explanation:The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.", + "image": "https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg" + }, + { + "text": "Example 2: Input:dungeon = [[0]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer[][] min;\n public int calculateMinimumHP(int[][] dungeon) {\n min = new Integer[dungeon.length][dungeon[0].length];\n int answer = min(0, 0, dungeon);\n return Math.max(answer, 1);\n }\n public int min(int i, int j, int[][] dungeon){\n if(i > dungeon.length - 1 || j > dungeon[0].length - 1) return 400000;\n if(i == dungeon.length - 1 && j == dungeon[0].length - 1) return - dungeon[i][j] + 1; \n if(min[i][j] == null){\n int down = min(i + 1, j, dungeon);\n int right = min(i, j + 1, dungeon);\n min[i][j] = Math.min(Math.max(right, 1), Math.max(down, 1)) - dungeon[i][j];\n }\n return min[i][j];\n }\n}\n", + "title": "174. Dungeon Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon . The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess . Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == dungeon.length", + "n == dungeon[i].length", + "1 <= m, n <= 200", + "-1000 <= dungeon[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]Output:7Explanation:The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.", + "image": "https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg" + }, + { + "text": "Example 2: Input:dungeon = [[0]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n\n\tdef calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n\n\t\tdp = defaultdict(lambda: inf)\n\t\tdp[(len(dungeon), len(dungeon[0]) - 1)] = 1\n\n\t\tfor i in range(len(dungeon) - 1, -1, -1):\n\n\t\t\tfor j in range(len(dungeon[0]) - 1, -1, -1):\n\n\t\t\t\tdp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i][j]\n\n\t\t\t\tif dp[(i, j)] <= 0:\n\t\t\t\t\tdp[(i, j)] = 1\n\n\t\treturn dp[(0, 0)]", + "title": "174. Dungeon Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a fixed-length integer array arr , duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,2,3,0,4,5,0]Output:[1,0,0,2,3,0,0,4]Explanation:After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3]Output:[1,2,3]Explanation:After calling your function, the input array is modified to: [1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n // Time Complexity = O(n)\n // Space Complexity = O(1)\n \n public void duplicateZeros(int[] arr) {\n \n // Loop through the array\n for(int i = 0; i < arr.length; i++) {\n \n // Trigger Condition \n if(arr[i] ==0) {\n int j; // auxilliary variable for swapping \n for(j = arr.length-2; j>=i+1; j--) {\n arr[j+1] = arr[j]; // Shift each element by one space\n }\n arr[j+1] = 0; // Duplicating the zero on the consecutive index of i\n i++; // Skipping the duplicated zero index in the array \n }\n }\n } \n}\n", + "title": "1089. Duplicate Zeros", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a fixed-length integer array arr , duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,2,3,0,4,5,0]Output:[1,0,0,2,3,0,0,4]Explanation:After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3]Output:[1,2,3]Explanation:After calling your function, the input array is modified to: [1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 107 ms (Top 60.66%) | Memory: 14.9 MB (Top 70.68%)\nclass Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n \"\"\"\n Do not return anything, modify arr in-place instead.\n \"\"\"\n l = len(arr)\n i,c=0,0\n while i a[1] - b[1]);\n // Max grow + plant time\n int maxTime = 0;\n for (int[] plant : plants) {\n maxTime = Math.max(maxTime, totalPlantTime + plant[1]);\n // After putting this plant at the end of the chain,\n // we can take the current plant time out of the total plant time\n totalPlantTime -= plant[0];\n }\n return maxTime;\n }\n}", + "title": "2136. Earliest Possible Day of Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime , of length n each: From the beginning of day 0 , you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "plantTime[i] is the number of full days it takes you to plant the i th seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total.", + "growTime[i] is the number of full days it takes the i th seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever." + ], + "examples": [ + { + "text": "Example 1: Input:plantTime = [1,4,3], growTime = [2,3,1]Output:9Explanation:The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 0, plant the 0thseed. The seed grows for 2 full days and blooms on day 3.\nOn days 1, 2, 3, and 4, plant the 1stseed. The seed grows for 3 full days and blooms on day 8.\nOn days 5, 6, and 7, plant the 2ndseed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/1.png" + }, + { + "text": "Example 2: Input:plantTime = [1,2,3,2], growTime = [2,1,2,1]Output:9Explanation:The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 1, plant the 0thseed. The seed grows for 2 full days and blooms on day 4.\nOn days 0 and 3, plant the 1stseed. The seed grows for 1 full day and blooms on day 5.\nOn days 2, 4, and 5, plant the 2ndseed. The seed grows for 2 full days and blooms on day 8.\nOn days 6 and 7, plant the 3rdseed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/2.png" + }, + { + "text": "Example 3: Input:plantTime = [1], growTime = [1]Output:2Explanation:On day 0, plant the 0thseed. The seed grows for 1 full day and blooms on day 2.\nThus, on day 2, all the seeds are blooming.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n data = list(zip(plantTime, growTime))\n data.sort(key=lambda x: -x[1]) #sort by grow time in descending order\n \n res = 0\n start_time = 0\n for plant, grow in data:\n start_time += plant\n res = max(res, start_time + grow)\n return res\n", + "title": "2136. Earliest Possible Day of Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Insert a character", + "Delete a character", + "Replace a character" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"horse\", word2 = \"ros\"Output:3Explanation:horse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"Output:5Explanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int minDistance(String word1, String word2) {\n int m = word1.length();\n int n = word2.length();\n int dp[][] = new int[m][n];\n for(int i=0 ; i rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"Output:5Explanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cache\n\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n \n @cache\n def dp(i, j):\n if i == 0:\n return j\n if j == 0:\n return i\n \n l1, l2 = word1[i - 1], word2[j - 1]\n if l1 != l2:\n return 1 + min(\n dp(i, j - 1), # Delete / insert j\n dp(i - 1, j), # Delete / insert i\n dp(i - 1, j - 1) # Replace i or j\n )\n return dp(i - 1, j - 1) \n \n return dp(m, n)\n", + "title": "72. Edit Distance", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:14Explanation:One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 32.31%) | Memory: 42.5 MB (Top 12.73%)\nclass Solution {\n public int twoEggDrop(int n) {\n int egg = 2; // hard coded to 2 eggs for this problem\n int[][] dp = new int[n+1][egg+1];\n return eggDrop(n, egg, dp);\n }\n\n int eggDrop(int n, int egg, int[][] dp) {\n if(n <= 2 || egg == 1) return n;\n if(dp[n][egg] != 0) return dp[n][egg];\n int min = n; // when you drop at each floor starting from 1\n for(int i = 1; i < n; i++) {\n int eggBreak = 1 + eggDrop(i-1, egg-1, dp); // drops needed if egg breaks at this floor\n int noEggBreak = 1 + eggDrop(n-i, egg, dp); // drops needed if egg does not break at this floor\n int moves = Math.max(eggBreak, noEggBreak); // since we want certain moves for n floor take max\n min = Math.min(min, moves);\n }\n dp[n][egg] = min;\n return min;\n }\n}", + "title": "1884. Egg Drop With 2 Eggs and N Floors", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:14Explanation:One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 37 ms (Top 76.06%) | Memory: 17.40 MB (Top 35.12%)\n\nclass Solution:\n def twoEggDrop(self, n: int) -> int:\n return ceil(((1+n*8)**0.5-1)/2)\n", + "title": "1884. Egg Drop With 2 Eggs and N Floors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]Output:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findSpecialInteger(int[] arr) {\n HashMaphm=new HashMap<>();\n int comp=arr.length/4;\n for (int i:arr)\n {\n if (!hm.containsKey(i)){hm.put(i,1);}\n else\n {\n int val=hm.get(i);\n val++;\n hm.put(i,val);\n }\n if (hm.get(i)>comp){return i;}\n }\n return 0;\n }\n}", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]Output:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findSpecialInteger(int[] arr) {\n if (arr.length == 1) {\n return arr[0];\n }\n int count = (int) Math.ceil(arr.length / 4);\n System.out.println(count);\n\n Map map = new HashMap<>();\n\n for (Integer i : arr) {\n map.put(i, map.getOrDefault(i, 0) + 1);\n if (map.get(i) > count) {\n return i;\n }\n }\n return -1;\n }\n}\n", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,6,6,6,6,7,10]Output:6", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l=len(arr)\n c=(l//4)+1\n d={}\n for i in arr:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n if d[i]>=c:\n return i\n", + "title": "1287. Element Appearing More Than 25% In Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n , where dist[i] is the initial distance in kilometers of the i th monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n , where speed[i] is the speed of the i th monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss , and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == dist.length == speed.length", + "1 <= n <= 10^5", + "1 <= dist[i], speed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,4], speed = [1,1,1]Output:3Explanation:In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,1,2,3], speed = [1,1,1,1]Output:1Explanation:In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + }, + { + "text": "Example 3: Input:dist = [3,2,4], speed = [5,3,2]Output:1Explanation:In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 72.0%) | Memory: 54.86 MB (Top 75.9%)\n\nclass Solution {\n public int eliminateMaximum(int[] dist, int[] speed) {\n \n int n = dist.length;\n \n int[] time = new int[n];\n \n for(int i = 0; i < n; i++){\n time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]);\n }\n \n Arrays.sort(time);\n \n int eliminated = 0;\n\t\t\n\t\t// At i = 0, minute = 0 ( therefore, we can use i in place of minute )\n \n for(int i = 0; i < n; i++){\n\t\t\t \n if(time[i] > i){ // At ith minute, eliminate the first monster arriving after ith minute\n eliminated++;\n }else{\n break; // Monster reached the city\n }\n }\n \n return eliminated;\n }\n}", + "title": "1921. Eliminate Maximum Number of Monsters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n , where dist[i] is the initial distance in kilometers of the i th monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n , where speed[i] is the speed of the i th monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss , and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == dist.length == speed.length", + "1 <= n <= 10^5", + "1 <= dist[i], speed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,4], speed = [1,1,1]Output:3Explanation:In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,1,2,3], speed = [1,1,1,1]Output:1Explanation:In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + }, + { + "text": "Example 3: Input:dist = [3,2,4], speed = [5,3,2]Output:1Explanation:In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])):\n if i > t:\n return i\n return len(dist) \n", + "title": "1921. Eliminate Maximum Number of Monsters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr : Given the integer n , return the last number that remains in arr . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.", + "Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.", + "Keep repeating the steps again, alternating left to right and right to left, until a single number remains." + ], + "examples": [ + { + "text": "Example 1: Input:n = 9Output:6Explanation:arr = [1, 2,3, 4,5, 6,7, 8,9]\narr = [2,4, 6,8]\narr = [2, 6]\narr = [6]", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lastRemaining(int n) {\n int head = 1;\n int remain = n;\n boolean left = true;\n int step =1;\n \n while(remain > 1){\n if(left || remain%2==1){\n head = head + step;\n }\n remain /= 2;\n step *= 2;\n left = !left;\n }\n return head;\n }\n}\n", + "title": "390. Elimination Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr : Given the integer n , return the last number that remains in arr . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.", + "Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.", + "Keep repeating the steps again, alternating left to right and right to left, until a single number remains." + ], + "examples": [ + { + "text": "Example 1: Input:n = 9Output:6Explanation:arr = [1, 2,3, 4,5, 6,7, 8,9]\narr = [2,4, 6,8]\narr = [2, 6]\narr = [6]", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lastRemaining(self, n: int) -> int:\n beg = 1\n len = n\n d = 1\n fromleft = True\n\n while len > 1:\n if(fromleft or len%2 == 1):\n beg += d\n d <<= 1\n len >>= 1\n fromleft = not fromleft\n \n return beg\n", + "title": "390. Elimination Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees employees where: Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "employees[i].id is the ID of the i th employee.", + "employees[i].importance is the importance value of the i th employee.", + "employees[i].subordinates is a list of the IDs of the direct subordinates of the i th employee." + ], + "examples": [ + { + "text": "Example 1: Input:employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1Output:11Explanation:Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg" + }, + { + "text": "Example 2: Input:employees = [[1,2,[5]],[5,-3,[]]], id = 5Output:-3Explanation:Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private Map idToIndex;\n\n private void populateIdToIndexMap(List employees) { \n for(int idx = 0; idx employees, int id) {\n int currEmpIdx = idToIndex.get(id);\n Employee currEmp = employees.get(currEmpIdx);\n int totalImportance = currEmp.importance;\n for(int child : currEmp.subordinates) {\n totalImportance += dfsGetImportance(employees, child);\n }\n \n return totalImportance;\n }\n \n public int getImportance(List employees, int id) {\n if(employees == null || employees.size() < 1) {\n return 0; \n }\n \n idToIndex = new HashMap<>();\n populateIdToIndexMap(employees);\n return dfsGetImportance(employees, id);\n }\n}\n", + "title": "690. Employee Importance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees employees where: Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "employees[i].id is the ID of the i th employee.", + "employees[i].importance is the importance value of the i th employee.", + "employees[i].subordinates is a list of the IDs of the direct subordinates of the i th employee." + ], + "examples": [ + { + "text": "Example 1: Input:employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1Output:11Explanation:Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg" + }, + { + "text": "Example 2: Input:employees = [[1,2,[5]],[5,-3,[]]], id = 5Output:-3Explanation:Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.", + "image": "https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 254 ms (Top 40.58%) | Memory: 15.6 MB (Top 60.31%)\n\"\"\"\n# Definition for Employee.\nclass Employee:\n def __init__(self, id: int, importance: int, subordinates: List[int]):\n self.id = id\n self.importance = importance\n self.subordinates = subordinates\n\"\"\"\n\nclass Solution:\n def dfs(self, graph, employees, empId, totalImportance, visited):\n totalImportance += graph[empId][0]\n visited.add(empId)\n\n for neighbour in graph[empId][1]:\n if neighbour not in visited:\n totalImportance = self.dfs(graph, employees, neighbour, totalImportance, visited)\n\n return totalImportance\n\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n graph = {}\n\n for employeeInfo in employees:\n empId, importance, suboordinates = employeeInfo.id, employeeInfo.importance, employeeInfo.subordinates\n graph[empId] = [importance, suboordinates]\n\n n = len(employees)\n\n if graph[id][1] == []:\n return graph[id][0]\n\n visited = set()\n totalImportance = 0\n totalImportance = self.dfs(graph, employees, id, totalImportance, visited)\n\n return totalImportance", + "title": "690. Employee Importance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk . Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution() Initializes the object of the system.", + "String encode(String longUrl) Returns a tiny URL for the given longUrl .", + "String decode(String shortUrl) Returns the original long URL for the given shortUrl . It is guaranteed that the given shortUrl was encoded by the same object." + ], + "examples": [ + { + "text": "Example 1: Input:url = \"https://leetcode.com/problems/design-tinyurl\"Output:\"https://leetcode.com/problems/design-tinyurl\"Explanation:Solution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Codec {\n\n // Encodes a URL to a shortened URL.\n public String encode(String longUrl) {\n return longUrl;\n }\n\n // Decodes a shortened URL to its original URL.\n public String decode(String shortUrl) {\n return shortUrl;\n }\n}\n", + "title": "535. Encode and Decode TinyURL", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk . Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution() Initializes the object of the system.", + "String encode(String longUrl) Returns a tiny URL for the given longUrl .", + "String decode(String shortUrl) Returns the original long URL for the given shortUrl . It is guaranteed that the given shortUrl was encoded by the same object." + ], + "examples": [ + { + "text": "Example 1: Input:url = \"https://leetcode.com/problems/design-tinyurl\"Output:\"https://leetcode.com/problems/design-tinyurl\"Explanation:Solution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Codec:\n\n def encode(self, longUrl):\n return longUrl\n\n def decode(self, shortUrl):\n return shortUrl\n", + "title": "535. Encode and Decode TinyURL", + "topic": "Database" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string. A string is encrypted with the following process: Note that in case a character of the string is not present in keys , the encryption process cannot be carried out, and an empty string \"\" is returned. A string is decrypted with the following process: Implement the Encrypter class: Example 1:", + "description_images": [], + "constraints": [ + "Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values , and dictionary .", + "String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.", + "int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Encrypter\", \"encrypt\", \"decrypt\"]\n[[['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]], [\"abcd\"], [\"eizfeiam\"]]Output[null, \"eizfeiam\", 2]ExplanationEncrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]);\nencrypter.encrypt(\"abcd\"); // return \"eizfeiam\". \n  // 'a' maps to \"ei\", 'b' maps to \"zf\", 'c' maps to \"ei\", and 'd' maps to \"am\".\nencrypter.decrypt(\"eizfeiam\"); // return 2. \n // \"ei\" can map to 'a' or 'c', \"zf\" maps to 'b', and \"am\" maps to 'd'. \n // Thus, the possible strings after decryption are \"abad\", \"cbad\", \"abcd\", and \"cbcd\". \n // 2 of those strings, \"abad\" and \"abcd\", appear in dictionary, so the answer is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Encrypter {\n \n Map encryptedDictCount;\n int[] keys;\n Set dictionary;\n String[] val;\n \n public Encrypter(char[] keys, String[] values, String[] dictionary) {\n this.keys = new int[26];\n encryptedDictCount = new HashMap<>();\n this.val = values.clone();\n this.dictionary = new HashSet<>(Arrays.asList(dictionary));\n \n for(int i=0; i str:\n output = ''\n for char in word1:\n output += self.hashmap[char]\n return output\n\n def decrypt(self, word2: str) -> int:\n return self.dictmap[word2]\n", + "title": "2227. Encrypt and Decrypt Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + " For example, 12 , 0 , and 123 .", + "For example, 12 , 0 , and 123 .", + " <.> For example, 0.5 , 1. , 2.12 , and 123.0001 .", + "For example, 0.5 , 1. , 2.12 , and 123.0001 .", + " <.> <(> <)> For example, 0.1(6) , 1.(9) , 123.00(1212) .", + "For example, 0.1(6) , 1.(9) , 123.00(1212) ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0.(52)\", t = \"0.5(25)\"Output:trueExplanation:Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0.1666(6)\", t = \"0.166(66)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"0.9(9)\", t = \"1.\"Output:trueExplanation:\"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.00 MB (Top 31.82%)\n\nclass Solution {\n\n private List ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999);\n\n public boolean isRationalEqual(String S, String T) {\n return Math.abs(computeValue(S) - computeValue(T)) < 1e-9;\n }\n\n private double computeValue(String s) {\n if (!s.contains(\"(\")) {\n return Double.valueOf(s);\n } else {\n double intNonRepeatingValue = Double.valueOf(s.substring(0, s.indexOf('(')));\n int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1;\n int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1;\n int repeatingValue = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')')));\n return intNonRepeatingValue + repeatingValue * Math.pow(0.1, nonRepeatingLength) * ratios.get(repeatingLength);\n }\n }\n}\n", + "title": "972. Equal Rational Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + " For example, 12 , 0 , and 123 .", + "For example, 12 , 0 , and 123 .", + " <.> For example, 0.5 , 1. , 2.12 , and 123.0001 .", + "For example, 0.5 , 1. , 2.12 , and 123.0001 .", + " <.> <(> <)> For example, 0.1(6) , 1.(9) , 123.00(1212) .", + "For example, 0.1(6) , 1.(9) , 123.00(1212) ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0.(52)\", t = \"0.5(25)\"Output:trueExplanation:Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0.1666(6)\", t = \"0.166(66)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"0.9(9)\", t = \"1.\"Output:trueExplanation:\"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 69 ms (Top 5.88%) | Memory: 14 MB (Top 23.53%)\nclass Solution:\n # inspired from:\n # https://coolconversion.com/math/recurring-decimals-as-a-fraction/\n # to which we wouldn't have access during interview.\n\n import typing\n def isRationalEqual(self, s: str, t: str) -> bool:\n\n # intuition:\n # write each numbes as fraction: num / den\n # then compare the two fractions.\n\n num1, den1 = self.toFraction(s)\n num2, den2 = self.toFraction(t)\n\n return den1 * num2 == den2 * num1\n\n def toFraction(self, s: str) -> typing.Tuple[int, int]:\n if \".\" not in s:\n return int(s), 1\n\n intp, frac = s.split(\".\")\n # decimal dot, but no repeating part:\n # xyz.abc = xyzabc / 1000\n if \"(\" not in frac:\n ifrac = int(frac) if len(frac) > 0 else 0\n num = int(intp) * (10 ** len(frac)) + ifrac\n den = 10 ** len(frac)\n return num, den\n\n # this is for cases like a.b(c)\n # let n = a.b(c)\n # then, 10^(len(b+c)) * n = abc.(c)\n # and 10^(len(b)) * n = ab.(c)\n # subtract the two, and solve for n:\n # n = (abc - ab) / (10^len(b + c) - 10^len(b))\n frac, repfrac = frac.split(\"(\")\n repfrac = repfrac[:-1]\n\n iintp = int(intp)\n ifrac = int(frac) if len(frac) > 0 else 0\n irep = int(repfrac)\n\n return (\n (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac),\n (10** len(frac+repfrac) - 10 **len(frac))\n )\n ```", + "title": "972. Equal Rational Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (R i , C j ) such that row R i and column C j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]Output:1Explanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]Output:3Explanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int equalPairs(int[][] grid) {\n HashMap map = new HashMap<>();\n int row = grid.length;\n int col = grid.length;\n for(int i = 0; i < row; i++){\n String res = \"\";\n for(int j = 0; j < col; j++){\n res += \"-\" + grid[i][j];\n }\n map.put(res, map.getOrDefault(res, 0) + 1);\n }\n int cnt = 0;\n for(int j = 0; j < col; j++){\n String res = \"\";\n for(int i = 0; i < row; i++){\n res += \"-\" + grid[i][j];\n }\n cnt += map.getOrDefault(res, 0);\n }\n return cnt;\n }\n}\n", + "title": "2352. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (R i , C j ) such that row R i and column C j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]Output:1Explanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]Output:3Explanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 467 ms (Top 64.2%) | Memory: 21.54 MB (Top 44.5%)\n\nclass Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n m = defaultdict(int)\n cnt = 0\n\n for row in grid:\n m[str(row)] += 1\n \n for i in range(len(grid[0])):\n col = []\n for j in range(len(grid)):\n col.append(grid[j][i])\n cnt += m[str(col)]\n return cnt\n", + "title": "2352. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two arrays of integers nums1 and nums2 , possibly of different lengths. The values in the arrays are between 1 and 6 , inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6 , inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2 . Return -1 ​​​​​ if it is not possible to make the sum of the two arrays equal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]Output:3Explanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,1,1,1,1,1], nums2 = [6]Output:-1Explanation:There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [6,6], nums2 = [1]Output:3Explanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 89.13%) | Memory: 97.8 MB (Top 84.45%)\nclass Solution {\n public int minOperations(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length;\n if (m > 6 * n || n > 6 * m) return -1;\n\n int sum1 = 0, sum2 = 0;\n for (int i : nums1) sum1 += i;\n for (int i : nums2) sum2 += i;\n\n int diff = sum1 - sum2;\n if (diff == 0) return 0;\n\n return (diff > 0 ? helper(nums1, nums2, diff)\n : helper(nums2, nums1, -diff));\n }\n\n private int helper(int[] nums1, int[] nums2, int diff) {\n // count[i] : frequency of numbers that can reduce the diff by i\n int[] count = new int[6];\n for (int num : nums1) count[num - 1]++;\n for (int num : nums2) count[6 - num]++;\n\n int res = 0;\n for (int i = 5; i > 0; i--) {\n int c = Math.min(count[i], diff / i + (diff % i == 0 ? 0 : 1));\n\n res += c;\n diff -= c * i;\n\n if (diff <= 0) break;\n }\n return res;\n }\n}", + "title": "1775. Equal Sum Arrays With Minimum Number of Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two arrays of integers nums1 and nums2 , possibly of different lengths. The values in the arrays are between 1 and 6 , inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6 , inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2 . Return -1 ​​​​​ if it is not possible to make the sum of the two arrays equal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]Output:3Explanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,1,1,1,1,1], nums2 = [6]Output:-1Explanation:There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [6,6], nums2 = [1]Output:3Explanation:You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max \"gain\" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the \"gain\" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1\n", + "title": "1775. Equal Sum Arrays With Minimum Number of Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array trees where trees[i] = [x i , y i ] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed . Return the coordinates of trees that are exactly located on the fence perimeter . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 3000", + "points[i].length == 2", + "0 <= x i , y i <= 100", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]Output:[[1,1],[2,0],[3,3],[2,4],[4,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg" + }, + { + "text": "Example 2: Input:points = [[1,2],[2,2],[4,2]]Output:[[4,2],[2,2],[1,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public static class Pair {\n int x;\n int y;\n \n Pair(int x, int y) {\n this.x = x;\n this.y = y;\n }\n \n }\n public int[][] outerTrees(int[][] trees) {\n List points=new ArrayList<>();\n for(int[] point:trees){\n points.add(new Pair(point[0],point[1])); \n }\n\n List res=new ArrayList<>();\n if(points.size()==1){\n return trees;\n }\n int n=points.size();\n Collections.sort(points,(a,b)->a.y==b.y?a.x-b.x:a.y-b.y);\n HashSet> dup=new HashSet<>();\n Stack hull=new Stack<>();\n \n hull.push(points.get(0));\n hull.push(points.get(1));\n \n for(int i=2;i=0;i--){\n Pair top=hull.pop();\n while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){\n top=hull.pop();\n }\n hull.push(top);\n hull.push(points.get(i));\n }\n\n for(Pair p:hull){\n ArrayList tmp=new ArrayList<>();\n tmp.add(p.x);\n tmp.add(p.y);\n if(dup.contains(tmp))continue;\n dup.add(tmp);\n res.add(p);\n }\n\n int[][] ans=new int[res.size()][2];\n int i=0;\n for(Pair p:res){\n ans[i][0]=p.x;\n ans[i][1]=p.y;\n i++;\n }\n \n return ans;\n \n }\n\n public int ccw(Pair a,Pair b,Pair c){\n double cp=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\n if(cp<0)return -1;\n else if(cp>0)return 1;\n else return 0;\n }\n}\n", + "title": "587. Erect the Fence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array trees where trees[i] = [x i , y i ] represents the location of a tree in the garden. You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed . Return the coordinates of trees that are exactly located on the fence perimeter . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 3000", + "points[i].length == 2", + "0 <= x i , y i <= 100", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]Output:[[1,1],[2,0],[3,3],[2,4],[4,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg" + }, + { + "text": "Example 2: Input:points = [[1,2],[2,2],[4,2]]Output:[[4,2],[2,2],[1,2]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\n \"\"\"Compute the convex hull of a set of points.\n\n Use Andrew's Monotone Chain algorithm, which has order O(N log(N)),\n where N is the number of input points.\n \"\"\"\n\n def cross(self, p, a, b):\n \"\"\"Return the cross product of the vectors p -> a and p -> b.\"\"\"\n return (a[0] - p[0]) * (b[1] - p[1]) \\\n - (a[1] - p[1]) * (b[0] - p[0])\n\n def _convex_hull_monotone_chain(self, points):\n \"\"\"Compute the convex hull of a list of points.\n \n Use Andrew's Monotone Chain algorithm, which is similar to Graham Scan,\n except that it doesn't require sorting the points by angle. This algorithm\n takes O(N log(N)) time, where N is len(points).\n \"\"\"\n # Ensure all points are unique, and sort lexicographically.\n points = list(sorted(set(points)))\n \n # If there are fewer than three points, they must form a hull.\n if len(points) <= 2:\n return points\n \n # Compute the lower and upper portion of the hull.\n lower, upper = [], []\n for out, it in ((lower, points), (upper, reversed(points))):\n for p in it:\n while len(out) >= 2 and self.cross(out[-2], out[-1], p) > 0:\n out.pop()\n out.append(p)\n\n # Concatenate the upper and lower hulls. Remove the last point from each\n # because those points are duplicated in both upper and lower.\n return lower[:-1] + upper[:-1]\n\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Find the convex hull of a collection of points.\n Return a list of indices of points forming the hull in clockwise order,\n starting with the leftmost point.\n \"\"\"\n # Convert input points to tuples.\n points = [tuple(p) for p in trees]\n ans = set()\n for point in self._convex_hull_monotone_chain(points):\n ans.add(point)\n return ans", + "title": "587. Erect the Fence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y) . We start at the source = [s x , s y ] square and want to reach the target = [t x , t y ] square. There is also an array of blocked squares, where each blocked[i] = [x i , y i ] represents a blocked square with coordinates (x i , y i ) . Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= blocked.length <= 200", + "blocked[i].length == 2", + "0 <= x i , y i < 10^6", + "source.length == target.length == 2", + "0 <= s x , s y , t x , t y < 10^6", + "source != target", + "It is guaranteed that source and target are not blocked." + ], + "examples": [ + { + "text": "Example 1: Input:blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]Output:falseExplanation:The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.", + "image": null + }, + { + "text": "Example 2: Input:blocked = [], source = [0,0], target = [999999,999999]Output:trueExplanation:Because there are no blocked cells, it is possible to reach the target square.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 724 ms (Top 51.43%) | Memory: 118.9 MB (Top 56.19%)\nclass Solution\n{\n static final int limit= 1000000;//boundary check\n\n public boolean isEscapePossible(int[][] blocked, int[] source, int[] target)\n {\n Set blocks= new HashSet<>();//HashSet to reduce the access time from O(N)-> O(1)\n\n for(int block[] : blocked)\n blocks.add(block[0]+ \"-\"+ block[1]);//putting the blocked node into the HashSet to access it at O(1)\n\n return bfsRange(source, target, blocks) && bfsRange(target, source, blocks);//sector division\n\n /*checking for both the case that the source is blocked or the target is blocked\n *if one of them is blocked we return false\n *since it is not practical to traverse each node, it will provide us with TLE\n */\n }\n\n /* Formula ::\n * shortest arc(displacement) of 1/4 sector of circel is a* 2^1/2\n * Area of the triangular sector is 1/2 * ( r{base} * r{height} )\n * Number of minimum shell to cover to move ahed of sector or boundary if possible = 0 + 1 + 2 + 3 + ... + 199 = 19900 (A.P)\n */\n\n public boolean bfsRange(int[] source, int[] target, Set blocks)\n {//we simply do bsf to check the circular quadrant 1/4th boundary of the sector\n\n Set visited= new HashSet<>();//visited hash set is so that we dont visit the visited cell again and the access time is O(1)\n Queue q= new LinkedList<>();//as we use in BT\n\n q.offer(source);//adding the starting BFS node to the Queue\n\n visited.add(source[0] + \"-\" + source[1]);//marking it as visited so that we dont traverse it again\n\n int count= 0;//number of node traverse total outside + inside\n while(!q.isEmpty())\n {//r m* w a*\n int temp[]= q.poll();//poling the node\n count+= 1;//counting the number of node traverse\n\n int trav[][]= {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};//Traversing in 4-Direction\n\n for(int direction[] : trav)\n {\n int i= temp[0] + direction[0];\n int j= temp[1] + direction[1];\n\n String key= (i+ \"-\"+ j);\n\n if(i < 0 || j < 0 || i >= limit || j >= limit || visited.contains(key) || blocks.contains(key))\n continue;//base case 1)checking the index 2)We dont visit the blocked node 3) we dont visit the visited node\n\n if(i == target[0] && j == target[1]) //when we find the target within the boundary(same sector or the quadrand) we just return true //best case saves a lot of time\n return true;\n\n visited.add(key);//marking the node as visited and adding it to the Queue\n\n q.offer(new int[]{i, j});//Expaning the search for path and adding the node\n\n if(count > 19900) //number of cell, crossing the boundary limit\n return true;//path exists from this node\n }\n }\n return false;//no path, to reach the node//boundary blocked us\n }\n}//Please do Upvote, it helps a lot", + "title": "1036. Escape a Large Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y) . We start at the source = [s x , s y ] square and want to reach the target = [t x , t y ] square. There is also an array of blocked squares, where each blocked[i] = [x i , y i ] represents a blocked square with coordinates (x i , y i ) . Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= blocked.length <= 200", + "blocked[i].length == 2", + "0 <= x i , y i < 10^6", + "source.length == target.length == 2", + "0 <= s x , s y , t x , t y < 10^6", + "source != target", + "It is guaranteed that source and target are not blocked." + ], + "examples": [ + { + "text": "Example 1: Input:blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]Output:falseExplanation:The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.", + "image": null + }, + { + "text": "Example 2: Input:blocked = [], source = [0,0], target = [999999,999999]Output:trueExplanation:Because there are no blocked cells, it is possible to reach the target square.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object): \n def isEscapePossible(self, blocked, source, target):\n \"\"\"\n :type blocked: List[List[int]]\n :type source: List[int]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n \n self.blocked = blocked\n self.source = source\n self.target = target\n \n #hashset of all blocked cells\n self.blocked_dict = {}\n \n #hashset of all visited edges\n self.edge_dict = {}\n \n #min/max x/y coords used for checking if an edge intersects the \"easy path\"\n self.min_x = min(self.source[0],self.target[0])\n self.max_x = max(self.source[0],self.target[0])\n self.min_y = min(self.source[1],self.target[1])\n self.max_y = max(self.source[1],self.target[1])\n \n #iterate through all cells in blocked,\n #and add each cell to the hash set\n for blocked_cell in blocked:\n if blocked_cell[0] in self.blocked_dict:\n self.blocked_dict[blocked_cell[0]][blocked_cell[1]] = None\n else:\n self.blocked_dict[blocked_cell[0]]={blocked_cell[1]:None}\n \n #for each cell in blocked\n for blocked_cell in self.blocked:\n \n #list the faces of blocked_cell that belong to an outline (4 of these at most)\n exposed_faces = self.enumerate_exposed_faces(blocked_cell[0],blocked_cell[1])\n \n #for each of these faces\n for face in exposed_faces:\n \n #check to see if we've already visited the edge while tracing out a loop\n x_edge = face[3]\n y_edge = face[4]\n edge_type = face[5]\n edge_visited = (x_edge in self.edge_dict \n and y_edge in self.edge_dict[x_edge]\n and edge_type in self.edge_dict[x_edge][y_edge])\n \n #if not, then we are looking at a new outline that we haven't seen before\n if not edge_visited: \n \n #count the number of edges of the outline that intersect the \"easy path\"\n num_intervening_edges = self.check_loop(face[0],face[1],face[2])\n \n #if the number of intersections is odd, a path does not exist. return false\n if num_intervening_edges%2==1:\n return False\n \n #if we could not find an outline the separates source from target, return true \n return True\n \n #lists the faces of occupied cell x,y that do not touch other occupied cells\n #these cell faces are edges that belong to one of the outlines that are formed \n #by painting in all occupied cells and grid boundaries\n #there are at most 4 such edges per cell\n def enumerate_exposed_faces(self,x,y):\n out_list = []\n \n #iterate through each neighbor of the cell\n for i in range(4):\n \n #if the neighbor cell is not occupied (blocked), then the corresponding face is a boundary face\n #in which case, add it to the list\n if not self.is_occupied(x+self.dxe[i],y+self.dye[i]):\n \n #there is a little bit of accounting going on to keep track of the correct edge coordinates\n #note that what we are really listing here is a starting grid point (not cell) + starting direction\n #and we also need to take into account that cells are indexed by their bottom left corner\n x_star = x+self.dxe2[i]\n y_star = y+self.dye2[i]\n x_edge_coords = x_star + self.dx_edge_coords[(i+2)%4]\n y_edge_coords = y_star + self.dy_edge_coords[(i+2)%4]\n \n out_list.append([x_star,y_star,i,x_edge_coords,y_edge_coords,self.edge_code_list[i]])\n return out_list\n \n #returns the number of times a given outline intersects the \"easy path\"\n #x_start,y_start is the starting gridpoint on the outline\n #starting_direction is... the starting direction (see __init__ for how it's coded)\n #is_cc is True if traversing in counterclockwise direction, False if clockwise\n #note that (counter)clockwise is referring to the winding number of the whole outline we are tracing\n def check_loop(self,x_start,y_start,starting_direction,is_cc = True):\n #correct the starting direction if it needs to be adjusted\n starting_direction = self.update_edge_direction(x_start,y_start,starting_direction,is_cc)\n direction = starting_direction\n \n x = x_start\n y = y_start\n \n num_intervening_edges = 0\n \n # return False\n touched_grid_boundary = False\n \n #iterate until we either touch the grid boundary\n #or return to where we started\n #this is a do-while, hence the True + break condition\n while True: \n #evaluate next grid point after moving along edge\n x_new = x+self.dxp[direction]\n y_new = y+self.dyp[direction]\n \n #if the edge is on the boundary, do not proceed. break out of the loop\n if self.edge_on_boundary(x,y,x_new,y_new):\n touched_grid_boundary = True\n break\n \n #otherwise, mark the edge as visited\n x_edge_coords = x + self.dx_edge_coords[direction]\n y_edge_coords = y + self.dy_edge_coords[direction]\n edge_coords = [x_edge_coords,y_edge_coords]\n \n #a little bit of a hassle since it's a dictionary of dictionaries of 1-2 element lists\n if x_edge_coords in self.edge_dict:\n if y_edge_coords in self.edge_dict[x_edge_coords]:\n if self.edge_code_list[direction] not in self.edge_dict[x_edge_coords][y_edge_coords]:\n self.edge_dict[x_edge_coords][y_edge_coords].append(self.edge_code_list[direction])\n else:\n self.edge_dict[x_edge_coords][y_edge_coords] = [self.edge_code_list[direction]] \n else:\n self.edge_dict[x_edge_coords] = {y_edge_coords: [self.edge_code_list[direction]]}\n \n \n #check to see if the edge intersects our \"easy path\" from source to target\n #if an intersection has occured, increment the intersection counter\n \n #checks to see if the edge intersects the horizontal portion of the easy path\n #for an edge to do so, it must be vertical, have the same y as source\n #and must have an x between source and target\n if self.edge_code_list[direction]=='v':\n if (self.min_x bool:\n \n dist = lambda x : abs(x[0] - target[0]) + abs(x[1] - target[1])\n\n return dist((0,0)) < min(dist(g) for g in ghosts)\n", + "title": "789. Escape The Ghosts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: You are situated in the top-left cell, (0, 0) , and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1) . Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse . If this is impossible, return -1 . If you can always reach the safehouse regardless of the minutes stayed, return 10^9 . Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 represents grass,", + "1 represents fire,", + "2 represents a wall that you and fire cannot pass through." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]Output:3Explanation:The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex1new.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]Output:-1Explanation:The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex2new2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,0,0],[2,2,0],[1,2,0]]Output:1000000000Explanation:The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex3new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 89.41%) | Memory: 45.50 MB (Top 60.0%)\n\nclass Solution {\n public int maximumMinutes(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n \n int[][] times = new int[m][n];\n for(int[] row : times) {\n Arrays.fill(row, Integer.MAX_VALUE);\n }\n \n int[] dir = new int[]{-1, 0, 1, 0, -1};\n \n\t\t// Queue for running BFS\n Deque fires = new ArrayDeque<>();\n\t\t\n for(int row = 0; row < m; row++) {\n for(int col = 0; col < n; col++) {\n if (grid[row][col] == 1) {\n times[row][col] = 0;\n fires.offer(new int[]{row, col});\n }\n }\n }\n \n int time = 1;\n while(!fires.isEmpty()) {\n int size = fires.size();\n \n for(int i = 0; i < size; i++) {\n int[] pos = fires.poll();\n \n for(int j = 0; j < 4; j++) {\n int x = pos[0] + dir[j];\n int y = pos[1] + dir[j + 1];\n \n if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 0 && times[x][y] == Integer.MAX_VALUE) {\n times[x][y] = time;\n fires.offer(new int[]{x, y});\n }\n }\n }\n \n time++;\n }\n \n fires.clear();\n \n int ans = Integer.MAX_VALUE;\n fires.offer(new int[]{0, 0});\n grid[0][0] = 2;\n\n time = 1;\n while(!fires.isEmpty() && grid[m - 1][n - 1] == 0) {\n int size = fires.size();\n \n int t = Integer.MIN_VALUE;\n \n for(int i = 0; i < size && grid[m - 1][n - 1] == 0; i++) {\n int[] pos = fires.poll();\n \n for(int j = 0; j < 4 && grid[m - 1][n - 1] == 0; j++) {\n \n int x = pos[0] + dir[j];\n int y = pos[1] + dir[j + 1];\n\n if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 0 && times[x][y] >= time) {\n if (x == m - 1 && y == n - 1) {\n t = times[x][y] - time;\n grid[x][y] = 2;\n break;\n }\n\n grid[x][y] = 2;\n fires.offer(new int[]{x, y});\n \n\t\t\t\t\t\t// if times[x][y] == Integer.MAX_VALUE, fire will never reach this cell and it will contribute maximum wait time\n t = Math.max(t, times[x][y] == Integer.MAX_VALUE ? 1000000000 : times[x][y] - time - 1);\n }\n }\n }\n \n ans = Math.min(ans, t);\n \n time++;\n }\n \n\t\t// You can never reach the safe house\n if (grid[m - 1][n - 1] != 2) {\n return -1;\n }\n \n\t\t// you can reach the safe house but fire can not\n if (times[m - 1][n - 1] == Integer.MAX_VALUE) {\n return 1000000000;\n }\n \n return ans == Integer.MAX_VALUE || ans == Integer.MIN_VALUE ? -1 : ans;\n }\n}\n", + "title": "2258. Escape the Spreading Fire", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values: You are situated in the top-left cell, (0, 0) , and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1) . Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse . If this is impossible, return -1 . If you can always reach the safehouse regardless of the minutes stayed, return 10^9 . Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 represents grass,", + "1 represents fire,", + "2 represents a wall that you and fire cannot pass through." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]Output:3Explanation:The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex1new.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]Output:-1Explanation:The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex2new2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,0,0],[2,2,0],[1,2,0]]Output:1000000000Explanation:The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/10/ex3new.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maximumMinutes(self, A):\n m, n = len(A), len(A[0])\n inf = 10 ** 10\n d = [[0,1],[1,0],[0,-1],[-1,0]]\n fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1]\n A = [[inf if a < 2 else -1 for a in r] for r in A]\n\n def bfs(queue, seen):\n for i, j, t in queue:\n if seen[i][j] < inf: continue\n seen[i][j] = t\n for di,dj in d:\n x, y = i + di, j + dj\n if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]:\n queue.append([x, y, t + 1])\n \n def die(t):\n seen = [[inf + 10] * n for i in range(m)]\n bfs([[0, 0, t]], seen)\n return seen[-1][-1] > A[-1][-1]\n\n bfs(fires, A)\n A[-1][-1] += 1\n return bisect_left(range(10**9 + 1), True, key=die) - 1\n", + "title": "2258. Escape the Spreading Fire", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a full binary tree with the following properties: The evaluation of a node is as follows: Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Leaf nodes have either the value 0 or 1 , where 0 represents False and 1 represents True .", + "Non-leaf nodes have either the value 2 or 3 , where 2 represents the boolean OR and 3 represents the boolean AND ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3,null,null,0,1]Output:trueExplanation:The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/05/16/example1drawio1.png" + }, + { + "text": "Example 2: Input:root = [0]Output:falseExplanation:The root node is a leaf node and it evaluates to false, so we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.4 MB (Top 93.53%)\nclass Solution {\n public boolean evaluateTree(TreeNode root) {\n if(root.val == 1)\n return true;\n if(root.val == 0)\n return false;\n if(root.val == 2)\n return evaluateTree(root.left) || evaluateTree(root.right);\n return evaluateTree(root.left) && evaluateTree(root.right);\n }\n}", + "title": "2331. Evaluate Boolean Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a full binary tree with the following properties: The evaluation of a node is as follows: Return the boolean result of evaluating the root node. A full binary tree is a binary tree where each node has either 0 or 2 children. A leaf node is a node that has zero children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Leaf nodes have either the value 0 or 1 , where 0 represents False and 1 represents True .", + "Non-leaf nodes have either the value 2 or 3 , where 2 represents the boolean OR and 3 represents the boolean AND ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3,null,null,0,1]Output:trueExplanation:The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/05/16/example1drawio1.png" + }, + { + "text": "Example 2: Input:root = [0]Output:falseExplanation:The root node is a leaf node and it evaluates to false, so we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 98 ms (Top 35.75%) | Memory: 14.7 MB (Top 20.30%)\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n def recur(node):\n if not node.left and not node.right: #leaf node\n return True if node.val == 1 else False\n left = recur(node.left)\n right = recur(node.right)\n if node.val == 2: #if node is or\n return left or right\n if node.val == 3: #if node is and\n return left and right\n return recur(root)", + "title": "2331. Evaluate Boolean Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]Output:[6.00000,0.50000,-1.00000,1.00000,-1.00000]Explanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]Output:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]Output:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double[] calcEquation(List> equations, double[] values, List> queries) {\n int len = equations.size();\n Map varMap = new HashMap<>();\n int varCnt = 0;\n for (int i = 0; i < len; i++) {\n if (!varMap.containsKey(equations.get(i).get(0))) {\n varMap.put(equations.get(i).get(0), varCnt++);\n }\n if (!varMap.containsKey(equations.get(i).get(1))) {\n varMap.put(equations.get(i).get(1), varCnt++);\n }\n }\n\n List[] edges = new List[varCnt];\n for (int i = 0; i < varCnt; i++) {\n edges[i] = new ArrayList<>();\n }\n\n for (int i = 0; i < len; i++) {\n int va = varMap.get(equations.get(i).get(0));\n int vb = varMap.get(equations.get(i).get(1));\n edges[va].add(new Pair(vb, values[i]));\n edges[vb].add(new Pair(va, 1.0 / values[i]));\n }\n\n int queriesCnt = queries.size();\n double[] ans = new double[queriesCnt];\n for (int i = 0; i < queriesCnt; i++) {\n List query = queries.get(i);\n double result = -1.0;\n if (varMap.containsKey(query.get(0)) && varMap.containsKey(query.get(1))) {\n int idxA = varMap.get(query.get(0));\n int idxB = varMap.get(query.get(1));\n if (idxA == idxB) {\n result = 1.0;\n } else {\n Queue points = new LinkedList<>();\n points.offer(idxA);\n double[] ratios = new double[varCnt];\n Arrays.fill(ratios, -1.0);\n ratios[idxA] = 1.0;\n while (!points.isEmpty() && ratios[idxB] < 0) {\n int cur = points.poll();\n for (Pair pair : edges[cur]) {\n int y = pair.index;\n double value = pair.value;\n if (ratios[y] < 0) {\n ratios[y] = ratios[cur] * value;\n points.offer(y);\n }\n }\n }\n\n result = ratios[idxB];\n }\n }\n\n ans[i] = result;\n }\n\n return ans;\n }\n\n class Pair {\n int index;\n double value;\n\n public Pair(int index, double value) {\n this.index = index;\n this.value = value;\n }\n }\n}\n", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]Output:[6.00000,0.50000,-1.00000,1.00000,-1.00000]Explanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]Output:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]Output:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n graph = dict()\n \n for (n, d), v in zip(equations, values):\n if n not in graph:\n graph[n] = []\n if d not in graph:\n graph[d] = []\n \n graph[n].append((d, v))\n graph[d].append((n, 1/v))\n \n def dfs(node, target, product, visited):\n if n not in graph or d not in graph:\n return -1\n \n if node == target:\n return product\n \n visited.add(node)\n \n for neighbor, quotient in graph[node]:\n if neighbor not in visited:\n soln = dfs(neighbor, target, product * quotient, visited)\n if soln != -1:\n return soln\n \n return -1\n \n solns = []\n for n, d in queries:\n solns.append(dfs(n, d, 1, set()))\n \n return solns", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation . Valid operators are + , - , * , and / . Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= tokens.length <= 10^4", + "tokens[i] is either an operator: \"+\" , \"-\" , \"*\" , or \"/\" , or an integer in the range [-200, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]Output:9Explanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]Output:6Explanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]Output:22Explanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int evalRPN(String[] tokens) {\n Stack stack = new Stack();\n for(String i: tokens){\n if(i.equals(\"+\") || i.equals(\"-\") || i.equals(\"*\") || i.equals(\"/\")){\n int a = stack.pop();\n int b = stack.pop();\n int temp = 0;\n if(i.equals(\"+\"))\n temp = a+b;\n else if(i.equals(\"-\"))\n temp = b-a;\n else if(i.equals(\"*\"))\n temp = a*b;\n else if(i.equals(\"/\"))\n temp = b/a;\n stack.push(temp);\n }\n else\n stack.push(Integer.parseInt(i));\n }\n return stack.pop();\n }\n}\n", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Evaluate the value of an arithmetic expression in Reverse Polish Notation . Valid operators are + , - , * , and / . Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= tokens.length <= 10^4", + "tokens[i] is either an operator: \"+\" , \"-\" , \"*\" , or \"/\" , or an integer in the range [-200, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]Output:9Explanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]Output:6Explanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]Output:22Explanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n stack = [] \n for i in tokens:\n if i == \"+\":\n stack[-1] = stack[-2] + stack.pop()\n elif i == \"-\":\n stack[-1] = stack[-2] - stack.pop()\n elif i == \"*\":\n stack[-1] = stack[-2] * stack.pop()\n elif i == \"/\":\n stack[-1] = int(stack[-2] / stack.pop())\n else:\n stack.append(int(i))\n \n return stack.pop()\n \n", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [key i , value i ] indicates that key key i has a value of value i . You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key key i , you will: Each key will appear at most once in your knowledge . There will not be any nested brackets in s . Return the resulting string after evaluating all of the bracket pairs. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, in the string \"(name)is(age)yearsold\" , there are two bracket pairs that contain the keys \"name\" and \"age\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]Output:\"bobistwoyearsold\"Explanation:The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]Output:\"hi?\"Explanation:As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]Output:\"yesyesyesaaa\"Explanation:The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 56.41%) | Memory: 91.9 MB (Top 81.62%)\nclass Solution {\n public String evaluate(String s, List> knowledge) {\n Map map = new HashMap<>();\n for(List ele : knowledge) {\n map.put(ele.get(0), ele.get(1));\n }\n StringBuilder sb = new StringBuilder();\n int b_start = -1;\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) == '(') {\n b_start = i;\n } else if(s.charAt(i) == ')') {\n String key = s.substring(b_start + 1, i);\n sb.append(map.getOrDefault(key, \"?\"));\n b_start = -1;\n } else {\n if(b_start == -1) {\n sb.append(s.charAt(i));\n }\n }\n }\n return sb.toString();\n }\n}", + "title": "1807. Evaluate the Bracket Pairs of a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [key i , value i ] indicates that key key i has a value of value i . You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key key i , you will: Each key will appear at most once in your knowledge . There will not be any nested brackets in s . Return the resulting string after evaluating all of the bracket pairs. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, in the string \"(name)is(age)yearsold\" , there are two bracket pairs that contain the keys \"name\" and \"age\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]Output:\"bobistwoyearsold\"Explanation:The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]Output:\"hi?\"Explanation:As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]Output:\"yesyesyesaaa\"Explanation:The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n knowledge = dict(knowledge)\n answer, start = [], None\n for i, char in enumerate(s):\n if char == '(': \n start = i + 1\n elif char == ')':\n answer.append(knowledge.get(s[start:i], '?'))\n start = None\n elif start is None: \n answer.append(char)\n return ''.join(answer)\n", + "title": "1807. Evaluate the Bracket Pairs of a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A binary tree is named Even-Odd if it meets the following conditions: Given the root of a binary tree, return true if the binary tree is Even-Odd , otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The root of the binary tree is at level index 0 , its children are at level index 1 , their children are at level index 2 , etc.", + "For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).", + "For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right)." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]Output:trueExplanation:The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png" + }, + { + "text": "Example 2: Input:root = [5,4,2,3,3,7]Output:falseExplanation:The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png" + }, + { + "text": "Example 3: Input:root = [5,9,1,3,5,7]Output:falseExplanation:Node values in the level 1 should be even integers.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 96.0%) | Memory: 66.10 MB (Top 31.24%)\n\nclass Solution {\n public boolean isEvenOddTree(TreeNode root) {\n Queue qu = new LinkedList<>();\n qu.add(root);\n boolean even = true; // maintain check for levels\n while(qu.size()>0){\n int size = qu.size();\n int prev = (even)?0:Integer.MAX_VALUE; // start prev with 0 to check strictly increasing and Integer_MAX_VALUE to check strictly decreasing \n while(size-->0){\n TreeNode rem = qu.remove();\n if(even){\n if(rem.val%2==0 || rem.val<=prev){ // false if value at even level is even or not strictly increasing \n return false;\n }\n }else{\n if(rem.val%2!=0 || rem.val>=prev){// false if value at odd level is odd or not strictly decreasing\n return false;\n }\n }\n if(rem.left!=null){\n qu.add(rem.left); \n }\n if(rem.right!=null){\n qu.add(rem.right);\n }\n prev=rem.val; //update previous\n \n }\n even = !even; //change level\n } \n return true;\n }\n}\n", + "title": "1609. Even Odd Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A binary tree is named Even-Odd if it meets the following conditions: Given the root of a binary tree, return true if the binary tree is Even-Odd , otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The root of the binary tree is at level index 0 , its children are at level index 1 , their children are at level index 2 , etc.", + "For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).", + "For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right)." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]Output:trueExplanation:The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png" + }, + { + "text": "Example 2: Input:root = [5,4,2,3,3,7]Output:falseExplanation:The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.", + "image": "https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png" + }, + { + "text": "Example 3: Input:root = [5,9,1,3,5,7]Output:falseExplanation:Node values in the level 1 should be even integers.", + "image": "https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png" + } + ], + "follow_up": null, + "solution": "from collections import deque\n# Runtime:838ms 44.05% || Memory: 40.8mb 57.22%\n# O(n) || O(h); where h is the height of the tree\n\nclass Solution:\n def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return False\n\n level = 0\n evenOddLevel = {0:1, 1:0}\n queue = deque([root])\n\n while queue:\n prev = 0\n for _ in range(len(queue)):\n currNode = queue.popleft()\n comparison = {0:prev < currNode.val, 1:prev > currNode.val}\n if currNode.val % 2 != evenOddLevel[level % 2]:\n return False\n else:\n if prev != 0 and comparison[level % 2]:\n prev = currNode.val\n elif prev == 0:\n prev = currNode.val\n else:\n return False\n\n if currNode.left:\n queue.append(currNode.left)\n\n if currNode.right:\n queue.append(currNode.right)\n\n level += 1\n\n return True\n", + "title": "1609. Even Odd Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an exam room with n seats in a single row labeled from 0 to n - 1 . When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0 . Design a class that simulates the mentioned exam room. Implement the ExamRoom class: Example 1:", + "description_images": [], + "constraints": [ + "ExamRoom(int n) Initializes the object of the exam room with the number of the seats n .", + "int seat() Returns the label of the seat at which the next student will set.", + "void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]Output[null, 0, 9, 4, 2, null, 5]ExplanationExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 87.99%) | Memory: 52.8 MB (Top 24.67%)\nclass ExamRoom {\n\n private final int max;\n private final TreeSet available;\n private final TreeSet taken;\n\n public ExamRoom(int n) {\n this.max = n - 1;\n this.available = new TreeSet<>((a, b) -> {\n var distA = getMinDistance(a);\n var distB = getMinDistance(b);\n return distA == distB ? a.s - b.s : distB - distA;\n });\n this.available.add(new Interval(0, max));\n this.taken = new TreeSet<>();\n }\n\n public int seat() {\n var inter = available.pollFirst();\n var idx = getInsertPosition(inter);\n taken.add(idx);\n if ((idx - 1) - inter.s >= 0)\n available.add(new Interval(inter.s, idx - 1));\n if (inter.e - (idx + 1) >= 0)\n available.add(new Interval(idx + 1, inter.e));\n return idx;\n }\n\n public void leave(int p) {\n taken.remove(p);\n var lo = taken.lower(p);\n if (lo == null)\n lo = -1;\n var hi = taken.higher(p);\n if (hi == null)\n hi = max + 1;\n available.remove(new Interval(lo + 1, p - 1));\n available.remove(new Interval(p + 1, hi - 1));\n available.add(new Interval(lo + 1, hi - 1));\n }\n\n private int getInsertPosition(Interval inter) {\n if (inter.s == 0)\n return 0;\n else if (inter.e == max)\n return max;\n else\n return inter.s + (inter.e - inter.s) / 2;\n }\n\n private int getMinDistance(Interval in) {\n return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2;\n }\n\n private final class Interval {\n private final int s;\n private final int e;\n\n Interval(int s, int e) {\n this.s = s;\n this.e = e;\n }\n\n @Override\n public String toString() {\n return \"[\" + s + \",\" + e + \"]\";\n }\n }\n}", + "title": "855. Exam Room", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an exam room with n seats in a single row labeled from 0 to n - 1 . When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0 . Design a class that simulates the mentioned exam room. Implement the ExamRoom class: Example 1:", + "description_images": [], + "constraints": [ + "ExamRoom(int n) Initializes the object of the exam room with the number of the seats n .", + "int seat() Returns the label of the seat at which the next student will set.", + "void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p ." + ], + "examples": [ + { + "text": "Example 1: Input[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]Output[null, 0, 9, 4, 2, null, 5]ExplanationExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 182 ms (Top 65.24%) | Memory: 20.7 MB (Top 5.08%)\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.N = n\n self.pq = []\n self.dict = {}\n self.addSegment(0, self.N - 1)\n\n def seat(self) -> int:\n start, end, distance = heapq.heappop(self.pq)\n self.dict.pop(start, None) #Remove old segment from dictionary\n self.dict.pop(end, None)\n\n if start == end:\n position = start\n\n elif start == 0:\n position = start\n right = self.addSegment(start + 1, end)\n\n elif end == self.N - 1:\n position = end\n left = self.addSegment(start, end - 1)\n\n elif end - start == 1: #ONLY ONE PLACE TO PUT\n position = start\n left = self.addSegment(start + 1, end)\n\n else:\n position = start + (end - start) // 2\n right = self.addSegment(start, position - 1)\n left = self.addSegment(position + 1, end)\n\n return position\n\n def leave(self, p: int) -> None:\n left = self.dict.get(p - 1, None)\n right = self.dict.get(p + 1, None)\n\n new_start = new_end = p\n\n if left:\n self.removeSegment(left)\n new_start = left.start\n\n if right:\n self.removeSegment(right)\n new_end = right.end\n\n self.addSegment(new_start, new_end)\n\n def addSegment(self, start, end):\n segment = Segment(start, end, self.N)\n self.dict[segment.start] = segment\n self.dict[segment.end] = segment\n heapq.heappush(self.pq, segment)\n\n def removeSegment(self, segment):\n self.dict.pop(segment.start, None)\n self.dict.pop(segment.end, None)\n self.pq.remove(segment)\n\nclass Segment():\n def __init__(self, start, end, N):\n self.start = start\n self.end = end\n self.distance = self.calculateDistance(start, end, N)\n\n def __lt__(self, other_segment):\n return self.distance > other_segment.distance if self.distance != other_segment.distance else self.start < other_segment.start\n\n def calculateDistance(self, start, end, N):\n if start == 0:\n return end\n\n if end == N - 1:\n return end - start\n\n else:\n return (end - start) // 2\n\n def __iter__(self):\n return iter((self.start, self.end, self.distance))", + "title": "855. Exam Room", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"Output:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"Output:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 81.25%) | Memory: 42.4 MB (Top 81.68%)\nclass Solution {\n public int titleToNumber(String columnTitle) {\n int n = columnTitle.length();\n int pow = 0;\n int res = 0;\n for(int i = n-1; i >= 0; i--) {\n char c = columnTitle.charAt(i);\n res += (c - 64) * Math.pow(26, pow);\n pow++;\n }\n\n return res;\n }\n}", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"Output:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"Output:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "def let_to_num(char):\n abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n return abc.index(char) + 1\n\nclass Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n ans = 0\n for i in range(len(columnTitle)):\n ans *= 26\n ans += let_to_num(columnTitle[i])\n return ans\n", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1Output:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701Output:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 36.84%) | Memory: 41.2 MB (Top 58.44%)\nclass Solution {\n public String convertToTitle(int columnNumber) {\n String ans = \"\";\n while(columnNumber > 0){\n columnNumber--;\n ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans;\n columnNumber /= 26;\n }\n return ans;\n }\n}", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1Output:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701Output:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def convertToTitle(self, num: int) -> str:\n\t\t# We make this lookup list, having A-Z in ascending order\n alpha = [chr(x) for x in range(ord(\"A\"), ord(\"Z\")+1)] # range(65, 90+1) -> 91-65 = 26\n res = \"\"\n\n while num > 0:\n res += alpha[(num-1)%26] # since 0 indexed list, num-1 % 26 gives the index of ch in alpha\n num = (num-1) // 26 \n return res[::-1]\n", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1 . Function calls are stored in a call stack : when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed . Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs , where logs[i] represents the i th log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\" . For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3 , and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2 . Note that a function can be called multiple times, possibly recursively . A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3 . Return the exclusive time of each function in an array, where the value at the i th index represents the exclusive time for the function with ID i . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "1 <= logs.length <= 500", + "0 <= function_id < n", + "0 <= timestamp <= 10^9", + "No two start events will happen at the same timestamp.", + "No two end events will happen at the same timestamp.", + "Each function has an \"end\" log for each \"start\" log." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]Output:[3,4]Explanation:Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.", + "image": "https://assets.leetcode.com/uploads/2019/04/05/diag1b.png" + }, + { + "text": "Example 2: Input:n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]Output:[8]Explanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]Output:[7,1]Explanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 31.28%) | Memory: 52.6 MB (Top 22.01%)\nclass Solution {\n\n //Time Complexity: O(N) for looping through logs\n //Space Complexity: O(N) for stack\n\n public int[] exclusiveTime(int n, List logs) {\n if (n == 0) {\n return new int[0];\n }\n\n int[] result = new int[n];\n\n Stack> stack = new Stack<>();\n\n for (String s : logs) {\n String[] sArr = s.split(\":\");\n int functionId = Integer.parseInt(sArr[0]);\n String startOrEnd = sArr[1];\n int timestamp = Integer.parseInt(sArr[2]);\n\n if (startOrEnd.equals(\"start\")) {\n\n //calculate previous in-progress length\n if (!stack.empty()) {\n Pair pair = stack.peek();\n int oldFunctionId = pair.getKey();\n int oldTimestamp = pair.getValue();\n result[oldFunctionId] += timestamp - oldTimestamp;\n }\n\n //add new start\n stack.push(new Pair(functionId, timestamp));\n } else {\n //calculate current length\n Pair pair = stack.pop();\n int oldTimestamp = pair.getValue();\n\n result[functionId] += timestamp - oldTimestamp + 1;\n\n //reset previous function's start\n if (!stack.empty()) {\n pair = stack.pop();\n Pair replacementPair = new Pair(pair.getKey(), timestamp + 1);\n stack.push(replacementPair);\n }\n }\n }\n\n return result;\n }\n}", + "title": "636. Exclusive Time of Functions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1 . Function calls are stored in a call stack : when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed . Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs , where logs[i] represents the i th log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\" . For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3 , and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2 . Note that a function can be called multiple times, possibly recursively . A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3 . Return the exclusive time of each function in an array, where the value at the i th index represents the exclusive time for the function with ID i . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "1 <= logs.length <= 500", + "0 <= function_id < n", + "0 <= timestamp <= 10^9", + "No two start events will happen at the same timestamp.", + "No two end events will happen at the same timestamp.", + "Each function has an \"end\" log for each \"start\" log." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]Output:[3,4]Explanation:Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.", + "image": "https://assets.leetcode.com/uploads/2019/04/05/diag1b.png" + }, + { + "text": "Example 2: Input:n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]Output:[8]Explanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]Output:[7,1]Explanation:Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 78 ms (Top 92.98%) | Memory: 14.2 MB (Top 33.69%)\nclass Solution:\n #T=O(n), S=O(d)\n #n=len of logs, d=depth of stack\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n #init result array to zeroes of length n (function ids)\n res = [0]*n\n stack = []\n #iterate through logs\n for log in logs:\n #split the log\n #function_id: start|end: timestamp\n log = log.split(\":\")\n #type cast function id and timestamp to int type\n id = int(log[0])\n timestamp = int(log[2])\n state = log[1]\n #detect start of a function call\n #stack[function_id, start_timestamp]\n if state == \"start\":\n #stack is non empty\n if stack:\n #get the time taken by last function so far\n res[stack[-1][0]] += timestamp - stack[-1][1]\n #append the current function_id and start timestamp to the stack\n stack.append([id, timestamp])\n else:\n #get the time consumed by current function\n #dont forget to add 1 as the last unit of time should be included\n res[id] += timestamp - stack.pop()[1] + 1\n if stack:\n #update the start time of last function in stack to get the cumulative result\n stack[-1][1] = timestamp + 1\n\n return res", + "title": "636. Exclusive Time of Functions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1) . You are given the integer n and an integer array startPos where startPos = [start row , start col ] indicates that a robot is initially at cell (start row , start col ) . You are also given a 0-indexed string s of length m where s[i] is the i th instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any i th instruction in s . It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the i th instruction in s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The next instruction will move the robot off the grid.", + "There are no more instructions left to execute." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, startPos = [0,1], s = \"RRDDLU\"Output:[1,5,4,3,1,0]Explanation:Starting from startPos and beginning execution from the ithinstruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st: \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th: \"U\". If moving up, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/1.png" + }, + { + "text": "Example 2: Input:n = 2, startPos = [1,1], s = \"LURD\"Output:[4,1,0,0]Explanation:- 0th: \"LURD\".\n- 1st: \"URD\".\n- 2nd: \"RD\".\n- 3rd: \"D\".", + "image": "https://assets.leetcode.com/uploads/2021/12/09/2.png" + }, + { + "text": "Example 3: Input:n = 1, startPos = [0,0], s = \"LRUD\"Output:[0,0,0,0]Explanation:No matter which instruction the robot begins execution from, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 101 ms (Top 24.39%) | Memory: 46.7 MB (Top 33.10%)\nclass Solution {\n public int[] executeInstructions(int n, int[] startPos, String s) {\n //Make array of length equal to string length\n int ans[]=new int[s.length()];\n\n //Now use two for loops\n for(int i=0;i=n || yIndex<0 || yIndex>=n){\n break;\n }\n else{\n countMoves++;\n }\n }\n\n ans[i]=countMoves;\n\n }\n return ans;\n\n }\n}", + "title": "2120. Execution of All Suffix Instructions Staying in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1) . You are given the integer n and an integer array startPos where startPos = [start row , start col ] indicates that a robot is initially at cell (start row , start col ) . You are also given a 0-indexed string s of length m where s[i] is the i th instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any i th instruction in s . It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the i th instruction in s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The next instruction will move the robot off the grid.", + "There are no more instructions left to execute." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, startPos = [0,1], s = \"RRDDLU\"Output:[1,5,4,3,1,0]Explanation:Starting from startPos and beginning execution from the ithinstruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st: \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th: \"U\". If moving up, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/1.png" + }, + { + "text": "Example 2: Input:n = 2, startPos = [1,1], s = \"LURD\"Output:[4,1,0,0]Explanation:- 0th: \"LURD\".\n- 1st: \"URD\".\n- 2nd: \"RD\".\n- 3rd: \"D\".", + "image": "https://assets.leetcode.com/uploads/2021/12/09/2.png" + }, + { + "text": "Example 3: Input:n = 1, startPos = [0,0], s = \"LRUD\"Output:[0,0,0,0]Explanation:No matter which instruction the robot begins execution from, it would move off the grid.", + "image": "https://assets.leetcode.com/uploads/2021/12/09/3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:\n result = []\n for idx in range(len(s)):\n count, row, col = 0, startPos[0],startPos[1]\n while idx < len(s):\n if s[idx] == 'D':\n row += 1\n if row >= n:\n break\n count += 1\n elif s[idx] == 'U':\n row -= 1\n if row < 0:\n break\n count += 1\n elif s[idx] == 'R':\n col += 1\n if col >= n:\n break\n count += 1\n else:\n col -= 1\n if col < 0:\n break\n count += 1\n idx += 1\n result.append(count)\n return result\n", + "title": "2120. Execution of All Suffix Instructions Staying in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string num that contains only digits and an integer target , return all possibilities to insert the binary operators '+' , '-' , and/or '*' between the digits of num so that the resultant expression evaluates to the target value . Note that operands in the returned expressions should not contain leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10", + "num consists of only digits.", + "-2 31 <= target <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"123\", target = 6Output:[\"1*2*3\",\"1+2+3\"]Explanation:Both \"1*2*3\" and \"1+2+3\" evaluate to 6.", + "image": null + }, + { + "text": "Example 2: Input:num = \"232\", target = 8Output:[\"2*3+2\",\"2+3*2\"]Explanation:Both \"2*3+2\" and \"2+3*2\" evaluate to 8.", + "image": null + }, + { + "text": "Example 3: Input:num = \"3456237490\", target = 9191Output:[]Explanation:There are no expressions that can be created from \"3456237490\" to evaluate to 9191.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 142 ms (Top 13.4%) | Memory: 44.41 MB (Top 73.2%)\n\nclass Solution {\n String s;\n Listresult;\n int target;\n public void operator(int i,int prev,long prod,long mid,String exp,Listl){\n if(i==l.size()){\n if(mid+prod==target)\n result.add(exp);\n return;\n }\n if(prev==-1){\n operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+\"*\"+l.get(i),l);\n }else if(prev==1){\n operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+\"*\"+l.get(i),l);\n }else{\n operator(i+1,0,prod*l.get(i),mid,exp+\"*\"+l.get(i),l);\n }\n operator(i+1,-1,0,mid+prod-l.get(i),exp+\"-\"+l.get(i),l);\n operator(i+1,1,0,mid+prod+l.get(i),exp+\"+\"+l.get(i),l);\n }\n public void rec(int in,Listl){\n if(in==s.length()){\n operator(1,1,0,l.get(0),l.get(0)+\"\",l);\n return;\n }\n if(s.charAt(in)=='0'){\n l.add(0L);\n rec(in+1,l);\n l.remove(l.size()-1);\n }else{\n for(int i=in;i addOperators(String num, int target) {\n result=new ArrayList<>();\n this.s=num;\n this.target=target;\n rec(0,new ArrayList<>(30));\n return result;\n }\n}", + "title": "282. Expression Add Operators", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string num that contains only digits and an integer target , return all possibilities to insert the binary operators '+' , '-' , and/or '*' between the digits of num so that the resultant expression evaluates to the target value . Note that operands in the returned expressions should not contain leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10", + "num consists of only digits.", + "-2 31 <= target <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"123\", target = 6Output:[\"1*2*3\",\"1+2+3\"]Explanation:Both \"1*2*3\" and \"1+2+3\" evaluate to 6.", + "image": null + }, + { + "text": "Example 2: Input:num = \"232\", target = 8Output:[\"2*3+2\",\"2+3*2\"]Explanation:Both \"2*3+2\" and \"2+3*2\" evaluate to 8.", + "image": null + }, + { + "text": "Example 3: Input:num = \"3456237490\", target = 9191Output:[]Explanation:There are no expressions that can be created from \"3456237490\" to evaluate to 9191.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n s=num[0]\n q=[\"+\",\"-\",\"*\",\"\"]\n ans=[]\n def cal(w):\n i=1\n while i \"heeellooo\"", + "\"hi\" -> \"hiiii\"" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]Output:1Explanation:We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private String getFreqString(String s) {\n int len = s.length();\n StringBuilder freqString = new StringBuilder();\n int currFreq = 1;\n char prevChar = s.charAt(0);\n freqString.append(s.charAt(0));\n for(int i = 1; i0) {\n freqString.append(currFreq);\n }\n \n return freqString.toString();\n }\n \n private boolean isGreaterButLessThanThree(char sChar, char wChar) { \n return sChar > wChar && sChar < '3';\n }\n \n private boolean isStretchy(String s, String word) { \n int sLen = s.length();\n int wordLen = word.length();\n \n if(sLen != wordLen) {\n return false;\n }\n \n for(int i = 0; i \"heeellooo\"", + "\"hi\" -> \"hiiii\"" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]Output:1Explanation:We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def expressiveWords(self, s: str, words: List[str]) -> int:\n # edge cases\n if len(s) == 0 and len(words) != 0:\n return False\n if len(words) == 0 and len(s) != 0:\n return False\n if len(s) == 0 and len(words) == 0:\n return True\n \n # helper function, compressing string and extract counts\n def compressor(s_word):\n init_string =[s_word[0]]\n array = []\n start = 0\n for i,c in enumerate(s_word):\n if c == init_string[-1]:\n continue\n array.append(i-start)\n start = i\n init_string += c \n array.append(i-start+1) \n return init_string,array\n\n res = len(words)\n s_split, s_array = compressor(s)\n for word in words:\n word_split = ['']\n word_array = []\n word_split,word_array = compressor(word)\n if s_split == word_split:\n for num_s,num_word in zip(s_array,word_array):\n if num_s != num_word and num_s < 3 or num_word > num_s:\n res -= 1\n break\n else:\n res -= 1\n return res", + "title": "809. Expressive Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:0Explanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:1Explanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trailingZeroes(int n) {\n int count=0;\n while(n>1) {count+=n/5; n=n/5;}\n return count;\n }\n}", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:0Explanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:1Explanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n res = 0\n for i in range(2, n+1):\n while i > 0 and i%5 == 0:\n i //= 5\n res += 1\n return res", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the i th box of candy that Alice has and bobSizes[j] is the number of candies of the j th box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a n integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange . If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= aliceSizes.length, bobSizes.length <= 10^4", + "1 <= aliceSizes[i], bobSizes[j] <= 10^5", + "Alice and Bob have a different total number of candies.", + "There will be at least one valid answer for the given input." + ], + "examples": [ + { + "text": "Example 1: Input:aliceSizes = [1,1], bobSizes = [2,2]Output:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:aliceSizes = [1,2], bobSizes = [2,3]Output:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:aliceSizes = [2], bobSizes = [1,3]Output:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\nvector fairCandySwap(vector& aliceSizes, vector& bobSizes) {\n\n sort(bobSizes.begin(),bobSizes.end());\n sort(aliceSizes.begin(),aliceSizes.end());\n\n int sum1=0;\n int sum2=0;\n vector ans;\n for(int i =0 ; i aliceSizes[i]-dif)\n {\n end=mid-1;\n }\n \n } \n }\n \n return ans;\n \n}\n};\n", + "title": "888. Fair Candy Swap", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array cookies , where cookies[i] denotes the number of cookies in the i th bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution. Return the minimum unfairness of all distributions . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= cookies.length <= 8", + "1 <= cookies[i] <= 10^5", + "2 <= k <= cookies.length" + ], + "examples": [ + { + "text": "Example 1: Input:cookies = [8,15,10,20,8], k = 2Output:31Explanation:One optimal distribution is [8,15,8] and [10,20]\n- The 1stchild receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.\n- The 2ndchild receives [10,20] which has a total of 10 + 20 = 30 cookies.\nThe unfairness of the distribution is max(31,30) = 31.\nIt can be shown that there is no distribution with an unfairness less than 31.", + "image": null + }, + { + "text": "Example 2: Input:cookies = [6,1,3,2,2,4,1,2], k = 3Output:7Explanation:One optimal distribution is [6,1], [3,2,2], and [4,1,2]\n- The 1stchild receives [6,1] which has a total of 6 + 1 = 7 cookies.\n- The 2ndchild receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.\n- The 3rdchild receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.\nThe unfairness of the distribution is max(7,7,7) = 7.\nIt can be shown that there is no distribution with an unfairness less than 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.28 MB (Top 98.3%)\n\nclass Solution {\n int ans;\n int count[];\n public int distributeCookies(int[] cookies, int k) {\n ans= Integer.MAX_VALUE;\n count= new int[k];\n\n backtrack(0,cookies, k);\n return ans;\n }\n public void backtrack(int cookieNumber, int[] cookies, int k)\n {\n if(cookieNumber==cookies.length)\n {\n int max= 0;\n for(int i=0; i int:\n ans = float('inf')\n fair = [0]*k\n def rec(i):\n nonlocal ans,fair\n if i == len(cookies):\n ans = min(ans,max(fair))\n return\n\t\t\t# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution\n\t\t\tif ans <= max(fair):\n return\n for j in range(k):\n fair[j] += cookies[i]\n rec(i+1)\n fair[j] -= cookies[i]\n rec(0)\n return ans\n", + "title": "2305. Fair Distribution of Cookies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [left i , sideLength i ] represents the i th square with a side length of sideLength i that is dropped with its left edge aligned with X-coordinate left i . Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis . A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares . Return an integer array ans where ans[i] represents the height described above after dropping the i th square . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 1000", + "1 <= left i <= 10^8", + "1 <= sideLength i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[1,2],[2,3],[6,1]]Output:[2,5,5]Explanation:After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].", + "image": "https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg" + }, + { + "text": "Example 2: Input:positions = [[100,100],[200,100]]Output:[100,100]Explanation:After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 89.89%) | Memory: 46.10 MB (Top 5.62%)\n\nclass Solution {\n public List fallingSquares(int[][] positions) {\n SegmentNode root = new SegmentNode(0,Integer.MAX_VALUE,0);\n List ans = new ArrayList<>();\n int max = 0;\n for(int[] p : positions){\n int left = p[0], height = p[1], right = left + height;\n int maxHeight = query(root, left, right) + height;\n max = Math.max(max,maxHeight);\n ans.add(max);\n add(root, left, right, maxHeight);\n }\n return ans;\n }\n public int query(SegmentNode root, int start, int end){\n if(start<=root.start && end>=root.end) return root.maxHeight;\n if(start>=root.end || end<=root.start) return 0;\n if (root.left==null) return root.maxHeight;\n int mid = root.start + (root.end - root.start) / 2;\n if (end <= mid) {\n return query(root.left, start, end);\n } else if (start >= mid) {\n return query(root.right, start, end);\n }\n return Math.max(query(root.left,start,mid),query(root.right,mid,end));\n }\n\n public void add(SegmentNode root, int start, int end, int maxHeight){\n if(start<=root.start && end>=root.end){\n root.maxHeight = maxHeight;\n root.left = null;\n root.right = null;\n return;\n }\n if(start>=root.end || root.start>=end) return;\n if(root.left==null){\n int mid = root.start + (root.end - root.start) / 2;\n root.left = new SegmentNode(root.start,mid,0);\n root.right = new SegmentNode(mid,root.end,0);\n }\n add(root.left,start,end,maxHeight);\n add(root.right,start,end,maxHeight);\n root.maxHeight = Math.max(root.left.maxHeight,root.right.maxHeight);\n }\n}\nclass SegmentNode{\n public SegmentNode left , right;\n public int start, end, maxHeight;\n public SegmentNode(int start, int end, int maxHeight){\n this.start = start;\n this.end = end;\n this.maxHeight = maxHeight;\n }\n}\n", + "title": "699. Falling Squares", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [left i , sideLength i ] represents the i th square with a side length of sideLength i that is dropped with its left edge aligned with X-coordinate left i . Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis . A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved. After each square is dropped, you must record the height of the current tallest stack of squares . Return an integer array ans where ans[i] represents the height described above after dropping the i th square . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= positions.length <= 1000", + "1 <= left i <= 10^8", + "1 <= sideLength i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:positions = [[1,2],[2,3],[6,1]]Output:[2,5,5]Explanation:After the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].", + "image": "https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg" + }, + { + "text": "Example 2: Input:positions = [[100,100],[200,100]]Output:[100,100]Explanation:After the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.", + "image": null + } + ], + "follow_up": null, + "solution": "class SegmentTreeNode:\n def __init__(self, low, high):\n self.low = low\n self.high = high\n self.left = None\n self.right = None\n self.max = 0\n\nclass Solution: \n def _build(self, left, right):\n root = SegmentTreeNode(self.coords[left], self.coords[right])\n if left == right:\n return root\n \n mid = (left+right)//2\n root.left = self._build(left, mid)\n root.right = self._build(mid+1, right)\n return root\n \n def _update(self, root, lower, upper, val):\n if not root:\n return\n if lower <= root.high and root.low <= upper:# intersect\n root.max = val\n self._update(root.left, lower, upper, val)\n self._update(root.right, lower, upper, val)\n \n def _query(self, root, lower, upper):\n if lower <= root.low and root.high <= upper:\n return root.max\n if upper < root.low or root.high < lower:\n return 0\n return max(self._query(root.left, lower, upper), self._query(root.right, lower, upper))\n \n def fallingSquares(self, positions: List[List[int]]) -> List[int]:\n\t\t# coordinates compression\n coords = set()\n for left, size in positions:\n right = left+size-1\n coords.add(left)\n coords.add(right)\n self.coords = sorted(list(coords))\n root = self._build(0, len(self.coords)-1)\n \n res = []\n for left, size in positions:\n right = left+size-1\n h = self._query(root, left, right) + size\n res.append(max(res[-1],h)) if res else res.append(h)\n self._update(root, left, right, h)\n return res\n", + "title": "699. Falling Squares", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an API that generates fancy sequences using the append , addAll , and multAll operations. Implement the Fancy class: Example 1:", + "description_images": [], + "constraints": [ + "Fancy() Initializes the object with an empty sequence.", + "void append(val) Appends an integer val to the end of the sequence.", + "void addAll(inc) Increments all existing values in the sequence by an integer inc .", + "void multAll(m) Multiplies all existing values in the sequence by an integer m .", + "int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7 . If the index is greater or equal than the length of the sequence, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]Output[null, null, null, null, null, 10, null, null, null, 26, 34, 20]ExplanationFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "class Fancy {\n private ArrayList lst;\n private ArrayList add;\n private ArrayList mult;\n private final long MOD = 1000000007;\n\n public Fancy() {\n lst = new ArrayList<>();\n add = new ArrayList<>();\n mult = new ArrayList<>();\n add.add(0L);\n mult.add(1L);\n }\n\n public void append(int val) {\n lst.add((long) val);\n int l = add.size();\n add.add(add.get(l - 1));\n mult.add(mult.get(l - 1));\n }\n\n public void addAll(int inc) {\n int l = add.size();\n add.set(l - 1, add.get(l - 1) + inc);\n }\n\n public void multAll(int m) {\n int l = add.size();\n add.set(l - 1, (add.get(l - 1) * m) % MOD);\n mult.set(l - 1, (mult.get(l - 1) * m) % MOD);\n }\n\n public int getIndex(int idx) {\n if (idx >= lst.size()) return -1;\n\n int l = add.size();\n long m = (mult.get(l - 1) * inverse(mult.get(idx))) % MOD;\n long a = (add.get(l - 1) - (add.get(idx) * m) % MOD + MOD) % MOD;\n return (int) (((lst.get(idx) * m) % MOD + a) % MOD);\n }\n\n long inverse(long a) {\n return pow(a, MOD - 2);\n }\n\n long pow(long a, long n) {\n if (n == 0) return 1;\n if (n % 2 == 0) {\n long t = pow(a, n / 2);\n return (t * t) % MOD;\n } else {\n return (pow(a, n - 1) * a) % MOD;\n }\n }\n}\n", + "title": "1622. Fancy Sequence", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Write an API that generates fancy sequences using the append , addAll , and multAll operations. Implement the Fancy class: Example 1:", + "description_images": [], + "constraints": [ + "Fancy() Initializes the object with an empty sequence.", + "void append(val) Appends an integer val to the end of the sequence.", + "void addAll(inc) Increments all existing values in the sequence by an integer inc .", + "void multAll(m) Multiplies all existing values in the sequence by an integer m .", + "int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 10^9 + 7 . If the index is greater or equal than the length of the sequence, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]Output[null, null, null, null, null, 10, null, null, null, 26, 34, 20]ExplanationFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "def egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\ndef modinv(a, m):\n g, x, y = egcd(a, m)\n return x % m\n\nmod = 1000000007\n\nclass Fancy(object):\n\n def __init__(self):\n self.seq = []\n self.addC = 0\n self.mulC = 1\n \n def append(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.seq.append([val, self.mulC, self.addC])\n \n\n def addAll(self, inc):\n \"\"\"\n :type inc: int\n :rtype: None\n \"\"\"\n self.addC = (self.addC%mod + inc%mod)%mod\n\n def multAll(self, m):\n \"\"\"\n :type m: int\n :rtype: None\n \"\"\"\n self.mulC = (self.mulC%mod * m%mod)%mod\n self.addC = (self.addC%mod * m%mod)%mod\n \n\n def getIndex(self, idx):\n \"\"\"\n :type idx: int\n :rtype: int\n \"\"\"\n if(idx >= len(self.seq)):\n return -1\n \n mulCo = self.seq[idx][1]\n addCo = self.seq[idx][2]\n val = self.seq[idx][0]\n \n inv = modinv(mulCo, mod)\n a = (self.mulC%mod * inv%mod)%mod\n val = (val%mod * a%mod)%mod\n b = (addCo%mod * a%mod)%mod\n val = (val%mod - b%mod)%mod\n val = (val%mod + self.addC%mod)%mod\n \n return val\n", + "title": "1622. Fancy Sequence", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The Fibonacci numbers , commonly denoted F(n) form a sequence, called the Fibonacci sequence , such that each number is the sum of the two preceding ones, starting from 0 and 1 . That is, Given n , calculate F(n) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:F(2) = F(1) + F(0) = 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:2Explanation:F(3) = F(2) + F(1) = 1 + 1 = 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:3Explanation:F(4) = F(3) + F(2) = 2 + 1 = 3.", + "image": null + }, + { + "text": "F(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.00 MB (Top 41.57%)\n\nclass Solution {\n public int fib(int n) {\n if(n == 0)\n return 0;\n if(n == 1)\n return 1;\n int[] Fibonacci = new int[n+1];\n Fibonacci[0] = 0;\n Fibonacci[1] = 1;\n for(int i = 2; i < n+1; i++)\n Fibonacci[i] = Fibonacci[i-1] + Fibonacci[i-2];\n return Fibonacci[n];\n }\n}\n\n", + "title": "509. Fibonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The Fibonacci numbers , commonly denoted F(n) form a sequence, called the Fibonacci sequence , such that each number is the sum of the two preceding ones, starting from 0 and 1 . That is, Given n , calculate F(n) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:F(2) = F(1) + F(0) = 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:2Explanation:F(3) = F(2) + F(1) = 1 + 1 = 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:3Explanation:F(4) = F(3) + F(2) = 2 + 1 = 3.", + "image": null + }, + { + "text": "F(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 80.68%) | Memory: 13.8 MB (Top 55.21%)\nclass Solution:\n def fib(self, n: int) -> int:\n fa = [0, 1]\n\n for i in range(2, n + 1):\n fa.append(fa[i-2] + fa[i-1])\n\n return fa[n]", + "title": "509. Fibonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array books where books[i] = [thickness i , height i ] indicates the thickness and height of the i th book. You are also given an integer shelfWidth . We want to place these books in order onto bookcase shelves that have a total width shelfWidth . We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth , then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf." + ], + "examples": [ + { + "text": "Example 1: Input:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4Output:6Explanation:The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.", + "image": "https://assets.leetcode.com/uploads/2019/06/24/shelves.png" + }, + { + "text": "Example 2: Input:books = [[1,3],[2,4],[3,2]], shelfWidth = 6Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.30 MB (Top 39.5%)\n\nclass Solution {\n public int minHeightShelves(int[][] books, int shelfWidth) {\n int memo[] = new int[books.length];\n return recur(books, shelfWidth, 0, memo);\n }\n \n private int recur(int[][] books, int shelfWidth, int index, int[] memo) {\n \n if (index == books.length) {\n return 0;\n }\n \n if (memo[index] > 0) {\n return memo[index];\n }\n int ans = Integer.MAX_VALUE;\n int height = 0;\n int width = 0;\n \n for (int i = index; i < books.length; i++) {\n width += books[i][0];\n \n if (width > shelfWidth) {\n break;\n }\n height = Math.max(height, books[i][1]);\n ans = Math.min(ans, height + recur(books, shelfWidth, i + 1, memo));\n }\n return memo[index] = ans;\n }\n}\n", + "title": "1105. Filling Bookcase Shelves", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array books where books[i] = [thickness i , height i ] indicates the thickness and height of the i th book. You are also given an integer shelfWidth . We want to place these books in order onto bookcase shelves that have a total width shelfWidth . We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth , then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf." + ], + "examples": [ + { + "text": "Example 1: Input:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4Output:6Explanation:The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.", + "image": "https://assets.leetcode.com/uploads/2019/06/24/shelves.png" + }, + { + "text": "Example 2: Input:books = [[1,3],[2,4],[3,2]], shelfWidth = 6Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minHeightShelves(self, books, shelf_width: int) -> int:\n n, dp = len(books), [float('inf')] * (len(books)+1)\n dp[0] = 0\n\n for i in range(1, n+1):\n max_width, max_height, j = shelf_width, 0, i - 1\n \n while j >= 0 and max_width - books[j][0] >= 0:\n max_width -= books[j][0]\n max_height = max(max_height, books[j][1])\n dp[i] = max_height\n j -= 1\n\n if j >= 0 and max_width - books[j][0] < 0:\n j = i - 1\n dp[i] = float('inf')\n width, height = 0, 0\n while j >= 0 and width + books[j][0] <= shelf_width:\n width = width + books[j][0]\n height = max(books[j][1], height)\n dp[i] = min(dp[i], height + dp[j])\n j -= 1\n\n return dp[n]\n", + "title": "1105. Filling Bookcase Shelves", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array restaurants where restaurants[i] = [id i , rating i , veganFriendly i , price i , distance i ] . You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendly i set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendly i and veganFriendly take value 1 when it is true , and 0 when it is false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= restaurants.length <= 10^4", + "restaurants[i].length == 5", + "1 <= id i , rating i , price i , distance i <= 10^5", + "1 <= maxPrice, maxDistance <= 10^5", + "veganFriendly i and veganFriendly are 0 or 1.", + "All id i are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10Output:[3,1,5]Explanation:The restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "image": null + }, + { + "text": "Example 2: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10Output:[4,3,2,1,5]Explanation:The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.", + "image": null + }, + { + "text": "Example 3: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3Output:[4,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 93.75%) | Memory: 58 MB (Top 51.88%)\nclass Restaurant {\n int id, rating;\n Restaurant(int id, int rating) {\n this.id = id;\n this.rating = rating;\n }\n}\n\nclass RestaurantComparator implements Comparator {\n @Override\n public int compare(Restaurant r1, Restaurant r2) {\n return r1.rating == r2.rating ? r2.id - r1.id : r2.rating - r1.rating;\n }\n}\n\nclass Solution {\n public List filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {\n PriorityQueue heap = new PriorityQueue<>(new RestaurantComparator());\n if(veganFriendly == 1) {\n for(int[] restaurant: restaurants) {\n if(restaurant[2] == 1 && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n } else {\n for(int[] restaurant: restaurants) {\n if(restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n }\n List answer = new ArrayList<>();\n while(!heap.isEmpty()) {\n answer.add(heap.poll().id);\n }\n return answer;\n }\n}", + "title": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array restaurants where restaurants[i] = [id i , rating i , veganFriendly i , price i , distance i ] . You have to filter the restaurants using three filters. The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendly i set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively. Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendly i and veganFriendly take value 1 when it is true , and 0 when it is false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= restaurants.length <= 10^4", + "restaurants[i].length == 5", + "1 <= id i , rating i , price i , distance i <= 10^5", + "1 <= maxPrice, maxDistance <= 10^5", + "veganFriendly i and veganFriendly are 0 or 1.", + "All id i are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10Output:[3,1,5]Explanation:The restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).", + "image": null + }, + { + "text": "Example 2: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10Output:[4,3,2,1,5]Explanation:The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.", + "image": null + }, + { + "text": "Example 3: Input:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3Output:[4,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef f_fcn(self,restaurants, veganFriendly, maxPrice, maxDistance):\n\tf_lst = filter(lambda x: (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or\n\t\t\t\t (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance), restaurants)\n\treturn f_lst\n\ndef h_fcn(self,lst):\n\treturn([lst[0], lst[1]])\n\ndef filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n\n\tres = map(self.h_fcn, self.f_fcn(restaurants, veganFriendly, maxPrice, maxDistance))\n\n\n\treturn map(lambda x: x[0], sorted(res, key=lambda x: (-x[1], -x[0])))\n", + "title": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i] , otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 500", + "1 <= prices[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [8,4,6,2,3]Output:[4,2,4,2,3]Explanation:For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. \nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. \nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. \nFor items 3 and 4 you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:[1,2,3,4,5]Explanation:In this case, for all items, you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 3: Input:prices = [10,1,1,6]Output:[9,0,1,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 50.03%) | Memory: 44.5 MB (Top 32.12%)\nclass Solution {\n public int[] finalPrices(int[] prices) {\n for(int i = 0; i < prices.length; i++){\n for(int j = i + 1; j < prices.length; j++){\n if(j > i && prices[j] <= prices[i]){\n prices[i] -= prices[j];\n break;\n }\n }\n }\n return prices;\n }\n}", + "title": "1475. Final Prices With a Special Discount in a Shop", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i] , otherwise, you will not receive any discount at all. Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 500", + "1 <= prices[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [8,4,6,2,3]Output:[4,2,4,2,3]Explanation:For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. \nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. \nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. \nFor items 3 and 4 you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:[1,2,3,4,5]Explanation:In this case, for all items, you will not receive any discount at all.", + "image": null + }, + { + "text": "Example 3: Input:prices = [10,1,1,6]Output:[9,0,1,6]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 83.49%) | Memory: 16.60 MB (Top 61.19%)\n\nclass Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n for i in range(len(prices)):\n for j in range(i+1,len(prices)):\n if prices[j]<=prices[i]:\n prices[i]=prices[i]-prices[j]\n break\n return (prices)\n", + "title": "1475. Final Prices With a Special Discount in a Shop", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a programming language with only four operations and one variable X : Initially, the value of X is 0 . Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "++X and X++ increments the value of the variable X by 1 .", + "--X and X-- decrements the value of the variable X by 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:operations = [\"--X\",\"X++\",\"X++\"]Output:1Explanation:The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X = 0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:operations = [\"++X\",\"++X\",\"X++\"]Output:3Explanation:The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:operations = [\"X++\",\"++X\",\"--X\",\"X--\"]Output:0Explanation:The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int finalValueAfterOperations(String[] operations) {\n int val = 0;\n for(int i = 0; i int:\n x = 0\n for o in operations:\n if '+' in o:\n x += 1\n else:\n x -= 1\n return x", + "title": "2011. Final Value of Variable After Performing Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "The values of the nodes of the tree are unique.", + "target node is a node from the original tree and is not null ." + ], + "examples": [ + { + "text": "Example 1: Input:tree = [7,4,3,null,null,6,19], target = 3Output:3Explanation:In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e1.png" + }, + { + "text": "Example 2: Input:tree = [7], target = 7Output:7", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e2.png" + }, + { + "text": "Example 3: Input:tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4Output:4", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e3.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {\n TreeNode[] ref = new TreeNode[]{null};\n dfs(cloned, target, ref);\n return ref[0];\n }\n public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) {\n if (root == null) return;\n if (root.val == target.val) {\n ref[0] = root;\n return;\n } else {\n dfs(root.left, target, ref);\n dfs(root.right, target, ref);\n }\n }\n}\n", + "title": "1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "The values of the nodes of the tree are unique.", + "target node is a node from the original tree and is not null ." + ], + "examples": [ + { + "text": "Example 1: Input:tree = [7,4,3,null,null,6,19], target = 3Output:3Explanation:In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e1.png" + }, + { + "text": "Example 2: Input:tree = [7], target = 7Output:7", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e2.png" + }, + { + "text": "Example 3: Input:tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4Output:4", + "image": "https://assets.leetcode.com/uploads/2020/02/21/e3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1109 ms (Top 30.14%) | Memory: 24.2 MB (Top 19.53%)\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n def DFS(node1,node2):\n if node1==target:\n return node2\n if node1 and node1.left is None and node1.right is None:\n return\n\n res1 = DFS(node1.left,node2.left) if node1 else None\n if res1 is not None:\n return res1\n res2 = DFS(node1.right,node2.right) if node1 else None\n if res2 is not None:\n return res2\n res=DFS(original,cloned)\n return res", + "title": "1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal , find any peak element mat[i][j] and return the length 2 array [i,j] . You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/08/1.png", + "https://assets.leetcode.com/uploads/2021/06/07/3.png" + ], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 500", + "1 <= mat[i][j] <= 10^5", + "No two adjacent cells are equal." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,4],[3,2]]Output:[0,1]Explanation:Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[10,20,15],[21,30,14],[7,16,32]]Output:[1,1]Explanation:Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 887 ms (Top 94.77%) | Memory: 48.10 MB (Top 59.48%)\n\nclass Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n m, n = len(mat), len(mat[0])\n l, r = 0, n\n while l <= r:\n mid = (l + r) // 2\n cur_max, left = 0, False\n for i in range(m):\n if i > 0 and mat[i-1][mid] >= mat[i][mid]:\n continue\n if i+1 < m and mat[i+1][mid] >= mat[i][mid]: \n continue\n if mid+1 < n and mat[i][mid+1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], not mat[i][mid] > cur_max\n continue\n if mid > 0 and mat[i][mid-1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], mat[i][mid] > cur_max\n continue\n return [i, mid]\n if left:\n r = mid-1\n else:\n l = mid+1\n return []\n", + "title": "1901. Find a Peak Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Winston was given the above mysterious function func . He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target| . Notice that func should be called with the values l and r where 0 <= l, r < arr.length . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/09/change.png" + ], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "0 <= target <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,12,3,7,15], target = 5Output:2Explanation:Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1000000,1000000,1000000], target = 1Output:999999Explanation:Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4,8,16], target = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] tree;\n int[] arr;\n int target;\n int min;\n \n public int closestToTarget(int[] arr, int target) {\n int n = arr.length;\n this.arr = arr;\n this.target = target;\n tree = new int[n << 2];\n Arrays.fill(tree, (1 << 31) - 1); // initialize\n min = Integer.MAX_VALUE;\n for (int i = 0; i < n; i++) {\n add(i, 0, n, 0);\n }\n return min;\n }\n private void add(int x, int l, int r, int n) {\n if (l == r) {\n tree[n] = arr[x];\n min = Math.min(min, Math.abs(tree[n] - target));\n return;\n }\n int mid = l + (r - l) / 2;\n if (x <= mid) {\n add(x, l, mid, 2 * n + 1);\n } else {\n add(x, mid + 1, r, 2 * n + 2);\n }\n tree[n] = (tree[2 * n + 1] & tree[2 * n + 2]); // & two subtrees\n min = Math.min(min, Math.abs(tree[n] - target));\n }\n}\n", + "title": "1521. Find a Value of a Mysterious Function Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Winston was given the above mysterious function func . He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target| . Notice that func should be called with the values l and r where 0 <= l, r < arr.length . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/09/change.png" + ], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "0 <= target <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,12,3,7,15], target = 5Output:2Explanation:Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1000000,1000000,1000000], target = 1Output:999999Explanation:Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,4,8,16], target = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1091 ms (Top 49.0%) | Memory: 27.44 MB (Top 83.6%)\n\nclass Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n ans, seen = inf, set()\n for x in arr: \n seen = {ss & x for ss in seen} | {x}\n ans = min(ans, min(abs(ss - target) for ss in seen))\n return ans ", + "title": "1521. Find a Value of a Mysterious Function Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"Output:[0,6]Explanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"Output:[0,1,2]Explanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n \n public List findAnagrams(String s, String p) {\n int fullMatchCount = p.length();\n Map anagramMap = new HashMap<>();\n \n for (Character c : p.toCharArray())\n anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1);\n \n List result = new ArrayList<>();\n int left = 0, right = 0, currentMatchCount = 0;\n Map currentAnagramMap = new HashMap<>();\n while (right < s.length()) {\n char c = s.charAt(right);\n if (anagramMap.get(c) == null) {\n currentAnagramMap = new HashMap<>();\n right++;\n left = right;\n currentMatchCount = 0;\n continue;\n }\n currentAnagramMap.put(c, currentAnagramMap.getOrDefault(c, 0) + 1);\n currentMatchCount++;\n \n if (currentAnagramMap.get(c) > anagramMap.get(c)) {\n char leftC = s.charAt(left);\n while (leftC != c) {\n currentAnagramMap.put(leftC, currentAnagramMap.get(leftC) - 1);\n left++;\n leftC = s.charAt(left);\n currentMatchCount--;\n }\n left++;\n currentAnagramMap.put(c, currentAnagramMap.get(c) - 1);\n currentMatchCount--;\n }\n \n if (currentMatchCount == fullMatchCount)\n result.add(left);\n \n right++;\n }\n return result;\n }\n}\n", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"Output:[0,6]Explanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"Output:[0,1,2]Explanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n l='abcdefghijklmnopqrstuvwxyz'\n if len(p)>len(s):\n return []\n d={}\n for x in l:\n d[x]=0\n d1=dict(d)\n d2=dict(d)\n for x in range(len(p)):\n d1[s[x]]+=1\n d2[p[x]]+=1\n l1=[]\n if d1==d2:\n l1=[0]\n #print(d1)\n for x in range(len(p),len(s)):\n d1[s[x]]+=1\n d1[s[x-len(p)]]-=1\n if d1==d2:\n l1.append(x-len(p)+1)\n return l1\n", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice , return an array of all the integers that appears twice . You must write an algorithm that runs in O(n) time and uses only constant extra space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n", + "Each element in nums appears once or twice ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]Output:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2]Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 36.17%) | Memory: 65.2 MB (Top 76.59%)\nclass Solution {\n public List findDuplicates(int[] nums) {\n List ans = new ArrayList<>();\n for(int i=0;i List[int]:\n res = []\n hm = {}\n # adding entries in hashmap to check frequency\n for i, v in enumerate(nums):\n if v not in hm:\n hm[v] = 1\n else:\n hm[v] += 1\n # checking frequency of item and adding output to an array\n for key, value in hm.items():\n if value > 1:\n res.append(key)\n return res", + "title": "442. Find All Duplicates in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the strings s1 and s2 of size n and the string evil , return the number of good strings . A good string has size n , it is alphabetically greater than or equal to s1 , it is alphabetically smaller than or equal to s2 , and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "s1 <= s2", + "1 <= n <= 500", + "1 <= evil.length <= 50", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"Output:51Explanation:There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".", + "image": null + }, + { + "text": "Example 2: Input:n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"Output:0Explanation:All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 72.7%) | Memory: 43.76 MB (Top 33.3%)\n\nclass Solution {\n Integer[][][][] dp;\n int mod = 1000000007;\n int[] lps;\n private int add(int a, int b) {\n return (a % mod + b % mod) % mod;\n }\n private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) {\n if(evI == evil.length) return 0;\n if(cur == s2.length) return 1;\n if(dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] != null) return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI];\n char start = isStrictLower ? s1[cur] : 'a';\n char end = isStrictUpper ? s2[cur] : 'z';\n int res = 0;\n for(char ch = start; ch <= end; ch ++) {\n if(evil[evI] == ch)\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, evI + 1));\n else {\n int j = evI;\n while (j > 0 && evil[j] != ch) j = lps[j - 1];\n if (ch == evil[j]) j++;\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, j));\n }\n }\n return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] = res;\n }\n public int findGoodStrings(int n, String s1, String s2, String evil) {\n char[] arr = s1.toCharArray();\n char[] brr = s2.toCharArray();\n char[] crr = evil.toCharArray();\n lps = new int[crr.length];\n for (int i = 1, j = 0; i < crr.length; i++) {\n while (j > 0 && crr[i] != crr[j]) j = lps[j - 1];\n if (crr[i] == crr[j]) lps[i] = ++j;\n }\n dp = new Integer[n][2][2][crr.length];\n return solve(arr, brr, 0, true, true, crr, 0);\n }\n}", + "title": "1397. Find All Good Strings", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the strings s1 and s2 of size n and the string evil , return the number of good strings . A good string has size n , it is alphabetically greater than or equal to s1 , it is alphabetically smaller than or equal to s2 , and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "s1.length == n", + "s2.length == n", + "s1 <= s2", + "1 <= n <= 500", + "1 <= evil.length <= 50", + "All strings consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"Output:51Explanation:There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\".", + "image": null + }, + { + "text": "Example 2: Input:n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"Output:0Explanation:All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.", + "image": null + }, + { + "text": "Example 3: Input:n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nclass Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n def srange(a, b):\n return [chr(i) for i in range(ord(a),ord(b)+1)]\n def LPS(pat):\n lps = [0]\n i, target = 1, 0\n while i < len(pat):\n if pat[i] == pat[target]:\n target += 1\n lps.append(target)\n i += 1\n elif target:\n target = lps[target-1]\n else:\n lps.append(0)\n i += 1\n return lps\n lps = LPS(evil)\n M = 10**9+7\n @lru_cache(None)\n def dfs(i, max_matched_idx, lb, rb):\n if max_matched_idx == len(evil): return 0\n if i == n: return 1\n l = s1[i] if lb else 'a'\n r = s2[i] if rb else 'z'\n candidates = srange(l, r)\n res = 0\n for j, c in enumerate(candidates):\n nxt_matched_idx = max_matched_idx\n while evil[nxt_matched_idx] != c and nxt_matched_idx:\n nxt_matched_idx = lps[nxt_matched_idx-1]\n res = (res + dfs(i+1, nxt_matched_idx+(c==evil[nxt_matched_idx]),\n lb = (lb and j == 0), rb = (rb and j==len(candidates)-1)))%M\n return res\n return dfs(0, 0, True, True)", + "title": "1397. Find All Good Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups . No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1) . Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r 1 , c 1 ) and a bottom right corner at (r 2 , c 2 ) is represented by the 4-length array [r 1 , c 1 , r 2 , c 2 ]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land . If there are no groups of farmland, return an empty array. You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == land.length", + "n == land[i].length", + "1 <= m, n <= 300", + "land consists of only 0 's and 1 's.", + "Groups of farmland are rectangular in shape." + ], + "examples": [ + { + "text": "Example 1: Input:land = [[1,0,0],[0,1,1],[0,1,1]]Output:[[0,0,0,0],[1,1,2,2]]Explanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:land = [[1,1],[1,1]]Output:[[0,0,1,1]]Explanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 3: Input:land = [[0]]Output:[]Explanation:There are no groups of farmland.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-32-24-copy-of-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 59.55%) | Memory: 62.3 MB (Top 88.99%)\nclass Solution {\n int[] arr;\n public int[][] findFarmland(int[][] land) {\n List res = new ArrayList<>();\n for(int i=0;ii).toArray(int[][] :: new);\n }\n public void dfs(int[][] land, int i,int j){\n if(i<0 || j<0 || i>=land.length || j>= land[0].length || land[i][j] == 0) return;\n arr[2] = Math.max(i,arr[2]);\n arr[3] = Math.max(j,arr[3]);\n land[i][j] = 0;\n dfs(land,i-1,j);\n dfs(land,i,j+1);\n dfs(land,i+1,j);\n dfs(land,i,j-1);\n }\n}", + "title": "1992. Find All Groups of Farmland", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups . No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1) . Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r 1 , c 1 ) and a bottom right corner at (r 2 , c 2 ) is represented by the 4-length array [r 1 , c 1 , r 2 , c 2 ]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land . If there are no groups of farmland, return an empty array. You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == land.length", + "n == land[i].length", + "1 <= m, n <= 300", + "land consists of only 0 's and 1 's.", + "Groups of farmland are rectangular in shape." + ], + "examples": [ + { + "text": "Example 1: Input:land = [[1,0,0],[0,1,1],[0,1,1]]Output:[[0,0,0,0],[1,1,2,2]]Explanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:land = [[1,1],[1,1]]Output:[[0,0,1,1]]Explanation:The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 3: Input:land = [[0]]Output:[]Explanation:There are no groups of farmland.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-32-24-copy-of-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1416 ms (Top 90.80%) | Memory: 33.1 MB (Top 49.64%)\nclass Solution:\n\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n n = len(land)\n m = len(land[0])\n\n groups = []\n visited = set()\n\n for y in range(n):\n for x in range(m):\n if land[y][x] == 0:\n continue\n\n if (y, x) in visited:\n continue\n\n q = collections.deque()\n q.append((y, x))\n visited.add((y, x))\n\n while q:\n cy, cx = q.popleft()\n\n for dy, dx in ((0, 1), (1, 0)):\n if (cy + dy, cx + dx) in visited:\n continue\n\n if 0 <= cy + dy < n and 0 <= cx + dx < m:\n if land[cy + dy][cx + dx] == 1:\n q.append((cy + dy, cx + dx))\n visited.add((cy + dy, cx + dx))\n\n groups.append([y, x, cy, cx])\n\n return groups", + "title": "1992. Find All Groups of Farmland", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and two integers key and k . A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key . Return a list of all k-distant indices sorted in increasing order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 1000", + "key is an integer from the array nums .", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,9,1,3,9,5], key = 9, k = 1Output:[1,2,3,4,5,6]Explanation:Here,nums[2] == keyandnums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no jwhere|0 - j| <= kandnums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.Thus, we return [1,2,3,4,5,6] which is sorted in increasing order.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], key = 2, k = 2Output:[0,1,2,3,4]Explanation:For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n lis=deque([])\n prev_popped=-1\n for i in range(len(nums)):\n if(nums[i]==key):\n lis.append(i)\n ans=[]\n for i in range(len(nums)):\n if(len(lis)>0 and lis[0]0 and (lis[0]-i)<=k):\n ans.append(i)\n return ans\n", + "title": "2200. Find All K-Distant Indices in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . A number x is lonely when it appears only once , and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,6,5,8]Output:[10,8]Explanation:- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,3]Output:[1,5]Explanation:- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 100.00%) | Memory: 61.2 MB (Top 97.43%)\nclass Solution {\n public List findLonely(int[] nums) {\n Arrays.sort(nums);\n ArrayList list = new ArrayList<>();\n for (int i = 1; i < nums.length - 1; i++) {\n if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) {\n list.add(nums[i]);\n }\n }\n if (nums.length == 1) {\n list.add(nums[0]);\n }\n if (nums.length > 1) {\n if (nums[0] + 1 < nums[1]) {\n list.add(nums[0]);\n }\n if (nums[nums.length - 2] + 1 < nums[nums.length - 1]) {\n list.add(nums[nums.length - 1]);\n }\n }\n return list;\n }\n}", + "title": "2150. Find All Lonely Numbers in the Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . A number x is lonely when it appears only once , and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,6,5,8]Output:[10,8]Explanation:- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,3]Output:[1,5]Explanation:- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4306 ms (Top 5.12%) | Memory: 38.2 MB (Top 71.56%)\nclass Solution:\n def findLonely(self, nums: List[int]) -> List[int]:\n m = Counter(nums)\n return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]", + "title": "2150. Find All Lonely Numbers in the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n] , return an array of all the integers in the range [1, n] that do not appear in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]Output:[5,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 62.33%) | Memory: 67.5 MB (Top 39.21%)\nclass Solution {\n public List findDisappearedNumbers(int[] nums) {\n List res = new ArrayList<>();\n // 0 1 2 3 4 5 6 7 <- indx\n // 4 3 2 7 8 2 3 1 <- nums[i]\n for(int i=0;i0) {\n nums[indx] = nums[indx]*-1;\n }\n }\n // 0 1 2 3 4 5 6 7 <- indx\n // -4 -3 -2 -7 8 2 -3 -1 <- nums[i]\n for(int i=0;i0) {\n res.add(i+1);\n }else {\n nums[i] *= -1;\n }\n }\n // [ 5, 6]\n return res;\n }\n}", + "title": "448. Find All Numbers Disappeared in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums of n integers where nums[i] is in the range [1, n] , return an array of all the integers in the range [1, n] that do not appear in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "1 <= nums[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,7,8,2,3,1]Output:[5,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n return set(nums) ^ set(range(1,len(nums)+1))\n", + "title": "448. Find All Numbers Disappeared in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1Output:[0,1,2,3,5]Explanation:At time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.​​​​\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3Output:[0,1,3]Explanation:At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1Output:[0,1,2,3,4]Explanation:At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 53.2%) | Memory: 108.54 MB (Top 41.1%)\n\nclass Solution {\n public List findAllPeople(int n, int[][] meetings, int firstPerson) {\n\t\n\t\t// create map\n Map> timeToIndexes = new TreeMap<>();\n int m = meetings.length;\n for (int i = 0; i < m; i++) {\n timeToIndexes.putIfAbsent(meetings[i][2], new ArrayList<>());\n timeToIndexes.get(meetings[i][2]).add(i);\n }\n\t\t\n UF uf = new UF(n);\n\t\t// base\n uf.union(0, firstPerson);\n\t\t\n\t\t// for every time we have a pool of people that talk to each other\n\t\t// if someone knows a secret proir to this meeting - all pool will too\n\t\t// if not - reset unions from this pool\n for (int time : timeToIndexes.keySet()) {\n Set pool = new HashSet<>();\n\t\t\t\n for (int ind : timeToIndexes.get(time)) {\n int[] currentMeeting = meetings[ind];\n uf.union(currentMeeting[0], currentMeeting[1]);\n pool.add(currentMeeting[0]);\n pool.add(currentMeeting[1]);\n }\n\t\t\t\n\t\t\t// meeting that took place now should't affect future\n\t\t\t// meetings if people don't know the secret\n for (int i : pool) if (!uf.connected(0, i)) uf.reset(i);\n }\n\t\t\n\t\t// if the person is conneted to 0 - they know a secret\n List ans = new ArrayList<>();\n for (int i = 0; i < n; i++) if (uf.connected(i,0)) ans.add(i);\n return ans;\n }\n \n\t// regular union find\n private static class UF {\n int[] parent, rank;\n\t\t\n public UF(int n) {\n parent = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n public void union(int p, int q) {\n int rootP = find(p);\n int rootQ = find(q);\n\n if (rootP == rootQ)\n return;\n\n if (rank[rootP] < rank[rootQ]) {\n parent[rootP] = rootQ;\n } else {\n parent[rootQ] = rootP;\n rank[rootP]++;\n }\n }\n \n public int find(int p) {\n while (parent[p] != p) {\n p = parent[parent[p]];\n }\n return p;\n }\n \n public boolean connected(int p, int q) {\n return find(p) == find(q);\n }\n \n public void reset(int p) {\n parent[p] = p;\n rank[p] = 0;\n }\n }\n}", + "title": "2092. Find All People With Secret", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1Output:[0,1,2,3,5]Explanation:At time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.​​​​\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3Output:[0,1,3]Explanation:At time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1Output:[0,1,2,3,4]Explanation:At time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6190 ms (Top 5.05%) | Memory: 57.3 MB (Top 48.67%)\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n\n class UnionFind:\n def __init__(self):\n self.parents = {}\n self.ranks = {}\n\n def insert(self, x):\n if x not in self.parents:\n self.parents[x] = x\n self.ranks[x] = 0\n\n def find_parent(self, x):\n if self.parents[x] != x:\n self.parents[x] = self.find_parent(self.parents[x])\n return self.parents[x]\n\n def union(self, x, y):\n self.insert(x)\n self.insert(y)\n x, y = self.find_parent(x), self.find_parent(y)\n if x == y:\n return\n if self.ranks[x] > self.ranks[y]:\n self.parents[y] = x\n else:\n self.parents[x] = y\n if self.ranks[x] == self.ranks[y]:\n self.ranks[y] += 1\n\n time2meets = defaultdict(list)\n for x, y, t in meetings:\n time2meets[t].append((x, y))\n time2meets = sorted(time2meets.items())\n\n curr_know = set([0, firstPerson])\n\n for time, meets in time2meets:\n uf = UnionFind()\n for x, y in meets:\n uf.union(x, y)\n\n groups = defaultdict(set)\n for idx in uf.parents:\n groups[uf.find_parent(idx)].add(idx)\n\n for group in groups.values():\n if group & curr_know:\n curr_know.update(group)\n\n return list(curr_know)", + "title": "2092. Find All People With Secret", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients . The i th recipe has the name recipes[i] , and you can create it if you have all the needed ingredients from ingredients[i] . Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes . You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order . Note that two recipes may contain each other in their ingredients. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == recipes.length == ingredients.length", + "1 <= n <= 100", + "1 <= ingredients[i].length, supplies.length <= 100", + "1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10", + "recipes[i], ingredients[i][j] , and supplies[k] consist only of lowercase English letters.", + "All the values of recipes and supplies combined are unique.", + "Each ingredients[i] does not contain any duplicate values." + ], + "examples": [ + { + "text": "Example 1: Input:recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]Output:[\"bread\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".", + "image": null + }, + { + "text": "Example 2: Input:recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]Output:[\"bread\",\"sandwich\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".", + "image": null + }, + { + "text": "Example 3: Input:recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]Output:[\"bread\",\"sandwich\",\"burger\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nWe can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 86.45%) | Memory: 46.50 MB (Top 57.39%)\n\nclass Solution {\n public List findAllRecipes(String[] recipes, List> ingredients, String[] supplies) {\n HashSet sup = new HashSet<>();\n HashMap index = new HashMap<>();\n HashMap> map = new HashMap<>();\n \n // create hashset of supplies\n for(String s: supplies) {\n sup.add(s);\n }\n \n // store index of all recipes\n for(int i = 0; i < recipes.length; i++) {\n index.put(recipes[i], i);\n }\n \n int[] indegree = new int[recipes.length];\n // create a mapping of all the recipes that are Ingredients as well\n // to the recipes they are ingredients for\n for(int i = 0; i < recipes.length; i++) {\n for(String need: ingredients.get(i)) {\n if(sup.contains(need))\n continue;\n \n map.putIfAbsent(need, new ArrayList());\n map.get(need).add(recipes[i]);\n indegree[i]++;\n }\n }\n \n LinkedList q = new LinkedList<>();\n // add all the recipes with indegree 0 to the queue\n for(int i = 0; i < recipes.length; i++) {\n if(indegree[i] == 0) {\n q.add(i);\n }\n }\n \n List cooked = new ArrayList<>();\n while(!q.isEmpty()) {\n int i = q.poll();\n cooked.add(recipes[i]);\n \n if(!map.containsKey(recipes[i])) {\n // if the map does not contain this recipe, this means\n // this recipe is not an ingredient for any other recipe\n // and no further processing is required\n continue;\n }\n \n for(String recipe: map.get(recipes[i])) {\n if(--indegree[index.get(recipe)] == 0) {\n q.add(index.get(recipe));\n }\n }\n }\n \n return cooked;\n }\n}\n", + "title": "2115. Find All Possible Recipes from Given Supplies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients . The i th recipe has the name recipes[i] , and you can create it if you have all the needed ingredients from ingredients[i] . Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes . You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order . Note that two recipes may contain each other in their ingredients. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == recipes.length == ingredients.length", + "1 <= n <= 100", + "1 <= ingredients[i].length, supplies.length <= 100", + "1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10", + "recipes[i], ingredients[i][j] , and supplies[k] consist only of lowercase English letters.", + "All the values of recipes and supplies combined are unique.", + "Each ingredients[i] does not contain any duplicate values." + ], + "examples": [ + { + "text": "Example 1: Input:recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]Output:[\"bread\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".", + "image": null + }, + { + "text": "Example 2: Input:recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]Output:[\"bread\",\"sandwich\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".", + "image": null + }, + { + "text": "Example 3: Input:recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]Output:[\"bread\",\"sandwich\",\"burger\"]Explanation:We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nWe can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n\n\t\tgraph = defaultdict(list)\n\t\tin_degree = defaultdict(int)\n\t\tfor r,ing in zip(recipes,ingredients):\n\t\t\tfor i in ing:\n\t\t\t\tgraph[i].append(r)\n\t\t\t\tin_degree[r]+=1\n\n\t\tqueue = supplies[::]\n\t\tres = []\n\t\twhile queue:\n\t\t\ting = queue.pop(0)\n\t\t\tif ing in recipes:\n\t\t\t\tres.append(ing)\n\n\t\t\tfor child in graph[ing]:\n\t\t\t\tin_degree[child]-=1\n\t\t\t\tif in_degree[child]==0:\n\t\t\t\t\tqueue.append(child)\n\n\t\treturn res\n", + "title": "2115. Find All Possible Recipes from Given Supplies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices , sources , and targets , all of length k . To complete the i th replacement operation: For example, if s = \" ab cd\" , indices[i] = 0 , sources[i] = \"ab\" , and targets[i] = \"eee\" , then the result of this replacement will be \" eee cd\" . All replacement operations must occur simultaneously , meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap . Return the resulting string after performing all replacement operations on s . A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, a testcase with s = \"abc\" , indices = [0, 1] , and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]Output:\"eeebffff\"Explanation:\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex1.png" + }, + { + "text": "Example 2: Input:s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]Output:\"eeecd\"Explanation:\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {\n \n HashMap subst = new HashMap<>();\n HashMap tgt = new HashMap<>();\n \n for(int i = 0; i< indices.length; i++) {\n subst.put(indices[i], sources[i]);\n tgt.put(indices[i],targets[i]);\n }\n \n Arrays.sort(indices);\n \n String res = \"\";\n int count = 0;\n int avail[] = new int[indices.length];\n for(int i = 0; i< s.length(); i++) {\n if(count < indices.length && i == indices[count] && s.indexOf(subst.get(indices[count]), indices[count]) == indices[count]){\n res = res+\"\"+tgt.get(indices[count]);\n i = i+ subst.get(indices[count]).length()-1;\n count++;\n } else {\n if(count < indices.length && i == indices[count])\n count++;\n res+= s.charAt(i);\n }\n }\n \n return res;\n }\n}\n", + "title": "833. Find And Replace in String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices , sources , and targets , all of length k . To complete the i th replacement operation: For example, if s = \" ab cd\" , indices[i] = 0 , sources[i] = \"ab\" , and targets[i] = \"eee\" , then the result of this replacement will be \" eee cd\" . All replacement operations must occur simultaneously , meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap . Return the resulting string after performing all replacement operations on s . A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, a testcase with s = \"abc\" , indices = [0, 1] , and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]Output:\"eeebffff\"Explanation:\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex1.png" + }, + { + "text": "Example 2: Input:s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]Output:\"eeecd\"Explanation:\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.", + "image": "https://assets.leetcode.com/uploads/2021/06/12/833-ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n \n inputs = list(zip(indices,sources,targets))\n inputs.sort(key = lambda x: x[0])\n \n offset = 0\n for idx, src, tgt in inputs:\n idx += offset\n if s[idx:idx + len(src)] != src:\n print('hi')\n print(idx)\n continue\n \n offset += len(tgt) - len(src)\n s = s[:idx] + tgt + s[idx+len(src):]\n \n return s\n", + "title": "833. Find And Replace in String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of strings words and a string pattern , return a list of words[i] that match pattern . You may return the answer in any order . A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x) , we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= pattern.length <= 20", + "1 <= words.length <= 50", + "words[i].length == pattern.length", + "pattern and words[i] are lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"Output:[\"mee\",\"aqq\"]Explanation:\"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\"], pattern = \"a\"Output:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findAndReplacePattern(String[] words, String pattern) {\n List result=new ArrayList<>();\n for(String word:words) {\n Map map=new HashMap<>();\n Set set=new HashSet<>();\n int i=0;\n for(;i m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\"], pattern = \"a\"Output:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 36.0%) | Memory: 16.40 MB (Top 44.2%)\n\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n d={}\n for i,v in enumerate(pattern):\n if v in d:\n d[v].append(i)\n else:\n d|={v:[i]}\n #DICTIONARY CONTAINING LETTERS AND THEIR INDICES\n ans=[]\n for i in words:\n e={}\n for j,v in enumerate(i):\n if v in e:\n e[v].append(j)\n else:\n e|={v:[j]}\n #DICTIONARY CONTAINING LETTERS OF INDICES OF CURRENT WORD\n for u,v in zip(d.values(),e.values()):\n #COMPARING EACH VALUE\n if u!=v:\n break\n #IF SUCCESSFUL APPEND TO ANS\n else:ans.append(i)\n return ans", + "title": "890. Find and Replace Pattern", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2 n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them . An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr . The sum of the elements in sub is one possible subset sum of arr . The sum of an empty array is considered to be 0 . Note: Test cases are generated such that there will always be at least one correct answer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "sums.length == 2 n", + "-10^4 <= sums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, sums = [-3,-2,-1,0,0,1,2,3]Output:[1,2,-3]Explanation:[1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, sums = [0,0,0,0]Output:[0,0]Explanation:The only correct answer is [0,0].", + "image": null + }, + { + "text": "Example 3: Input:n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]Output:[0,-1,4,5]Explanation:[0,-1,4,5] is able to achieve the given subset sums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 73 ms (Top 62.96%) | Memory: 85.2 MB (Top 70.37%)\nclass Solution {\n public int[] recoverArray(int n, int[] sums) {\n Arrays.sort(sums);\n int m = sums.length;\n int[] res = new int[n], left = new int[m / 2], right = new int[m / 2];\n for (int i = 0; i < n; ++i) {\n int diff = sums[1] - sums[0], hasZero = 0, p = -1, q = -1, k = 0;\n for (int j = 0; j < m; ++j) {\n if (k <= q && right[k] == sums[j]) k++;\n else {\n if (0 == sums[j]) hasZero = 1;\n left[++p] = sums[j];\n right[++q] = sums[j] + diff;\n }\n }\n if (1 == hasZero) {\n res[i] = diff;\n sums = left;\n } else {\n res[i] = -diff;\n sums = right;\n }\n m /= 2;\n }\n return res;\n }\n}", + "title": "1982. Find Array Given Subset Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2 n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them . An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr . The sum of the elements in sub is one possible subset sum of arr . The sum of an empty array is considered to be 0 . Note: Test cases are generated such that there will always be at least one correct answer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "sums.length == 2 n", + "-10^4 <= sums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, sums = [-3,-2,-1,0,0,1,2,3]Output:[1,2,-3]Explanation:[1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, sums = [0,0,0,0]Output:[0,0]Explanation:The only correct answer is [0,0].", + "image": null + }, + { + "text": "Example 3: Input:n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]Output:[0,-1,4,5]Explanation:[0,-1,4,5] is able to achieve the given subset sums.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4011 ms (Top 18.39%) | Memory: 19.7 MB (Top 40.23%)\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n res = [] # Result set\n sums.sort()\n\n while len(sums) > 1:\n num = sums[-1] - sums[-2] # max - secondMax\n countMap = Counter(sums) # Get count of each elements\n excluding = [] # Subset sums that do NOT contain num\n including = [] # Subset sums that contain num\n\n for x in sums:\n if countMap.get(x) > 0:\n excluding.append(x)\n including.append(x+num)\n countMap[x] -= 1\n countMap[x+num] -= 1\n\n # Check validity of excluding set\n if 0 in excluding:\n sums = excluding\n res.append(num)\n else:\n sums = including\n res.append(-1*num)\n\n return res", + "title": "1982. Find Array Given Subset Sums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,null,5,6,null,null,7]Output:7", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int max = Integer.MIN_VALUE;\n int res = -1;\n public int findBottomLeftValue(TreeNode root) {\n check(root,0);\n return res;\n }\n void check(TreeNode root, int h){\n if(root==null)\n return;\n if(h>max){\n max=h;\n res = root.val;\n }\n check(root.left,h+1);\n check(root.right,h+1);\n }\n}", + "title": "513. Find Bottom Left Tree Value", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the leftmost value in the last row of the tree. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,null,5,6,null,null,7]Output:7", + "image": "https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n \n res = root.val\n stack = [(0, root)]\n prev_d = 0\n \n while stack:\n \n curr_d, curr_v = stack.pop(0)\n \n if curr_v.left:\n stack.append((curr_d+1, curr_v.left))\n if prev_d != curr_d + 1:\n res = curr_v.left.val\n prev_d = curr_d+1\n \n if curr_v.right:\n stack.append((curr_d+1, curr_v.right))\n if prev_d != curr_d + 1:\n res = curr_v.right.val\n prev_d = curr_d+1\n \n return res\n\t\t\n\t\t# An Upvote will be encouraging\n", + "title": "513. Find Bottom Left Tree Value", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected star graph consisting of n nodes labeled from 1 to n . A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [u i , v i ] indicates that there is an edge between the nodes u i and v i . Return the center of the given star graph. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= u i, v i <= n", + "u i != v i", + "The given edges represent a valid star graph." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[2,3],[4,2]]Output:2Explanation:As shown in the figure above, node 2 is connected to every other node, so 2 is the center.", + "image": "https://assets.leetcode.com/uploads/2021/02/24/star_graph.png" + }, + { + "text": "Example 2: Input:edges = [[1,2],[5,1],[1,3],[1,4]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n \n \"\"\" From the Constraints: A valid STAR GRAPH is confirmed. \n\t\tThat means the center will be common to every edges. \n\t\tTherefore we can get the center by comparing only first 2 elements\"\"\"\n \n for i in range (1):\n \n # Check if first element of first edge mathches with any element of second edges\n \n if edges[i][0] == edges [i+1][0] or edges[i][0] == edges[i+1][1]:\n return edges[i][0]\n \n #Otherwise second element of first edge will be the answer\n else:\n return edges[i][1]\n", + "title": "1791. Find Center of Star Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from i , then edges[i] == -1 . You are also given two integers node1 and node2 . Return the index of the node that can be reached from both node1 and node2 , such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized . If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1 . Note that edges may contain cycles. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i", + "0 <= node1, node2 < n" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [2,2,3,-1], node1 = 0, node2 = 1Output:2Explanation:The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\nThe maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-2.png" + }, + { + "text": "Example 2: Input:edges = [1,2,-1], node1 = 0, node2 = 2Output:2Explanation:The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\nThe maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-4.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3032 ms (Top 5.02%) | Memory: 139.1 MB (Top 14.52%)\nclass Solution:\n def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:\n\n res = float(\"inf\")\n\n def dfs(node, arr, counter=0):\n\n #making sure we haven't visited the node before (i.e., value in the array != -1)\n while arr[node]==-1 and node!=-1:\n\n #assigning how many moves it takes to reach node\n arr[node] = counter\n next_node = edges[node]\n\n #going through each neighbor if exists and updating the counter\n dfs(edges[node], arr, counter+1)\n\n return arr\n\n #find moves to reach nodes from node1\n n1 = [-1 for i in range(len(edges))]\n dfs(node1, n1)\n\n #find moves to reach nodes from node2\n n2 = [-1 for i in range(len(edges))]\n dfs(node2, n2)\n\n answer = -1\n\n for i in range(len(edges)):\n\n #check if the end node is reachable from both starting nodes\n if n1[i]!=-1 and n2[i]!=-1:\n maximum_distance = max(n1[i], n2[i])\n\n #update the distance and the final answer if relevant\n if maximum_distance int:\n return min(nums, key=lambda x: (abs(x), -x))\n \n def findClosestNumber2(self, nums: List[int]) -> int:\n return min(nums, key=lambda x: abs(x - .1))\n \n def findClosestNumber3(self, nums: List[int]) -> int:\n return max((-abs(x), x) for x in nums)[1]\n \n def findClosestNumber4(self, nums: List[int]) -> int:\n return -min(zip(map(abs, nums), map(neg, nums)))[1]\n\n def findClosestNumber5(self, nums: List[int]) -> int:\n a = min(map(abs, nums))\n return a if a in nums else -a\n\n def findClosestNumber6(self, nums: List[int]) -> int:\n a = abs(min(nums, key=abs))\n return a if a in nums else -a\n\n def findClosestNumber7(self, nums: List[int]) -> int:\n x = min(nums, key=abs)\n return x if x >= 0 or -x not in nums else -x\n \n def findClosestNumber8(self, nums: List[int]) -> int:\n return min(sorted(nums, reverse=True), key=abs)\n \n def findClosestNumber9(self, nums: List[int]) -> int: \n a = abs(nums[0])\n for x in nums:\n if x < 0:\n x = -x\n if x < a:\n a = x\n return a if a in nums else -a\n \n def findClosestNumberA(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < 0:\n if x > neg:\n neg = x\n elif x < pos:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberB(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < pos and neg < x:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberC(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x and x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberD(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumber(self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]) -> int:\n name = 'findClosestNumber'\n solutions = [getattr(self, s)\n for s in dir(self)\n if s.startswith(name)\n and s != name]\n expect = dummy = object()\n from time import perf_counter as time\n for i in range(10):\n shuffle(solutions)\n for solution in solutions:\n start = time()\n result = solution(nums)\n end = time()\n if expect is dummy:\n expect = result\n assert result == expect\n timess[solution.__name__][i] += end - start\n testcase[0] += 1\n if testcase[0] == 224:\n for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):\n print(name, *(f'{t*1e3:6.2f} ms' for t in sorted(times)[:3]))\n return\n return result\n\t\t\n", + "title": "2239. Find Closest Number to Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string array words , return an array of all characters that show up in all strings within the words (including duplicates) . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"bella\",\"label\",\"roller\"]Output:[\"e\",\"l\",\"l\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"cool\",\"lock\",\"cook\"]Output:[\"c\",\"o\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 42.12%) | Memory: 14.3 MB (Top 6.17%)\nclass Solution:\n def _get_char_counts(self, s: str) -> dict[str]:\n \"\"\"builds a dict of letters : count\"\"\"\n d = {}\n for i in s:\n d[i] = d.get(i,0)+1\n return d\n\n def commonChars(self, words: list[str]) -> list[str]:\n \"\"\"returns a string of letters common between a list of words (including duplicates)\"\"\"\n if not words:\n return\n\n # O(n^2)\n words = [self._get_char_counts(word) for word in words]\n\n # O(nm), set intersection\n common = words[0].keys()\n for other in words[1:]:\n common &= other.keys()\n\n # O(nm), number of common characters across the number of words\n result = []\n for c in common:\n result += [c] * min(count[c] for count in words)\n\n return result", + "title": "1002. Find Common Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1 , and an array edges where edges[i] = [a i , b i , weight i ] represents a bidirectional and weighted edge between nodes a i and b i . A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST) . An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge . On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/06/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/06/04/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= min(200, n * (n - 1) / 2)", + "edges[i].length == 3", + "0 <= a i < b i < n", + "1 <= weight i <= 1000", + "All pairs (a i , b i ) are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]Output:[[0,1],[2,3,4,5]]Explanation:The figure above describes the graph.\nThe following figure shows all the possible MSTs:Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]Output:[[],[0,1,2,3]]Explanation:We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static class UnionFind{\n int[]parent;\n int[]rank;\n int comp = 0;\n UnionFind(int n){\n parent = new int[n];\n rank = new int[n];\n comp = n;\n for(int i=0;i{\n int u;\n int v;\n int wt;\n Edge(int u,int v,int wt){\n this.u = u;\n this.v = v;\n this.wt = wt;\n }\n public int compareTo(Edge o){\n return this.wt - o.wt;\n } \n }\n public int buildMST(int n,int[][]edges,int[]edgeSkip,int[]edgePick){\n PriorityQueue pq = new PriorityQueue<>();\n \n for(int[]edge : edges){\n if(edge == edgeSkip){\n continue;\n }else if(edge == edgePick){\n continue;\n }\n int u = edge[0];\n int v = edge[1];\n int wt = edge[2];\n pq.add(new Edge(u,v,wt));\n }\n \n UnionFind uf = new UnionFind(n);\n int cost = 0;\n \n if(edgePick != null){\n uf.union(edgePick[0],edgePick[1]);\n cost += edgePick[2];\n }\n while(pq.size() > 0){\n Edge rem = pq.remove();\n if(uf.union(rem.u,rem.v) == true){\n cost += rem.wt;\n }\n }\n \n if(uf.isConnected() == true){\n return cost;\n }else{\n return Integer.MAX_VALUE;\n }\n }\n \n public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n int mstCost = buildMST(n,edges,null,null);\n \n ArrayList critical = new ArrayList<>();\n ArrayList pcritical = new ArrayList<>();\n \n for(int i=0;i mstCost){\n critical.add(i); //Critical edge index\n }else{\n int mstCostWithEdge = buildMST(n,edges,null,edge);\n if(mstCostWithEdge > mstCost){\n //redundant\n }else{\n pcritical.add(i); //pseduo critical edge index\n }\n }\n }\n \n List> res = new ArrayList<>();\n res.add(critical);\n res.add(pcritical);\n return res;\n }\n}\n\n\n", + "title": "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1 , and an array edges where edges[i] = [a i , b i , weight i ] represents a bidirectional and weighted edge between nodes a i and b i . A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST) . An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge . On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/06/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/06/04/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= min(200, n * (n - 1) / 2)", + "edges[i].length == 3", + "0 <= a i < b i < n", + "1 <= weight i <= 1000", + "All pairs (a i , b i ) are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]Output:[[0,1],[2,3,4,5]]Explanation:The figure above describes the graph.\nThe following figure shows all the possible MSTs:Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]Output:[[],[0,1,2,3]]Explanation:We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n def find(v, parent):\n if parent[v] != v:\n parent[v] = find(parent[v], parent)\n return parent[v]\n def union(u,v, parent):\n parent[find(u,parent)] = find(v,parent)\n edges = [(u,v,w,i) for i, (u,v,w) in enumerate(edges)]\n edges.sort(key = lambda e:e[2])\n def find_mst_without_this_edge(idx):\n parent = list(range(n))\n res = 0\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx: continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n def find_mst_with_this_edge(idx):\n parent = list(range(n))\n u0, v0, w0, _ = edges[idx]\n res = w0\n union(u0,v0,parent)\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx:\n continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n base_mst_wgt = find_mst_without_this_edge(-1)\n cri, pcri = set(), set()\n for i in range(len(edges)):\n wgt_excl = find_mst_without_this_edge(i)\n if wgt_excl > base_mst_wgt:\n cri.add(edges[i][3])\n else:\n wgt_incl = find_mst_with_this_edge(i)\n if wgt_incl == base_mst_wgt:\n pcri.add(edges[i][3])\n return [cri, pcri]\n", + "title": "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths . You may return the answer in any order . A group of duplicate files consists of at least two files that have the same content. A single directory info string in the input list has the following format: It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory \" root/d1/d2/.../dm\" . Note that n >= 1 and m >= 0 . If m = 0 , it means the directory is just the root directory. The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "\"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)\"" + ], + "examples": [ + { + "text": "Example 1: Input:paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]Output:[[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]", + "image": null + }, + { + "text": "Example 2: Input:paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]Output:[[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n vector> findDuplicate(vector& paths) {\n vector> vec1;\n for(int i = 0; i < paths.size(); ++i){\n vector level;\n string temp1 = paths[i];\n string temp2 = \"\";\n for(int j = 0; j < temp1.length(); ++j){\n if(temp1[j] == ' '){\n level.push_back(temp2);\n temp2 = \"\";\n }\n else\n temp2 += temp1[j];\n if(j == temp1.length() - 1)\n level.push_back(temp2);\n }\n vec1.push_back(level);\n }\n unordered_map> ump;\n for(int i = 0; i < vec1.size(); ++i){\n string rootDir = vec1[i][0];\n for(int j = 1; j < vec1[i].size(); ++j){\n string str1 = rootDir, str2 = \"\";\n int pos = -1;\n for(int k = 0; k < vec1[i][j].length(); ++k){\n if(vec1[i][j][k] == '('){\n pos = k;\n break;\n }\n }\n str1 += '/';\n for(int k = 0; k < pos; ++k)\n str1 += vec1[i][j][k];\n str2 = vec1[i][j].substr(pos);\n ump[str2].push_back(str1);\n }\n }\n vector> res;\n for(auto it = ump.begin(); it != ump.end(); ++it)\n if(it->second.size() > 1)\n res.push_back(it->second);\n return res;\n }\n};\n", + "title": "609. Find Duplicate File in System", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return all duplicate subtrees . For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree will be in the range [1, 10^4]", + "-200 <= Node.val <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,null,2,4,null,null,4]Output:[[2,4],[4]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e1.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,1]Output:[[1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e2.jpg" + }, + { + "text": "Example 3: Input:root = [2,2,2,3,null,3,null]Output:[[2,3],[3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e33.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1783 ms (Top 5.02%) | Memory: 64.5 MB (Top 11.80%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List findDuplicateSubtrees(TreeNode root) {\n List list = new ArrayList();\n HashSet hashes = new HashSet();\n HashSet added = new HashSet();\n\n // for each node, perform a dfs traversal and generate a hash\n // check if the hash already exists in a set,\n // if it does, get the treenode and add it to the list\n Stack s = new Stack();\n\n s.add(root);\n while(!s.isEmpty()){\n TreeNode tmp = s.pop();\n dfs(tmp, \"\", tmp, list, hashes, added);\n\n if(tmp.left != null){\n s.add(tmp.left);\n }\n if(tmp.right != null){\n s.add(tmp.right);\n }\n }\n\n return list;\n\n }\n\n public void dfs(TreeNode parent, String hash, TreeNode root, List list, HashSet set, HashSet added){\n\n Stack stack = new Stack();\n\n stack.add(root);\n //String hash = \"\";\n hash += root.val + \"ROOT,\";\n while(!stack.isEmpty()){\n TreeNode tmp = stack.pop();\n //hash += tmp.val + \",\";\n\n if(tmp.left != null){\n hash += tmp.left.val + \"L,\";\n stack.add(tmp.left);\n }\n else{\n hash+= \"NULLL,\";\n }\n if(tmp.right != null){\n hash += tmp.right.val + \"R,\";\n stack.add(tmp.right);\n }\n else{\n hash+=\"NULLR,\";\n }\n if(tmp.left == null && tmp.right == null && stack.isEmpty()){\n if(set.contains(hash)){\n if(!added.contains(hash)){\n list.add(parent);\n added.add(hash);\n }\n }\n else{\n set.add(hash);\n }\n return;\n }\n\n }\n }\n}", + "title": "652. Find Duplicate Subtrees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return all duplicate subtrees . For each kind of duplicate subtrees, you only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with the same node values . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of the nodes in the tree will be in the range [1, 10^4]", + "-200 <= Node.val <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,null,2,4,null,null,4]Output:[[2,4],[4]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e1.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,1]Output:[[1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e2.jpg" + }, + { + "text": "Example 3: Input:root = [2,2,2,3,null,3,null]Output:[[2,3],[3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/16/e33.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n ans = []\n path_map = {}\n \n def dfs(node):\n if not node:\n return \"#\"\n \n path = \",\".join([str(node.val), dfs(node.left), dfs(node.right)])\n \n if path in path_map:\n path_map[path] += 1\n if path_map[path] == 2:\n ans.append(node)\n else:\n path_map[path] = 1\n \n return path\n \n \n dfs(root)\n return ans\n", + "title": "652. Find Duplicate Subtrees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1 . Implement the FindElements class: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.", + "bool find(int target) Returns true if the target value exists in the recovered binary tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]Output[null,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg" + }, + { + "text": "Example 2: Input[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]Output[null,true,true,false]ExplanationFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg" + }, + { + "text": "Example 3: Input[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]Output[null,true,false,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 75.56%) | Memory: 52.2 MB (Top 77.99%)\nclass FindElements {\n TreeNode tree,nodept;\n public FindElements(TreeNode root) {\n tree=root;\n tree.val=0;\n go(tree);\n }\n\n void go(TreeNode node){\n if(node.left!=null){\n node.left.val=node.val*2+1;\n go(node.left);\n }\n if(node.right!=null){\n node.right.val=node.val*2+2;\n go(node.right);\n }\n }\n\n public boolean find(int target) {\n return doit(target);\n }\n\n boolean doit(int target){\n if(target==0){\n nodept=tree;\n return true;\n }\n boolean f=doit((target-1)/2);\n if(!f)return false;\n if(nodept.left!=null && nodept.left.val==target)\n nodept=nodept.left;\n else if(nodept.right!=null && nodept.right.val==target)\n nodept=nodept.right;\n else f=false;\n return f;\n }\n}", + "title": "1261. Find Elements in a Contaminated Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1 . Implement the FindElements class: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.", + "bool find(int target) Returns true if the target value exists in the recovered binary tree." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]Output[null,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg" + }, + { + "text": "Example 2: Input[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]Output[null,true,true,false]ExplanationFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False", + "image": "https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg" + }, + { + "text": "Example 3: Input[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]Output[null,true,false,false,true]ExplanationFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True", + "image": "https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 227 ms (Top 13.41%) | Memory: 18.1 MB (Top 62.12%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass FindElements:\n\n def __init__(self, root: Optional[TreeNode]):\n def recoverTree(root):\n if not root:\n return None\n self.vals.add(root.val)\n if root.left:\n root.left.val = 2 * root.val + 1\n recoverTree(root.left)\n if root.right:\n root.right.val = 2 * root.val + 2\n recoverTree(root.right)\n self.vals = set()\n root.val = 0\n recoverTree(root)\n\n def find(self, target: int) -> bool:\n return target in self.vals\n\n# Your FindElements object will be instantiated and called as such:\n# obj = FindElements(root)\n# param_1 = obj.find(target)", + "title": "1261. Find Elements in a Contaminated Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2],[2,3],[5],[0],[5],[],[]]Output:[2,4,5,6]Explanation:The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png" + }, + { + "text": "Example 2: 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.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 80.80%) | Memory: 65.9 MB (Top 65.16%)\n\nclass Solution {\n public List eventualSafeNodes(int[][] graph) {\n int n=graph.length;\n List ans=new ArrayList<>();\n\n boolean visited[]=new boolean[n];\n boolean dfsVisited[]=new boolean[n];\n\n boolean nodeCycles[]=new boolean[n];\n\n for(int i=0;i list[int]:\n\n n = len(graph)\n ans = []\n \n for i in range(n):\n if not graph[i]:\n ans.append(i)\n \n def loop(key, loops):\n \n loops.append(key)\n for i in graph[key]:\n if i in loops:\n return False\n elif i in ans: \n continue\n else:\n r = loop(i, loops)\n if r == True: \n continue\n else: \n return False\n\n idx = loops.index(key)\n loops.pop(idx)\n return True\n \n for i in range(n):\n loops = []\n if i in ans:\n continue\n r = loop(i, loops)\n if r == True: ans.append(i)\n \n return sorted(ans)\n", + "title": "802. Find Eventual Safe States", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8Output:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6Output:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0Output:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 22.02%) | Memory: 45.50 MB (Top 10.41%)\n\nclass Solution {\n public int[] searchRange(int[] nums, int target) {\n int first = -1, last = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n if (first == -1) {\n first = i;\n }\n last = i;\n }\n }\n return new int[]{first, last};\n }\n}\n\n", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8Output:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6Output:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0Output:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n # if target is not in nums list, we simply return [-1,-1]\n\t\tif target not in nums:\n return [-1,-1]\n \n\t\t# create an empty list\n result = []\n\t\t# iterate nums for the first time, if we found nums[i] matches with target\n\t\t# append the index i to result, break the for loop\n\t\t# because we only care the first and last index of target in nums\n for i in range(len(nums)):\n if nums[i] == target:\n result.append(i)\n break\n \n\t\t# loop through nums backward, if we found nums[j] matches target\n\t\t# append j to result and break the for loop\n for j in range(len(nums)-1, -1, -1):\n if nums[j] == target:\n result.append(j)\n break\n \n return result\n\t\t\n\t\t\n", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words , return the first palindromic string in the array . If there is no such string, return an empty string \"\" . A string is palindromic if it reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]Output:\"ada\"Explanation:The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"notapalindrome\",\"racecar\"]Output:\"racecar\"Explanation:The first and only string that is palindromic is \"racecar\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"def\",\"ghi\"]Output:\"\"Explanation:There are no palindromic strings, so the empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String firstPalindrome(String[] words) {\n for (String s : words) {\n StringBuilder sb = new StringBuilder(s);\n if (s.equals(sb.reverse().toString())) {\n return s;\n }\n }\n return \"\";\n }\n}", + "title": "2108. Find First Palindromic String in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words , return the first palindromic string in the array . If there is no such string, return an empty string \"\" . A string is palindromic if it reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]Output:\"ada\"Explanation:The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"notapalindrome\",\"racecar\"]Output:\"racecar\"Explanation:The first and only string that is palindromic is \"racecar\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"def\",\"ghi\"]Output:\"\"Explanation:There are no palindromic strings, so the empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def firstPalindrome(self, words):\n for word in words:\n if word == word[::-1]: return word\n return \"\"\n", + "title": "2108. Find First Palindromic String in the Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2Output:[2,3]Explanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0Output:[0,1,2,3,4]Explanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2Output:[]Explanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 6.78%) | Memory: 59.90 MB (Top 5.93%)\n\nclass Solution {\n public List goodDaysToRobBank(int[] security, int time) {\n List res = new ArrayList<>();\n if (time == 0) {\n for (int i = 0; i < security.length; i++) res.add(i);\n return res;\n }\n Set set = new HashSet<>();\n int count = 1;\n for (int i = 1; i < security.length; i++) {\n if (security[i] <= security[i - 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time) {\n set.add(i);\n }\n }\n \n count = 1;\n for (int i = security.length - 2; i >= 0; i--) {\n if (security[i] <= security[i + 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time && set.contains(i)) res.add(i);\n }\n return res;\n }\n}\n", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2Output:[2,3]Explanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0Output:[0,1,2,3,4]Explanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2Output:[]Explanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List goodDaysToRobBank(int[] security, int time) {\n int[] nonincrease = new int[security.length];\n for(int i = 1; i < security.length - time; i++){\n if(security[i]>security[i-1]){\n nonincrease[i] = 0;\n } else {\n nonincrease[i] = nonincrease[i-1] + 1;\n }\n }\n\n int[] nondecrease = new int[security.length];\n for(int i = security.length - 2; i >= time; i--) {\n if(security[i] > security[i + 1]){\n nondecrease[i] = 0;\n } else {\n nondecrease[i] = nondecrease[i + 1] + 1;\n }\n }\n\n ArrayList result = new ArrayList<>();\n for(int i = time; i < security.length - time; i++) {\n if(nonincrease[i] >= time && nondecrease[i] >= time) {\n result.add(i);\n }\n }\n return result;\n\n }\n", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security , where security[i] is the number of guards on duty on the i th day. The days are numbered starting from 0 . You are also given an integer time . The i th day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time] . Return a list of all days (0-indexed) that are good days to rob the bank . The order that the days are returned in does not matter. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are at least time days before and after the i th day,", + "The number of guards at the bank for the time days before i are non-increasing , and", + "The number of guards at the bank for the time days after i are non-decreasing ." + ], + "examples": [ + { + "text": "Example 1: Input:security = [5,3,3,3,5,6,2], time = 2Output:[2,3]Explanation:On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.", + "image": null + }, + { + "text": "Example 2: Input:security = [1,1,1,1,1], time = 0Output:[0,1,2,3,4]Explanation:Since time equals 0, every day is a good day to rob the bank, so return every day.", + "image": null + }, + { + "text": "Example 3: Input:security = [1,2,3,4,5,6], time = 2Output:[]Explanation:No day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n decreasing = [0] * len(security)\n increasing = [0] * len(security)\n for i in range(len(security)):\n if i > 0 and security[i - 1] >= security[i]:\n decreasing[i] = decreasing[i - 1] + 1\n for i in reversed(range(len(security))):\n if i < len(security) - 1 and security[i] <= security[i + 1]:\n increasing[i] = increasing[i + 1] + 1\n return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time]", + "title": "2100. Find Good Days to Rob the Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the greatest common divisor of the smallest number and largest number in nums . The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,9,10]Output:2Explanation:The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,5,6,8,3]Output:1Explanation:The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3]Output:3Explanation:The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 25.8%) | Memory: 42.56 MB (Top 95.7%)\n\nclass Solution {\n public int findGCD(int[] nums) {\n Arrays.sort(nums);\n int n=nums[nums.length-1];\n int result=nums[0];\n while(result>0){\n if(nums[0]%result==0 && n%result==0){\n break;\n }\n result--;\n }\n return result;\n }\n}", + "title": "1979. Find Greatest Common Divisor of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the greatest common divisor of the smallest number and largest number in nums . The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,9,10]Output:2Explanation:The smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,5,6,8,3]Output:1Explanation:The smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3]Output:3Explanation:The smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 282 ms (Top 5.10%) | Memory: 13.9 MB (Top 81.34%)\nclass Solution:\n def findGCD(self, nums: List[int]) -> int:\n i_min = min(nums)\n i_max = max(nums)\n greater = i_max\n while True:\n if greater % i_min == 0 and greater % i_max == 0:\n lcm = greater\n break\n greater += 1\n return int(i_min/(lcm/i_max))", + "title": "1979. Find Greatest Common Divisor of Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination . Given edges and the integers n , source , and destination , return true if there is a valid path from source to destination , or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^5", + "0 <= edges.length <= 2 * 10^5", + "edges[i].length == 2", + "0 <= u i , v i <= n - 1", + "u i != v i", + "0 <= source, destination <= n - 1", + "There are no duplicate edges.", + "There are no self edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2Output:trueExplanation:There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2", + "image": "https://assets.leetcode.com/uploads/2021/08/14/validpath-ex1.png" + }, + { + "text": "Example 2: Input:n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5Output:falseExplanation:There is no path from vertex 0 to vertex 5.", + "image": "https://assets.leetcode.com/uploads/2021/08/14/validpath-ex2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1647 ms (Top 68.5%) | Memory: 108.91 MB (Top 50.2%)\n\nclass Solution(object):\n def validPath(self, n, edges, start, end):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type start: int\n :type end: int\n :rtype: bool\n \"\"\"\n visited = [False]*n\n d = {}\n\t\t#store the undirected edges for both vertices\n for i in edges:\n if i[0] in d:\n d[i[0]].append(i[1])\n else:\n d[i[0]] = [i[1]]\n \n if i[1] in d:\n d[i[1]].append(i[0])\n else:\n d[i[1]] = [i[0]]\n #create a queue as we will apply BFS\n q = [start]\n while q:\n curr = q.pop(0) #pop the first element as we do in queue\n if curr == end: #if its the end then we can return True\n return True\n elif curr in d and not visited[curr]: #else if it is not the end then check whether its visited or not\n q.extend(d[curr]) #add the adjacent vertices of the current node to the queue\n visited[curr] = True #mark this curr vertex as visited = True, so that we dont visit this vertex again\n return False #return False if the queue gets empty and we dont reach the end", + "title": "1971. Find if Path Exists in Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "(This problem is an interactive problem .) You may recall that an array arr is a mountain array if and only if: Given a mountain array mountainArr , return the minimum index such that mountainArr.get(index) == target . If such an index does not exist, return -1 . You cannot access the mountain array directly. You may only access the array using a MountainArray interface: Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer . Also, any solutions that attempt to circumvent the judge will result in disqualification. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:array = [1,2,3,4,5,3,1], target = 3Output:2Explanation:3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.", + "image": null + }, + { + "text": "Example 2: Input:array = [0,1,2,4,2,1], target = 3Output:-1Explanation:3 does not exist inthe array,so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findInMountainArray(int target, MountainArray mountainArr) {\n int peak = findPeak(mountainArr);\n \n int left =binary(0,peak,mountainArr,target,true);\n if(left!=-1){\n return left;\n }\n int right= binary(peak+1,mountainArr.length()-1,mountainArr, target,false);\n return right; \n }\n \n static int findPeak(MountainArray mountainArr){\n int start=0;\n int end =mountainArr.length()-1;\n \n while(startarr.get(mid)){\n if(left){\n low=mid+1;\n }else{\n high=mid-1; \n } \n }else{\n return mid;\n }\n } \n return -1;\n }\n}\n", + "title": "1095. Find in Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "(This problem is an interactive problem .) You may recall that an array arr is a mountain array if and only if: Given a mountain array mountainArr , return the minimum index such that mountainArr.get(index) == target . If such an index does not exist, return -1 . You cannot access the mountain array directly. You may only access the array using a MountainArray interface: Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer . Also, any solutions that attempt to circumvent the judge will result in disqualification. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:array = [1,2,3,4,5,3,1], target = 3Output:2Explanation:3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.", + "image": null + }, + { + "text": "Example 2: Input:array = [0,1,2,4,2,1], target = 3Output:-1Explanation:3 does not exist inthe array,so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:\n min_index = -1\n peak = self.findpeak(mountain_arr)\n \n min_index = self.binary_search(0, peak, mountain_arr, target, 1)\n if min_index == -1:\n min_index = self.binary_search(peak+1, mountain_arr.length() - 1, mountain_arr, target, -1)\n return min_index\n\n def findpeak(self, mountain_arr):\n start = 0\n end = mountain_arr.length() - 1\n while start < end:\n mid = start + int((end - start)/2)\n if mountain_arr.get(mid) < mountain_arr.get(mid + 1):\n start = mid + 1\n else:\n end = mid\n \n return start\n \n def binary_search(self, start, end, mountain_arr, target, asc):\n while start <= end:\n mid = start + int((end - start)/2)\n mountain_arr_get_mid = mountain_arr.get(mid)\n if target == mountain_arr_get_mid:\n return mid\n if asc == 1:\n if target < mountain_arr_get_mid:\n end = mid - 1\n elif target > mountain_arr_get_mid:\n start = mid + 1\n else:\n if target < mountain_arr_get_mid:\n start = mid + 1\n elif target > mountain_arr_get_mid:\n end = mid - 1\n \n return -1\n\n\n\n\n\n\n", + "title": "1095. Find in Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted integer array arr , two integers k and x , return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "|a - x| < |b - x| , or", + "|a - x| == |b - x| and a < b" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 4, x = 3Output:[1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5], k = 4, x = -1Output:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 41.96%) | Memory: 62.2 MB (Top 71.32%)\nclass Solution {\npublic List findClosestElements(int[] arr, int k, int x) {\n List result = new ArrayList<>();\n\n int low = 0, high = arr.length -1;\n\n while(high - low >= k){\n if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x))\n low++;\n else\n high--;\n }\n\n for(int i = low; i <= high; i++)\n result.add(arr[i]);\n\n return result;\n}\n}", + "title": "658. Find K Closest Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sorted integer array arr , two integers k and x , return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "|a - x| < |b - x| , or", + "|a - x| == |b - x| and a < b" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 4, x = 3Output:[1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4,5], k = 4, x = -1Output:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n \n def sorted_distance(value, static_input = x):\n return abs(value - static_input)\n \n distances = []\n result = []\n heapq.heapify(distances)\n \n for l,v in enumerate(arr):\n distances.append((l, sorted_distance(value = v)))\n \n for i in heapq.nsmallest(k, distances, key = lambda x: x[1]):\n result.append(arr[i[0]])\n \n result.sort()\n return result\n \n \n", + "title": "658. Find K Closest Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in ascending order .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3Output:[[1,2],[1,4],[1,6]]Explanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2Output:[[1,1],[1,1]]Explanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2], nums2 = [3], k = 3Output:[[1,3],[2,3]]Explanation:All possible pairs are returned from the sequence: [1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 44.52%) | Memory: 128.2 MB (Top 22.61%)\nclass Solution {\n public List> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n PriorityQueue pq = new PriorityQueue<>(\n (a, b) -> (a[0] + a[1]) - (b[0] + b[1])\n );\n for(int i = 0; i < nums1.length && i < k; i++){\n pq.add(new int[]{nums1[i], nums2[0], 0});\n }\n\n List> res = new ArrayList<>();\n for(int i = 0; i < k && !pq.isEmpty(); i++){\n int [] curr = pq.poll();\n res.add(Arrays.asList(curr[0], curr[1]));\n int idx2 = curr[2];\n if(idx2 < nums2.length - 1){\n pq.add(new int[]{curr[0], nums2[idx2 + 1], idx2 + 1});\n }\n }\n return res;\n }\n}", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in ascending order .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3Output:[[1,2],[1,4],[1,6]]Explanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2Output:[[1,1],[1,1]]Explanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2], nums2 = [3], k = 3Output:[[1,3],[2,3]]Explanation:All possible pairs are returned from the sequence: [1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1647 ms (Top 67.28%) | Memory: 34.4 MB (Top 27.52%)\nimport heapq\nclass Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n\n ans = []\n\n heapq.heapify(ans)\n\n for i in range(min(k,len(nums1))):\n for j in range(min(k,len(nums2))):\n pairs = [nums1[i],nums2[j]]\n if len(ans)-ans[0][0]:\n break\n heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs])\n heapq.heappop(ans)\n\n res = []\n for i in range(len(ans)):\n res.append(ans[i][1])\n\n return res", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^4", + "0 <= nums[i] <= 10^6", + "1 <= k <= n * (n - 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1], k = 1Output:0Explanation:Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1stsmallest distance pair is (1,1), and its distance is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 2Output:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,6,1], k = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int smallestDistancePair(int[] nums, int k) {\n Arrays.sort(nums);\n int low = 0, high = nums[nums.length-1] - nums[0];\n \n while(low<=high){\n int mid = low + (high-low)/2;\n if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private int noOfDistancesLessThan(int dist,int[] nums){\n int count = 0,i = 0, j = 0;\n while(i 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1stsmallest distance pair is (1,1), and its distance is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1], k = 2Output:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,6,1], k = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heappush, heappop, heapify\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n # pairs = list(combinations(nums, 2))\n \n maxHeap = []\n heapify(maxHeap)\n \n for idx, val1 in enumerate(nums):\n for val2 in nums[idx + 1:]:\n pair = [val1, val2]\n heappush(maxHeap, [-1*abs(pair[0] - pair[1]), pair])\n if len(maxHeap) > k:\n heappop(maxHeap)\n \n return -1*maxHeap[0][0]\n", + "title": "719. Find K-th Smallest Pair Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two positive integers n and k , the binary string S n is formed as follows: Where + denotes the concatenation operation, reverse(x) returns the reversed string x , and invert(x) inverts all the bits in x ( 0 changes to 1 and 1 changes to 0 ). For example, the first four strings in the above sequence are: Return the k th bit in S n . It is guaranteed that k is valid for the given n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "S 1 = \"0\"", + "S i = S i - 1 + \"1\" + reverse(invert(S i - 1 )) for i > 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1Output:\"0\"Explanation:S3is \"0111001\".\nThe 1stbit is \"0\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 11Output:\"1\"Explanation:S4is \"011100110110001\".\nThe 11thbit is \"1\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2755 ms (Top 5.21%) | Memory: 238.8 MB (Top 5.21%)\nclass Solution {\n private String invert(String s){\n char [] array=s.toCharArray();\n for(int i=0;i 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 1Output:\"0\"Explanation:S3is \"0111001\".\nThe 1stbit is \"0\".", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 11Output:\"1\"Explanation:S4is \"011100110110001\".\nThe 11thbit is \"1\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n i, s, hash_map = 1, '0', {'1': '0', '0': '1'}\n for i in range(1, n):\n s = s + '1' + ''.join((hash_map[i] for i in s))[::-1]\n return s[k-1]", + "title": "1545. Find Kth Bit in Nth Binary String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D matrix of size m x n , consisting of non-negative integers. You are also given an integer k . The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed) . Find the k th largest value (1-indexed) of all the coordinates of matrix . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "0 <= matrix[i][j] <= 10^6", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[5,2],[1,6]], k = 1Output:7Explanation:The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[5,2],[1,6]], k = 2Output:5Explanation:The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[5,2],[1,6]], k = 3Output:4Explanation:The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 96.62%) | Memory: 250.3 MB (Top 62.84%)\nclass Solution {\n\n private static final Random RAND = new Random(0);\n\n public int kthLargestValue(int[][] matrix, int k) {\n var xor = convertToXorArray(matrix);\n var targetIdx = xor.length - k;\n sortPartially(xor, targetIdx, 0, xor.length);\n return xor[targetIdx];\n }\n\n void sortPartially(int[] nums, int targetIdx, int origLo, int origHi) {\n if (origHi - origLo < 2)\n return;\n\n var pivotIdx = RAND.nextInt(origHi - origLo) + origLo;\n var pivot = nums[pivotIdx];\n swap(nums, origLo, pivotIdx);\n\n var lo = origLo;\n var mid = lo + 1;\n var hi = origHi;\n while (mid < hi) {\n if (pivot < nums[mid])\n swap(nums, mid, --hi);\n else if (pivot > nums[mid])\n swap(nums, mid++, lo++);\n else\n mid++;\n }\n\n if (targetIdx < lo)\n sortPartially(nums, targetIdx, origLo, lo);\n\n sortPartially(nums, targetIdx, mid, origHi);\n }\n\n void swap(int[] n, int p, int q) {\n var tmp = n[p];\n n[p] = n[q];\n n[q] = tmp;\n }\n\n int[] convertToXorArray(int[][] matrix) {\n var rows = matrix.length;\n var cols = matrix[0].length;\n var xor = new int[rows * cols];\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n var xIdx = r * cols + c;\n xor[xIdx] = matrix[r][c];\n if (c > 0)\n xor[xIdx] ^= xor[xIdx - 1];\n }\n }\n\n for (int i = cols; i < xor.length; i++)\n xor[i] ^= xor[i - cols];\n\n return xor;\n }\n}", + "title": "1738. Find Kth Largest XOR Coordinate Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D matrix of size m x n , consisting of non-negative integers. You are also given an integer k . The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed) . Find the k th largest value (1-indexed) of all the coordinates of matrix . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "0 <= matrix[i][j] <= 10^6", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[5,2],[1,6]], k = 1Output:7Explanation:The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[5,2],[1,6]], k = 2Output:5Explanation:The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[5,2],[1,6]], k = 3Output:4Explanation:The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n temp=0\n pq= []\n n = len(matrix)\n m = len(matrix[0])\n \n prefix= [ [0]*m for i in range(n) ]\n \n \n for i in range(n):\n for j in range(m):\n if i==0 or j==0:\n if i==0 and j==0:\n prefix[i][j] = matrix[i][j]\n elif i==0 and j!=0:\n prefix[i][j] ^= prefix[i][j-1]^ matrix[i][j]\n else:\n prefix[i][j]^=prefix[i-1][j]^ matrix[i][j]\n else:\n \n prefix[i][j] ^= prefix[i-1][j] ^ prefix[i][j-1]^matrix[i][j]^prefix[i-1][j-1]\n if len(pq) li=new ArrayList<>();\n\n public List largestValues(TreeNode root) {\n\n if(root==null) return li; //if root is NULL\n\n //using bfs(level-order)\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty()){\n int size=q.size();\n int res=Integer.MIN_VALUE;\n while(size-->0){\n TreeNode temp=q.poll();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n res =Math.max(res,temp.val); //comparing every node in each level to get max\n }\n li.add(res); //adding each level Max value to the list\n }\n return li;\n }\n}", + "title": "515. Find Largest Value in Each Tree Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,3,2,5,3,null,9]Output:[1,3,9]", + "image": "https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3]Output:[1,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def largestValues(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n ans=[]\n q=[]\n q.append(root)\n while q:\n s=len(q)\n t=[]\n for i in range(s):\n n=q.pop(0)\n t.append(n.val)\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n ans.append(max(t))\n return ans\n", + "title": "515. Find Largest Value in Each Tree Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr that represents a permutation of numbers from 1 to n . You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n , the bit at position arr[i] is set to 1 . You are also given an integer m . Find the latest step at which there exists a group of ones of length m . A group of ones is a contiguous substring of 1 's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m . If no such group exists, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= m <= n <= 10^5", + "1 <= arr[i] <= n", + "All integers in arr are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1,2,4], m = 1Output:4Explanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,1,5,4,2], m = 2Output:-1Explanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int[] par, size, count, bits; \n // par: parent array, tells about whose it the parent of ith element\n // size: it tells the size of component\n // count: it tells the count of islands (1111 etc) of size i;\n // count[3] = 4: ie -> there are 4 islands of size 3\n \n public int find(int u) {\n if (u == par[u]) return u;\n par[u] = find(par[u]);\n return par[u];\n }\n \n public void union(int u, int v) {\n // union is performed over parents of elements not nodes itself\n int p1 = find(u), p2 = find(v);\n if (p1 == p2) return;\n \n // decrease the count of islands of size p1, p2\n count[size[p1]]--;\n count[size[p2]]--;\n \n // now merge\n par[p2] = p1;\n \n // adjust sizes\n size[p1] += size[p2];\n \n // adjust the count of islands of new size ie: size of p1\n count[size[p1]]++;\n }\n \n public int findLatestStep(int[] arr, int m) {\n int n = arr.length;\n par = new int[n + 1];\n size = new int[n + 1];\n count = new int[n + 1];\n bits = new int[n + 2];\n \n for (int i = 0; i < n; i++) {\n par[i] = i;\n size[i] = 1;\n }\n \n int ans = -1;\n for (int i = 0; i < n; i++) {\n int idx = arr[i];\n // set the bit\n bits[idx] = 1;\n // increase the count of islands of size 1\n count[1]++;\n \n if (bits[idx - 1] > 0) {\n union(idx, idx - 1);\n } \n if (bits[idx + 1] > 0) {\n union(idx, idx + 1);\n }\n \n // check if island of size m exists\n if (count[m] > 0) {\n ans = i + 1;\n // as it is 1 based indexing\n }\n }\n return ans;\n }\n}\n\n", + "title": "1562. Find Latest Group of Size M", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array arr that represents a permutation of numbers from 1 to n . You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n , the bit at position arr[i] is set to 1 . You are also given an integer m . Find the latest step at which there exists a group of ones of length m . A group of ones is a contiguous substring of 1 's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m . If no such group exists, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= m <= n <= 10^5", + "1 <= arr[i] <= n", + "All integers in arr are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,5,1,2,4], m = 1Output:4Explanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,1,5,4,2], m = 2Output:-1Explanation:Step 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n n = len(arr)\n ans = -1\n if n == m: return m #just in case\n \n# make in \"inverted\" array with artificial ends higher then everything between\n\n sor= [0 for _ in range(n+2)]\n for i in range(n):\n sor[(arr[i])] = i+1 \n sor[0] = sor[n+1] = n+1\n \n# scan and see, if ones in the middle of space of length m appear \n# before ones on its ends,\n# and find the latest of such spaces to disappear, if exists\n\n for i in range(1, n-m+2): \n if all(sor[i-1]>sor[j] and sor[i+m]>sor[j] for j in range(i,i+m)):\n if min(sor[i-1]-1,sor[i+m]-1)>ans: ans = min(sor[i-1]-1,sor[i+m]-1) \n return ans\n", + "title": "1562. Find Latest Group of Size M", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome. Return the length of the maximum length awesome substring of s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists only of digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3242415\"Output:5Explanation:\"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"12345678\"Output:1", + "image": null + }, + { + "text": "Example 3: Input:s = \"213123\"Output:6Explanation:\"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestAwesome(String s) {\n Mapmap=new HashMap<>();\n map.put(0,-1);\n \n int state=0;\n int ans=0;\n for(int i=0;i int:\n # li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n li = [2**i for i in range(10)]\n # checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}\n checker = set(li)\n checker.add(0)\n # di: k = prefix xor, v = the first idx I got a new prefix_xor_value.\n di = collections.OrderedDict({0: -1})\n maxLength = prefix_xor = 0\n \n for i in range(len(s)):\n prefix_xor ^= li[int(s[i])]\n # Found a new prefix_xor_value\n if prefix_xor not in di:\n di[prefix_xor] = i\n \n # XOR operation with previous prefix_xor_value\n for key in di.keys():\n if i - di[key] <= maxLength:\n break\n\t\t\t\t# s[di[key] : i] is Awesome Substring\n if key ^ prefix_xor in checker:\n maxLength = i - di[key]\n return maxLength\n \n", + "title": "1542. Find Longest Awesome Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array . If there is no lucky integer return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "1 <= arr[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,3,4]Output:2Explanation:The only lucky number in the array is 2 because frequency[2] == 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,2,3,3,3]Output:3Explanation:1, 2 and 3 are all lucky numbers, return the largest of them.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,2,2,3,3]Output:-1Explanation:There are no lucky numbers in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 12.82%) | Memory: 44.3 MB (Top 18.67%)\nclass Solution {\n public int findLucky(int[] arr) {\n HashMap map = new HashMap<>();\n for(int i : arr){\n map.put(i, map.getOrDefault(i,0)+1);\n }\n System.out.print(map);\n int max = 0;\n for (Map.Entry e : map.entrySet()){\n int temp = 0;\n if(e.getKey() == (int)e.getValue()){\n temp = (int)e.getKey();\n }\n if(max < temp){\n max= temp;\n }\n }\n if(max != 0)return max;\n return -1;\n }\n}", + "title": "1394. Find Lucky Integer in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , a lucky integer is an integer that has a frequency in the array equal to its value. Return the largest lucky integer in the array . If there is no lucky integer return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "1 <= arr[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,3,4]Output:2Explanation:The only lucky number in the array is 2 because frequency[2] == 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,2,3,3,3]Output:3Explanation:1, 2 and 3 are all lucky numbers, return the largest of them.", + "image": null + }, + { + "text": "Example 3: Input:arr = [2,2,2,3,3]Output:-1Explanation:There are no lucky numbers in the array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n dc = {}\n \n for i in range(len(arr)):\n if arr[i] not in dc:\n dc[arr[i]] = 1\n else:\n dc[arr[i]] = dc[arr[i]] + 1\n mx = -1\n for key,value in dc.items():\n if key == value:\n mx = max(key, mx)\n return mx\n", + "title": "1394. Find Lucky Integer in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Implement the MedianFinder class: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 183 ms (Top 63.97%) | Memory: 124.7 MB (Top 57.27%)\nclass MedianFinder {\n\n PriorityQueue maxHeap;\n PriorityQueue minHeap;\n\n public MedianFinder() {\n maxHeap= new PriorityQueue((a,b)->b-a);\n minHeap= new PriorityQueue();\n }\n\n public void addNum(int num) {\n\n //Pushing\n if ( maxHeap.isEmpty() || ((int)maxHeap.peek() > num) ){\n maxHeap.offer(num);\n }\n else{\n minHeap.offer(num);\n }\n\n //Balancing\n if ( maxHeap.size() > minHeap.size()+ 1){\n minHeap.offer(maxHeap.peek());\n maxHeap.poll();\n }\n else if (minHeap.size() > maxHeap.size()+ 1 ){\n maxHeap.offer(minHeap.peek());\n minHeap.poll();\n }\n\n }\n\n public double findMedian() {\n\n //Evaluating Median\n if ( maxHeap.size() == minHeap.size() ){ // Even Number\n return ((int)maxHeap.peek()+ (int)minHeap.peek())/2.0;\n }\n else{ //Odd Number\n if ( maxHeap.size() > minHeap.size()){\n return (int)maxHeap.peek()+ 0.0;\n }\n else{ // minHeap.size() > maxHeap.size()\n return (int)minHeap.peek()+ 0.0;\n }\n }\n }\n}", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Implement the MedianFinder class: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 705 ms (Top 15.04%) | Memory: 39.30 MB (Top 5.61%)\n\nclass MedianFinder:\n\n def __init__(self):\n ### max heap to store the first half of the list\n self.maxHeap = []\n ### min heap to store the second half of the list\n self.minHeap = []\n\n def addNum(self, num: int) -> None:\n ### push num into the correct heap\n if not self.maxHeap or num <= -self.maxHeap[0]:\n heappush(self.maxHeap, -num)\n else:\n heappush(self.minHeap, num)\n \n ### banance the two heaps so that each of them representing half of the list\n ### for odd length list, len(maxHeap) == len(minHeap)+1\n ### for even length list, len(maxHeap) == len(minHeap)\n if len(self.minHeap) > len(self.maxHeap):\n heappush(self.maxHeap, -heappop(self.minHeap)) \n elif len(self.maxHeap) > len(self.minHeap)+1:\n heappush(self.minHeap, -heappop(self.maxHeap)) \n\n def findMedian(self) -> float:\n \n ### if the length of entire list is even, \n ### get the mean of the two middle values\n if (len(self.maxHeap)+len(self.minHeap))%2==0:\n return (-self.maxHeap[0]+self.minHeap[0])/2\n \n ### when odd, we know that the median is in maxHeap\n return -self.maxHeap[0]\n", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:1Explanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]Output:0Explanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]Output:11Explanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 45.46%) | Memory: 42.8 MB (Top 25.20%)\nclass Solution {\n public int findMin(int[] nums)\n {\n int min=nums[0];\n\n for(int i=0;inums[i])\n {\n min=nums[i];\n }\n }\n return min;\n }\n}", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:1Explanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]Output:0Explanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]Output:11Explanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n if len(nums) == 1 or nums[0] < nums[-1]:\n return nums[0]\n \n l, r = 0, len(nums) - 1\n \n while l <= r:\n mid = l + (r - l) // 2\n \n if mid > 0 and nums[mid - 1] > nums[mid]:\n return nums[mid]\n \n\t\t\t# We compare the middle number and the right index number\n\t\t\t# but why we cannot compare it with the left index number?\n if nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: 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 that may contain duplicates , return the minimum element of this array . You must decrease the overall operation steps as much as possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "[4,5,6,7,0,1,4] if it was rotated 4 times.", + "[0,1,4,4,5,6,7] if it was rotated 7 times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5]Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,0,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 43.6 MB (Top 61.18%)\nclass Solution {\n public int findMin(int[] nums) {\n int l = 0;\n int h = nums.length - 1;\n while (l < h) {\n while (l < h && nums[l] == nums[l + 1])\n ++l;\n while (l < h && nums[h] == nums[h - 1])\n --h;\n int mid = l + (h - l) / 2;\n if (nums[mid] > nums[h]) { // smaller elements are in the right side\n l = mid + 1;\n } else {\n h = mid;\n }\n }\n return nums[l];\n }\n}", + "title": "154. Find Minimum in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: 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 that may contain duplicates , return the minimum element of this array . You must decrease the overall operation steps as much as possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "[4,5,6,7,0,1,4] if it was rotated 4 times.", + "[0,1,4,4,5,6,7] if it was rotated 7 times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5]Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,0,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n return min(nums)\n \n", + "title": "154. Find Minimum in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array jobs , where jobs[i] is the amount of time it takes to complete the i th job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized . Return the minimum possible maximum working time of any assignment. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= jobs.length <= 12", + "1 <= jobs[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:jobs = [3,2,3], k = 3Output:3Explanation:By assigning each person one job, the maximum time is 3.", + "image": null + }, + { + "text": "Example 2: Input:jobs = [1,2,4,7,8], k = 2Output:11Explanation:Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int result = Integer.MAX_VALUE;\n public int minimumTimeRequired(int[] jobs, int k) {\n int length = jobs.length;\n Arrays.sort(jobs);\n backtrack(jobs, length - 1, new int [k]);\n return result;\n }\n \n public void backtrack(int [] jobs, int current, int [] workers) {\n if (current < 0) {\n result = Math.min(result, Arrays.stream(workers).max().getAsInt());\n return;\n }\n \n if (Arrays.stream(workers).max().getAsInt() >= result)\n return;\n for (int i=0; i 0 && workers[i] == workers[i-1])\n continue;\n // make choice\n workers[i] += jobs[current];\n // backtrack\n backtrack(jobs, current-1, workers);\n // undo the choice\n workers[i] -= jobs[current];\n }\n }\n \n \n}\n", + "title": "1723. Find Minimum Time to Finish All Jobs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array jobs , where jobs[i] is the amount of time it takes to complete the i th job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized . Return the minimum possible maximum working time of any assignment. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= jobs.length <= 12", + "1 <= jobs[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:jobs = [3,2,3], k = 3Output:3Explanation:By assigning each person one job, the maximum time is 3.", + "image": null + }, + { + "text": "Example 2: Input:jobs = [1,2,4,7,8], k = 2Output:11Explanation:Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 30 ms (Top 99.44%) | Memory: 16.50 MB (Top 63.13%)\n\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n def branchAndBound(i: int):\n nonlocal r\n if i == n:\n r = min(r, max(a))\n return\n visited = set()\n for j in range(k):\n if a[j] in visited:\n continue\n visited.add(a[j])\n if a[j] + jobs[i] >= r:\n continue\n a[j] += jobs[i]\n branchAndBound(i+1)\n a[j] -= jobs[i]\n\n n = len(jobs)\n if n <= k:\n return max(jobs)\n\n # use greed algorithm to get upper bound\n jobs.sort(reverse=True)\n a = list(jobs[:k])\n for job in jobs[k:]:\n m0 = min(a)\n i = a.index(m0)\n a[i] += job\n r = max(a)\n\n a = [0] * k\n branchAndBound(0)\n return r\n", + "title": "1723. Find Minimum Time to Finish All Jobs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6 . n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the i th observation. You are also given the two integers mean and n . Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean . If there are multiple valid answers, return any of them . If no such array exists, return an empty array . The average value of a set of k numbers is the sum of the numbers divided by k . Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == rolls.length", + "1 <= n, m <= 10^5", + "1 <= rolls[i], mean <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [3,2,4,3], mean = 4, n = 2Output:[6,6]Explanation:The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,5,6], mean = 3, n = 4Output:[2,3,2,2]Explanation:The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,2,3,4], mean = 6, n = 4Output:[]Explanation:It is impossible for the mean to be 6 no matter what the 4 missing rolls are.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 98.11%) | Memory: 61.90 MB (Top 20.33%)\n\nclass Solution {\n public int[] missingRolls(int[] rolls, int mean, int n) {\n \n \tint i,m=rolls.length,sum=0;\n \tfor(i=0;i0?1:0);\n \t\tq--;\n \t}\n \treturn arr;\n }\n}\n", + "title": "2028. Find Missing Observations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6 . n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. You are given an integer array rolls of length m where rolls[i] is the value of the i th observation. You are also given the two integers mean and n . Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean . If there are multiple valid answers, return any of them . If no such array exists, return an empty array . The average value of a set of k numbers is the sum of the numbers divided by k . Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == rolls.length", + "1 <= n, m <= 10^5", + "1 <= rolls[i], mean <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [3,2,4,3], mean = 4, n = 2Output:[6,6]Explanation:The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,5,6], mean = 3, n = 4Output:[2,3,2,2]Explanation:The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,2,3,4], mean = 6, n = 4Output:[]Explanation:It is impossible for the mean to be 6 no matter what the 4 missing rolls are.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)\n if rem == 0:\n if 1 <= missing_val <= 6:\n return [missing_val] * n\n elif 1 <= missing_val < 6:\n return [missing_val + 1] * rem + [missing_val] * (n - rem)\n return []", + "title": "2028. Find Missing Observations", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it . If the tree has more than one mode, return them in any order . Assume a BST is defined as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than or equal to the node's key.", + "The right subtree of a node contains only nodes with keys greater than or equal to the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,2,2]Output:[2]", + "image": "https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg" + }, + { + "text": "Example 2: Input:root = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 17.7%) | Memory: 45.06 MB (Top 9.4%)\n\nclass Solution {\n public int[] findMode(TreeNode root) {\n if(root==null) return new int[0];\n Map map = new HashMap(); //we are taking map to count each and every value of the tree and the no of times they occurs in the tree\n Queue qu = new LinkedList(); // to itereate over the tree\n List list = new ArrayList(); //to save our result into a dynamic arraylist then will convert into static array for return it\n qu.add(root); // add the first root node into queue to iterate over the tree\n while(!qu.isEmpty()) { \n TreeNode tmp = qu.poll(); //we poll out the node which is last inputed to the queue\n if(map.containsKey(tmp.val)) { //we are checking through the map wheather the value this node have already stored into the map or not\n map.put(tmp.val, map.get(tmp.val)+1); //the value is already stored then we just increase the count by 1\n }\n else {\n map.put(tmp.val, 1); //if the value is unique then we store it to the map with the count 1\n }\n if(tmp.left!=null) qu.add(tmp.left); //this way we are checking wheather left node has any value or not respect to the current poped element of queue\n if(tmp.right!=null) qu.add(tmp.right); //the same thing of the above just this is for right node of respective poped out node\n }\n int max = Integer.MIN_VALUE; //we are taking it because of requirement to identify highest no of repeated node available in this tree \n for(Integer key : map.keySet()) { //we are using keySet() for iterating over the map here key is differernt nodes and value is the no of count they have in this tree\n if(map.get(key)>max) { //if anything we find have greater value then previous maximum no of node like 2 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now \n list.clear(); //just to clear previous data that are stored into that list\n max = map.get(key); //now max will replaced by the new no of count of a node\n list.add(key); //we are adding the key which has most no of count\n }\n else if(max==map.get(key)) { //if we found another node which also has present maximum no of node count in the tree\n list.add(key); //we are also adding those key\n }\n }\n\t\t//now we just create an array transfer hole data that arraylist has and then return\n int[] res = new int[list.size()];\n for(int i=0; i max_streak:\n max_streak = curr_streak\n result = [curr_num]\n \n curr_node = curr_node.right\n \n return result\n", + "title": "501. Find Mode in Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return any array containing n unique integers such that they add up to 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:[-7,-1,1,3,4]Explanation:These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:[-1,0,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n int j=0;\n \n for(int i=1;i<=n/2;i++)\n {\n ans[j] = i;\n j++;\n }\n for(int i=1;i<=n/2;i++)\n {\n ans[j] = -i;\n j++;\n }\n if(n%2!=0) ans[j] = 0;\n \n return ans;\n }\n}\n", + "title": "1304. Find N Unique Integers Sum up to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return any array containing n unique integers such that they add up to 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:[-7,-1,1,3,4]Explanation:These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:[-1,0,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumZero(self, n: int) -> List[int]:\n q,p=divmod(n,2)\n if p:\n return list(range(-q, q+1))\n else:\n return list(range(-q,0))+list(range(1,q+1))", + "title": "1304. Find N Unique Integers Sum up to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers, x and y , which represent your current location on a Cartesian grid: (x, y) . You are also given an array points where each points[i] = [a i , b i ] represents that a point exists at (a i , b i ) . A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location . If there are multiple, return the valid point with the smallest index . If there are no valid points, return -1 . The Manhattan distance between two points (x 1 , y 1 ) and (x 2 , y 2 ) is abs(x 1 - x 2 ) + abs(y 1 - y 2 ) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^4", + "points[i].length == 2", + "1 <= x, y, a i , b i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]Output:2Explanation:Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 4, points = [[3,4]]Output:0Explanation:The answer is allowed to be on the same location as your current location.", + "image": null + }, + { + "text": "Example 3: Input:x = 3, y = 4, points = [[2,3]]Output:-1Explanation:There are no valid points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nearestValidPoint(int x, int y, int[][] points) {\n int min=Integer.MAX_VALUE, index=-1, i;\n \n for ( i=0;i no longer needed as index is initialized as -1 in the declartion.\n return index;\n \n }\n}\n", + "title": "1779. Find Nearest Point That Has the Same X or Y Coordinate", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers, x and y , which represent your current location on a Cartesian grid: (x, y) . You are also given an array points where each points[i] = [a i , b i ] represents that a point exists at (a i , b i ) . A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location . If there are multiple, return the valid point with the smallest index . If there are no valid points, return -1 . The Manhattan distance between two points (x 1 , y 1 ) and (x 2 , y 2 ) is abs(x 1 - x 2 ) + abs(y 1 - y 2 ) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^4", + "points[i].length == 2", + "1 <= x, y, a i , b i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]Output:2Explanation:Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 4, points = [[3,4]]Output:0Explanation:The answer is allowed to be on the same location as your current location.", + "image": null + }, + { + "text": "Example 3: Input:x = 3, y = 4, points = [[2,3]]Output:-1Explanation:There are no valid points.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 689 ms (Top 99.93%) | Memory: 19.5 MB (Top 5.79%)\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist9 && val<100) || (val>999 && val<10000) || val==100000 )\n count++;\n }\n return count;\n }\n}\n", + "title": "1295. Find Numbers with Even Number of Digits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [12,345,2,6,7896]Output:2Explanation:12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.", + "image": null + }, + { + "text": "Example 2: Input:nums = [555,901,482,1771]Output:1Explanation:Only 1771 contains an even number of digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n even_count = 0\n for elem in nums:\n if(len(str(elem))%2 == 0):\n even_count += 1\n return even_count\n \n", + "title": "1295. Find Numbers with Even Number of Digits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original , and then randomly shuffling the resulting array. Given an array changed , return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= changed.length <= 10^5", + "0 <= changed[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:changed = [1,3,4,2,6,8]Output:[1,3,4]Explanation:One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:changed = [6,3,0,1]Output:[]Explanation:changed is not a doubled array.", + "image": null + }, + { + "text": "Example 3: Input:changed = [1]Output:[]Explanation:changed is not a doubled array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 93 ms (Top 85.10%) | Memory: 128.6 MB (Top 72.29%)\nclass Solution {\n public int[] findOriginalArray(int[] changed) {\n\n Arrays.sort(changed);\n\n if(changed.length%2!=0) return new int[0];\n\n int mid = changed.length/2;\n\n int[] res = new int[mid];\n\n int[] freq = new int[100001];\n\n for(int no : changed)\n freq[no]++;\n\n int idx=0;\n\n for(int no: changed){\n if(freq[no] > 0 && no*2 <= 100000 && freq[no*2]>0){\n freq[no]--;\n freq[no*2]--;\n res[idx++] = no;\n }\n }\n\n for(int i=0; i List[int]:\n counter = collections.Counter(changed)\n res = []\n for k in counter.keys():\n \n if k == 0:\n # handle zero as special case\n if counter[k] % 2 > 0:\n return []\n res += [0] * (counter[k] // 2)\n \n elif counter[k] > 0:\n x = k\n \n # walk down the chain\n while x % 2 == 0 and x // 2 in counter:\n x = x // 2\n \n # walk up and process all numbers within the chain. mark the counts as 0\n while x in counter:\n if counter[x] > 0:\n res += [x] * counter[x]\n if counter[x+x] < counter[x]:\n return []\n counter[x+x] -= counter[x]\n counter[x] = 0\n x += x\n return res\n", + "title": "2007. Find Original Array From Doubled Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array queries and a positive integer intLength , return an array answer where answer[i] is either the queries[i] th smallest positive palindrome of length intLength or -1 if no such palindrome exists . A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 5 * 10^4", + "1 <= queries[i] <= 10^9", + "1 <= intLength <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [1,2,3,4,5,90], intLength = 3Output:[101,111,121,131,141,999]Explanation:The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90thpalindrome of length 3 is 999.", + "image": null + }, + { + "text": "Example 2: Input:queries = [2,4,6], intLength = 4Output:[1111,1331,1551]Explanation:The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 121 ms (Top 54.38%) | Memory: 96.6 MB (Top 65.63%)\n\nclass Solution {\n public long[] kthPalindrome(int[] queries, int intLength) {\n long[] res= new long[queries.length];\n for(int i=0;i0)\n palindrome /= 10;\n while (palindrome>0)\n {\n res1=res1*10+(palindrome % 10);\n palindrome /= 10;\n }\n String g=\"\";\n g+=res1;\n if(g.length()!=kdigit)\n return -1;\n return res1;\n}\n}", + "title": "2217. Find Palindrome With Fixed Length", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array queries and a positive integer intLength , return an array answer where answer[i] is either the queries[i] th smallest positive palindrome of length intLength or -1 if no such palindrome exists . A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= queries.length <= 5 * 10^4", + "1 <= queries[i] <= 10^9", + "1 <= intLength <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:queries = [1,2,3,4,5,90], intLength = 3Output:[101,111,121,131,141,999]Explanation:The first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90thpalindrome of length 3 is 999.", + "image": null + }, + { + "text": "Example 2: Input:queries = [2,4,6], intLength = 4Output:[1111,1331,1551]Explanation:The first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n ogLength = intLength\n isOdd = intLength & 1\n if isOdd:\n intLength += 1\n k = intLength // 2\n k = 10 ** (k - 1)\n op = []\n for q in queries:\n pal = str(k + q - 1)\n if isOdd:\n pal += pal[::-1][1:]\n else:\n pal += pal[::-1]\n if len(pal) == ogLength:\n op.append(int(pal))\n else:\n op.append(-1)\n return op\n", + "title": "2217. Find Palindrome With Fixed Length", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:2Explanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]Output:5Explanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findPeakElement(int[] nums) {\n int start = 0;\n int end = nums.length - 1;\n \n while(start < end){\n int mid = start + (end - start) / 2;\n if(nums[mid] > nums[mid + 1]){\n //It means that we are in decreasing part of the array\n end = mid;\n }\n else{\n //It means that we are in increasing part of the array\n start = mid + 1;\n }\n }\n return start;\n }\n}\n", + "title": "162. Find Peak Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:2Explanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]Output:5Explanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = [-2**32]+nums+[-2**32]\n l,r = 0,len(nums)-1\n while l <=r:\n m = (l+r)//2\n\t\t\t# we find the target:\n if nums[m] > nums[m-1] and nums[m] > nums[m+1]:\n return m -1\n else:\n if nums[m] int:\n right = sum(nums)\n left = 0\n\n for i in range(len(nums)):\n right -= nums[i]\n left += nums[i - 1] if i > 0 else 0\n\n if right == left: return i\n\n return -1", + "title": "724. Find Pivot Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array matches where matches[i] = [winner i , loser i ] indicates that the player winner i defeated player loser i in a match. Return a list answer of size 2 where: The values in the two lists should be returned in increasing order. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all players that have not lost any matches.", + "answer[1] is a list of all players that have lost exactly one match." + ], + "examples": [ + { + "text": "Example 1: Input:matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]Output:[[1,2,10],[4,5,7,8]]Explanation:Players 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].", + "image": null + }, + { + "text": "Example 2: Input:matches = [[2,3],[1,3],[5,4],[6,4]]Output:[[1,2,5,6],[]]Explanation:Players 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 99.73%) | Memory: 91.90 MB (Top 61.98%)\n\nclass Solution {\n public List> findWinners(int[][] matches) {\n int[] losses = new int[100001];\n\n for (int i = 0; i < matches.length; i++) {\n int win = matches[i][0];\n int loss = matches[i][1];\n\n if (losses[win] == 0) {\n losses[win] = -1;\n } \n\n if (losses[loss] == -1) {\n losses[loss] = 1;\n } else {\n losses[loss]++;\n }\n }\n\n List zeroLoss = new ArrayList<>();\n List oneLoss = new ArrayList<>();\n\n List> result = new ArrayList<>();\n\n for (int i = 0; i < losses.length; i++) {\n if (losses[i] == -1) {\n zeroLoss.add(i);\n } else if (losses[i] == 1) {\n oneLoss.add(i);\n }\n }\n\n result.add(zeroLoss);\n result.add(oneLoss);\n\n return result;\n }\n}\n", + "title": "2225. Find Players With Zero or One Losses", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array matches where matches[i] = [winner i , loser i ] indicates that the player winner i defeated player loser i in a match. Return a list answer of size 2 where: The values in the two lists should be returned in increasing order. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all players that have not lost any matches.", + "answer[1] is a list of all players that have lost exactly one match." + ], + "examples": [ + { + "text": "Example 1: Input:matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]Output:[[1,2,10],[4,5,7,8]]Explanation:Players 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].", + "image": null + }, + { + "text": "Example 2: Input:matches = [[2,3],[1,3],[5,4],[6,4]]Output:[[1,2,5,6],[]]Explanation:Players 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5248 ms (Top 5.11%) | Memory: 68.3 MB (Top 89.11%)\nclass Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n winners, losers, table = [], [], {}\n for winner, loser in matches:\n # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.\n # map.get(key, 0) returns map[key] if key exists and 0 if it does not.\n table[winner] = table.get(winner, 0) # Winner\n table[loser] = table.get(loser, 0) + 1\n for k, v in table.items(): # Player k with losses v\n if v == 0:\n winners.append(k) # If player k has no loss ie v == 0\n if v == 1:\n losers.append(k) # If player k has one loss ie v == 1\n return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.", + "title": "2225. Find Players With Zero or One Losses", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a callable function f(x, y) with a hidden formula and a value z , reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z . You may return the pairs in any order. While the exact formula is hidden, the function is monotonically increasing, i.e.: The function interface is defined like this: We will judge your solution as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "f(x, y) < f(x + 1, y)", + "f(x, y) < f(x, y + 1)" + ], + "examples": [ + { + "text": "Example 1: Input:function_id = 1, z = 5Output:[[1,4],[2,3],[3,2],[4,1]]Explanation:The hidden formula for function_id = 1 is f(x, y) = x + y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=4 -> f(1, 4) = 1 + 4 = 5.\nx=2, y=3 -> f(2, 3) = 2 + 3 = 5.\nx=3, y=2 -> f(3, 2) = 3 + 2 = 5.\nx=4, y=1 -> f(4, 1) = 4 + 1 = 5.", + "image": null + }, + { + "text": "Example 2: Input:function_id = 2, z = 5Output:[[1,5],[5,1]]Explanation:The hidden formula for function_id = 2 is f(x, y) = x * y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=5 -> f(1, 5) = 1 * 5 = 5.\nx=5, y=1 -> f(5, 1) = 5 * 1 = 5.", + "image": null + }, + { + "text": "interface CustomFunction {\npublic:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n};", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int binarySearch(int ans, int x, CustomFunction func){\n int left = 1, right =1000;\n while(left <= right){\n int mid = left + (right -left)/2;\n \n int res = func.f(x, mid);\n \n if(res == ans){\n return mid;\n }\n if(res < ans){\n left = mid+1;\n }else{\n right = mid-1;\n }\n }\n return -1;\n }\n public List> findSolution(CustomFunction customfunction, int z) {\n List> res = new ArrayList<>();\n\n for(int i=1; i<=1000; i++){\n int ans = binarySearch(z, i, customfunction);\n if(ans != -1){\n List temp = new ArrayList<>();\n temp.add(i);\n temp.add(ans);\n res.add(temp);\n }\n if(customfunction.f(i,1) > z){\n break;\n }\n }\n return res;\n }\n}\n", + "title": "1237. Find Positive Integer Solution for a Given Equation", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string array words , where words[i] consists of lowercase English letters. In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams , and delete words[i] from words . Keep performing this operation as long as you can select an index that satisfies the conditions. Return words after performing all operations . It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, \"dacb\" is an anagram of \"abdc\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]Output:[\"abba\",\"cd\"]Explanation:One of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = \"bbaa\" and words[1] = \"baba\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"baba\",\"cd\",\"cd\"].\n- Since words[1] = \"baba\" and words[0] = \"abba\" are anagrams, we choose index 1 and delete words[1].\n Now words = [\"abba\",\"cd\",\"cd\"].\n- Since words[2] = \"cd\" and words[1] = \"cd\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"cd\"].\nWe can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"b\",\"c\",\"d\",\"e\"]Output:[\"a\",\"b\",\"c\",\"d\",\"e\"]Explanation:No two adjacent strings in words are anagrams of each other, so no operations are performed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List removeAnagrams(String[] words) {\n String prev =\"\";\n List li=new ArrayList<>();\n for(int i=0;i List[str]:\n i = 0\n while i < len(words) - 1:\n if sorted(words[i]) == sorted(words[i + 1]):\n words.remove(words[i + 1])\n continue\n i += 1\n return words", + "title": "2273. Find Resultant Array After Removing Anagrams", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of intervals , where intervals[i] = [start i , end i ] and each start i is unique . The right interval for an interval i is an interval j such that start j >= end i and start j is minimized . Note that i may equal j . Return an array of right interval indices for each interval i . If no right interval exists for interval i , then put -1 at index i . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 2 * 10^4", + "intervals[i].length == 2", + "-10^6 <= start i <= end i <= 10^6", + "The start point of each interval is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2]]Output:[-1]Explanation:There is only one interval in the collection, so it outputs -1.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[3,4],[2,3],[1,2]]Output:[-1,0,1]Explanation:There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0= 3 is the smallest start that is >= end1= 3.\nThe right interval for [1,2] is [2,3] since start1= 2 is the smallest start that is >= end2= 2.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,4],[2,3],[3,4]]Output:[-1,2,-1]Explanation:There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2= 3 is the smallest start that is >= end1= 3.", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n- Time: O(N*log(N))\nLoop through the array with n elements and run binary search with log(N) time for each of them.\n\n- Space: O(N)\nUsed a hashmap map of size N to store the original indeces of intervals\n */\nclass Solution {\n public int[] findRightInterval(int[][] intervals) {\n int n = intervals.length;\n int[] res = new int[n];\n Map map = new HashMap<>();\n for (int i = 0; i < n; i++) {\n map.put(intervals[i], i);\n }\n\n Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n for (int i = 0; i < n; i++) {\n int[] interval = binarySearch(intervals, intervals[i][1], i);\n res[map.get(intervals[i])] = interval == null ? -1 : map.get(interval);\n }\n \n return res;\n }\n\n private int[] binarySearch(int[][] intervals, int target, int start) {\n int l = start, r = intervals.length - 1;\n \n while (l <= r) {\n int m = l + (r - l) / 2;\n if (intervals[m][0] >= target) {\n // keep moving the right boundary to the left to get the first\n // element bigger than target\n r = m - 1;\n } else {\n // if the element we get is bigger than the target, we move the \n // left boundary to look at right part of the array\n l = m + 1;\n }\n }\n return l == intervals.length ? null : intervals[l];\n }\n}\n", + "title": "436. Find Right Interval", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of intervals , where intervals[i] = [start i , end i ] and each start i is unique . The right interval for an interval i is an interval j such that start j >= end i and start j is minimized . Note that i may equal j . Return an array of right interval indices for each interval i . If no right interval exists for interval i , then put -1 at index i . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 2 * 10^4", + "intervals[i].length == 2", + "-10^6 <= start i <= end i <= 10^6", + "The start point of each interval is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2]]Output:[-1]Explanation:There is only one interval in the collection, so it outputs -1.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[3,4],[2,3],[1,2]]Output:[-1,0,1]Explanation:There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0= 3 is the smallest start that is >= end1= 3.\nThe right interval for [1,2] is [2,3] since start1= 2 is the smallest start that is >= end2= 2.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,4],[2,3],[3,4]]Output:[-1,2,-1]Explanation:There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2= 3 is the smallest start that is >= end1= 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 229 ms (Top 99.26%) | Memory: 22.50 MB (Top 16.77%)\n\nclass Solution:\n def findRightInterval(self, intervals):\n ints = sorted([[j,k,i] for i,[j,k] in enumerate(intervals)])\n begs = [i for i,_,_ in ints]\n out = [-1]*len(begs)\n for i,j,k in ints:\n t = bisect.bisect_left(begs, j)\n if t < len(begs):\n out[k] = ints[t][2]\n \n return out\n", + "title": "436. Find Right Interval", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time . The requests are assigned to servers according to a specific algorithm: You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the i th request, and another array load , where load[i] represents the load of the i th request (the time it takes to complete). Your goal is to find the busiest server(s) . A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s) . You may return the IDs in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The i th (0-indexed) request arrives.", + "If all servers are busy, the request is dropped (not handled at all).", + "If the (i % k) th server is available, assign the request to that server.", + "Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the i th server is busy, try to assign the request to the (i+1) th server, then the (i+2) th server, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]Output:[1]Explanation:All of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.", + "image": "https://assets.leetcode.com/uploads/2020/09/08/load-1.png" + }, + { + "text": "Example 2: Input:k = 3, arrival = [1,2,3,4], load = [1,2,1,2]Output:[0]Explanation:The first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.", + "image": null + }, + { + "text": "Example 3: Input:k = 3, arrival = [1,2,3], load = [10,12,11]Output:[0,1,2]Explanation:Each server handles a single request, so they are all considered the busiest.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 158 ms (Top 89.09%) | Memory: 61.5 MB (Top 92.12%)\nclass Solution {\n public List busiestServers(int k, int[] arrival, int[] load) {\n\n // use a tree to track available servers\n TreeSet availableServerIdxs = new TreeSet();\n for (int num = 0; num < k; num++) {\n availableServerIdxs.add(num);\n }\n // use a PQ to maintain the availability based on curTime + loadTime and the server index = idx%k\n Queue runningServers = new PriorityQueue<>((a, b)->(a[0] - b[0]));\n\n int[] serverHandledReqCount = new int[k];\n\n for (int idx = 0; idx < arrival.length; idx++) {\n int newTaskCompletionTime = arrival[idx];\n\n // peek if the server's work time is less than or equal to the next task completion time, if it is poll those servers from the running servers queue and add the index of that server to the availableServerIdxs treeSet\n while (!runningServers.isEmpty() && runningServers.peek()[0] <= newTaskCompletionTime) {\n int freedServer = runningServers.poll()[1];\n availableServerIdxs.add(freedServer);\n }\n\n if (availableServerIdxs.size() == 0) continue; // all busy\n\n // to always get the last freed server\n Integer serverIdx = availableServerIdxs.ceiling(idx % k);\n\n if (serverIdx == null) {\n serverIdx = availableServerIdxs.first();\n }\n\n serverHandledReqCount[serverIdx]++;\n availableServerIdxs.remove(serverIdx);\n\n runningServers.offer(new int[] {newTaskCompletionTime + load[idx], serverIdx});\n }\n\n int max = Arrays.stream(serverHandledReqCount).max().getAsInt();\n return IntStream.range(0, k).filter(i -> serverHandledReqCount[i] == max).boxed().collect(Collectors.toList());\n\n //return findMaxesInCounter(counter);\n }\n\n /*\n private List findMaxesInCounter(int[] counter) {\n int max = 0;\n for (int i = 0; i < counter.length; i++) {\n max = Math.max(max, counter[i]);\n }\n List result = new ArrayList<>();\n for (int i = 0; i < counter.length; i++) {\n if (counter[i] == max) {\n result.add(i);\n }\n }\n return result;\n }\n */\n}", + "title": "1606. Find Servers That Handled Most Number of Requests", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time . The requests are assigned to servers according to a specific algorithm: You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the i th request, and another array load , where load[i] represents the load of the i th request (the time it takes to complete). Your goal is to find the busiest server(s) . A server is considered busiest if it handled the most number of requests successfully among all the servers. Return a list containing the IDs (0-indexed) of the busiest server(s) . You may return the IDs in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The i th (0-indexed) request arrives.", + "If all servers are busy, the request is dropped (not handled at all).", + "If the (i % k) th server is available, assign the request to that server.", + "Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the i th server is busy, try to assign the request to the (i+1) th server, then the (i+2) th server, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3]Output:[1]Explanation:All of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.", + "image": "https://assets.leetcode.com/uploads/2020/09/08/load-1.png" + }, + { + "text": "Example 2: Input:k = 3, arrival = [1,2,3,4], load = [1,2,1,2]Output:[0]Explanation:The first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.", + "image": null + }, + { + "text": "Example 3: Input:k = 3, arrival = [1,2,3], load = [10,12,11]Output:[0,1,2]Explanation:Each server handles a single request, so they are all considered the busiest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def busiestServers(self, k: int, A: List[int], B: List[int]) -> List[int]:\n available = list(range(k)) # already a min-heap\n busy = [] \n res = [0] * k\n for i, a in enumerate(A):\n while busy and busy[0][0] <= a: # these are done, put them back as available\n _, x = heapq.heappop(busy)\n heapq.heappush(available, i + (x-i)%k) # invariant: min(available) is at least i, at most i+k-1\n if available: \n j = heapq.heappop(available) % k\n heapq.heappush(busy, (a+B[i],j))\n res[j] += 1\n a = max(res)\n return [i for i in range(k) if res[i] == a]\n", + "title": "1606. Find Servers That Handled Most Number of Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target , return the smallest character in the array that is larger than target . Note that the letters wrap around. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:letters = [\"c\",\"f\",\"j\"], target = \"a\"Output:\"c\"", + "image": null + }, + { + "text": "Example 2: Input:letters = [\"c\",\"f\",\"j\"], target = \"c\"Output:\"f\"", + "image": null + }, + { + "text": "Example 3: Input:letters = [\"c\",\"f\",\"j\"], target = \"d\"Output:\"f\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.10 MB (Top 77.94%)\n\nclass Solution {\n public char nextGreatestLetter(char[] letters, char target) {\n char res=letters[0];\n int start=0;\n int end=letters.length-1;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n if(letters[mid]==target)\n {\n start=mid+1;\n }\n else if(target>letters[mid])\n {\n start=mid+1;\n }\n else if(letters[mid]>target)\n {\n res=letters[mid];\n end=mid-1;\n }\n }\n return res;\n \n }\n}\n", + "title": "744. Find Smallest Letter Greater Than Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a characters array letters that is sorted in non-decreasing order and a character target , return the smallest character in the array that is larger than target . Note that the letters wrap around. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if target == 'z' and letters == ['a', 'b'] , the answer is 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:letters = [\"c\",\"f\",\"j\"], target = \"a\"Output:\"c\"", + "image": null + }, + { + "text": "Example 2: Input:letters = [\"c\",\"f\",\"j\"], target = \"c\"Output:\"f\"", + "image": null + }, + { + "text": "Example 3: Input:letters = [\"c\",\"f\",\"j\"], target = \"d\"Output:\"f\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n beg = 0\n end = len(letters)-1\n while beg <= end:\n mid = (beg+end)//2\n if letters[mid]>target:\n end = mid -1\n else:\n beg = mid +1\n return letters[beg] if beg pq = new PriorityQueue<>((a,b) -> b[0] - a[0]);\n \n for(int i=0; i l = new ArrayList<>();\n \n while(k-- != 0)\n l.add(pq.poll());\n \n Collections.sort(l, (a,b) -> a[1] - b[1]);\n \n int[] res = new int[l.size()];\n \n int index = 0;\n \n for(int[] i: l)\n res[index++] = i[0];\n \n return res;\n }\n}\n", + "title": "2099. Find Subsequence of Length K With the Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k . A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3,3], k = 2Output:[3,3]Explanation:The subsequence has the largest sum of 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-2,3,4], k = 3Output:[-1,3,4]Explanation:The subsequence has the largest sum of -1 + 3 + 4 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,3,3], k = 2Output:[3,4]Explanation:The subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxSubsequence(self, nums, k):\n ret, max_k = [], sorted(nums, reverse=True)[:k]\n for num in nums:\n if num in max_k:\n ret.append(num)\n max_k.remove(num)\n if len(max_k) == 0:\n return ret\n", + "title": "2099. Find Subsequence of Length K With the Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The hash of a 0-indexed string s of length k , given integers p and m , is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26 . You are given a string s and the integers power , modulo , k , and hashValue. Return sub , the first substring of s of length k such that hash(sub, power, modulo) == hashValue . The test cases will be generated such that an answer always exists . A substring is a contiguous non-empty sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "hash(s, p, m) = (val(s[0]) * p 0 + val(s[1]) * p 1 + ... + val(s[k-1]) * p k-1 ) mod m ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0Output:\"ee\"Explanation:The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32Output:\"fbx\"Explanation:The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String subStrHash(String s, int power, int modulo, int k, int hashValue) {\n\t\t// calculate all the powers from power^0 till power^k\n\t\t// utilized binary exponentiation\n\t\tlong[] powers = new long[k];\n for (int i = 0; i < k; i++) \n powers[i] = binaryExponentiation(power, i, modulo);\n \n\t\t// pre compute the initial hash from behind.\n\t\t// I have explained at top you why traversing from behind is easy\n long currentHashValue = 0;\n int index = s.length() - 1;\n int powerIndex = k-1;\n while (index >= s.length() - k) {\n\t\t\t// (a+b) % modulo = ( (a % modulo) + (b % modulo) ) % modulo;\n\t\t\t// do it for k times from behind\n currentHashValue += ((s.charAt(index--) - 'a' + 1) % modulo * powers[powerIndex--] % modulo) % modulo;\n }\n currentHashValue %= modulo;\n \n int startIndex = 0;\n if (currentHashValue == hashValue) {\n startIndex = s.length() - k;\n }\n \n\t\t// I have pre computed already for k values from behind. so start from (length of S - k - 1)\n\t\t// Let's take an example of \"leetcode\" itself\n\t\t// \"de\" is pre computed\n\t\t// point is to add one character from behind and remove one from end (Sliding from back to first)\n\t\t// Modular Arithmetic for (a-b) % modulo = ( (a % modulo) - (b % modulo) + modulo) % modulo;\n\t\t// keep tracking of the start index if hash value matches. That's it.\n for (int i = s.length() - k - 1; i >= 0; i--) {\n\t\t\t// below line a --> currentHashValue \n\t\t\t// below line b --> (s.charAt(i+k) - 'a' + 1 * powers[k-1])\n currentHashValue = ((currentHashValue % modulo) - (((s.charAt(i+k) - 'a' + 1) * powers[k-1]) % modulo) + modulo) % modulo;\n\t\t\t// we need to multiply a power once for all\n\t\t\t// MULTIPLICATION\n currentHashValue = currentHashValue * power;\n\t\t\t// Modular Arithmetic for (a+b) % modulo is below line\n currentHashValue = (currentHashValue % modulo + (s.charAt(i) - 'a' + 1) % modulo) % modulo;\n \n if (currentHashValue == hashValue) {\n startIndex = i;\n }\n }\n return s.substring(startIndex, startIndex+k);\n }\n \n private long binaryExponentiation(long a, long b, long mod) {\n a %= mod;\n long result = 1;\n while (b > 0) {\n if (b % 2 == 1)\n result = result * a % mod;\n a = a * a % mod;\n b >>= 1;\n }\n return result;\n }\n}\n", + "title": "2156. Find Substring With Given Hash Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The hash of a 0-indexed string s of length k , given integers p and m , is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26 . You are given a string s and the integers power , modulo , k , and hashValue. Return sub , the first substring of s of length k such that hash(sub, power, modulo) == hashValue . The test cases will be generated such that an answer always exists . A substring is a contiguous non-empty sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "hash(s, p, m) = (val(s[0]) * p 0 + val(s[1]) * p 1 + ... + val(s[k-1]) * p k-1 ) mod m ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0Output:\"ee\"Explanation:The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32Output:\"fbx\"Explanation:The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 996 ms (Top 33.98%) | Memory: 14.1 MB (Top 94.23%)\nclass Solution:\n def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n val = lambda ch : ord(ch) - ord(\"a\") + 1\n hash, res, power_k = 0, 0, pow(power, k, mod)\n for i in reversed(range(len(s))):\n hash = (hash * power + val(s[i])) % mod\n if i < len(s) - k:\n hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod\n res = i if hash == hashValue else res\n return s[res:res + k]", + "title": "2156. Find Substring With Given Hash Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums and a target element target . A target index is an index i such that nums[i] == target . Return a list of the target indices of nums after sorting nums in non-decreasing order . If there are no target indices, return an empty list . The returned list must be sorted in increasing order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], target <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,2,3], target = 2Output:[1,2]Explanation:After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,5,2,3], target = 3Output:[3]Explanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,5,2,3], target = 5Output:[4]Explanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 82.14%) | Memory: 43.8 MB (Top 60.21%)\nclass Solution {\n /** Algorithm:\n - Parse the array once and count how many are lesser than target and how many are equal\n - DO NOT sort the array as we don't need it sorted.\n Just to know how many are lesser and how many are equal. O(N) better than O(NlogN - sorting)\n - The response list will have a size = with the number of equal elements (as their positions)\n - Loop from smaller to smaller+equal and add the values into the list. Return the list\n */\n public List targetIndices(int[] nums, int target) {\n int smaller = 0;\n int equal = 0;\n for (int num : nums) {\n if (num < target) {\n smaller++;\n } else if (num == target) {\n equal++;\n }\n }\n List indices = new ArrayList<>(equal);\n for (int i = smaller; i < smaller + equal; i++) {\n indices.add(i);\n }\n return indices;\n }\n}", + "title": "2089. Find Target Indices After Sorting Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and a target element target . A target index is an index i such that nums[i] == target . Return a list of the target indices of nums after sorting nums in non-decreasing order . If there are no target indices, return an empty list . The returned list must be sorted in increasing order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i], target <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,2,3], target = 2Output:[1,2]Explanation:After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,5,2,3], target = 3Output:[3]Explanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,5,2,3], target = 5Output:[4]Explanation:After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def targetIndices(self, nums, target):\n ans = []\n for i,num in enumerate(sorted(nums)):\n if num == target: ans.append(i)\n return ans\n", + "title": "2089. Find Target Indices After Sorting Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n-1 . Given the array edges where edges[i] = [from i , to i , weight i ] represents a bidirectional and weighted edge between cities from i and to i , and given the integer distanceThreshold . Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold , If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= n * (n - 1) / 2", + "edges[i].length == 3", + "0 <= from i < to i < n", + "1 <= weight i , distanceThreshold <= 10^4", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4Output:3Explanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2Output:0Explanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findTheCity(int n, int[][] edges, int distanceThreshold) {\n int[][] graph = new int[n][n];\n for(int[] row: graph)\n Arrays.fill(row, Integer.MAX_VALUE);\n \n for(int i = 0; i < n; i++)\n graph[i][i] = 0;\n \n for(int[] edge: edges)\n {\n graph[edge[0]][edge[1]] = edge[2];\n graph[edge[1]][edge[0]] = edge[2];\n }\n \n for(int k = 0; k < n; k++)\n {\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < n; j++)\n {\n if(graph[i][k] != Integer.MAX_VALUE && graph[k][j] != Integer.MAX_VALUE)\n {\n if(graph[i][k] + graph[k][j] < graph[i][j])\n graph[i][j] = graph[i][k] + graph[k][j];\n }\n }\n }\n }\n \n int ans = 0;\n int city = Integer.MAX_VALUE;;\n \n for(int i = 0; i < n; i++)\n {\n int current = 0;\n for(int j = 0; j < n; j++)\n {\n if(i != j && graph[i][j] <= distanceThreshold)\n current++;\n }\n if(current <= city)\n {\n ans = i;\n city = current;\n }\n }\n \n return ans;\n }\n}\n", + "title": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cities numbered from 0 to n-1 . Given the array edges where edges[i] = [from i , to i , weight i ] represents a bidirectional and weighted edge between cities from i and to i , and given the integer distanceThreshold . Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold , If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= edges.length <= n * (n - 1) / 2", + "edges[i].length == 3", + "0 <= from i < to i < n", + "1 <= weight i , distanceThreshold <= 10^4", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4Output:3Explanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png" + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2Output:0Explanation:The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.", + "image": "https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n matrix = [[float('inf')] * n for _ in range(n)]\n \n # initializing the matrix\n for u, v, w in edges:\n matrix[u][v] = w\n matrix[v][u] = w\n\n for u in range(n):\n matrix[u][u] = 0\n \n for k in range(n):\n for i in range(n):\n for j in range(n):\n if matrix[i][j] > matrix[i][k] + matrix[k][j]:\n matrix[i][j] = matrix[i][k] + matrix[k][j]\n \n # counting reachable cities(neighbor) for every single city \n res = [0] * n\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if 0 < matrix[i][j] <= distanceThreshold:\n res[j] += 1\n return [i for i, x in enumerate(res) if x == min(res)][-1]\n", + "title": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome . If there is a tie, return the smaller one . The closest is defined as the absolute difference minimized between two integers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n.length <= 18", + "n consists of only digits.", + "n does not have leading zeros.", + "n is representing an integer in the range [1, 10^18 - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"123\"Output:\"121\"", + "image": null + }, + { + "text": "Example 2: Input:n = \"1\"Output:\"0\"Explanation:0 and 2 are the closest palindromes but we return the smallest which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static long pow(long base,long exp){\n long ans = 1;\n for(;exp != 0;){\n if((exp & 1) == 1){\n ans *= base;\n }\n base *= base;\n exp >>= 1;\n }\n return ans;\n }\n public String nearestPalindromic(String n) {\n long num = Long.parseLong(n);\n if(num <= 10){\n return String.valueOf(num - 1);\n }\n long comp[] = new long[5];\n comp[0] = pow(10,n.length() - 1) - 1;\n comp[1] = pow(10,n.length()) + 1;\n int mid = (n.length() + 1) / 2;\n long half = Long.parseLong(n.substring(0,mid));\n long pref[] = {half,half + 1,half - 1};\n for(int i = 0;i < 3;i++){\n StringBuilder st = new StringBuilder(String.valueOf(pref[i]));\n if(n.length() % 2 == 1) st.deleteCharAt(st.length() - 1);\n st.reverse();\n comp[i + 2] = Long.parseLong(String.valueOf(pref[i]) + st.toString()); \n }\n long min = Long.MAX_VALUE;\n long ans = Long.MAX_VALUE;\n for(int i = 0;i < 5;i++){\n long dif = Math.abs(num - comp[i]);\n if(dif != 0 && min > dif){\n min = dif;\n ans = comp[i];\n }\n else if(min == dif) ans = Math.min(ans,comp[i]);\n }\n return String.valueOf(ans);\n }\n}\n", + "title": "564. Find the Closest Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome . If there is a tie, return the smaller one . The closest is defined as the absolute difference minimized between two integers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n.length <= 18", + "n consists of only digits.", + "n does not have leading zeros.", + "n is representing an integer in the range [1, 10^18 - 1] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"123\"Output:\"121\"", + "image": null + }, + { + "text": "Example 2: Input:n = \"1\"Output:\"0\"Explanation:0 and 2 are the closest palindromes but we return the smallest which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "", + "title": "564. Find the Closest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and t . String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 1000", + "t.length == s.length + 1", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"abcde\"Output:\"e\"Explanation:'e' is the letter that was added.", + "image": null + }, + { + "text": "Example 2: Input:s = \"\", t = \"y\"Output:\"y\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public char findTheDifference(String s, String t) {\n char c = 0;\n for(char cs : s.toCharArray()) c ^= cs;\n for(char ct : t.toCharArray()) c ^= ct;\n return c;\n }\n}\n", + "title": "389. Find the Difference", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s and t . String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 1000", + "t.length == s.length + 1", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"abcde\"Output:\"e\"Explanation:'e' is the letter that was added.", + "image": null + }, + { + "text": "Example 2: Input:s = \"\", t = \"y\"Output:\"y\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n c = 0\n for cs in s: c ^= ord(cs) #ord is ASCII value\n for ct in t: c ^= ord(ct)\n return chr(c) #chr = convert ASCII into character\n", + "title": "389. Find the Difference", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]Output:[[1,3],[4,6]]Explanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]Output:[[3],[]]Explanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 69.34%) | Memory: 54.7 MB (Top 58.44%)\nclass Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n Set set1 = new HashSet<>(); // create 2 hashsets\n Set set2 = new HashSet<>();\n for(int num : nums1){ set1.add(num); } // add nums1 elements to set1\n for(int num : nums2){ set2.add(num); } // add nums2 elements to set2\n\n List> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return\n resultList.add(new ArrayList<>());\n resultList.add(new ArrayList<>());\n\n for(int num : set1){ // just iterate to all elements of set1\n if(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.\n }\n for(int num : set2){ // just iterate to all elements of set2\n if(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1\n }\n return resultList;\n }\n}", + "title": "2215. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]Output:[[1,3],[4,6]]Explanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]Output:[[3],[]]Explanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 953 ms (Top 29.31%) | Memory: 14.3 MB (Top 52.22%)\nclass Solution(object):\n def findDifference(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[List[int]]\n \"\"\"\n a = []\n for i in range(len(nums1)):\n if nums1[i] not in nums2:\n a.append(nums1[i])\n b = []\n for i in range(len(nums2)):\n if nums2[i] not in nums1:\n b.append(nums2[i])\n\n c = [list(set(a))] + [list(set(b))]\n\n return c", + "title": "2215. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays arr1 and arr2 , and the integer d , return the distance value between the two arrays . The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 500", + "-1000 <= arr1[i], arr2[j] <= 1000", + "0 <= d <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2Output:2Explanation:For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:|8-10|=2 <= d=2|8-9|=1 <= d=2|8-1|=7 > d=2|8-8|=0 <= d=2", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 68.55%) | Memory: 44.9 MB (Top 25.67%)\nclass Solution {\n public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {\n int x=0,val=0;\n for(int i:arr1){\n for(int j:arr2){\n if(Math.abs(i-j)<=d){\n x--;\n break;\n }\n }\n x++;\n }\n return x;\n }\n}", + "title": "1385. Find the Distance Value Between Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays arr1 and arr2 , and the integer d , return the distance value between the two arrays . The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 500", + "-1000 <= arr1[i], arr2[j] <= 1000", + "0 <= d <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2Output:2Explanation:For arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:|8-10|=2 <= d=2|8-9|=1 <= d=2|8-1|=7 > d=2|8-8|=0 <= d=2", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findTheDistanceValue(self, array1: List[int], array2: List[int], d: int) -> int:\n\n\t\tresult = 0\n\n\t\tarray2 = sorted(array2)\n\n\t\tfor num in array1:\n\n\t\t\tflag = True\n\n\t\t\tlow = 0\n\t\t\thigh = len(array2)-1\n\n\t\t\twhile low <= high:\n\n\t\t\t\tmid = (low + high) // 2\n\n\t\t\t\tif abs(array2[mid] - num) <= d:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\n\t\t\t\telif array2[mid] > num:\n\t\t\t\t\thigh = mid - 1\n\n\t\t\t\telse:\n\t\t\t\t\tlow = mid + 1;\n\n\t\t\tif flag == True:\n\n\t\t\t\tresult = result + 1\n\n\t\treturn result\n", + "title": "1385. Find the Distance Value Between Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 uses only constant extra space. Example 1: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findDuplicate(int[] nums) {\n int i = 0; \n while (i < nums.length) {\n\n if (nums[i] != i + 1) {\n int correct = nums[i] - 1;\n if (nums[i] != nums[correct]) {\n swap(nums, i , correct);\n } else {\n return nums[i];\n }\n } else {\n i++;\n }\n }\n return -1;\n }\n static void swap(int[] arr, int first, int second) {\n int temp = arr[first];\n arr[first] = arr[second];\n arr[second] = temp;\n }\n }\n", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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 uses only constant extra space. Example 1: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1523 ms (Top 9.74%) | Memory: 34 MB (Top 8.51%)\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n\n dictx = {}\n\n for each in nums:\n if each not in dictx:\n dictx[each] = 1\n else:\n return each\n", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0 . You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i ​​​​​​ and i + 1 for all ( 0 <= i < n) . Return the highest altitude of a point. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == gain.length", + "1 <= n <= 100", + "-100 <= gain[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:gain = [-5,1,5,0,-7]Output:1Explanation:The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.", + "image": null + }, + { + "text": "Example 2: Input:gain = [-4,-3,-2,-1,4,3,2]Output:0Explanation:The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.7 MB (Top 97.89%)\nclass Solution {\n public int largestAltitude(int[] gain) {\n int max_alt=0;\n int curr_alt=0;\n for(int i=0;i int:\n return max(accumulate([0]+gain))", + "title": "1732. Find the Highest Altitude", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: Given integers num and k , return the k-beauty of num . Note: A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It has a length of k .", + "It is a divisor of num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 240, k = 2Output:2Explanation:The following are the substrings of num of length k:\n- \"24\" from \"240\": 24 is a divisor of 240.\n- \"40\" from \"240\": 40 is a divisor of 240.\nTherefore, the k-beauty is 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 430043, k = 2Output:2Explanation:The following are the substrings of num of length k:\n- \"43\" from \"430043\": 43 is a divisor of 430043.\n- \"30\" from \"430043\": 30 is not a divisor of 430043.\n- \"00\" from \"430043\": 0 is not a divisor of 430043.\n- \"04\" from \"430043\": 4 is not a divisor of 430043.\n- \"43\" from \"430043\": 43 is a divisor of 430043.\nTherefore, the k-beauty is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divisorSubstrings(int num, int k) {\n String str=String.valueOf(num); // to covert integer to String\n int count=0; // count of ans..\n for(int i=0;i int:\n # since integer has no length function, we convert our num into a str.\n # Then we run a loop that goes until i+k-1 < len(numStr) and take\n # n = int(numStr[i: i+k]); and if n!=0 and num%n==0 meaning \n\t\t# num is divisible by n so we add 1 to k_beauty and return it in the end.\n\t\t\n numStr = str(num)\n i, k_beauty = 0, 0\n \n while i+k-1 < len(numStr):\n n = int(numStr[i: i+k])\n if n!=0 and num%n==0:\n k_beauty += 1\n \n i += 1\n \n return k_beauty\n", + "title": "2269. Find the K-Beauty of a Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings nums and an integer k . Each string in nums represents an integer without leading zeros. Return the string that represents the k th largest integer in nums . Note : Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"] , \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^4", + "1 <= nums[i].length <= 100", + "nums[i] consists of only digits.", + "nums[i] will not have any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"3\",\"6\",\"7\",\"10\"], k = 4Output:\"3\"Explanation:The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4thlargest integer in nums is \"3\".", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"2\",\"21\",\"12\",\"1\"], k = 3Output:\"2\"Explanation:The numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rdlargest integer in nums is \"2\".", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"0\",\"0\"], k = 2Output:\"0\"Explanation:The numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2ndlargest integer in nums is \"0\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 27.4%) | Memory: 53.91 MB (Top 31.3%)\n\nclass Solution {\n public String kthLargestNumber(String[] nums, int k) {\n \n int n=nums.length;\n \n Arrays.sort(nums,(a,b)->{\n if(a.length()>b.length()) return 1;\n else if(b.length()>a.length()) return -1;\n else{\n return isgreater(a,b); \n }\n });\n return nums[n-k]; \n }\n \n public static int isgreater(String a,String b){\n \n int n=a.length();\n \n for(int i=0;ib1) return 1;\n if(b1>a1) return -1;\n }\n return 0;\n }\n}", + "title": "1985. Find the Kth Largest Integer in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings nums and an integer k . Each string in nums represents an integer without leading zeros. Return the string that represents the k th largest integer in nums . Note : Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"] , \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^4", + "1 <= nums[i].length <= 100", + "nums[i] consists of only digits.", + "nums[i] will not have any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"3\",\"6\",\"7\",\"10\"], k = 4Output:\"3\"Explanation:The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4thlargest integer in nums is \"3\".", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"2\",\"21\",\"12\",\"1\"], k = 3Output:\"2\"Explanation:The numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rdlargest integer in nums is \"2\".", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"0\",\"0\"], k = 2Output:\"0\"Explanation:The numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2ndlargest integer in nums is \"0\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])\n", + "title": "1985. Find the Kth Largest Integer in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k . You are allowed to choose exactly one element from each row to form an array. Return the k th smallest array sum among all possible arrays . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat.length[i]", + "1 <= m, n <= 40", + "1 <= mat[i][j] <= 5000", + "1 <= k <= min(200, n m )", + "mat[i] is a non-decreasing array." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,3,11],[2,4,6]], k = 5Output:7Explanation:Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,3,11],[2,4,6]], k = 9Output:17", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7Output:9Explanation:Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kthSmallest(int[][] mat, int k) {\n int[] row = mat[0];\n \n for(int i=1; i list = new ArrayList<>();\n PriorityQueue minHeap = new PriorityQueue<>((a,b) -> (a[0]+a[1]) - (b[0]+b[1]));\n \n for(int i=0; ii).toArray();\n }\n}\n", + "title": "1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k . You are allowed to choose exactly one element from each row to form an array. Return the k th smallest array sum among all possible arrays . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat.length[i]", + "1 <= m, n <= 40", + "1 <= mat[i][j] <= 5000", + "1 <= k <= min(200, n m )", + "mat[i] is a non-decreasing array." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,3,11],[2,4,6]], k = 5Output:7Explanation:Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,3,11],[2,4,6]], k = 9Output:17", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7Output:9Explanation:Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n h = [(nums1[0]+nums2[0],0,0)]\n visited = set()\n res = []\n while h and k > 0:\n e, i, j = heappop(h)\n if (i,j) in visited: continue\n res.append(e)\n visited.add((i,j))\n if j+1 < len(nums2):\n heappush(h,(nums1[i]+nums2[j+1],i,j+1))\n if i+1 < len(nums1):\n heappush(h,(nums1[i+1]+nums2[j],i+1,j))\n k -= 1\n return res\n res = mat[0]\n for i in range(1, len(mat)):\n res = kSmallestPairs(res, mat[i], k)\n return res[-1]", + "title": "1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the string s , return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 x 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"eleetminicoworoep\"Output:13Explanation:The longest substring is \"leetminicowor\" which contains two each of the vowels:e,iandoand zero of the vowels:aandu.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcodeisgreat\"Output:5Explanation:The longest substring is \"leetc\" which contains two e's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"bcbcbc\"Output:6Explanation:In this case, the given string \"bcbcbc\" is the longest because all vowels:a,e,i,oanduappear zero times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 87.39%) | Memory: 45.40 MB (Top 86.55%)\n\nclass Solution {\n\n // taken help as for my code TLE T.C = (n^2);\n\n/* static boolean check(String s){\n int n = s.length();\n\n int arr[] = new int[26];\n\n for(int i=0; i int:\n integrals = [(False, False, False, False, False)] # integrals[10][mapping[\"a\"]] == False means we have seen \"a\" appears even times before index 10\n mapping = {\n \"a\": 0,\n \"i\": 1,\n \"u\": 2,\n \"e\": 3,\n \"o\": 4\n }\n\n for v in s:\n vector = list(integrals[-1])\n if v in mapping: # if v is a vowel\n vector[mapping[v]] = not vector[mapping[v]] # toggle that dimension, because if v had appeared even times before, it becomes odd times now\n integrals.append(tuple(vector))\n\n seen = {}\n res = 0\n\n for i, v in enumerate(integrals):\n if v in seen: # we have seen this vector before\n res = max(res, i - seen[v]) # compare its substring length\n else:\n seen[v] = i # just record the first time each vector appears\n\n return res\n", + "title": "1371. Find the Longest Substring Containing Vowels in Even Counts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n , where obstacles[i] describes the height of the i th obstacle. For every index i between 0 and n - 1 ( inclusive ), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n , where ans[i] is the length of the longest obstacle course for index i as described above . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "You choose any number of obstacles between 0 and i inclusive .", + "You must include the i th obstacle in the course.", + "You must put the chosen obstacles in the same order as they appear in obstacles .", + "Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [1,2,3,2]Output:[1,2,3,3]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.", + "image": null + }, + { + "text": "Example 2: Input:obstacles = [2,2,1]Output:[1,2,1]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.", + "image": null + }, + { + "text": "Example 3: Input:obstacles = [3,1,5,6,4,2]Output:[1,1,2,3,2,2]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {\n int i = -1, cur = 0, lisSize = -1;\n int[] lis = new int[obstacles.length];\n int[] ans = new int[obstacles.length];\n \n for (int curHeight: obstacles) {\n if (i == -1 || lis[i] <= curHeight) {\n lis[++i] = curHeight;\n lisSize = i;\n } else {\n lisSize = search(lis, 0, i, curHeight);\n lis[lisSize] = curHeight;\n }\n \n ans[cur++] = lisSize + 1;\n }\n \n return ans; \n }\n \n private int search(int[] nums, int start, int end, int target) {\n int left = start, right = end;\n int boundary = 0;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] > target) {\n boundary = mid;\n right = mid - 1;\n } else left = mid + 1;\n }\n return boundary;\n }\n}\n", + "title": "1964. Find the Longest Valid Obstacle Course at Each Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n , where obstacles[i] describes the height of the i th obstacle. For every index i between 0 and n - 1 ( inclusive ), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n , where ans[i] is the length of the longest obstacle course for index i as described above . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "You choose any number of obstacles between 0 and i inclusive .", + "You must include the i th obstacle in the course.", + "You must put the chosen obstacles in the same order as they appear in obstacles .", + "Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [1,2,3,2]Output:[1,2,3,3]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.", + "image": null + }, + { + "text": "Example 2: Input:obstacles = [2,2,1]Output:[1,2,1]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.", + "image": null + }, + { + "text": "Example 3: Input:obstacles = [3,1,5,6,4,2]Output:[1,1,2,3,2,2]Explanation:The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_right\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n longest, res = [], []\n for i in range(len(obstacles)):\n idx = bisect_right(longest, obstacles[i])\n if idx == len(longest):\n longest.append(obstacles[i])\n else:\n longest[idx] = obstacles[i]\n res.append(idx+1)\n return res\n", + "title": "1964. Find the Longest Valid Obstacle Course at Each Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1] . If middleIndex == 0 , the left side sum is considered to be 0 . Similarly, if middleIndex == nums.length - 1 , the right side sum is considered to be 0 . Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-1,8,4]Output:3Explanation:The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-1,4]Output:2Explanation:The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,5]Output:-1Explanation:There is no valid middleIndex.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 16.64%) | Memory: 42.4 MB (Top 52.37%)\n\nclass Solution {\n public int findMiddleIndex(int[] nums) {\n\n for(int i=0;i int:\n A = [0] + list(accumulate(nums)) + [0]\n total, n = sum(nums), len(nums)\n for i in range(n):\n if A[i] == total - A[i] - nums[i]:\n return i\n return -1 \n", + "title": "1991. Find the Middle Index in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A critical point in a linked list is defined as either a local maxima or a local minima . A node is a local maxima if the current node has a value strictly greater than the previous node and the next node. A node is a local minima if the current node has a value strictly smaller than the previous node and the next node. Note that a node can only be a local maxima/minima if there exists both a previous node and a next node. Given a linked list head , return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [2, 10^5 ] .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,1]Output:[-1,-1]Explanation:There are no critical points in [3,1].", + "image": "https://assets.leetcode.com/uploads/2021/10/13/a1.png" + }, + { + "text": "Example 2: Input:head = [5,3,1,2,5,1,2]Output:[1,3]Explanation:There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.", + "image": "https://assets.leetcode.com/uploads/2021/10/13/a2.png" + }, + { + "text": "Example 3: Input:head = [1,3,2,2,3,2,2,2,7]Output:[3,3]Explanation:There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node.", + "image": "https://assets.leetcode.com/uploads/2021/10/14/a5.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 51.50%) | Memory: 100.7 MB (Top 69.00%)\n\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int res[]=new int[]{-1,-1};\n if(head==null||head.next==null||head.next.next==null) return res;\n int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1;\n ListNode prev=head,ptr=head.next;\n int idx=1,minD=Integer.MAX_VALUE;\n while(ptr!=null&&ptr.next!=null){\n if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val List[int]:\n idx, i = [], 1\n prev, cur = head, head.next\n while cur and cur.next:\n if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n idx.append(i)\n prev = cur\n cur = cur.next\n i += 1\n\n if len(idx) < 2:\n return [-1, -1]\n \n minDist = min(j - i for i, j in pairwise(idx))\n maxDist = idx[-1] - idx[0]\n\n return [minDist, maxDist]\n", + "title": "2058. Find the Minimum and Maximum Number of Nodes Between Critical Points", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer k , return the minimum number of Fibonacci numbers whose sum is equal to k . The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "F 1 = 1", + "F 2 = 1", + "F n = F n-1 + F n-2 for n > 2." + ], + "examples": [ + { + "text": "Example 1: Input:k = 7Output:2Explanation:The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.", + "image": null + }, + { + "text": "Example 2: Input:k = 10Output:2Explanation:For k = 10 we can use 2 + 8 = 10.", + "image": null + }, + { + "text": "Example 3: Input:k = 19Output:3Explanation:For k = 19 we can use 1 + 5 + 13 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMinFibonacciNumbers(int k) {\n int ans = 0;\n\n while (k > 0) {\n\t\t\t// Run until solution is reached\n int fib2prev = 1;\n int fib1prev = 1;\n while (fib1prev <= k) {\n\t\t\t\t// Generate Fib values, stop when fib1prev is > k, we have the fib number we want stored in fib2prev\n int temp = fib2prev + fib1prev;\n fib2prev = fib1prev;\n fib1prev = temp;\n }\n k -= fib2prev;\n ans += 1;\n }\n return ans;\n }\n}\n", + "title": "1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer k , return the minimum number of Fibonacci numbers whose sum is equal to k . The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "F 1 = 1", + "F 2 = 1", + "F n = F n-1 + F n-2 for n > 2." + ], + "examples": [ + { + "text": "Example 1: Input:k = 7Output:2Explanation:The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.", + "image": null + }, + { + "text": "Example 2: Input:k = 10Output:2Explanation:For k = 10 we can use 2 + 8 = 10.", + "image": null + }, + { + "text": "Example 3: Input:k = 19Output:3Explanation:For k = 19 we can use 1 + 5 + 13 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinFibonacciNumbers(self, k: int) -> int:\n fib_sq = [1, 1]\n while fib_sq[-1] + fib_sq[-2] <= k:\n fib_sq.append(fib_sq[-1]+fib_sq[-2])\n counter = 0\n for i in range(len(fib_sq)-1, -1, -1):\n if fib_sq[i] <= k:\n counter += 1\n k -= fib_sq[i]\n return counter\n", + "title": "1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and a positive integer k , return the most competitive subsequence of nums of size k . An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b . For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,2,6], k = 2Output:[2,6]Explanation:Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,3,5,4,9,6], k = 4Output:[2,3,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 96.43%) | Memory: 61.60 MB (Top 10.06%)\n\nclass Solution {\n public int[] mostCompetitive(int[] nums, int k) {\n int[] stack = new int[k];\n for(int i=0,j=0;i0 && stack[j-1]>nums[i] && j+nums.length-i>k) {\n j--;\n }\n if(j List[int]:\n\t\tend = len(nums) - k\n\t\tans = []\n\t\tfor num in nums:\n\t\t\twhile end and ans and num < ans[-1] :\n\t\t\t\tans.pop()\n\t\t\t\tend -= 1\n\t\t\tans.append(num)\n\t\t\n\t\treturn ans[:k]", + "title": "1673. Find the Most Competitive Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words , return the smallest string that contains each string in words as a substring . If there are multiple valid strings of the smallest length, return any of them . You may assume that no string in words is a substring of another string in words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 12", + "1 <= words[i].length <= 20", + "words[i] consists of lowercase English letters.", + "All the strings of words are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"alex\",\"loves\",\"leetcode\"]Output:\"alexlovesleetcode\"Explanation:All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]Output:\"gctaagttcatgcatc\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 66 ms (Top 42.04%) | Memory: 50.5 MB (Top 75.16%)\nclass Solution {\n public String shortestSuperstring(String[] words) {\n int n = words.length;\n int[][] discount = new int[n][n];\n for (int i = 0; i < n; i++){\n for (int j = 0; j < n; j++){\n for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->j and j->i\n if (words[j].startsWith(words[i].substring(k))){\n discount[i][j]=words[i].length()-k;\n break;\n }\n }\n }\n }\n int[][] dp = new int[1<0; k++){\n if ((i&1<=dp[i|1<dp[(1<dp[(1<0){\n ans[--idx]=words[end].substring((m&(m-1))==0?0:discount[path[m][end]][end]);\n m^=1< str:\n n = len(words)\n graph = [[0]*n for _ in range(n)] # graph as adjacency matrix \n \n for i in range(n):\n for j in range(n): \n if i != j: \n for k in range(len(words[j])): \n if words[i].endswith(words[j][:k]): \n graph[i][j] = len(words[j]) - k \n \n @cache\n def fn(prev, mask): \n \"\"\"Return length of shortest superstring & current choice of word.\"\"\"\n if mask == 0: return 0, None\n vv, kk = inf, None\n for k in range(n): \n if mask & 1< r) r = x;\n\n while (l < r) {\n int m = l + (r-l)/2;\n if (valid(a, m, h)) r = m;\n else l = m + 1;\n }\n\n return l;\n }\n\n private boolean valid(int[] a, int m, int h) {\n for (int x : a)\n if ((h -= (x + m-1)/m) < 0) return false;\n return true;\n }\n}", + "title": "1283. Find the Smallest Divisor Given a Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums and an integer threshold , we will choose a positive integer divisor , divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold . Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5 ). The test cases are generated so that there will be an answer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 10^6", + "nums.length <= threshold <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,5,9], threshold = 6Output:5Explanation:We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [44,22,33,11,1], threshold = 5Output:44", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def helper(self,nums,m):\n Sum = 0\n for n in nums:\n Sum += math.ceil(n/m)\n return Sum\n \n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n l,r = 1, max(nums)\n while l < r:\n mid = (l+r)//2\n Sum = self.helper(nums,mid)\n if Sum > threshold:\n l = mid + 1\n else:\n r = mid \n return r\n", + "title": "1283. Find the Smallest Divisor Given a Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n students in a class numbered from 0 to n - 1 . The teacher will give each student a problem starting with the student number 0 , then the student number 1 , and so on until the teacher reaches the student number n - 1 . After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k . There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i] , then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "chalk.length == n", + "1 <= n <= 10^5", + "1 <= chalk[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:chalk = [5,1,5], k = 22Output:0Explanation:The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "image": null + }, + { + "text": "Example 2: Input:chalk = [3,4,1,2], k = 25Output:1Explanation:The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for (int c : chalk) {\n sum += c;\n }\n long left = k % sum; \n for (int i = 0; i < chalk.length; i++){\n if(left >= chalk[i]){ \n left -= chalk[i];\n } else { \n return i;\n }\n }\n return -1; //just for return statement, put whatever you want here\n}\n}", + "title": "1894. Find the Student that Will Replace the Chalk", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n students in a class numbered from 0 to n - 1 . The teacher will give each student a problem starting with the student number 0 , then the student number 1 , and so on until the teacher reaches the student number n - 1 . After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k . There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i] , then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "chalk.length == n", + "1 <= n <= 10^5", + "1 <= chalk[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:chalk = [5,1,5], k = 22Output:0Explanation:The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.", + "image": null + }, + { + "text": "Example 2: Input:chalk = [3,4,1,2], k = 25Output:1Explanation:The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x int:\n Trusted = [0] * (N+1)\n for (a, b) in trust:\n Trusted[a] -= 1\n Trusted[b] += 1\n \n for i in range(1, len(Trusted)):\n if Trusted[i] == N-1:\n return i\n return -1\n", + "title": "997. Find the Town Judge", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr of distinct integers and an integer k . A game will be played between the first two elements of the array (i.e. arr[0] and arr[1] ). In each round of the game, we compare arr[0] with arr[1] , the larger integer wins and remains at position 0 , and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game . It is guaranteed that there will be a winner of the game. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "arr contains distinct integers.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,5,4,6,7], k = 2Output:5Explanation:Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,2,1], k = 10Output:3Explanation:3 will win the first 10 rounds consecutively.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getWinner(int[] arr, int k) {\n \n int winner =arr[0];\n int count=0;\n for(int i=1;iarr[i])\n count++;\n else\n {\n winner=arr[i];\n count=1;\n }\n if(count==k)\n return winner;\n }\n return winner;\n }\n}\n", + "title": "1535. Find the Winner of an Array Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr of distinct integers and an integer k . A game will be played between the first two elements of the array (i.e. arr[0] and arr[1] ). In each round of the game, we compare arr[0] with arr[1] , the larger integer wins and remains at position 0 , and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds. Return the integer which will win the game . It is guaranteed that there will be a winner of the game. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^6", + "arr contains distinct integers.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,5,4,6,7], k = 2Output:5Explanation:Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,2,1], k = 10Output:3Explanation:3 will win the first 10 rounds consecutively.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 506 ms (Top 96.6%) | Memory: 30.16 MB (Top 47.7%)\n\nclass Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n winner = arr[0]\n wins = 0\n for i in range(1,len(arr),1):\n if(winner > arr[i]): wins+=1 # increment wins count \n else:\n wins = 1 # new winner\n winner = arr[i]\n if(wins == k): break # if wins count is k, then return winner\n \n return winner", + "title": "1535. Find the Winner of an Array Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order . More formally, moving clockwise from the i th friend brings you to the (i+1) th friend for 1 <= i < n , and moving clockwise from the n th friend brings you to the 1 st friend. The rules of the game are as follows: Given the number of friends, n , and an integer k , return the winner of the game . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, k = 2Output:3Explanation:Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" + }, + { + "text": "Example 2: Input:n = 6, k = 5Output:1Explanation:The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 26.7%) | Memory: 43.29 MB (Top 18.2%)\n\nclass Solution {\n public int findTheWinner(int n, int k) {\n\t // Initialisation of the LinkedList\n LinkedList participants = new LinkedList<>();\n for (int i = 1; i <= n; i++) {\n\t\t participants.add(i);\n\t\t}\n\t\t\n\t\tint lastKilled = 0;\n\t\t// Run the game\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < k-1; j++) {\n\t\t\t participants.add(participants.poll());\n\t\t\t}\n lastKilled = participants.poll();\n }\n // Return the last one killed\n return lastKilled;\n }\n}", + "title": "1823. Find the Winner of the Circular Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order . More formally, moving clockwise from the i th friend brings you to the (i+1) th friend for 1 <= i < n , and moving clockwise from the n th friend brings you to the 1 st friend. The rules of the game are as follows: Given the number of friends, n , and an integer k , return the winner of the game . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, k = 2Output:3Explanation:Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" + }, + { + "text": "Example 2: Input:n = 6, k = 5Output:1Explanation:The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef findTheWinner(self, n: int, k: int) -> int:\n ls=list(range(1,n+1))\n while len(ls)>1:\n i=(k-1)%len(ls)\n ls.pop(i)\n ls=ls[i:]+ls[:i]\n \n return ls[0]\n", + "title": "1823. Find the Winner of the Circular Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return three consecutive integers (as a sorted array) that sum to num . If num cannot be expressed as the sum of three consecutive integers, return an empty array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= num <= 10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 33Output:[10,11,12]Explanation:33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].", + "image": null + }, + { + "text": "Example 2: Input:num = 4Output:[]Explanation:There is no way to express 4 as the sum of 3 consecutive integers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 76.35%) | Memory: 17.40 MB (Top 18.24%)\n\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n temp=(num-3)/3\n if floor(temp)==ceil(temp):\n return [int(temp),int(temp)+1,int(temp)+2]\n else:\n return []\n", + "title": "2177. Find Three Consecutive Integers That Sum to a Given Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums , where nums[i] is a digit between 0 and 9 ( inclusive ). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]Output:8Explanation:The above diagram depicts the process from which we obtain the triangular sum of the array.", + "image": "https://assets.leetcode.com/uploads/2022/02/22/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5]Output:5Explanation:Since there is only one element in nums, the triangular sum is the value of that element itself.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int triangularSum(int[] nums) {\n return find(nums,nums.length);\n }\n \n public int find(int[] a, int n){\n if(n == 1)\n return a[0];\n \n for(int i=0;i 1:\n arr = []\n for i in range(len(nums)-1):\n arr.append((nums[i] + nums[i+1]) % 10)\n nums = arr\n return nums[0]\n", + "title": "2221. Find Triangular Sum of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers arr and an integer target . You have to find two non-overlapping sub-arrays of arr each with a sum equal target . There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum . Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 1000", + "1 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,2,4,3], target = 3Output:2Explanation:Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,3,4,7], target = 7Output:2Explanation:Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,3,2,6,2,3,4], target = 6Output:-1Explanation:We have only one sub-array of sum = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSumOfLengths(int[] arr, int target) { //this fits the case when there's negative number, kind like 560\n if (arr == null || arr.length == 0) return 0;\n Map map = new HashMap<>(); //sum - index\n map.put(0, -1);\n int sum = 0;\n for (int i = 0; i < arr.length; i++) { //record preSum and index\n sum += arr[i];\n map.put(sum, i);\n }\n sum = 0;\n int size = arr.length + 1, res = arr.length + 1;//note if we set size as MAX_VALUE the line 16 may overflow\n for (int i = 0; i < arr.length; i++) {\n sum += arr[i];\n if (map.containsKey(sum - target)) size = Math.min(size, i - map.get(sum - target)); //find the subarray from the previous index to current one\n if (map.containsKey(sum + target)) res = Math.min(res, size + map.get(sum + target) - i); //from the current index to next one, this avoid overlap\n }\n return res == arr.length + 1 ? -1 : res;\n }\n}\n", + "title": "1477. Find Two Non-overlapping Sub-arrays Each With Target Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of integers arr and an integer target . You have to find two non-overlapping sub-arrays of arr each with a sum equal target . There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum . Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 1000", + "1 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,2,4,3], target = 3Output:2Explanation:Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,3,4,7], target = 7Output:2Explanation:Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,3,2,6,2,3,4], target = 6Output:-1Explanation:We have only one sub-array of sum = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float('inf')\n min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer and index of num in arr\n windowSum += num\n while windowSum > target: \n\t\t\t# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target\n windowSum -= arr[l]\n l += 1\n\t\t\t# the case when we found a new target sub-array, i.e. current window\n if windowSum == target:\n\t\t\t # length of current window\n curLen = r - l + 1\n\t\t\t\t# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window: \n\t\t\t\t# avoid overlap with cur window\n\t\t\t\t# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping\n\t\t\t\t# , if < res, update res.\n res = min(res, curLen + min_till[l - 1])\n\t\t\t\t# Everytime we found a target window, update the min_till of current right end of the window, \n\t\t\t\t# for future use when sum up to new length of sum_of_two_subarray and update the res.\n min_till[r] = min(curLen, min_till[r - 1])\n else:\n\t\t\t# If windowSum < target: window with current arr[r] as right end does not have any target subarry, \n\t\t\t# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1. \n min_till[r] = min_till[r - 1]\n return res if res < float('inf') else -1\n\t\nTime = O(n): when sliding the window, left and right pointers traverse the array once.\nSpace = O(n): we use one additional list min_till[] to record min length of target subarray till index i.", + "title": "1477. Find Two Non-overlapping Sub-arrays Each With Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings nums containing n unique binary strings each of length n , return a binary string of length n that does not appear in nums . If there are multiple answers, you may return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 16", + "nums[i].length == n", + "nums[i] is either '0' or '1' .", + "All the strings of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"01\",\"10\"]Output:\"11\"Explanation:\"11\" does not appear in nums. \"00\" would also be correct.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"00\",\"01\"]Output:\"11\"Explanation:\"11\" does not appear in nums. \"10\" would also be correct.", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"111\",\"011\",\"001\"]Output:\"101\"Explanation:\"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder ans= new StringBuilder(); \n for(int i=0; i List[List[int]]:\n matrix = []\n for row in range(len(rowSum)):\n data, array = rowSum[row], []\n for col in range(len(colSum)):\n if data == 0 or colSum[col] == 0:\n array.append(0)\n elif data > colSum[col]:\n data -= colSum[col]\n array.append(colSum[col])\n colSum[col] = 0\n else:\n array.append(data)\n colSum[col] -= data\n data = 0\n matrix.append(array)\n\n return matrix\n \n \n\n\n\n\n\n\n\n", + "title": "1605. Find Valid Matrix Given Row and Column Sums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Given a 2D integer array moves where moves[i] = [row i , col i ] indicates that the i th move will be played on grid[row i ][col i ] . return the winner of the game if it exists ( A or B ). In case the game ends in a draw return \"Draw\" . If there are still movements to play return \"Pending\" . You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe ), the grid is initially empty, and A will play first. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player A always places 'X' characters, while the second player B always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never on filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]Output:\"A\"Explanation:A wins, they always play first.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo1-grid.jpg" + }, + { + "text": "Example 2: Input:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]Output:\"B\"Explanation:B wins.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo2-grid.jpg" + }, + { + "text": "Example 3: Input:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]Output:\"Draw\"Explanation:The game ends in a draw since there are no moves to make.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo3-grid.jpg" + } + ], + "follow_up": null, + "solution": "/**\nHere is my solution : \n\nTime Complexity O(M) \nSpace Complaexity O(1)\n*/\n\nclass Solution {\n public String tictactoe(int[][] moves) {\n \n int [][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals\n \n for(int turn =0 ; turn < moves.length ; turn++){\n \n\t\t\tint AorB =-1;\n if(turn%2==0){AorB=1;}\n \n rcd[0][moves[turn][0]]+= AorB; \n rcd[1][moves[turn][1]]+= AorB; \n \n if(moves[turn][0]== moves[turn][1]){rcd[2][0]+=AorB;} // first diagonal\n if(moves[turn][0]+moves[turn][1]-2 == 0){rcd[2][1]+=AorB;} //2nd diagonal \n \n if( Math.abs(rcd[0][moves[turn][0]]) == 3 || Math.abs(rcd[1][moves[turn][1]]) == 3 \n ||Math.abs(rcd[2][0]) ==3 || Math.abs(rcd[2][1]) ==3 ){\n \n\t\t\t return AorB == 1 ? \"A\" : \"B\"; }\n } \n \n return moves.length == 9 ? \"Draw\" : \"Pending\";\n \n }\n}\n\n", + "title": "1275. Find Winner on a Tic Tac Toe Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Given a 2D integer array moves where moves[i] = [row i , col i ] indicates that the i th move will be played on grid[row i ][col i ] . return the winner of the game if it exists ( A or B ). In case the game ends in a draw return \"Draw\" . If there are still movements to play return \"Pending\" . You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe ), the grid is initially empty, and A will play first. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player A always places 'X' characters, while the second player B always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never on filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]Output:\"A\"Explanation:A wins, they always play first.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo1-grid.jpg" + }, + { + "text": "Example 2: Input:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]Output:\"B\"Explanation:B wins.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo2-grid.jpg" + }, + { + "text": "Example 3: Input:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]Output:\"Draw\"Explanation:The game ends in a draw since there are no moves to make.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/xo3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n wins = [\n [(0, 0), (0, 1), (0, 2)],\n [(1, 0), (1, 1), (1, 2)],\n [(2, 0), (2, 1), (2, 2)],\n [(0, 0), (1, 0), (2, 0)],\n [(0, 1), (1, 1), (2, 1)],\n [(0, 2), (1, 2), (2, 2)],\n [(0, 0), (1, 1), (2, 2)],\n [(0, 2), (1, 1), (2, 0)],\n ]\n \n def checkWin(S):\n for win in wins:\n flag = True\n for pos in win:\n if pos not in S:\n flag = False\n break\n if flag:\n return True\n return False\n \n A, B = set(), set()\n for i, (x, y) in enumerate(moves):\n if i % 2 == 0:\n A.add((x, y))\n else:\n B.add((x, y))\n \n if checkWin(A):\n return 'A'\n elif checkWin(B):\n return 'B'\n \n return \"Draw\" if len(moves) == 9 else \"Pending\"\n", + "title": "1275. Find Winner on a Tic Tac Toe Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings words and a string chars . A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, chars.length <= 100", + "words[i] and chars consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"Output:6Explanation:The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"Output:10Explanation:The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 90.62%) | Memory: 53.5 MB (Top 72.75%)\nclass Solution {\n public int countCharacters(String[] words, String chars) {\n int[] freq = new int[26];\n for (int i = 0; i < chars.length(); i++) {\n // char - char is a kind of clever way to get the position of\n // the character in the alphabet. 'a' - 'a' would give you 0.\n // 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.\n freq[chars.charAt(i) - 'a'] ++;\n }\n\n int result = 0;\n for (String word : words) {\n int[] copy = Arrays.copyOf(freq, freq.length);\n boolean pass = true;\n for (int j = 0; j < word.length(); j++) {\n // decrement the frequency of this char in array for using\n // if there are less than 1 chance for using this character, invalid,\n // move to next word in words\n if (-- copy[word.charAt(j) - 'a'] < 0) {\n pass = false;\n break;\n }\n }\n if (pass) {\n result += word.length();\n }\n }\n return result;\n }\n}", + "title": "1160. Find Words That Can Be Formed by Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words and a string chars . A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length, chars.length <= 100", + "words[i] and chars consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"Output:6Explanation:The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"Output:10Explanation:The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countCharacters(self, words, chars):\n \"\"\"\n :type words: List[str]\n :type chars: str\n :rtype: int\n \"\"\"\n b = set(chars)\n anwser = 0\n for i in words:\n a = set(i)\n if a.issubset(b):\n test = [o for o in a if chars.count(o) < i.count(o)]\n if len(test) == 0: \n anwser += len(i)\n return anwser\n", + "title": "1160. Find Words That Can Be Formed by Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND ) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length . Return the XOR sum of the aforementioned list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4 , and the XOR sum of [3] is equal to 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3], arr2 = [6,5]Output:0Explanation:The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [12], arr2 = [4]Output:4Explanation:The list = [12 AND 4] = [4]. The XOR sum = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 19.55%) | Memory: 56.30 MB (Top 85.71%)\n\nclass Solution {\n public int getXORSum(int[] arr1, int[] arr2) {\n \n int xor1 = 0, xor2 = 0;\n \n for (int arr : arr1) {\n xor1 ^= arr;\n }\n \n for (int arr : arr2) {\n xor2 ^= arr;\n }\n \n return xor1 & xor2;\n }\n}\n", + "title": "1835. Find XOR Sum of All Pairs Bitwise AND", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND ) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length . Return the XOR sum of the aforementioned list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4 , and the XOR sum of [3] is equal to 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3], arr2 = [6,5]Output:0Explanation:The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [12], arr2 = [4]Output:4Explanation:The list = [12 AND 4] = [4]. The XOR sum = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2209 ms (Top 51.91%) | Memory: 30.3 MB (Top 21.37%)\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)\n return xor_lis(arr1) & xor_lis(arr2)", + "title": "1835. Find XOR Sum of All Pairs Bitwise AND", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array digits , where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3] , integers 132 and 312 follow the requirements. Return a sorted array of the unique integers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The integer consists of the concatenation of three elements from digits in any arbitrary order.", + "The integer does not have leading zeros .", + "The integer is even ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [2,1,3,0]Output:[102,120,130,132,210,230,302,310,312,320]Explanation:All the possible integers that follow the requirements are in the output array. \nNotice that there are nooddintegers or integers withleading zeros.", + "image": null + }, + { + "text": "Example 2: Input:digits = [2,2,8,8,2]Output:[222,228,282,288,822,828,882]Explanation:The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882.", + "image": null + }, + { + "text": "Example 3: Input:digits = [3,7,5]Output:[]Explanation:Noevenintegers can be formed using the given digits.", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n\nAs we know that we want unique numbers of 3 digits only that too only even. so first we \ngather the frequency of all the digits we have, then we iterate from 100 to 999 ( all possible 3 digits numbers, 100,102,104...\nall possible even 3 digit numbers). for ex we are iterating and we are\nat 104 so we will see that if we have digits\n1,0,4 in our database if yes then we can make this number from our\navailable digits given to us.\n\n\nTime complexity : O(digits.length) // due to making of frequency map\nSpace Complexity : O(1) //fixed map array space for digits 0 to 9\n*/\n\nclass Solution {\n public int[] findEvenNumbers(int[] digits) {\n int [] map = new int[10]; // for freq of 0 to 9 (digits are fixed)\n \n for(int i = 0;i arr = new ArrayList<>();\n \n for(int i = 100;i<=999;i = i + 2){ //will always runs from 100 to 999 \n int num = i;\n int [] freq = new int[10];\n while(num > 0){ // will always run 3 times\n int rem = num % 10;\n freq[rem]++;\n num = num/10;\n }\n \n boolean res = findans(freq,map);\n if(res) arr.add(i);\n }\n \n int [] ans = new int[arr.size()]; //logic for arraylist to array conversion\n for(int i = 0;i database[i]) return false;\n }\n return true;\n }\n}\n", + "title": "2094. Finding 3-Digit Even Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array digits , where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3] , integers 132 and 312 follow the requirements. Return a sorted array of the unique integers. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The integer consists of the concatenation of three elements from digits in any arbitrary order.", + "The integer does not have leading zeros .", + "The integer is even ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [2,1,3,0]Output:[102,120,130,132,210,230,302,310,312,320]Explanation:All the possible integers that follow the requirements are in the output array. \nNotice that there are nooddintegers or integers withleading zeros.", + "image": null + }, + { + "text": "Example 2: Input:digits = [2,2,8,8,2]Output:[222,228,282,288,822,828,882]Explanation:The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882.", + "image": null + }, + { + "text": "Example 3: Input:digits = [3,7,5]Output:[]Explanation:Noevenintegers can be formed using the given digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n hmap, res = defaultdict(int), []\n for num in digits:\n hmap[num] += 1 #counting frequency of digits of digits array\n \n for num in range(100, 999, 2): #step 2 because we need even numbers\n checker = defaultdict(int)\n for digit in str(num):\n checker[int(digit)] += 1 #counting frequency of digits of num\n \n\t\t\t#check if every digit in num is in digits array and its frequency is less than or equal to its frequency in digits array\n if all(map(lambda x: x in hmap and checker[x] <= hmap[x], checker)):\n res.append(num)\n \n return res\n", + "title": "2094. Finding 3-Digit Even Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers, m and k , and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class: Example 1:", + "description_images": [], + "constraints": [ + "MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k .", + "void addElement(int num) Inserts a new element num into the stream.", + "int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]Output[null, null, null, -1, null, 3, null, null, null, 5]ExplanationMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be[3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be[5].\n // The average of [5] equals 5/1 = 5, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "class MKAverage {\n class Node implements Comparable {\n int val;\n int time;\n \n Node(int val, int time) {\n this.val = val;\n this.time = time;\n }\n \n @Override\n public int compareTo(Node other) {\n return (this.val != other.val ? this.val - other.val \n : this.time - other.time);\n }\n }\n \n private TreeSet set = new TreeSet<>(); // natural order\n private Deque queue = new LinkedList<>();\n private Node kLeft;\n private Node kRight;\n \n private int m, k;\n \n private int time = 0;\n private int sum = 0;\n\n public MKAverage(int m, int k) {\n this.m = m;\n this.k = k;\n }\n \n public void addElement(int num) {\n Node node = new Node(num, time++);\n\n addNode(node);\n removeNode();\n \n if (time == m) init();\n }\n \n private void init() {\n int i = 0;\n for (Node node : set) {\n if (i < k-1);\n else if (i == k-1) kLeft = node;\n else if (i < m-k) sum += node.val;\n else if (i == m-k) {\n kRight = node;\n return;\n }\n \n i++;\n }\n return;\n }\n \n private void addNode(Node node) {\n queue.offerLast(node);\n set.add(node);\n \n if (queue.size() <= m) return;\n \n if (node.compareTo(kLeft) < 0) {\n sum += kLeft.val;\n kLeft = set.lower(kLeft);\n } else if (node.compareTo(kRight) > 0) {\n sum += kRight.val;\n kRight = set.higher(kRight);\n } else {\n sum += node.val;\n } \n }\n \n private void removeNode() {\n if (queue.size() <= m) return;\n \n Node node = queue.pollFirst();\n \n if (node.compareTo(kLeft) <= 0) {\n kLeft = set.higher(kLeft);\n sum -= kLeft.val;\n } else if (node.compareTo(kRight) >= 0) {\n kRight = set.lower(kRight);\n sum -= kRight.val;\n } else {\n sum -= node.val;\n }\n \n set.remove(node);\n }\n \n public int calculateMKAverage() {\n return (queue.size() < m ? -1 : sum / (m - 2 * k));\n }\n}\n", + "title": "1825. Finding MK Average", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two integers, m and k , and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class: Example 1:", + "description_images": [], + "constraints": [ + "MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k .", + "void addElement(int num) Inserts a new element num into the stream.", + "int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]Output[null, null, null, -1, null, 3, null, null, null, 5]ExplanationMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be[3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be[5].\n // The average of [5] equals 5/1 = 5, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\n\nclass MKAverage:\n\n MAX_NUM = 10 ** 5\n def __init__(self, m: int, k: int):\n \n self.m = m\n self.k = k\n \n # sorted list\n self.sl = SortedList([0] * m)\n\t\t# sum of k smallest elements\n self.sum_k = 0\n\t\t# sum of m - k smallest elements\n self.sum_m_k = 0\n \n # queue for the last M elements if the stream\n self.q = deque([0] * m)\n \n def addElement(self, num: int) -> None:\n # Time: O(logm)\n\t\t\n m, k, q, sl = self.m, self.k, self.q, self.sl \n \n # update q\n q.append(num)\n old = q.popleft()\n \n # remove the old num\n r = sl.bisect_right(old)\n\t\t# maintain sum_k\n if r <= k:\n self.sum_k -= old\n self.sum_k += sl[k]\n\t\t# maintain sum_m_k\n if r <= m - k:\n self.sum_m_k -= old\n self.sum_m_k += sl[m-k]\n # remove the old num\n sl.remove(old)\n \n # add the new num\n r = sl.bisect_right(num)\n if r < k:\n self.sum_k -= sl[k-1]\n self.sum_k += num\n if r < m - k:\n self.sum_m_k -= sl[m - k - 1]\n self.sum_m_k += num\n \n sl.add(num)\n \n return\n\n def calculateMKAverage(self) -> int:\n\t\t# Time: O(1)\n if self.sl[0] == 0:\n return -1\n return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)\n", + "title": "1825. Finding MK Average", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 . You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: Example 1:", + "description_images": [], + "constraints": [ + "FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2 .", + "void add(int index, int val) Adds val to nums2[index] , i.e., apply nums2[index] += val .", + "int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot ." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]Output[null, 8, null, 2, 1, null, null, 11]ExplanationFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "class FindSumPairs {\n\n private int [] nums1;\n private int [] nums2;\n Map map = new HashMap<>();\n public FindSumPairs(int[] nums1, int[] nums2) {\n this.nums1 = nums1;\n this.nums2 = nums2;\n for (int number : nums2) {\n map.put(number, map.getOrDefault(number, 0) + 1);\n } \n \n }\n \n public void add(int index, int val) {\n map.put(nums2[index], map.get(nums2[index]) - 1);\n nums2[index] += val;\n map.put(nums2[index], map.getOrDefault(nums2[index], 0) + 1);\n }\n \n public int count(int tot) {\n int result = 0;\n for (int number : nums1) {\n if (map.containsKey(tot - number)) {\n result += map.get(tot - number);\n }\n }\n return result;\n }\n}\n\n/**\n * Your FindSumPairs object will be instantiated and called as such:\n * FindSumPairs obj = new FindSumPairs(nums1, nums2);\n * obj.add(index,val);\n * int param_2 = obj.count(tot);\n */\n", + "title": "1865. Finding Pairs With a Certain Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 . You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: Example 1:", + "description_images": [], + "constraints": [ + "FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2 .", + "void add(int index, int val) Adds val to nums2[index] , i.e., apply nums2[index] += val .", + "int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot ." + ], + "examples": [ + { + "text": "Example 1: Input[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]Output[null, 8, null, 2, 1, null, null, 11]ExplanationFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1039 ms (Top 5.41%) | Memory: 80.00 MB (Top 22.7%)\n\nclass FindSumPairs:\n\n def __init__(self, nums1: List[int], nums2: List[int]):\n self.nums1 = sorted(nums1)\n self.nums2 = nums2\n self.hash2 = defaultdict(int)\n for n in nums2:\n self.hash2[n] += 1\n\n def add(self, index: int, val: int) -> None:\n self.hash2[self.nums2[index]] -= 1\n self.nums2[index] += val\n self.hash2[self.nums2[index]] += 1\n\n def count(self, tot: int) -> int:\n result = 0\n for n in self.nums1:\n if n >= tot:\n break\n result += self.hash2[tot - n]\n return result\n", + "title": "1865. Finding Pairs With a Certain Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the logs for users' actions on LeetCode, and an integer k . The logs are represented by a 2D integer array logs where each logs[i] = [ID i , time i ] indicates that the user with ID i performed an action at the minute time i . Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j ( 1 <= j <= k ), answer[j] is the number of users whose UAM equals j . Return the array answer as described above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 10^4", + "0 <= ID i <= 10^9", + "1 <= time i <= 10^5", + "k is in the range [The maximum UAM for a user, 10^5 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5Output:[0,2,0,0,0]Explanation:The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1,1],[2,2],[2,3]], k = 4Output:[1,1,0,0]Explanation:The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 74.46%) | Memory: 56.30 MB (Top 38.32%)\n\nclass Solution {\n public int[] findingUsersActiveMinutes(int[][] logs, int k) {\n // create a hashmap to record the ids of users \n // and a set to store the minutes in which they were active\n Map> map = new HashMap<>();\n for (int[] l : logs) {\n // l[0] -> id, l[1] -> active minute\n map.putIfAbsent(l[0], new HashSet<>()); // if new id\n map.get(l[0]).add(l[1]); // add the minute of activeness to the set\n }\n\n // create answer array\n int[] ans = new int[k]; \n for (int id : map.keySet()) {\n // the set contains all the minutes in which the id was active\n // so the set size will be the number of active minutes\n // or the 'User Active Minutes' (UAM)\n int uam = map.get(id).size();\n // each index in ans array is a UAM, \n // and we need to put the number of users having that UAM\n // whenever we enocunter a UAM, we increment the value in array\n // which means we have found one more user with the same UAM\n ans[uam-1]++; // since array is 1 based indexing, we substract 1\n }\n\n return ans; // return ans array\n }\n}\n", + "title": "1817. Finding the Users Active Minutes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the logs for users' actions on LeetCode, and an integer k . The logs are represented by a 2D integer array logs where each logs[i] = [ID i , time i ] indicates that the user with ID i performed an action at the minute time i . Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j ( 1 <= j <= k ), answer[j] is the number of users whose UAM equals j . Return the array answer as described above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 10^4", + "0 <= ID i <= 10^9", + "1 <= time i <= 10^5", + "k is in the range [The maximum UAM for a user, 10^5 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5Output:[0,2,0,0,0]Explanation:The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1,1],[2,2],[2,3]], k = 4Output:[1,1,0,0]Explanation:The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n ret = [0] * k # UAM store\n user_acts = {} # User minutes store\n \n # Adding user minutes to hash table\n\t\tfor log in logs:\n if user_acts.get(log[0], 0):\n user_acts[log[0]].append(log[1])\n else:\n user_acts[log[0]] = [log[1]]\n \n # Calculating UAM\n\t\tfor k, v in user_acts.items():\n l = len(set(v))\n ret[l-1] += 1\n \n return ret\n", + "title": "1817. Finding the Users Active Minutes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4Output:4Explanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/* The isBadVersion API is defined in the parent class VersionControl.\n boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n public int firstBadVersion(int n) {\n int s = 0; int e = n;\n \n while(s < e) {\n int mid = s +(e-s)/2;\n \n if(isBadVersion(mid)){\n e = mid ;\n } else {\n s = mid +1;\n }\n }\n return e ;\n }\n}\n", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4Output:4Explanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n fast, slow = int(n/2), n\n diff = abs(fast-slow)\n while isBadVersion(fast) == isBadVersion(slow) or diff > 1:\n fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast\n diff = abs(fast-slow)\n return fast if isBadVersion(fast) else slow\n", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms you need to visit, labeled from 0 to n - 1 . Each day is labeled, starting from 0 . You will go in and visit one room a day. Initially on day 0 , you visit room 0 . The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n : Return the label of the first day where you have been in all the rooms . It can be shown that such a day exists. Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Assuming that on a day, you visit room i ,", + "if you have been in room i an odd number of times ( including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i ;", + "if you have been in room i an even number of times ( including the current visit), on the next day you will visit room (i + 1) mod n ." + ], + "examples": [ + { + "text": "Example 1: Input:nextVisit = [0,0]Output:2Explanation:- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n  On the next day you will visit room nextVisit[0] = 0\n- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n  On the next day you will visit room (0 + 1) mod 2 = 1\n- On day 2, you visit room 1. This is the first day where you have been in all the rooms.", + "image": null + }, + { + "text": "Example 2: Input:nextVisit = [0,0,2]Output:6Explanation:Your room visiting order for each day is: [0,0,1,0,0,1,2,...].\nDay 6 is the first day where you have been in all the rooms.", + "image": null + }, + { + "text": "Example 3: Input:nextVisit = [0,1,2,0]Output:6Explanation:Your room visiting order for each day is: [0,0,1,1,2,2,3,...].\nDay 6 is the first day where you have been in all the rooms.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstDayBeenInAllRooms(int[] nextVisit) {\n int rooms = nextVisit.length;\n long dp[] = new long[rooms];\n int mod = (int)(1e9)+7;\n for (int i=1 ; i int:\n\t n:int = len(nextVisit)\n days:List[int] = n*[0] # days[i] is the number of days it takes to first reach room i\n MOD = pow(10, 9) + 7\n for i in range(0,n-1):\n # First we are already at room i. days[i] days has passed\n days[i+1] = days[i]\n # lets go from room i to room i+1. \n # When we first visit room i, we need to visit room i again (so room i is visited twice, which is an even number), then we can visit room i+1\n # after we fist visit room i, the next day we will visit room (nextVisit[i]). \n days[i+1] = (days[i+1] + 1) % MOD\n # Then the problem becomes \"how to go from room (nextVisit[i]) back to room i\". The step is (days[i] - days[nextVisit[i]])\n days[i+1] = (days[i+1] + days[i] - days[nextVisit[i]]) % MOD\n # Then, in the next day we go from room i to i+1\n days[i+1] = (days[i+1] + 1) % MOD\n \n return days[n-1]\n", + "title": "1997. First Day Where You Have Been in All the Rooms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of lowercase English letters, return the first letter to appear twice . Note : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b .", + "s will contain at least one letter that appears twice." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccbaacz\"Output:\"c\"Explanation:The letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdd\"Output:\"d\"Explanation:The only letter that appears twice is 'd' so we return 'd'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 23.65%)\n\nclass Solution {\n public char repeatedCharacter(String s) {\n HashSet set = new HashSet<>();//Create a set of characters\n for(int i = 0 ; i < s.length() ; i++){\n if(set.contains(s.charAt(i))) return s.charAt(i);//If the set already contains the current character, then it is the required ans\n set.add(s.charAt(i));\n }\n return 'a';//As it is given in the question that there is at least one letter that appears twice, therefore it is certain that the ans will be found before we reach this statement. So, just adding any random return statement so that there is no error in the code.\n }\n}\n", + "title": "2351. First Letter to Appear Twice", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s consisting of lowercase English letters, return the first letter to appear twice . Note : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b .", + "s will contain at least one letter that appears twice." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccbaacz\"Output:\"c\"Explanation:The letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcdd\"Output:\"d\"Explanation:The only letter that appears twice is 'd' so we return 'd'.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def repeatedCharacter(self, s: str) -> str:\n occurences = defaultdict(int)\n for char in s:\n occurences[char] += 1\n if occurences[char] == 2:\n return char\n", + "title": "2351. First Letter to Appear Twice", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an unsorted integer array nums , return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0]Output:3Explanation:The numbers in the range [1,2] are all in the array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,-1,1]Output:2Explanation:1 is in the array but 2 is missing.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,8,9,11,12]Output:1Explanation:The smallest positive integer 1 is missing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 91.14%) | Memory: 57.8 MB (Top 74.85%)\nclass Solution {\n public int firstMissingPositive(int[] nums) {\n //cyclic sort\n int i = 0;\n while (i0 && nums[i]<=nums.length && nums[i]!=nums[correct]){\n swap(nums,i,correct);\n }else{\n i++;\n }\n }\n //linear search to find the missing number\n for(int index=0;index int:\n mn = float('inf')\n mx = 0\n numsSet = set()\n\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] > 0:\n if nums[i] < mn:\n mn = nums[i]\n if nums[i] > mx:\n mx = nums[i]\n numsSet.add(nums[i])\n del nums[i]\n\n if mn >= 2:\n return 1\n if len(numsSet) == mx:\n return mx + 1\n for i in range(2, len(numsSet) + 1):\n if i not in numsSet:\n return i", + "title": "41. First Missing Positive", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the first non-repeating character in it and return its index . If it does not exist, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\"Output:0", + "image": null + }, + { + "text": "Example 2: Input:s = \"loveleetcode\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabb\"Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstUniqChar(String s) {\n HashMaphmap=new HashMap<>();\n for(int i=0;i int:\n ls=[]\n for i in range(len(s)):\n x=s.count(s[i])\n if x==1:\n return i\n return -1\n", + "title": "387. First Unique Character in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a string array answer ( 1-indexed ) where : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5 .", + "answer[i] == \"Fizz\" if i is divisible by 3 .", + "answer[i] == \"Buzz\" if i is divisible by 5 .", + "answer[i] == i (as a string) if none of the above conditions are true." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[\"1\",\"2\",\"Fizz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 15Output:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.61%) | Memory: 45.20 MB (Top 33.59%)\n\nclass Solution {\n public List fizzBuzz(int n) {\n List ans = new ArrayList<>();\n for (int i = 1; i <= n; i++) {\n if (i % 15 == 0) {\n ans.add(\"FizzBuzz\");\n } else if (i % 3 == 0) {\n ans.add(\"Fizz\");\n } else if (i % 5 == 0) {\n ans.add(\"Buzz\");\n } else {\n ans.add(String.valueOf(i));\n }\n }\n \n return ans; \n }\n}\n\n// TC: O(n), SC: O(n)\n", + "title": "412. Fizz Buzz", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return a string array answer ( 1-indexed ) where : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5 .", + "answer[i] == \"Fizz\" if i is divisible by 3 .", + "answer[i] == \"Buzz\" if i is divisible by 5 .", + "answer[i] == i (as a string) if none of the above conditions are true." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[\"1\",\"2\",\"Fizz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 15Output:[\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n result = []\n for i in range(1, n+1):\n if i % 3 == 0 and i % 5 == 0:\n result.append('FizzBuzz')\n elif i % 3 == 0:\n result.append('Fizz')\n elif i % 5 == 0:\n result.append('Buzz')\n else:\n result.append(str(i))\n return result\n", + "title": "412. Fizz Buzz", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer . This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of Nodes will not exceed 1000 .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]Output:[1,2,3,7,8,11,12,9,10,4,5,6]Explanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,null,3]Output:[1,3,2]Explanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]Explanation:There could be empty list in the input.", + "image": null + }, + { + "text": "Example 1 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]", + "image": null + }, + { + "text": "[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.2 MB (Top 95.78%)\nclass Solution {\n public Node flatten(Node head) {\n Node curr = head ; // for traversal\n Node tail = head; // for keeping the track of previous node\n Stack stack = new Stack<>(); // for storing the reference of next node when child node encounters\n while(curr != null){\n if(curr.child != null){ // if there is a child\n Node child = curr.child; // creating a node for child\n if(curr.next != null){ // if there is list after we find child a child\n stack.push(curr.next); // pushing the list to the stack\n curr.next.prev = null; // pointing its previous to null\n }\n curr.next = child; // pointing the current's reference to child\n child.prev = curr; // pointing child's previous reference to current.\n curr.child = null; // pointing the current's child pointer to null\n }\n tail = curr ; // for keeping track of previous nodes\n curr= curr.next; // traversing\n }\n while(!stack.isEmpty()){ // checking if the stack has still nodes in it.\n curr = stack.pop(); // getting the last node of the list pushed into the stack\n tail.next = curr; // pointing the previos node to the last node\n curr.prev = tail; // pointing previos pointer of the last node to the previos node.\n while( curr != null){ // traversing the last node's popped out of stack\n tail = curr;\n curr = curr.next ;\n }\n }\n return head;\n }\n}", + "title": "430. Flatten a Multilevel Doubly Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer . This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of Nodes will not exceed 1000 .", + "1 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]Output:[1,2,3,7,8,11,12,9,10,4,5,6]Explanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,null,3]Output:[1,3,2]Explanation:The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:", + "image": "https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]Explanation:There could be empty list in the input.", + "image": null + }, + { + "text": "Example 1 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]", + "image": null + }, + { + "text": "[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]", + "image": null + }, + { + "text": "[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': \n node = head\n while node:\n if node.child: # If there is a child travel to last node of the child\n child = node.child\n while child.next:\n child = child.next\n child.next = node.next # Update the next of child to the the next of the current node\n if node.next: # update the prev of the next node to chile to make it valid doubly linked list\n node.next.prev = child\n node.next = node.child # Update the child to become the next of the current\n node.next.prev = node # update the prev of the next node to chile to make it valid doubly linked list\n node.child = None # Make the child of the current node None to fulfill the requirements\n node = node.next\n return head\n\n# time and space complexity\n# time: O(n)\n# space: O(1)\n", + "title": "430. Flatten a Multilevel Doubly Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\": Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]Output:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void flatten(TreeNode root) {\n TreeNode curr=root;\n while(curr!=null)\n {\n if(curr.left!=null)\n {\n TreeNode prev=curr.left;\n while(prev.right!=null)\n prev=prev.right;\n prev.right=curr.right;\n curr.right=curr.left; \n curr.left=null; \n }\n curr=curr.right;\n }\n }\n}\n", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\": Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]Output:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 52.37%) | Memory: 15.1 MB (Top 89.03%)\n#Call the right of the tree node till the node root left and right is not None\n#After reaching the bottom of the tree make the root.right = prev and\n#root.left = None and then prev = None\n#Initially prev will point to None but this is used to point the previously visited root node\n#Prev pointer helps us to change the values from left to right\nclass Solution:\n def flatten(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n prev = None #You can also define that variable inside the init function using self keyword\n def dfs(root):\n nonlocal prev\n\n if not root:\n return\n\n dfs(root.right)\n dfs(root.left)\n\n root.right = prev\n root.left = None\n prev = root\n\n dfs(root)\n# If the above solution is hard to understand than one can do level order traversal\n#Using Stack DS but this will increase the space complexity to O(N).", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a nested list of integers nestedList . Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: Your code will be tested with the following pseudocode: If res matches the expected flattened list, then your code will be judged as correct. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList .", + "int next() Returns the next integer in the nested list.", + "boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input:nestedList = [[1,1],2,[1,1]]Output:[1,1,2,1,1]Explanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nestedList = [1,[4,[6]]]Output:[1,4,6]Explanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].", + "image": null + }, + { + "text": "initialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 77.47%) | Memory: 46.1 MB (Top 81.31%)\npublic class NestedIterator implements Iterator {\n List list=new ArrayList();\n void flatten(List nestedList){\n for(NestedInteger nested:nestedList){\n if(nested.isInteger())\n list.add(nested.getInteger());\n else\n flatten(nested.getList());\n }\n }\n public NestedIterator(List nestedList) {\n flatten(nestedList);\n }\n int index=0;\n @Override\n public Integer next() {\n return list.get(index++);\n }\n\n @Override\n public boolean hasNext() {\n return index nestedList) Initializes the iterator with the nested list nestedList .", + "int next() Returns the next integer in the nested list.", + "boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input:nestedList = [[1,1],2,[1,1]]Output:[1,1,2,1,1]Explanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nestedList = [1,[4,[6]]]Output:[1,4,6]Explanation:By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].", + "image": null + }, + { + "text": "initialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res", + "image": null + } + ], + "follow_up": null, + "solution": "class NestedIterator:\n def __init__(self, nestedList: [NestedInteger]):\n self.flattened_lst = self.flattenList(nestedList)\n self.idx = 0\n \n def next(self) -> int:\n if self.idx >= len(self.flattened_lst):\n raise Exception(\"Index out of bound\")\n self.idx += 1\n return self.flattened_lst[self.idx-1]\n \n def hasNext(self) -> bool:\n return self.idx < len(self.flattened_lst)\n \n def flattenList(self, lst):\n flattened_lst = []\n for ele in lst:\n if ele.isInteger():\n flattened_lst.append(ele.getInteger())\n else:\n flattened_lst.extend(self.flattenList(ele.getList()))\n return flattened_lst", + "title": "341. Flatten Nested List Iterator", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n . You are also given a sequence of n values voyage , which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage . Return a list of the values of all flipped nodes. You may return the answer in any order . If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage , return the list [-1] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "n == voyage.length", + "1 <= n <= 100", + "1 <= Node.val, voyage[i] <= n", + "All the values in the tree are unique .", + "All the values in voyage are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2], voyage = [2,1]Output:[-1]Explanation:It is impossible to flip the nodes such that the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], voyage = [1,3,2]Output:[1]Explanation:Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3], voyage = [1,2,3]Output:[]Explanation:The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.10 MB (Top 56.52%)\n\nclass Solution {\n int vix = 0;\n List ans = new ArrayList<>();\n private void dfs(TreeNode node, int[] V) {\n if (node == null || (ans.size() != 0 && ans.get(0) == -1)) return;\n if (node.val != V[vix++])\n ans = new ArrayList(Arrays.asList(-1));\n else if (node.left != null && node.left.val != V[vix]) {\n ans.add(node.val);\n dfs(node.right, V);\n dfs(node.left, V);\n } else {\n dfs(node.left, V);\n dfs(node.right, V);\n }\n }\n public List flipMatchVoyage(TreeNode root, int[] V) {\n dfs(root, V);\n return ans;\n }\n}\n", + "title": "971. Flip Binary Tree To Match Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n . You are also given a sequence of n values voyage , which is the desired pre-order traversal of the binary tree. Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage . Return a list of the values of all flipped nodes. You may return the answer in any order . If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage , return the list [-1] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "n == voyage.length", + "1 <= n <= 100", + "1 <= Node.val, voyage[i] <= n", + "All the values in the tree are unique .", + "All the values in voyage are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2], voyage = [2,1]Output:[-1]Explanation:It is impossible to flip the nodes such that the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" + }, + { + "text": "Example 2: Input:root = [1,2,3], voyage = [1,3,2]Output:[1]Explanation:Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + }, + { + "text": "Example 3: Input:root = [1,2,3], voyage = [1,2,3]Output:[]Explanation:The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.", + "image": "https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 21.2%) | Memory: 16.23 MB (Top 89.3%)\n\nclass Solution:\n def flipMatchVoyage(self, root, voyage):\n \n # ------------------------------\n \n def dfs(root):\n \n if not root:\n # base case aka stop condition\n\t\t\t\t# empty node or empty tree\n return True\n \n \n ## general cases\n if root.val != voyage[dfs.idx]:\n \n # current node mismatch, no chance to make correction by flip\n return False\n \n # voyage index moves forward\n dfs.idx += 1\n \n if root.left and (root.left.val != voyage[dfs.idx]):\n \n # left child mismatch, flip with right child if right child exists\n root.right and result.append( root.val )\n \n # check subtree in preorder DFS with child node flip\n return dfs(root.right) and dfs(root.left)\n \n else:\n \n # left child match, check subtree in preorder DFS\n return dfs(root.left) and dfs(root.right)\n \n \n # --------------------------\n \n # flip sequence\n result = []\n \n # voyage index during dfs\n dfs.idx = 0\n \n # start checking from root node\n good = dfs(root)\n \n return result if good else [-1]", + "title": "971. Flip Binary Tree To Match Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary matrix matrix . You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1],[1,1]]Output:1Explanation:After flipping no values, 1 row has all values equal.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[0,1],[1,0]]Output:2Explanation:After flipping values in the first column, both rows have equal values.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[0,0,0],[0,0,1],[1,1,0]]Output:2Explanation:After flipping values in the first two columns, the last two rows have equal values.", + "image": null + } + ], + "follow_up": null, + "solution": "from typing import List\nfrom collections import Counter\n\n\nclass Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n counter = Counter()\n max_val = 2 ** len(matrix[0]) - 1\n for row in matrix:\n v = self.calculate_binary(row)\n counter[v] += 1\n counter[max_val - v] += 1\n # print(f'counter: {counter}')\n\n return counter.most_common(1)[0][1]\n\n def calculate_binary(self, row: List[int]) -> int:\n val = 0\n for r in row:\n val = val * 2 + r\n return val\n", + "title": "1072. Flip Columns For Maximum Number of Equal Rows", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For a binary tree T , we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees root1 and root2 , return true if the two trees are flip equivalent or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 100] .", + "Each tree will have unique node values in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]Output:trueExplanation:We flipped at nodes with values 1, 3, and 5.", + "image": "https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png" + }, + { + "text": "Example 2: Input:root1 = [], root2 = []Output:true", + "image": null + }, + { + "text": "Example 3: Input:root1 = [], root2 = [1]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean flipEquiv(TreeNode root1, TreeNode root2) {\n return helper(root1, root2);\n }\n \n private boolean helper(TreeNode x, TreeNode y)\n {\n if(x == null && y == null) return true;\n if(x == null || y == null || x.val != y.val) return false;\n boolean similarity = helper(x.left, y.left) && helper(x.right, y.right); // check if 2 subtrees are similar\n boolean swap = helper(x.left, y.right) && helper(x.right, y.left); // check if the 2 subtrees can be similar after swapping the left & right subtrees with each other\n \n return similarity || swap; // if either true, means we can flip to match both trees\n }\n}\n", + "title": "951. Flip Equivalent Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "For a binary tree T , we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Given the roots of two binary trees root1 and root2 , return true if the two trees are flip equivalent or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in each tree is in the range [0, 100] .", + "Each tree will have unique node values in the range [0, 99] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]Output:trueExplanation:We flipped at nodes with values 1, 3, and 5.", + "image": "https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png" + }, + { + "text": "Example 2: Input:root1 = [], root2 = []Output:true", + "image": null + }, + { + "text": "Example 3: Input:root1 = [], root2 = [1]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 89.57%) | Memory: 16.70 MB (Top 53.69%)\n\nclass Solution:\n def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n queue = deque([(root1, root2)])\n while queue:\n node1, node2 = queue.pop()\n if (not node1) and (not node2):\n continue\n elif (not node1) or (not node2) or (node1.val != node2.val):\n return False\n L1, R1, L2, R2 = node1.left, node1.right, node2.left, node2.right\n if (L1 and L2 and L1.val == L2.val) or (R1 and R2 and R1.val == R2.val):\n queue.append((L1, L2))\n queue.append((R1, R2))\n else:\n queue.append((L1, R2))\n queue.append((L2, R1))\n return True\n", + "title": "951. Flip Equivalent Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A binary string is monotone increasing if it consists of some number of 0 's (possibly none), followed by some number of 1 's (also possibly none). You are given a binary string s . You can flip s[i] changing it from 0 to 1 or from 1 to 0 . Return the minimum number of flips to make s monotone increasing . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"00110\"Output:1Explanation:We flip the last digit to get 00111.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010110\"Output:2Explanation:We flip to get 011111, or alternatively 000111.", + "image": null + }, + { + "text": "Example 3: Input:s = \"00011000\"Output:2Explanation:We flip to get 00000000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlipsMonoIncr(String s) {\n int n = s.length();\n int zeroToOne =0;\n int countOfOnes=0;\n for(int i=0;i int:\n n = len(s)\n min_flip = n\n one_left = 0\n # zero_right = 0\n # for c in s:\n # if c == \"0\":\n # zero_right += 1\n \n zero_right = s.count(\"0\") # since we will start with 11...11 then every zero in s will be on the right side of the border\n \n # for each i imagine that we have the borderline at i index any index >= i will be 1 and index < i will be 0.\n # i = 0, n = 5 -> 11111\n # i = 1, n = 5 -> 01111\n # i = 5 -> 00000\n for i in range(n + 1):\n # the number of flip will be equal number of 1 on the left side of the border + number of zero on the right side of the border\n # from example 00110\n # v \n # comparing with 00111 : i = 2, one_left = 0, zero_right = 1, then we have to do 0 + 1 flip in this i\n min_flip = min(min_flip,one_left+zero_right)\n \n # edge case for i = n or all zero (00...00)\n if i == len(s):\n continue\n # reduce count of zero_right when 0 is moving to the 0-zone or left side of border\n if s[i] == \"0\":\n zero_right -= 1\n else:\n one_left += 1 # increase one on the left side when we move 1 into the left side\n \n return min_flip\n \n \n", + "title": "926. Flip String to Monotone Increasing", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an n x n binary matrix image , flip the image horizontally , then invert it, and return the resulting image . To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1 , and each 1 is replaced by 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, flipping [1,1,0] horizontally results in [0,1,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,0],[1,0,1],[0,0,0]]Output:[[1,0,0],[0,1,0],[1,1,1]]Explanation:First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]Output:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]Explanation:First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.21%) | Memory: 44.9 MB (Top 51.92%)\nclass Solution {\n public int[][] flipAndInvertImage(int[][] image) {\n for (int i = 0; i < image.length; ++i) {\n flip(image[i]);\n }\n for (int i = 0; i < image.length; ++i) {\n for (int j = 0; j < image[i].length; ++j) {\n image[i][j] = image[i][j] == 1 ? 0:1;\n }\n }\n return image;\n }\n public static void flip(int[] row) {\n int i = 0;\n int j = row.length - 1;\n while (i < j) {\n int temp = row[i];\n row[i] = row[j];\n row[j] = temp;\n ++i;\n --j;\n }\n }\n}", + "title": "832. Flipping an Image", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n x n binary matrix image , flip the image horizontally , then invert it, and return the resulting image . To flip an image horizontally means that each row of the image is reversed. To invert an image means that each 0 is replaced by 1 , and each 1 is replaced by 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, flipping [1,1,0] horizontally results in [0,1,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,0],[1,0,1],[0,0,0]]Output:[[1,0,0],[0,1,0],[1,1,1]]Explanation:First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]Output:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]Explanation:First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n return [[(1 - i) for i in row[::-1]] for row in image]\n", + "title": "832. Flipping an Image", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr , sc , and color . You should perform a flood fill on the image starting from the pixel image[sr][sc] . To perform a flood fill , consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color . Return the modified image after performing the flood fill . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == image.length", + "n == image[i].length", + "1 <= m, n <= 50", + "0 <= image[i][j], color < 2 16", + "0 <= sr < m", + "0 <= sc < n" + ], + "examples": [ + { + "text": "Example 1: Input:image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2Output:[[2,2,2],[2,2,0],[2,0,1]]Explanation:From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.", + "image": "https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg" + }, + { + "text": "Example 2: Input:image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0Output:[[0,0,0],[0,0,0]]Explanation:The starting pixel is already colored 0, so no changes are made to the image.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.13%) | Memory: 48.4 MB (Top 21.53%)\nclass Solution {\n void colorFill(int[][]image,int sr,int sc,int sourceColor,int targetColor){\n int m = image.length, n = image[0].length;\n\n if(sr>=0 && sr=0 && sc List[List[int]]:\n queue = deque()\n rows = len(image)\n cols = len(image[0])\n \n targetColor = image[sr][sc]\n \n if color == targetColor:\n\t\t # in this case, we don't need to do anything\n return image\n\n rDirs = [1, 0, -1, 0]\n cDirs = [0, 1, 0, -1]\n \n queue.append((sr, sc))\n \n while len(queue) > 0:\n r, c = queue.pop()\n \n image[r][c] = color\n for rd, cd in zip(rDirs, cDirs):\n newRow = r + rd\n newCol = c + cd\n \n isValidCoordinate = newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols\n \n if isValidCoordinate and image[newRow][newCol] == targetColor:\n queue.append((newRow, newCol))\n \n return image\n \n \n", + "title": "733. Flood Fill", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n gardens, labeled from 1 to n , and an array paths where paths[i] = [x i , y i ] describes a bidirectional path between garden x i to garden y i . In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer , where answer[i] is the type of flower planted in the (i+1) th garden. The flower types are denoted 1 , 2 , 3 , or 4 . It is guaranteed an answer exists. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= paths.length <= 2 * 10^4", + "paths[i].length == 2", + "1 <= x i , y i <= n", + "x i != y i", + "Every garden has at most 3 paths coming into or leaving it." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, paths = [[1,2],[2,3],[3,1]]Output:[1,2,3]Explanation:Gardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].", + "image": null + }, + { + "text": "Example 2: Input:n = 4, paths = [[1,2],[3,4]]Output:[1,2,1,2]", + "image": null + }, + { + "text": "Example 3: Input:n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]Output:[1,2,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] gardenNoAdj(int n, int[][] paths) {\n boolean[][] graph = new boolean[n][n];\n for(int i = 0;i List[int]:\n\t\tg = defaultdict(list)\n\t\tfor u,v in paths:\n\t\t\tg[u-1].append(v-1) \n\t\t\tg[v-1].append(u-1) \n\t\tans = [0]*n\n\t\tfor i in range(n):\n\t\t\tc = [1,2,3,4]\n\t\t\tfor j in g[i]:\n\t\t\t\tif ans[j] in c: c.remove(ans[j])\n\t\t\tans[i] = c.pop()\n\t\treturn ans", + "title": "1042. Flower Planting With No Adjacent", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array groups of length n . You are also given an integer array nums . You are asked if you can choose n disjoint subarrays from the array nums such that the i th subarray is equal to groups[i] ( 0-indexed ), and if i > 0 , the (i-1) th subarray appears before the i th subarray in nums (i.e. the subarrays must be in the same order as groups ). Return true if you can do this task, and false otherwise . Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "groups.length == n", + "1 <= n <= 10^3", + "1 <= groups[i].length, sum(groups[i].length) <= 10^3", + "1 <= nums.length <= 10^3", + "-10^7 <= groups[i][j], nums[k] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]Output:trueExplanation:You can choose the 0thsubarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1stone as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.", + "image": null + }, + { + "text": "Example 2: Input:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]Output:falseExplanation:Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "image": null + }, + { + "text": "Example 3: Input:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]Output:falseExplanation:Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int search(int[] group, int[] nums, int start, int end )\n {\n int i=start, j=0;\n while(i 0 , the (i-1) th subarray appears before the i th subarray in nums (i.e. the subarrays must be in the same order as groups ). Return true if you can do this task, and false otherwise . Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "groups.length == n", + "1 <= n <= 10^3", + "1 <= groups[i].length, sum(groups[i].length) <= 10^3", + "1 <= nums.length <= 10^3", + "-10^7 <= groups[i][j], nums[k] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]Output:trueExplanation:You can choose the 0thsubarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1stone as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.", + "image": null + }, + { + "text": "Example 2: Input:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]Output:falseExplanation:Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].", + "image": null + }, + { + "text": "Example 3: Input:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]Output:falseExplanation:Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n groups = ['-'.join(str(s) for s in group) for group in groups]\n nums = '-'.join(str(s) for s in nums)\n j = k = 0\n while k < len(groups):\n group = groups[k]\n i = nums.find(group, j)\n if i == -1: return False\n if i == 0 or i > 0 and nums[i-1] == '-':\n j = i + len(group)\n k += 1\n else: j += 1\n return True \n", + "title": "1764. Form Array by Concatenating Subarrays of Another Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers cost and an integer target , return the maximum integer you can paint under the following rules : Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\" . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The cost of painting a digit (i + 1) is given by cost[i] ( 0-indexed ).", + "The total cost used must be equal to target .", + "The integer does not have 0 digits." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [4,3,2,5,6,7,2,5,5], target = 9Output:\"7772\"Explanation:The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.Digit cost1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5", + "image": null + }, + { + "text": "Example 2: Input:cost = [7,6,5,5,5,6,8,7,8], target = 12Output:\"85\"Explanation:The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.", + "image": null + }, + { + "text": "Example 3: Input:cost = [2,4,6,2,4,6,4,4,4], target = 5Output:\"0\"Explanation:It is impossible to paint any integer with total cost equal to target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Space Complexity = O(N*M) (N == length of cost array and M == target )\n// Time Complexity = O(N*M)\n\nclass Solution {\n Map map = new HashMap<>();\n String[][] memo;\n public String largestNumber(int[] cost, int target) {\n memo = new String[cost.length+1][target+1];\n \n for( int i = 0;i<=cost.length;i++ ){\n for(int j = 0;j<=target;j++) memo[i][j] = \"0\";\n }\n \n String res = helper(cost,cost.length-1,target);\n \n return res == \"-1\" ? \"0\" : res; \n \n }\n \n public String helper( int[] cost , int index , int target){\n if(target == 0) {\n return \"\";\n }\n \n if(target < 0) return \"-1\";\n \n if(index < 0) return \"-1\";\n \n if( memo[index][target] != \"0\") return memo[index][target];\n \n String str1 = (index+1) + helper(cost,cost.length-1,target-cost[index]) ;\n String str2 = helper(cost,index-1,target);\n \n String res = getBigger(str1,str2);\n \n memo[index][target] = res;\n \n return res;\n }\n \n public String getBigger(String num1 , String num2){\n if( num1.contains(\"-1\") ) return num2;\n if( num2.contains(\"-1\") ) return num1;\n if( num1.length() > num2.length() ) return num1;\n if( num2.length() > num1.length() ) return num2;\n return Double.parseDouble( num1 ) < Double.parseDouble( num2 ) ? num2 : num1;\n }\n}\n", + "title": "1449. Form Largest Integer With Digits That Add up to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers cost and an integer target , return the maximum integer you can paint under the following rules : Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\" . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The cost of painting a digit (i + 1) is given by cost[i] ( 0-indexed ).", + "The total cost used must be equal to target .", + "The integer does not have 0 digits." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [4,3,2,5,6,7,2,5,5], target = 9Output:\"7772\"Explanation:The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.Digit cost1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5", + "image": null + }, + { + "text": "Example 2: Input:cost = [7,6,5,5,5,6,8,7,8], target = 12Output:\"85\"Explanation:The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.", + "image": null + }, + { + "text": "Example 3: Input:cost = [2,4,6,2,4,6,4,4,4], target = 5Output:\"0\"Explanation:It is impossible to paint any integer with total cost equal to target.", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n @lru_cache(None)\n def dfs(t):\n if t == 0: return 0\n res = float('-inf')\n for digit in range(1,10):\n if t - cost[digit-1] >= 0:\n res = max(res, dfs(t - cost[digit-1])*10+digit)\n return res\n res = dfs(target)\n return \"0\" if res == float('-inf') else str(res)", + "title": "1449. Form Largest Integer With Digits That Add up to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the sum of divisors of the integers in that array that have exactly four divisors . If there is no such integer in the array, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [21,4,7]Output:32\nExplanation:21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.", + "image": null + }, + { + "text": "Example 2: Input:nums = [21,21]Output:64", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumFourDivisors(int[] nums) {\n int res = 0;\n for(int val : nums){\n int sum = 0;\n int count = 0;\n for(int i=1;i*i <= val;i++){\n if(val % i == 0){\n sum += i;\n count++;\n if(i != val/i){\n sum += val/i;\n count++;\n }\n }\n }\n if(count == 4){\n res += sum;\n }\n }\n return res;\n }\n}\n", + "title": "1390. Four Divisors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the sum of divisors of the integers in that array that have exactly four divisors . If there is no such integer in the array, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [21,4,7]Output:32Explanation:21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.", + "image": null + }, + { + "text": "Example 2: Input:nums = [21,21]Output:64", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "import math \nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n s=0\n for i in nums:\n r=i+1\n c=2\n for j in range(2, int(math.sqrt(i))+1):\n if i%j==0:\n if (i / j == j) :\n c+=1\n r+=j\n else :\n c+=2\n r+=j+int(i/j)\n print(c, r)\n if c==4:\n s+=r\n return s\n", + "title": "1390. Four Divisors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"Output:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"Output:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"Output:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 16.51%) | Memory: 44.40 MB (Top 27.52%)\n\nclass Solution {\n private int gcd(int x, int y){\n return x!=0?gcd(y%x, x):Math.abs(y);\n }\n\n public String fractionAddition(String exp) {\n Scanner sc = new Scanner(exp).useDelimiter(\"/|(?=[-+])\");\n\n int A=0, B=1;\n while(sc.hasNext()){\n int a = sc.nextInt(), b=sc.nextInt();\n A = A * b + B * a;\n B *= b;\n\n int gcdX = gcd(A, B);\n A/=gcdX;\n B/=gcdX;\n }\n return A+\"/\"+B;\n }\n}\n", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"Output:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"Output:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"Output:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n //Great Common Divisor \n private int gcd(int a,int b) {\n int r=b%a;\n if (r==0) return a;\n return gcd(r,a);\n }\n private int[] add(int[] a,int[] b){\n if(a[0]==0) return b;\n if(b[0]==0) return a;\n int[] ret=new int[]{a[0]*b[1]+b[0]*a[1],a[1]*b[1]};\n if(ret[0]==0){\n ret[1]=1;\n return ret; \n }\n int sign=ret[0]<0?-1:1;\n ret[0]*=sign;\n int g=gcd(Math.min(ret[0],ret[1]),Math.max(ret[0],ret[1]));\n if(g>1) {\n ret[0]/=g;\n ret[1]/=g; \n }\n ret[0]*=sign;\n return ret;\n }\n public String fractionAddition(String expression) {\n return Stream.of(\n expression.replaceAll(\"\\\\-\",\"+-\").split(\"\\\\+\")).filter(s->s.length()>0).map(\n s->s.split(\"/\")).map(\n a->new int[]{Integer.parseInt(a[0]),Integer.parseInt(a[1])}).reduce((a,b)->add(a,b)).map(p->p[0]+\"/\"+p[1]).get();\n \n }\n}\n", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction . If your final result is an integer, change it to the format of a fraction that has a denominator 1 . So in this case, 2 should be converted to 2/1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The input string only contains '0' to '9' , '/' , '+' and '-' . So does the output.", + "Each fraction (input and output) has the format ±numerator/denominator . If the first input fraction or the output is positive, then '+' will be omitted.", + "The input only contains valid irreducible fractions , where the numerator and denominator of each fraction will always be in the range [1, 10] . If the denominator is 1 , it means this fraction is actually an integer in a fraction format defined above.", + "The number of given fractions will be in the range [1, 10] .", + "The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"-1/2+1/2\"Output:\"0/1\"", + "image": null + }, + { + "text": "Example 2: Input:expression = \"-1/2+1/2+1/3\"Output:\"1/3\"", + "image": null + }, + { + "text": "Example 3: Input:expression = \"1/3-1/2\"Output:\"-1/6\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 35 ms (Top 88.02%) | Memory: 14.1 MB (Top 5.79%)\n\"\"\"\napproach:\nfirst replace - with +- in the string so that implementation gets\na little easy\n\"\"\"\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n expression = expression.replace('-', '+-')\n parts = [item for item in expression.split('+') if item != '']\n numes, denoms, denom_set, lcm = [], [], set(), 1\n def get_lcm(a, b):\n if a == 1:\n return b\n if b == 1:\n return a\n if a < b:\n if b % a == 0:\n return a * get_lcm(1, b/a)\n else:\n return a * get_lcm(1, b)\n else:\n if a % b == 0:\n return b * get_lcm(a/b, 1)\n else:\n return b * get_lcm(a, 1)\n\n for part in parts:\n num, den = part.split('/')\n numes.append(int(num))\n denoms.append(int(den))\n lcm = get_lcm(lcm, int(den))\n\n result = 0\n for num, den in zip(numes, denoms):\n result +=num * int(lcm/den)\n\n def get_gcd(a, b):\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n elif a < b:\n return get_gcd(a, b-a)\n else:\n return get_gcd(a-b, b)\n\n gcd = get_gcd(abs(result), lcm)\n return str(int(result/gcd)) + '/' + str(int(lcm/gcd))", + "title": "592. Fraction Addition and Subtraction", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format . If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them . It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= numerator, denominator <= 2 31 - 1", + "denominator != 0" + ], + "examples": [ + { + "text": "Example 1: Input:numerator = 1, denominator = 2Output:\"0.5\"", + "image": null + }, + { + "text": "Example 2: Input:numerator = 2, denominator = 1Output:\"2\"", + "image": null + }, + { + "text": "Example 3: Input:numerator = 4, denominator = 333Output:\"0.(012)\"", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public String fractionToDecimal(int numerator, int denominator) {\n if(numerator == 0){\n return \"0\";\n }\n \n StringBuilder sb = new StringBuilder(\"\");\n if(numerator<0 && denominator>0 || numerator>0 && denominator<0){\n sb.append(\"-\");\n }\n \n long divisor = Math.abs((long)numerator);\n long dividend = Math.abs((long)denominator);\n long remainder = divisor % dividend;\n sb.append(divisor / dividend);\n \n if(remainder == 0){\n return sb.toString();\n }\n sb.append(\".\");\n HashMap map = new HashMap();\n while(remainder!=0){\n if(map.containsKey(remainder)){\n sb.insert(map.get(remainder), \"(\");\n sb.append(\")\");\n break;\n }\n map.put(remainder, sb.length());\n remainder*= 10;\n sb.append(remainder/dividend);\n remainder%= dividend;\n }\n return sb.toString();\n }\n}\n\n", + "title": "166. Fraction to Recurring Decimal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format . If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them . It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= numerator, denominator <= 2 31 - 1", + "denominator != 0" + ], + "examples": [ + { + "text": "Example 1: Input:numerator = 1, denominator = 2Output:\"0.5\"", + "image": null + }, + { + "text": "Example 2: Input:numerator = 2, denominator = 1Output:\"2\"", + "image": null + }, + { + "text": "Example 3: Input:numerator = 4, denominator = 333Output:\"0.(012)\"", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n sign = \"\" if numerator*denominator >= 0 else \"-\"\n numerator, denominator = abs(numerator), abs(denominator)\n a = numerator//denominator\n numerator %= denominator\n if not numerator: return sign+str(a)\n fractions = []\n index = defaultdict(int)\n while 10*numerator not in index:\n numerator *= 10\n index[numerator] = len(fractions)\n fractions.append(str(numerator//denominator))\n numerator %= denominator\n i = index[10*numerator]\n return sign+str(a)+\".\"+\"\".join(fractions[:i])+\"(\"+\"\".join(fractions[i:])+\")\" if numerator else sign+str(a)+\".\"+\"\".join(fractions[:i])", + "title": "166. Fraction to Recurring Decimal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\" and use the dial to spell a specific keyword to open the door. Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword . Initially, the first character of the ring is aligned at the \"12:00\" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the \"12:00\" direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i] : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= ring.length, key.length <= 100", + "ring and key consist of only lower case English letters.", + "It is guaranteed that key could always be spelled by rotating ring ." + ], + "examples": [ + { + "text": "Example 1: Input:ring = \"godding\", key = \"gd\"Output:4Explanation:For the first key character 'g', since it is already in place, we just need 1 step to spell this character. \nFor the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\nAlso, we need 1 more step for spelling.\nSo the final output is 4.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/ring.jpg" + }, + { + "text": "Example 2: Input:ring = \"godding\", key = \"godding\"Output:13", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 46.01%) | Memory: 46.5 MB (Top 66.67%)\nclass Solution {\n public int findRotateSteps(String ring, String key) {\n Map> locMap = new HashMap<>();\n for (int i = 0; i < ring.length(); i++){\n locMap.computeIfAbsent(ring.charAt(i), o->new TreeSet<>()).add(i);\n }\n return dfs(0, 0, locMap, key, new int[key.length()][ring.length()]);\n }\n\n private int dfs(int cur, int where, Map> locMap, String key, int[][] memo){\n if (cur==key.length()){ // the end\n return 0;\n }\n if (memo[cur][where]>0){ // have computed [cur, end) already.\n return memo[cur][where];\n }\n TreeSet idx = locMap.get(key.charAt(cur));\n if (idx.contains(where)){ // greedily take this if it is already matched\n return memo[cur][where]=dfs(cur+1, where, locMap, key, memo)+1;\n }\n Integer hi = idx.higher(where); // otherwise, we can take the higher key\n Integer lo = idx.lower(where); // or, the lower key\n if (hi == null){ // if no higher key, it becomes the lowest key.\n hi = idx.first();\n }\n if (lo == null){ // if no lower key, it becomes the highest key.\n lo = idx.last();\n }\n int hcost = dfs(cur+1, hi, locMap, key, memo) + (hi>where? hi-where:memo[0].length-where+hi);\n int lcost = dfs(cur+1, lo, locMap, key, memo) + (lo int:\n locs = {}\n for i, ch in enumerate(ring): locs.setdefault(ch, []).append(i)\n \n @cache \n def fn(i, j): \n \"\"\"Return turns to finish key[j:] startin from ith position on ring.\"\"\"\n if j == len(key): return 0 \n loc = locs[key[j]]\n k = bisect_left(loc, i) % len(loc)\n ans = min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1)\n k = (k-1) % len(loc)\n ans = min(ans, min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1))\n return ans \n \n return fn(0, 0) + len(key)\n", + "title": "514. Freedom Trail", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k . In one operation, you can choose an index of nums and increment the element at that index by 1 . Return the maximum possible frequency of an element after performing at most k operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4], k = 5Output:3Explanation:Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,8,13], k = 5Output:2Explanation:There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,9,6], k = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 33.83%) | Memory: 95.9 MB (Top 65.95%)\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n //Step-1: Sorting->\n Arrays.sort(nums);\n //Step-2: Two-Pointers->\n int L=0,R=0;\n long totalSum=0;\n int res=1;\n //Iterating over the array:\n while(R=\" \"windowSize*nums[R]\"\n //then only the window is possible else decrease the \"totalSum\"\n //till the value \"totalSum+k\" is \">=\" \"windowSize*nums[R]\"\n while(! ((totalSum+k) >= ((R-L+1)*nums[R])) )\n {\n totalSum-=nums[L];\n L++;\n }\n res=Math.max(res,(R-L+1));\n R++;\n }\n return res;\n }\n}", + "title": "1838. Frequency of the Most Frequent Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k . In one operation, you can choose an index of nums and increment the element at that index by 1 . Return the maximum possible frequency of an element after performing at most k operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4], k = 5Output:3Explanation:Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,8,13], k = 5Output:2Explanation:There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,9,6], k = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n sums, i, ans = 0, 0, 0\n for j in range(len(nums)):\n sums += nums[j]\n while nums[j]*(j-i+1) > sums+k:\n sums -= nums[i]\n i = i+1\n ans = max(ans, j-i+1)\n return ans", + "title": "1838. Frequency of the Most Frequent Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i th person. A Person x will not send a friend request to a person y ( x != y ) if any of the following conditions is true: Otherwise, x will send a friend request to y . Note that if x sends a request to y , y will not necessarily send a request to x . Also, a person will not send a friend request to themself. Return the total number of friend requests made . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "age[y] <= 0.5 * age[x] + 7", + "age[y] > age[x]", + "age[y] > 100 && age[x] < 100" + ], + "examples": [ + { + "text": "Example 1: Input:ages = [16,16]Output:2Explanation:2 people friend request each other.", + "image": null + }, + { + "text": "Example 2: Input:ages = [16,17,18]Output:2Explanation:Friend requests are made 17 -> 16, 18 -> 17.", + "image": null + }, + { + "text": "Example 3: Input:ages = [20,30,100,110,120]Output:3Explanation:Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static int upperBound(int arr[], int target) {\n int l = 0, h = arr.length - 1;\n for (; l <= h;) {\n int mid = (l + h) >> 1;\n if (arr[mid] <= target)\n l = mid + 1;\n else\n h = mid - 1;\n }\n return l;\n }\n public int numFriendRequests(int[] ages) {\n long ans = 0;\n Arrays.sort(ages);\n\t\t// traversing order doesn't matter as we are doing binary-search in whole array\n\t\t// you can traverse from left side also\n for(int i = ages.length - 1;i >= 0;--i){\n int k = upperBound(ages,ages[i] / 2 + 7);\n int t = upperBound(ages,ages[i]);\n ans += Math.max(0,t - k - 1);\n }\n return (int)ans;\n }\n}\n", + "title": "825. Friends Of Appropriate Ages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i th person. A Person x will not send a friend request to a person y ( x != y ) if any of the following conditions is true: Otherwise, x will send a friend request to y . Note that if x sends a request to y , y will not necessarily send a request to x . Also, a person will not send a friend request to themself. Return the total number of friend requests made . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "age[y] <= 0.5 * age[x] + 7", + "age[y] > age[x]", + "age[y] > 100 && age[x] < 100" + ], + "examples": [ + { + "text": "Example 1: Input:ages = [16,16]Output:2Explanation:2 people friend request each other.", + "image": null + }, + { + "text": "Example 2: Input:ages = [16,17,18]Output:2Explanation:Friend requests are made 17 -> 16, 18 -> 17.", + "image": null + }, + { + "text": "Example 3: Input:ages = [20,30,100,110,120]Output:3Explanation:Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 936 ms (Top 28.73%) | Memory: 14.9 MB (Top 52.36%)\nclass Solution:\n \"\"\"\n approach:\n we can try solving this problem by finding the valid age group for each age\n sort the array in descending order\n iterate from right to left\n for current age, find the valid agegroup to which the current age person will send a request\n we can use binary search for that\n if current age is x, then valid age group to send a request is:\n x*0.5 + 7 < age(y) <= x\n we can find the left limit using binary search\n \"\"\"\n def binary_search(self, arr, low, high, value):\n if low > high:\n return high\n mid = (low + high) // 2\n if arr[mid] > value:\n return self.binary_search(arr, low, mid-1, value)\n else:\n return self.binary_search(arr, mid+1, high, value)\n\n def numFriendRequests(self, ages: List[int]) -> int:\n ages = sorted(ages)\n total_count = 0\n for i in range(len(ages)-1, -1, -1):\n if i+1 < len(ages) and ages[i] == ages[i+1]:\n total_count+= prev_count\n continue\n\n prev_count = 0\n lower_limit = 0.5 * ages[i] + 7\n index = self.binary_search(ages, 0, i-1, lower_limit)\n prev_count = i - (index+1)\n total_count+=prev_count\n return total_count", + "title": "825. Friends Of Appropriate Ages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones ' positions (in units) in sorted ascending order , determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1 , k , or k + 1 units. The frog can only jump in the forward direction. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= stones.length <= 2000", + "0 <= stones[i] <= 2 31 - 1", + "stones[0] == 0", + "stones is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [0,1,3,5,6,8,12,17]Output:trueExplanation:The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [0,1,2,3,4,8,9,11]Output:falseExplanation:There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static boolean flag = false; // If flag is true no more operations in recursion, directly return statement\n public boolean canCross(int[] stones) {\n int i = 0; // starting stone\n int k = 1; // starting jump\n flag = false; \n return canBeCrossed(stones, k, i);\n }\n \n public boolean canBeCrossed(int[] stones, int k, int i){\n if(!flag){ // If flag is false \n if(stones[i] + k == stones[stones.length - 1]){ // If frog do 'k' jump from current stone lands on last stones, no more recusive calls and return true\n flag = true;\n return true;\n }\n\t\t// If frog do 'k' jump from current stone crosses last stone or not able to reach next stone\n\t\t//return false\n if((stones[i] + k > stones[stones.length - 1]) || (stones[i]+k stones[temp]) temp++;\n\t\t//If loop exited 2 condition possible\n\t\t//jump from current stone is reached next possible stone\n\t\t//or not\n\t\t\n\t\t//If next possible stone reached\n\t\t//then do all possible jumps from this stone \n\t\t//the current stone is 'temp'\n\t\t//possible jumps are 'k-1', k, 'k+1'\n if(stones[i]+k == stones[temp]) return (canBeCrossed(stones, k+1, temp) || canBeCrossed(stones, k, temp) || canBeCrossed(stones,k-1,temp));\n\t\t\n\t\t//If next possible stone not reached means jump from the current stone can't reach any stone\n\t\t//hence return false\n else return false;\n }\n else return true;\n }\n}", + "title": "403. Frog Jump", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones ' positions (in units) in sorted ascending order , determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1 , k , or k + 1 units. The frog can only jump in the forward direction. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= stones.length <= 2000", + "0 <= stones[i] <= 2 31 - 1", + "stones[0] == 0", + "stones is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [0,1,3,5,6,8,12,17]Output:trueExplanation:The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [0,1,2,3,4,8,9,11]Output:falseExplanation:There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 231 ms (Top 72.60%) | Memory: 19.2 MB (Top 61.18%)\nclass Solution:\n def possible(self, i, n, stones, pos, allowedJumps):\n if i == n - 1:\n return True\n key = tuple([i] + allowedJumps)\n if key in self.cache:\n return self.cache[key]\n for jump in allowedJumps:\n if jump > 0 and stones[i] + jump in pos:\n if self.possible(pos[stones[i] + jump], n, stones, pos, [jump - 1, jump, jump + 1]):\n self.cache[key] = True\n return True\n self.cache[key] = False\n return False\n\n def canCross(self, stones: List[int]) -> bool:\n n = len(stones)\n pos = {}\n for i, stone in enumerate(stones):\n pos[stone] = i\n self.cache = {}\n return self.possible(0, n, stones, pos, [1])", + "title": "403. Frog Jump", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n . A frog starts jumping from vertex 1 . In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Return the probability that after t seconds the frog is on the vertex target . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= a i , b i <= n", + "1 <= t <= 50", + "1 <= target <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4Output:0.16666666666666666Explanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 aftersecond 1and then jumping with 1/2 probability to vertex 4 aftersecond 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/frog1.jpg" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7Output:0.3333333333333333Explanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 aftersecond 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double frogPosition(int n, int[][] edges, int t, int target) {\n \n List> graph=new ArrayList<>();\n for(int i=0;i<=n;i++) graph.add(new ArrayList<>());\n \n for(int i=0;i> graph,int ver,int t,int tar,boolean[] vis){\n \n int count=0;\n for(Integer child:graph.get(ver)){\n if(!vis[child]) count++;\n }\n \n \n vis[ver]=true;\n if(t<0) return 0;\n \n if(ver==tar){\n if(count==0 || t==0) return 1.0;\n }\n \n if(graph.get(ver).size()==0) return 0;\n \n double ans=0.0;\n \n \n for(Integer child:graph.get(ver)){\n\n // System.out.println(child);\n if(!vis[child])\n ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis);\n }\n // System.out.println(ans);\n vis[ver]=false;\n return ans;\n }\n}\n\n\n", + "title": "1377. Frog Position After T Seconds", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an undirected tree consisting of n vertices numbered from 1 to n . A frog starts jumping from vertex 1 . In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Return the probability that after t seconds the frog is on the vertex target . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "edges.length == n - 1", + "edges[i].length == 2", + "1 <= a i , b i <= n", + "1 <= t <= 50", + "1 <= target <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4Output:0.16666666666666666Explanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 aftersecond 1and then jumping with 1/2 probability to vertex 4 aftersecond 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.", + "image": "https://assets.leetcode.com/uploads/2021/12/21/frog1.jpg" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7Output:0.3333333333333333Explanation:The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 aftersecond 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 25.36%) | Memory: 17.90 MB (Top 5.07%)\n\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n nei = collections.defaultdict(set)\n for a, b in edges:\n nei[a].add(b)\n nei[b].add(a)\n \n visited, res = set(), 0.\n def dfs(leaf_id, p, time):\n nonlocal res\n if time >= t:\n if leaf_id == target: res = p\n return\n visited.add(leaf_id)\n neighbors = nei[leaf_id] - visited\n for n in neighbors or [leaf_id]:\n dfs(n, p / (len(neighbors) or 1), time + 1)\n dfs(1, 1, 0)\n return res\n", + "title": "1377. Frog Position After T Seconds", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i th tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: Given the integer array fruits , return the maximum number of fruits you can pick . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.", + "Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.", + "Once you reach a tree with fruit that cannot fit in your baskets, you must stop." + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [1,2,1]Output:3Explanation:We can pick from all 3 trees.", + "image": null + }, + { + "text": "Example 2: Input:fruits = [0,1,2,2]Output:3Explanation:We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].", + "image": null + }, + { + "text": "Example 3: Input:fruits = [1,2,3,2,2]Output:4Explanation:We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 61 ms (Top 63.76%) | Memory: 95 MB (Top 59.07%)\nclass Solution {\n public int totalFruit(int[] fruits) {\n if (fruits == null || fruits.length == 0) {\n return 0;\n }\n int start = 0, end = 0, res = 0;\n HashMap map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit\n\n while (end < fruits.length) {\n if (map.size() <= 2) {\n map.put(fruits[end], end);\n end++;\n }\n\n if (map.size() > 2) {\n int leftMost = fruits.length;\n for (int num : map.values()) {\n leftMost = Math.min(leftMost, num);\n }\n map.remove(fruits[leftMost]);\n start = leftMost + 1;\n }\n\n res = Math.max(res, end - start);\n }\n return res;\n }\n}", + "title": "904. Fruit Into Baskets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i th tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: Given the integer array fruits , return the maximum number of fruits you can pick . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.", + "Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.", + "Once you reach a tree with fruit that cannot fit in your baskets, you must stop." + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [1,2,1]Output:3Explanation:We can pick from all 3 trees.", + "image": null + }, + { + "text": "Example 2: Input:fruits = [0,1,2,2]Output:3Explanation:We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].", + "image": null + }, + { + "text": "Example 3: Input:fruits = [1,2,3,2,2]Output:4Explanation:We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n ans=0\n fruitdict=defaultdict()\n stack=[]\n i,j=0,0\n\n while jfruitdict[stack[1]] :\n i = fruitdict[stack[1]]+1\n del fruitdict[stack[1]]\n stack.pop()\n else:\n i = fruitdict[stack[0]]+1\n del fruitdict[stack[0]] \n stack.pop(0) \n \n ans=max(ans,j-i)\n return ans", + "title": "904. Fruit Into Baskets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array heights representing the heights of buildings, some bricks , and some ladders . You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 ( 0-indexed ), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.", + "If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1Output:4Explanation:Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.", + "image": "https://assets.leetcode.com/uploads/2020/10/27/q4.gif" + }, + { + "text": "Example 2: Input:heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2Output:7", + "image": null + }, + { + "text": "Example 3: Input:heights = [14,3,19,3], bricks = 17, ladders = 0Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def furthestBuilding(self, H: List[int], B: int, L: int) -> int:\n heap = []\n for i in range(len(H) - 1):\n diff = H[i+1] - H[i]\n if diff > 0:\n if L > 0:\n heappush(heap, diff)\n L -= 1\n elif heap and diff > heap[0]:\n heappush(heap, diff)\n B -= heappop(heap)\n else: B -= diff\n if B < 0: return i\n return len(H) - 1\n", + "title": "1642. Furthest Building You Can Reach", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board , return the next state . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]Output:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]Output:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.1 MB (Top 73.63%)\nclass Solution {\n public void gameOfLife(int[][] board) {\n int m = board.length, n = board[0].length;\n int[][] next = new int[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n next[i][j] = nextState(board, i, j, m, n);\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n board[i][j] = next[i][j];\n }\n }\n }\n\n public int nextState(int[][] board, int i, int j, int m, int n) {\n int ones = 0;\n for (int x = -1; x <=1; x++) {\n for (int y = -1; y <= 1; y++) {\n if (x == 0 && y == 0) {\n continue;\n }\n int a = i + x, b = j + y;\n if (a >= 0 && a < m) {\n if (b >= 0 && b < n) {\n ones += board[a][b];\n }\n }\n }\n }\n if (board[i][j] == 0) {\n return ones == 3 ? 1 : 0;\n } else {\n if (ones == 2 || ones == 3) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n}", + "title": "289. Game of Life", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board , return the next state . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]Output:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]Output:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "#pattern\nactual update ref \n0 0 0\n1 1 1\n0 1 -1\n1 0 -2\n\nclass Solution:\n\tdef gameOfLife(self, board: List[List[int]]) -> None:\n\t\tr = len(board)\n\t\tc = len(board[0])\n\t\tans = [[0]*c for _ in range(r)]\n\t\tneighs = [[1,0],[-1,0],[0,1],[0,-1],[-1,-1],[-1,1],[1,1],[1,-1]]\n\n\t\tfor i in range(r):\n\t\t\tfor j in range(c):\n\t\t\t\tlivecnt,deadcnt = 0,0\n\t\t\t\tfor di,dj in neighs:\n\t\t\t\t\tif 0<=(i+di) < r and 0<=(j+dj) int:\n deltas = [x-y for x, y in zip(gas, cost)]\n n = len(deltas)\n deltas = deltas + deltas\n cursum, curi = 0, 0\n maxsum, maxi = 0, 0\n for i, delta in enumerate(deltas):\n cursum = max(0, cursum + delta)\n if cursum == 0:\n curi = i+1\n if cursum > maxsum:\n maxi = curi\n maxsum = cursum\n cursum = 0\n for i in range(n):\n cursum += deltas[(maxi+i)%n]\n if cursum < 0: return -1\n return maxi", + "title": "134. Gas Station", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums , and you can perform the following operation any number of times on nums : Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,21,3]Output:trueExplanation:We can sort [7,21,3] by performing the following operations:\n- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]\n- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,6,2]Output:falseExplanation:It is impossible to sort the array because 5 cannot be swapped with any other element.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,5,9,3,15]Output:true\nWe can sort [10,5,9,3,15] by performing the following operations:\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]\n- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 94.62%) | Memory: 71.9 MB (Top 80.64%)\nclass Solution {\n private static final int[] primes;\n // precompute prime numbers\n static {\n primes = new int[5133];\n final int max = 100000 / 2;\n boolean[] notprime = new boolean[max];\n for (int index = 0, i = 2; i < max; i++) {\n if (notprime[i]) continue;\n primes[index++] = i;\n for (int j = (max - 1) / i; j >= 2; j--) notprime[i * j] = true;\n }\n }\n\n public boolean gcdSort(int[] nums) {\n final var sorted = nums.clone();\n Arrays.sort(sorted);\n final int len = nums.length, max = sorted[len - 1];\n final int[] map = new int[max + 1]; // grouping tree child->parent\n for (int i = 0; i < len; i++) map[nums[i]] = nums[i];\n\n for (final var p : primes) {\n if (p > max / 2) break;\n int group = p;\n map[p] = p;\n for (int num = p + p; num <= max; num += p) {\n var existing = map[num];\n if (existing == 0) continue; // value doens't exist in array\n if (existing == num) map[num] = group; // 1st hit, set group, otherwise, group merging\n else if ((existing = root(map, existing)) < group) {\n map[group] = existing;\n group = existing;\n } else map[existing] = group;\n }\n }\n\n for (int i = 0; i < len; i++) if (root(map, nums[i]) != root(map, (sorted[i]))) return false;\n return true;\n }\n\n private static int root(int[] map, int num) {\n int group;\n while (num != (group = map[num])) num = group;\n return group;\n }\n}", + "title": "1998. GCD Sort of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a string with n characters such that each character in such string occurs an odd number of times . The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:\"pppz\"Explanation:\"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:\"xy\"Explanation:\"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".", + "image": null + }, + { + "text": "Example 3: Input:n = 7Output:\"holasss\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 6.68%) | Memory: 45.2 MB (Top 20.03%)\nclass Solution {\n public String generateTheString(int n) {\n String s = \"\";\n String string =\"a\";\n for (int i = 0; i < n-1; i++)\n s += string;\n if(n%2==0)\n return s+\"b\";\n return s+\"a\";\n }\n}", + "title": "1374. Generate a String With Characters That Have Odd Counts", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a string with n characters such that each character in such string occurs an odd number of times . The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:\"pppz\"Explanation:\"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:\"xy\"Explanation:\"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".", + "image": null + }, + { + "text": "Example 3: Input:n = 7Output:\"holasss\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generateTheString(self, n: int) -> str:\n alpha = \"abcdefghijklmnopqrstuvwxyz\"\n res=\"\"\n while n>0:\n curr, alpha = alpha[0], alpha[1:]\n if n%2:\n res += curr*n\n n-=n\n else: \n res += curr*(n-1)\n n-=n-1\n return res", + "title": "1374. Generate a String With Characters That Have Odd Counts", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n List s = new ArrayList<>();\n public void get(int n, int x, String p)\n {\n if(n==0 && x==0)\n {\n s.add(p);\n return;\n }\n if(n==0)\n {\n get(n,x-1,p+\")\");\n }\n else if(x==0)\n {\n get(n-1,x+1,p+\"(\");\n }\n else\n {\n get(n,x-1,p+\")\");\n get(n-1,x+1,p+\"(\");\n }\n }\n public List generateParenthesis(int n) \n {\n s.clear();\n get(n,0,\"\");\n return s;\n }\n}\n", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generateParenthesis(self, n: int) -> list[str]:\n\n # Initialize the result\n res = []\n\n # Recursively go through all possible combinations\n def add(open, close, partialRes):\n\n nonlocal res\n\n # If we have added opening and closing parentheses n times, we reaches a solution\n if open == close == n:\n res.append(\"\".join(partialRes))\n return\n\n # Add a closing parenthesis to the partial result if we have at least 1 opening parenthesis\n if close < open:\n add(open, close + 1, partialRes + [\")\"])\n\n # Add an opening parenthesis to the partial result if we haven't added n parenthesis yet\n if open < n:\n add(open + 1, close, partialRes + [\"(\"])\n\n add(0, 0, [])\n\n return res\n", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center) .", + "randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]Output[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]ExplanationSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n double radius;\n double x_center;\n double y_center;\n Random r=new Random();\n public Solution(double radius, double x_center, double y_center) {\n this.radius=radius;\n this.x_center=x_center;\n this.y_center=y_center;\n }\n \n public double[] randPoint() {\n double angle=r.nextDouble(Math.PI*2);\n\t\t//For probability is inversely proportional to radius, we use sqrt of random number.\n double rad=Math.sqrt(r.nextDouble())*radius;\n double[] ret=new double[2];\n ret[0]=rad*Math.cos(angle)+x_center;\n ret[1]=rad*Math.sin(angle)+y_center;\n return ret;\n }\n}\n\n", + "title": "478. Generate Random Point in a Circle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center) .", + "randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]Output[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]ExplanationSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def __init__(self, radius: float, x_center: float, y_center: float):\n self.rad = radius\n self.xc = x_center\n self.yc = y_center\n\n def randPoint(self) -> List[float]:\n while True:\n xg=self.xc+random.uniform(-1, 1)*self.rad*2\n yg=self.yc+random.uniform(-1, 1)*self.rad*2\n if (xg-self.xc)**2 + (yg-self.yc)**2 <= self.rad**2:\n return [xg, yg]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(radius, x_center, y_center)\n# param_1 = obj.randPoint()\n", + "title": "478. Generate Random Point in a Circle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix grid ​​​. A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid ​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum : Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return the biggest three distinct rhombus sums in the grid in descending order . If there are less than three distinct values, return all of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]Output:[228,216,211]Explanation:The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211", + "image": "https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex1.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6],[7,8,9]]Output:[20,9,8]Explanation:The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)", + "image": "https://assets.leetcode.com/uploads/2021/04/23/pc73-q4-ex2.png" + }, + { + "text": "Example 3: Input:grid = [[7,7,7]]Output:[7]Explanation:All three possible rhombus sums are the same, so return [7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 89.47%) | Memory: 52.7 MB (Top 72.81%)\nclass Solution {\n public int[] getBiggestThree(int[][] grid) {\n int end = Math.min(grid.length, grid[0].length);\n int maxThree[] = {0,0,0};\n for(int length=0; length= length){\n addToMaxThree(maxThree, getSum(grid, start, start1, length));\n }\n }\n }\n }\n\n /*\n get sum of edges of rhombus abcd\n a\n / \\\n d b\n \\ /\n c\n\n */\n int getSum(int[][] grid, int i, int j, int length){\n if(length == 0){\n return grid[i][j];\n }\n\n int sum = 0;\n // edge ab\n for(int it=0; it<=length; it++){\n sum = sum + grid[i+it][j+it];\n }\n\n // edge ad\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+it][j-it];\n }\n\n // edge dc\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+length+it][j-length+it];\n }\n\n // edge bc\n for(int it=1; it List[int]:\n \n def calc(l,r,u,d):\n sc=0\n c1=c2=(l+r)//2\n expand=True\n for row in range(u,d+1):\n if c1==c2:\n sc+=grid[row][c1]\n else:\n sc+=grid[row][c1]+grid[row][c2]\n \n if c1==l:\n expand=False\n \n if expand:\n c1-=1\n c2+=1\n else:\n c1+=1\n c2-=1\n return sc\n \n \n m=len(grid)\n n=len(grid[0])\n heap=[]\n for i in range(m):\n for j in range(n):\n l=r=j\n d=i\n while l>=0 and r<=n-1 and d<=m-1:\n sc=calc(l,r,i,d)\n l-=1\n r+=1\n d+=2\n if len(heap)<3:\n if sc not in heap:\n heapq.heappush(heap,sc)\n else:\n if sc not in heap and sc>heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap,sc)\n \n heap.sort(reverse=True)\n return heap\n", + "title": "1878. Get Biggest Three Rhombus Sums in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and t of the same length and an integer maxCost . You want to change s to t . Changing the i th character of s to i th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost . If there is no substring from s that can be changed to its corresponding substring from t , return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "t.length == s.length", + "0 <= maxCost <= 10^6", + "s and t consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"bcdf\", maxCost = 3Output:3Explanation:\"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", t = \"cdef\", maxCost = 3Output:1Explanation:Each character in s costs 2 to change to character in t, so the maximum length is 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcd\", t = \"acde\", maxCost = 0Output:1Explanation:You cannot make any change, so the maximum length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 46.31%) | Memory: 43.1 MB (Top 83.52%)\nclass Solution {\n public int equalSubstring(String s, String t, int maxCost) {\n int ans =0;\n int tempcost =0;\n int l =0 ;\n int r= 0 ;\n for(;r!=s.length();r++){\n tempcost += Math.abs(s.charAt(r)-t.charAt(r));\n while(tempcost>maxCost){\n tempcost -= Math.abs(s.charAt(l)-t.charAt(l));\n l++;\n }\n ans =Math.max(ans,r+1-l);\n }\n return ans;\n }\n}", + "title": "1208. Get Equal Substrings Within Budget", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and t of the same length and an integer maxCost . You want to change s to t . Changing the i th character of s to i th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost . If there is no substring from s that can be changed to its corresponding substring from t , return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "t.length == s.length", + "0 <= maxCost <= 10^6", + "s and t consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", t = \"bcdf\", maxCost = 3Output:3Explanation:\"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", t = \"cdef\", maxCost = 3Output:1Explanation:Each character in s costs 2 to change to character in t, so the maximum length is 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcd\", t = \"acde\", maxCost = 0Output:1Explanation:You cannot make any change, so the maximum length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def equalSubstring(self, s, t, maxCost):\n \"\"\"\n :type s: str\n :type t: str\n :type maxCost: int\n :rtype: int\n \"\"\"\n \n \n \n \n best = 0\n \n windowCost = 0\n l = 0\n for r in range(len(s)):\n \n windowCost += abs(ord(s[r]) - ord(t[r]))\n \n while windowCost > maxCost:\n \n windowCost -= abs(ord(s[l]) - ord(t[l]))\n l+=1\n \n best = max(best,r-l+1)\n \n return best\n \n \n \n\n", + "title": "1208. Get Equal Substrings Within Budget", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums ​​​. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums[0] = 0", + "nums[1] = 1", + "nums[2 * i] = nums[i] when 2 <= 2 * i <= n", + "nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:3Explanation:According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:1Explanation:According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3Output:2Explanation:According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 71.82%) | Memory: 41.2 MB (Top 34.16%)\nclass Solution {\n public int getMaximumGenerated(int n) {\n if(n==0 || n==1) return n;\n\n int nums[]=new int [n+1];\n\n nums[0]=0;\n nums[1]=1;\n int max=Integer.MIN_VALUE;\n\n for(int i=2;i<=n;i++){\n if(i%2==0){\n nums[i]=nums[i/2];\n }\n else{\n nums[i]=nums[i/2]+nums[i/2 + 1];\n }\n max=Math.max(max,nums[i]);\n }\n return max;\n }\n}", + "title": "1646. Get Maximum in Generated Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n . A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums ​​​. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums[0] = 0", + "nums[1] = 1", + "nums[2 * i] = nums[i] when 2 <= 2 * i <= n", + "nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7Output:3Explanation:According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:1Explanation:According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3Output:2Explanation:According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 84.4%) | Memory: 17.50 MB (Top 12.64%)\n\nfrom queue import deque\n\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n \n def arrgen(n):\n yield 0\n q = deque([1])\n while True:\n yield q[0]\n q.append(q[0])\n q.append(q[0]+q[1])\n q.popleft()\n \n g = arrgen(n)\n return max(next(g) for _ in range(n+1))", + "title": "1646. Get Maximum in Generated Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose array nums1 or nums2 to traverse (from index-0).", + "Traverse the current array from left to right.", + "If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path)." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]Output:30Explanation:Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green[2,4,6,8,10].", + "image": "https://assets.leetcode.com/uploads/2020/07/16/sample_1_1893.png" + }, + { + "text": "Example 2: Input:nums1 = [1,3,5,7,9], nums2 = [3,5,100]Output:109Explanation:Maximum sum is obtained with the path[1,3,5,100].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]Output:40Explanation:There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long currSum = 0, sum1 = 0, sum2 = 0;\n int i = 0;\n int j = 0;\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] == nums2[j]) {\n currSum += Math.max(sum1, sum2) + nums2[j];\n sum1 = 0;\n sum2 = 0;\n i++;\n j++;\n }\n else if(nums1[i] < nums2[j]){\n sum1 += nums1[i++];\n } else {\n sum2 += nums2[j++];\n }\n }\n \n while(i < nums1.length){\n sum1 += nums1[i++];\n }\n while(j < nums2.length){\n sum2 += nums2[j++];\n }\n return (int)((currSum + Math.max(sum1, sum2)) % 1000000007);\n }\n}\n", + "title": "1537. Get the Maximum Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two sorted arrays of distinct integers nums1 and nums2. A valid path is defined as follows: The score is defined as the sum of uniques values in a valid path. Return the maximum score you can obtain of all possible valid paths . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose array nums1 or nums2 to traverse (from index-0).", + "Traverse the current array from left to right.", + "If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path)." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]Output:30Explanation:Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green[2,4,6,8,10].", + "image": "https://assets.leetcode.com/uploads/2020/07/16/sample_1_1893.png" + }, + { + "text": "Example 2: Input:nums1 = [1,3,5,7,9], nums2 = [3,5,100]Output:109Explanation:Maximum sum is obtained with the path[1,3,5,100].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]Output:40Explanation:There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n acc1 = list(accumulate(nums1, initial = 0))\n acc2 = list(accumulate(nums2, initial = 0))\n i, j = len(nums1)-1, len(nums2)-1\n previ, prevj = len(nums1), len(nums2)\n prev_maxscore = 0\n while i >= 0 and j >= 0:\n while i >= 0 and j >= 0 and nums1[i] < nums2[j]:\n j -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n while i >= 0 and j >= 0 and nums2[j] < nums1[i]:\n i -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n prev_maxscore += max(acc1[previ]-acc1[0], acc2[prevj]-acc2[0])\n return prev_maxscore % (10**9 + 7)\n", + "title": "1537. Get the Maximum Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people, each person has a unique id between 0 and n-1 . Given the arrays watchedVideos and friends , where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i . Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png", + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png" + ], + "constraints": [ + "n == watchedVideos.length == friends.length", + "2 <= n <= 100", + "1 <= watchedVideos[i].length <= 100", + "1 <= watchedVideos[i][j].length <= 8", + "0 <= friends[i].length < n", + "0 <= friends[i][j] < n", + "0 <= id < n", + "1 <= level < n", + "if friends[i] contains j , then friends[j] contains i" + ], + "examples": [ + { + "text": "Example 1: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1Output:[\"B\",\"C\"]Explanation:You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2", + "image": null + }, + { + "text": "Example 2: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2Output:[\"D\"]Explanation:You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List watchedVideosByFriends(List> watchedVideos, int[][] friends, int id, int level) {\n int n = friends.length;\n boolean[] visited = new boolean[n];\n List> graph = new ArrayList<>();\n for(int i=0;i());\n for(int i=0;i queue = new ArrayDeque<>();\n queue.offer(id);\n visited[id] = true;\n Map answer = new HashMap<>();\n while(!queue.isEmpty() && level>0){\n int size = queue.size();\n for(int i=0;i sortedQueue = new PriorityQueue<>((a,b)->{\n if(a[1].equals(b[1])) return a[0].compareTo(b[0]);\n return Integer.parseInt(a[1])-Integer.parseInt(b[1]);\n });\n for(String key: answer.keySet()){\n sortedQueue.offer(new String[]{key,Integer.toString(answer.get(key))});\n }\n List finalAnswer = new ArrayList<>();\n while(!sortedQueue.isEmpty()) finalAnswer.add(sortedQueue.remove()[0]);\n return finalAnswer;\n }\n}\n", + "title": "1311. Get Watched Videos by Your Friends", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people, each person has a unique id between 0 and n-1 . Given the arrays watchedVideos and friends , where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i . Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_1.png", + "https://assets.leetcode.com/uploads/2020/01/02/leetcode_friends_2.png" + ], + "constraints": [ + "n == watchedVideos.length == friends.length", + "2 <= n <= 100", + "1 <= watchedVideos[i].length <= 100", + "1 <= watchedVideos[i][j].length <= 8", + "0 <= friends[i].length < n", + "0 <= friends[i][j] < n", + "0 <= id < n", + "1 <= level < n", + "if friends[i] contains j , then friends[j] contains i" + ], + "examples": [ + { + "text": "Example 1: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1Output:[\"B\",\"C\"]Explanation:You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2", + "image": null + }, + { + "text": "Example 2: Input:watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2Output:[\"D\"]Explanation:You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n\t\tq=[id]\n\t\tvis=set([id])\n\t\tl=0\n\t\twhile l nums[j]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,2]Output:trueExplanation:There is 1 global inversion and 1 local inversion.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,0]Output:falseExplanation:There are 2 global inversions and 1 local inversion.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 34.63%) | Memory: 77.1 MB (Top 70.64%)\nclass Solution {\n public boolean isIdealPermutation(int[] nums) {\n\n for(int i=0;i1) return false;\n }\n\n return true;\n }\n}", + "title": "775. Global and Local Inversions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1] . The number of global inversions is the number of the different pairs (i, j) where: The number of local inversions is the number of indices i where: Return true if the number of global inversions is equal to the number of local inversions . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < j < n", + "nums[i] > nums[j]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,2]Output:trueExplanation:There is 1 global inversion and 1 local inversion.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,0]Output:falseExplanation:There are 2 global inversions and 1 local inversion.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 620 ms (Top 99.42%) | Memory: 31.10 MB (Top 5.81%)\n\nclass Solution:\n def isIdealPermutation(self, A: List[int]) -> bool:\n for i in range(len(A)):\n if i - A[i] > 1 or i - A[i] < -1: return False\n return True\n", + "title": "775. Global and Local Inversions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You own a Goal Parser that can interpret a string command . The command consists of an alphabet of \"G\" , \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\" , \"()\" as the string \"o\" , and \"(al)\" as the string \"al\" . The interpreted strings are then concatenated in the original order. Given the string command , return the Goal Parser 's interpretation of command . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= command.length <= 100", + "command consists of \"G\" , \"()\" , and/or \"(al)\" in some order." + ], + "examples": [ + { + "text": "Example 1: Input:command = \"G()(al)\"Output:\"Goal\"Explanation:The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".", + "image": null + }, + { + "text": "Example 2: Input:command = \"G()()()()(al)\"Output:\"Gooooal\"", + "image": null + }, + { + "text": "Example 3: Input:command = \"(al)G(al)()()G\"Output:\"alGalooG\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.40 MB (Top 29.82%)\n\nclass Solution {\n public String interpret(String c) {\n StringBuilder st = new StringBuilder();\n for(int i =0; i G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".", + "image": null + }, + { + "text": "Example 2: Input:command = \"G()()()()(al)\"Output:\"Gooooal\"", + "image": null + }, + { + "text": "Example 3: Input:command = \"(al)G(al)()()G\"Output:\"alGalooG\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def interpret(self, command: str) -> str:\n return command.replace('()','o').replace('(al)','al')\n", + "title": "1678. Goal Parser Interpretation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: Return the final sentence representing the conversion from sentence to Goat Latin . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If a word begins with a vowel ( 'a' , 'e' , 'i' , 'o' , or 'u' ), append \"ma\" to the end of the word. For example, the word \"apple\" becomes \"applema\" .", + "For example, the word \"apple\" becomes \"applema\" .", + "If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\" . For example, the word \"goat\" becomes \"oatgma\" .", + "For example, the word \"goat\" becomes \"oatgma\" .", + "Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1 . For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.", + "For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"I speak Goat Latin\"Output:\"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"The quick brown fox jumped over the lazy dog\"Output:\"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 83.72%) | Memory: 42.5 MB (Top 62.02%)\nclass Solution {\n public String toGoatLatin(String sentence) {\n StringBuffer sb = new StringBuffer();\n StringBuffer temp = new StringBuffer(\"a\"); // temporary stringbuffer\n\n for(String str : sentence.split(\" \")) {\n if(beginsWithConsonant(str)) {\n sb.append(str.substring(1)); // removing the first letter\n sb.append(str.charAt(0)); // appending it to the end\n } else {\n sb.append(str);\n }\n\n sb.append(\"ma\"); // appending \"ma\" to the end of the word (common operation)\n sb.append(temp); // adding one letter 'a' to the end of each word\n\n // the first word gets \"a\" added to the end,\n // the second word gets \"aa\" added to the end,\n // and so on.\n temp.append(\"a\"); // increasing the a's for every word\n sb.append(\" \"); // to put space between words\n }\n\n return sb.toString().trim(); // using trim() to remove the one extra space from the end of string.\n }\n\n public boolean beginsWithConsonant(String str) {\n return \"aeiou\".indexOf(str.toLowerCase().charAt(0)) == -1;\n }\n}", + "title": "824. Goat Latin", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: Return the final sentence representing the conversion from sentence to Goat Latin . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If a word begins with a vowel ( 'a' , 'e' , 'i' , 'o' , or 'u' ), append \"ma\" to the end of the word. For example, the word \"apple\" becomes \"applema\" .", + "For example, the word \"apple\" becomes \"applema\" .", + "If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\" . For example, the word \"goat\" becomes \"oatgma\" .", + "For example, the word \"goat\" becomes \"oatgma\" .", + "Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1 . For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.", + "For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"I speak Goat Latin\"Output:\"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"The quick brown fox jumped over the lazy dog\"Output:\"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n wordList, result, index = sentence.split(' '), \"\", 1\n for word in wordList:\n if index > 1:\n result += \" \"\n firstLetter = word[0]\n if firstLetter in 'aeiouAEIOU':\n result += word + \"ma\"\n else:\n result += word[1:] + firstLetter + \"ma\"\n for i in range(index):\n result += 'a'\n index += 1\n return result\n", + "title": "824. Goat Latin", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We have n cities labeled from 1 to n . Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold . More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: Given the two integers, n and threshold , and an array of queries , you must determine for each queries[i] = [a i , b i ] if cities a i and b i are connected directly or indirectly. (i.e. there is some path between them). Return an array answer , where answer.length == queries.length and answer[i] is true if for the i th query, there is a path between a i and b i , or answer[i] is false if there is no path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x % z == 0 ,", + "y % z == 0 , and", + "z > threshold ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]Output:[false,false,true]Explanation:The divisors for each number:\n1: 1\n2: 1, 2\n3: 1,34: 1, 2,45: 1,56: 1, 2,3,6Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6", + "image": "https://assets.leetcode.com/uploads/2020/10/09/ex1.jpg" + }, + { + "text": "Example 2: Input:n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]Output:[true,true,true,true,true]Explanation:The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.", + "image": "https://assets.leetcode.com/uploads/2020/10/10/tmp.jpg" + }, + { + "text": "Example 3: Input:n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]Output:[false,false,false,false,false]Explanation:Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].", + "image": "https://assets.leetcode.com/uploads/2020/10/17/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 59.15%) | Memory: 91.1 MB (Top 32.39%)\n//Solving the problem using Disjoint Set Union Find approach\n\nclass Solution {\n\n public int find(int x){\n\n if(parent[x] == x)\n return x;\n\n //Optimising by placing the same parent for all the elements to reduce reduntant calls\n return parent[x] = find(parent[x]);\n }\n\n public void union(int a, int b){\n\n a = find(a);\n b = find(b);\n\n //Using Rank optimisation\n if(rank[a] > rank[b]){\n parent[b] = a;\n rank[a] += rank[b];\n }\n\n else{\n parent[a] = b;\n rank[b] += rank[a];\n }\n\n //parent[b] = a;\n }\n\n int parent[];\n int rank[];\n public List areConnected(int n, int threshold, int[][] queries) {\n\n List ans = new ArrayList();\n parent = new int[n+1];\n rank = new int[n+1];\n\n for(int i=1; i<=n; i++){\n //Each element is its own parent\n parent[i] = i;\n //At beginning each element has rank 1\n rank[i] = 1;\n }\n\n // Finding the possible divisors with pairs above given threshold\n for(int th = threshold+1; th<=n; th++){\n\n int mul = 1;\n while(mul * th <= n){\n //If possible pair then making a union of those paired element\n union(th, mul*th);\n mul++;\n }\n }\n\n //Generating ans for all possible queries\n for(int[] query : queries){\n ans.add((find(query[0]) == find(query[1])));\n }\n return ans;\n }\n}", + "title": "1627. Graph Connectivity With Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We have n cities labeled from 1 to n . Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold . More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: Given the two integers, n and threshold , and an array of queries , you must determine for each queries[i] = [a i , b i ] if cities a i and b i are connected directly or indirectly. (i.e. there is some path between them). Return an array answer , where answer.length == queries.length and answer[i] is true if for the i th query, there is a path between a i and b i , or answer[i] is false if there is no path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x % z == 0 ,", + "y % z == 0 , and", + "z > threshold ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]Output:[false,false,true]Explanation:The divisors for each number:\n1: 1\n2: 1, 2\n3: 1,34: 1, 2,45: 1,56: 1, 2,3,6Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6", + "image": "https://assets.leetcode.com/uploads/2020/10/09/ex1.jpg" + }, + { + "text": "Example 2: Input:n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]Output:[true,true,true,true,true]Explanation:The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.", + "image": "https://assets.leetcode.com/uploads/2020/10/10/tmp.jpg" + }, + { + "text": "Example 3: Input:n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]Output:[false,false,false,false,false]Explanation:Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].", + "image": "https://assets.leetcode.com/uploads/2020/10/17/ex3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 881 ms (Top 97.89%) | Memory: 49.3 MB (Top 35.92%)\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n parent = list(range(n+1))\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n parent[find(i)] = find(j)\n if not threshold: return [True]*len(queries)\n for i in range(1, n+1):\n for j in range(2*i, n+1, i):\n if i > threshold: union(i,j)\n return [find(i) == find(j) for i,j in queries]", + "title": "1627. Graph Connectivity With Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An n-bit gray code sequence is a sequence of 2 n integers where: Given an integer n , return any valid n-bit gray code sequence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every integer is in the inclusive range [0, 2 n - 1] ,", + "The first integer is 0 ,", + "An integer appears no more than once in the sequence,", + "The binary representation of every pair of adjacent integers differs by exactly one bit , and", + "The binary representation of the first and last integers differs by exactly one bit ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[0,1,3,2]Explanation:The binary representation of [0,1,3,2] is [00,01,11,10].\n- 00and 01differ by one bit\n-01 and11 differ by one bit\n- 11and 10differ by one bit\n-10 and00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n-00 and10 differ by one bit\n- 10and 11differ by one bit\n-11 and01 differ by one bit\n- 01and 00differ by one bit", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:[0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List grayCode(int n) {\n ArrayList list=new ArrayList();\n for(int i=0;i<(1<>1));\n }\n return list;\n }\n}\n", + "title": "89. Gray Code", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An n-bit gray code sequence is a sequence of 2 n integers where: Given an integer n , return any valid n-bit gray code sequence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every integer is in the inclusive range [0, 2 n - 1] ,", + "The first integer is 0 ,", + "An integer appears no more than once in the sequence,", + "The binary representation of every pair of adjacent integers differs by exactly one bit , and", + "The binary representation of the first and last integers differs by exactly one bit ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[0,1,3,2]Explanation:The binary representation of [0,1,3,2] is [00,01,11,10].\n- 00and 01differ by one bit\n-01 and11 differ by one bit\n- 11and 10differ by one bit\n-10 and00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n-00 and10 differ by one bit\n- 10and 11differ by one bit\n-11 and01 differ by one bit\n- 01and 00differ by one bit", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:[0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "import math\nclass Solution(object):\n def grayCode(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)]\n grayCodes = [0]\n for diff in allowedDiffs:\n grayCodes += [code + diff for code in reversed(grayCodes)]\n return grayCodes\n", + "title": "89. Gray Code", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"Output:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String gcdOfStrings(String str1, String str2) {\n \n int length1 = str1.length();\n int length2 = str2.length();\n String temp;\n \n for(int i=gcd(length1,length2); i>0 && length1 % i == 0 && length2 % i == 0; i--) {\n if(str1.substring(0,i).equals(str2.substring(0,i))) {\n if(doesRepeat(str1.substring(0,i),str1,str2))\n return str1.substring(0,i);\n }\n }\n return \"\";\n \n }\n public int gcd(int a, int b) {\n if(b==0)\n return a;\n return gcd(b,a % b);\n }\n public boolean doesRepeat(String s, String str1, String str2) {\n int sLength = s.length();\n boolean bool1 = true, bool2 = true;\n String temp = str1,temp2;\n \n while(sLength < temp.length()) {\n temp2 = temp.substring(sLength,sLength*2);\n \n if(s.equals(temp2));\n else\n bool1 = false;\n temp = temp.substring(sLength,temp.length());\n }\n temp = str2;\n while(sLength < temp.length()) {\n temp2 = temp.substring(sLength,sLength*2);\n if(s.equals(temp2));\n else\n bool2 = false;\n temp = temp.substring(sLength,temp.length());\n }\n return bool1 && bool2;\n }\n \n}\n", + "title": "1071. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"Output:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 85 ms (Top 15.89%) | Memory: 14 MB (Top 5.19%)\nclass Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n\n if len(str2) > len(str1):\n str1, str2 = str2, str1\n\n curr_str2 = str2\n while True:\n\n rep = len(str1)//len(curr_str2)\n\n if curr_str2*rep == str1:\n return curr_str2\n\n found = False\n for i in range(len(curr_str2)-1, 1, -1):\n try_str2 = curr_str2[:i]\n rep2 = len(str2)//len(try_str2)\n\n if try_str2*rep2 == str2:\n curr_str2 = try_str2\n found = True\n break\n\n if not found:\n break\n return \"\"", + "title": "1071. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string of English letters s , return the greatest English letter which occurs as both a lowercase and uppercase letter in s . The returned letter should be in uppercase . If no such letter exists, return an empty string . An English letter b is greater than another letter a if b appears after a in the English alphabet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase and uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lEeTcOdE\"Output:\"E\"Explanation:The letter 'E' is the only letter to appear in both lower and upper case.", + "image": null + }, + { + "text": "Example 2: Input:s = \"arRAzFif\"Output:\"R\"Explanation:The letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"AbCdEfGhIjK\"Output:\"\"Explanation:There is no letter that appears in both lower and upper case.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 53.1%) | Memory: 41.50 MB (Top 23.1%)\n\nclass Solution\n{\n public String greatestLetter(String s)\n {\n Set set = new HashSet<>();\n for(char ch : s.toCharArray())\n set.add(ch);\n \n for(char ch = 'Z'; ch >= 'A'; ch--)\n if(set.contains(ch) && set.contains((char)('a'+(ch-'A'))))\n return \"\"+ch;\n return \"\";\n }\n}", + "title": "2309. Greatest English Letter in Upper and Lower Case", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string of English letters s , return the greatest English letter which occurs as both a lowercase and uppercase letter in s . The returned letter should be in uppercase . If no such letter exists, return an empty string . An English letter b is greater than another letter a if b appears after a in the English alphabet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase and uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lEeTcOdE\"Output:\"E\"Explanation:The letter 'E' is the only letter to appear in both lower and upper case.", + "image": null + }, + { + "text": "Example 2: Input:s = \"arRAzFif\"Output:\"R\"Explanation:The letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"AbCdEfGhIjK\"Output:\"\"Explanation:There is no letter that appears in both lower and upper case.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 34 ms (Top 92.91%) | Memory: 13.8 MB (Top 66.80%)\n\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n cnt = Counter(s)\n return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), \"\")", + "title": "2309. Greatest English Letter in Upper and Lower Case", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the maximum possible sum of elements of the array such that it is divisible by three . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 4 * 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,5,1,8]Output:18Explanation:Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [4]Output:0Explanation:Since 4 is not divisible by 3, do not pick any number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4]Output:12Explanation:Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 68.46%) | Memory: 54.3 MB (Top 56.38%)\n\nclass Solution {\n\n public int maxSumDivThree(int[] nums) {\n int r0 = 0;\n int r1 = 0;\n int r2 = 0;\n for (int i = 0; i < nums.length; i++) {\n int nr0 = r0;\n int nr1 = r1;\n int nr2 = r2;\n int a = r0 + nums[i];\n int b = r1 + nums[i];\n int c = r2 + nums[i];\n if (a % 3 == 0) {\n nr0 = Math.max(nr0, a);\n } else if (a % 3 == 1) {\n nr1 = Math.max(nr1, a);\n } else if (a % 3 == 2) {\n nr2 = Math.max(nr2, a);\n }\n\n if (b % 3 == 0) {\n nr0 = Math.max(nr0, b);\n } else if (b % 3 == 1) {\n nr1 = Math.max(nr1, b);\n } else if (b % 3 == 2) {\n nr2 = Math.max(nr2, b);\n }\n\n if (c % 3 == 0) {\n nr0 = Math.max(nr0, c);\n } else if (c % 3 == 1) {\n nr1 = Math.max(nr1, c);\n } else if (c % 3 == 2) {\n nr2 = Math.max(nr2, c);\n }\n r0=nr0;\n r1=nr1;\n r2=nr2;\n }\n\n return r0;\n }\n}", + "title": "1262. Greatest Sum Divisible by Three", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the maximum possible sum of elements of the array such that it is divisible by three . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 4 * 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,5,1,8]Output:18Explanation:Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [4]Output:0Explanation:Since 4 is not divisible by 3, do not pick any number.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4]Output:12Explanation:Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 190 ms (Top 92.53%) | Memory: 22.10 MB (Top 78.57%)\n\nfrom math import inf\n\n\nclass Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n res = 0\n r1_min1 = inf\n r1_min2 = inf\n r2_min1 = inf\n r2_min2 = inf\n\n for v in nums:\n res += v\n if v % 3 == 1:\n if v < r1_min1:\n r1_min2 = r1_min1\n r1_min1 = v\n elif v < r1_min2:\n r1_min2 = v\n elif v % 3 == 2:\n if v < r2_min1:\n r2_min2 = r2_min1\n r2_min1 = v\n elif v < r2_min2:\n r2_min2 = v\n\n if res % 3 == 1:\n res -= min(r1_min1, r2_min1 + r2_min2)\n elif res % 3 == 2:\n res -= min(r2_min1, r1_min1 + r1_min2)\n\n return res\n", + "title": "1262. Greatest Sum Divisible by Three", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 2D array grid of size 2 x n , where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1) . Each robot may only move to the right ( (r, c) to (r, c + 1) ) or down ( (r, c) to (r + 1, c) ). At the start of the game, the first robot moves from (0, 0) to (1, n-1) , collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0 . Then, the second robot moves from (0, 0) to (1, n-1) , collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally , return the number of points collected by the second robot. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "grid.length == 2", + "n == grid[r].length", + "1 <= n <= 5 * 10^4", + "1 <= grid[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,5,4],[1,5,1]]Output:4Explanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a1.png" + }, + { + "text": "Example 2: Input:grid = [[3,3,1],[8,5,2]]Output:4Explanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a2.png" + }, + { + "text": "Example 3: Input:grid = [[1,3,1,15],[1,3,3,1]]Output:7Explanation:The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.", + "image": "https://assets.leetcode.com/uploads/2021/09/08/a3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 40.95%) | Memory: 94.7 MB (Top 51.18%)\n\nclass Solution {\n public long gridGame(int[][] grid) {\n int n = grid[0].length;\n long preRow1[] = new long[n];\n long preRow2[] = new long[n];\n\n preRow1[0] = grid[0][0];\n preRow2[0] = grid[1][0];\n\n for(int i = 1;i int:\n top, bottom, res = sum(g[0]), 0, math.inf\n for g0, g1 in zip(g[0], g[1]):\n top -= g0\n res = min(res, max(top, bottom))\n bottom += g1\n return res", + "title": "2017. Grid Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off . You are given a 2D array of lamp positions lamps , where lamps[i] = [row i , col i ] indicates that the lamp at grid[row i ][col i ] is turned on . Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal . You are also given another 2D array queries , where queries[j] = [row j , col j ] . For the j th query, determine whether grid[row j ][col j ] is illuminated or not. After answering the j th query, turn off the lamp at grid[row j ][col j ] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[row j ][col j ] . Return an array of integers ans , where ans[j] should be 1 if the cell in the j th query was illuminated, or 0 if the lamp was not. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "0 <= lamps.length <= 20000", + "0 <= queries.length <= 20000", + "lamps[i].length == 2", + "0 <= row i , col i < n", + "queries[j].length == 2", + "0 <= row j , col j < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]Output:[1,0]Explanation:We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0thquery asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.The 1stquery asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.", + "image": "https://assets.leetcode.com/uploads/2020/08/19/illu_1.jpg" + }, + { + "text": "Example 2: Input:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]Output:[1,1]", + "image": null + }, + { + "text": "Example 3: Input:n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]Output:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {\n //we take 5 hashmap\n //1st hashmap for row\n HashMap row = new HashMap<>();\n //2nd hashmap for column\n HashMap col = new HashMap<>();\n //3rd hashmap for lower diagonal\n HashMap d1 = new HashMap<>();\n //4th diagonal for upper diagonal\n HashMap d2 = new HashMap<>();\n //5th diagonal for cell no meaning lamp is present at this spot\n HashMap cellno = new HashMap<>();\n \n for(int i = 0;i List[int]:\n rows = collections.Counter()\n cols = collections.Counter()\n diags1 = collections.Counter()\n diags2 = collections.Counter()\n lamps = {tuple(lamp) for lamp in lamps}\n \n for i, j in lamps:\n rows[i] += 1\n cols[j] += 1\n diags1[i + j] += 1\n diags2[i - j] += 1\n \n ans = []\n directions = ((-1, -1), (-1, 0), (-1, 1),\n (0, -1), (0, 0), (0, 1),\n (1, -1), (1, 0), (1, 1))\n \n for i, j in queries:\n if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:\n ans.append(1)\n else:\n ans.append(0)\n \n for di, dj in directions:\n newI, newJ = i + di, j + dj\n if (newI, newJ) not in lamps:\n continue\n lamps.remove((newI, newJ))\n rows[newI] -= 1\n cols[newJ] -= 1\n diags1[newI + newJ] -= 1\n diags2[newI - newJ] -= 1\n \n return ans", + "title": "1001. Grid Illumination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings strs , group the anagrams together. You can return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 10^4", + "0 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]Output:[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"\"]Output:[[\"\"]]", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"a\"]Output:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 40.82%) | Memory: 46.2 MB (Top 88.53%)\nclass Solution {\n public List> groupAnagrams(String[] strs) {\n HashMap> hm=new HashMap<>();\n for(String s : strs)\n {\n char ch[]=s.toCharArray();\n Arrays.sort(ch);\n StringBuilder sb=new StringBuilder(\"\");\n for(char c: ch)\n {\n sb.append(c);\n }\n String str=sb.toString();\n if(hm.containsKey(str))\n {\n ArrayList temp=hm.get(str);\n temp.add(s);\n hm.put(str,temp);\n }\n else\n {\n ArrayList temp=new ArrayList<>();\n temp.add(s);\n hm.put(str,temp);\n }\n }\n System.out.println(hm);\n List> res=new ArrayList<>();\n for(ArrayList arr : hm.values())\n {\n res.add(arr);\n }\n return res;\n }\n}", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings strs , group the anagrams together. You can return the answer in any order . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 10^4", + "0 <= strs[i].length <= 100", + "strs[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]Output:[[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"\"]Output:[[\"\"]]", + "image": null + }, + { + "text": "Example 3: Input:strs = [\"a\"]Output:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n strs_table = {}\n\n for string in strs:\n sorted_string = ''.join(sorted(string))\n\n if sorted_string not in strs_table:\n strs_table[sorted_string] = []\n\n strs_table[sorted_string].append(string)\n\n return list(strs_table.values())\n", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1 . You are given an integer array groupSizes , where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3 , then person 1 must be in a group of size 3 . Return a list of groups such that each person i is in a group of size groupSizes[i] . Each person should appear in exactly one group , and every person must be in a group. If there are multiple answers, return any of them . It is guaranteed that there will be at least one valid solution for the given input. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "groupSizes.length == n", + "1 <= n <= 500", + "1 <= groupSizes[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:groupSizes = [3,3,3,3,3,1,3]Output:[[5],[0,1,2],[3,4,6]]Explanation:The first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "image": null + }, + { + "text": "Example 2: Input:groupSizes = [2,1,3,3,3,2]Output:[[1],[0,5],[2,3,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 5.31%) | Memory: 53.9 MB (Top 61.36%)\nclass Solution {\n public List> groupThePeople(int[] groupSizes) {\n\n List> temp = new ArrayList>();\n List> result = new ArrayList>();\n for(int i = 0; itemp.get(j).get(1)){\n result.get(j).add(i);\n temp.get(j).set(1,temp.get(j).get(1)+1);\n flag=false;\n break;\n }\n }\n if(flag){\n // comment 1\n // We create a list with index and put it to result\n List res = new ArrayList();\n res.add(i);\n result.add(res);\n // comment 2\n // we create a new list recording max value can stored and currently filled\n List tempRes = new ArrayList();\n tempRes.add(k);\n tempRes.add(1);\n temp.add(tempRes);\n }\n }\n return result;\n }\n}", + "title": "1282. Group the People Given the Group Size They Belong To", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1 . You are given an integer array groupSizes , where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3 , then person 1 must be in a group of size 3 . Return a list of groups such that each person i is in a group of size groupSizes[i] . Each person should appear in exactly one group , and every person must be in a group. If there are multiple answers, return any of them . It is guaranteed that there will be at least one valid solution for the given input. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "groupSizes.length == n", + "1 <= n <= 500", + "1 <= groupSizes[i] <= n" + ], + "examples": [ + { + "text": "Example 1: Input:groupSizes = [3,3,3,3,3,1,3]Output:[[5],[0,1,2],[3,4,6]]Explanation:The first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].", + "image": null + }, + { + "text": "Example 2: Input:groupSizes = [2,1,3,3,3,2]Output:[[1],[0,5],[2,3,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 97.76%) | Memory: 14 MB (Top 88.55%)\nclass Solution(object):\n def groupThePeople(self, groupSizes):\n \"\"\"\n :type groupSizes: List[int]\n :rtype: List[List[int]]\n \"\"\"\n dict_group={}\n for i in range(len(groupSizes)):\n if groupSizes[i] not in dict_group:\n dict_group[groupSizes[i]]=[i]\n else:\n dict_group[groupSizes[i]].append(i)\n return_list=[]\n for i in dict_group:\n num_list=dict_group[i]\n for j in range(0,len(num_list),i):\n return_list.append(num_list[j:j+i])\n return return_list", + "title": "1282. Group the People Given the Group Size They Belong To", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings of the same length words . In one move , you can swap any two even indexed characters or any two odd indexed characters of a string words[i] . Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j] . A group of special-equivalent strings from words is a non-empty subset of words such that: Return the number of groups of special-equivalent strings from words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]Output:3Explanation:One group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 698 ms (Top 5.47%) | Memory: 145 MB (Top 5.47%)\n\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n if(words.length == 0 || words.length == 1) return words.length;\n\n // To store group sizes\n HashMap hashmap = new HashMap<>();\n\n // To mark the strings already part of some groups\n boolean[] isGrouped = new boolean[words.length];\n\n for(int index = 0; index < words.length; index++) {\n if(isGrouped[index]) continue; // Already grouped\n String word = words[index];\n for(int j = index + 1; j < words.length; j++) {\n if(isGrouped[j]) continue; // Already grouped\n String string = words[j];\n\n // The idea is to store count of characters on even and odd indices\n // It is done by incrementing counts of characters in both even and odd maps respectively\n // Then compare the two strings by reducing the same count in both even and odd maps\n // If both the maps are empty at last, the two strings for a group\n HashMap evens = new HashMap<>();\n HashMap odds = new HashMap<>();\n boolean isSpecialEquivalent = true;\n\n for(int i = 0; i < word.length(); i++) {\n if(i % 2 == 0) {\n evens.put(word.charAt(i), evens.getOrDefault(word.charAt(i), 0) + 1);\n } else {\n odds.put(word.charAt(i), odds.getOrDefault(word.charAt(i), 0) + 1);\n }\n }\n\n for(int i = 0; i < string.length(); i++) {\n char character = string.charAt(i);\n if(i % 2 == 0) {\n if(!evens.containsKey(character)) {\n isSpecialEquivalent = false;\n break;\n }\n\n evens.put(character, evens.get(character) - 1);\n if(evens.get(character) == 0) evens.remove(character);\n } else {\n if(!odds.containsKey(character)) {\n isSpecialEquivalent = false;\n break;\n }\n\n odds.put(character, odds.get(character) - 1);\n if(odds.get(character) == 0) odds.remove(character);\n }\n }\n\n if(isSpecialEquivalent) {\n hashmap.put(word, hashmap.getOrDefault(word, 0) + 1);\n isGrouped[j] = true;\n }\n }\n\n // If no group is formed, the word alone forms a group of size 1\n if(!hashmap.containsKey(word)) hashmap.put(word, 1);\n }\n\n return hashmap.size();\n }\n}", + "title": "893. Groups of Special-Equivalent Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings of the same length words . In one move , you can swap any two even indexed characters or any two odd indexed characters of a string words[i] . Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j] . A group of special-equivalent strings from words is a non-empty subset of words such that: Return the number of groups of special-equivalent strings from words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]Output:3Explanation:One group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSpecialEquivGroups(self, words) -> int:\n return len(set([(''.join(sorted(i[::2])),''.join(sorted(i[1::2]))) for i in words]))", + "title": "893. Groups of Special-Equivalent Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array of strings words . Each string consists of lowercase English letters only. No letter occurs more than once in any string of words . Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups . A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Adding exactly one letter to the set of the letters of s1 .", + "Deleting exactly one letter from the set of the letters of s1 .", + "Replacing exactly one letter from the set of the letters of s1 with any letter, including itself." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ab\",\"cde\"]Output:[2,3]Explanation:- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n- words[3] is not connected to any string in words.\nThus, words can be divided into 2 groups [\"a\",\"b\",\"ab\"] and [\"cde\"]. The size of the largest group is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\"]Output:[1,3]Explanation:- words[0] is connected to words[1].\n- words[1] is connected to words[0] and words[2].\n- words[2] is connected to words[1].\nSince all strings are connected to each other, they should be grouped together.\nThus, the size of the largest group is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] groupStrings(String[] words) {\n int n = words.length;\n Arrays.sort(words, Comparator.comparingInt(String::length));\n int[] parents = new int[n];\n int[] ranks = new int[n];\n for (int i = 0; i < n; i++) parents[i] = i;\n Arrays.fill(ranks, 1);\n\n int[] masks = new int[n];\n for (int i = 0; i < n; i++) {\n int val = 0;\n for (int j = 0; j < words[i].length(); j++) {\n val += (1 << (words[i].charAt(j) - 'a'));\n }\n masks[i] = val;\n }\n Set seen = new HashSet<>();\n for (int i = 0; i < n; i++) {\n if (seen.contains(masks[i])) continue;\n for (int j = i + 1; j < n; j++) {\n if (words[i].length() + 1 < words[j].length()) break;\n int p1 = find(parents, i), p2 = find(parents, j);\n if (p1 == p2) continue;\n int a = masks[i], b = masks[j];\n if (a == b) merge(parents, ranks, p1, p2);\n int xor = a ^ b;\n int and = a & b;\n int xor1 = a ^ and, xor2 = b ^ and;\n if ((xor & (xor - 1)) == 0 || ((xor1 & (xor1 - 1)) == 0 && (xor2 & (xor2 - 1)) == 0)) {\n merge(parents, ranks, p1, p2);\n }\n }\n seen.add(masks[i]);\n }\n\n Map map = new HashMap<>();\n int max = 1;\n for (int i = 0; i < n; i++) {\n int f = find(parents, i);\n int cnt = map.getOrDefault(f, 0) + 1;\n map.put(f, cnt);\n max = Math.max(max, cnt);\n }\n\n return new int[]{map.size(), max};\n }\n\n private int find(int[] parents, int i) {\n return parents[i] = parents[i] == i ? i: find(parents, parents[i]);\n }\n\n private void merge(int[] parents, int[] ranks, int i, int j) {\n int p1 = find(parents, i), p2 = find(parents, j);\n if (p1 == p2) return;\n if (ranks[p1] > ranks[p2]) {\n parents[p1] = p2;\n parents[i] = p2;\n ranks[p2]++;\n return;\n }\n parents[p2] = p1;\n parents[j] = p1;\n ranks[p1]++;\n }\n}\n", + "title": "2157. Groups of Strings", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array of strings words . Each string consists of lowercase English letters only. No letter occurs more than once in any string of words . Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups . A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Adding exactly one letter to the set of the letters of s1 .", + "Deleting exactly one letter from the set of the letters of s1 .", + "Replacing exactly one letter from the set of the letters of s1 with any letter, including itself." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ab\",\"cde\"]Output:[2,3]Explanation:- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n- words[3] is not connected to any string in words.\nThus, words can be divided into 2 groups [\"a\",\"b\",\"ab\"] and [\"cde\"]. The size of the largest group is 3.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\"]Output:[1,3]Explanation:- words[0] is connected to words[1].\n- words[1] is connected to words[0] and words[2].\n- words[2] is connected to words[1].\nSince all strings are connected to each other, they should be grouped together.\nThus, the size of the largest group is 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class DSU:\n def __init__(self, n):\n self.root = list(range(n))\n def find(self, x):\n if self.root[x] != x:\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n self.root[self.find(x)] = self.find(y)\n\nclass Solution:\n def groupStrings(self, A: List[str]) -> List[int]: \n c = collections.defaultdict(int)\n for a in A: \n\t\t\tc[\"\".join(sorted(a))] += 1\n \n A = list(set([\"\".join(sorted(a)) for a in A]))\n n = len(A)\n \n idx = collections.defaultdict(int) # (binary representation -> index)\n\t\tdsu = DSU(n) # dsu \n\n def add(base):\n for i in range(26):\n if not base & 1 << i:\n yield base ^ 1 << i\n def dele(base):\n for i in range(26):\n if base & 1 << i:\n if base - (1 << i) != 0:\n yield base - (1 << i) \n def rep(base):\n pre, new = [], []\n for i in range(26):\n if base & 1 << i: pre.append(i)\n else: new.append(i)\n for p in pre:\n for n in new:\n yield base - (1 << p) + (1 << n) \n \n for i, a in enumerate(A):\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord('a')\n idx[base] = i\n\n for base in idx.keys():\n for new in add(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in dele(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in rep(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n \n group = collections.defaultdict(int)\n for a in A:\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord('a')\n cnum = c[a]\n group[dsu.find(idx[base])] += cnum\n \n return [len(group), max(group.values())]\n \n", + "title": "2157. Groups of Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3Output:16Explanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n int start = -1;\n int count = 0;\n \n int max = 0;\n int curr = 0;\n \n for (int i = 0; i < customers.length; i++) {\n if (grumpy[i] == 0) {\n count += customers[i];\n } else {\n curr += customers[i];\n }\n \n if (i-start > minutes) {\n start++;\n if (grumpy[start] == 1) {\n curr -= customers[start];\n }\n }\n max = Math.max(max, curr);\n }\n \n return count + max;\n }\n}\n", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3Output:16Explanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def recursion(self,index,used):\n # base case\n if index == self.n: return 0\n \n #check in dp\n if (index,used) in self.dp: return self.dp[(index,used)]\n #choice1 is using the secret technique\n choice1 = -float('inf')\n \n # we can only use secret technique once and consecutively\n if used == True :\n # use the secret technique\n end = index + self.minutes if index + self.minutes < self.n else self.n\n to_substract = self.prefix_sum[index - 1] if index != 0 else 0\n val = self.prefix_sum[end - 1] - to_substract\n choice1 = self.recursion(end,False) + val\n \n # Do not use the secret tehcnique and play simple \n choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)\n ans = choice1 if choice1 > choice2 else choice2\n \n # Memoization is done here\n self.dp[(index,used)] = ans\n return ans\n \n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n self.n = len(customers)\n self.customers = customers\n self.grumpy = grumpy\n self.minutes = minutes\n self.dp = {}\n self.prefix_sum = [x for x in customers]\n for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]\n return self.recursion(0,True)\n \n", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6Output:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1Output:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/** \n * Forward declaration of guess API.\n * @param num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n public int guessNumber(int n) {\n int left = 1;\n int right = n;\n \n while(left < right){\n int mid = ((right - left) / 2) + left;\n if(guess(mid) == 0)\n return mid;\n else if(guess(mid) < 0)\n right = mid - 1;\n else\n left = mid + 1;\n }\n \n return left;\n }\n}\n", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6Output:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1Output:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def guessNumber(self, n: int) -> int:\n l=1\n h=n\n while l<=h:\n mid=(l+h)//2\n x =guess(mid)\n if(x==0):\n return mid\n elif(x==1):\n l = mid+1\n else:\n h = mid-1\n", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We are playing the Guessing Game. The game will work as follows: Given a particular n , return the minimum amount of money you need to guarantee a win regardless of what number I pick . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:16Explanation:The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n  - If this is my number, your total is $0. Otherwise, you pay $7.\n  - If my number is higher, the range is [8,10]. Guess 9.\n  - If this is my number, your total is $7. Otherwise, you pay $9.\n  - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n  - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n  - If my number is lower, the range is [1,6]. Guess 3.\n  - If this is my number, your total is $7. Otherwise, you pay $3.\n  - If my number is higher, the range is [4,6]. Guess 5.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n  - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, the range is [1,2]. Guess 1.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/graph.png" + }, + { + "text": "Example 2: Input:n = 1Output:0Explanation:There is only one possible number, so you can guess 1 and not have to pay anything.", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:1Explanation:There are two possible numbers, 1 and 2.\n- Guess 1.\n  - If this is my number, your total is $0. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMoneyAmount(int n) {\n int dp[][]=new int[n+1][n+1];\n for(int a[]:dp){\n Arrays.fill(a,-1);\n }\n return solve(1,n,dp);\n }\n static int solve(int start,int end,int[][] dp){\n if(start>=end) return 0;\n if(dp[start][end]!=-1) return dp[start][end];\n int min=Integer.MAX_VALUE;\n for(int i=start;i<=end;i++){\n min=Math.min(min,i+Math.max(solve(start,i-1,dp),solve(i+1,end,dp)));\n }\n dp[start][end]=min;\n return min;\n }\n}", + "title": "375. Guess Number Higher or Lower II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are playing the Guessing Game. The game will work as follows: Given a particular n , return the minimum amount of money you need to guarantee a win regardless of what number I pick . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:16Explanation:The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n  - If this is my number, your total is $0. Otherwise, you pay $7.\n  - If my number is higher, the range is [8,10]. Guess 9.\n  - If this is my number, your total is $7. Otherwise, you pay $9.\n  - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n  - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n  - If my number is lower, the range is [1,6]. Guess 3.\n  - If this is my number, your total is $7. Otherwise, you pay $3.\n  - If my number is higher, the range is [4,6]. Guess 5.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n  - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n  - If my number is lower, the range is [1,2]. Guess 1.\n  - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/graph.png" + }, + { + "text": "Example 2: Input:n = 1Output:0Explanation:There is only one possible number, so you can guess 1 and not have to pay anything.", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:1Explanation:There are two possible numbers, 1 and 2.\n- Guess 1.\n  - If this is my number, your total is $0. Otherwise, you pay $1.\n  - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMoneyAmount(self, n):\n # For an interval [l,r], we choose a num, which if incorrect still\n # allows us to know whether the secret# is in either [l,num-1] or\n # [num+1,r]. So, the worst-case (w-c) cost is\n #\n # num + max(w-c cost in [l,num-1], w-c cost in [num+1,r])\n # \n # We do this by recursion and binary search, starting with [1,n].\n\n @lru_cache(None) # <-- we cache function results to avoid recomputing them\n def dp(l = 1, r = n)-> int:\n if r-l < 1: return 0 # <-- base case for the recursion; one number in [l,r] \n ans = 1000 # <-- the answer for n = 200 is 952\n \n for choice in range((l+r)//2,r):\n ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r)))\n\n return ans\n\n return dp()", + "title": "375. Guess Number Higher or Lower II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master . You may call Master.guess(word) where word is a six-letter-long string, and it must be from words . Master.guess(word) returns: There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word) . For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-1 if word is not from words , or", + "an integer representing the number of exact matches (value and position) of your guess to the secret word." + ], + "examples": [ + { + "text": "Example 1: Input:secret = \"acckzz\", words = [\"acckzz\",\"ccbazz\",\"eiowzz\",\"abcczz\"], allowedGuesses = 10Output:You guessed the secret word correctly.Explanation:master.guess(\"aaaaaa\") returns -1, because \"aaaaaa\" is not in wordlist.\nmaster.guess(\"acckzz\") returns 6, because \"acckzz\" is secret and has all 6 matches.\nmaster.guess(\"ccbazz\") returns 3, because \"ccbazz\" has 3 matches.\nmaster.guess(\"eiowzz\") returns 2, because \"eiowzz\" has 2 matches.\nmaster.guess(\"abcczz\") returns 4, because \"abcczz\" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case.", + "image": null + }, + { + "text": "Example 2: Input:secret = \"hamada\", words = [\"hamada\",\"khaled\"], allowedGuesses = 10Output:You guessed the secret word correctly.Explanation:Since there are two words, you can guess both.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findSecretWord(self, words: List[str], master: 'Master') -> None: \n k = 1 # for tracing the number of loops\n matches = 0\n blacklists = [[] for i in range(6)]\n \n while matches != 6:\n n = len(words)\n r = random.randint(0, n - 1)\n matches = master.guess(words[r])\n key = words[r]\n # print(k, n, r, matches, key)\n \n words.pop(r)\n \n if matches == 0:\n for i in range(6):\n blacklists[i].append(key[i])\n # print(blacklists)\n \n elif matches > 0 and matches < 6:\n candidates = []\n for i in range(n - 1):\n count = 0\n for j in range(6):\n if words[i][j] not in blacklists[j] and words[i][j] == key[j]:\n count += 1\n if count >= matches:\n candidates.append(words[i])\n \n words = candidates.copy()\n # print(words)\n \n k += 1\n", + "title": "843. Guess the Word", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]Output:3Explanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) {\n int n = citations.length;\n Arrays.sort(citations);\n for(int i = 0; i < n; i++) {\n int hlen = (n-1) - i + 1;\n if(citations[i] >= hlen) {\n return hlen;\n }\n }\n return 0;\n }\n}\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]Output:3Explanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n num = sorted(citations)\n h = 0\n j = len(num)-1\n for i in range(len(num)):\n if i+1 <=num[i] and j-i+1>=num[i]:\n h =max(num[i],h)\n elif i+1 <= num[i] and j-i+1 num[i] and j-i+1 >=num[i]:\n h = max(h, num[i])\n \n return h\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper and citations is sorted in an ascending order , return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . You must write an algorithm that runs in logarithmic time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 10^5", + "0 <= citations[i] <= 1000", + "citations is sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:citations = [0,1,3,5,6]Output:3Explanation:[0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,2,100]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) {\n int n=citations.length;\n int res=0;\n for(int i=0;i=n-i)\n {\n return n-i;\n }\n }\n return res;\n }\n}\n", + "title": "275. H-Index II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper and citations is sorted in an ascending order , return compute the researcher's h -index . According to the definition of h-index on Wikipedia : A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each. If there are several possible values for h , the maximum one is taken as the h -index . You must write an algorithm that runs in logarithmic time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 10^5", + "0 <= citations[i] <= 1000", + "citations is sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:citations = [0,1,3,5,6]Output:3Explanation:[0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,2,100]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n n = len(citations)\n for h in range(n, -1, -1):\n if h <= n - bisect.bisect_left(citations, h):\n return h\n", + "title": "275. H-Index II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y , return the Hamming distance between them . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= x, y <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 1, y = 4Output:2Explanation:1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hammingDistance(int x, int y) {\n int ans=x^y;\n int count=0;\n while(ans>0){\n count+=ans&1;\n ans>>=1;\n }\n \n return count;\n }\n}", + "title": "461. Hamming Distance", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y , return the Hamming distance between them . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= x, y <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 1, y = 4Output:2Explanation:1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different.", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n\t\t# First, using XOR Bitwise Operator, we take all distinct set bits.\n z = x ^ y\n\t\t# We inicialize our answer with zero.\n ans = 0\n\t\t# Iterate while our z is not zero.\n while z:\n\t\t\t# Every iteration we add one to our answer.\n ans += 1\n\t\t\t# Using the expression z & (z - 1), we erase the lowest set bit in z.\n z &= z - 1\n return ans\n", + "title": "461. Hamming Distance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3Output:trueExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4Output:falseExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 96 ms (Top 31.30%) | Memory: 61.2 MB (Top 7.04%)\nclass Solution {\n public boolean isNStraightHand(int[] hand, int groupSize) {\n if(hand.length % groupSize != 0)\n return false;\n\n Map map = new HashMap<>();\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for(int card : hand){\n if(map.containsKey(card))\n map.put(card, map.get(card) + 1);\n else {\n map.put(card, 1);\n minHeap.add(card);\n }\n }\n\n while(!minHeap.isEmpty()){\n int min = minHeap.peek();\n for(int i=min; i < min + groupSize; i++){\n if(!map.containsKey(i) || map.get(i) == 0)\n return false;\n map.put(i, map.get(i) - 1);\n if(map.get(i) == 0){\n if(minHeap.peek() != i)\n return false;\n minHeap.poll();\n }\n }\n }\n return true;\n }\n}", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3Output:trueExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4Output:falseExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 304 ms (Top 61.38%) | Memory: 15.7 MB (Top 75.38%)\n\n#####################################################################################################################\n# Problem: Hand of Straights\n# Solution : Hash Table, Min Heap\n# Time Complexity : O(n logn)\n# Space Complexity : O(n)\n#####################################################################################################################\n\nclass Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n if len(hand) % groupSize:\n return False\n\n freq = collections.defaultdict(int)\n\n for num in hand:\n freq[num] += 1\n\n min_heap = list(freq.keys())\n heapq.heapify(min_heap)\n\n while min_heap:\n smallest = min_heap[0]\n for num in range(smallest, smallest + groupSize):\n if num not in freq:\n return False\n freq[num] -= 1\n\n if freq[num] == 0:\n if num != min_heap[0]:\n return False\n heapq.heappop(min_heap)\n return True", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19Output:trueExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 47.06%) | Memory: 41.5 MB (Top 32.65%)\nclass Solution {\n public boolean isHappy(int n) {\n // Create a hash set...\n Set hset = new HashSet();\n // If the number is not in the HashSet, we should add it...\n while (hset.add(n)) {\n // Initialize the total...\n int total = 0;\n // Create a while loop...\n while (n > 0) {\n // Process to get happy number...\n // We use division and modulus operators to repeatedly take digits off the number until none remain...\n // Then squaring each removed digit and adding them together...\n total += (n % 10) * (n % 10);\n n /= 10;\n // Each new converted number must not had occurred before...\n }\n // If total is equal to 1 return true.\n if (total == 1)\n return true;\n // Insert the current number into the set s...\n // Replace the current number with total of the square of its digits.\n else\n n = total;\n }\n // If current number is already in the HashSet, that means we're in a cycle and we should return false..\n return false;\n }\n}", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19Output:trueExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isHappy(self, n):\n hset = set()\n while n != 1:\n if n in hset: return False\n hset.add(n)\n n = sum([int(i) ** 2 for i in str(n)])\n else:\n return True\n", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= houses.length, heaters.length <= 3 * 10^4", + "1 <= houses[i], heaters[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,2,3], heaters = [2]Output:1Explanation:The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 2: Input:houses = [1,2,3,4], heaters = [1,4]Output:1Explanation:The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 3: Input:houses = [1,5], heaters = [2]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 66.0%) | Memory: 46.54 MB (Top 44.7%)\n\nclass Solution {\n public boolean can(int r, int[] houses, int[] heaters) {\n int prevHouseIdx = -1;\n for(int i = 0; i < heaters.length; i++) {\n int from = heaters[i]-r;\n int to = heaters[i]+r;\n for(int j = prevHouseIdx+1; j < houses.length; j++){\n if(houses[j]<=to && houses[j]>=from){\n prevHouseIdx++;\n }\n else break;\n }\n if(prevHouseIdx >= houses.length-1)return true;\n }\n return prevHouseIdx>= houses.length-1;\n }\n public int findRadius(int[] houses, int[] heaters) {\n Arrays.sort(houses);\n Arrays.sort(heaters);\n int lo = 0, hi = 1000000004;\n int mid, ans = hi;\n while(lo <= hi) {\n mid = (lo+hi)/2;\n if(can(mid, houses, heaters)){\n ans = mid;\n hi = mid - 1;\n } else lo = mid + 1;\n }\n return ans;\n }\n}", + "title": "475. Heaters", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= houses.length, heaters.length <= 3 * 10^4", + "1 <= houses[i], heaters[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:houses = [1,2,3], heaters = [2]Output:1Explanation:The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 2: Input:houses = [1,2,3,4], heaters = [1,4]Output:1Explanation:The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.", + "image": null + }, + { + "text": "Example 3: Input:houses = [1,5], heaters = [2]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 766 ms (Top 22.98%) | Memory: 17.7 MB (Top 39.36%)\nclass Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n \"\"\"\n\n \"\"\"\n\n houses.sort()\n heaters.sort()\n\n max_radius = -inf\n\n for house in houses:\n i = bisect_left(heaters, house)\n\n if i == len(heaters):\n max_radius = max(max_radius, house - heaters[-1])\n elif i == 0:\n max_radius = max(max_radius, heaters[i] - house)\n else:\n curr = heaters[i]\n prev = heaters[i-1]\n max_radius = max(max_radius,min(abs(house - curr), abs(house-prev)))\n\n return max_radius\n\n # O(NLOGN)", + "title": "475. Heaters", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i th student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i th student in line ( 0-indexed ). Return the number of indices where heights[i] != expected[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 100", + "1 <= heights[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [1,1,4,2,1,3]Output:3Explanation:heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,4]Output:5Explanation:heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.", + "image": null + }, + { + "text": "Example 3: Input:heights = [1,2,3,4,5]Output:0Explanation:heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.11%) | Memory: 42.1 MB (Top 31.42%)\nclass Solution {\n public int heightChecker(int[] heights) {\n\n int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length);\n\n Arrays.sort(dupheights);\n int count = 0;\n\n for(int i=0 ; i< heights.length ; i++){\n\n if(heights[i] != dupheights[i]){\n count++;\n }\n\n }\n\n return count;\n\n }\n}\n", + "title": "1051. Height Checker", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the i th student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the i th student in line ( 0-indexed ). Return the number of indices where heights[i] != expected[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 100", + "1 <= heights[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [1,1,4,2,1,3]Output:3Explanation:heights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,4]Output:5Explanation:heights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.", + "image": null + }, + { + "text": "Example 3: Input:heights = [1,2,3,4,5]Output:0Explanation:heights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n heightssort = sorted(heights)\n import numpy as np\n diff = list(np.array(heightssort) - np.array(heights))\n return (len(diff) - diff.count(0))\n", + "title": "1051. Height Checker", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:4Explanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]Output:12Explanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 31.47%)\nclass Solution {\n public int rob(int[] nums) {\n int[] t = new int[nums.length] ;\n for(int i=0; i=nums.length){\n return 0;\n }\n if(i==nums.length-1){\n return nums[i];\n }\n if(t[i] != -1){\n return t[i];\n }\n\n int pick = nums[i] + helper(nums,i+2,t);\n int unpicked = helper(nums,i+1,t);\n t[i] = Math.max(pick,unpicked);\n return t[i];\n\n }\n}", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:4Explanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]Output:12Explanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rob(self, nums: List[int]) -> int:\n # [rob1,rob2,n,n+1]\n # 1 | 2 | 3 | 1 \n #index 0 1 2 3\n # so upto last index it depends on previous 2 values :\n # here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2\n # and upto 1st index max rob is 2 ; not choosing any adjacent elements\n # so at 3rd index it depend on prev rob value and 1st index rob value+last value\n # i.e max(2+(val at last index),4)\n rob1=0;rob2=0;\n for i in nums:\n temp=max(rob1+i,rob2);\n rob1=rob2;\n rob2=temp;\n return rob2;\n\n", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2]Output:3Explanation:You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,1]Output:4Explanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.4 MB (Top 99.44%)\nclass Solution {\n public int rob(int[] nums) {\n if(nums.length==1){\n return nums[0];\n }\n int[] t = new int[nums.length];\n for(int i = 0 ; i < t.length;i++){\n t[i] = -1;\n }\n int[] k = new int[nums.length];\n for(int i = 0 ; i < k.length;i++){\n k[i] = -1;\n }\n return Math.max(helper(nums,0,0,t),helper(nums,1,1,k));\n }\n static int helper(int[] nums, int i,int start , int[] t){\n if(start==0 && i==nums.length-2){\n return nums[i];\n }\n if(start==1 && i==nums.length-1){\n return nums[i];\n }\n if(start==0 && i>=nums.length-1){\n return 0;\n }\n if(start==1 && i>=nums.length){\n return 0;\n }\n if(t[i] != -1){\n return t[i];\n }\n int pick = nums[i]+helper(nums,i+2,start,t);\n int notpick = helper(nums,i+1,start,t);\n t[i] = Math.max(pick,notpick);\n return t[i];\n }\n}", + "title": "213. House Robber II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2]Output:3Explanation:You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,1]Output:4Explanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n def helper(nums):\n one, two = 0, 0\n for i in nums:\n temp = max(i + one, two)\n one = two\n two = temp\n return two\n \n return max(helper(nums[:-1]), helper(nums[1:]))\n", + "title": "213. House Robber II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root . Besides the root , each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night . Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,2,3,null,3,null,1]Output:7Explanation:Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,3,null,1]Output:9Explanation:Maximum amount of money the thief can rob = 4 + 5 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.60 MB (Top 27.04%)\n\nclass Solution {\n public int rob(TreeNode root) {\n int ans[] = robHouse(root);\n return Math.max(ans[0],ans[1]);\n }\n \n public int[] robHouse(TreeNode root){\n if(root==null){\n return new int[2];\n }\n \n int left[] = robHouse(root.left);\n int right[] = robHouse(root.right);\n \n int ans[] = new int[2];\n \n ans[0] = Math.max(left[0],left[1])+Math.max(right[0],right[1]);\n ans[1] = root.val+left[0]+right[0];\n \n return ans;\n }\n}\n", + "title": "337. House Robber III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root . Besides the root , each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night . Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,2,3,null,3,null,1]Output:7Explanation:Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,3,null,1]Output:9Explanation:Maximum amount of money the thief can rob = 4 + 5 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def rob(self, root: Optional[TreeNode]) -> int:\n hashMap = {}\n \n def helper(root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n if root in hashMap:\n return hashMap[root]\n ansOption1 = root.val\n if root.left is not None:\n ansOption1 += (helper(root.left.left) + helper(root.left.right))\n if root.right is not None:\n ansOption1 += (helper(root.right.left) + helper(root.right.right))\n ansOption2 = helper(root.left) + helper(root.right)\n ansFinal = max(ansOption1, ansOption2)\n hashMap[root] = ansFinal\n return ansFinal\n \n return helper(root)\n \n", + "title": "337. House Robber III", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array nums , for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i] . Return the answer in an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,1,2,2,3]Output:[4,0,1,1,3]Explanation:For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,8]Output:[2,1,0,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7]Output:[0,0,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 76.25%) | Memory: 44.5 MB (Top 55.91%)\nclass Solution {\n public int[] smallerNumbersThanCurrent(int[] nums) {\n int[] sorted = nums.clone();\n int[] res = new int[nums.length];//result array\n Arrays.sort(sorted);\n for (int i = 0; i < nums.length; ++i) {\n //binary search it, if there is no duplicates the idx will be how many smaller are there\n int idx = binarySearch(sorted, nums[i]);\n //if there are duplicates, then we need to find the first one presented in the array\n if (idx-1>=0 && sorted[idx-1] == nums[i]) {\n while (idx >= 0 && sorted[idx] == nums[i]) {\n --idx;\n }\n ++idx;\n }\n //As I said before, array of indices(indexes) will be the answer\n res[i] = idx;\n }\n return res;\n }\n //Just simple iterative binary search\n public static int binarySearch(int[] arr, int target) {\n int s = 0;\n int e = arr.length-1;\n int m = (s+e)/2;\n\n while (s<=e) {\n if (arr[m] == target) {\n return m;\n } else if (arr[m] > target) {\n e = m-1;\n } else {\n s = m+1;\n }\n m = (s+e)/2;\n }\n return -1;\n }\n}", + "title": "1365. How Many Numbers Are Smaller Than the Current Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the array nums , for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i] . Return the answer in an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "0 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,1,2,2,3]Output:[4,0,1,1,3]Explanation:For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,8]Output:[2,1,0,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7]Output:[0,0,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallerNumbersThanCurrent(self, nums):\n sortify = sorted(nums)\n return (bisect_left(sortify, i) for i in nums)\n", + "title": "1365. How Many Numbers Are Smaller Than the Current Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Quotation Mark: the entity is " and symbol character is \" .", + "Single Quote Mark: the entity is ' and symbol character is ' .", + "Ampersand: the entity is & and symbol character is & .", + "Greater Than Sign: the entity is > and symbol character is > .", + "Less Than Sign: the entity is < and symbol character is < .", + "Slash: the entity is ⁄ and symbol character is / ." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"& is an HTML entity but &ambassador; is not.\"Output:\"& is an HTML entity but &ambassador; is not.\"Explanation:The parser will replace the & entity by &", + "image": null + }, + { + "text": "Example 2: Input:text = \"and I quote: "..."\"Output:\"and I quote: \\\"...\\\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 70.19%) | Memory: 56.3 MB (Top 73.08%)\nclass Solution {\n public String entityParser(String text) {\n return text.replace(\""\",\"\\\"\").replace(\"'\",\"'\").replace(\">\",\">\").replace(\"<\",\"<\").replace(\"⁄\",\"/\").replace(\"&\",\"&\");\n }\n}", + "title": "1410. HTML Entity Parser", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Quotation Mark: the entity is " and symbol character is \" .", + "Single Quote Mark: the entity is ' and symbol character is ' .", + "Ampersand: the entity is & and symbol character is & .", + "Greater Than Sign: the entity is > and symbol character is > .", + "Less Than Sign: the entity is < and symbol character is < .", + "Slash: the entity is ⁄ and symbol character is / ." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"& is an HTML entity but &ambassador; is not.\"Output:\"& is an HTML entity but &ambassador; is not.\"Explanation:The parser will replace the & entity by &", + "image": null + }, + { + "text": "Example 2: Input:text = \"and I quote: "..."\"Output:\"and I quote: \\\"...\\\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def entityParser(self, text: str) -> str:\n d = {\""\" : '\"' , \"'\":\"'\" , \"&\" : \"&\" , \">\" : \">\" , \"<\":\"<\" , \"⁄\" : \"/\"}\n \n \n \n ans = \"\"\n i = 0\n while i < len(text):\n bag = \"\"\n \n #condition if find & and next char is not & also and handdling index out of range for i + 1\n if i+1 < len(text) and text[i] == \"&\" and text[i+1] != \"&\":\n \n #create subtring for speacial char till \";\"\n for j in range(i , len(text)):\n if text[j] == \";\":\n bag += text[j]\n break\n else:\n bag += text[j]\n \n #if that not present in dict we added same as it is\n if bag not in d:\n ans += bag\n else:\n ans += d[bag]\n \n #increment by length of bag \n i += len(bag)\n \n #otherwise increment by 1\n else:\n ans += text[i]\n i += 1\n return ans\n \n", + "title": "1410. HTML Entity Parser", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two images, img1 and img2 , represented as binary, square matrices of size n x n . A binary matrix has only 0 s and 1 s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images. Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased. Return the largest possible overlap . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == img1.length == img1[i].length", + "n == img2.length == img2[i].length", + "1 <= n <= 30", + "img1[i][j] is either 0 or 1 .", + "img2[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]Output:3Explanation:We translate img1 to right by 1 unit and down by 1 unit.The number of positions that have a 1 in both images is 3 (shown in red).", + "image": "https://assets.leetcode.com/uploads/2020/09/09/overlap1.jpg" + }, + { + "text": "Example 2: Input:img1 = [[1]], img2 = [[1]]Output:1", + "image": null + }, + { + "text": "Example 3: Input:img1 = [[0]], img2 = [[0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 593 ms (Top 76.00%) | Memory: 14.7 MB (Top 44.00%)\nclass Solution:\n def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:\n n = len(img1)\n list1, list2 = [], []\n res = 0\n for r in range(n):\n for c in range(n):\n if img1[r][c]:\n list1.append((r, c))\n if img2[r][c]:\n list2.append((r, c))\n\n shiftDict = defaultdict(int)\n for x1, y1 in list1:\n for x2, y2 in list2:\n dx, dy = x2 - x1, y2 - y1\n shiftDict[(dx, dy)] += 1\n\n return max(shiftDict.values()) if shiftDict else 0", + "title": "835. Image Overlap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == img.length", + "n == img[i].length", + "1 <= m, n <= 200", + "0 <= img[i][j] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:img = [[1,1,1],[1,0,1],[1,1,1]]Output:[[0,0,0],[0,0,0],[0,0,0]]Explanation:For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg" + }, + { + "text": "Example 2: Input:img = [[100,200,100],[200,50,200],[100,200,100]]Output:[[137,141,137],[141,138,141],[137,141,137]]Explanation:For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Constant Space Solution. Using input array to store the average\n * This solution can be modified to work if numbers are upto 2^16 - 1 (65,535).\n *\n * Time Complexity: O(8*M*N + M*N) = O(M*N)\n *\n * Space Complexity: O(1)\n *\n * M = Number of rows. N = Number of columns.\n * \n * Note: Similar to \"289. Game of Life\"\n */\nclass Solution {\n private static final int[][] DIRS = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } };\n\n public int[][] imageSmoother(int[][] img) {\n if (img == null) {\n throw new IllegalArgumentException(\"Input image is null\");\n }\n if (img.length == 0 || img[0].length == 0) {\n return img;\n }\n\n int rows = img.length;\n int cols = img[0].length;\n if (rows == 1 && cols == 1) {\n return img;\n }\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n int sum = img[i][j];\n int count = 1;\n for (int[] d : DIRS) {\n int x = i + d[0];\n int y = j + d[1];\n if (x >= 0 && x < rows && y >= 0 && y < cols) {\n sum += img[x][y] & 0xFF;\n count++;\n }\n }\n img[i][j] |= (sum / count) << 8;\n }\n }\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n img[i][j] >>>= 8;\n }\n }\n\n return img;\n }\n}\n", + "title": "661. Image Smoother", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == img.length", + "n == img[i].length", + "1 <= m, n <= 200", + "0 <= img[i][j] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:img = [[1,1,1],[1,0,1],[1,1,1]]Output:[[0,0,0],[0,0,0],[0,0,0]]Explanation:For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg" + }, + { + "text": "Example 2: Input:img = [[100,200,100],[200,50,200],[100,200,100]]Output:[[137,141,137],[141,138,141],[137,141,137]]Explanation:For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138", + "image": "https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1147 ms (Top 25.09%) | Memory: 14.8 MB (Top 29.59%)\nclass Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n m, n = len(img), len(img[0])\n\n def avg(i, j):\n s = squares = 0\n top, bottom = max(0, i - 1), min(m, i + 2)\n left, right = max(0, j - 1), min(n, j + 2)\n\n for x in range(top, bottom):\n for y in range(left, right):\n s += img[x][y]\n squares += 1\n\n return s // squares\n\n return [[avg(i, j) for j in range(n)] for i in range(m)]", + "title": "661. Image Smoother", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class: Example 1:", + "description_images": [], + "constraints": [ + "MagicDictionary() Initializes the object.", + "void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary .", + "bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]Output[null, null, false, true, false, false]ExplanationMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class MagicDictionary {\n private String[] dictionary;\n \n public MagicDictionary() {}\n \n public void buildDict(String[] dictionary) {\n this.dictionary = dictionary;\n }\n \n public boolean search(String searchWord) {\n for (String dictWord: this.dictionary) {\n if (this.match(searchWord, dictWord, 1))\n return true;\n }\n \n return false;\n }\n \n private boolean match(String s, String t, int expectedDiff) {\n if (s.length() != t.length())\n return false;\n \n int diff = 0;\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) != t.charAt(i))\n diff++;\n if (diff > expectedDiff)\n return false;\n }\n \n return diff == expectedDiff;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */\n", + "title": "676. Implement Magic Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class: Example 1:", + "description_images": [], + "constraints": [ + "MagicDictionary() Initializes the object.", + "void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary .", + "bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]Output[null, null, false, true, false, false]ExplanationMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class MagicDictionary:\n\n\tdef __init__(self):\n\t\tTrieNode = lambda : defaultdict(TrieNode)\n\t\tself.root = TrieNode()\n\n\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\tfor s in dictionary:\n\t\t\tcur = self.root\n\t\t\tfor c in s: cur = cur[ord(c)-ord('a')]\n\t\t\tcur['$']=True\n\n\tdef search(self, searchWord: str) -> bool:\n\t\tdef find(i,cur,mis):\n\t\t\tif i==len(searchWord) and mis==0: return('$' in cur)\n\t\t\tif mis < 0: return False\n\t\t\tif i==len(searchWord) and mis!=0: return False\n\t\t\tind = ord(searchWord[i])-ord('a')\n\t\t\tans = False\n\t\t\tfor j in range(26):\n\t\t\t\tif j in cur:\n\t\t\t\t\tif(j!=ind):\n\t\t\t\t\t\tans |= find(i+1,cur[j],mis-1)\n\t\t\t\t\telse: ans |= find(i+1,cur[j],mis)\n\t\t\treturn ans\n\t\t\t\n\t\treturn find(0,self.root,1)\n", + "title": "676. Implement Magic Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 1 ms (Top 70.23%) | Memory: 41.5 MB (Top 77.34%)\nclass MyQueue {\n\n private final Deque stack = new ArrayDeque<>();\n private final Deque temp = new ArrayDeque<>();\n\n /**\n * Initialize your data structure here.\n */\n public MyQueue() {}\n\n /**\n * Pushes element x to the back of the queue.\n */\n public void push(int x) {\n stack.push(x);\n }\n\n /**\n * @return the element at the front of the queue and remove it.\n */\n public int pop() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.pop();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return the element at the front of the queue.\n */\n public int peek() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.peek();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return true if the queue is empty, false otherwise.\n */\n public boolean empty() {\n return stack.isEmpty();\n }\n}", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 53 ms (Top 33.00%) | Memory: 13.9 MB (Top 98.49%)\nclass MyStack:\n def __init__(self):\n self.stack = []\n\n def push(self, x):\n self.stack.append(x)\n\n def top(self):\n return self.stack[-1]\n\n def pop(self):\n return self.stack.pop()\n\n def size(self):\n return len(self.stack)\n\n def isEmpty(self):\n return len(self.stack) == 0\n\nclass MyQueue:\n\n def __init__(self):\n self.stack1 = MyStack()\n self.stack2 = MyStack()\n\n def push(self, x: int) -> None:\n self.stack1.push(x)\n\n def pop(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.pop()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def peek(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.top()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def empty(self) -> bool:\n return self.stack1.isEmpty()\n\n# Your MyQueue object will be instantiated and called as such:\n# obj = MyQueue()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.peek()\n# param_4 = obj.empty()", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the API rand7() that generates a uniform random integer in the range [1, 7] , write a function rand10() that generates a uniform random integer in the range [1, 10] . You can only call the API rand7() , and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n , the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10() . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:[2]", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:[2,8]", + "image": null + }, + { + "text": "Example 3: Input:n = 3Output:[3,8,10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rand10(self):\n \"\"\"\n :rtype: int\n \"\"\"\n x = rand7()\n y = rand7()\n pos = (x - 1) * 7 + y\n if pos > 40:\n return self.rand10()\n return (pos % 10) + 1\n\t\t```", + "title": "470. Implement Rand10() Using Rand7()", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 44 ms (Top 15.83%) | Memory: 16.50 MB (Top 18.94%)\n\nclass MyStack:\n\n def __init__(self):\n self.q1 = deque()\n self.q2 = deque()\n\n def push(self, x: int) -> None:\n self.q1.append(x)\n\n def pop(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n popped_element = self.q1.popleft()\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return popped_element\n\n def top(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n top_element = self.q1[0]\n \n self.q2.append(self.q1.popleft())\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return top_element\n\n def empty(self) -> bool:\n return len(self.q1) == 0\n", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 1 ms (Top 34.13%) | Memory: 42.2 MB (Top 19.29%)\nclass MyStack {\n\n Queue queue = null;\n\n public MyStack() {\n queue = new LinkedList<>();\n }\n\n public void push(int x) {\n\n Queue tempQueue = new LinkedList<>();\n tempQueue.add(x);\n\n while(!queue.isEmpty()){\n tempQueue.add(queue.remove());\n }\n\n queue = tempQueue;\n\n }\n\n public int pop() {\n return queue.remove();\n }\n\n public int top() {\n return queue.peek();\n }\n\n public boolean empty() {\n return queue.isEmpty();\n }\n}", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack ( push , top , pop , and empty ). Implement the MyStack class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the top of the stack.", + "int pop() Removes the element on the top of the stack and returns it.", + "int top() Returns the element on the top of the stack.", + "boolean empty() Returns true if the stack is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 2, 2, false]ExplanationMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class MyStack(object):\n\n def __init__(self):\n self.stack=[]\n\n def push(self, x):\n self.stack.append(x)\n return None\n \n def pop(self):\n return self.stack.pop(-1)\n \n\n def top(self):\n return self.stack[-1]\n\n def empty(self):\n if self.stack==[]:\n return True\n return False\n\n\n# Your MyStack object will be instantiated and called as such:\n# obj = MyStack()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.top()\n# param_4 = obj.empty()\n", + "title": "225. Implement Stack using Queues", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement strStr() . Given two strings needle and haystack , return the index of the first occurrence of needle in haystack , or -1 if needle is not part of haystack . Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf() . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= haystack.length, needle.length <= 10^4", + "haystack and needle consist of only lowercase English characters." + ], + "examples": [ + { + "text": "Example 1: Input:haystack = \"hello\", needle = \"ll\"Output:2", + "image": null + }, + { + "text": "Example 2: Input:haystack = \"aaaaa\", needle = \"bba\"Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int strStr(String haystack, String needle) {\n \n if(needle.length()>haystack.length()) {\n return -1;\n } \n if(needle.length()==haystack.length()) {\n if(haystack.equals(needle)) {\n return 0;\n }\n return -1;\n }\n \n \n int i=0;\n int j=0;\n while(i map;\n public Trie() {\n root = new Node('\\0');\n map = new HashMap<>();\n }\n\n public void insert(String word) {\n Node temp = root;\n for(char c : word.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n temp.sub[index] = new Node(c);\n\n temp = temp.sub[index];\n }\n map.put(word, true);\n }\n\n public boolean search(String word) {\n return map.containsKey(word);\n }\n\n public boolean startsWith(String prefix) {\n Node temp = root;\n for(char c : prefix.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n return false;\n temp = temp.sub[index];\n }\n return true;\n }\n}", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]Output[null, null, true, false, true, null, true]ExplanationTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\"); // return True\ntrie.search(\"app\"); // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class Node : \n def __init__(self ):\n self.child = {} # to hold the nodes.\n self.end = False # to mark a node if it is the end node or not.\n\nclass Trie:\n \n def __init__(self):\n self.root = Node()\n\n def insert(self, word:str) -> None:\n # time compl len(word)\n \n sz = len(word) \n temp = self.root # to hold the root node.\n \n for ind , i in enumerate( word ) :\n if i in temp.child.keys() : # if this curr char in the current node.\n temp = temp.child[i] #another node.\n \n else:\n temp.child[i] = Node()\n temp = temp.child[i]\n\n \n if ind == sz - 1 :\n temp.end = True \n \n \n\n def search(self, word: str) -> bool:\n \n temp = self.root \n for i in word : \n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n \n return temp.end == True \n \n def startsWith(self, prefix: str) -> bool:\n temp = self.root \n for i in prefix :\n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n return 1 \n\n\n", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . Reorder the string using the following algorithm: In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaaabbbbcccc\"Output:\"abccbaabccba\"Explanation:After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\"Output:\"art\"Explanation:The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String sortString(String s) {\n \n StringBuilder result = new StringBuilder();\n int[] freq = new int[26];\n for(char c: s.toCharArray()){\n freq[c-'a']++;\n }\n int remaining = s.length();\n while(remaining!=0){\n for(int i=0;i<26&&remaining!=0;i++){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n for(int i=25;i>=0&&remaining!=0;i--){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n }\n return result.toString();\n }\n}\n", + "title": "1370. Increasing Decreasing String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s . Reorder the string using the following algorithm: In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result. Return the result string after sorting s with this algorithm . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaaabbbbcccc\"Output:\"abccbaabccba\"Explanation:After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\"Output:\"art\"Explanation:The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 48.8%) | Memory: 17.70 MB (Top 9.21%)\n\nclass Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n result = ''\n while s:\n for letter in sorted(set(s)):\n s.remove(letter)\n result += letter\n for letter in sorted(set(s), reverse=True):\n s.remove(letter)\n result += letter\n return result\n", + "title": "1370. Increasing Decreasing String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree will be in the range [1, 100] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]Output:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,7]Output:[1,null,5,null,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.5 MB (Top 73.31%)\nclass Solution {\n TreeNode inRoot = new TreeNode();\n TreeNode temp = inRoot;\n public TreeNode increasingBST(TreeNode root) {\n inorder(root);\n return inRoot.right;\n }\n public void inorder(TreeNode root) {\n if(root==null)\n return;\n inorder(root.left);\n temp.right = new TreeNode(root.val);\n temp = temp.right;\n inorder(root.right);\n }\n}", + "title": "897. Increasing Order Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the given tree will be in the range [1, 100] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]Output:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,7]Output:[1,null,5,null,7]", + "image": "https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 21.66%) | Memory: 17.30 MB (Top 23.65%)\n\nclass Solution:\n def increasingBST(self, node: TreeNode) -> TreeNode:\n dummy = tail = TreeNode()\n while node is not None:\n if node.left is not None:\n predecessor = node.left\n while predecessor.right is not None:\n predecessor = predecessor.right\n \n predecessor.right = node\n left, node.left = node.left, None\n node = left\n else:\n tail.right = tail = node\n node = node.right\n \n return dummy.right\n", + "title": "897. Increasing Order Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return all the different possible increasing subsequences of the given array with at least two elements . You may return the answer in any order . The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 15", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,7,7]Output:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,3,2,1]Output:[[4,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 13.29%) | Memory: 68.6 MB (Top 66.07%)\nclass Solution {\n HashSet> set;\n public List> findSubsequences(int[] nums) {\n set=new HashSet<>();\n\n dfs(nums,0,new ArrayList<>());\n\n List> ans=new ArrayList<>();\n if(set.size()>0){\n ans.addAll(set);\n }\n return ans;\n }\n\n private void dfs(int nums[], int start, List temp){\n if(start==nums.length) return;\n\n for(int i=start;i=2) set.add(new ArrayList<>(temp));\n\n dfs(nums,i+1,temp);\n temp.remove(temp.size()-1);\n }\n }\n }\n}", + "title": "491. Increasing Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return all the different possible increasing subsequences of the given array with at least two elements . You may return the answer in any order . The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 15", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,7,7]Output:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,3,2,1]Output:[[4,4]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 750 ms (Top 10.08%) | Memory: 22.4 MB (Top 30.72%)\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n def backtracking(nums,path):\n # to ensure that the base array has at least 2 elements\n if len(path)>=2:\n res.add(tuple(path))\n for i in range(len(nums)):\n # to ensure that every element to be added is equal or larger than the former\n if not path or path[-1] <= nums[i]:\n backtracking(nums[i+1:],path+[nums[i]])\n\n res=set()\n backtracking(nums,[])\n return res", + "title": "491. Increasing Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]Output:trueExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]Output:falseExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]Output:trueExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n if(nums.length < 3)\n return false;\n \n int x = Integer.MAX_VALUE;\n int y = Integer.MAX_VALUE;\n \n for (int i : nums){\n if(i <= x){\n x = i;\n }else if (i <= y)\n y = i;\n else \n return true;\n }\n \n return false;\n }\n}\n", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]Output:trueExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]Output:falseExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]Output:trueExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n first = second = float('inf')\n for n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\n return False\n", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the i th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes . Return an array containing [crashTime, memory1 crash , memory2 crash ] , where crashTime is the time (in seconds) when the program crashed and memory1 crash and memory2 crash are the available bits of memory in the first and second sticks respectively . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= memory1, memory2 <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:memory1 = 2, memory2 = 2Output:[3,1,0]Explanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rdsecond, the program crashes. The sticks have 1 and 0 bits available respectively.", + "image": null + }, + { + "text": "Example 2: Input:memory1 = 8, memory2 = 11Output:[6,0,4]Explanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rdsecond, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4thsecond, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5thsecond, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6thsecond, the program crashes. The sticks have 0 and 4 bits available respectively.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 87.96%) | Memory: 41.8 MB (Top 45.37%)\nclass Solution {\n public int[] memLeak(int memory1, int memory2) {\n int i = 1;\n while(Math.max(memory1, memory2) >= i){\n if(memory1 >= memory2)\n memory1 -= i;\n else\n memory2 -= i;\n i++;\n }\n return new int[]{i, memory1, memory2};\n }\n}", + "title": "1860. Incremental Memory Leak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the i th second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes . Return an array containing [crashTime, memory1 crash , memory2 crash ] , where crashTime is the time (in seconds) when the program crashed and memory1 crash and memory2 crash are the available bits of memory in the first and second sticks respectively . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= memory1, memory2 <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:memory1 = 2, memory2 = 2Output:[3,1,0]Explanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rdsecond, the program crashes. The sticks have 1 and 0 bits available respectively.", + "image": null + }, + { + "text": "Example 2: Input:memory1 = 8, memory2 = 11Output:[6,0,4]Explanation:The memory is allocated as follows:\n- At the 1stsecond, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2ndsecond, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rdsecond, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4thsecond, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5thsecond, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6thsecond, the program crashes. The sticks have 0 and 4 bits available respectively.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n \n inverted = False \n if memory2>memory1:\n memory2, memory1 = memory1, memory2\n inverted = True \n\n\t\t#Compute the number of steps in first stage - 1\n i_start = solve_quadratic(1,2*(memory1-memory2))\n \n\t\t#Memory1 after the end of first stage is computed using the sum of arithmetic sequence\n memory1-= i_start*(i_start+1)//2\n\t\t\n\t\tif memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion)\n inverted = False \n \n #Compute number of steps in stage - 2\n n_end = solve_quadratic((i_start+1), memory2)\n \n\t\t#Compute sums of respective arithmetic sequences\n i_end_1 = i_start - 1 + 2*n_end\n i_end_2 = i_start + 2*n_end\n \n sum1 = n_end * (i_start+1 + i_end_1)//2\n sum2 = n_end * (i_start+2 + i_end_2)//2\n \n\t\t#Compute updated memories \n memory1-=sum1\n memory2-=sum2\n \n full_cnt=2*n_end+i_start\n \n if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it.\n memory1-=(i_end_2+1)\n full_cnt+=1\n \n return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2]\n \n\t\t ```", + "title": "1860. Incremental Memory Leak", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity. Example 1:", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedSet {\n HashMap map;\n ArrayList list;\n Random rand;\n public RandomizedSet() {\n map = new HashMap<>();\n list = new ArrayList<>();\n rand = new Random();\n }\n \n public boolean insert(int val) {\n if (!map.containsKey(val)){\n map.put(val, list.size());\n list.add(val);\n return true;\n }\n return false;\n }\n \n public boolean remove(int val) {\n if (map.containsKey(val)){\n int index = map.get(val);\n int last = list.get(list.size() - 1);\n if (index != list.size() - 1){\n list.set(index, last);\n map.put(last, index);\n }\n list.remove(list.size() - 1); \n map.remove(val);\n return true;\n }\n return false;\n }\n \n public int getRandom() {\n int r = rand.nextInt(list.size()); \n return list.get(r);\n }\n}\n", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity. Example 1:", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedSet:\n\n def __init__(self):\n self.data = set() \n\n def insert(self, val: int) -> bool:\n if val not in self.data:\n self.data.add(val)\n return True \n return False \n \n def remove(self, val: int) -> bool:\n if val in self.data:\n self.data.remove(val)\n return True \n return False \n\n def getRandom(self) -> int:\n return random.choice(list(self.data))\n", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection . Example 1:", + "description_images": [], + "constraints": [ + "RandomizedCollection() Initializes the empty RandomizedCollection object.", + "bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.", + "bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.", + "int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"]\n[[], [1], [1], [2], [], [1], []]Output[null, true, false, true, 2, true, 1]ExplanationRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\nrandomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\nrandomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedCollection {\n List multiSet;\n HashMap> map;\n Random random;\n public RandomizedCollection() {\n map = new HashMap<>();\n multiSet = new ArrayList<>();\n random = new Random();\n }\n \n public boolean insert(int val) {\n boolean contains = map.containsKey(val);\n multiSet.add(val);\n PriorityQueue pq;\n if(!contains){\n pq = new PriorityQueue<>(Collections.reverseOrder());\n map.put(val, pq);\n }else\n pq = map.get(val);\n \n pq.add(multiSet.size()-1);\n return !contains;\n }\n \n public boolean remove(int val) {\n if(!map.containsKey(val))\n return false;\n \n PriorityQueue pq = map.get(val);\n int indexToRemove = pq.poll();\n if(pq.size() == 0) map.remove(val);\n \n int lastIndex = multiSet.size()-1;\n if(indexToRemove != lastIndex){\n int valLast = multiSet.get(lastIndex);\n PriorityQueue temp = map.get(valLast);\n temp.poll();\n temp.add(indexToRemove);\n multiSet.set(indexToRemove, valLast);\n }\n multiSet.remove(lastIndex);\n return true;\n }\n \n public int getRandom() {\n int index = random.nextInt(multiSet.size());\n return multiSet.get(index);\n }\n}\n", + "title": "381. Insert Delete GetRandom O(1) - Duplicates allowed", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element. Implement the RandomizedCollection class: You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection . Example 1:", + "description_images": [], + "constraints": [ + "RandomizedCollection() Initializes the empty RandomizedCollection object.", + "bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.", + "bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.", + "int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"]\n[[], [1], [1], [2], [], [1], []]Output[null, true, false, true, 2, true, 1]ExplanationRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\nrandomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\nrandomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.", + "image": null + } + ], + "follow_up": null, + "solution": "class RandomizedCollection:\n\n def __init__(self):\n self.items = []\n\n def insert(self, val: int) -> bool:\n self.items.append(val)\n if self.items.count(val) > 1:\n return False\n else:\n return True\n\n def remove(self, val: int) -> bool:\n if val in self.items:\n flag = True\n self.items.remove(val)\n else:\n flag = False\n \n return flag\n\n def getRandom(self) -> int:\n return choice(self.items)\n \n", + "title": "381. Insert Delete GetRandom O(1) - Duplicates allowed", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 . Example 1: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]Output:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: 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].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n if (newInterval == null || newInterval.length == 0) return intervals;\n \n List merged = new LinkedList<>();\n int i = 0;\n // add not overlapping\n while (i < intervals.length && intervals[i][1] < newInterval[0]) {\n merged.add(intervals[i]);\n i++;\n }\n // add overlapping\n while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(intervals[i][0], newInterval[0]);\n newInterval[1] = Math.max(intervals[i][1], newInterval[1]);\n i++;\n }\n merged.add(newInterval);\n // add rest\n while (i < intervals.length) {\n merged.add(intervals[i]);\n i++;\n }\n return merged.toArray(new int[merged.size()][]);\n }\n}\n", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 . Example 1: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]Output:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: 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].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 202 ms (Top 7.96%) | Memory: 17.3 MB (Top 91.79%)\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n\n intervals.append(newInterval)\n intervals.sort(key=lambda x: x[0])\n\n result = []\n for interval in intervals:\n if not result or result[-1][1] < interval[0]:\n result.append(interval)\n else:\n result[-1][1] = max(result[-1][1],interval[1])\n\n return result", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion . It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-10^8 <= Node.val <= 10^8", + "All the values Node.val are unique .", + "-10^8 <= val <= 10^8", + "It's guaranteed that val does not exist in the original BST." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 5Output:[4,2,7,1,3,5]Explanation:Another accepted tree is:", + "image": "https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg" + }, + { + "text": "Example 2: Input:root = [40,20,60,10,30,50,70], val = 25Output:[40,20,60,10,30,50,70,null,null,25]", + "image": null + }, + { + "text": "Example 3: Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5Output:[4,2,7,1,3,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode insertIntoBST(TreeNode root, int val) {\n if(root == null) return new TreeNode(val);\n \n if(root.val > val) root.left = insertIntoBST(root.left, val);\n \n else root.right = insertIntoBST(root.right, val);\n \n return root;\n }\n}\n", + "title": "701. Insert into a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion . It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [0, 10^4 ] .", + "-10^8 <= Node.val <= 10^8", + "All the values Node.val are unique .", + "-10^8 <= val <= 10^8", + "It's guaranteed that val does not exist in the original BST." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 5Output:[4,2,7,1,3,5]Explanation:Another accepted tree is:", + "image": "https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg" + }, + { + "text": "Example 2: Input:root = [40,20,60,10,30,50,70], val = 25Output:[40,20,60,10,30,50,70,null,null,25]", + "image": null + }, + { + "text": "Example 3: Input:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5Output:[4,2,7,1,3,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def insertIntoBST(self, root, val):\n if not root:\n return TreeNode(val)\n \n if val= cur.val)\n prev = temp;\n while(prev.next != null && prev.next.val < cur.val)\n prev = prev.next;\n cur.next = prev.next;\n prev.next = cur;\n cur = nxt;\n }\n return temp.next;\n }\n}\n", + "title": "147. Insertion Sort List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a singly linked list, sort the list using insertion sort , and return the sorted list's head . The steps of the insertion sort algorithm: The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]Output:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]Output:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction insertionSortList(head: ListNode | null): ListNode | null {\n if (!head) return null\n if (!head.next) return head\n\n let output = head\n let curr = head.next\n\n head.next = null\n\n while (curr) {\n const next = curr.next\n const insertion = curr\n\n output = insert(output, insertion)\n curr = next as ListNode\n }\n\n return output\n}\n\nfunction insert(head: ListNode, other: ListNode) {\n let curr = head\n const val = other.val\n\n if (val <= head.val) {\n other.next = head\n return other\n }\n\n while (curr) {\n if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) {\n other.next = curr.next\n curr.next = other\n\n return head\n }\n\n curr = curr.next as ListNode\n }\n\n return head\n}\n", + "title": "147. Insertion Sort List", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and an integer limit , delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree . A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit . A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "-10^5 <= Node.val <= 10^5", + "-10^9 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1Output:[1,2,3,4,null,null,7,8,9,null,14]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-11.png" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22Output:[5,4,8,11,null,17,4,7,null,null,null,5]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-3.png" + }, + { + "text": "Example 3: Input:root = [1,2,-3,-5,null,4,null], limit = -1Output:[1,null,-3,4]", + "image": "https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83301-pm.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 45.20 MB (Top 7.32%)\n\nclass Solution { \n public TreeNode helper(TreeNode root,int limit, int sumTillNow)\n {\n if(root == null) return null;\n \n if(root.left == null && root.right == null)\n return root.val + sumTillNow < limit ? null : root;\n \n root.left = helper(root.left,limit,sumTillNow + root.val);\n root.right = helper(root.right,limit,sumTillNow + root.val);\n \n return root.left == null && root.right == null ? null : root;\n }\n \n \n public TreeNode sufficientSubset(TreeNode root, int limit){\n return helper(root,limit,0);\n }\n}\n", + "title": "1080. Insufficient Nodes in Root to Leaf Paths", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree and an integer limit , delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree . A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit . A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "-10^5 <= Node.val <= 10^5", + "-10^9 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1Output:[1,2,3,4,null,null,7,8,9,null,14]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-11.png" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22Output:[5,4,8,11,null,17,4,7,null,null,null,5]", + "image": "https://assets.leetcode.com/uploads/2019/06/05/insufficient-3.png" + }, + { + "text": "Example 3: Input:root = [1,2,-3,-5,null,4,null], limit = -1Output:[1,null,-3,4]", + "image": "https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83301-pm.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n we can try to solve this problem using depth first traversal\n \"\"\"\n def dfs(self, root, sum_so_far, limit):\n if root is None:\n return None, 0\n \n x, left = self.dfs(root.left, sum_so_far + root.val, limit)\n y, right = self.dfs(root.right, sum_so_far + root.val, limit)\n # print('for node= {}, sum_so_far= {}, left= {}, right= {}'.format(root.val, sum_so_far, left, right))\n if root.left is None and root.right is None:\n # it is leaf, left and right should be 0\n if sum_so_far + root.val < limit:\n # node is insufficient\n return None, root.val\n else:\n # node is sufficient\n return root, root.val\n elif root.left is not None and root.right is None:\n root.left = x\n if sum_so_far + root.val + left < limit:\n # node is insufficient\n return None, root.val + left\n else:\n return root, root.val + left\n \n elif root.left is None and root.right is not None:\n root.right = y\n if sum_so_far + root.val + right < limit:\n return None, root.val + right\n else:\n return root, root.val + right\n \n elif root.left is not None and root.right is not None:\n root.left = x\n root.right = y\n if sum_so_far + root.val + left < limit and sum_so_far + root.val + right < limit:\n return None, max(root.val + left, root.val + right)\n elif sum_so_far + root.val + left < limit and sum_so_far + root.val + right > limit:\n return root, root.val + right\n elif sum_so_far + root.val + left > limit and sum_so_far + root.val + right < limit:\n return root, root.val + left\n else:\n return root, max(root.val + left, root.val + right)\n \n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n root, _ = self.dfs(root, 0, limit)\n return root\n", + "title": "1080. Insufficient Nodes in Root to Leaf Paths", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , break it into the sum of k positive integers , where k >= 2 , and maximize the product of those integers. Return the maximum product you can get . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 58" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:2 = 1 + 1, 1 × 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:36Explanation:10 = 3 + 3 + 4, 3 × 3 × 4 = 36.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.80 MB (Top 7.7%)\n\nclass Solution {\n public int integerBreak(int n) {\n if (n <= 1) {\n return 0;\n }\n int[] memo = new int[n + 1];\n return maxProduct(n, memo);\n }\n \n private int maxProduct(int n, int[] memo) {\n if (n == 2) {\n return 1;\n }\n if (memo[n] != 0) {\n return memo[n];\n }\n int max = 0;\n for (int i = 1; i < n; i++) {\n max = Math.max(max, Math.max(i * (n - i), i * maxProduct(n - i, memo)));\n }\n memo[n] = max;\n return max;\n }\n}\n", + "title": "343. Integer Break", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , break it into the sum of k positive integers , where k >= 2 , and maximize the product of those integers. Return the maximum product you can get . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 58" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:2 = 1 + 1, 1 × 1 = 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 10Output:36Explanation:10 = 3 + 3 + 4, 3 × 3 × 4 = 36.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def integerBreak(self, n: int) -> int:\n dp = [0 for _ in range(n+1)]\n dp[1] = 1\n for i in range(2, n+1):\n for j in range(1, i//2+1):\n dp[i] = max(j * (i-j), j * dp[i-j], dp[i])\n return dp[-1]\n", + "title": "343. Integer Break", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , you can apply one of the following operations: Return the minimum number of operations needed for n to become 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 8Output:3Explanation:8 -> 4 -> 2 -> 1", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int integerReplacement(int n) {\n return (int)calc(n,0);\n }\n public long calc(long n,int i){\n if(n==1) \n return i;\n if(n<1) \n return 0;\n \n long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE;\n \n if(n%2==0) \n a=calc(n/2,i+1);\n else{\n b=calc(n-1,i+1);\n c=calc(n+1,i+1);\n }\n long d=Math.min(a,Math.min(b,c));\n return d;\n }\n}\n", + "title": "397. Integer Replacement", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , you can apply one of the following operations: Return the minimum number of operations needed for n to become 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 8Output:3Explanation:8 -> 4 -> 2 -> 1", + "image": null + }, + { + "text": "Example 2: Input:n = 7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 77.23%) | Memory: 14 MB (Top 29.19%)\n\nclass Solution:\n def integerReplacement(self, n: int) -> int:\n dp = {}\n def dfs(num):\n if num == 1:\n return 0\n\n if num in dp:\n return dp[num]\n\n # if num is even, we have only one option -> n / 2\n even = odd = 0\n if num % 2 == 0:\n even = 1 + dfs(num // 2)\n else:\n # if num is odd, we have two option, either we increment the num or decrement the num\n odd1 = 1 + dfs(num - 1)\n odd2 = 1 + dfs(num + 1)\n # take the min of both operation\n odd = min(odd1, odd2)\n\n dp[num] = even + odd\n return dp[num]\n\n return dfs(n)", + "title": "397. Integer Replacement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Convert a non-negative integer num to its English words representation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 123Output:\"One Hundred Twenty Three\"", + "image": null + }, + { + "text": "Example 2: Input:num = 12345Output:\"Twelve Thousand Three Hundred Forty Five\"", + "image": null + }, + { + "text": "Example 3: Input:num = 1234567Output:\"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[] INT_NUMBERS = {\n 1_000_000_000, 1_000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};\n private static final String[] STRING_NUMBERS = {\n \"Billion\", \"Million\", \"Thousand\", \"Hundred\", \"Ninety\", \"Eighty\", \"Seventy\", \"Sixty\", \"Fifty\", \"Forty\", \"Thirty\", \"Twenty\",\n \"Nineteen\", \"Eighteen\", \"Seventeen\", \"Sixteen\", \"Fifteen\", \"Fourteen\", \"Thirteen\", \"Twelve\", \"Eleven\", \"Ten\",\n \"Nine\", \"Eight\", \"Seven\", \"Six\", \"Five\", \"Four\", \"Three\", \"Two\", \"One\"};\n\n public String numberToWords(int num) {\n if (num == 0) return \"Zero\";\n return numberToWordsHelper(num).toString();\n }\n\n private StringBuilder numberToWordsHelper(int num) {\n StringBuilder sb = new StringBuilder();\n if (num == 0) return sb;\n for (int i = 0; i < INT_NUMBERS.length; i++) {\n if (num >= INT_NUMBERS[i]) {\n if (num >= 100) {\n sb.append(numberToWordsHelper(num / INT_NUMBERS[i]).append(\" \"));\n }\n\n sb.append(STRING_NUMBERS[i]).append(\" \").append(numberToWordsHelper(num % INT_NUMBERS[i]));\n break;\n }\n }\n return sb.charAt(sb.length() - 1) == ' ' ? sb.deleteCharAt(sb.length() - 1) : sb; // trim\n }\n \n}\n\n", + "title": "273. Integer to English Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Convert a non-negative integer num to its English words representation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= num <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 123Output:\"One Hundred Twenty Three\"", + "image": null + }, + { + "text": "Example 2: Input:num = 12345Output:\"Twelve Thousand Three Hundred Forty Five\"", + "image": null + }, + { + "text": "Example 3: Input:num = 1234567Output:\"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberToWords(self, num: int) -> str:\n \n if num == 0:\n return \"Zero\"\n \n dic1 = {1000000000: \"Billion\", 1000000: \"Million\", 1000: \"Thousand\", 1: \"\"}\n dic2 = {90: \"Ninety\", 80: \"Eighty\", 70: \"Seventy\", 60: \"Sixty\", 50: \"Fifty\", 40: \"Forty\", 30: \"Thirty\", 20: \"Twenty\", 19: 'Nineteen', 18: \"Eighteen\", 17: \"Seventeen\", 16: \"Sixteen\", 15: \"Fifteen\", 14: \"Fourteen\", 13: \"Thirteen\", 12: \"Twelve\", 11: \"Eleven\", 10: \"Ten\", 9: \"Nine\", 8: \"Eight\", 7: \"Seven\", 6: \"Six\", 5: \"Five\", 4: \"Four\", 3: \"Three\", 2: \"Two\", 1: \"One\"}\n \n def construct_num(num):\n ans = ''\n d, num = divmod(num, 100)\n if d > 0:\n ans += dic2[d] + \" \" + \"Hundred\"\n for k, v in dic2.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + v\n return ans.lstrip() \n \n ans = \"\"\n for k, v in dic1.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + construct_num(d) + \" \" + v\n \n return ans.strip()\n", + "title": "273. Integer to English Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:num = 3Output:\"III\"Explanation:3 is represented as 3 ones.", + "image": null + }, + { + "text": "Example 2: Input:num = 58Output:\"LVIII\"Explanation:L = 50, V = 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:num = 1994Output:\"MCMXCIV\"Explanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 27.77%) | Memory: 44.00 MB (Top 31.59%)\n\nclass Solution {\n final static int[] val = {1000,900,500,400,100,90,50,40,10,9,5,4,1};\n final static String[] rom = {\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"};\n\n public String intToRoman(int N) {\n StringBuilder ans = new StringBuilder();\n for (int i = 0; N > 0; i++)\n while (N >= val[i]) {\n ans.append(rom[i]);\n N -= val[i];\n }\n return ans.toString();\n }\n}\n", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given an integer, convert it to a roman numeral. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:num = 3Output:\"III\"Explanation:3 is represented as 3 ones.", + "image": null + }, + { + "text": "Example 2: Input:num = 58Output:\"LVIII\"Explanation:L = 50, V = 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:num = 1994Output:\"MCMXCIV\"Explanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 86.4%) | Memory: 16.42 MB (Top 14.9%)\n\nclass Solution:\n def intToRoman(self, num: int) -> str:\n # Creating Dictionary for Lookup\n num_map = {\n 1: \"I\",\n 5: \"V\", 4: \"IV\",\n 10: \"X\", 9: \"IX\",\n 50: \"L\", 40: \"XL\",\n 100: \"C\", 90: \"XC\",\n 500: \"D\", 400: \"CD\",\n 1000: \"M\", 900: \"CM\",\n }\n \n # Result Variable\n r = ''\n \n \n for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:\n # If n in list then add the roman value to result variable\n while n <= num:\n r += num_map[n]\n num-=n\n return r", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 non-empty substrings respectively, such that: Note: a + b is the concatenation of strings a and b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 + ..." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"Output:trueExplanation:One way to obtain s3 is:\nSplit s1 into s1 = \"aa\" + \"bc\" + \"c\", and s2 into s2 = \"dbbc\" + \"a\".\nInterleaving the two splits, we get \"aa\" + \"dbbc\" + \"bc\" + \"a\" + \"c\" = \"aadbbcbcac\".\nSince s3 can be obtained by interleaving s1 and s2, we return true.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg" + }, + { + "text": "Example 2: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"Output:falseExplanation:Notice how it is impossible to interleave s2 with any other string to obtain s3.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"\", s2 = \"\", s3 = \"\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s1) + len(s2) != len(s3) :\n return False\n dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)]\n dp[len(s1)][len(s2)] = True\n \n for i in range(len(s1), -1, -1):\n for j in range(len(s2), -1, -1):\n if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]:\n dp[i][j] = True\n if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]:\n dp[i][j] = True\n return dp[0][0]\n", + "title": "97. Interleaving String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= sum(nums[i].length) <= 1000", + "1 <= nums[i][j] <= 1000", + "All the values of nums[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]Output:[3,4]Explanation:The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[4,5,6]]Output:[]Explanation:There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.41%) | Memory: 46.4 MB (Top 56.41%)\n\nclass Solution {\n public List intersection(int[][] nums) {\n\n List ans = new ArrayList<>();\n\n int[] count = new int[1001];\n\n for(int[] arr : nums){\n for(int i : arr){\n count[i]++;\n }\n }\n\n for(int i=0;i List[int]:\n return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])\n\t\t\n", + "title": "2248. Intersection of Multiple Arrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must be unique and you may return the result in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[9,4]Explanation:[4,9] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.90%) | Memory: 44.3 MB (Top 29.92%)\nclass Solution {\n public int[] intersection(int[] nums1, int[] nums2) {\n int[] dp = new int[1000];\n for(int i:nums1){\n dp[i]++;\n }\n int[] ans = new int[1000];\n\n //declaring ptr to track ans array index\n int ptr = 0;\n for(int i:nums2){\n if(dp[i] != 0){\n dp[i] = 0;\n ans[ptr] = i;\n ptr++;\n }\n }\n return Arrays.copyOfRange(ans, 0, ptr);\n }\n}", + "title": "349. Intersection of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must be unique and you may return the result in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[9,4]Explanation:[4,9] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 73.60%) | Memory: 14 MB (Top 91.27%)\nclass Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n nums1.sort()\n nums2.sort()\n ans = []\n i, j = 0, 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n if len(ans) == 0 or nums1[i] != ans[-1]:\n ans.append(nums1[i])\n i += 1\n j += 1\n return ans", + "title": "349. Intersection of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[4,9]Explanation:[9,4] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] intersect(int[] nums1, int[] nums2) {\n int[] dp = new int[1000+1];\n for(int i: nums1){\n dp[i]++;\n }\n int ptr =0;\n int ans[] = new int[1000+1];\n for(int i:nums2){\n if(dp[i]!= 0){\n ans[ptr]= i;\n ptr++;\n dp[i]--;\n }\n \n }\n return Arrays.copyOfRange(ans,0,ptr);\n }\n}\n", + "title": "350. Intersection of Two Arrays II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integer arrays nums1 and nums2 , return an array of their intersection . Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[4,9]Explanation:[9,4] is also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n nums1.sort()\n nums2.sort()\n ans = []\n i, j = 0, 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n ans.append(nums1[i])\n i += 1\n j += 1\n return ans\n", + "title": "350. Intersection of Two Arrays II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3Output:Intersected at '8'Explanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1Output:Intersected at '2'Explanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2Output:No intersectionExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.75%) | Memory: 55.6 MB (Top 36.20%)\npublic class Solution {\n public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n ListNode tempA = headA, tempB = headB;\n int lenA = 0, lenB = 0;\n while (tempA != null) {\n lenA++;\n tempA = tempA.next;\n }\n while (tempB != null) {\n lenB++;\n tempB = tempB.next;\n }\n tempA = headA; tempB = headB;\n if (lenB > lenA) {\n for (int i = 0; i < lenB - lenA; i++) {\n tempB = tempB.next;\n }\n } else if (lenA > lenB) {\n for (int i = 0; i < lenA - lenB; i++) {\n tempA = tempA.next;\n }\n }\n while (tempA != null && tempA != tempB) {\n tempA = tempA.next;\n tempB = tempB.next;\n }\n return tempA;\n }\n}", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3Output:Intersected at '8'Explanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1Output:Intersected at '2'Explanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2Output:No intersectionExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n m = 0\n n = 0\n temp = headA\n while temp != None:\n m+=1\n temp = temp.next\n temp = headB\n while temp != None:\n n+=1\n temp = temp.next\n diff = 0\n if m>=n : \n diff = m-n\n else:\n diff = n-m\n p1 = headA\n p2 = headB\n if max(m,n) == m:\n while diff > 0:\n p1 = p1.next\n diff-=1\n else:\n while diff > 0:\n p2 = p2.next\n diff-=1\n while p1 != None and p2!=None:\n if p1 == p2:\n return p1\n p1 = p1.next\n p2 = p2.next\n return None\n", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: 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]]", + "image": "https://assets.leetcode.com/uploads/2019/01/30/interval1.png" + }, + { + "text": "Example 2: Input:firstList = [[1,3],[5,9]], secondList = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 9.49%) | Memory: 45.30 MB (Top 8.74%)\n\nclass Solution {\n public int[][] intervalIntersection(int[][] A, int[][] B) {\n List ans = new ArrayList<>();\n int i = 0, j = 0;\n while(i < A.length && j< B.length){\n int start = Math.max(A[i][0], B[j][0]);\n int end = Math.min(A[i][1], B[j][1]);\n if(start <= end) ans.add(new int[]{start, end});\n if(A[i][1]>B[j][1]) j++;\n else i++;\n }\n \n int[][] res = new int[ans.size()][2];\n i = 0;\n for(int[] pair: ans){\n res[i++] = pair;\n }\n \n return res;\n }\n}\n", + "title": "986. Interval List Intersections", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: 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]]", + "image": "https://assets.leetcode.com/uploads/2019/01/30/interval1.png" + }, + { + "text": "Example 2: Input:firstList = [[1,3],[5,9]], secondList = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 325 ms (Top 13.56%) | Memory: 15.2 MB (Top 15.52%)\nfrom collections import deque\n\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\n answer = []\n\n if len(firstList) == 0 or len(secondList) == 0:\n return answer\n\n first_queue= deque(firstList)\n second_queue = deque(secondList )\n\n first = first_queue.popleft()\n second = second_queue.popleft()\n\n while first_queue or second_queue:\n\n if first[1] < second[0]:\n if len(first_queue):\n first = first_queue.popleft()\n continue\n break\n if second[1] < first[0]:\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n answer.append([second[0], first[1]])\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n else:\n answer.append(second)\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n if second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n answer.append([first[0], second[1]])\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n else:\n answer.append(first)\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n\n if len(answer) > 0:\n\n if answer[-1] != [second[0], first[1]]:\n answer.append([second[0], first[1]])\n elif not answer:\n answer.append([second[0], first[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != second:\n answer.append(second)\n elif not answer:\n answer.append(second)\n elif second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n if len(answer) > 0:\n if answer[-1] != [first[0], second[1]]:\n answer.append([first[0], second[1]])\n elif not answer:\n answer.append([first[0], second[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != first:\n answer.append(first)\n elif not answer:\n\n answer.append(first)\n\n return answer", + "title": "986. Interval List Intersections", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array of n integers arr . The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j| . Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i] . Note: |x| is the absolute value of x . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10^5", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,1,2,3,3]Output:[4,2,7,2,4,4,5]Explanation:- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5", + "image": null + }, + { + "text": "Example 2: Input:arr = [10,5,10,10]Output:[5,0,3,4]Explanation:- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 544 ms (Top 6.59%) | Memory: 244.1 MB (Top 25.15%)\nclass Solution {\n public long[] getDistances(int[] arr) {\n long[] output = new long[arr.length];\n Map sumMap = new HashMap<>();\n Map countMap = new HashMap<>();\n for (int i = 0; i < arr.length; ++ i) {\n if (!sumMap.containsKey(arr[i])) {\n sumMap.put(arr[i], 0l);\n countMap.put(arr[i], 0);\n }\n\n output[i] += i * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n sumMap.put(arr[i], sumMap.get(arr[i]) + i);\n countMap.put(arr[i], countMap.get(arr[i]) + 1);\n }\n\n sumMap = new HashMap<>();\n countMap = new HashMap<>();\n int len = arr.length;\n for (int i = len - 1; i >= 0; -- i) {\n if (!sumMap.containsKey(arr[i])) {\n sumMap.put(arr[i], 0l);\n countMap.put(arr[i], 0);\n }\n\n output[i] += (len - i - 1) * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n sumMap.put(arr[i], sumMap.get(arr[i]) + (len - i - 1));\n countMap.put(arr[i], countMap.get(arr[i]) + 1);\n }\n\n return output;\n }\n}", + "title": "2121. Intervals Between Identical Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of n integers arr . The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j| . Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i] . Note: |x| is the absolute value of x . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10^5", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,3,1,2,3,3]Output:[4,2,7,2,4,4,5]Explanation:- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5", + "image": null + }, + { + "text": "Example 2: Input:arr = [10,5,10,10]Output:[5,0,3,4]Explanation:- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4", + "image": null + } + ], + "follow_up": null, + "solution": "\n# helper data structure Scout\nclass Scout:\n \n def __init__(self, prev_idx=-1, count_of_equal=0):\n \n # record of index of last identical element\n self.prev_idx = prev_idx\n \n # count of identical elements so far\n self.count_of_equal = count_of_equal\n \n def __iter__(self):\n\t\t# ouput previous index, and count of equal in order\n return iter( (self.prev_idx, self.count_of_equal) )\n \n \n \nclass Solution:\n def getDistances(self, arr: List[int]) -> List[int]:\n \n size = len(arr)\n \n pre_scout = defaultdict( Scout )\n pre_dist_sum = [0 for _ in range(size)]\n \n post_scout = defaultdict( Scout )\n post_dist_sum = [0 for _ in range(size)]\n \n \n ## Step_1:\n # update for pre_dist_sum table, direction is from left to right\n for i, element in enumerate(arr):\n \n prev_equal_idx, prev_count_of_equal = pre_scout[element]\n \n # update pre_dist_sum table if we have identical elements before index i\n if prev_count_of_equal:\n pre_dist_sum[i] += pre_dist_sum[ prev_equal_idx ] + (i - prev_equal_idx) * prev_count_of_equal\n \n # update Scout information for current element\n pre_scout[element] = i, prev_count_of_equal+1\n \n # --------------------------------------------------------------\n \n ## Step_2:\n # update for pos_dist_sum table, direction is from right to left\n for i, element in reversed( [*enumerate(arr)] ):\n \n post_equal_idx, post_count_of_equal = post_scout[element]\n\n # update post_dist_sum table if we have identical elements after index i\n if post_count_of_equal:\n post_dist_sum[i] += post_dist_sum[ post_equal_idx ] + (post_equal_idx - i) * post_count_of_equal\n \n # update Scout information for current element\n post_scout[element] = i, post_count_of_equal+1\n \n \n ## Step_3:\n # Generate final output by definition\n return [ pre_dist_sum[i] + post_dist_sum[i] for i in range(size) ]\n \n \n", + "title": "2121. Intervals Between Identical Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A transaction is possibly invalid if: You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "the amount exceeds $1000 , or;", + "if it occurs within (and including) 60 minutes of another transaction with the same name in a different city ." + ], + "examples": [ + { + "text": "Example 1: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]Output:[\"alice,20,800,mtv\",\"alice,50,100,beijing\"]Explanation:The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.", + "image": null + }, + { + "text": "Example 2: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]Output:[\"alice,50,1200,mtv\"]", + "image": null + }, + { + "text": "Example 3: Input:transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]Output:[\"bob,50,1200,mtv\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 63.84%) | Memory: 50.7 MB (Top 74.53%)\nclass Solution {\n public List invalidTransactions(String[] transactions) {\n Map> nameToTransaction = new HashMap<>();\n for (int i = 0; i < transactions.length; i++) {\n Transaction t = new Transaction(transactions[i], i);\n nameToTransaction.putIfAbsent(t.name, new ArrayList<>());\n nameToTransaction.get(t.name).add(t);\n }\n List invalid = new ArrayList<>();\n for (List list : nameToTransaction.values()) {\n for (Transaction t : list) {\n if (t.isInvalidAmount()) invalid.add(transactions[t.id]);\n else {\n for (Transaction otherT : list) {\n if (t.isInvalidCity(otherT)) {\n invalid.add(transactions[t.id]);\n break;\n }\n }\n }\n }\n }\n return invalid;\n }\n}\n\nclass Transaction {\n String name, city;\n int time, amount, id;\n\n Transaction(String s, int id) {\n this.id = id;\n String[] split = s.split(\",\");\n name = split[0];\n time = Integer.parseInt(split[1]);\n amount = Integer.parseInt(split[2]);\n city = split[3];\n }\n\n boolean isInvalidAmount() {\n return this.amount > 1000;\n }\n\n boolean isInvalidCity(Transaction t) {\n return !city.equals(t.city) && Math.abs(t.time - time) <= 60;\n }\n}", + "title": "1169. Invalid Transactions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A transaction is possibly invalid if: You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "the amount exceeds $1000 , or;", + "if it occurs within (and including) 60 minutes of another transaction with the same name in a different city ." + ], + "examples": [ + { + "text": "Example 1: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]Output:[\"alice,20,800,mtv\",\"alice,50,100,beijing\"]Explanation:The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.", + "image": null + }, + { + "text": "Example 2: Input:transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]Output:[\"alice,50,1200,mtv\"]", + "image": null + }, + { + "text": "Example 3: Input:transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]Output:[\"bob,50,1200,mtv\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 99.79%) | Memory: 18.10 MB (Top 5.19%)\n\nclass Transaction:\n def __init__(self, name, time, amount, city):\n self.name = name\n self.time = int(time)\n self.amount = int(amount)\n self.city = city\n\nfrom collections import defaultdict\nclass Solution:\n def invalidTransactions(self, transactions):\n transactions = [Transaction(*transaction.split(',')) for transaction in transactions]\n transactions.sort(key=lambda t: t.time) # O(nlogn) time\n\n trans_indexes = defaultdict(list)\n for i, t in enumerate(transactions): # O(n) time\n trans_indexes[t.name].append(i)\n\n res = []\n for name, indexes in trans_indexes.items(): # O(n) time\n left = right = 0\n for i, t_index in enumerate(indexes):\n t = transactions[t_index]\n if (t.amount > 1000):\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n continue\n while left <= len(indexes)-2 and transactions[indexes[left]].time < t.time - 60: # O(60) time\n left += 1\n while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time\n right += 1\n for i in range(left,right+1): # O(120) time\n if transactions[indexes[i]].city != t.city:\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n break\n\n return res\n", + "title": "1169. Invalid Transactions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, invert the tree, and return its root . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]Output:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]Output:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 66.34%)\nclass Solution {\n public TreeNode invertTree(TreeNode root) {\n\n swap(root);\n return root;\n }\n\n private static void swap(TreeNode current) {\n if (current == null) {\n return;\n }\n\n swap(current.left);\n swap(current.right);\n\n TreeNode temp = current.left;\n current.left = current.right;\n current.right = temp;\n }\n}", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, invert the tree, and return its root . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]Output:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]Output:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7 ms (Top 98.3%) | Memory: 13.26 MB (Top 67.3%)\n\nclass Solution(object):\n def invertTree(self, root):\n # Base case...\n if root == None:\n return root\n # swapping process...\n root.left, root.right = root.right, root.left\n # Call the function recursively for the left subtree...\n self.invertTree(root.left)\n # Call the function recursively for the right subtree...\n self.invertTree(root.right)\n return root # Return the root...", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]Output:4Explanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tstatic int[][] dp;\n\n\tpublic int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n\t\tdp = new int[k + 1][profits.length + 1];\n\t\tfor (int[] row : dp) {\n\t\t\tArrays.fill(row, -1);\n\t\t}\n\t\treturn w + help(k, w, 0, profits, capital);\n\t}\n\n\tpublic int help(int k, int w, int i, int[] profits, int[] capital) {\n\t\tif (k == 0 || i >= profits.length)\n\t\t\treturn 0;\n\t\tif (dp[k][i] != -1)\n\t\t\treturn dp[k][i];\n\t\tint res = Integer.MIN_VALUE;\n\t\tif (capital[i] <= w) {\n\t\t\tres = Math.max(res, Math.max(profits[i] + help(k - 1, w + profits[i], i + 1, profits, capital),\n\t\t\t\t\thelp(k, w, i + 1, profits, capital)));\n\t\t} else {\n\t\t\tres = Math.max(res, help(k, w, i + 1, profits, capital));\n\t\t}\n\t\treturn dp[k][i] = res;\n\t}\n}\n", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]Output:4Explanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heappush, heappop, nlargest\nclass Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n if w >= max(capital):\n return w + sum(nlargest(k, profits))\n \n projects = [[capital[i],profits[i]] for i in range(len(profits))]\n projects.sort(key=lambda x: x[0])\n \n heap = []\n \n for i in range(k):\n while projects and projects[0][0] <= w:\n heappush(heap, -1*projects.pop(0)[1])\n \n if not heap:\n break\n p = -heappop(heap)\n w += p\n return w\n", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n public boolean isSubsequence(String s, String t) \n {\n int i,x,p=-1;\n if(s.length()>t.length())\n return false;\n for(i=0;ip)\n p=x;\n else\n return false;\n }\n return true;\n }\n}\n", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n if len(s) > len(t):return False\n if len(s) == 0:return True\n subsequence=0\n for i in range(0,len(t)):\n if subsequence <= len(s) -1:\n print(s[subsequence])\n if s[subsequence]==t[i]:\n\n subsequence+=1\n return subsequence == len(s) \n", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 100", + "grid[i][j] is 0 or 1 .", + "There is exactly one island in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]Output:16Explanation:The perimeter is the 16 yellow stripes in the image above.", + "image": "https://assets.leetcode.com/uploads/2018/10/12/island.png" + }, + { + "text": "Example 2: Input:grid = [[1]]Output:4", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 73.55%) | Memory: 62.3 MB (Top 52.61%)\nclass Solution {\n public int islandPerimeter(int[][] grid) {\n if(grid == null || grid.length == 0) return 0;\n\n int row=grid.length,col=grid[0].length;\n int perimeter=0;\n\n for(int i=0;i0 && grid[i-1][j]==1){\n perimeter-=2;\n }\n\n if(j>0 && grid[i][j-1]==1){\n perimeter-=2;\n }\n }\n\n }\n }\n return perimeter;\n }\n}", + "title": "463. Island Perimeter", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 100", + "grid[i][j] is 0 or 1 .", + "There is exactly one island in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]Output:16Explanation:The perimeter is the 16 yellow stripes in the image above.", + "image": "https://assets.leetcode.com/uploads/2018/10/12/island.png" + }, + { + "text": "Example 2: Input:grid = [[1]]Output:4", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 382 ms (Top 98.7%) | Memory: 16.57 MB (Top 93.9%)\n\nclass Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n perimeter = 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n perimeter += 4\n if i != 0 and grid[i-1][j] == 1:\n perimeter -= 2\n if j != 0 and grid[i][j-1] == 1:\n perimeter -= 2 \n \n return perimeter\n", + "title": "463. Island Perimeter", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , determine if they are isomorphic . Two strings s and t are isomorphic if the characters in s can be replaced to get t . All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "t.length == s.length", + "s and t consist of any valid ascii character." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"egg\", t = \"add\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"foo\", t = \"bar\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:s = \"paper\", t = \"title\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isIsomorphic(String s, String t) {\n \n ArrayListlist1 = new ArrayList<>();\n ArrayListlist2 = new ArrayList<>();\n for(int i=0;i bool:\n dict1={}\n m=\"\"\n\t\t#creating a dictionary by mapping each element from string S to string T\n for i,j in zip(s,t):\n\t\t# this for the cases like \"badc\" and \"baba\" so we dont want two keys mapping to same value hence we can reject directly\n if j in dict1.values() and i not in dict1.keys():\n return False\n dict1[i]=j \n \n\t\t#now take each letter from string s and using dictionary values replace it with that specific character\n for k in s:\n m=m+dict1[k]\n\t\t\t\n\t\t#now if newly formed string m == T is same then the strings are Isomorphic\n if(m==t):\n return True\n else:\n return False\n", + "title": "205. Isomorphic Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design the CombinationIterator class: Example 1:", + "description_images": [], + "constraints": [ + "CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.", + "next() Returns the next combination of length combinationLength in lexicographical order .", + "hasNext() Returns true if and only if there exists a next combination." + ], + "examples": [ + { + "text": "Example 1: Input[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]Output[null, \"ab\", true, \"ac\", true, \"bc\", false]ExplanationCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next(); // return \"ab\"\nitr.hasNext(); // return True\nitr.next(); // return \"ac\"\nitr.hasNext(); // return True\nitr.next(); // return \"bc\"\nitr.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "class CombinationIterator {\n\n private Queue allCombinations;\n public CombinationIterator(String characters, int combinationLength) {\n this.allCombinations = new LinkedList<>();\n generateAllCombinations(characters,0,combinationLength,new StringBuilder());\n }\n \n private void generateAllCombinations(String characters,int index,int combinationLength,StringBuilder currentString){\n \n if(currentString.length() == combinationLength){\n this.allCombinations.offer(currentString.toString());\n return;\n }\n \n for(int i = index ; i < characters.length() ; i++){\n currentString.append(characters.charAt(i));\n generateAllCombinations(characters,i+1,combinationLength,currentString);\n currentString.deleteCharAt(currentString.length()-1);\n }\n \n }\n \n public String next() {\n return this.allCombinations.poll();\n }\n \n public boolean hasNext() {\n return !this.allCombinations.isEmpty();\n }\n}\n", + "title": "1286. Iterator for Combination", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design the CombinationIterator class: Example 1:", + "description_images": [], + "constraints": [ + "CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.", + "next() Returns the next combination of length combinationLength in lexicographical order .", + "hasNext() Returns true if and only if there exists a next combination." + ], + "examples": [ + { + "text": "Example 1: Input[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]Output[null, \"ab\", true, \"ac\", true, \"bc\", false]ExplanationCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next(); // return \"ab\"\nitr.hasNext(); // return True\nitr.next(); // return \"ac\"\nitr.hasNext(); // return True\nitr.next(); // return \"bc\"\nitr.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 68.38%) | Memory: 20.00 MB (Top 5.53%)\n\nclass CombinationIterator:\n\n def __init__(self, characters: str, combinationLength: int):\n self.characters = characters\n self.n = len(characters)\n self.combinations = gen_combinations(self.n, combinationLength)\n self.ind = len(self.combinations) - 1\n\n def next(self) -> str:\n s = \"\"\n for i in range(self.n):\n if self.combinations[self.ind][i] != \"0\":\n s += self.characters[i]\n self.ind -= 1\n return s\n\n def hasNext(self) -> bool:\n return self.ind > -1 \n \ndef gen_combinations(l, n):\n end = int(\"1\" * l, 2)\n ans = []\n for i in range(end + 1):\n b = bin(i)[2:]\n if b.count('1') == n:\n ans.append(b.zfill(l))\n return ans\n", + "title": "1286. Iterator for Combination", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= jewels.length, stones.length <= 50", + "jewels and stones consist of only English letters.", + "All the characters of jewels are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:jewels = \"aA\", stones = \"aAAbbbb\"Output:3", + "image": null + }, + { + "text": "Example 2: Input:jewels = \"z\", stones = \"ZZ\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 31.57%) | Memory: 42.7 MB (Top 19.07%)\nclass Solution {\n public int numJewelsInStones(String jewels, String stones) {\n HashSet hs=new HashSet<>();\n int count=0;\n for(int i=0;i int:\n\t\t# 1 : One line solution, My best runtime 38 with 13.9 MB\n return sum(1 for k in stones if k in jewels)\n\t\t\n\t\t# 2 : Traditional solution\n\t\tx=0\n\t\tfor k in stones:\n\t\t\tif k in jewels:\n\t\t\t\tx+=1\n\t\treturn x\n", + "title": "771. Jewels and Stones", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]Output:trueExplanation:Jump 1 step from index 0 to 1, then 3 steps to the last index.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,0,4]Output:falseExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 67.02%) | Memory: 67.1 MB (Top 78.50%)\nclass Solution {\n public boolean canJump(int[] nums)\n {\n int maxjump = 0;\n for(int i=0;i bool:\n \"\"\"\n # Memoization + DFS Solution\n # TLE as we have as much as n decisions depending on nums[i] which could be\n # 10^5 as an uppercase according to problem constraints\n # better off with a greedy approach\n\n cache = {} # i : bool\n\n def dfs(i):\n if i == len(nums) -1:\n return True\n if nums[i] == 0:\n return False\n if i in cache:\n return cache[i]\n for j in range(1, nums[i] + 1):\n res = dfs(i + j)\n if res:\n cache[i] = True\n return cache[i]\n cache[i] = False\n return cache[i]\n\n return dfs(0)\n \"\"\"\n # Greedy Solution\n # Key with greedy is to find a local and gobal optimum\n # here we find the furthest distance we can travel with each index\n\n # futhest index reachable\n reachable = 0\n\n # iterate through all indexes and if the current index is futher than what we can travel return fasle\n for i in range(len(nums)):\n if i > reachable:\n return False\n\n reachable = max(reachable, nums[i] + i)\n # if the futherest distance we can jump to is greater or equal than the last index break\n if reachable >= len(nums) - 1:\n break\n\n return True", + "title": "55. Jump Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of non-negative integers nums , you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 82.01%) | Memory: 50 MB (Top 21.41%)\nclass Solution {\n\n public int jump(int[] nums) {\n\n int result = 0;\n\n int L = 0;\n int R = 0;\n\n while (R < nums.length - 1) {\n\n int localMaxRight = 0;\n\n for (int i=L; i<=R; i++) {\n\n localMaxRight = Math.max(i + nums[i], localMaxRight);\n }\n\n L = R + 1;\n R = localMaxRight;\n result++;\n }\n\n return result;\n }\n}", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of non-negative integers nums , you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 305 ms (Top 40.77%) | Memory: 15 MB (Top 90.04%)\nclass Solution(object):\n def jump(self, nums):\n ans = l = r = 0\n\n while r < len(nums) - 1:\n farthestJump = 0\n\n for i in range(l, r + 1):\n farthestJump = max(farthestJump, i + nums[i])\n\n l = r + 1\n r = farthestJump\n ans += 1\n\n return ans", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of non-negative integers arr , you are initially positioned at start index of the array. When you are at index i , you can jump to i + arr[i] or i - arr[i] , check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 5 * 10^4", + "0 <= arr[i] < arr.length", + "0 <= start < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,3,0,3,1,2], start = 5Output:trueExplanation:All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,2,3,0,3,1,2], start = 0Output:trueExplanation:One possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,0,2,1,2], start = 2Output:falseExplanation:There is no way to reach at index 1 with value 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReach(int[] arr, int start) {\n int n = arr.length;\n boolean[] vis = new boolean[n];\n Queue q = new LinkedList<>();\n q.add(start);\n while(!q.isEmpty()){\n int size = q.size();\n while(size-- > 0){\n int curr = q.poll();\n if(vis[curr])\n continue;\n if(arr[curr] == 0)\n return true;\n if(curr+arr[curr] < n)\n q.add(curr+arr[curr]);\n if(curr-arr[curr] >= 0)\n q.add(curr-arr[curr]);\n vis[curr] = true;\n }\n }\n return false;\n }\n}\n", + "title": "1306. Jump Game III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of non-negative integers arr , you are initially positioned at start index of the array. When you are at index i , you can jump to i + arr[i] or i - arr[i] , check if you can reach to any index with value 0. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 5 * 10^4", + "0 <= arr[i] < arr.length", + "0 <= start < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,3,0,3,1,2], start = 5Output:trueExplanation:All possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,2,3,0,3,1,2], start = 0Output:trueExplanation:One possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,0,2,1,2], start = 2Output:falseExplanation:There is no way to reach at index 1 with value 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n vis = [0]*len(arr)\n q = deque() \n q.append(start) \n while q:\n cur = q.popleft() \n print(cur)\n vis[cur] = 1\n if arr[cur] == 0:\n return True\n if cur+arr[cur]=0 and vis[cur-arr[cur]] == 0: \n q.append(cur-arr[cur]) \n return False\n\n ", + "title": "1306. Jump Game III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , you are initially positioned at the first index of the array. In one step you can jump from index i to index: Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i + 1 where: i + 1 < arr.length .", + "i - 1 where: i - 1 >= 0 .", + "j where: arr[i] == arr[j] and i != j ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [100,-23,-23,404,100,23,23,23,3,404]Output:3Explanation:You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7]Output:0Explanation:Start index is the last index. You do not need to jump.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,9,6,9,6,9,7]Output:1Explanation:You can jump directly from index 0 to index 7 which is last index of the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 147 ms (Top 48.60%) | Memory: 103.8 MB (Top 70.82%)\n/*\nHere we are using map and queue\nmap for storing the array elements and where are the other indices of the same element\nand queue for BFS\n\nInitially we start with 0 index\nSo we offer it to the queue\nNow until the queue is empty we have to do few things for a given position\ni> check the next index (i+1)\nii> check the previous index(i-1)\niii> check all the indices of the list whih are present in the map\nonce these three things have been done we will\nremove the element that is arr[i]\nbecause if we did not remove it we are going to do the same repeated task over and over again\nand this will result in stack overflow\nso it is important to remove the indices which have been visited once\nevery time we check the queue we incease the answer because viewing a queue means that\nwe are not at the last index\n\nI hope the idea was clear :) you'll understand better when you see the code\n*/\nclass Solution {\n public int minJumps(int[] arr) {\n int n = arr.length;\n\n if(n <= 1) return 0;\n Map> mp = new HashMap<>();\n for(int i = 0;i < arr.length ; i++) {\n if(!mp.containsKey(arr[i])) {\n mp.put(arr[i],new ArrayList<>());\n }\n List ls = mp.get(arr[i]);\n ls.add(i);\n }\n //System.out.print(mp);\n Queue q = new LinkedList<>();\n q.offer(0);\n int ans = 0;\n while(!q.isEmpty()) {\n ans++;\n int size = q.size();\n for(int i = 0;i < size;i++)\n {\n int j = q.poll();\n //adding j+1\n if(j+1 < n && mp.containsKey(arr[j+1])) {\n if(j+1 == n-1) return ans;\n q.offer(j+1);\n }\n //adding j-1\n if(j-1 > 0 && mp.containsKey(arr[j-1])) {\n q.offer(j-1);\n }\n\n //adding list indices\n if(mp.containsKey(arr[j])) {\n for(int k : mp.get(arr[j])) {\n //if(k == n-1) return ans;\n if(k != j) {\n if(k == n-1) return ans;\n q.offer(k);\n }\n }\n mp.remove(arr[j]);\n }\n }\n }\n return ans;\n }\n}", + "title": "1345. Jump Game IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , you are initially positioned at the first index of the array. In one step you can jump from index i to index: Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i + 1 where: i + 1 < arr.length .", + "i - 1 where: i - 1 >= 0 .", + "j where: arr[i] == arr[j] and i != j ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [100,-23,-23,404,100,23,23,23,3,404]Output:3Explanation:You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7]Output:0Explanation:Start index is the last index. You do not need to jump.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,9,6,9,6,9,7]Output:1Explanation:You can jump directly from index 0 to index 7 which is last index of the array.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import deque\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n minSteps = 0\n queue = deque()\n queue.append(0)\n n = len(arr)\n visited = set()\n visited.add(0)\n \n\t\td = {i:[] for i in arr}\n \n for i, val in enumerate(arr):\n d[val].append(i)\n \n while queue:\n for _ in range(len(queue)):\n idx = queue.popleft()\n if idx == n - 1:\n return minSteps\n \n for i in [*d[arr[idx]], idx - 1, idx + 1]:\n if i not in visited and 0 <= i < n:\n visited.add(i)\n queue.append(i)\n d[arr[idx]].clear()\n minSteps += 1\n", + "title": "1345. Jump Game IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr and an integer d . In one step you can jump from index i to index: In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j) ). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i + x where: i + x < arr.length and 0 < x <= d .", + "i - x where: i - x >= 0 and 0 < x <= d ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2Output:4Explanation:You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.", + "image": "https://assets.leetcode.com/uploads/2020/01/23/meta-chart.jpeg" + }, + { + "text": "Example 2: Input:arr = [3,3,3,3,3], d = 3Output:1Explanation:You can start at any index. You always cannot jump to any index.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,5,4,3,2,1], d = 1Output:7Explanation:Start at index 0. You can visit all the indicies.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 24.5%) | Memory: 43.52 MB (Top 29.6%)\n\nclass Solution {\n public int maxJumps(int[] arr, int d) {\n List jumpsFrom[] = new List[arr.length]; //find all possible jumps from each spot\n findJumps (arr,d,true,jumpsFrom); // add left jumps (itareting left to right)\n findJumps (arr,d,false,jumpsFrom); // add right jumps\n int jumpChain[] = new int[arr.length] , max = 1; // 0 - unvisited\n for (int i = 0 ; i < arr.length; i++) {\n if (jumpChain[i] == 0) {\n jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n max = Math.max(max, jumpChain[i]);\n }\n }\n return max;\n }\n\n private void findJumps(int[] arr, int d, boolean left , List jumpsFrom[]){\n Stack s = new Stack();\n int i = (left) ? 0 : arr.length - 1;\n while (i >=0 && i < arr.length){\n if (left) jumpsFrom[i] = new ArrayList();\n while (!s.isEmpty() && arr[i] > arr[s.peek()]){ // pop stack until higher step found from left/right, adding all left/right lower jumps from i\n int lowerIndex = s.pop(); \n if (Math.abs(i - lowerIndex) <= d) jumpsFrom[i].add(lowerIndex); \n else s = new Stack(); // past d steps\n }\n s.push(i);\n i += (left) ? 1 : -1;\n }\n }\n\n private int dfs(int[] arr , int jumpChain[], List jumpsFrom[], int start){\n int max = 1;\n for (int i: jumpsFrom[start]) {\n if (jumpChain[i] == 0) jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n max = Math.max (max , 1 + jumpChain[i]);\n }\n return max;\n }\n\n}", + "title": "1340. Jump Game V", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr and an integer d . In one step you can jump from index i to index: In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j) ). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "i + x where: i + x < arr.length and 0 < x <= d .", + "i - x where: i - x >= 0 and 0 < x <= d ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2Output:4Explanation:You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.", + "image": "https://assets.leetcode.com/uploads/2020/01/23/meta-chart.jpeg" + }, + { + "text": "Example 2: Input:arr = [3,3,3,3,3], d = 3Output:1Explanation:You can start at any index. You always cannot jump to any index.", + "image": null + }, + { + "text": "Example 3: Input:arr = [7,6,5,4,3,2,1], d = 1Output:7Explanation:Start at index 0. You can visit all the indicies.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n n = len(arr)\n sorted_arr = []\n for i in range(n):\n sorted_arr.append((arr[i], i))\n sorted_arr.sort(reverse = True)\n depth = [1 for i in range(n)]\n while(sorted_arr):\n val, i = sorted_arr.pop()\n for j in range(i-1, max(-1, i-d-1), -1):\n if(arr[j] >= arr[i]):\n break\n depth[i] = max(depth[j] + 1, depth[i])\n for j in range(i+1, min(n, i+d+1)):\n if(arr[j] >= arr[i]):\n break\n depth[i] = max(depth[j] + 1, depth[i])\n return max(depth)\n", + "title": "1340. Jump Game V", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums and an integer k . You are initially standing at index 0 . In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive . You want to reach the last index of the array (index n - 1 ). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,-2,4,-7,3], k = 2Output:7Explanation:You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,-5,-2,4,0,3], k = 3Output:17Explanation:You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-5,-20,4,-1,3,-6,-3], k = 2Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 93.03%) | Memory: 78 MB (Top 81.86%)\nclass Solution {\n public int maxResult(int[] nums, int k) {\n int n = nums.length, a = 0, b = 0;\n int[] deq = new int[n];\n deq[0] = n - 1;\n for (int i = n - 2; i >= 0; i--) {\n if (deq[a] - i > k) a++;\n nums[i] += nums[deq[a]];\n while (b >= a && nums[deq[b]] <= nums[i]) b--;\n deq[++b] = i;\n }\n return nums[0];\n }\n}", + "title": "1696. Jump Game VI", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and an integer k . You are initially standing at index 0 . In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive . You want to reach the last index of the array (index n - 1 ). Your score is the sum of all nums[j] for each index j you visited in the array. Return the maximum score you can get . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,-2,4,-7,3], k = 2Output:7Explanation:You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,-5,-2,4,0,3], k = 3Output:17Explanation:You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-5,-20,4,-1,3,-6,-3], k = 2Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 791 ms (Top 67.87%) | Memory: 30.60 MB (Top 42.3%)\n\nclass Solution:\n def maxResult(self, nums, k):\n deq, n = deque([0]), len(nums)\n\n for i in range(1, n):\n while deq and deq[0] < i - k: deq.popleft()\n nums[i] += nums[deq[0]] \n while deq and nums[i] >= nums[deq[-1]]: deq.pop()\n deq.append(i)\n \n return nums[-1]\n", + "title": "1696. Jump Game VI", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Return true if you can reach index s.length - 1 in s , or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "i + minJump <= j <= min(i + maxJump, s.length - 1) , and", + "s[j] == '0' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011010\", minJump = 2, maxJump = 3Output:trueExplanation:In the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \"01101110\", minJump = 2, maxJump = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canReach(String s, int minJump, int maxJump) {\n if(s.charAt(s.length() - 1) != '0')\n return false;\n \n Queue queue = new LinkedList<>();\n queue.add(0);\n \n // This variable tells us till which index we have processed\n int maxReach = 0;\n \n while(!queue.isEmpty()){\n int idx = queue.remove();\n // If we reached the last index\n if(idx == s.length() - 1)\n return true;\n \n // start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)]\n for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){\n if(s.charAt(j) == '0')\n queue.add(j);\n }\n \n // since we have processed till idx + maxJump so update maxReach to next index\n maxReach = Math.min(idx + maxJump + 1, s.length() - 1);\n }\n \n return false;\n }\n}\n", + "title": "1871. Jump Game VII", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Return true if you can reach index s.length - 1 in s , or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "i + minJump <= j <= min(i + maxJump, s.length - 1) , and", + "s[j] == '0' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011010\", minJump = 2, maxJump = 3Output:trueExplanation:In the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \"01101110\", minJump = 2, maxJump = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n\t\t# dp[i] represents whether i is reachable\n dp = [False for _ in s]\n dp[0] = True\n\n for i in range(1, len(s)):\n if s[i] == \"1\":\n continue\n\n\t\t\t# iterate through the solutions in range [i - maxJump, i - minJump]\n\t\t\t# and if any previous spot in range is reachable, then i is also reachable\n window_start = max(0, i - maxJump)\n window_end = i - minJump\n for j in range(window_start, window_end + 1):\n if dp[j]:\n dp[i] = True\n break\n \n return dp[-1] \n\n", + "title": "1871. Jump Game VII", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 < x i , y i < 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1Output:[[-2,2]]Explanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2Output:[[3,3],[-2,4]]Explanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n static class Distance {\n int i;\n int j;\n double dist;\n\n public Distance(int i, int j, double dist) {\n this.i = i;\n this.j = j;\n this.dist = dist;\n }\n }\n\n public int[][] kClosest(int[][] points, int k) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Double.compare(x.dist, y.dist));\n for(int[] point : points) {\n double dist = calcDistance(point[0], point[1]);\n pq.offer(new Distance(point[0], point[1], dist));\n }\n int cnt = 0;\n ArrayList l = new ArrayList<>();\n while(cnt < k) {\n Distance d = pq.poll();\n l.add(new int[]{d.i, d.j});\n cnt++;\n }\n int[][] res = l.toArray(new int[l.size()][]);\n return res;\n }\n\n private double calcDistance(int i, int j) {\n double dist = Math.sqrt(Math.pow(i,2) + Math.pow(j,2));\n return dist;\n }\n}", + "title": "973. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 < x i , y i < 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1Output:[[-2,2]]Explanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2Output:[[3,3],[-2,4]]Explanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2003 ms (Top 6.82%) | Memory: 20.5 MB (Top 21.33%)\n\ndef cal(ele):\n return ele[0]**2 +ele[1]**2\n\ndef partition(arr,start,end):\n # We must take a pivot element randomly to make Quick select work faster\n rdIdx = randint(start,end)\n arr[rdIdx],arr[end] = arr[end],arr[rdIdx]\n pivot = arr[end]\n i = start-1\n pivot_dis = cal(pivot)\n for j in range(start,end):\n if cal(arr[j]) <= pivot_dis:\n i+=1\n arr[j],arr[i] = arr[i],arr[j]\n\n arr[i+1],arr[end] = arr[end],arr[i+1]\n return i+1\ndef qSelect(arr,kth,start,end):\n if start < end:\n pv= partition(arr,start,end)\n # _______________________\n # | Left |ele| Right|\n # ------------------------\n # pv\n # after partition function call, pv is the index that sacrify:\n # all elements in Left will smaller than ele\n # all elements in Right side will greater than ele\n if pv == kth:#\n return\n if kth < pv:\n return qSelect(arr,kth,start,pv-1)\n else:\n return qSelect(arr,kth,pv+1,end)\n# Space O (logn) because of using recursion\n# Time: Average case: O(N)\n# Worst case: O(N**2)\nclass Solution:\n def kClosest(self, points, k):\n # print(points)\n qSelect(points,k-1,0,len(points)-1)# kth smallest number will be at (k-1) index in sorted array\n return points[:k]", + "title": "973. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and two integers k and p , return the number of distinct subarrays which have at most k elements divisible by p . Two arrays nums1 and nums2 are said to be distinct if: A subarray is defined as a non-empty contiguous sequence of elements in an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "They are of different lengths, or", + "There exists at least one index i where nums1[i] != nums2[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2,2], k = 2, p = 2Output:11Explanation:The elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 4, p = 1Output:10Explanation:All element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 84.38%) | Memory: 67.2 MB (Top 74.81%)\nclass Solution {\n public int countDistinct(int[] nums, int k, int p) {\n int n = nums.length;\n // we are storing hashcode for all the substrings so that we can compare them faster.\n // main goal is to avoid entire sub array comparision using hashcode.\n Set ways = new HashSet<>();\n for(int i = 0; i < n; i++) {\n int cnt = 0;\n long hc = 1; // this is the running hashcode for sub array [i...j]\n for(int j = i; j < n; j++) {\n hc = 199L * hc + nums[j]; // updating running hashcode, since we nums are <=200, we shall consider a prime near 200 to avoid collision\n if(nums[j] % p == 0)\n cnt++;\n if(cnt <= k) { // if current subarray [i...j] is valid, add its hashcode in our storage.\n ways.add(hc);\n }\n }\n }\n return ways.size();\n }\n}", + "title": "2261. K Divisible Elements Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and two integers k and p , return the number of distinct subarrays which have at most k elements divisible by p . Two arrays nums1 and nums2 are said to be distinct if: A subarray is defined as a non-empty contiguous sequence of elements in an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "They are of different lengths, or", + "There exists at least one index i where nums1[i] != nums2[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2,2], k = 2, p = 2Output:11Explanation:The elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 4, p = 1Output:10Explanation:All element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n n = len(nums) \n sub_arrays = set()\n \n\t\t# generate all combinations of subarray\n for start in range(n):\n cnt = 0\n temp = ''\n for i in range(start, n):\n if nums[i]%p == 0:\n cnt+=1 \n temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format \n if cnt>k: # check for termination \n break\n sub_arrays.add(temp) \n \n return len(sub_arrays)\n", + "title": "2261. K Divisible Elements Subarrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] ( inclusive ). You are further given an integer k . You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest) . If there are fewer than k reachable items within the price range, return all of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 represents a wall that you cannot pass through.", + "1 represents an empty cell that you can freely move to and from.", + "All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3Output:[[0,1],[1,1],[2,1]]Explanation:You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2Output:[[2,1],[1,2]]Explanation:You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3Output:[[2,1],[2,0]]Explanation:You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/example3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 88.06%) | Memory: 75.50 MB (Top 67.16%)\n\nclass Solution {\n public List> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n int low = pricing[0];\n int high = pricing[1];\n int n = grid.length;\n int m = grid[0].length;\n Queue q = new LinkedList<>();\n boolean[][] visited = new boolean[n][m];\n ArrayList list = new ArrayList<>();\n int dis = 0;\n q.add(new Pair(start[0], start[1], grid[start[0]][start[1]], 0));\n visited[start[0]][start[1]] = true;\n\t\t// normal bfs starts here.\n while (!q.isEmpty()) {\n int size = q.size();\n dis++;\n while (size-- > 0) {\n Pair p = q.remove();\n int x = p.x;\n int y = p.y;\n int val = p.val;\n\t\t\t\t// if nearby cells in range add that element to queue and mark the cell as visited.\n if (isInRange(x + 1, y, n, m, grid, visited, low, high)) {\n q.add(new Pair(x + 1, y, grid[x + 1][y], dis));\n visited[x + 1][y] = true;\n }\n if (isInRange(x - 1, y, n, m, grid, visited, low, high)) {\n q.add(new Pair(x - 1, y, grid[x - 1][y], dis));\n visited[x - 1][y] = true;\n }\n if (isInRange(x, y + 1, n, m, grid, visited, low, high)) {\n q.add(new Pair(x, y + 1, grid[x][y + 1], dis));\n visited[x][y + 1] = true;\n }\n if (isInRange(x, y - 1, n, m, grid, visited, low, high)) {\n q.add(new Pair(x, y - 1, grid[x][y - 1], dis));\n visited[x][y - 1] = true;\n }\n\t\t\t\t// add every element of queue to list.\n list.add(new Pair(p.x, p.y, p.val, p.dis));\n }\n }\n ArrayList list2 = new ArrayList<>();\n for(Pair p: list) {\n\t\t // remove the values from list if they are not in pricing range and add that to list2.\n if (p.val != 1 && p.val >= low && p.val <= high) {\n list2.add(new Pair(p.x, p.y, p.val, p.dis));\n }\n }\n\t\t// Most important part. Sorting the list2 on basis of the conditions given in question. Higher rank cells must be added first(before) in the list.\n Collections.sort(list2, new Comparator() {\n @Override\n public int compare(Pair p1, Pair p2) {\n\t\t\t // first check on basis of distance (high value, then add it before the second pair).\n if (p1.dis > p2.dis) {\n return 1;\n } else if (p1.dis < p2.dis) {\n return -1;\n } else {\n\t\t\t\t // if distances are equal, then second check on basis of value (high value, then add it before the second pair).\n if (p1.val > p2.val) {\n return 1;\n } else if (p1.val < p2.val) {\n return -1;\n } else {\n\t\t\t\t\t // if distances and values are equal, then third check on basis of x-coordinate (high value, then add it before the second pair).\n if (p1.x > p2.x) {\n return 1;\n } else if (p1.x < p2.x) {\n return -1;\n } else {\n\t\t\t\t\t\t // if distances, values and x-coordinate are equal, then fourth check on basis of y-coordinate (high value, then add it before the second pair).).\n if (p1.y > p2.y) {\n return 1;\n } else {\n return -1;\n }\n }\n }\n }\n }\n });\n List> ans = new ArrayList<>();\n\t\t// selecting only first k values from list2, and adding there x,y - coordinates in ans arraylist.\n for(Pair p: list2) {\n if (k == 0) {\n break;\n } \n k--;\n List temp = new ArrayList<>();\n temp.add(p.x);\n temp.add(p.y);\n ans.add(new ArrayList<>(temp));\n }\n return ans;\n }\n \n\t// check whether i, j is in range or not (ignore visited cells and cells with zero value)\n private boolean isInRange(int i, int j, int n, int m, int[][] grid, boolean[][] visited, int low, int high) {\n if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0 || visited[i][j]) {\n return false;\n }\n return true;\n }\n}\n\n// Pair class for x-coordinate, y-coordinate, grid value, distance from start point\nclass Pair {\n int x; int y; int val; int dis;\n \n public Pair(int x, int y, int val, int dis) {\n this.x = x;\n this.y = y;\n this.val = val;\n this.dis = dis;\n }\n}\n", + "title": "2146. K Highest Ranked Items Within a Price Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] ( inclusive ). You are further given an integer k . You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest) . If there are fewer than k reachable items within the price range, return all of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 represents a wall that you cannot pass through.", + "1 represents an empty cell that you can freely move to and from.", + "All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3Output:[[0,1],[1,1],[2,1]]Explanation:You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" + }, + { + "text": "Example 2: Input:grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2Output:[[2,1],[1,2]]Explanation:You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).", + "image": "https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" + }, + { + "text": "Example 3: Input:grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3Output:[[2,1],[2,0]]Explanation:You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/example3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3258 ms (Top 98.66%) | Memory: 66 MB (Top 18.12%)\nclass Solution:\n def highestRankedKItems(self, G, pricing, start, k):\n m, n = len(G), len(G[0])\n row, col = start\n node = (0, G[row][col], row, col)\n visited = set()\n visited.add((row, col))\n d = deque([node])\n ans = []\n\n while d:\n dist, cost, row, col = d.popleft()\n if pricing[0] <= cost <= pricing[1]:\n ans += [(dist, cost, row, col)]\n\n for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):\n if 0 <= x <= m-1 and 0 <= y <= n-1 and (x, y) not in visited and G[x][y] != 0:\n d.append((dist + 1, G[x][y], x, y))\n visited.add((x, y))\n\n ans = sorted(ans)\n\n return [[x, y] for _, _, x, y in ans[:k]]", + "title": "2146. K Highest Ranked Items Within a Price Range", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "For an integer array nums , an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j] . Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs . Since the answer can be huge, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 0Output:1Explanation:Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 1Output:2Explanation:The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 65.12%) | Memory: 47.8 MB (Top 52.38%)\nclass Solution {\n public int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[][] opt = new int[k + 1][n];\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0) {\n opt[i][j] = 1;\n } else if (j > 0) {\n opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD;\n if (i >= j + 1) {\n opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD;\n }\n }\n }\n }\n\n return opt[k][n - 1];\n }\n}", + "title": "629. K Inverse Pairs Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For an integer array nums , an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j] . Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs . Since the answer can be huge, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= k <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 0Output:1Explanation:Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, k = 1Output:2Explanation:The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 185 ms (Top 92.81%) | Memory: 17.30 MB (Top 67.63%)\n\nclass Solution:\n # A very good description of the dp solution is at\n # https://leetcode.com/problems/k-inverse-pairs-array/solution/ \n # The code below uses two 1D arrays--dp and tmp--instead if a \n # 2D array. tmp replaces dp after each i-iteration.\n def kInversePairs(self, n: int, k: int) -> int:\n dp, mod = [1]+[0] * k, 1000000007\n \n for i in range(n):\n tmp, sm = [], 0\n for j in range(k + 1):\n sm+= dp[j]\n if j-i >= 1: sm-= dp[j-i-1]\n sm%= mod\n tmp.append(sm)\n dp = tmp\n #print(dp) # <-- uncomment this line to get a sense of dp from the print output\n\t\t\t # try n = 6, k = 4; your answer should be 49.\n return dp[k]", + "title": "629. K Inverse Pairs Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array nums of n integers, and an integer k . The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k ( inclusive ). If there are less than k elements before or after the index i , then the k-radius average is -1 . Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i . The average of x elements is the sum of the x elements divided by x , using integer division . The integer division truncates toward zero, which means losing its fractional part. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the average of four elements 2 , 3 , 1 , and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75 , which truncates to 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,4,3,9,1,8,5,2,6], k = 3Output:[-1,-1,-1,5,4,4,-1,-1,-1]Explanation:- avg[0], avg[1], and avg[2] are -1 because there are less than k elementsbeforeeach index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Usinginteger division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elementsaftereach index.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/eg1.png" + }, + { + "text": "Example 2: Input:nums = [100000], k = 0Output:[100000]Explanation:- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.", + "image": null + }, + { + "text": "Example 3: Input:nums = [8], k = 100000Output:[-1]Explanation:- avg[0] is -1 because there are less than k elements before and after index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 10.87%) | Memory: 165.8 MB (Top 61.96%)\nclass Solution\n{\n public int[] getAverages(int[] nums, int k)\n {\n if(k == 0)\n return nums;\n\n int N = nums.length;\n long[] sum = new long[N];\n sum[0] = nums[0];\n\n for(int i = 1; i < N; i++)\n sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i]\n\n int[] ret = new int[N];\n Arrays.fill(ret,-1);\n\n for(int i = k; i < N-k; i++) // Beyond this range, there are less than k elements so -1\n {\n long temp = (sum[i+k]-sum[i-k]+nums[i-k])/(k*2+1);\n ret[i] = (int)temp;\n }\n return ret;\n }\n}", + "title": "2090. K Radius Subarray Averages", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array nums of n integers, and an integer k . The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k ( inclusive ). If there are less than k elements before or after the index i , then the k-radius average is -1 . Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i . The average of x elements is the sum of the x elements divided by x , using integer division . The integer division truncates toward zero, which means losing its fractional part. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the average of four elements 2 , 3 , 1 , and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75 , which truncates to 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,4,3,9,1,8,5,2,6], k = 3Output:[-1,-1,-1,5,4,4,-1,-1,-1]Explanation:- avg[0], avg[1], and avg[2] are -1 because there are less than k elementsbeforeeach index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Usinginteger division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elementsaftereach index.", + "image": "https://assets.leetcode.com/uploads/2021/11/07/eg1.png" + }, + { + "text": "Example 2: Input:nums = [100000], k = 0Output:[100000]Explanation:- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.", + "image": null + }, + { + "text": "Example 3: Input:nums = [8], k = 100000Output:[-1]Explanation:- avg[0] is -1 because there are less than k elements before and after index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1318 ms (Top 77.1%) | Memory: 35.26 MB (Top 20.0%)\n\nclass Solution:\n def getAverages(self, nums: list[int], k: int) -> list[int]:\n\n n, diam = len(nums), 2*k+1\n if n < diam: return [-1]*n\n\n ans = [-1]*k\n\n arr = list(accumulate(nums, initial = 0))\n\n for i in range(n-diam+1):\n ans.append((arr[i+diam]-arr[i])//diam)\n\n return ans + [-1]*k", + "title": "2090. K Radius Subarray Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3Output:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int mod = 1000000007;\n \n public int kadane(int[] a ){\n int curr = 0;\n int max = Integer.MIN_VALUE;\n for(int i: a )\n {\n curr+=i;\n if(curr<0 )\n curr =0;\n max = Math.max(max,curr );\n \n }\n \n return max%mod ;\n }\n public int kConcatenationMaxSum(int[] arr, int k) {\n \n int n = arr.length;\n if(k==1 ) \n return kadane(arr);\n int[] temp = new int[2*n]; \n for(int i=0;i=0 )\n return (int)( (kadane(temp)%mod)+ ((sum%mod) * (k-2)%mod) %mod);\n else\n return (kadane(temp)%mod );\n }\n}\n", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3Output:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n \n dp = [0] * len(arr) # sum of the best subarry ends at i\n dp[0] = arr[0]\n total = arr[0] # total sum \n right = arr[0] # sum of the best subarray starts at 0\n \n p = 1 \n while p < len(arr):\n dp[p] = max(arr[p], dp[p-1] + arr[p])\n total += arr[p] \n right = max(right, total)\n \n p += 1\n \n isolated = max(dp + [0]) # max sum\n left = dp[-1] # sum of the best subarray ends at n-1\n \n if k == 1:\n \n return isolated % (10**9 + 7)\n \n return max(left + right + max(0,(k-2) * total), isolated) % (10**9 + 7)\n", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr and an integer k , modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2] . Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0 . As the answer can be very large, return the answer modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= k <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2], k = 3Output:9", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,1], k = 5Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-2], k = 7Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kConcatenationMaxSum(self, nums: List[int], k: int) -> int:\n def maxSum(k):\n res = cur = 0\n for _ in range(k):\n for num in nums:\n cur = max(cur + num, num)\n res = max(res, cur)\n \n return res\n \n return (max(0, k - 2) * max(0, sum(nums)) + maxSum(min(2, k))) % (10 ** 9 + 7)", + "title": "1191. K-Concatenation Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2Output:2Explanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1Output:4Explanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0Output:1Explanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": " // O(n) Time Solution\n\n class Solution {\n \t\tpublic int findPairs(int[] nums, int k) {\n \t\t\tMap map = new HashMap();\n \t\t\tfor (int num : nums)\n \t\t\t\tmap.put(num, map.getOrDefault(num, 0) + 1);\n\n \t\t\tint result = 0;\n \t\t\tfor (int i : map.keySet())\n \t\t\t\tif (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)\n \t\t\t\t\tresult++;\n \t\t\treturn result;\n \t\t}\n \t}\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2Output:2Explanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1Output:4Explanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0Output:1Explanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n nums.sort()\n dict1={}\n s=0\n res=[]\n for n in nums:\n if dict1.get(n,None) is not None:\n res.append(n)\n dict1[n+k]=n\n res=list(set(res))\n return len(res)\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of unique k-diff pairs in the array . A k-diff pair is an integer pair (nums[i], nums[j]) , where the following are true: Notice that |val| denotes the absolute value of val . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= i, j < nums.length", + "i != j", + "nums[i] - nums[j] == k" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,1,5], k = 2Output:2Explanation:There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number ofuniquepairs.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], k = 1Output:4Explanation:There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,1,5,4], k = 0Output:1Explanation:There is one 0-diff pair in the array, (1, 1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n if k < 0:\n return 0\n \n # initialize hash table\n freq = {}\n for num in nums:\n freq[num] = freq.get(num, 0) + 1\n \n # iterate through array and find pairs\n count = 0\n for num in freq:\n if k == 0:\n if freq[num] > 1:\n count += 1\n else:\n if num + k in freq:\n count += 1\n \n # return count of unique pairs\n return count\n", + "title": "532. K-diff Pairs in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Strings s1 and s2 are k -similar (for some non-negative integer k ) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2 . Given two anagrams s1 and s2 , return the smallest k for which s1 and s2 are k -similar . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length <= 20", + "s2.length == s1.length", + "s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'} .", + "s2 is an anagram of s1 ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"ba\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abc\", s2 = \"bca\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kSimilarity(String s1, String s2) {\n HashSet vis = new HashSet<>();\n \n ArrayDeque queue = new ArrayDeque<>();\n int level = 0;\n queue.add(s1);\n \n while(queue.size() > 0){\n int size = queue.size();\n for(int i=0;i getNeighbors(String rem,String s2){\n ArrayList res = new ArrayList<>();\n \n int idx = -1;\n for(int i=0;i int:\n n = len(s1)\n \n def helper(i, curr, dp):\n if curr == s2:\n return 0\n \n if curr not in dp[i]:\n if curr[i] == s2[i]:\n dp[i][curr] = helper(i+1, curr, dp)\n else:\n temp = sys.maxsize\n for j in range(i+1, n):\n if curr[j] == s2[i]:\n temp = min(temp, 1+helper(i+1, curr[:i]+curr[j]+curr[i+1:j]+curr[i]+curr[j+1:], dp))\n\n dp[i][curr] = temp\n return dp[i][curr]\n \n dp = [{} for _ in range(n)]\n return helper(0, s1, dp)\n", + "title": "854. K-Similar Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers n and k , return the k th lexicographically smallest integer in the range [1, n] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13, k = 2Output:10Explanation:The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n \n def prefix(op,n):\n if op==n: return 1\n if int(op)>int(n): return 0\n for i in range(len(op)):\n if int(op[i])>int(n[i]): \n rem = len(n)-1-len(op)\n if not rem: return 1\n return 1+int(10*((1-10**rem)/-9))\n elif int(op[i])1:\n pref = prefix(str(ans),str(n)) \n if pref >= k:\n ans*=10; k-=1\n else: \n ans += 1; k-= pref\n \n return ans\n \n \n", + "title": "440. K-th Smallest in Lexicographical Order", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k . For every i and j where 0 <= i < j < arr.length , we consider the fraction arr[i] / arr[j] . Return the k th smallest fraction considered . Return your answer as an array of integers of size 2 , where answer[0] == arr[i] and answer[1] == arr[j] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 1000", + "1 <= arr[i] <= 3 * 10^4", + "arr[0] == 1", + "arr[i] is a prime number for i > 0 .", + "All the numbers of arr are unique and sorted in strictly increasing order.", + "1 <= k <= arr.length * (arr.length - 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,5], k = 3Output:[2,5]Explanation:The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,7], k = 1Output:[1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n vector kthSmallestPrimeFraction(vector& arr, int k) {\n priority_queue>, vector>>, greater>>> myHeap;\n for (int i=0; i mid + 1) {\n return invert(kthGrammar(n - 1, k - mid));\n } else {\n return 1;\n }\n }\n static int invert(int x) {\n if (x == 0) {\n return 1;\n }\n return 0;\n }\n}\n", + "title": "779. K-th Symbol in Grammar", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We build a table of n rows ( 1-indexed ). We start by writing 0 in the 1 st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01 , and each occurrence of 1 with 10 . Given two integer n and k , return the k th ( 1-indexed ) symbol in the n th row of a table of n rows. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for n = 3 , the 1 st row is 0 , the 2 nd row is 01 , and the 3 rd row is 0110 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 1Output:0Explanation:row 1:0", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 1Output:0Explanation:row 1: 0\nrow 2:01", + "image": null + }, + { + "text": "Example 3: Input:n = 2, k = 2Output:1Explanation:row 1: 0\nrow 2: 01", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solve(self,n,k):\n if n==1 and k==1:\n return 0 \n mid = pow(2,n-1)//2 \n if k<=mid:\n return self.solve(n-1,k) \n \n return not self.solve(n-1,k-mid)\n \n \n def kthGrammar(self,n,k):\n if self.solve(n,k):\n return 1 \n else:\n return 0 \n \n \n \n \n \n \n \n \n \n \n", + "title": "779. K-th Symbol in Grammar", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums . You are also given an integer original which is the first number that needs to be searched for in nums . You then do the following steps: Return the final value of original . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i], original <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,6,1,12], original = 3Output:24Explanation:- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9], original = 4Output:4Explanation:- 4 is not found in nums. Thus, 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public int findFinalValue(int[] nums, int original)\n {\n HashSet set = new HashSet<>();\n for(int i : nums)\n if(i >= original)\n set.add(i);\n while(true)\n if(set.contains(original))\n original *= 2;\n else\n break;\n return original;\n }\n}\n", + "title": "2154. Keep Multiplying Found Values by Two", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of integers nums . You are also given an integer original which is the first number that needs to be searched for in nums . You then do the following steps: Return the final value of original . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i], original <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,6,1,12], original = 3Output:24Explanation:- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9], original = 4Output:4Explanation:- 4 is not found in nums. Thus, 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findFinalValue(self, nums: List[int], original: int) -> int:\n while original in nums:\n original *= 2\n return original", + "title": "2154. Keep Multiplying Found Values by Two", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words , return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below . In the American keyboard : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "the first row consists of the characters \"qwertyuiop\" ,", + "the second row consists of the characters \"asdfghjkl\" , and", + "the third row consists of the characters \"zxcvbnm\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"Hello\",\"Alaska\",\"Dad\",\"Peace\"]Output:[\"Alaska\",\"Dad\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"omk\"]Output:[]", + "image": null + }, + { + "text": "Example 3: Input:words = [\"adsdf\",\"sfd\"]Output:[\"adsdf\",\"sfd\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.50 MB (Top 13.89%)\n\nclass Solution {\n public String[] findWords(String[] words) {\n String s1 = \"qwertyuiopQWERTYUIOP\";\n String s2 = \"asdfghjklASDFGHJKL\";\n String s3 = \"zxcvbnmZXCVBNM\"; \n ArrayList list = new ArrayList<>();\n for(int i=0;i List[str]:\n #\n set1 = {'q','w','e','r','t','y','u','i','o','p'}\n set2 = {'a','s','d','f','g','h','j','k','l'}\n set3 = {'z','x','c','v','b','n','m'}\n \n res = []\n for i in words:\n wordset = set(i.lower())\n if (wordset&set1 == wordset) or (wordset&set2 == wordset) or (wordset&set3 == wordset):\n res.append(i)\n return res\n", + "title": "500. Keyboard Row", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]Output:trueExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]Output:falseExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canVisitAllRooms(List> rooms) {\n \t\t boolean[] visited = new boolean[rooms.size()];\n \t\t visited[0]= true;\n \t\t for(int a:rooms.get(0))\n \t\t {\n \t\t\t if(!visited[a])\n \t\t\t {\n \t\t\t\t bfs(a, visited, rooms.size()-1, rooms);\n \t\t\t\t \n \t\t\t }\n \t\t }\n \t\t //System.out.println(\"arr -->>\"+Arrays.toString(visited));\n \t\tfor(boolean a:visited)\n \t\t{\n \t\t\tif(!a)\n \t\t\t\treturn false;\n \t\t}\n \t return true;\n \t \n \t }\n \t public void bfs(int key, boolean[] vivsted, int target,List> rooms)\n \t {\n \t\t\n \t\t\n \t\t vivsted[key] = true;\n \t\t for(int a:rooms.get(key))\n \t\t {\n \t\t\t if(!vivsted[a])\n \t\t\t {\n \t\t\t\t bfs(a, vivsted, target, rooms);\n \t\t\t }\n \t\t }\n \t\t \n \t\t \n \t\t\n \t }\n \n}", + "title": "841. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]Output:trueExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]Output:falseExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n # Create a set of for rooms visited\n visited_rooms = set()\n \n # Create a queue to do a breadth first search visiting rooms\n # Append the first room, 0, to the queue to begin the search\n queue = collections.deque()\n queue.append(0)\n \n # Perform the breadth first search with the queue\n while queue:\n for _ in range(0, len(queue)):\n # Search the room\n room_number = queue.popleft()\n \n # If we haven't visited the room, get the keys from the room\n if room_number not in visited_rooms:\n \n # Collect the keys from the room\n found_keys = rooms[room_number]\n \n # Add the keys to the queue so they can be tested\n for key in found_keys:\n queue.append(key)\n \n # Add the current room to the visited set\n visited_rooms.add(room_number)\n \n # If we visited all of the rooms, then the number of visited rooms should be\n # equal to the number of total rooms\n if len(visited_rooms) == len(rooms):\n return True\n \n return False\n", + "title": "841. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3Output:[true,true,true,false,true]Explanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1Output:[true,false,false,false,false]Explanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10Output:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.09%) | Memory: 42.9 MB (Top 55.32%)\nclass Solution {\n public List kidsWithCandies(int[] candies, int extraCandies) {\n Listresult = new ArrayList<>(candies.length); // better practice since the length is known\n int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1\n for (int i = 1; i= theHighest) or (candies[i] >= theHighest-extraCandies)\n int mathLogic = theHighest - extraCandies;\n for (int i = 0; i=10 or 6 >=10-5\n if (candies[i] >= mathLogic) {\n result.add(true);\n } else {\n result.add(false);\n }\n }\n return result;\n }\n}", + "title": "1431. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3Output:[true,true,true,false,true]Explanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1Output:[true,false,false,false,false]Explanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10Output:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kidsWithCandies(self, candy, extra):\n #create an array(res) with all values as True and it's lenght is same as candies\n res = [True]*len(candy)\n #iterate over the elements in the array candy\n for i in range(len(candy)):\n #if the no. of canides at curr position + extra is greater than or equal to the maximum of candies then continue \n if (candy[i] + extra) >= max(candy):\n continue\n #if not \n else:\n #change the value of that position in res as false\n res[i] = False\n #return the res list\n return res ", + "title": "1431. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The chess knight has a unique movement , it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L ). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n , return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n . All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:10Explanation:We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:20Explanation:All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]", + "image": null + }, + { + "text": "Example 3: Input:n = 3131Output:136006598Explanation:Please take care of the mod.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int knightDialer(int n) {\n var dp = new long[10];\n var tmp = new long[10];\n Arrays.fill(dp, 1);\n for (int i = 1; i < n; i++) {\n tmp[1] = dp[6]+dp[8];\n tmp[2] = dp[7]+dp[9];\n tmp[3] = dp[4]+dp[8];\n tmp[4] = dp[0]+dp[3]+dp[9];\n tmp[5] = 0;\n tmp[6] = dp[0]+dp[1]+dp[7];\n tmp[7] = dp[2]+dp[6];\n tmp[8] = dp[1]+dp[3];\n tmp[9] = dp[2]+dp[4];\n tmp[0] = dp[4]+dp[6];\n for (int j = 0; j < 10; j++) tmp[j] = tmp[j] % 1000000007;\n var arr = dp;\n dp = tmp;\n tmp = arr;\n }\n long res = 0;\n for (int i = 0; i < 10; i++) {\n res = (res+dp[i]) % 1000000007;\n }\n return (int)res;\n }\n}\n", + "title": "935. Knight Dialer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The chess knight has a unique movement , it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L ). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n , return how many distinct phone numbers of length n we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n . All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:10Explanation:We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:20Explanation:All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]", + "image": null + }, + { + "text": "Example 3: Input:n = 3131Output:136006598Explanation:Please take care of the mod.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 226 ms (Top 89.51%) | Memory: 16.80 MB (Top 56.81%)\n\nclass Solution:\n MOD = 10**9 + 7\n\n def knightDialer(self, n: int) -> int:\n # Initialize an array to store the possible positions of the knight on the phone pad\n cur_pos = [1] * 10\n\n # Loop through the number of jumps required\n for jump in range(2, n + 1):\n # Create a new list to store the updated positions after each jump\n new_pos = [0] * 10\n\n # Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % self.MOD\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % self.MOD\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % self.MOD\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % self.MOD\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % self.MOD\n new_pos[5] = 0 # Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % self.MOD\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % self.MOD\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % self.MOD\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % self.MOD\n\n # Update the current positions list for the next iteration\n cur_pos = new_pos\n\n # Calculate the total count of distinct phone numbers\n total_count = sum(cur_pos) % self.MOD\n\n return total_count\n", + "title": "935. Knight Dialer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed , so the top-left cell is (0, 0) , and the bottom-right cell is (n - 1, n - 1) . A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 25", + "0 <= k <= 100", + "0 <= row, column <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2, row = 0, column = 0Output:0.06250Explanation:There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 0, row = 0, column = 0Output:1.00000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double knightProbability(int n, int k, int row, int column) {\n double [][]curr=new double[n][n];\n double [][]next=new double[n][n];\n \n curr[row][column]=1;\n \n int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};\n for(int p=1;p<=k;p++){\n for(int i=0;i=n || nj>=n){\n continue;\n }\n \n next[ni][nj]+=curr[i][j]/8.0;\n }\n }\n }\n }\n \n curr=next;\n next=new double[n][n];\n }\n \n double sum=0.0;\n \n for(int i=0;i float:\n \n x_dir = [2, 1, -1, -2, -2, -1, 1, 2]\n y_dir = [1, 2, 2, 1, -1, -2, -2, -1]\n \n cache = {}\n \n def kMoves(i, j, moves):\n if i >= n or j >= n or i < 0 or j < 0:\n return 0\n \n if moves == k:\n return 1\n \n if (i, j, moves) in cache:\n return cache[(i, j, moves)]\n \n totMoves = 0\n for ind in range(8):\n totMoves += kMoves(i+x_dir[ind], j+y_dir[ind], moves+1)*(1/8)\n \n cache[(i, j, moves)] = totMoves\n return totMoves\n \n return kMoves(row, column, 0)\n", + "title": "688. Knight Probability in Chessboard", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8Output:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5Output:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minEatingSpeed(int[] piles, int h) {\n int max=0;\n int ans=0;\n for(int i=0;ipiles[i]/mid)\n time+=num+1;\n else\n time+=num;\n }\n if(time<=h)\n {\n ans=mid;\n right=mid-1;\n }\n else\n left=mid+1;\n }\n return ans;\n }\n}\n", + "title": "875. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8Output:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5Output:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 308 ms (Top 92.4%) | Memory: 17.82 MB (Top 76.3%)\n\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n def check(x):\n return sum(ceil(ele/x) for ele in piles) <= h\n\n l = 1\n r = max(piles)\n while l < r:\n mid = (l+r) >> 1\n if not check(mid):\n l=mid+1\n else:\n r=mid\n return l", + "title": "875. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of i th node. The root of the tree is node 0 . Find the k th ancestor of a given node. The k th ancestor of a tree node is the k th node in the path from that node to the root node. Implement the TreeAncestor class: Example 1:", + "description_images": [], + "constraints": [ + "TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.", + "int getKthAncestor(int node, int k) return the k th ancestor of the given node node . If there is no such ancestor, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]Output[null, 1, 0, -1]ExplanationTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor", + "image": "https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 96 ms (Top 79.04%) | Memory: 112.4 MB (Top 41.18%)\nclass TreeAncestor {\n int n;\n int[] parent;\n List[] nodeInPath;\n int[] nodeIdxInPath;\n\n public TreeAncestor(int n, int[] parent) {\n this.n = n;\n this.parent = parent;\n nodeInPath = new ArrayList[n];\n nodeIdxInPath = new int[n];\n fill();\n }\n\n private void fill() {\n boolean[] inner = new boolean[n];\n for (int i = 1; i < n; i++) {\n inner[parent[i]] = true;\n }\n\n for (int i = 1; i < n; i++) {\n if (inner[i] || nodeInPath[i] != null) {\n continue;\n }\n List path = new ArrayList<>();\n int k = i;\n while (k != -1) {\n path.add(k);\n k = parent[k];\n }\n int m = path.size();\n for (int j = 0; j < m; j++) {\n int node = path.get(j);\n if (nodeInPath[node] != null) break;\n nodeInPath[node] = path;\n nodeIdxInPath[node] = j;\n }\n }\n }\n\n public int getKthAncestor(int node, int k) {\n List path = nodeInPath[node];\n int idx = nodeIdxInPath[node] + k;\n return idx >= path.size() ? -1 : path.get(idx);\n }\n}", + "title": "1483. Kth Ancestor of a Tree Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of i th node. The root of the tree is node 0 . Find the k th ancestor of a given node. The k th ancestor of a tree node is the k th node in the path from that node to the root node. Implement the TreeAncestor class: Example 1:", + "description_images": [], + "constraints": [ + "TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.", + "int getKthAncestor(int node, int k) return the k th ancestor of the given node node . If there is no such ancestor, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]Output[null, 1, 0, -1]ExplanationTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor", + "image": "https://assets.leetcode.com/uploads/2019/08/28/1528_ex1.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2359 ms (Top 39.76%) | Memory: 44.3 MB (Top 93.27%)\nfrom math import ceil, log2\nfrom typing import List\n\nNO_PARENT = -1\n\nclass TreeAncestor:\n def __init__(self, n: int, parent: List[int]):\n self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]\n self.__initialize(parent)\n\n def __initialize(self, parent: List[int]):\n self.parent[0], prev = parent, parent\n\n for jump_pow in range(1, len(self.parent)):\n cur = self.parent[jump_pow]\n\n for i, p in enumerate(prev):\n if p != NO_PARENT:\n cur[i] = prev[p]\n\n prev = cur\n\n def getKthAncestor(self, node: int, k: int) -> int:\n jump_pow = self.jump_pow\n\n while k > 0 and node != NO_PARENT:\n jumps = 1 << jump_pow\n\n if k >= jumps:\n node = self.parent[jump_pow][node]\n k -= jumps\n else:\n jump_pow -= 1\n\n return node\n\n @property\n def jump_pow(self) -> int:\n return len(self.parent) - 1", + "title": "1483. Kth Ancestor of a Tree Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr , and an integer k , return the k th distinct string present in arr . If there are fewer than k distinct strings, return an empty string \"\" . Note that the strings are considered in the order in which they appear in the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= arr.length <= 1000", + "1 <= arr[i].length <= 5", + "arr[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2Output:\"a\"Explanation:The only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1stdistinct string.\n\"a\" appears 2nd, so it is the 2nddistinct string.\nSince k == 2, \"a\" is returned.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"aaa\",\"aa\",\"a\"], k = 1Output:\"aaa\"Explanation:All strings in arr are distinct, so the 1ststring \"aaa\" is returned.", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"a\",\"b\",\"a\"], k = 3Output:\"\"Explanation:The only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 99.0%) | Memory: 43.48 MB (Top 20.1%)\n\nclass Solution {\n public String kthDistinct(String[] arr, int k) {\n Map map=new HashMap<>();\n \n for(String s:arr){\n \n if(map.containsKey(s)) map.put(s,map.get(s)+1);\n else map.put(s,1);\n }\n\t\tint i=0;\n for(String s:arr){\n if(map.get(s)==1 && ++i==k){\n \n return s;\n } \n \n }\n return \"\";\n \n }\n}", + "title": "2053. Kth Distinct String in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A distinct string is a string that is present only once in an array. Given an array of strings arr , and an integer k , return the k th distinct string present in arr . If there are fewer than k distinct strings, return an empty string \"\" . Note that the strings are considered in the order in which they appear in the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= arr.length <= 1000", + "1 <= arr[i].length <= 5", + "arr[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2Output:\"a\"Explanation:The only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1stdistinct string.\n\"a\" appears 2nd, so it is the 2nddistinct string.\nSince k == 2, \"a\" is returned.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"aaa\",\"aa\",\"a\"], k = 1Output:\"aaa\"Explanation:All strings in arr are distinct, so the 1ststring \"aaa\" is returned.", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"a\",\"b\",\"a\"], k = 3Output:\"\"Explanation:The only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n hash_map = {}\n for string in arr:\n hash_map[string] = hash_map.get(string, 0) + 1\n for string in arr:\n if hash_map[string] == 1:\n k -= 1\n if k == 0:\n return string\n return \"\"\n", + "title": "2053. Kth Distinct String in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a class to find the k th largest element in a stream. Note that it is the k th largest element in the sorted order, not the k th distinct element. Implement KthLargest class: Example 1:", + "description_images": [], + "constraints": [ + "KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums .", + "int add(int val) Appends the integer val to the stream and returns the element representing the k th largest element in the stream." + ], + "examples": [ + { + "text": "Example 1: Input[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]Output[null, 4, 5, 5, 8, 8]ExplanationKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3); // return 4\nkthLargest.add(5); // return 5\nkthLargest.add(10); // return 5\nkthLargest.add(9); // return 8\nkthLargest.add(4); // return 8", + "image": null + } + ], + "follow_up": null, + "solution": "class KthLargest {\n PriorityQueue queue=new PriorityQueue();\n int k=0;\n public KthLargest(int k, int[] nums) {\n this.k=k;\n for(int i:nums)\n add(i);\n }\n \n public int add(int val) {\n if(k>queue.size())\n queue.add(val);\n else\n if(val>queue.peek())\n {\n queue.poll();\n queue.add(val);\n }\n return queue.peek();\n }\n}\n", + "title": "703. Kth Largest Element in a Stream", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a class to find the k th largest element in a stream. Note that it is the k th largest element in the sorted order, not the k th distinct element. Implement KthLargest class: Example 1:", + "description_images": [], + "constraints": [ + "KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums .", + "int add(int val) Appends the integer val to the stream and returns the element representing the k th largest element in the stream." + ], + "examples": [ + { + "text": "Example 1: Input[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]Output[null, 4, 5, 5, 8, 8]ExplanationKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3); // return 4\nkthLargest.add(5); // return 5\nkthLargest.add(10); // return 5\nkthLargest.add(9); // return 8\nkthLargest.add(4); // return 8", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 143 ms (Top 61.21%) | Memory: 18.3 MB (Top 46.75%)\nclass KthLargest:\n def __init__(self, k: int, nums: List[int]):\n self.k = k\n self.hp = []\n for x in nums:\n self.add(x)\n\n return None\n\n def add(self, val: int) -> int:\n heapq.heappush(self.hp, (val))\n if len(self.hp) > self.k:\n heapq.heappop(self.hp)\n\n return self.get_kth_largest()\n\n def get_kth_largest(self):\n return self.hp[0]", + "title": "703. Kth Largest Element in a Stream", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. You must solve it in O(n) time complexity. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,5,6,4], k = 2Output:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,3,1,2,4,5,5,6], k = 4Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n nums.sort(reverse = True)\n return nums[k-1]", + "title": "215. Kth Largest Element in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of positive integers sorted in a strictly increasing order , and an integer k . Return the k th positive integer that is missing from this array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000", + "1 <= k <= 1000", + "arr[i] < arr[j] for 1 <= i < j <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,3,4,7,11], k = 5Output:9Explanation:The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5thmissing positive integer is 9.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,3,4], k = 2Output:6Explanation:The missing positive integers are [5,6,7,...]. The 2ndmissing positive integer is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthPositive(int[] arr, int k) {\n if(arr[0] > k) {\n return k;\n }\n \n for(int i=0; i int:\n arr = set(arr)\n i = 0\n missed = 0\n while missed != k:\n i += 1\n if i not in arr:\n missed += 1\n return i", + "title": "1539. Kth Missing Positive Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1Output:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3Output:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.10 MB (Top 76.35%)\n\nclass Solution {\n private int count = 0;\n private int result = 0;\n\n public int kthSmallest(TreeNode root, int k) {\n inorderTraversal(root, k);\n return result;\n }\n\n private void inorderTraversal(TreeNode node, int k) {\n if (node == null || count >= k) {\n return;\n }\n\n inorderTraversal(node.left, k);\n\n count++;\n if (count == k) {\n result = node.val;\n return;\n }\n\n inorderTraversal(node.right, k);\n }\n}\n", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1Output:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3Output:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 42.71%) | Memory: 18.1 MB (Top 15.27%)\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n n=0\n stack=[] # to store the elements\n cur=root # pointer to iterate\n while cur or stack:\n while cur: # used to find the left most element\n stack.append(cur)\n cur=cur.left\n cur=stack.pop() # pop the most recent element which will be the least value at that moment\n n+=1\n if n==k:\n return cur.val\n cur=cur.right", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the k th smallest element in the matrix . Note that it is the k th smallest element in the sorted order , not the k th distinct element. You must find a solution with a memory complexity better than O(n 2 ) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 300", + "-10^9 <= matrix[i][j] <= 10^9", + "All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order .", + "1 <= k <= n 2" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8Output:13Explanation:The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8thsmallest number is 13", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[-5]], k = 1Output:-5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Using PriorityQueue\n *\n * Time Complexity:\n * O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.\n * If we were adding all elements in one go, then the complexity would be O(min(N,K))\n * Refer: https://stackoverflow.com/a/34697891\n * O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.\n * Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))\n *\n * Space Complexity: O(min(N, K))\n *\n * N = Length of one side of the matrix. K = input value k.\n */\nclass Solution {\n public int kthSmallest(int[][] matrix, int k) {\n if (matrix == null || k <= 0) {\n throw new IllegalArgumentException(\"Input is invalid\");\n }\n\n int n = matrix.length;\n if (k > n * n) {\n throw new NoSuchElementException(\"k is greater than number of elements in matrix\");\n }\n if (k == 1) {\n return matrix[0][0];\n }\n if (k == n * n) {\n return matrix[n - 1][n - 1];\n }\n\n PriorityQueue queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));\n\n for (int i = 0; i < Math.min(n, k); i++) {\n queue.offer(new int[] { i, 0 });\n }\n while (k > 1) {\n int[] cur = queue.poll();\n if (cur[1] < n - 1) {\n cur[1]++;\n queue.offer(cur);\n }\n k--;\n }\n\n return matrix[queue.peek()[0]][queue.peek()[1]];\n }\n}\n", + "title": "378. Kth Smallest Element in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the k th smallest element in the matrix . Note that it is the k th smallest element in the sorted order , not the k th distinct element. You must find a solution with a memory complexity better than O(n 2 ) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 300", + "-10^9 <= matrix[i][j] <= 10^9", + "All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order .", + "1 <= k <= n 2" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8Output:13Explanation:The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8thsmallest number is 13", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[-5]], k = 1Output:-5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 281 ms (Top 5.06%) | Memory: 22.00 MB (Top 9.58%)\n\nclass Solution:\n def kthSmallest(self, matrix, k):\n n, beg, end = len(matrix), matrix[0][0], matrix[-1][-1]\n \n def check(m):\n i, j, cnt = 0, n-1, 0\n for i in range(n):\n while j >= 0 and matrix[i][j] > m: j -= 1\n cnt += (j + 1)\n return cnt\n \n while beg < end:\n mid = (beg + end)//2\n if check(mid) < k:\n beg = mid + 1\n else:\n end = mid\n \n return beg\n", + "title": "378. Kth Smallest Element in a Sorted Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Bob is standing at cell (0, 0) , and he wants to reach destination : (row, column) . He can only travel right and down . You are going to help Bob by providing instructions for him to reach destination . The instructions are represented as a string, where each character is either: Multiple instructions will lead Bob to destination . For example, if destination is (2, 3) , both \"HHHVV\" and \"HVHVH\" are valid instructions . However, Bob is very picky. Bob has a lucky number k , and he wants the k th lexicographically smallest instructions that will lead him to destination . k is 1-indexed . Given an integer array destination and an integer k , return the k th lexicographically smallest instructions that will take Bob to destination . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/12/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/12/ex2.png", + "https://assets.leetcode.com/uploads/2020/10/12/ex3.png" + ], + "constraints": [ + "'H' , meaning move horizontally (go right ), or", + "'V' , meaning move vertically (go down )." + ], + "examples": [ + { + "text": "Example 1: Input:destination = [2,3], k = 1Output:\"HHHVV\"Explanation:All the instructions that reach (2, 3) in lexicographic order are as follows:\n[\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].", + "image": null + }, + { + "text": "Example 2: Input:destination = [2,3], k = 2Output:\"HHVHV\"", + "image": null + }, + { + "text": "Example 3: Input:destination = [2,3], k = 3Output:\"HHVVH\"", + "image": null + } + ], + "follow_up": null, + "solution": "from math import comb\nclass Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n i,j = destination\n \n @lru_cache(None)\n def helper(i,j,k):\n if k == 1:\n return \"H\"*j+\"V\"*i\n else:\n horizontal = comb(i+j-1,j-1)\n if k <= horizontal:\n return \"H\" + helper(i,j-1,k)\n else:\n return \"V\" + helper(i-1,j,k-horizontal)\n \n return helper(i,j,k)\n", + "title": "1643. Kth Smallest Instructions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Nearly everyone has used the Multiplication Table . The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j ( 1-indexed ). Given three integers m , n , and k , return the k th smallest element in the m x n multiplication table . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 3 * 10^4", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, k = 5Output:3Explanation:The 5thsmallest number is 3.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg" + }, + { + "text": "Example 2: Input:m = 2, n = 3, k = 6Output:6Explanation:The 6thsmallest number is 6.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthNumber(int m, int n, int k) {\n int lo = 1;\n int hi = m * n;\n \n while(lo < hi){\n int mid = lo + (hi - lo) / 2;\n \n if(count(mid, m, n) < k){\n lo = mid + 1;\n } else if(count(mid, m, n) >= k){\n hi = mid;\n }\n }\n return lo;\n }\n private int count(int mid, int m, int n){\n int ans = 0;\n for(int i = 1; i <= m; i++){\n int res = Math.min(mid / i, n);\n ans += res;\n }\n return ans;\n }\n}\n", + "title": "668. Kth Smallest Number in Multiplication Table", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Nearly everyone has used the Multiplication Table . The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j ( 1-indexed ). Given three integers m , n , and k , return the k th smallest element in the m x n multiplication table . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 3 * 10^4", + "1 <= k <= m * n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, k = 5Output:3Explanation:The 5thsmallest number is 3.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg" + }, + { + "text": "Example 2: Input:m = 2, n = 3, k = 6Output:6Explanation:The 6thsmallest number is 6.", + "image": "https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 593 ms (Top 63.06%) | Memory: 17.30 MB (Top 29.73%)\n\nclass Solution:\n def findKthNumber(self, m, n, k):\n def count(x):\n return sum(min(x//i, n) for i in range(1,m+1))\n\t\t\t\n L, R, mid, ans = 0, m*n, 0, 0\n while L <= R:\n mid = (L + R) >> 1\n if count(mid) < k:\n L = mid + 1\n else:\n R, ans = mid - 1, mid\n return ans\n", + "title": "668. Kth Smallest Number in Multiplication Table", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 5 * 10^4", + "-10^5 <= nums1[i], nums2[j] <= 10^5", + "1 <= k <= nums1.length * nums2.length", + "nums1 and nums2 are sorted." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,5], nums2 = [3,4], k = 2Output:8Explanation:The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2ndsmallest product is 8.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6Output:0Explanation:The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6thsmallest product is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3Output:-6Explanation:The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rdsmallest product is -6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 740 ms (Top 67.46%) | Memory: 89.4 MB (Top 63.10%)\nclass Solution {\n static long INF = (long) 1e10;\n public long kthSmallestProduct(int[] nums1, int[] nums2, long k) {\n int m = nums1.length, n = nums2.length;\n long lo = -INF - 1, hi = INF + 1;\n while (lo < hi) {\n long mid = lo + ((hi - lo) >> 1), cnt = 0;\n for (int i : nums1) {\n if (0 <= i) {\n int l = 0, r = n - 1, p = 0;\n while (l <= r) {\n int c = l + ((r - l) >> 1);\n long mul = i * (long) nums2[c];\n if (mul <= mid) {\n p = c + 1;\n l = c + 1;\n } else r = c - 1;\n }\n cnt += p;\n } else {\n int l = 0, r = n - 1, p = 0;\n while (l <= r) {\n int c = l + ((r - l) >> 1);\n long mul = i * (long) nums2[c];\n if (mul <= mid) {\n p = n - c;\n r = c - 1;\n } else l = c + 1;\n }\n cnt += p;\n }\n }\n if (cnt >= k) {\n hi = mid;\n } else lo = mid + 1L;\n }\n return lo;\n }\n}", + "title": "2040. Kth Smallest Product of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 5 * 10^4", + "-10^5 <= nums1[i], nums2[j] <= 10^5", + "1 <= k <= nums1.length * nums2.length", + "nums1 and nums2 are sorted." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,5], nums2 = [3,4], k = 2Output:8Explanation:The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2ndsmallest product is 8.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6Output:0Explanation:The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6thsmallest product is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3Output:-6Explanation:The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rdsmallest product is -6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n result = []\n for i in range(len(nums1)):\n for j in range(len(nums2)):\n temp = nums1[i]*nums2[j]\n result.append(temp)\n result.sort()\n return result[k-1]\n", + "title": "2040. Kth Smallest Product of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D grid of 0 s and 1 s, return the number of elements in the largest square subgrid that has all 1 s on its border , or 0 if such a subgrid doesn't exist in the grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= grid.length <= 100", + "1 <= grid[0].length <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]Output:9", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1,0,0]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largest1BorderedSquare(int[][] grid) {\n int m=grid.length;\n int n=grid[0].length;\n\t\t// rows[r][c] is the length of the line ended at [r,c] on row r\n int[][] rows=new int[m][n]; \n\t\t// the length of the line ended at [r,c] on colume c\n int[][] cols=new int[m][n];\n int res=0;\n for(int r=0;r=rows[r][c]||res>=cols[r][c]){\n continue;\n }\n res=Math.max(res,getD(rows,cols,r,c));\n }\n }\n }\n return res*res;\n }\n \n\t// get the dimension of the largest square which bottom-right point is [row,col]\n private int getD(int[][] rows,int[][] cols,int row,int col){\n int len=Math.min(rows[row][col],cols[row][col]);\n for(int i=len-1;i>=0;i--){\n if(rows[row-i][col]>i && cols[row][col-i]>i){\n return i+1;\n }\n }\n return 1;\n }\n}\n", + "title": "1139. Largest 1-Bordered Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid of 0 s and 1 s, return the number of elements in the largest square subgrid that has all 1 s on its border , or 0 if such a subgrid doesn't exist in the grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= grid.length <= 100", + "1 <= grid[0].length <= 100", + "grid[i][j] is 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]Output:9", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1,0,0]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1382 ms (Top 13.45%) | Memory: 15.1 MB (Top 9.94%)\nclass Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)]\n for i in range(m):\n for j in range(n):\n if i > 0:\n if grid[i][j] == 1:\n dp[i][j][1] = dp[i - 1][j][1] + 1\n if j > 0:\n if grid[i][j] == 1:\n dp[i][j][0] = dp[i][j - 1][0] + 1\n for i in range(m - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n if i < m - 1:\n if grid[i][j] == 1:\n dp[i][j][2] = dp[i + 1][j][2] + 1\n if j < n - 1:\n if grid[i][j] == 1:\n dp[i][j][3] = dp[i][j + 1][3] + 1\n mside = min(m, n)\n for l in range(mside - 1, -1, -1):\n for i in range(m - l):\n for j in range(n - l):\n if min(dp[i][j][2], dp[i][j][3], dp[i + l][j + l][0], dp[i + l][j + l][1]) >= l + 1:\n return (l + 1) * (l + 1)\n return 0", + "title": "1139. Largest 1-Bordered Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num representing a large integer. An integer is good if it meets the following conditions: Return the maximum good integer as a string or an empty string \"\" if no such integer exists . Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is a substring of num with length 3 .", + "It consists of only one unique digit." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"6777133339\"Output:\"777\"Explanation:There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".", + "image": null + }, + { + "text": "Example 2: Input:num = \"2300019\"Output:\"000\"Explanation:\"000\" is the only good integer.", + "image": null + }, + { + "text": "Example 3: Input:num = \"42352338\"Output:\"\"Explanation:No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public String largestGoodInteger(String num)\n {\n String ans = \"\";\n for(int i = 2; i < num.length(); i++)\n if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2))\n if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is larger\n ans = num.substring(i-2,i+1);\n return ans;\n }\n}\n", + "title": "2264. Largest 3-Same-Digit Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num representing a large integer. An integer is good if it meets the following conditions: Return the maximum good integer as a string or an empty string \"\" if no such integer exists . Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is a substring of num with length 3 .", + "It consists of only one unique digit." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"6777133339\"Output:\"777\"Explanation:There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".", + "image": null + }, + { + "text": "Example 2: Input:num = \"2300019\"Output:\"000\"Explanation:\"000\" is the only good integer.", + "image": null + }, + { + "text": "Example 3: Input:num = \"42352338\"Output:\"\"Explanation:No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestGoodInteger(self, n: str) -> str:\n return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else \"\" for i in range(2, len(n)))\n", + "title": "2264. Largest 3-Same-Digit Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1 . You are given a string colors where colors[i] is a lowercase English letter representing the color of the i th node in this graph ( 0-indexed ). You are also given a 2D array edges where edges[j] = [a j , b j ] indicates that there is a directed edge from node a j to node b j . A valid path in the graph is a sequence of nodes x 1 -> x 2 -> x 3 -> ... -> x k such that there is a directed edge from x i to x i+1 for every 1 <= i < k . The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/21/leet1.png", + "https://assets.leetcode.com/uploads/2021/04/21/leet2.png" + ], + "constraints": [ + "n == colors.length", + "m == edges.length", + "1 <= n <= 10^5", + "0 <= m <= 10^5", + "colors consists of lowercase English letters.", + "0 <= a j , b j < n" + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]Output:3Explanation:The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored\"a\" (red in the above image).", + "image": null + }, + { + "text": "Example 2: Input:colors = \"a\", edges = [[0,0]]Output:-1Explanation:There is a cycle from 0 to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int max;\n private Map> memo;\n private boolean hasCycle;\n \n public int largestPathValue(String colors, int[][] edges) { \n Map> map = new HashMap<>();\n \n for(int edge[] : edges) {\n List list = map.getOrDefault(edge[0], new ArrayList<>());\n list.add(edge[1]);\n map.put(edge[0], list);\n }\n \n max = -1;\n memo = new HashMap<>();\n \n boolean visited[] = new boolean[colors.length()];\n hasCycle = false;\n \n for(int i = 0; i < colors.length(); i++) {\n dfs(i, map, colors, visited);\n \n if(hasCycle) {\n return -1;\n }\n }\n \n return max;\n }\n \n private Map dfs(int curr, Map> map, String colors, boolean visited[]) {\n if(visited[curr]) {\n hasCycle = true;\n return new HashMap<>();\n }\n \n if(memo.get(curr) != null) {\n return memo.get(curr);\n }\n \n visited[curr] = true;\n List list = map.get(curr);\n Map currMap = new HashMap<>();\n \n if(list != null && !list.isEmpty()) {\n for(int i : list) {\n Map resMap = dfs(i, map, colors, visited);\n \n if(hasCycle) {\n return currMap;\n }\n \n for(char c : resMap.keySet()) {\n int val = resMap.get(c);\n int currVal = currMap.getOrDefault(c, 0);\n currVal = Math.max(currVal, val);\n currMap.put(c, currVal);\n max = Math.max(currVal, max);\n }\n }\n }\n \n int currentNodeColorCount = currMap.getOrDefault(colors.charAt(curr), 0);\n currMap.put(colors.charAt(curr), currentNodeColorCount + 1);\n \n max = Math.max(currentNodeColorCount + 1, max);\n \n visited[curr] = false;\n memo.put(curr, currMap);\n return currMap;\n }\n}", + "title": "1857. Largest Color Value in a Directed Graph", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1 . You are given a string colors where colors[i] is a lowercase English letter representing the color of the i th node in this graph ( 0-indexed ). You are also given a 2D array edges where edges[j] = [a j , b j ] indicates that there is a directed edge from node a j to node b j . A valid path in the graph is a sequence of nodes x 1 -> x 2 -> x 3 -> ... -> x k such that there is a directed edge from x i to x i+1 for every 1 <= i < k . The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/21/leet1.png", + "https://assets.leetcode.com/uploads/2021/04/21/leet2.png" + ], + "constraints": [ + "n == colors.length", + "m == edges.length", + "1 <= n <= 10^5", + "0 <= m <= 10^5", + "colors consists of lowercase English letters.", + "0 <= a j , b j < n" + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]Output:3Explanation:The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored\"a\" (red in the above image).", + "image": null + }, + { + "text": "Example 2: Input:colors = \"a\", edges = [[0,0]]Output:-1Explanation:There is a cycle from 0 to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Graph:\n \n def __init__(self, colors):\n self.V = len(colors)\n self.adj = [[] for _ in range(self.V)]\n self.reset()\n \n def reset(self):\n self.visited = [False] * self.V\n self.recursion = [False] * self.V\n self.stack = []\n \n def addEdges(self, edges: List[List[int]]):\n for u,v in edges:\n self.addEdge(u, v)\n \n def addEdge(self, u, v):\n self.adj[u].append(v) \n \n def DFS(self, u):\n if self.recursion[u]:\n raise ValueError(\"Cycled Detected\")\n\n if self.visited[u]:\n return\n\n self.visited[u] = True\n self.recursion[u] = True\n\n for v in self.adj[u]:\n self.DFS(v)\n \n self.stack.append(u)\n \n self.recursion[u] = False\n \n def getTopologicalSortOrder(self): \n self.reset()\n \n for u in range(self.V):\n self.DFS(u)\n \n return self.stack[::-1]\n \n def isConnected(self, u, v):\n return self.adj[u].index(v) >= 0\n \n def getAdjs(self, u):\n return self.adj[u]\n \n \n\nclass Solution:\n def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:\n \n g = Graph(colors)\n g.addEdges(edges)\n \n try:\n order = g.getTopologicalSortOrder()\n\n result, dp = 0, [[0]*26 for _ in range(len(order)+1)]\n for i in range(len(order)-1, -1, -1): \n u = order[i]\n # we are storing the max colours possible for all paths from this node \n for v in g.getAdjs(u):\n for k in range(26):\n dp[u][k] = max(dp[u][k], dp[v][k])\n\n c = ord(colors[u])-97\n dp[u][c] += 1\n\n result = max(result, max(dp[u]))\n\n return result \n except:\n return -1\n \n", + "title": "1857. Largest Color Value in a Directed Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The bitwise AND of an array nums is the bitwise AND of all integers in nums . You are given an array of positive integers candidates . Evaluate the bitwise AND of every combination of numbers of candidates . Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, for nums = [1, 5, 3] , the bitwise AND is equal to 1 & 5 & 3 = 1 .", + "Also, for nums = [7] , the bitwise AND is 7 ." + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [16,17,71,62,12,24,14]Output:4Explanation:The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [8,8]Output:2Explanation:The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 19.3%) | Memory: 56.45 MB (Top 7.1%)\n\nclass Solution {\n public static int largestCombination(int[] candidates) {\n\t\tint arr[] = new int[32];\n\t\tfor (int i = 0; i < candidates.length; i++) {\n\t\t\tString temp = Integer.toBinaryString(candidates[i]);\n\t\t\tint n = temp.length();\n\t\t\tint index = 0;\n\t\t\twhile (n-- > 0) {\n\t\t\t\tarr[index++] += temp.charAt(n) - '0';\n\t\t\t}\n\t\t}\n\t\tint res = Integer.MIN_VALUE;\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tres = Math.max(res, arr[i]);\n\t\t}\n\t\treturn res;\n\t}\n}", + "title": "2275. Largest Combination With Bitwise AND Greater Than Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The bitwise AND of an array nums is the bitwise AND of all integers in nums . You are given an array of positive integers candidates . Evaluate the bitwise AND of every combination of numbers of candidates . Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, for nums = [1, 5, 3] , the bitwise AND is equal to 1 & 5 & 3 = 1 .", + "Also, for nums = [7] , the bitwise AND is 7 ." + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [16,17,71,62,12,24,14]Output:4Explanation:The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [8,8]Output:2Explanation:The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2282 ms (Top 70.42%) | Memory: 24.8 MB (Top 77.26%)\nclass Solution:\n def largestCombination(self, candidates: List[int]) -> int:\n return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))", + "title": "2275. Largest Combination With Bitwise AND Greater Than Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array of unique positive integers nums . Consider the following graph: Return the size of the largest connected component in the graph . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are nums.length nodes, labeled nums[0] to nums[nums.length - 1] ,", + "There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,15,35]Output:4", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex1.png" + }, + { + "text": "Example 2: Input:nums = [20,50,9,63]Output:2", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex2.png" + }, + { + "text": "Example 3: Input:nums = [2,3,6,7,4,12,21,39]Output:8", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 117 ms (Top 99.00%) | Memory: 50 MB (Top 86.57%)\nclass Solution {\n public int largestComponentSize(int[] nums) {\n int maxNum = getMaxNum(nums);\n Map numToFirstPrimeFactor = new HashMap<>();\n DisjointSet ds = new DisjointSet(maxNum + 1);\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n List primeFactors = getPrimeFactors(num);\n int firstPrimeFactor = primeFactors.get(0);\n numToFirstPrimeFactor.put(num, firstPrimeFactor);\n\n for (int i = 1; i < primeFactors.size(); i++) {\n ds.union(primeFactors.get(i-1), primeFactors.get(i));\n }\n }\n\n Map componentToSize = new HashMap<>();\n int maxSize = 0;\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n int firstPrimeFactor = numToFirstPrimeFactor.get(num);\n int component = ds.find(firstPrimeFactor);\n int size = componentToSize.getOrDefault(component, 0);\n componentToSize.put(component, ++size);\n maxSize = Math.max(maxSize, size);\n }\n return maxSize;\n }\n\n public int getMaxNum(int[] nums) {\n int maxNum = 0;\n for (int num : nums) {\n maxNum = Math.max(maxNum, num);\n }\n return maxNum;\n }\n\n public List getPrimeFactors(int num) {\n List primeFactors = new ArrayList<>();\n\n // even prime factor i.e. 2\n if((num & 1) == 0){\n primeFactors.add(2);\n\n do{\n num >>= 1;\n }while((num & 1) == 0);\n }\n\n // odd prime factors\n int primeFactor = 3;\n while(num != 1 && primeFactor*primeFactor <= num){\n if(num % primeFactor == 0){\n primeFactors.add(primeFactor);\n\n do{\n num /= primeFactor;\n }while(num % primeFactor == 0);\n }\n primeFactor += 2;\n }\n\n // num is prime\n if(num != 1){\n primeFactors.add(num);\n }\n return primeFactors;\n }\n}\n\nclass DisjointSet {\n int[] root;\n int[] rank;\n\n public DisjointSet(int size) {\n root = new int[size];\n rank = new int[size];\n for (int i = 0; i < size; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n public int find(int x) {\n while (x != root[x]) {\n root[x] = root[root[x]];\n x = root[x];\n }\n return x;\n }\n\n public void union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n\n if (rootX == rootY) {\n return;\n }\n\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = rootX;\n } else if (rank[rootX] < rank[rootY]) {\n root[rootX] = rootY;\n } else {\n root[rootY] = rootX;\n rank[rootX]++;\n }\n }\n}", + "title": "952. Largest Component Size by Common Factor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array of unique positive integers nums . Consider the following graph: Return the size of the largest connected component in the graph . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are nums.length nodes, labeled nums[0] to nums[nums.length - 1] ,", + "There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,6,15,35]Output:4", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex1.png" + }, + { + "text": "Example 2: Input:nums = [20,50,9,63]Output:2", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex2.png" + }, + { + "text": "Example 3: Input:nums = [2,3,6,7,4,12,21,39]Output:8", + "image": "https://assets.leetcode.com/uploads/2018/12/01/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 818 ms (Top 91.97%) | Memory: 26.40 MB (Top 28.47%)\n\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def union(self, p, q): \n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = qrt\n self.rank[qrt] += self.rank[prt]\n return True \n\n\nclass Solution:\n def largestComponentSize(self, A: List[int]) -> int:\n m = max(A)\n uf = UnionFind(m+1)\n seen = set(A)\n \n # modified sieve of eratosthenes \n sieve = [1]*(m+1)\n sieve[0] = sieve[1] = 0 \n for k in range(m//2+1): \n if sieve[k]: \n prev = k if k in seen else 0\n for x in range(2*k, m+1, k): \n sieve[x] = 0\n if x in seen: \n if prev: uf.union(prev, x)\n else: prev = x\n return max(uf.rank)\n", + "title": "952. Largest Component Size by Common Factor", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a set of distinct positive integers nums , return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are multiple solutions, return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[i] % answer[j] == 0 , or", + "answer[j] % answer[i] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[1,2]Explanation:[1,3] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,8]Output:[1,2,4,8]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 44.53%) | Memory: 44.1 MB (Top 26.48%)\nclass Solution {\n public List largestDivisibleSubset(int[] nums) {\n Arrays.sort(nums);\n int N = nums.length;\n List ans =new ArrayList();\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int []hash =new int[N];\n for(int i=0;idp[i]){\n dp[i] = dp[j]+1;\n hash[i] = j;\n }\n if(dp[i] > maxi){\n maxi = dp[i];\n lastindex = i;\n }\n }\n }//for ends\n ans.add(nums[lastindex]);\n while(hash[lastindex] != lastindex){\n lastindex = hash[lastindex];\n ans.add(nums[lastindex]);\n }\n return ans;\n }\n\n}", + "title": "368. Largest Divisible Subset", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a set of distinct positive integers nums , return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are multiple solutions, return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[i] % answer[j] == 0 , or", + "answer[j] % answer[i] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[1,2]Explanation:[1,3] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,8]Output:[1,2,4,8]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n nums.sort()\n n = len(nums)\n dp = [1 for i in range(n)]\n hashh = [i for i in range(n)]\n ans_ind = 0\n \n for i in range(1, n):\n for j in range(0,i):\n if nums[i]%nums[j] == 0 and dp[j]+1 > dp[i]: \n dp[i] = dp[j]+1\n hashh[i] = j\n \n # print(dp)\n # print(hashh)\n out = []\n maxi = dp[0]\n \n for i in range(len(nums)):\n if dp[i] > maxi:\n ans_ind = i\n maxi = dp[i]\n \n while(hashh[ans_ind]!=ans_ind):\n out.append(nums[ans_ind])\n ans_ind = hashh[ans_ind]\n out.append(nums[ans_ind])\n return(out)\n \n \n \n", + "title": "368. Largest Divisible Subset", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal . The integers in the magic square do not have to be distinct . Every 1 x 1 grid is trivially a magic square . Given an m x n integer grid , return the size (i.e., the side length k ) of the largest magic square that can be found within this grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]Output:3Explanation:The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 71.23%) | Memory: 45.5 MB (Top 49.32%)\nclass Solution {\n public int largestMagicSquare(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n // every row prefix sum\n int[][] rowPrefix = new int[m][n];\n for (int i = 0; i < m; i++) {\n rowPrefix[i][0] = grid[i][0];\n for (int j = 1; j < n; j++) {\n rowPrefix[i][j] = rowPrefix[i][j - 1] + grid[i][j];\n }\n }\n\n // every column prefix sum\n int[][] columnPrefix = new int[m][n];\n for (int i = 0; i < n; i++) {\n columnPrefix[0][i] = grid[0][i];\n for (int j = 1; j < m; j++) {\n columnPrefix[j][i] = columnPrefix[j - 1][i] + grid[j][i];\n }\n }\n\n int result = 1;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // length of square\n int l = Math.min(m - i, n - j);\n // only check square's length is better than previous result\n for (int k = l; k > result; k--) {\n if (magic(i, j, k, grid, rowPrefix, columnPrefix)) {\n result = k;\n break;\n }\n }\n }\n }\n return result;\n }\n\n private boolean magic(\n int i, int j, int l, int[][] grid, int[][] rowPrefix, int[][] columnPrefix) {\n // check every row\n int target = rowPrefix[i][j + l - 1] - rowPrefix[i][j] + grid[i][j];\n for (int k = 0; k < l; k++) {\n if (rowPrefix[i + k][j + l - 1] - rowPrefix[i + k][j] + grid[i + k][j] != target) {\n return false;\n }\n }\n\n // check every column\n for (int k = 0; k < l; k++) {\n if (columnPrefix[i + l - 1][j + k] - columnPrefix[i][j + k] + grid[i][j + k] != target) {\n return false;\n }\n }\n\n // check both diagonal\n int diagonal = 0;\n // \\\n // \\\n for (int k = 0; k < l; k++) {\n diagonal += grid[i + k][j + k];\n }\n\n if (diagonal != target) {\n return false;\n }\n\n // /\n // /\n for (int k = 0; k < l; k++) {\n diagonal -= grid[i + l - 1 - k][j + k];\n }\n\n return diagonal == 0;\n }\n}", + "title": "1895. Largest Magic Square", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal . The integers in the magic square do not have to be distinct . Every 1 x 1 grid is trivially a magic square . Given an m x n integer grid , return the size (i.e., the side length k ) of the largest magic square that can be found within this grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "1 <= grid[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]Output:3Explanation:The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1987 ms (Top 15.7%) | Memory: 16.60 MB (Top 82.4%)\n\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n for j in range(n): \n rows[i][j+1] = grid[i][j] + rows[i][j]\n cols[i+1][j] = grid[i][j] + cols[i][j]\n \n ans = 1\n for i in range(m): \n for j in range(n): \n diag = grid[i][j]\n for k in range(min(i, j)): \n ii, jj = i-k-1, j-k-1\n diag += grid[ii][jj]\n ss = {diag}\n for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])\n for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])\n ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal\n if len(ss) == 1: ans = max(ans, k+2)\n return ans ", + "title": "1895. Largest Magic Square", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings word1 and word2 . You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: Return the lexicographically largest merge you can construct . A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b . For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If word1 is non-empty, append the first character in word1 to merge and delete it from word1 . For example, if word1 = \"abc\" and merge = \"dv\" , then after choosing this operation, word1 = \"bc\" and merge = \"dva\" .", + "For example, if word1 = \"abc\" and merge = \"dv\" , then after choosing this operation, word1 = \"bc\" and merge = \"dva\" .", + "If word2 is non-empty, append the first character in word2 to merge and delete it from word2 . For example, if word2 = \"abc\" and merge = \"\" , then after choosing this operation, word2 = \"bc\" and merge = \"a\" .", + "For example, if word2 = \"abc\" and merge = \"\" , then after choosing this operation, word2 = \"bc\" and merge = \"a\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cabaa\", word2 = \"bcaaa\"Output:\"cbcabaaaaa\"Explanation:One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"abcabc\", word2 = \"abdcaba\"Output:\"abdcabcabcaba\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 92.79%) | Memory: 44.70 MB (Top 66.67%)\n\nclass Solution {\n public String largestMerge(String word1, String word2) {\n StringBuilder sb = new StringBuilder();\n int i=0;\n int j=0;\n char[] w1 = word1.toCharArray();\n char[] w2 = word2.toCharArray();\n \n int n1=w1.length;\n int n2=w2.length;\n \n // we loop until we exhaust any one of the 2 words completely\n while(iw2[j]){\n sb.append(w1[i++]);\n }else{\n sb.append(w2[j++]);\n }\n }\n \n // at the end of the loop we append any remaining word\n sb.append(word1.substring(i));\n sb.append(word2.substring(j));\n\t\t\n return sb.toString();\n }\n \n private boolean check(char[] w1, int i, char[] w2, int j){\n // will return true if we need to extract from word1 and false if we need to extract from word2\n \n while(iw2[j]){\n return true;\n }else{\n return false;\n }\n }\n \n // if we are unable to find any exhaustable character till the end of the loop we use the one having larger length\n if(i str:\n res = ''\n p1 = 0\n p2 = 0\n while p1 < len(word1) and p2 < len(word2):\n if word1[p1:] > word2[p2:]:\n res += word1[p1]\n p1 += 1\n else:\n res += word2[p2]\n p2 += 1\n \n res += word1[p1:] + word2[p2:]\n\n \n return res\n", + "title": "1754. Largest Merge Of Two Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digits digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order . If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 10^4", + "0 <= digits[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [8,1,9]Output:\"981\"", + "image": null + }, + { + "text": "Example 2: Input:digits = [8,6,7,1,0]Output:\"8760\"", + "image": null + }, + { + "text": "Example 3: Input:digits = [1]Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String largestMultipleOfThree(int[] digits) {\n int n=digits.length;\n Arrays.sort(digits);\n \n if(digits[digits.length-1]==0){\n return \"0\";\n }\n \n int sum=0;\n \n for(int i=0;i=0;i--){\n sb.append(digits[i]);\n }\n \n return sb.toString();\n }else if(sum%3==1){\n int modOne=-1;\n \n for(int i=0;i=0;i--){\n if(digits[i]!=-1){\n sb.append(digits[i]);\n }\n \n }\n \n if(sb.length()>0 && sb.toString().charAt(0)=='0'){\n return \"0\";\n }\n return sb.toString();\n }\n}\n", + "title": "1363. Largest Multiple of Three", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of digits digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order . If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 10^4", + "0 <= digits[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [8,1,9]Output:\"981\"", + "image": null + }, + { + "text": "Example 2: Input:digits = [8,6,7,1,0]Output:\"8760\"", + "image": null + }, + { + "text": "Example 3: Input:digits = [1]Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef largestMultipleOfThree(self, digits: List[int]) -> str:\n\t\tA = digits\n\t\tA.sort()\n\t\tA.reverse()\n\n\t\t@cache\n\t\tdef DP(i, r): # max number whose remainder is r using subarray [0:i] (inclusive) \n\t\t\tif i == 0:\n\t\t\t\tif A[0] % 3 == r:\n\t\t\t\t\treturn A[0]\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\n\t\t\tRa = DP(i-1, r)\n\t\t\tRb = [ x for j in range(3) \\\n\t\t\t\t for x in ( DP(i-1,j) * 10 + A[i] ,)\n\t\t\t\t if x % 3 == r ]\n\n\t\t\treturn max([Ra, *Rb])\n\n\t\tans = DP(len(A) - 1, 0)\n\n\t\tif ans == 0 and 0 not in A:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn str(ans)\n", + "title": "1363. Largest Multiple of Three", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a list of non-negative integers nums , arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2]Output:\"210\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,30,34,5,9]Output:\"9534330\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 69.93%) | Memory: 44.3 MB (Top 32.60%)\n\nclass Solution {\n public String largestNumber(int[] nums) {\n String[] arr=new String[nums.length];\n for(int i=0;i(b+a).compareTo(a+b));\n if(arr[0].equals(\"0\")) return \"0\";\n StringBuilder builder=new StringBuilder();\n for(String item:arr){\n builder.append(item);\n }\n return builder.toString();\n }\n}", + "title": "179. Largest Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a list of non-negative integers nums , arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,2]Output:\"210\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,30,34,5,9]Output:\"9534330\"", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cmp_to_key\nclass Solution:\n def largestNumber(self, nums: List[int]) -> str:\n nums = list(map(str, nums))\n nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0))))\n res = \"\".join(nums)\n return res if int(res) else \"0\"", + "title": "179. Largest Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer num . You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 1234Output:3412Explanation:Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.", + "image": null + }, + { + "text": "Example 2: Input:num = 65875Output:87655Explanation:Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 55.01%) | Memory: 41.3 MB (Top 44.82%)\nclass Solution {\n public int largestInteger(int num) {\n PriorityQueue opq = new PriorityQueue<>();\n PriorityQueue epq = new PriorityQueue<>();\n int bnum = num;\n while(num>0){\n int cur = num%10;\n if(cur%2==1){\n opq.add(cur);\n }else{\n epq.add(cur);\n }\n num /= 10;\n }\n StringBuilder sb = new StringBuilder();\n num = bnum;\n while(num>0){\n int cur = num%10;\n if(cur%2==1)\n sb.insert(0, opq.poll());\n else\n sb.insert(0, epq.poll());\n num /= 10;\n }\n return Integer.parseInt(sb.toString());\n }\n}", + "title": "2231. Largest Number After Digit Swaps by Parity", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer num . You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = 1234Output:3412Explanation:Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.", + "image": null + }, + { + "text": "Example 2: Input:num = 65875Output:87655Explanation:Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res\n", + "title": "2231. Largest Number After Digit Swaps by Parity", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string num , which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d] . You may choose to mutate a single substring of num . To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]] ). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num . A substring is a contiguous sequence of characters within the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num consists of only digits 0-9 .", + "change.length == 10", + "0 <= change[d] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]Output:\"832\"Explanation:Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.", + "image": null + }, + { + "text": "Example 2: Input:num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]Output:\"934\"Explanation:Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.", + "image": null + }, + { + "text": "Example 3: Input:num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]Output:\"5\"Explanation:\"5\" is already the largest number that can be created, so return it.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maximumNumber(String num, int[] change) {\n int i=0, n=num.length(), startIndex=-1, substringLength=0;\n \n // traverse through each digit in the input string\n while(i digit) {\n startIndex = i;\n // keep on replacing subsequent characters with with the change if they also have greater change\n while(i=startIndex && j str:\n flag=0\n ls=list(num)\n for i in range(len(ls)):\n k=int(ls[i])\n if change[k]>k:\n ls[i]=str(change[k])\n flag=1\n elif flag==1 and change[k] max){\n secondMax = max;\n max = nums[i];\n index = i;\n } else if(nums[i] != max && nums[i] > secondMax){\n secondMax = nums[i];\n }\n }\n if(secondMax * 2 <= max){\n return index;\n }\n return -1;\n }\n}\n", + "title": "747. Largest Number At Least Twice of Others", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums where the largest integer is unique . Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 50", + "0 <= nums[i] <= 100", + "The largest element in nums is unique." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,0]Output:1Explanation:6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:-1Explanation:4 is less than twice the value of 3, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 86.73%) | Memory: 13.8 MB (Top 57.55%)\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n if len(nums) is 1:\n return 0\n dom = max(nums)\n i = nums.index(dom)\n nums.remove(dom)\n if max(nums) * 2 <= dom:\n return i\n return -1", + "title": "747. Largest Number At Least Twice of Others", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string num , representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num , or an empty string \"\" if no odd integer exists . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num only consists of digits and does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"52\"Output:\"5\"Explanation:The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.", + "image": null + }, + { + "text": "Example 2: Input:num = \"4206\"Output:\"\"Explanation:There are no odd numbers in \"4206\".", + "image": null + }, + { + "text": "Example 3: Input:num = \"35427\"Output:\"35427\"Explanation:\"35427\" is already an odd number.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 63.81%) | Memory: 54.8 MB (Top 11.36%)\nclass Solution {\n public String largestOddNumber(String num) {\n for (int i = num.length() - 1; i > -1; i--) {\n if (num.charAt(i) % 2 == 1) return num.substring(0,i+1);\n }\n return \"\";\n }\n}", + "title": "1903. Largest Odd Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num , representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num , or an empty string \"\" if no odd integer exists . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 10^5", + "num only consists of digits and does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"52\"Output:\"5\"Explanation:The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.", + "image": null + }, + { + "text": "Example 2: Input:num = \"4206\"Output:\"\"Explanation:There are no odd numbers in \"4206\".", + "image": null + }, + { + "text": "Example 3: Input:num = \"35427\"Output:\"35427\"Explanation:\"35427\" is already an odd number.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestOddNumber(self, num: str) -> str:\n indx = -1\n n = len(num)\n for i in range(n):\n if int(num[i])%2 == 1:\n indx = i\n \n if indx == -1:\n return \"\"\n return num[:indx+1]\n", + "title": "1903. Largest Odd Number in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n -digits integers . Since the answer can be very large, return it modulo 1337 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestPalindrome(int n) {\n if(n == 1 ){\n return 9;\n }\n if(n == 2){\n return 987;\n }\n if(n == 3){\n return 123;\n }\n if(n == 4){\n return 597;\n }\n if(n == 5){\n return 677;\n }\n if(n == 6){\n return 1218;\n }\n if(n == 7){\n return 877;\n }\n return 475;\n \n }\n}\n\n", + "title": "479. Largest Palindrome Product", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n -digits integers . Since the answer can be very large, return it modulo 1337 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n]\n\n \n def isPalindrome(x):\n return str(x) == str(x)[::-1]\n\n def solve(n):\n best = 0\n for i in range(10**n-1, 0, -1):\n for j in range(max(i, (best-1)//i+1), 10**n):\n if isPalindrome(i*j):\n #print(i, j, i*j)\n best = i*j\n return best\n", + "title": "479. Largest Palindrome Product", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums , return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths . If it is impossible to form any triangle of a non-zero area, return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,2]Output:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 44.30%) | Memory: 54.1 MB (Top 55.23%)\nclass Solution {\n public int largestPerimeter(int[] nums) {\n Arrays.sort(nums);\n\n for(int i = nums.length - 3; i >= 0; i--) {\n if(nums[i] + nums[i + 1] > nums[i + 2])\n return nums[i] + nums[i + 1] + nums[i + 2];\n }\n return 0;\n }\n}", + "title": "976. Largest Perimeter Triangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths . If it is impossible to form any triangle of a non-zero area, return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,2]Output:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestPerimeter(self, nums: List[int]) -> int:\n nums=sorted(nums,reverse=True)\n l=len(nums)\n for i in range(l-2):\n if nums[i]= 0 && arr[i - 1][j] == 1) {\n dpTop[i][j] = 1 + dpTop[i - 1][j];\n }\n\n if(j - 1 >= 0 && arr[i][j - 1] == 1) {\n dpLeft[i][j] = 1 + dpLeft[i][j - 1];\n }\n }\n }\n\n // Prefix count of 1 cells on bottom and right directions\n for(int i = arr.length - 1; i >= 0; i--) {\n for(int j = arr.length - 1; j >= 0; j--) {\n if(i + 1 < arr.length && arr[i + 1][j] == 1) {\n dpBottom[i][j] = 1 + dpBottom[i + 1][j];\n }\n\n if(j + 1 < arr.length && arr[i][j + 1] == 1) {\n dpRight[i][j] = 1 + dpRight[i][j + 1];\n }\n }\n }\n\n int maxPlusSignLength = 0;\n for(int i = 0; i < arr.length; i++) {\n for(int j = 0; j < arr.length; j++) {\n if(arr[i][j] == 0) continue;\n\n // Minimum adjacent 1 cell count from all four directions to ensure symmetry\n int minAdjacentOnes = Math.min(Math.min(dpTop[i][j], dpBottom[i][j]), Math.min(dpLeft[i][j], dpRight[i][j]));\n maxPlusSignLength = Math.max(maxPlusSignLength, minAdjacentOnes + 1);\n }\n }\n\n return maxPlusSignLength;\n }\n}", + "title": "764. Largest Plus Sign", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n . You have an n x n binary grid grid with all values initially 1 's except for some indices given in the array mines . The i th element of the array mines is defined as mines[i] = [x i , y i ] where grid[x i ][y i ] == 0 . Return the order of the largest axis-aligned plus sign of 1 's contained in grid . If there is none, return 0 . An axis-aligned plus sign of 1 's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1 's. Note that there could be 0 's or 1 's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1 's. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "1 <= mines.length <= 5000", + "0 <= x i , y i < n", + "All the pairs (x i , y i ) are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, mines = [[4,2]]Output:2Explanation:In the above grid, the largest plus sign can only be of order 2. One of them is shown.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/plus1-grid.jpg" + }, + { + "text": "Example 2: Input:n = 1, mines = [[0,0]]Output:0Explanation:There is no plus sign, so return 0.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/plus2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:\n matrix = [1] * n\n aux = {}\n hasOne = False\n for i in range(0,n):\n matrix[i] = [1] * n\n for mine in mines:\n matrix[mine[0]][mine[1]] = 0\n for i in range(0,n):\n for j in range(0,n):\n if(matrix[i][j] == 1):\n hasOne = True\n if((i,j) not in aux):\n aux[(i,j)] = {\"t\":0,\"l\":0,\"r\":0,\"b\":0}\n if(j>0 and matrix[i][j] == 1 and matrix[i][j-1] == 1):\n aux[(i,j)][\"l\"] = aux[(i,j-1)][\"l\"] + 1 \n if(i>0 and matrix[i][j] == 1 and matrix[i-1][j] == 1):\n aux[(i,j)][\"t\"] = aux[(i-1,j)][\"t\"] + 1\n \n maxOrder = 0 \n for i in range(n-1,-1,-1):\n if(i stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.length;\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n \n for(int i=0; i= heights[i])\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n \n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights[stack2.peek()] >= heights[i])\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n \n for(int i=0; i int:\n maxArea = 0\n stack = [] # (index, height)\n \n for i, h in enumerate(heights):\n startIndex = i\n while stack and stack[-1][1] > h:\n index, height = stack.pop()\n maxArea = max(maxArea, height * (i - index))\n startIndex = index\n stack.append((startIndex, h))\n \n \n \n for index, height in stack:\n maxArea = max(maxArea, height * (len(heights) - index))\n \n \n return maxArea", + "title": "84. Largest Rectangle in Histogram", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a binary matrix matrix of size m x n , and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m * n <= 10^5", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,0,1],[1,1,1],[1,0,1]]Output:4Explanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" + }, + { + "text": "Example 2: Input:matrix = [[1,0,1,0,1]]Output:3Explanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" + }, + { + "text": "Example 3: Input:matrix = [[1,1,0],[1,0,1]]Output:2Explanation:Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 97.37%) | Memory: 73.60 MB (Top 19.35%)\n\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length;\n for (int i = 1; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (matrix[i][j] == 1) {\n matrix[i][j] = matrix[i - 1][j] + 1;\n }\n }\n }\n int ans = 0;\n for (var row : matrix) {\n Arrays.sort(row);\n for (int j = n - 1, k = 1; j >= 0 && row[j] > 0; --j, ++k) {\n int s = row[j] * k;\n ans = Math.max(ans, s);\n }\n }\n return ans;\n }\n}\n", + "title": "1727. Largest Submatrix With Rearrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary matrix matrix of size m x n , and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m * n <= 10^5", + "matrix[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,0,1],[1,1,1],[1,0,1]]Output:4Explanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" + }, + { + "text": "Example 2: Input:matrix = [[1,0,1,0,1]]Output:3Explanation:You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.", + "image": "https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" + }, + { + "text": "Example 3: Input:matrix = [[1,1,0],[1,0,1]]Output:2Explanation:Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3821 ms (Top 7.64%) | Memory: 37.3 MB (Top 95.14%)\nfrom collections import Counter\n\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n M = len(matrix)\n N = len(matrix[0])\n\n colcons = [] # preprocess columns\n for c in range(N):\n cons = []\n s = 0\n for r in range(M):\n if not matrix[r][c]:\n s = 0\n else:\n s += 1\n cons.append(s)\n colcons.append(cons)\n # colcons[c][r] is how much 1's we'll get if we start from column c at row r and go up\n\n best = 0\n for r in range(M):\n # try r as the lowest row\n C = Counter(colcons[c][r] for c in range(N))\n vs = sorted(C.keys(), reverse=True)\n cs = accumulate(C[v] for v in vs)\n for v,c in zip(vs,cs):\n best = max(best,v*c)\n return best", + "title": "1727. Largest Submatrix With Rearrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1 . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 300", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\"Output:0Explanation:The optimal substring here is an empty substring between the two'a's.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"Output:2Explanation:The optimal substring here is \"bc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"cbzxy\"Output:-1Explanation:There are no characters that appear twice in s.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 92.59%) | Memory: 41.10 MB (Top 80.55%)\n\nclass Solution {\n public int maxLengthBetweenEqualCharacters(String s) {\n int[] v1 = new int[26];\n int[] v2 = new int[26];\n Arrays.fill(v1, -1);\n Arrays.fill(v2, -1);\n int ans = -1;\n\n for (int i = 0; i < s.length(); ++i) {\n int temp = s.charAt(i) - 'a';\n\n if (v1[temp] == -1) {\n v1[temp] = i;\n } else {\n v2[temp] = i;\n ans = Math.max(ans, v2[temp] - v1[temp] - 1);\n }\n }\n\n return ans;\n }\n}\n\n\n", + "title": "1624. Largest Substring Between Two Equal Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1 . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 300", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\"Output:0Explanation:The optimal substring here is an empty substring between the two'a's.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"Output:2Explanation:The optimal substring here is \"bc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"cbzxy\"Output:-1Explanation:There are no characters that appear twice in s.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans \n", + "title": "1624. Largest Substring Between Two Equal Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums and an integer k . You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums , and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions . Answers within 10 -6 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,1,2,3,9], k = 3Output:20.00000Explanation:The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6,7], k = 4Output:20.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Double dp[][][];\n int n;\n int k1;\n public double check(int b, int c,long sum,int n1,int ar[]){\n System.out.println(b+\" \"+c);\n if(dp[b][c][n1]!=null)\n return dp[b][c][n1];\n if(b==n){\n if(sum!=0)\n return (double)sum/(double)n1;\n else\n return 0.0;}\n if(c0)\n dp[b][c][n1]=Math.max((double)sum/(double)n1+check(b,c+1,0,0,ar),check(b+1,c,sum+(long)ar[b],n1+1,ar));\n else\n dp[b][c][n1]=check(b+1,c,sum+(long)ar[b],n1+1,ar);\n\n return dp[b][c][n1];\n }\n public double largestSumOfAverages(int[] nums, int k) {\n n=nums.length;\n k1=k-1;\n dp= new Double[n+1][k][n+1];\n return check(0,0,0l,0,nums);\n }\n}\n", + "title": "813. Largest Sum of Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer k . You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums , and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions . Answers within 10 -6 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,1,2,3,9], k = 3Output:20.00000Explanation:The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6,7], k = 4Output:20.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestSumOfAverages(self, A, k):\n n = len(A)\n dp = [0] * n\n sum = 0\n for i in range(n-1,-1,-1):\n sum += A[i]\n dp[i] = sum / (n-i)\n for l in range(1,k):\n for i in range(n-l):\n sum = 0\n for j in range(i,n-l):\n sum += A[j]\n dp[i] = max(dp[i],dp[j+1] + sum / (j-i+1))\n return dp[0]\n", + "title": "813. Largest Sum of Averages", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . Return the latest 24-hour time in \"HH:MM\" format . If no valid time can be made, return an empty string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length == 4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4]Output:\"23:41\"Explanation:The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,5,5,5]Output:\"\"Explanation:There are no valid 24-hour times as \"55:55\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String largestTimeFromDigits(int[] arr) {\n int[] count = new int[10];\n for (int num: arr) {\n count[num]++;\n }\n StringBuilder sb = backTrack(count, new StringBuilder());\n if (sb.length() == 4) sb.insert(2, ':');\n return sb.toString();\n \n }\n private StringBuilder backTrack(int[] count, StringBuilder sb) {\n int size = sb.length();\n int start = 0;\n if (size == 0) {\n start = 2;\n }\n if (size == 1) {\n start = sb.charAt(0) == '2' ? 3 : 9;\n }\n if (size == 2) {\n start = 5;\n }\n if (size == 3) {\n start = 9;\n }\n for (int i = start; i >= 0; i--) {\n if (count[i] == 0) continue;\n count[i]--;\n sb.append(i);\n backTrack(count, sb);\n if (sb.length() == 4) {\n return sb;\n }\n else {\n count[Character.getNumericValue(sb.charAt(sb.length() - 1))]++;\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n return sb;\n }\n}\n", + "title": "949. Largest Time for Given Digits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . Return the latest 24-hour time in \"HH:MM\" format . If no valid time can be made, return an empty string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length == 4", + "0 <= arr[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4]Output:\"23:41\"Explanation:The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,5,5,5]Output:\"\"Explanation:There are no valid 24-hour times as \"55:55\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n res = \"\"\n digit_freq = collections.Counter(arr)\n # first digit\n \n \n if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2:\n res += \"2\"\n arr.remove(2)\n else:\n for digit in [1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # can't make 24-hour time\n if len(res) == 0:\n return \"\"\n \n # second digit 0-3\n if res == \"2\":\n for digit in [3,2,1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # no 0-3 left in arr\n if len(res) == 1:\n return \"\"\n # second digit 0-9\n else:\n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n res += \":\"\n \n for digit in range(5, -1, -1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n if len(res) == 3:\n return \"\"\n \n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n return res\n \n", + "title": "949. Largest Time for Given Digits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of points on the X-Y plane points where points[i] = [x i , y i ] , return the area of the largest triangle that can be formed by any three different points . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= points.length <= 50", + "-50 <= x i , y i <= 50", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[0,1],[1,0],[0,2],[2,0]]Output:2.00000Explanation:The five points are shown in the above figure. The red triangle is the largest.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png" + }, + { + "text": "Example 2: Input:points = [[1,0],[0,0],[0,1]]Output:0.50000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double largestTriangleArea(int[][] points) {\n double ans = 0;\n int n = points.length;\n for(int i=0;i float:\n maxA = 0\n for p1, p2, p3 in combinations(points, 3):\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y1 - y2))\n if A > maxA: maxA = A\n return maxA\n", + "title": "812. Largest Triangle Area", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the i th element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit . Choose a subset s of the n elements such that: The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The size of the subset s is less than or equal to numWanted .", + "There are at most useLimit items with the same label in s ." + ], + "examples": [ + { + "text": "Example 1: Input:values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1Output:9Explanation:The subset chosen is the first, third, and fifth items.", + "image": null + }, + { + "text": "Example 2: Input:values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2Output:12Explanation:The subset chosen is the first, second, and third items.", + "image": null + }, + { + "text": "Example 3: Input:values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1Output:16Explanation:The subset chosen is the first and fourth items.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {\n PriorityQueue> maxHeap = \n new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey()));\n for(int i=0;i(values[i], labels[i]));\n }\n Map labelLimitMap = new HashMap<>();\n int sum = 0;\n while(numWanted != 0) {\n int label = maxHeap.peek().getValue();\n if(labelLimitMap.containsKey(label)) {\n if(labelLimitMap.get(label) == useLimit) {\n maxHeap.poll();\n } else {\n labelLimitMap.put(label, labelLimitMap.get(label) + 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n } else {\n labelLimitMap.put(label, 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n // This Holds since at most numWanted is mentioned.\n if(maxHeap.isEmpty()) {\n return sum;\n }\n }\n return sum;\n }\n}\n", + "title": "1090. Largest Values From Labels", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the i th element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit . Choose a subset s of the n elements such that: The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The size of the subset s is less than or equal to numWanted .", + "There are at most useLimit items with the same label in s ." + ], + "examples": [ + { + "text": "Example 1: Input:values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1Output:9Explanation:The subset chosen is the first, third, and fifth items.", + "image": null + }, + { + "text": "Example 2: Input:values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2Output:12Explanation:The subset chosen is the first, second, and third items.", + "image": null + }, + { + "text": "Example 3: Input:values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1Output:16Explanation:The subset chosen is the first and fourth items.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def largestValsFromLabels(\n self, values: list[int], labels: list[int], numWanted: int, useLimit: int\n ) -> int:\n\n # Add labels and values into the heap\n heap = [(-value, label) for value, label in zip(values, labels)]\n heapq.heapify(heap)\n\n # Initialize the hashmap\n used = defaultdict(int)\n\n # Initialize the result\n res = 0\n\n # Iterate until we have used a certain number or the heap is empty\n while numWanted > 0 and heap:\n\n # Pop a label and its value from the heap\n value, label = heapq.heappop(heap)\n\n # If we can use such label\n if used[label] < useLimit:\n\n # Add its value to the result\n res += -value\n\n # Increment its count in the hashmap\n used[label] += 1\n\n # Decrement the number of numbers we still want\n numWanted -= 1\n\n return res\n", + "title": "1090. Largest Values From Labels", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0 , the entire matrix is land . However, each day a new cell becomes flooded with water . You are given a 1-based 2D array cells , where cells[i] = [r i , c i ] represents that on the i th day, the cell on the r i th row and c i th column ( 1-based coordinates) will be covered with water (i.e., changed to 1 ). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= row, col <= 2 * 10^4", + "4 <= row * col <= 2 * 10^4", + "cells.length == row * col", + "1 <= r i <= row", + "1 <= c i <= col", + "All the values of cells are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]Output:2Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/1.png" + }, + { + "text": "Example 2: Input:row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]Output:1Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/2.png" + }, + { + "text": "Example 3: Input:row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]Output:3Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 49.61%) | Memory: 121.4 MB (Top 10.85%)\nclass Solution {\n int[][] dir = new int[][]{{0, -1}, {-1, 0}, {1, 0}, {0, 1}};\n public int latestDayToCross(int row, int col, int[][] cells) {\n int grid[][] = new int[row][col];\n int low = 0, high = cells.length - 1;\n int ans = 0;\n\n while(low <= high){\n int mid = low + (high - low) / 2;\n\n for(int i = 0; i <= mid; i++)\n grid[cells[i][0] -1][cells[i][1] - 1] = 1;\n\n if(helper(grid, new boolean[row][col])){\n ans = mid;\n low = mid + 1;\n }\n\n else high = mid - 1;\n\n for(int i = 0; i < grid.length; i++)\n for(int j = 0; j < grid[i].length; j++)\n grid[i][j] = 0;\n }\n\n return ans + 1;\n }\n\n public boolean helper(int[][] grid, boolean[][] visited){\n for(int i = 0; i < grid[0].length; i++)\n if(grid[0][i] == 0 && !visited[0][i] &&safe(0, i, grid, visited)) return true;\n return false;\n }\n\n public boolean safe(int i, int j, int[][] cells, boolean[][] visited){\n if(i < 0 || j < 0 || i >= visited.length || j >= visited[i].length || visited[i][j] || cells[i][j] == 1) return false;\n if(i == cells.length - 1 && j < cells[i].length && cells[i][j] == 0) return true;\n\n visited[i][j] = true;\n for(int k = 0; k < dir.length; k++)\n if(safe(i + dir[k][0], j + dir[k][1], cells, visited)) return true;\n return false;\n }\n}", + "title": "1970. Last Day Where You Can Still Cross", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0 , the entire matrix is land . However, each day a new cell becomes flooded with water . You are given a 1-based 2D array cells , where cells[i] = [r i , c i ] represents that on the i th day, the cell on the r i th row and c i th column ( 1-based coordinates) will be covered with water (i.e., changed to 1 ). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= row, col <= 2 * 10^4", + "4 <= row * col <= 2 * 10^4", + "cells.length == row * col", + "1 <= r i <= row", + "1 <= c i <= col", + "All the values of cells are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]Output:2Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/1.png" + }, + { + "text": "Example 2: Input:row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]Output:1Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/2.png" + }, + { + "text": "Example 3: Input:row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]Output:3Explanation:The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/27/3.png" + } + ], + "follow_up": null, + "solution": "class UF:\n def __init__(self, m, n):\n self.n, self.loc_id, c_id = n, dict(), 0\n self.col_set = [set() for _ in range(m*n)]\n for i in range(m): # Assign id for each location (i ,j)\n for j in range(n):\n self.loc_id[(i, j)] = c_id\n self.col_set[c_id].add(j)\n c_id += 1\n self.p = [i for i in range(m*n)] # Initialize parents array `p`\n \n def find(self, i):\n if self.p[i] != i:\n self.p[i] = self.find(self.p[i])\n return self.p[i] \n \n def union(self, i, j):\n pi, pj = self.find(i), self.find(j)\n if pi != pj:\n self.p[pj] = pi # Update `pi`\n self.col_set[pi] = self.col_set[pi] | self.col_set[pj] # Take union of two sets (union all occupied columns)\n return len(self.col_set[pi]) == self.n # if length of col_set[pi] == self.n, meaning this piece occupied all columns from 1 to `col` inclusive, meaning we are blocked\n \nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n uf, visited = UF(row, col), set()\n for i, (x, y) in enumerate(cells):\n x, y = x-1, y-1\n visited.add((x, y))\n for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, 1), (0, -1)]:\n _x, _y = x+dx, y+dy # Check if neighbor is flooded\n if 0 <= _x < row and 0 <= _y < col and (_x, _y) in visited:\n id1, id2 = uf.loc_id[(_x, _y)], uf.loc_id[(x, y)]\n if uf.union(id1, id2): return i # Union two flooded piece and return index if union return True\n return -1\n", + "title": "1970. Last Day Where You Can Still Cross", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have a wooden plank of the length n units . Some ants are walking on the plank, each ant moves with a speed of 1 unit per second . Some of the ants move to the left , the other move to the right . When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t , it falls out of the plank immediately. Given an integer n and two integer arrays left and right , the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= left.length <= n + 1", + "0 <= left[i] <= n", + "0 <= right.length <= n + 1", + "0 <= right[i] <= n", + "1 <= left.length + right.length <= n + 1", + "All values of left and right are unique, and each value can appear only in one of the two arrays." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, left = [4,3], right = [0,1]Output:4Explanation:In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants.jpg" + }, + { + "text": "Example 2: Input:n = 7, left = [], right = [0,1,2,3,4,5,6,7]Output:7Explanation:All ants are going to the right, the ant at index 0 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants2.jpg" + }, + { + "text": "Example 3: Input:n = 7, left = [0,1,2,3,4,5,6,7], right = []Output:7Explanation:All ants are going to the left, the ant at index 7 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getLastMoment(int n, int[] left, int[] right) {\n int max = 0;\n for (int i = 0; i < left.length; i++) {\n if (left[i] > max)\n max = left[i];\n }\n for (int i = 0; i < right.length; i++) {\n if (n - right[i] > max)\n max = n - right[i];\n }\n return max;\n }\n}\n", + "title": "1503. Last Moment Before All Ants Fall Out of a Plank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have a wooden plank of the length n units . Some ants are walking on the plank, each ant moves with a speed of 1 unit per second . Some of the ants move to the left , the other move to the right . When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t , it falls out of the plank immediately. Given an integer n and two integer arrays left and right , the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "0 <= left.length <= n + 1", + "0 <= left[i] <= n", + "0 <= right.length <= n + 1", + "0 <= right[i] <= n", + "1 <= left.length + right.length <= n + 1", + "All values of left and right are unique, and each value can appear only in one of the two arrays." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, left = [4,3], right = [0,1]Output:4Explanation:In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants.jpg" + }, + { + "text": "Example 2: Input:n = 7, left = [], right = [0,1,2,3,4,5,6,7]Output:7Explanation:All ants are going to the right, the ant at index 0 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants2.jpg" + }, + { + "text": "Example 3: Input:n = 7, left = [0,1,2,3,4,5,6,7], right = []Output:7Explanation:All ants are going to the left, the ant at index 7 needs 7 seconds to fall.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/ants3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 316 ms (Top 23.17%) | Memory: 15 MB (Top 18.90%)\nclass Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n # make sure left and right are not empty without changing the answer\n left.append(0)\n right.append(n)\n\n return max(max(left), n - min(right))", + "title": "1503. Last Moment Before All Ants Fall Out of a Plank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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: Example 2:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]Output:1Explanation:We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 42.30%) | Memory: 40.7 MB (Top 84.83%)\nclass Solution {\n public int lastStoneWeight(int[] stones) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x));\n for (int i = 0; i < stones.length; i++) {\n pq.add(stones[i]);\n }\n while (pq.size() > 1) {\n int r1 = pq.poll();\n int r2 = pq.poll();\n if (r1 != r2) pq.add(r1 - r2);\n }\n return (pq.isEmpty()) ? 0 : pq.poll();\n }\n}", + "title": "1046. Last Stone Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: 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: Example 2:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]Output:1Explanation:We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.", + "image": null + }, + { + "text": "Example 2: Input:stones = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 27.86%) | Memory: 13.9 MB (Top 62.57%)\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n stones = [-x for x in stones]\n heapq.heapify(stones)\n\n while len(stones) > 1:\n mx1 = -heapq.heappop(stones)\n mx2 = -heapq.heappop(stones)\n if mx1 - mx2:\n heapq.heappush(stones, -(mx1 - mx2))\n\n if len(stones):\n return -heapq.heappop(stones)\n return 0\n", + "title": "1046. Last Stone Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 any two stones and smash them together. Suppose the stones have weights x and y with x <= y . The result of this smash is: At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone . If there are no stones left, return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,7,4,1,8,1]Output:1Explanation:We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\nwe can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\nwe can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\nwe can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.", + "image": null + }, + { + "text": "Example 2: Input:stones = [31,26,33,21,40]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n if len(stones) == 1: return stones[0]\n total = sum(stones)\n half, leng = total// 2, len(stones)\n dp = [[0] * (half + 1) for _ in range(leng + 1)]\n \n for i in range(1, leng+1):\n for j in range(1, half+1):\n if j - stones[i-1] >= 0:\n dp[i][j] = max(dp[i-1][j], dp[i-1][j - stones[i-1]] + stones[i-1])\n else:\n dp[i][j] = dp[i-1][j]\n return total - 2 * dp[leng][half]\n", + "title": "1049. Last Stone Weight II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , return the last substring of s in lexicographical order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 4 * 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"Output:\"bab\"Explanation:The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"tcode\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 54.24%) | Memory: 57.7 MB (Top 33.05%)\nclass Solution {\n\npublic String lastSubstring(String s) {\nint maxIndex = s.length() - 1;\n\nfor(int currIndex = s.length() - 1 ; currIndex >= 0 ; currIndex--){\n if(s.charAt(currIndex) > s.charAt(maxIndex))\n maxIndex = currIndex;\n\n else if(s.charAt(currIndex) == s.charAt(maxIndex)){\n int i = currIndex + 1;\n int j = maxIndex + 1;\n\n while(i < maxIndex && j < s.length() && s.charAt(i) == s.charAt(j)){\n i++;\n j++;\n }\n\n if(i == maxIndex || j == s.length() || s.charAt(i) > s.charAt(j))\n maxIndex = currIndex;\n }\n}\n\nreturn s.substring(maxIndex);\n}\n}", + "title": "1163. Last Substring in Lexicographical Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the last substring of s in lexicographical order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 4 * 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"Output:\"bab\"Explanation:The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"tcode\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 273 ms (Top 82.1%) | Memory: 20.15 MB (Top 100.0%)\n\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n i = 0\n j = 1\n k = 0\n n = len(s)\n while j + k < n:\n if s[i + k] == s[j + k]:\n k += 1\n elif s[i + k] > s[j + k]:\n j += k + 1\n k = 0\n elif s[i + k] < s[j + k]:\n i = max(i + k + 1, j)\n j = i + 1\n k = 0\n return s[i:]", + "title": "1163. Last Substring in Lexicographical Order", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string time in the form of hh:mm , where some of the digits in the string are hidden (represented by ? ). The valid times are those inclusively between 00:00 and 23:59 . Return the latest valid time you can get from time by replacing the hidden digits . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "time is in the format hh:mm .", + "It is guaranteed that you can produce a valid time from the given string." + ], + "examples": [ + { + "text": "Example 1: Input:time = \"2?:?0\"Output:\"23:50\"Explanation:The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.", + "image": null + }, + { + "text": "Example 2: Input:time = \"0?:3?\"Output:\"09:39\"", + "image": null + }, + { + "text": "Example 3: Input:time = \"1?:22\"Output:\"19:22\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maximumTime(String time) {\n char[] times = time.toCharArray();\n //for times[0]\n //if both characters of hour is ?, then hour is 23 then times[0] should be '2'(\"??:3?)\".\n //if 2nd character of hour is <= 3, then hour can be in 20s then times[0] should be '2'.\n //if 2nd character of hour is >3, then hour can only be in 10s then times[0] should be '1'.\n if(times[0]=='?')\n times[0]= (times[1]<='3' || times[1]=='?') ? '2' : '1';\n //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then times[1] should be '9'.\n //if 1st character of hour is 2, then hour can be 23 then times[1] should be '3'.\n if(times[1]=='?')\n times[1]= times[0]=='2' ? '3' : '9';\n //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so times[3] is always '5'.\n if(times[3]=='?')\n times[3]='5';\n //if 2nd character of minute is ?, then times[4] is '9'.\n if(times[4]=='?')\n times[4]='9';\n return new String(times);\n }\n}\n", + "title": "1736. Latest Time by Replacing Hidden Digits", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string time in the form of hh:mm , where some of the digits in the string are hidden (represented by ? ). The valid times are those inclusively between 00:00 and 23:59 . Return the latest valid time you can get from time by replacing the hidden digits . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "time is in the format hh:mm .", + "It is guaranteed that you can produce a valid time from the given string." + ], + "examples": [ + { + "text": "Example 1: Input:time = \"2?:?0\"Output:\"23:50\"Explanation:The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.", + "image": null + }, + { + "text": "Example 2: Input:time = \"0?:3?\"Output:\"09:39\"", + "image": null + }, + { + "text": "Example 3: Input:time = \"1?:22\"Output:\"19:22\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef maximumTime(self, time: str) -> str:\n memo = {\"0\":\"9\",\n \"1\":\"9\",\n \"?\":\"3\", \n \"2\":\"3\"}\n \n answer = \"\"\n for idx, val in enumerate(time):\n if val == \"?\":\n if idx == 0:\n if time[idx+1] == \"?\":\n answer += \"2\"\n \n else:\n if int(time[idx+1]) >= 4:\n answer += \"1\"\n \n else: answer += \"2\"\n \n if idx == 1:\n answer += memo[time[idx-1]]\n \n if idx == 3:\n answer += \"5\" \n \n if idx == 4:\n answer += \"9\"\n \n else:\n answer += val\n \n return answer\n", + "title": "1736. Latest Time by Replacing Hidden Digits", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Example 2:", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.37%) | Memory: 42.6 MB (Top 13.06%)\nclass Solution {\n public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n List list1 = new ArrayList<>();\n checkLeaf(root1, list1);\n List list2 = new ArrayList<>();\n checkLeaf(root2, list2);\n\n if(list1.size() != list2.size()) return false;\n\n int i = 0;\n while(i < list1.size()){\n if(list1.get(i) != list2.get(i)){\n return false;\n }\n i++;\n }\n return true;\n }\n\n private void checkLeaf(TreeNode node, List arr){\n if(node.left == null && node.right == null) arr.add(node.val);\n if(node.left != null) checkLeaf(node.left, arr);\n if(node.right != null) checkLeaf(node.right, arr);\n }\n}", + "title": "872. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Example 2:", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n tree=[]\n def inorder(root):\n nonlocal tree\n if root is None:\n return\n if root.left is None and root.right is None:\n tree.append(root.val)\n \n inorder(root.left)\n inorder(root.right)\n \n inorder(root1)\n inorder(root2)\n tree1=tree[:len(tree)//2]\n tree2=tree[len(tree)//2:]\n if tree1==tree2:\n return True\n else:\n return False", + "title": "872. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr and an integer k . Find the least number of unique integers after removing exactly k elements . Example 1:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^9", + "0 <= k <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,5,4], k = 1Output:1Explanation: Remove the single 4, only 5 is left.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,3,1,1,3,3,2], k = 3Output:2Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findLeastNumOfUniqueInts(int[] arr, int k) {\n Map freqMap = new HashMap<>();\n for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1);\n PriorityQueue pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2)));\n pq.addAll(freqMap.keySet());\n while(k>0 && !pq.isEmpty()){\n int element = pq.poll();\n int toBeDeleted = Math.min(k,freqMap.get(element));\n k-=toBeDeleted;\n if(toBeDeleted int:\n\n counter = collections.Counter(arr)\n\n min_heap = [(count, num) for num, count in counter.items()]\n\n\n\n heapify(min_heap)\n\n\n\n while k > 0:\n\n count, num = min_heap[0]\n\n\n\n if count > k:\n\n break\n\n\n\n heappop(min_heap)\n\n k -= count\n\n\n\n return len(min_heap)", + "title": "1481. Least Number of Unique Integers after K Removals", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a single positive integer x , we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1 , op2 , etc. is either addition, subtraction, multiplication, or division ( + , - , * , or /) . For example, with x = 3 , we might write 3 * 3 / 3 + 3 - 3 which is a value of 3 . When writing such an expression, we adhere to the following conventions: We would like to write an expression with the least number of operators such that the expression equals the given target . Return the least number of operators used. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The division operator ( / ) returns rational numbers.", + "There are no parentheses placed anywhere.", + "We use the usual order of operations: multiplication and division happen before addition and subtraction.", + "It is not allowed to use the unary negation operator ( - ). For example, \" x - x \" is a valid expression as it only uses subtraction, but \" -x + x \" is not because it uses negation." + ], + "examples": [ + { + "text": "Example 1: Input:x = 3, target = 19Output:5Explanation:3 * 3 + 3 * 3 + 3 / 3.\nThe expression contains 5 operations.", + "image": null + }, + { + "text": "Example 2: Input:x = 5, target = 501Output:8Explanation:5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\nThe expression contains 8 operations.", + "image": null + }, + { + "text": "Example 3: Input:x = 100, target = 100000000Output:3Explanation:100 * 100 * 100 * 100.\nThe expression contains 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3027 ms (Top 7.32%) | Memory: 13.9 MB (Top 97.56%)\nclass Solution(object):\n def leastOpsExpressTarget(self, x, target):\n return self.cost(x, target)\n\n def cost(self, x, val):\n if val == x:\n return 0\n elif val < x:\n # two possible states\n # either val > x / 2: we substract 1s\n state_1 = 2 * (x - val)\n # or val < x / 2: we divide once to 1 and we add enough 1s\n state_2 = 2*val - 1\n return min(state_1, state_2)\n else:\n # there is a maximum power of x that we can add\n p = int(log(val) // log(x))\n # and either x^p or x^(p+1) is the closest\n a = x**p\n b = a*x\n if b < 2*val:\n # x**(p+1) - val < val - x**p\n return min(p + self.cost(x, val - a), p + 1 + self.cost(x, b - val))\n else:\n return p + self.cost(x, val - a)", + "title": "964. Least Operators to Express Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "At a lemonade stand, each lemonade costs $5 . Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5 , $10 , or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5 . Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the i th customer pays, return true if you can provide every customer with the correct change, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= bills.length <= 10^5", + "bills[i] is either 5 , 10 , or 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:bills = [5,5,5,10,20]Output:trueExplanation:From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.", + "image": null + }, + { + "text": "Example 2: Input:bills = [5,5,10,10,20]Output:falseExplanation:From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean lemonadeChange(int[] bills) {\n int count5 = 0, count10 = 0;\n for(int p : bills){\n if(p == 5){\n count5++;\n }\n else if(p == 10){\n if(count5 > 0){\n count5--;\n count10++;\n }\n else{\n return false;\n }\n }\n else if(p == 20){\n if(count5 > 0 && count10 > 0){\n count5--;\n count10--;\n }\n else if(count5 == 0){\n return false;\n }\n else if(count5<3){\n return false;\n }\n else{\n count5 -= 3;\n }\n }\n }\n return true;\n }\n}\n", + "title": "860. Lemonade Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "At a lemonade stand, each lemonade costs $5 . Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5 , $10 , or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5 . Note that you do not have any change in hand at first. Given an integer array bills where bills[i] is the bill the i th customer pays, return true if you can provide every customer with the correct change, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= bills.length <= 10^5", + "bills[i] is either 5 , 10 , or 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:bills = [5,5,5,10,20]Output:trueExplanation:From the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.", + "image": null + }, + { + "text": "Example 2: Input:bills = [5,5,10,10,20]Output:falseExplanation:From the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 670 ms (Top 99.03%) | Memory: 22.00 MB (Top 10.8%)\n\nclass Solution:\n def lemonadeChange(self, bills):\n five = ten = 0\n for num in bills:\n if num == 5:\n five += 1\n elif num == 10 and five:\n ten += 1\n five -= 1\n elif num == 20 and five and ten:\n five -= 1\n ten -= 1\n elif num == 20 and five >= 3:\n five -= 3\n else:\n return False\n return True\n", + "title": "860. Lemonade Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"Output:5Explanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"Output:4Explanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"Output:6Explanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 78.55%)\nclass Solution {\n public int lengthOfLastWord(String s) {\n int j=s.length()-1,len=0; boolean flag=true;\n while(j>=0 && (flag || (!flag && s.charAt(j)!=' ')))\n if(s.charAt(j--)!=' '){\n flag=false;\n len++;\n }\n return len;\n }\n}", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"Output:5Explanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"Output:4Explanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"Output:6Explanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n return len(s.strip().split()[-1])\n", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sequence x 1 , x 2 , ..., x n is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr . If one does not exist, return 0 . A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr , without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n >= 3", + "x i + x i+1 == x i+2 for all i + 2 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,6,7,8]Output:5Explanation:The longest subsequence that is fibonacci-like: [1,2,3,5,8].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,7,11,12,14,18]Output:3Explanation:The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 97.6%) | Memory: 54.76 MB (Top 33.3%)\n\nclass Solution {\n /*\n * dp[i][j] is the max length of fibbonacci series whose last two elements\n * are A[i] & A[j]\n * for any integer A[k] we need to find two number A[i] & A[j] such that\n * i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time\n * complexity.\n * if there exist i,j,k such that i < j < k and A[i] + A[j] == A[k] then\n * dp[k][j] = dp[i][j] + 1 (A[k], A[j] are last two elements of fibbonacc series)\n */\n public int lenLongestFibSubseq(int[] A) {\n int n = A.length;\n int[][] dp = new int[n][n];\n int result = 0;\n for (int k = 2; k < n; k++) {\n int i = 0, j = k-1;\n while(i < j) {\n int sum = A[i] + A[j] - A[k];\n if (sum < 0) {\n i++;\n } else if (sum > 0) {\n j--;\n } else {\n // ith, jth kth element are fibbonaci sequence\n dp[j][k] = dp[i][j] + 1; // since numbers are unique\n result = Math.max(result, dp[j][k]);\n i++;\n j--;\n }\n }\n }\n return result + 2 >= 3? result + 2: 0;\n }\n}", + "title": "873. Length of Longest Fibonacci Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sequence x 1 , x 2 , ..., x n is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr . If one does not exist, return 0 . A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr , without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n >= 3", + "x i + x i+1 == x i+2 for all i + 2 <= n" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5,6,7,8]Output:5Explanation:The longest subsequence that is fibonacci-like: [1,2,3,5,8].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,7,11,12,14,18]Output:3Explanation:The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object): #DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A)\n def lenLongestFibSubseq(self, A):\n index = {Ai: i for i, Ai in enumerate(A)}\n dp = collections.defaultdict(lambda: 2)\n ans = 0\n for k, Ak in enumerate(A): #Following IJK idiom here\n for j in range(k-1,0,-1): \n i = index.get(Ak - A[j], None)\n if Ak - A[j] >= A[j]: break #Pruning for illegal Ai\n if i is not None and i < j:\n cur_len = dp[j, k] = dp[i, j] + 1\n ans = max(ans, cur_len)\n \n return ans # ans is either 0 or >=3 for SURE\n\n", + "title": "873. Length of Longest Fibonacci Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , you can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create . Return the output in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 12", + "s consists of lowercase English letters, uppercase English letters, and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a1b2\"Output:[\"a1b2\",\"a1B2\",\"A1b2\",\"A1B2\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"3z4\"Output:[\"3z4\",\"3Z4\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def letterCasePermutation(self, s):\n \n if s==\"\":\n return [\"\"]\n t=s[0].lower()\n li=[]\n res=self.letterCasePermutation(s[1:])\n for i in res:\n li.append(t+i)\n if t not in \"1234567890\":\n for i in res:\n li.append(t.upper()+i)\n return li\n \n \n \n", + "title": "784. Letter Case Permutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"Output:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"Output:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"Output:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n String[] num = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n public List letterCombinations(String digits) {\n List ll = new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n if (digits.length() != 0) {\n combination(digits.toCharArray(), ll, sb, 0);\n }\n return ll;\n }\n public void combination(char[] digits, List ll, StringBuilder sb, int idx) {\n \n if (sb.length() == digits.length) {\n ll.add(sb.toString());\n return;\n }\n \n String grp = num[digits[idx] - 48];\n for (int i = 0; i < grp.length(); i++) {\n sb.append(grp.charAt(i));\n combination(digits, ll, sb, idx + 1);\n sb.deleteCharAt(sb.length() - 1);\n }\n \n }\n}\n", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"Output:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"Output:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"Output:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n \n mapping = {\"2\": \"abc\",\n \"3\": \"def\",\n \"4\": \"ghi\",\n \"5\": \"jkl\",\n \"6\": \"mno\",\n \"7\": \"pqrs\",\n \"8\": \"tuv\",\n \"9\": \"wxyz\"}\n \n ans = []\n first = True\n for i in range(len(digits)):\n \n # mult: times we should print each digit\n mult = 1 \n for j in range(i+1, len(digits)):\n mult *= len(mapping[digits[j]])\n \n # cycles: times we should run same filling cycle\n if not first:\n cycles = len(ans) // mult\n else:\n cycles = 1\n if times > 1:\n cycles //= len(mapping[digits[i]])\n \n # cyclically adding each digits to answer\n answer_ind = 0 \n for _ in range(cycles):\n for char in mapping[digits[i]]:\n for __ in range(mult):\n if first:\n ans.append(char)\n else:\n ans[answer_ind] += char\n answer_ind += 1\n if first:\n first = False\n \n return ans\n", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 7", + "tiles consists of uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = \"AAB\"Output:8Explanation:The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".", + "image": null + }, + { + "text": "Example 2: Input:tiles = \"AAABBC\"Output:188", + "image": null + }, + { + "text": "Example 3: Input:tiles = \"V\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int result=0;\n public int numTilePossibilities(String tiles) {\n Map map = new HashMap<>();\n for(char c:tiles.toCharArray()){\n map.put(c,map.getOrDefault(c,0)+1);\n }\n find(map);\n return result-1;\n }\n public void find(Map map){\n result++;\n for(Map.Entry m:map.entrySet()){\n char c=m.getKey();\n int val =m.getValue();\n if(val>0){\n map.put(c,val-1);\n find(map);\n map.put(c,val);\n }\n }\n }\n}\n", + "title": "1079. Letter Tile Possibilities", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 7", + "tiles consists of uppercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = \"AAB\"Output:8Explanation:The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".", + "image": null + }, + { + "text": "Example 2: Input:tiles = \"AAABBC\"Output:188", + "image": null + }, + { + "text": "Example 3: Input:tiles = \"V\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n n= len(tiles)\n tiles=list(tiles)\n s1=set()\n for i in range(1,n+1):\n s1.update(permutations(tiles,i))\n return len(s1)", + "title": "1079. Letter Tile Possibilities", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 94 ms (Top 5.29%) | Memory: 74.9 MB (Top 5.05%)\nclass Solution {\n\n private final TrieNode trie = new TrieNode(' ');\n\n class TrieNode{\n\n private Character digit;\n private String value;\n private boolean isWord;\n private Map children;\n\n TrieNode(Character c){\n this.digit = c;\n this.isWord = false;\n this.children = new HashMap<>();\n }\n\n void insert(String s){\n TrieNode current = this;\n for(Character c : s.toCharArray()){\n current = current.children.computeIfAbsent(c, k -> new TrieNode(c));\n }\n current.value = s;\n current.isWord = true;\n }\n\n List getWordsPreOrder(){\n return getWordsPreOrder(this);\n }\n\n private List getWordsPreOrder(TrieNode root){\n List result = new ArrayList<>();\n if(root == null){\n return result;\n }\n\n if(root.isWord){\n result.add(Integer.parseInt(root.value));\n }\n for(TrieNode node : root.children.values()){\n result.addAll(getWordsPreOrder(node));\n }\n return result;\n }\n }\n\n public List lexicalOrder(int n) {\n for(int i = 1 ; i<=n;i++){\n trie.insert(String.valueOf(i));\n }\n return trie.getWordsPreOrder();\n }\n}", + "title": "386. Lexicographical Numbers", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return all the numbers in the range [1, n] sorted in lexicographical order. You must write an algorithm that runs in O(n) time and uses O(1) extra space. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:[1,10,11,12,13,2,3,4,5,6,7,8,9]", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lexicalOrder(self, n: int) -> List[int]:\n result = []\n orderDic = {}\n for i in range(1, n + 1):\n strI = str(i)\n level = orderDic\n for char in strI:\n if char not in level:\n level[char] = {}\n level = level[char]\n self.traverse(orderDic, \"\", result)\n return result\n \n def traverse(self, dic, temp, result):\n for key in dic:\n result.append(int(temp + key))\n self.traverse(dic[key], temp + key, result)\n", + "title": "386. Lexicographical Numbers", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of even length consisting of digits from 0 to 9 , and two integers a and b . You can apply either of the following two operations any number of times and in any order on s : Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Add a to all odd indices of s (0-indexed) . Digits post 9 are cycled back to 0 . For example, if s = \"3456\" and a = 5 , s becomes \"3951\" .", + "Rotate s to the right by b positions. For example, if s = \"3456\" and b = 1 , s becomes \"6345\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5525\", a = 9, b = 2Output:\"2050\"Explanation:We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\n​​​​​​​Add: \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"74\", a = 5, b = 1Output:\"24\"Explanation:We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"0011\", a = 4, b = 2Output:\"0011\"Explanation:There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private String result;\n public String findLexSmallestString(String s, int a, int b) {\n result = \"z\";\n HashSet set = new HashSet<>();\n dfs(s, a, b, set);\n return result;\n }\n private void dfs(String s, int a, int b, HashSet set) {\n if(set.contains(s))\n return;\n set.add(s);\n String s1, s2;\n s1 = addA(s, a);\n s2 = rotateB(s, b);\n dfs(s1, a , b, set);\n dfs(s2, a , b, set);\n }\n private String addA(String s, int a) {\n char c[] = s.toCharArray();\n int i, temp;\n for(i=1;i 0)\n result = s;\n return s;\n }\n private String rotateB(String s, int b) {\n if(b < 0)\n b += s.length();\n b = b % s.length();\n b = s.length() - b;\n s = s.substring(b) + s.substring(0, b);\n if(result.compareTo(s) > 0)\n result = s;\n return s;\n }\n}\n", + "title": "1625. Lexicographically Smallest String After Applying Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s of even length consisting of digits from 0 to 9 , and two integers a and b . You can apply either of the following two operations any number of times and in any order on s : Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s . A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Add a to all odd indices of s (0-indexed) . Digits post 9 are cycled back to 0 . For example, if s = \"3456\" and a = 5 , s becomes \"3951\" .", + "Rotate s to the right by b positions. For example, if s = \"3456\" and b = 1 , s becomes \"6345\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5525\", a = 9, b = 2Output:\"2050\"Explanation:We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\n​​​​​​​Add: \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"74\", a = 5, b = 1Output:\"24\"Explanation:We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"0011\", a = 4, b = 2Output:\"0011\"Explanation:There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nw: BFS\nh: for each possible number (node), we have two possible operations (add, rotate)\n it seems to be a 2^100 possible number, however, note:\n 1) add a to number of odd index, we will get to the same number after 10 rounds of add\n 2) s has even length, if b is odd, we can get the same number after n round\n 3) for each shift, we would get different number at even index in 10 rounds\n \n so we would have 10 * n * 10 number at most, then we can use BFS + memo\n'''\nimport collections\n\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n seen = set()\n deque = collections.deque([s])\n\n while deque:\n #print(deque)\n curr = deque.popleft()\n seen.add(curr)\n \n #1.add\n ad = self.add_(curr, a)\n if ad not in seen:\n deque.append(ad)\n seen.add(ad)\n\n \n #2. rotate:\n ro = self.rotate_(curr, b)\n if ro not in seen:\n deque.append(ro)\n seen.add(ro)\n\n return min(seen)\n \n \n def add_(self,s,a):\n res = ''\n for idx, i in enumerate(s):\n if idx % 2 == 1:\n num = (int(i) + a) % 10\n res += str(num)\n else:\n res += i\n \n return res\n \n \n def rotate_(self, s, b):\n idx = len(s)-b\n res = s[idx:] + s[0:idx]\n return res\n", + "title": "1625. Lexicographically Smallest String After Applying Operations", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 78.13%) | Memory: 133.90 MB (Top 10.6%)\n\nclass LFUCache {\n\n final int capacity;\n int curSize;\n int minFrequency;\n Map cache;\n Map frequencyMap;\n\n /*.*/\n /*\n * @param capacity: total capacity of LFU Cache\n * @param curSize: current size of LFU cache\n * @param minFrequency: frequency of the last linked list (the minimum frequency of entire LFU cache)\n * @param cache: a hash map that has key to Node mapping, which used for storing all nodes by their keys\n * @param frequencyMap: a hash map that has key to linked list mapping, which used for storing all\n * double linked list by their frequencies\n * */\n public LFUCache(int capacity) {\n this.capacity = capacity;\n this.curSize = 0;\n this.minFrequency = 0;\n\n this.cache = new HashMap<>();\n this.frequencyMap = new HashMap<>();\n }\n\n /** get node value by key, and then update node frequency as well as relocate that node **/\n public int get(int key) {\n DLLNode curNode = cache.get(key);\n if (curNode == null) {\n return -1;\n }\n updateNode(curNode);\n return curNode.val;\n }\n\n /**\n * add new node into LFU cache, as well as double linked list\n * condition 1: if LFU cache has input key, update node value and node position in list\n * condition 2: if LFU cache does NOT have input key\n * - sub condition 1: if LFU cache does NOT have enough space, remove the Least Recent Used node\n * in minimum frequency list, then add new node\n * - sub condition 2: if LFU cache has enough space, add new node directly\n * **/\n public void put(int key, int value) {\n // corner case: check cache capacity initialization\n if (capacity == 0) {\n return;\n }\n\n if (cache.containsKey(key)) {\n DLLNode curNode = cache.get(key);\n curNode.val = value;\n updateNode(curNode);\n }\n else {\n curSize++;\n if (curSize > capacity) {\n // get minimum frequency list\n DoubleLinkedList minFreqList = frequencyMap.get(minFrequency);\n cache.remove(minFreqList.tail.prev.key);\n minFreqList.removeNode(minFreqList.tail.prev);\n curSize--;\n }\n // reset min frequency to 1 because of adding new node\n minFrequency = 1;\n DLLNode newNode = new DLLNode(key, value);\n\n // get the list with frequency 1, and then add new node into the list, as well as into LFU cache\n DoubleLinkedList curList = frequencyMap.getOrDefault(1, new DoubleLinkedList());\n curList.addNode(newNode);\n frequencyMap.put(1, curList);\n cache.put(key, newNode);\n }\n }\n\n public void updateNode(DLLNode curNode) {\n int curFreq = curNode.frequency;\n DoubleLinkedList curList = frequencyMap.get(curFreq);\n curList.removeNode(curNode);\n\n // if current list the the last list which has lowest frequency and current node is the only node in that list\n // we need to remove the entire list and then increase min frequency value by 1\n if (curFreq == minFrequency && curList.listSize == 0) {\n minFrequency++;\n }\n\n curNode.frequency++;\n // add current node to another list has current frequency + 1,\n // if we do not have the list with this frequency, initialize it\n DoubleLinkedList newList = frequencyMap.getOrDefault(curNode.frequency, new DoubleLinkedList());\n newList.addNode(curNode);\n frequencyMap.put(curNode.frequency, newList);\n }\n\n /*\n * @param key: node key\n * @param val: node value\n * @param frequency: frequency count of current node\n * (all nodes connected in same double linked list has same frequency)\n * @param prev: previous pointer of current node\n * @param next: next pointer of current node\n * */\n class DLLNode {\n int key;\n int val;\n int frequency;\n DLLNode prev;\n DLLNode next;\n\n public DLLNode(int key, int val) {\n this.key = key;\n this.val = val;\n this.frequency = 1;\n }\n }\n\n /*\n * @param listSize: current size of double linked list\n * @param head: head node of double linked list\n * @param tail: tail node of double linked list\n * */\n class DoubleLinkedList {\n int listSize;\n DLLNode head;\n DLLNode tail;\n public DoubleLinkedList() {\n this.listSize = 0;\n this.head = new DLLNode(0, 0);\n this.tail = new DLLNode(0, 0);\n head.next = tail;\n tail.prev = head;\n }\n\n /** add new node into head of list and increase list size by 1 **/\n public void addNode(DLLNode curNode) {\n DLLNode nextNode = head.next;\n curNode.next = nextNode;\n curNode.prev = head;\n head.next = curNode;\n nextNode.prev = curNode;\n listSize++;\n }\n\n /** remove input node and decrease list size by 1**/\n public void removeNode(DLLNode curNode) {\n DLLNode prevNode = curNode.prev;\n DLLNode nextNode = curNode.next;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n listSize--;\n }\n\n }\n}\n\n/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */\n", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "class Node:\n \n def __init__(self, key, val, cnt=1, nxxt=None, prev=None):\n self.key = key\n self.val = val\n self.cnt = cnt\n self.nxxt = nxxt\n self.prev = prev\n \n \nclass NodeList(Node):\n \n def __init__(self):\n self.head = Node(0,0)\n self.tail = Node(0,0)\n self.head.nxxt = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n \n def addFront(self, node):\n temp = self.head.nxxt\n self.head.nxxt = node\n node.prev = self.head\n node.nxxt = temp\n temp.prev = node\n \n self.size += 1\n \n \n def removeNode(self, node):\n delprev = node.prev\n delnxxt = node.nxxt\n delprev.nxxt = delnxxt\n delnxxt.prev = delprev\n \n self.size -= 1\n \n\nclass LFUCache(NodeList):\n\n def __init__(self, capacity: int):\n self.keyNode = {}\n self.freqNodeList = {}\n self.maxSizeCache = capacity\n self.currSize = 0\n self.minFreq = 0\n \n \n def updateFreqNodeList(self, node):\n del self.keyNode[node.key]\n nodelist = self.freqNodeList[node.cnt]\n nodelist.removeNode(node)\n \n if node.cnt == self.minFreq and self.freqNodeList[node.cnt].size == 0:\n self.minFreq += 1\n \n if (node.cnt+1) in self.freqNodeList:\n nextHigherFreqNodeList = self.freqNodeList[node.cnt+1]\n else:\n nextHigherFreqNodeList = NodeList()\n \n node.cnt += 1\n nextHigherFreqNodeList.addFront(node)\n \n self.freqNodeList[node.cnt] = nextHigherFreqNodeList\n self.keyNode[node.key] = node\n \n\n def get(self, key: int) -> int:\n if key in self.keyNode:\n node = self.keyNode[key]\n ans = node.val\n self.updateFreqNodeList(node)\n \n return ans\n \n else:\n return -1\n \n\n def put(self, key: int, value: int) -> None:\n if self.maxSizeCache == 0:\n return\n \n if key in self.keyNode:\n node = self.keyNode[key]\n node.val = value\n self.updateFreqNodeList(node)\n return\n \n else:\n if self.currSize == self.maxSizeCache:\n nodelist = self.freqNodeList[self.minFreq]\n del self.keyNode[nodelist.tail.prev.key]\n nodelist.removeNode(nodelist.tail.prev)\n self.currSize -= 1\n \n self.currSize += 1\n self.minFreq = 1\n \n if self.minFreq in self.freqNodeList:\n nodelist = self.freqNodeList[self.minFreq]\n else:\n nodelist = NodeList()\n \n node = Node(key, value)\n nodelist.addFront(node)\n \n self.keyNode[key] = node\n self.freqNodeList[self.minFreq] = nodelist\n \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k . We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of English letters, digits, and dashes '-' .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5F3Z-2e-9-w\", k = 4Output:\"5F3Z-2E9W\"Explanation:The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.", + "image": null + }, + { + "text": "Example 2: Input:s = \"2-5g-3-J\", k = 2Output:\"2-5G-3J\"Explanation:The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 55.76%) | Memory: 45.6 MB (Top 53.19%)\nclass Solution {\n public String licenseKeyFormatting(String s, int k) {\n StringBuilder answer = new StringBuilder();\n int length = 0;\n // Iterate Backwards to fullfill first group condition\n for(int i=s.length()-1;i>=0;i--) {\n if(s.charAt(i) == '-') {\n continue;\n }\n if(length > 0 && length % k == 0) {\n answer.append('-');\n }\n answer.append(Character.toUpperCase(s.charAt(i)));\n length++;\n }\n return answer.reverse().toString();\n }\n}", + "title": "482. License Key Formatting", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k . We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of English letters, digits, and dashes '-' .", + "1 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"5F3Z-2e-9-w\", k = 4Output:\"5F3Z-2E9W\"Explanation:The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.", + "image": null + }, + { + "text": "Example 2: Input:s = \"2-5g-3-J\", k = 2Output:\"2-5G-3J\"Explanation:The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 55.38%) | Memory: 14.3 MB (Top 86.51%)\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n new_str = s.replace(\"-\", \"\")\n res = \"\"\n j = len(new_str)-1\n i = 0\n while j >= 0:\n res += new_str[j].upper()\n i += 1\n if i == k and j != 0:\n res += \"-\"\n i = 0\n j -= 1\n return res[::-1]", + "title": "482. License Key Formatting", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values. Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the linked list is n .", + "1 <= n <= 10^4", + "0 <= Node.val < n", + "All the values Node.val are unique .", + "1 <= nums.length <= n", + "0 <= nums[i] < n", + "All the values of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,1,2,3], nums = [0,1,3]Output:2Explanation:0 and 1 are connected, so [0, 1] and [3] are the two connected components.", + "image": "https://assets.leetcode.com/uploads/2021/07/22/lc-linkedlistcom1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2,3,4], nums = [0,3,1,4]Output:2Explanation:0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.", + "image": "https://assets.leetcode.com/uploads/2021/07/22/lc-linkedlistcom2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numComponents(ListNode head, int[] nums) {\n int count=0;\n HashSet set=new HashSet();\n for(int i=0;i int:\n d,count={},0\n for num in nums:\n d[num] = 0\n\n while head:\n if head.val in d:\n head = head.next\n while head and head.val in d:\n head = head.next\n count += 1\n else:\n head = head.next\n return count", + "title": "817. Linked List Components", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:falseExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "public class Solution {\n public boolean hasCycle(ListNode head) {\n ListNode fast = head;\n ListNode slow = head;\n boolean result = false;\n while(fast!=null && fast.next!=null){\n fast = fast.next.next;\n slow = slow.next;\n if(fast == slow){\n result = true;\n break;\n }\n }\n return result;\n }\n}\n", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:falseExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n for i in range(0, 10001):\n if head == None: return False\n head = head.next\n \n return True\n", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list. Example 1: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:tail connects to node index 1Explanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:tail connects to node index 0Explanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:no cycleExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "public class Solution {\n public ListNode detectCycle(ListNode head) {\n if (head == null) return null;\n ListNode tortoise = head;\n ListNode hare = new ListNode();\n hare.next = head.next;\n while (hare != null && hare.next != null && hare != tortoise) {\n tortoise = tortoise.next;\n hare = hare.next.next;\n }\n if (hare == null || hare.next == null) return null;\n tortoise = head;\n while (tortoise != hare) {\n tortoise = tortoise.next;\n hare = hare.next;\n }\n return hare;\n }\n}\n", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list. Example 1: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:tail connects to node index 1Explanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:tail connects to node index 0Explanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:no cycleExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return None\n slow = fast = entry = head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if slow == fast:\n while slow != entry:\n slow = slow.next\n entry = entry.next\n return entry\n return None\n", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png", + "https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png" + ], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 2500] .", + "The number of nodes in the list will be in the range [1, 100] .", + "1 <= Node.val <= 100 for each node in the linked list and binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:trueExplanation:Nodes in blue form a subpath in the binary Tree.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:true", + "image": null + }, + { + "text": "Example 3: Input:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:falseExplanation:There is no path in the binary tree that contains all the elements of the linked list fromhead.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 72.52%) | Memory: 49.5 MB (Top 46.71%)\nclass Solution {\n public boolean isSubPath(ListNode head, TreeNode root) {\n if(root == null) return false;\n if(issame(head, root)) return true;\n return isSubPath(head, root.left) || isSubPath(head, root.right);\n }\n private boolean issame(ListNode head, TreeNode root) {\n if(head == null) return true;\n if(root == null) return false;\n if(head.val != root.val) return false;\n return issame(head.next, root.left) || issame(head.next, root.right);\n }\n}", + "title": "1367. Linked List in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png", + "https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png" + ], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 2500] .", + "The number of nodes in the list will be in the range [1, 100] .", + "1 <= Node.val <= 100 for each node in the linked list and binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:trueExplanation:Nodes in blue form a subpath in the binary Tree.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:true", + "image": null + }, + { + "text": "Example 3: Input:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]Output:falseExplanation:There is no path in the binary tree that contains all the elements of the linked list fromhead.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 139 ms (Top 73.10%) | Memory: 16.3 MB (Top 54.16%)\n\nclass Solution(object):\n def isSubPath(self, head, root):\n if not root:\n return False\n if self.issame(head, root):\n return True\n return self.isSubPath(head, root.left) or self.isSubPath(head, root.right)\n def issame(self, head, root):\n if not head:\n return True\n if not root:\n return False\n if head.val != root.val:\n return False\n return self.issame(head.next, root.left) or self.issame(head.next, root.right)", + "title": "1367. Linked List in Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(ListNode head) Initializes the object with the head of the singly-linked list head .", + "int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 3, 2, 2, 3]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.", + "image": "https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 57.7%) | Memory: 44.32 MB (Top 46.5%)\n\nclass Solution {\n int N = 0;\n ListNode head = null;\n public Solution(ListNode head) {\n this.head = head;\n }\n \n public int getRandom() {\n ListNode p = this.head;\n int i = 1, ans = 0;\n while (p != null) {\n if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i\n p = p.next;\n i ++;\n }\n return ans;\n }\n}", + "title": "382. Linked List Random Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(ListNode head) Initializes the object with the head of the singly-linked list head .", + "int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 3, 2, 2, 3]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.", + "image": "https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 95.6%) | Memory: 20.10 MB (Top 30.35%)\n\nclass Solution:\n def __init__(self, head: Optional[ListNode]):\n self.ll=[]\n while head:\n self.ll.append(head.val)\n head=head.next\n def getRandom(self) -> int:\n return self.ll[randint(0, len(self.ll)-1)]\n", + "title": "382. Linked List Random Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c , the key might get long pressed , and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= name.length, typed.length <= 1000", + "name and typed consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:name = \"alex\", typed = \"aaleex\"Output:trueExplanation:'a' and 'e' in 'alex' were long pressed.", + "image": null + }, + { + "text": "Example 2: Input:name = \"saeed\", typed = \"ssaaedd\"Output:falseExplanation:'e' must have been pressed twice, but it was not in the typed output.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.52%) | Memory: 42.1 MB (Top 54.01%)\nclass Solution {\n public boolean isLongPressedName(String name, String typed) {\n int i = 0;\n int j = 0;\n int m = name.length();\n int n = typed.length();\n\n while(j < n)\n {\n if(i < m && name.charAt(i) == typed.charAt(j))\n {\n i++;\n j++;\n }\n else if(j > 0 && typed.charAt(j) == typed.charAt(j-1))\n {\n j++;\n }\n else\n {\n return false;\n }\n }\n\n return i == m;\n }\n}", + "title": "925. Long Pressed Name", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c , the key might get long pressed , and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= name.length, typed.length <= 1000", + "name and typed consist of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:name = \"alex\", typed = \"aaleex\"Output:trueExplanation:'a' and 'e' in 'alex' were long pressed.", + "image": null + }, + { + "text": "Example 2: Input:name = \"saeed\", typed = \"ssaaedd\"Output:falseExplanation:'e' must have been pressed twice, but it was not in the typed output.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n #dic for memoization\n\t\tdic = {}\n def dfs(i, j):\n if (i, j) in dic:\n return dic[(i, j)]\n \n\t\t\t#see if there is any case where both i and j reach to the end, cuz that will be the true condition\n\t\t\t#I only need one True \n if i >= len(name):\n return j == len(typed)\n\t\t\t#we iterated through the end of typed, and not yet for name \n if j >= len(typed):\n return False\n \n\t\t\t#if the characters don't match, return False\n if name[i] != typed[j]:\n dic[(i, j)] = False\n return False\n \n\t\t\t#if the two characters match\n\t\t\t#two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1))\n\t\t\t#return if any of them is True, which means that i, j reach to the end as aforementioned\n dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1)\n return dic[(i, j)]\n \n\t\t#start from index 0, 0\n return dfs(0, 0)\n", + "title": "925. Long Pressed Name", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s , return true if the longest contiguous segment of 1 ' s is strictly longer than the longest contiguous segment of 0 ' s in s , or return false otherwise . Note that if there are no 0 's, then the longest continuous segment of 0 's is considered to have a length 0 . The same applies if there is no 1 's. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, in s = \" 11 01 000 10\" the longest continuous segment of 1 s has length 2 , and the longest continuous segment of 0 s has length 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"Output:trueExplanation:The longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"111000\"Output:falseExplanation:The longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"110100010\"Output:falseExplanation:The longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 92.84%) | Memory: 41.5 MB (Top 80.00%)\n\nclass Solution {\n public boolean checkZeroOnes(String s) {\n int length1 = 0;\n int length0 = 0;\n\n int i = 0;\n while(i < s.length()){\n int temp = 0;\n while(i < s.length() && s.charAt(i) == '1'){ //counting 1s\n temp++;\n i++;\n }\n length1 = Math.max(temp,length1);\n temp = 0;\n while(i < s.length() && s.charAt(i) == '0'){ // counting 0s\n temp++;\n i++;\n }\n length0 = Math.max(temp,length0);\n }\n return length1 > length0;\n }\n}", + "title": "1869. Longer Contiguous Segments of Ones than Zeros", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a binary string s , return true if the longest contiguous segment of 1 ' s is strictly longer than the longest contiguous segment of 0 ' s in s , or return false otherwise . Note that if there are no 0 's, then the longest continuous segment of 0 's is considered to have a length 0 . The same applies if there is no 1 's. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, in s = \" 11 01 000 10\" the longest continuous segment of 1 s has length 2 , and the longest continuous segment of 0 s has length 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"Output:trueExplanation:The longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"111000\"Output:falseExplanation:The longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.", + "image": null + }, + { + "text": "Example 3: Input:s = \"110100010\"Output:falseExplanation:The longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 65.12%) | Memory: 13.9 MB (Top 66.60%)\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n s1 = s.split('0')\n s0 = s.split('1')\n r1 = max([len(i) for i in s1])\n r0 = max([len(i) for i in s0])\n return r1>r0", + "title": "1869. Longer Contiguous Segments of Ones than Zeros", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2 . subdir1 contains a file file1.ext and subdirectory subsubdir1 . subdir2 contains a subdirectory subsubdir2 , which contains a file file2.ext . In text form, it looks like this (with ⟶ representing the tab character): If we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\" . Note that the '\\n' and '\\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s . Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\" . Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension , where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system . If there is no file in the system, return 0 . Note that the testcases are generated such that the file system is valid and no file or directory name has length 0. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg" + ], + "constraints": [ + "1 <= input.length <= 10^4", + "input may contain lowercase or uppercase English letters, a new line character '\\n' , a tab character '\\t' , a dot '.' , a space ' ' , and digits.", + "All file and directory names have positive length." + ], + "examples": [ + { + "text": "Example 1: Input:input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"Output:20Explanation:We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg" + }, + { + "text": "Example 2: Input:input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"Output:32Explanation:We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg" + }, + { + "text": "Example 3: Input:input = \"a\"Output:0Explanation:We do not have any files, just a single directory named \"a\".", + "image": null + }, + { + "text": "dir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.1%) | Memory: 40.51 MB (Top 47.9%)\n\nclass Solution {\n public int lengthLongestPath(String input) {\n var stack = new ArrayDeque();\n int max = 0;\n String[] lines = input.split(\"\\n\");\n for(var line: lines) {\n int tabs = countTabs(line);\n while(tabs < stack.size()) {\n stack.pop();\n }\n int current = stack.isEmpty() ? 0: stack.peek();\n int nameLength = line.length() - tabs;\n if(isFilename(line)) {\n max = Math.max(max, current + nameLength);\n } else {\n stack.push(current + nameLength + 1);\n }\n }\n return max;\n }\n \n private int countTabs(String s) {\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) != '\\t') return i;\n }\n return 0;\n }\n \n private boolean isFilename(String s) {\n return s.lastIndexOf(\".\") != -1;\n }\n \n}\n", + "title": "388. Longest Absolute File Path", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2 . subdir1 contains a file file1.ext and subdirectory subsubdir1 . subdir2 contains a subdirectory subsubdir2 , which contains a file file2.ext . In text form, it looks like this (with ⟶ representing the tab character): If we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\" . Note that the '\\n' and '\\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s . Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\" . Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension , where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system . If there is no file in the system, return 0 . Note that the testcases are generated such that the file system is valid and no file or directory name has length 0. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg" + ], + "constraints": [ + "1 <= input.length <= 10^4", + "input may contain lowercase or uppercase English letters, a new line character '\\n' , a tab character '\\t' , a dot '.' , a space ' ' , and digits.", + "All file and directory names have positive length." + ], + "examples": [ + { + "text": "Example 1: Input:input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"Output:20Explanation:We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg" + }, + { + "text": "Example 2: Input:input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"Output:32Explanation:We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.", + "image": "https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg" + }, + { + "text": "Example 3: Input:input = \"a\"Output:0Explanation:We do not have any files, just a single directory named \"a\".", + "image": null + }, + { + "text": "dir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef lengthLongestPath(self, input: str) -> int:\n\t\tif \".\" not in input:\n\t\t\treturn 0\n\n\t\ta=input.split(\"\\n\")\n\t\tfiles=[]\n\t\tfor i in a:\n\t\t\tif \".\" in i:\n\t\t\t\tfiles.append(i)\n\n\t\tfinal=[]\n\t\tfor i in range(len(files)):\n\t\t\tfile=files[i]\n\t\t\tlvl=file.count(\"\\t\")\n\t\t\tidx=a.index(file)-1\n\t\t\tsave=[files[i].replace(\"\\t\",\"\")]\n\t\t\tfor j in range(lvl):\n\t\t\t\twhile a[idx].count(\"\\t\")!=lvl-1:\n\t\t\t\t\tidx-=1\n\t\t\t\tlvl=a[idx].count(\"\\t\")\n\t\t\t\tsave.append(a[idx].replace(\"\\t\",\"\"))\n\t\t\t\tidx-=1\n\t\t\tfinal.append(save)\n\n\t\tfinal=list(map(\"/\".join,final))\n\t\treturn len(max(final,key=len))", + "title": "388. Longest Absolute File Path", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums . Recall that a subsequence of an array nums is a list nums[i 1 ], nums[i 2 ], ..., nums[i k ] with 0 <= i 1 < i 2 < ... < i k <= nums.length - 1 , and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1 ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "0 <= nums[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,12]Output:4Explanation:The whole array is an arithmetic sequence with steps of length = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,7,2,10]Output:3Explanation:The longest arithmetic subsequence is [4,7,10].", + "image": null + }, + { + "text": "Example 3: Input:nums = [20,1,15,3,10,5,8]Output:4Explanation:The longest arithmetic subsequence is [20,15,10,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 440 ms (Top 73.2%) | Memory: 70.79 MB (Top 29.5%)\n\nclass Solution \n{\n public int longestArithSeqLength(int[] nums) \n {\n int n = nums.length;\n int longest = 0;\n Map[] dp = new HashMap[n];\n \n for (int i = 0; i < n; i++) \n {\n dp[i] = new HashMap<>();\n \n for (int j = 0; j < i; j++) \n {\n int diff = nums[i] - nums[j];\n dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1);\n longest = Math.max(longest, dp[i].get(diff));\n }\n }\n \n return longest;\n }\n}", + "title": "1027. Longest Arithmetic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums . Recall that a subsequence of an array nums is a list nums[i 1 ], nums[i 2 ], ..., nums[i k ] with 0 <= i 1 < i 2 < ... < i k <= nums.length - 1 , and that a sequence seq is arithmetic if seq[i+1] - seq[i] are all the same value (for 0 <= i < seq.length - 1 ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "0 <= nums[i] <= 500" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,12]Output:4Explanation:The whole array is an arithmetic sequence with steps of length = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,7,2,10]Output:3Explanation:The longest arithmetic subsequence is [4,7,10].", + "image": null + }, + { + "text": "Example 3: Input:nums = [20,1,15,3,10,5,8]Output:4Explanation:The longest arithmetic subsequence is [20,15,10,5].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7591 ms (Top 12.82%) | Memory: 21.8 MB (Top 96.69%)\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = [[1]*1001 for i in range(len(nums))]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n d = nums[j] - nums[i] + 500\n dp[j][d] = max(dp[i][d]+1,dp[j][d])\n return max([max(i) for i in dp])", + "title": "1027. Longest Arithmetic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr and an integer difference , return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference . A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i], difference <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4], difference = 1Output:4Explanation:The longest arithmetic subsequence is [1,2,3,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,5,7], difference = 1Output:1Explanation:The longest arithmetic subsequence is any single element.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,5,7,8,5,3,4,2,1], difference = -2Output:4Explanation:The longest arithmetic subsequence is [7,5,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 77.18%) | Memory: 57.40 MB (Top 33.18%)\n\nclass Solution\n{\npublic\n int longestSubsequence(int[] arr, int difference)\n {\n // Storing the final answer as 1\n int length = arr.length, max_length = 1;\n HashMap Terms_till_now = new HashMap<>();\n for (int i = 0; i < length; i++)\n {\n /*\n Find the number of terms, till curr_element - difference , say terms\n Mapping 1 + n to the current term of the sequence, i.e. curr_element\n */\n int terms = ((Terms_till_now.get(arr[i] - difference) == null) ? 0 : Terms_till_now.get(arr[i] - difference));\n Terms_till_now.put(arr[i], 1 + terms);\n max_length = Math.max(max_length, 1 + terms);\n }\n return max_length;\n }\n}\n", + "title": "1218. Longest Arithmetic Subsequence of Given Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr and an integer difference , return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference . A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i], difference <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4], difference = 1Output:4Explanation:The longest arithmetic subsequence is [1,2,3,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,5,7], difference = 1Output:1Explanation:The longest arithmetic subsequence is any single element.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,5,7,8,5,3,4,2,1], difference = -2Output:4Explanation:The longest arithmetic subsequence is [7,5,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 548 ms (Top 98.07%) | Memory: 27.7 MB (Top 73.31%)\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n d = defaultdict(int)\n for num in arr:\n if num - difference in d:\n d[num] = d[num - difference] + 1\n else:\n d[num] = 1\n return max((d[x] for x in d))\n", + "title": "1218. Longest Arithmetic Subsequence of Given Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary string s and a positive integer k . Return the length of the longest subsequence of s that makes up a binary number less than or equal to k . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The subsequence can contain leading zeroes .", + "The empty string is considered to be equal to 0 .", + "A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001010\", k = 5Output:5Explanation:The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00101001\", k = 1Output:6Explanation:\"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.60 MB (Top 67.53%)\n\nclass Solution {\n public int longestSubsequence(String s, int k) {\n int z=0;\n //count zero\n for(int i=0;ik\n for(int i=s.length()-1;i>=0;i--){\n \n if(num+base>k)break;\n if(s.charAt(i)=='1'){\n num+=base;\n }\n else {\n\t\t\t//remove already taken zeros from zeros count\n z--;\n }\n base*=2;\n len++;\n }\n \n return len+z;\n }\n}\n", + "title": "2311. Longest Binary Subsequence Less Than or Equal to K", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary string s and a positive integer k . Return the length of the longest subsequence of s that makes up a binary number less than or equal to k . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The subsequence can contain leading zeroes .", + "The empty string is considered to be equal to 0 .", + "A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1001010\", k = 5Output:5Explanation:The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.", + "image": null + }, + { + "text": "Example 2: Input:s = \"00101001\", k = 1Output:6Explanation:\"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 62.5%) | Memory: 16.50 MB (Top 18.75%)\n\nclass Solution:\n def longestSubsequence(self, s: str, k: int) -> int:\n \n end, n = len(s)-1, s.count(\"0\") \n while end >=0 and int(s[end:], 2)<= k:\n end-=1\n return n+ s[end+1:].count(\"1\")\n \n", + "title": "2311. Longest Binary Subsequence Less Than or Equal to K", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string text . You should split it to k substrings (subtext 1 , subtext 2 , ..., subtext k ) such that: Return the largest possible value of k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "subtext i is a non-empty string.", + "The concatenation of all the substrings is equal to text (i.e., subtext 1 + subtext 2 + ... + subtext k == text ).", + "subtext i == subtext k - i + 1 for all valid values of i (i.e., 1 <= i <= k )." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ghiabcdefhelloadamhelloabcdefghi\"Output:7Explanation:We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"merchant\"Output:1Explanation:We can split the string on \"(merchant)\".", + "image": null + }, + { + "text": "Example 3: Input:text = \"antaprezatepzapreanta\"Output:11Explanation:We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int longestDecomposition(String text) {\n int n = text.length(); \n for (int i = 0; i < n/2; i++) \n if (text.substring(0, i + 1).equals(text.substring(n-1-i, n))) \n return 2+longestDecomposition(text.substring(i+1, n-1-i));\n return (n==0)?0:1;\n}\n}", + "title": "1147. Longest Chunked Palindrome Decomposition", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string text . You should split it to k substrings (subtext 1 , subtext 2 , ..., subtext k ) such that: Return the largest possible value of k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "subtext i is a non-empty string.", + "The concatenation of all the substrings is equal to text (i.e., subtext 1 + subtext 2 + ... + subtext k == text ).", + "subtext i == subtext k - i + 1 for all valid values of i (i.e., 1 <= i <= k )." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ghiabcdefhelloadamhelloabcdefghi\"Output:7Explanation:We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".", + "image": null + }, + { + "text": "Example 2: Input:text = \"merchant\"Output:1Explanation:We can split the string on \"(merchant)\".", + "image": null + }, + { + "text": "Example 3: Input:text = \"antaprezatepzapreanta\"Output:11Explanation:We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 82 ms (Top 23.89%) | Memory: 13.9 MB (Top 78.76%)\n\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n left, right = 0, len(text) - 1\n sol, last_left = 0, 0\n a, b = deque(), deque()\n while right > left:\n a.append(text[left])\n b.appendleft(text[right])\n if a == b:\n sol += 2\n last_left = left\n a, b = deque(), deque()\n right -= 1\n left += 1\n if left == right or left > last_left + 1:\n sol += 1\n return max(sol, 1)\n", + "title": "1147. Longest Chunked Palindrome Decomposition", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 200", + "0 <= strs[i].length <= 200", + "strs[i] consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"flower\",\"flow\",\"flight\"]Output:\"fl\"", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"dog\",\"racecar\",\"car\"]Output:\"\"Explanation:There is no common prefix among the input strings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 21.11%) | Memory: 42.4 MB (Top 35.11%)\nclass TrieNode{\n TrieNode[] childs;\n int frequency;\n TrieNode(){\n childs = new TrieNode[26];\n this.frequency = 1;\n }\n}\n\nclass Solution {\n\n TrieNode root = new TrieNode();\n\n public String longestCommonPrefix(String[] strs) {\n if(strs.length == 0) return \"\";\n if(strs.length == 1) return strs[0];\n for(String str : strs){\n insertIntoTrie(str.toLowerCase());\n }\n return findCommonPrefix(strs[0], strs.length);\n }\n\n private void insertIntoTrie(String str) {\n TrieNode ptr = root;\n for(int i=0; i str:\n cmp=strs[0]\n for i in range(1,len(strs)):\n l=0\n if (len(cmp)>len(strs[i])):\n l+=len(strs[i])\n else:\n l+=len(cmp)\n ans=\"\"\n for j in range(l):\n if (cmp[j]!=strs[i][j]):\n if (j==0):\n return \"\"\n else:\n break\n else:\n ans+=strs[i][j]\n cmp=ans\n return cmp\n\t\t\nUpvote If you Like!!!", + "title": "14. Longest Common Prefix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a country of n cities numbered from 0 to n - 1 . In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once , but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the i th friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all . A subpath of a path is a contiguous sequence of cities within that path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "m == paths.length", + "2 <= m <= 10^5", + "sum(paths[i].length) <= 10^5", + "0 <= paths[i][j] < n", + "The same city is not listed multiple times consecutively in paths[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]Output:2Explanation:The longest common subpath is [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, paths = [[0],[1],[2]]Output:0Explanation:There is no common subpath shared by the three paths.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]Output:1Explanation:The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 460 ms (Top 16.0%) | Memory: 73.80 MB (Top 56.0%)\n\nclass Solution {\n \n //mod \n long mod = (long)(Math.pow(10,11) + 3);\n \n long p = 100003;\n \n long p_i[];\n \n public int longestCommonSubpath(int n, int[][] paths) {\n \n //min length will be 1 \n int min = 1;\n \n //max length will be the (path of min length) \n \n int max = Integer.MAX_VALUE;\n \n for(int path[] : paths){\n max = Math.min(max,path.length);\n }\n \n //now we will pre calculate the the powers of base\n //and upto max only bcoz that's the longest subarray \n //we are going to deal with\n p_i = new long[max + 1];\n \n p_i[0] = 1;\n \n for(int i=1;i<=max;i++){\n //mod multiplication\n p_i[i] = mulmod(p_i[i-1],p,mod);\n }\n \n int ans = 0;\n \n while(min <= max){\n \n int mid = (min + max) / 2;\n \n if(solve(mid,paths)){\n //if this length satisfies \n //we are moving to right \n //checking length greater than this\n ans = mid;\n min = mid + 1;\n }else{\n //else smaller\n max = mid - 1;\n }\n \n }\n \n return ans;\n \n }\n \n public boolean solve(int len,int paths[][]){\n \n Map map = new HashMap<>();\n \n // now for each path we are going to calculate the \n // hash value for each subpath of length -> len\n // and store the frequency of hash in map\n // and if for a hash value the frequency equals \n // paths.length it means it exists in all path array\n // so return true\n \n for(int path[] : paths){\n \n long hash = 0l;\n \n // we are using a set for storing hash value of particular len for \n // each path beacuse there is a possibility \n // that a subpath repeats multiple times \n // in a path so it directly updating in map\n // will lead to wrong count\n Set set = new HashSet<>();\n \n // hash is calculated as\n // let's say len is 3\n // (p^3 * (path[0]+1)) + (p^2 * (path[1]+1)) + (p^1 * (path[2] + 1))\n \n // now when we are moving forward \n // and we need to update the hash value \n // we can do it like \n // delete (p^3 * (path[index-len]+1)) from prev_hash\n // so now the hash will become -> \n // (p^2 * (path[1]+1)) + (p^1 * (path[2] + 1))\n // and then multiply prev_hash by p\n // (p^3 * (path[1]+1)) + (p^2 * (path[2] + 1))\n // now add (p^1 * (path[3]+1))\n // so hash becomes->\n //(p^3 * (path[1]+1)) + (p^2 * (path[2] + 1)) + (p^1 * (path[3]+1))\n \n //using this way we avoid calculating invmod\n //so easier to implement\n \n for(int i=0;i 0){\n if((b&1) == 1){\n ans = mulmod(ans,val,mod);\n }\n val = mulmod(val,val,mod);\n b = b >> 1;\n }\n \n return ans % mod;\n }\n \n long mulmod(long a, long b,long mod)\n {\n return ((a%mod) * (b%mod)) % mod;\n }\n \n \n \n}\n", + "title": "1923. Longest Common Subpath", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There is a country of n cities numbered from 0 to n - 1 . In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once , but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the i th friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all . A subpath of a path is a contiguous sequence of cities within that path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "m == paths.length", + "2 <= m <= 10^5", + "sum(paths[i].length) <= 10^5", + "0 <= paths[i][j] < n", + "The same city is not listed multiple times consecutively in paths[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]Output:2Explanation:The longest common subpath is [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, paths = [[0],[1],[2]]Output:0Explanation:There is no common subpath shared by the three paths.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]Output:1Explanation:The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4090 ms (Top 34.15%) | Memory: 51.70 MB (Top 78.05%)\n\nclass Solution:\n def longestCommonSubpath(self, n, paths) -> int:\n def get_common_subpath_hashes(k):\n \"\"\"Return hash values of common subpaths of length k, or empty set if none exists\"\"\"\n def get_subpath_hashes(path):\n hash, coeff = 0, pow(n, k-1, mod)\n for i in range(len(path)+1):\n if i < k:\n hash = (hash*n + path[i]) % mod\n else:\n yield hash\n if i < len(path):\n hash = ((hash-coeff*path[i-k])*n + path[i]) % mod \n return reduce(set.intersection, (set(get_subpath_hashes(p)) for p in paths))\n \n\t # can be replaced with a pre-computed large prime\n mod = self._generate_large_prime(int(1e18), int(9e18))\n low, high = 1, min(len(p) for p in paths)+1\n while low < high:\n mid = (low+high) // 2\n if get_common_subpath_hashes(mid):\n low = mid + 1\n else:\n high = mid\n return high - 1\n \n def _generate_large_prime(self, lower, upper):\n \"\"\"Generate a prime between [lower, upper)\"\"\"\n def is_prime(n, trials=50):\n def witness(a, n):\n x0 = pow(a, u, n)\n for _ in range(t):\n x = x0**2 % n\n if x == 1 and x0 != 1 and x0 != n-1:\n return True\n x0 = x\n return True if x0 != 1 else False\n\n t, u = 0, n-1\n while u%2 == 0:\n t, u = t+1, u>>1\n return not any(witness(randrange(1, n), n) for _ in range(trials))\n return next(r for r in iter(lambda: randrange(lower, upper), None) if is_prime(r))\n", + "title": "1923. Longest Common Subpath", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"Output:3Explanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"Output:3Explanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"Output:0Explanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 78.9%) | Memory: 48.13 MB (Top 74.6%)\n\nclass Solution {\n public int longestCommonSubsequence(String text1, String text2) {\n int m = text1.length();\n int n = text2.length();\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n dp[i][j] = 1 + dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n return dp[m][n];\n }\n}\n", + "title": "1143. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"Output:3Explanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"Output:3Explanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"Output:0Explanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n def lcs(ind1,ind2):\n prev=[0 for i in range(ind2+1)]\n curr=[0 for i in range(ind2+1)]\n \n for i in range(1,ind1+1):\n for j in range(1,ind2+1):\n if text1[i-1]==text2[j-1]:\n curr[j]=1+prev[j-1]\n \n else:\n curr[j]=max(prev[j],curr[j-1])\n prev=list(curr) # remember to use a new list for prev\n\n return prev[-1]\n \n \n ans=lcs(len(text1),len(text2))\n return ans\n", + "title": "1143. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]Output:4Explanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestConsecutive(int[] nums) {\n Set storage = new HashSet();\n \n for(int i = 0; i < nums.length; i++){\n storage.add(nums[i]);\n }\n \n int maxL = 0;\n \n for(int i = 0; i < nums.length; i++){\n \n //check if nums[i] id present in set or not\n //since after checking in set we remove the element from \n //set, there is no double calculation for same sequence \n if(storage.contains(nums[i])){\n storage.remove(nums[i]);\n \n int dec = nums[i]-1;\n int inc = nums[i]+1;\n int tempL = 1;\n \n //check both ways from nums[i] and calculate \n //tempL. since we are removing elements from \n //set we only calculate once for every sequence.\n \n while(storage.contains(dec)){\n storage.remove(dec);\n dec--;\n tempL++;\n }\n \n while(storage.contains(inc)){\n storage.remove(inc);\n inc++;\n tempL++;\n }\n \n \n maxL = Math.max(maxL, tempL);\n \n }\n }\n \n return maxL;\n }\n}\n", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]Output:4Explanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def longestConsecutive(self, nums):\n ans=0\n nums=set(nums)\n count=0\n for i in nums:\n if i-1 not in nums:\n j=i\n count=0\n while j in nums:\n count+=1\n j+=1\n ans=max(ans,count) \n return ans\n", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an unsorted array of integers nums , return the length of the longest continuous increasing subsequence (i.e. subarray) . The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r ( l < r ) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r , nums[i] < nums[i + 1] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]Output:3Explanation:The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]Output:1Explanation:The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 45.4 MB (Top 76.62%)\nclass Solution {\n public int findLengthOfLCIS(int[] nums) {\n int count = 1;\n int maxCount = 1;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] > nums[i - 1]) {\n count++;\n } else {\n maxCount = Math.max(count, maxCount);\n count = 1;\n }\n }\n maxCount = Math.max(count, maxCount);\n return maxCount;\n }\n}", + "title": "674. Longest Continuous Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an unsorted array of integers nums , return the length of the longest continuous increasing subsequence (i.e. subarray) . The subsequence must be strictly increasing. A continuous increasing subsequence is defined by two indices l and r ( l < r ) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r , nums[i] < nums[i + 1] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]Output:3Explanation:The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]Output:1Explanation:The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 416 ms (Top 5.00%) | Memory: 15.4 MB (Top 49.36%)\n\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n count=0\n for i in range(len(nums)):\n a=nums[i]\n c=1\n for j in range(i+1, len(nums)):\n if nums[j]>a:\n a=nums[j]\n c+=1\n else:\n break\n count=max(count, c)\n return count", + "title": "674. Longest Continuous Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4Output:2Explanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5Output:4Explanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n \n public int longestSubarray(int[] nums, int limit) {\n \n Deque increasing = new LinkedList(); // To keep track of Max_value index\n Deque decreasing = new LinkedList(); // To keep track of Min_value index\n \n int i = 0 ;\n int j = 0 ;\n int max_length = 0 ;\n \n while(j < nums.length){\n \n while(!increasing.isEmpty() && nums[increasing.peekLast()] >= nums[j]){\n increasing.pollLast() ;\n }\n \n increasing.add(j);\n \n while(!decreasing.isEmpty() && nums[decreasing.peekLast()] <= nums[j]){\n decreasing.pollLast() ;\n }\n \n decreasing.add(j);\n \n int max_val = nums[decreasing.peekFirst()] ;\n int min_val = nums[increasing.peekFirst()] ;\n \n if(max_val-min_val <= limit){\n max_length = Math.max(max_length , j-i+1);\n }else{\n \n // If maximum absolute diff > limit , then remove from dequeue and increase i\n while(i<=j && nums[decreasing.peekFirst()] - nums[increasing.peekFirst()] > limit ){\n \n if(!increasing.isEmpty() && increasing.peekFirst() == i){\n increasing.pollFirst() ;\n }\n \n if(!decreasing.isEmpty() && decreasing.peekFirst() == i){\n decreasing.pollFirst() ;\n }\n \n i++ ; \n } \n \n }\n \n \n j++ ;\n }\n \n return max_length ;\n }\n}\n\n", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4Output:2Explanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5Output:4Explanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# max absolte diff within a subarray is subarray max substracted by subarray min\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n q = collections.deque() # monotonic decreasing deque to compute subarray max, index of\n q2 = collections.deque() # monotonic increasing deque to compute subarray min, index of\n \n # sliding window\n res = left = 0\n for right in range(len(nums)):\n # pop monotocity-violating numbers from right end\n while q and nums[q[-1]] <= nums[right]:\n q.pop()\n q.append(right)\n \n # pop monotocity-violating numbers from right end\n while q2 and nums[q2[-1]] >= nums[right]:\n q2.pop()\n q2.append(right)\n \n # sliding window\n while left < right and q and q2 and nums[q[0]] - nums[q2[0]] > limit:\n # compress window from left pointer\n if q and q[0] == left:\n q.popleft()\n \n # compress left pointer\n if q2 and q2[0] == left:\n q2.popleft()\n \n left += 1\n \n if nums[q[0]] - nums[q2[0]] <= limit:\n res = max(res, right - left + 1)\n \n return res\n", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from node i , then edges[i] == -1 . Return the length of the longest cycle in the graph . If no cycle exists, return -1 . A cycle is a path that starts and ends at the same node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [3,3,4,2,3]Output:3Explanation:The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" + }, + { + "text": "Example 2: Input:edges = [2,-1,3,1]Output:-1Explanation:There are no cycles in this graph.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 81.42%) | Memory: 99.3 MB (Top 65.13%)\nclass Solution {\n public int longestCycle(int[] edges) {\n int[] map = new int[edges.length];\n int result = -1;\n\n for (int i = 0; i < edges.length; i++)\n result = Math.max(result, helper(i, 1, edges, map));\n\n return result;\n }\n\n int helper(int index, int total, int[] edges, int[] map) {\n if (index == -1 || map[index] == -1)\n return -1;\n\n if (map[index] != 0)\n return total - map[index];\n\n map[index] = total;\n int result = helper(edges[index], total + 1, edges, map);\n map[index] = -1;\n\n return result;\n }\n}", + "title": "2360. Longest Cycle in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a directed graph of n nodes numbered from 0 to n - 1 , where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n , indicating that there is a directed edge from node i to node edges[i] . If there is no outgoing edge from node i , then edges[i] == -1 . Return the length of the longest cycle in the graph . If no cycle exists, return -1 . A cycle is a path that starts and ends at the same node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == edges.length", + "2 <= n <= 10^5", + "-1 <= edges[i] < n", + "edges[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [3,3,4,2,3]Output:3Explanation:The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" + }, + { + "text": "Example 2: Input:edges = [2,-1,3,1]Output:-1Explanation:There are no cycles in this graph.", + "image": "https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestCycle(self, edges: List[int]) -> int:\n preorder = [-1 for _ in range(len(edges))]\n self.ans = -1\n self.pre = 0\n \n def dfs(self, i: int, st: int) -> None:\n preorder[i] = self.pre\n self.pre += 1\n \n if edges[i] == -1:\n return\n elif preorder[edges[i]] == -1:\n dfs(self, edges[i], st)\n return\n elif preorder[edges[i]] >= st:\n self.ans = max(self.ans, preorder[i] - preorder[edges[i]] + 1)\n return\n \n for i in range(len(edges)):\n if preorder[i] == -1 and edges[i] != -1:\n dfs(self, i, self.pre)\n \n return self.ans\n", + "title": "2360. Longest Cycle in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , consider all duplicated substrings : (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 3 * 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"banana\"Output:\"ana\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestDupSubstring(String s) {\n long[] e = new long[s.length()+1];\n long h = 1;\n int p = 991919;\n long M = 957689076713L;\n for (int i = 0; i < e.length; i++){\n e[i]=h;\n h=h*p%M;\n }\n int lo = 0, hi = s.length(), st = 0, end = 0;\n while(lo < hi){\n int mid = (lo+hi+1)>>1;\n Set seen = new HashSet<>();\n long hash = 0;\n boolean ok=false;\n for (int i = 0; i < s.length() && !ok; i++){\n hash = (hash*p+s.charAt(i))%M;\n if (i >= mid){\n hash = (hash - e[mid]*(s.charAt(i-mid))%M+M)%M;\n }\n if (i >= mid-1 && !seen.add(hash)){\n end = i;\n st = i-mid+1;\n ok=true;\n }\n }\n if (ok){\n lo=mid;\n }else{\n hi=mid-1;\n }\n }\n return lo == 0? \"\": s.substring(st, end+1);\n }\n}\n", + "title": "1044. Longest Duplicate Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , consider all duplicated substrings : (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 3 * 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"banana\"Output:\"ana\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2799 ms (Top 43.0%) | Memory: 16.80 MB (Top 93.0%)\n\nclass Solution:\n def longestDupSubstring(self, s: str) -> str:\n left = 0\n right = 1\n res = \"\"\n n = len(s)\n while right len(res):\n res = s[left:right]\n right+=1\n continue\n left+=1\n if left == right:\n right+=1\n return res", + "title": "1044. Longest Duplicate Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s , return the longest happy prefix of s . Return an empty string \"\" if no such prefix exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"level\"Output:\"l\"Explanation:s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababab\"Output:\"abab\"Explanation:\"abab\" is the largest prefix which is also suffix. They can overlap in the original string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 89.72%) | Memory: 43.2 MB (Top 90.81%)\nclass Solution {\n public String longestPrefix(String s) {\n int n=s.length();\n char arr[] = s.toCharArray();\n int lps[]=new int[n];\n for(int i=1; i0 && arr[j]!=arr[i]){\n j=lps[j-1]; // DEACREASING TILL WE FIND ITS PREFIX WHICH IS EQUAL TO ITS SUFFIX\n }\n if(arr[j]==arr[i]){// IF ITS PREV IS SAME AS CURRENT THEN INCREAMENT IT\n j++;\n }\n lps[i]=j; // SAVE WHATEVER THE VALUE IS\n }\n int j=lps[n-1];\n StringBuilder sb = new StringBuilder();\n for(int i=0;i0){ // ELSE DEACREASE TILL WE ARE NOT FINDING IT\n j=lps[j-1];\n i--;\n }\n }\n return s.substring(0,j);\n\n */", + "title": "1392. Longest Happy Prefix", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s , return the longest happy prefix of s . Return an empty string \"\" if no such prefix exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"level\"Output:\"l\"Explanation:s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababab\"Output:\"abab\"Explanation:\"abab\" is the largest prefix which is also suffix. They can overlap in the original string.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 186 ms (Top 90.2%) | Memory: 21.02 MB (Top 32.3%)\n\nclass Solution:\n def longestPrefix(self, s: str) -> str:\n n=len(s)\n lps=[0]*n\n j=0\n for i in range(1,n):\n while s[i]!=s[j] and j>0:\n j=lps[j-1]\n\n if s[i]==s[j]:\n lps[i]=j+1\n j+=1\n\n return s[:lps[-1]]", + "title": "1392. Longest Happy Prefix", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is called happy if it satisfies the following conditions: Given three integers a , b , and c , return the longest possible happy string . If there are multiple longest happy strings, return any of them . If there is no such string, return the empty string \"\" . A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s only contains the letters 'a' , 'b' , and 'c' .", + "s does not contain any of \"aaa\" , \"bbb\" , or \"ccc\" as a substring.", + "s contains at most a occurrences of the letter 'a' .", + "s contains at most b occurrences of the letter 'b' .", + "s contains at most c occurrences of the letter 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 1, c = 7Output:\"ccaccbcc\"Explanation:\"ccbccacc\" would also be a correct answer.", + "image": null + }, + { + "text": "Example 2: Input:a = 7, b = 1, c = 0Output:\"aabaa\"Explanation:It is the only correct answer in this case.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.66 MB (Top 66.7%)\n\n/*\nThe idea behid this problem\n1. Here we start by taking the size as the sum of a, b, c.\n2. Then we use 3 variables A, B, C to count the occurance of a, b, c.\n3. Now we iterate until the size, and \n -> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.\n \n4. Finally return the string.\n*/\nclass Solution {\n public String longestDiverseString(int a, int b, int c) {\n int totalSize = a + b + c;\n int A = 0;\n int B = 0;\n int C = 0;\n StringBuilder sb = new StringBuilder();\n for (int i=0; i=b && a>=c && A<2) || (B==2 && a>0) || (C==2 && a>0)) {\n sb.append(\"a\");\n a -= 1;\n A += 1;\n B = 0;\n C = 0;\n }\n // check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be added\n else if ((b>=a && b>=c && B<2) || (A==2 && b>0) || (C==2 && b>0)) {\n sb.append(\"b\");\n b -= 1;\n B += 1;\n A = 0;\n C = 0;\n }\n // checks c is largest and its count still < 2 or B and A = 2 and there are still c that can be added\n else if ((c>=a && c>=b && C<2) || (A==2 && c>0) || (B==2 && c>0)) {\n sb.append(\"c\");\n c -= 1;\n C += 1;\n A = 0;\n B = 0;\n }\n }\n return sb.toString();\n }\n}", + "title": "1405. Longest Happy String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string s is called happy if it satisfies the following conditions: Given three integers a , b , and c , return the longest possible happy string . If there are multiple longest happy strings, return any of them . If there is no such string, return the empty string \"\" . A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s only contains the letters 'a' , 'b' , and 'c' .", + "s does not contain any of \"aaa\" , \"bbb\" , or \"ccc\" as a substring.", + "s contains at most a occurrences of the letter 'a' .", + "s contains at most b occurrences of the letter 'b' .", + "s contains at most c occurrences of the letter 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 1, c = 7Output:\"ccaccbcc\"Explanation:\"ccbccacc\" would also be a correct answer.", + "image": null + }, + { + "text": "Example 2: Input:a = 7, b = 1, c = 0Output:\"aabaa\"Explanation:It is the only correct answer in this case.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef longestDiverseString(self, a: int, b: int, c: int) -> str:\n\t\tpq = []\n\t\tif a > 0: heapq.heappush(pq,(-a,'a')) \n\t\tif b > 0: heapq.heappush(pq,(-b,'b')) \n\t\tif c > 0: heapq.heappush(pq,(-c,'c'))\n\n\t\tans = ''\n\t\twhile pq:\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif len(ans)>1 and ans[-1] == ans[-2] == ch:\n\t\t\t\tif not pq: break\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\n\t\treturn ans\n", + "title": "1405. Longest Happy String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1 . Given an integer array nums , return the length of its longest harmonious subsequence among all its possible subsequences . A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,2,5,2,3,7]Output:5Explanation:The longest harmonious subsequence is [3,2,2,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 74.55%) | Memory: 54.5 MB (Top 74.21%)\nclass Solution {\n public static int firstOccurence(int[] arr,int target)\n {\n int res=-1;\n int start=0;\n int end=arr.length-1;\n while(start<=end)\n {\n int mid=start + (end-start)/2;\n if(arr[mid]==target)\n {\n res=mid;\n end=mid-1;\n }\n else if(arr[mid]maxLen)\n maxLen=b-a+1;\n }\n }\n return maxLen;\n }\n}", + "title": "594. Longest Harmonious Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1 . Given an integer array nums , return the length of its longest harmonious subsequence among all its possible subsequences . A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,2,5,2,3,7]Output:5Explanation:The longest harmonious subsequence is [3,2,2,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\nfrom collections import Counter\nclass Solution:\n\tdef findLHS(self, nums: List[int]) -> int:\n\t\tcounter=Counter(nums)\n\t\t# values=set(nums)\n\t\tres=0\n\t\t# if len(values)==1:return 0\n\t\tfor num in nums:\n\t\t\tif num+1 in counter or num-1 in counter:\n\t\t\t\tres=max(res,counter[num]+counter.get(num+1,0))\n\t\t\t\tres=max(res,counter[num]+counter.get(num-1,0))\n\n\t\treturn res\n\"\"", + "title": "594. Longest Harmonious Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of lowercase letters and an integer k . We call a string t ideal if the following conditions are satisfied: Return the length of the longest ideal string . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25 , not 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "t is a subsequence of the string s .", + "The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"acfgbd\", k = 2Output:4Explanation:The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", k = 3Output:4Explanation:The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 49.30%) | Memory: 48.5 MB (Top 48.18%)\nclass Solution {\n public int longestIdealString(String s, int k) {\n int DP[] = new int[26], ans = 1;\n\n for (int ch = 0, n = s.length(); ch < n; ch++) {\n int i = s.charAt(ch) - 'a';\n DP[i] = DP[i] + 1;\n\n for (int j = Math.max(0, i - k); j <= Math.min(25, i + k); j++)\n if (j != i)\n DP[i] = Math.max(DP[i], DP[j] + 1);\n\n ans = Math.max(ans, DP[i]);\n }\n\n return ans;\n }\n}", + "title": "2370. Longest Ideal Subsequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s consisting of lowercase letters and an integer k . We call a string t ideal if the following conditions are satisfied: Return the length of the longest ideal string . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25 , not 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "t is a subsequence of the string s .", + "The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"acfgbd\", k = 2Output:4Explanation:The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\", k = 3Output:4Explanation:The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 381 ms (Top 86.75%) | Memory: 17.40 MB (Top 70.48%)\n\nclass Solution:\n def longestIdealString(self, s: str, k: int) -> int:\n dp = [0] * 26\n for ch in s:\n i = ord(ch) - ord(\"a\")\n dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)])\n return max(dp)\n", + "title": "2370. Longest Ideal Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 200", + "0 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[9,9,4],[6,6,8],[2,1,1]]Output:4Explanation:The longest increasing path is[1, 2, 6, 9].", + "image": "https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[3,4,5],[3,2,6],[2,2,1]]Output:4Explanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.", + "image": "https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 22.67%) | Memory: 61.2 MB (Top 10.43%)\nclass Solution {\n public int longestIncreasingPath(int[][] matrix) {\n int[][] memo = new int[matrix.length][matrix[0].length];\n int longestPath = 0;\n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n dfs(matrix, i, j, memo);\n longestPath = Math.max(longestPath, memo[i][j]);\n }\n }\n return longestPath;\n }\n\n private void dfs(int[][] matrix, int i, int j, int[][] memo) {\n if (memo[i][j] != 0)\n return;\n int[][] dirs = {{-1,0}, {0,1}, {1,0}, {0,-1}};\n int max = 0;\n for (int k = 0; k < dirs.length; k++) {\n int x = dirs[k][0] + i;\n int y = dirs[k][1] + j;\n if (isValid(matrix, x, y) && matrix[x][y] > matrix[i][j]) {\n // Get/compute the largest path for that index\n if (memo[x][y] == 0) { // If longest path doesn't exist for that path then compute it\n dfs(matrix, x, y, memo);\n }\n max = Math.max(max, memo[x][y]);\n }\n }\n memo[i][j] = 1 + max;\n }\n\n private boolean isValid(int[][] matrix, int i, int j) {\n if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)\n return false;\n return true;\n }\n}", + "title": "329. Longest Increasing Path in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 200", + "0 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[9,9,4],[6,6,8],[2,1,1]]Output:4Explanation:The longest increasing path is[1, 2, 6, 9].", + "image": "https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[3,4,5],[3,2,6],[2,2,1]]Output:4Explanation:The longest increasing path is[3, 4, 5, 6]. Moving diagonally is not allowed.", + "image": "https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n ROWS, COLS = len(matrix), len(matrix[0])\n dp = {}\n \n def dfs(r, c, prevVal):\n if (r < 0 or r == ROWS or\n c < 0 or c == COLS or\n matrix[r][c] <= prevVal):\n return 0\n if (r, c) in dp:\n return dp[(r, c)]\n res = 1\n res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))\n res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))\n dp[(r, c)] = res\n return res\n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, -1)\n return max(dp.values())\n", + "title": "329. Longest Increasing Path in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2500", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,9,2,5,3,7,101,18]Output:4Explanation:The longest increasing subsequence is [2,3,7,101], therefore the length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,3,2,3]Output:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7,7,7,7]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 68.33%) | Memory: 43.7 MB (Top 85.25%)\nclass Solution {\n public int lengthOfLIS(int[] nums) {\n\n ArrayList lis = new ArrayList<>();\n\n for(int num:nums){\n\n int size = lis.size();\n\n if(size==0 ||size>0 && num>lis.get(size-1)){\n lis.add(num);\n }else{\n int insertIndex = bs(lis,num);\n lis.set(insertIndex,num);\n }\n }\n\n return lis.size();\n }\n\n int bs(List list, int target){\n int lo = 0;\n int hi = list.size()-1;\n\n while(lo int:\n\n # Initialize the result\n res = []\n\n # Binary search to find the index of the smallest number in result that is greater than or equal to the target\n def binarySearch(l, r, target):\n\n nonlocal res\n\n # If the left and right pointers meet, we have found the smallest number that is greater than the target\n if l == r:\n return l\n\n # Find the mid pointer\n m = (r - l) // 2 + l\n\n # If the number at the mid pointer is equal to the target, we have found a number that is equal to the target\n if res[m] == target:\n return m\n\n # Else if the number at the mid poitner is less than the target, we search the right side\n elif res[m] < target:\n return binarySearch(m + 1, r, target)\n\n # Else, we search the left side including the number at mid pointer because it is one of the possible solution since it is greater than the target\n else:\n return binarySearch(l, m, target)\n\n # Iterate through all numbers\n for n in nums:\n\n # If the last number in the result is less than the current number\n if not res or res[-1] < n:\n\n # Append the current number to the result\n res.append(n)\n\n continue\n\n # Else, find the index of the smallest number in the result that is greater than or equal to the current number\n i = binarySearch(0, len(res) - 1, n)\n\n # Replace the current number at such index\n res[i] = n\n\n return len(res)\n", + "title": "300. Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array arr , return the length of the longest subarray, which is a mountain . Return 0 if there is no mountain subarray. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,4,7,3,2,5]Output:5Explanation:The largest mountain is [1,4,7,3,2] which has length 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,2,2]Output:0Explanation:There is no mountain.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 81.75%) | Memory: 52.8 MB (Top 24.19%)\nclass Solution {\n public int longestMountain(int[] arr) {\n if (arr.length < 3)\n return 0;\n int max = 0;\n for (int i = 0; i < arr.length; i++) {\n if (isPeak(arr, i)) {\n int leftLength = left(arr, i);\n int rightLength = right(arr, i);\n max = Math.max(max, leftLength + rightLength + 1);\n }\n }\n return max;\n }\n\n public int left(int[] arr, int i) {\n int j = i - 1;\n while (j >= 0 && arr[j] < arr[j + 1])\n j--;\n return i - (j + 1);\n }\n\n public int right(int[] arr, int i) {\n int j = i + 1;\n while (j < arr.length && arr[j - 1] > arr[j])\n j++;\n return j - (i + 1);\n }\n\n public boolean isPeak(int[] arr, int i) {\n return i - 1 >= 0 && i + 1 < arr.length && arr[i - 1] < arr[i] && arr[i + 1] < arr[i];\n }\n}", + "title": "845. Longest Mountain in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array arr , return the length of the longest subarray, which is a mountain . Return 0 if there is no mountain subarray. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1,4,7,3,2,5]Output:5Explanation:The largest mountain is [1,4,7,3,2] which has length 5.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,2,2]Output:0Explanation:There is no mountain.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestMountain(self, arr: List[int]) -> int:\n if len(arr) < 3:\n return 0\n \n max_up, max_down = [1 for _ in arr], [1 for _ in arr]\n \n for i, x in enumerate(arr):\n if i == 0:\n continue\n if x > arr[i - 1]:\n max_up[i] = max_up[i - 1] + 1\n \n for j, y in reversed(list(enumerate(arr))):\n if j == len(arr) - 1:\n continue\n if y > arr[j + 1]:\n max_down[j] = max_down[j + 1] + 1\n \n return max(\n x + y - 1 if x > 1 and y > 1 else 0 \n for x, y in zip(max_up, max_down)\n )\n", + "title": "845. Longest Mountain in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s , return the longest substring of s that is nice . If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"YazaAay\"Output:\"aAa\"Explanation:\"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Bb\"Output:\"Bb\"Explanation:\"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"c\"Output:\"\"Explanation:There are no nice substrings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestNiceSubstring(String s) {\n String result = \"\";\n // take first index, go from 0 to length-1 of the string\n\t\tfor (int i = 0;i 1 && result.length() < temp.length() && checkNice(temp)) result = temp;\n } \n }\n return result;\n }\n \n\t//validate Nice String check\n public boolean checkNice(String temp){\n //add substring to the set\n\t\tSet s = new HashSet<>();\n for (char ch : temp.toCharArray()) s.add(ch);\n \n\t\t// return false If you do not find both lower case and upper case in the sub string\n\t\t//for e.g 'aAa' substring added to set will have both a and A in the substring which is valid\n\t\t// 'azaA' substring will fail for 'z'\n\t\t// 'aaaaaaaa' will return \"\" as result\n\t\t//make sure that the substring contains both lower and upper case\n for (char ch : s)\n if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch))) return false; \n return true;\n }\n}\n", + "title": "1763. Longest Nice Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not. Given a string s , return the longest substring of s that is nice . If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"YazaAay\"Output:\"aAa\"Explanation:\"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Bb\"Output:\"Bb\"Explanation:\"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.", + "image": null + }, + { + "text": "Example 3: Input:s = \"c\"Output:\"\"Explanation:There are no nice substrings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def divcon(s):\n\t\t # string with length 1 or less arent considered nice\n if len(s) < 2:\n return \"\"\n \n pivot = []\n # get every character that is not nice\n for i, ch in enumerate(s):\n if ch.isupper() and ch.lower() not in s:\n pivot.append(i)\n if ch.islower() and ch.upper() not in s:\n pivot.append(i)\n\t\t\t# if no such character return the string\n if not pivot:\n return s\n\t\t\t# divide the string in half excluding the char that makes the string not nice\n else:\n mid = (len(pivot)) // 2\n return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)\n \n return divcon(s)\n", + "title": "1763. Longest Nice Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome here. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"Output:7Explanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:1Explanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 56.47%) | Memory: 40.7 MB (Top 92.38%)\nclass Solution {\n public int longestPalindrome(String s) {\n HashMap map = new HashMap<>();\n\n int evenNo = 0;\n int oddNo = 0;\n\n for ( int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (map.containsKey(c)) {\n map.put(c, map.get(c) + 1);\n } else {\n map.put(c, 1);\n }\n\n }\n for (Map.Entry e : map.entrySet()) {\n int n = (int) e.getValue();\n if (n % 2 != 0) {\n oddNo += n;\n }\n evenNo += (n / 2) * 2;\n }\n\n if (oddNo > 0) {\n evenNo += 1;\n }\n return evenNo;\n }\n}", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome here. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"Output:7Explanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:1Explanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n letters = {} \n for letter in s: #count each letter and update letters dict\n if letter in letters:\n letters[letter] += 1\n else:\n letters[letter] = 1\n \n \n plus1 = 0 # if there is a letter with count of odd ans must +=1 \n ans = 0\n for n in letters.values():\n if n == 1: #1 can only appear in the middle of our word\n plus1 = 1\n elif n%2 == 0:\n ans += n\n else:\n ans += n - 1\n plus1 = 1\n \n return ans + plus1\n\n\n", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of strings words . Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order . Each element can be selected at most once . Return the length of the longest palindrome that you can create . If it is impossible to create any palindrome, return 0 . A palindrome is a string that reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^5", + "words[i].length == 2", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"lc\",\"cl\",\"gg\"]Output:6Explanation:One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]Output:8Explanation:One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"cc\",\"ll\",\"xx\"]Output:2Explanation:One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 99.82%) | Memory: 57.9 MB (Top 94.96%)\nclass Solution {\n public int longestPalindrome(String[] words) {\n int[][] freq = new int[26][26];//array for all alphabet combinations\n for (String word : words)\n freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word\n int left = 0;//to store freq counts\n boolean odd = false;\n for (int i = 0; i != 26; i++) {//iterate over our array\n odd |= (freq[i][i] & 1) == 1;//means odd number of freq for similar words are there\n left += freq[i][i] / 2;\n for (int j = i + 1; j != 26; j++)//nested iteration to find non similar pairs\n left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present\n }\n int res = left * 2 * 2;//res from total freq found!!\n if (odd){\n res+=2;// if odd then adding 2\n }\n return res;\n }\n}", + "title": "2131. Longest Palindrome by Concatenating Two Letter Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings words . Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order . Each element can be selected at most once . Return the length of the longest palindrome that you can create . If it is impossible to create any palindrome, return 0 . A palindrome is a string that reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 10^5", + "words[i].length == 2", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"lc\",\"cl\",\"gg\"]Output:6Explanation:One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]Output:8Explanation:One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"cc\",\"ll\",\"xx\"]Output:2Explanation:One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def longestPalindrome(self, words):\n wc = collections.Counter(words)\n aa = 0 # count how many words contain only two identical letters like 'aa'\n center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively\n\n for w, c in wc.items():\n if w[0] == w[1]: # like 'aa', 'bb', ...\n aa += c // 2 * 2 # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively\n # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n if c % 2 == 1: center = 2\n else:\n abba += min(wc[w], wc[w[::-1]]) * 0.5 # will definitely double counting\n return aa * 2 + int(abba) * 4 + center\n", + "title": "2131. Longest Palindrome by Concatenating Two Letter Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , find the longest palindromic subsequence 's length in s . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bbbab\"Output:4Explanation:One possible longest palindromic subsequence is \"bbbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"Output:2Explanation:One possible longest palindromic subsequence is \"bb\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestPalindromeSubseq(String s) {\n \tStringBuilder sb = new StringBuilder(s);\n \t sb.reverse();\n \t String s2 = sb.toString();\n return longestCommonSubsequence(s,s2);\n }\n public int longestCommonSubsequence(String text1, String text2) {\n int [][]dp = new int[text1.length()+1][text2.length()+1]; \n for(int i= text1.length()-1;i>=0;i--){\n for(int j = text2.length()-1;j>=0;j--){\n char ch1 = text1.charAt(i);\n char ch2 = text2.charAt(j);\n if(ch1==ch2) // diagnal\n dp[i][j]= 1+dp[i+1][j+1];\n else// right,down considering not matchning char from s1 and skipping s2 \n //considering not matchning char from s2 and skipping s1\n dp[i][j] = Math.max(dp[i][j+1],dp[i+1][j]);\n \n }\n }\n return dp[0][0];\n }\n}\n", + "title": "516. Longest Palindromic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , find the longest palindromic subsequence 's length in s . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bbbab\"Output:4Explanation:One possible longest palindromic subsequence is \"bbbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"Output:2Explanation:One possible longest palindromic subsequence is \"bb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1248 ms (Top 52.16%) | Memory: 34.60 MB (Top 50.8%)\n\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n dp = [[0 for _ in range(len(s))] for _ in range(len(s))]\n for k in range(1, len(s) + 1):\n for i in range(len(s) - k + 1):\n j = k + i - 1\n if i == j:\n dp[i][j] = 1\n elif i + 1 == j and s[i] == s[j]:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i+1][j-1] + 2\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return dp[0][-1]\n", + "title": "516. Longest Palindromic Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the longest palindromic substring in s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"Output:\"bab\"Explanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"Output:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n String max = \"\";\n \n private void checkPalindrome(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {\n if (r - l >= max.length()) {\n max = s.substring(l, r + 1);\n } \n\n l--;\n r++;\n }\n }\n \n public String longestPalindrome(String s) {\n for (int i = 0; i < s.length(); i++) {\n checkPalindrome(s, i, i);\n checkPalindrome(s, i, i + 1); \n }\n \n return max;\n }\n}\n", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the longest palindromic substring in s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"Output:\"bab\"Explanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"Output:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 643 ms (Top 86.54%) | Memory: 14 MB (Top 58.84%)\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n res = \"\"\n for i in range(len(s)):\n left, right = i - 1, i + 1\n\n while (right < len(s) and s[right] == s[i]):\n right += 1\n\n while (0 <= left < right < len(s) and s[left] == s[right]):\n left, right = left - 1, right + 1\n\n res = s[left+1:right] if right - left-1 > len(res) else res\n return res", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1 . The tree is represented by a 0-indexed array parent of size n , where parent[i] is the parent of node i . Since node 0 is the root, parent[0] == -1 . You are also given a string s of length n , where s[i] is the character assigned to node i . Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == parent.length == s.length", + "1 <= n <= 10^5", + "0 <= parent[i] <= n - 1 for all i >= 1", + "parent[0] == -1", + "parent represents a valid tree.", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:parent = [-1,0,0,1,1,2], s = \"abacbe\"Output:3Explanation:The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/testingdrawio.png" + }, + { + "text": "Example 2: Input:parent = [-1,0,0,0], s = \"aabc\"Output:3Explanation:The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/graph2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 151 ms (Top 22.99%) | Memory: 94.00 MB (Top 86.21%)\n\nclass Solution {\n int longestPathValue = 1; // variable to store the length of the longest path\n\n public int longestPath(int[] parent, String s) {\n // create an adjacency list representation of the tree\n Map> adj = new HashMap<>();\n for(int i = 1; i < parent.length; i++){\n int j = parent[i];\n adj.putIfAbsent(j, new LinkedList<>());\n adj.get(j).add(i);\n }\n // call dfs on the root of the tree\n dfs(0, adj, s);\n return longestPathValue;\n }\n\n public int dfs(int node, Map> adj, String s){\n // if the node is a leaf node, return 1\n if(!adj.containsKey(node)) return 1;\n int max = 0, secondMax = 0;\n // for each neighbor of the node\n for(int nbrNode : adj.get(node)){\n int longestPathFromNbrNode = dfs(nbrNode , adj, s);\n // if the characters at the current node and its neighbor are the same, ignore the neighbor\n if(s.charAt(node) == s.charAt(nbrNode)) continue;\n // update max and secondMax with the longest path from the neighbor node\n if(longestPathFromNbrNode > max){\n secondMax = max;\n max = longestPathFromNbrNode;\n }else if(longestPathFromNbrNode > secondMax){\n secondMax = longestPathFromNbrNode;\n }\n }\n // update longestPathValue with the longest path that includes the current node\n longestPathValue = Math.max(longestPathValue, max+secondMax+1);\n return max+1;\n }\n}\n\n", + "title": "2246. Longest Path With Different Adjacent Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1 . The tree is represented by a 0-indexed array parent of size n , where parent[i] is the parent of node i . Since node 0 is the root, parent[0] == -1 . You are also given a string s of length n , where s[i] is the character assigned to node i . Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == parent.length == s.length", + "1 <= n <= 10^5", + "0 <= parent[i] <= n - 1 for all i >= 1", + "parent[0] == -1", + "parent represents a valid tree.", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:parent = [-1,0,0,1,1,2], s = \"abacbe\"Output:3Explanation:The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/testingdrawio.png" + }, + { + "text": "Example 2: Input:parent = [-1,0,0,0], s = \"aabc\"Output:3Explanation:The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/graph2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestPath(self, parent: list[int], s: str) -> int:\n def l_path_and_chain(tree: dict[int, list[int]], s: str, root: int) -> tuple[int, int]:\n lp = lc1 = lc2 = 0\n for child, path, chain in ((c, *l_path_and_chain(tree, s, c)) for c in tree[root]):\n lp = max(lp, path)\n if s[child] != s[root]: *_, lc2, lc1 = sorted((chain, lc2, lc1))\n\n return max(lp, lc1 + lc2 + 1), lc1 + 1\n\n t = defaultdict(list)\n for c, p in enumerate(parent): t[p].append(c)\n return l_path_and_chain(t, s, 0)[0]\n", + "title": "2246. Longest Path With Different Adjacent Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only uppercase English letters.", + "0 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABAB\", k = 2Output:4Explanation:Replace the two 'A's with two 'B's or vice versa.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AABABBA\", k = 1Output:4Explanation:Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 85.13%) | Memory: 42.60 MB (Top 48.1%)\n\n/**\n * Time O(n)\n * Space O(26)\n */\nclass Solution {\n public int characterReplacement(String s, int k) {\n // Space O(26)\n int[] dic = new int[26];\n int start = 0;\n int maxLen = 0;\n // Time O(n)\n for (int end = 0; end < s.length(); end++) {\n maxLen = Math.max(maxLen, ++dic[s.charAt(end) - 'A']);\n if (end - start + 1 > maxLen + k) {\n dic[s.charAt(start) - 'A']--;\n start++;\n }\n }\n return s.length() - start;\n }\n}\n", + "title": "424. Longest Repeating Character Replacement", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only uppercase English letters.", + "0 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ABAB\", k = 2Output:4Explanation:Replace the two 'A's with two 'B's or vice versa.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AABABBA\", k = 1Output:4Explanation:Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n # Initialize variables\n window_start = 0\n max_length = 0\n max_count = 0\n char_count = {}\n\n # Traverse the string s\n for window_end in range(len(s)):\n # Increment the count of the current character\n char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1\n # Update the maximum count seen so far\n max_count = max(max_count, char_count[s[window_end]])\n \n # Shrink the window if required\n if window_end - window_start + 1 > max_count + k:\n char_count[s[window_start]] -= 1\n window_start += 1\n \n # Update the maximum length of the substring with repeating characters seen so far\n max_length = max(max_length, window_end - window_start + 1)\n \n return max_length\n", + "title": "424. Longest Repeating Character Replacement", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of words where each word consists of lowercase English letters. word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A without changing the order of the other characters to make it equal to word B . A word chain is a sequence of words [word 1 , word 2 , ..., word k ] with k >= 1 , where word 1 is a predecessor of word 2 , word 2 is a predecessor of word 3 , and so on. A single word is trivially a word chain with k == 1 . Return the length of the longest possible word chain with words chosen from the given list of words . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a predecessor of \"ab a c\" , while \"cba\" is not a predecessor of \"bcad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]Output:4Explanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]Output:5Explanation:All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].", + "image": null + }, + { + "text": "Example 3: Input:words = [\"abcd\",\"dbqca\"]Output:1Explanation:The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n Boolean compareForIncreaseByOne(String str1,String str2){\n //str 1 will be long than str2\n int first=0;\n int second=0;\n if(str1.length() != (str2.length() + 1)){\n return false;\n }\n while(first < str1.length()){\n if(second < str2.length() && str1.charAt(first) == str2.charAt(second)){\n first++;\n second++;\n }else{\n first++;\n }\n }\n if(first == str1.length() && second == str2.length()){\n return true;\n }\n return false;\n }\n \n public int longestStrChain(String[] words) {\n int N = words.length;\n Arrays.sort(words,(a,b) -> a.length()-b.length()); //as Sequence/Subset are not ordered\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j] + 1;\n maxi = Math.max(maxi,dp[i]);\n }\n }\n }//for neds\n return maxi;\n }\n}\n", + "title": "1048. Longest String Chain", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of words where each word consists of lowercase English letters. word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A without changing the order of the other characters to make it equal to word B . A word chain is a sequence of words [word 1 , word 2 , ..., word k ] with k >= 1 , where word 1 is a predecessor of word 2 , word 2 is a predecessor of word 3 , and so on. A single word is trivially a word chain with k == 1 . Return the length of the longest possible word chain with words chosen from the given list of words . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a predecessor of \"ab a c\" , while \"cba\" is not a predecessor of \"bcad\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]Output:4Explanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]Output:5Explanation:All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].", + "image": null + }, + { + "text": "Example 3: Input:words = [\"abcd\",\"dbqca\"]Output:1Explanation:The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 123 ms (Top 85.4%) | Memory: 16.81 MB (Top 58.4%)\n\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \n words.sort(key=len)\n dic = {}\n \n for i in words:\n dic[ i ] = 1\n \n for j in range(len(i)):\n \n # creating words by deleting a letter\n successor = i[:j] + i[j+1:]\n if successor in dic:\n dic[ i ] = max (dic[i], 1 + dic[successor])\n \n res = max(dic.values())\n return res", + "title": "1048. Longest String Chain", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]Output:3Explanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]Output:5Explanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]Output:2Explanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums) {\n List groups = new ArrayList<>();\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0)\n groups.add(nums[i]);\n if (nums[i] == 1) {\n int count = 0;\n while (i < nums.length && nums[i] == 1) {\n count++;\n i++;\n }\n groups.add(count);\n if (i < nums.length && nums[i] == 0)\n groups.add(0);\n }\n }\n int max = 0;\n if (groups.size() == 1) {\n return groups.get(0) - 1;\n }\n for (int i = 0; i < groups.size(); i++) {\n if (i < groups.size() - 2) {\n max = Math.max(max, groups.get(i) + groups.get(i+2));\n } else {\n max = Math.max(max, groups.get(i));\n }\n }\n \n return max;\n }\n}\n", + "title": "1493. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]Output:3Explanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]Output:5Explanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]Output:2Explanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n pre, suf = [1]*n, [1]*n\n if nums[0] == 0:pre[0] = 0\n if nums[-1] == 0:suf[-1] = 0\n \n for i in range(1, n):\n if nums[i] == 1 and nums[i-1] == 1:\n pre[i] = pre[i-1] + 1\n elif nums[i] == 0:\n pre[i] = 0\n \n for i in range(n-2, -1, -1):\n if nums[i] == 1 and nums[i+1] == 1:\n suf[i] = suf[i+1] + 1\n elif nums[i] == 0:\n suf[i] = 0\n \n ans = 0\n for i in range(n):\n if i == 0:\n ans = max(ans, suf[i+1])\n elif i == n-1:\n ans = max(ans, pre[i-1])\n else:\n ans = max(ans, pre[i-1] + suf[i+1])\n \n return ans", + "title": "1493. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of length n , and an integer k . You are tasked to find the longest subsequence repeated k times in string s . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s , where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s . If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"bba\" is repeated 2 times in the string \"bababcba\" , because the string \"bbabba\" , constructed by concatenating \"bba\" 2 times, is a subsequence of the string \" b a bab c ba \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"letsleetcode\", k = 2Output:\"let\"Explanation:There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.", + "image": "https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png" + }, + { + "text": "Example 2: Input:s = \"bb\", k = 2Output:\"b\"Explanation:The longest subsequence repeated 2 times is \"b\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\", k = 2Output:\"\"Explanation:There is no subsequence repeated 2 times. Empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 56.76%) | Memory: 43.2 MB (Top 86.49%)\nclass Solution {\n char[] A;\n public String longestSubsequenceRepeatedK(String s, int k) {\n A = s.toCharArray();\n Queue queue = new ArrayDeque<>();\n queue.offer(\"\");\n String ans = \"\";\n int[] count = new int[26];\n BitSet bit = new BitSet();\n for (char ch : A) if (++count[ch-'a'] >= k){\n bit.set(ch-'a');\n }\n while(!queue.isEmpty()){\n String sb = queue.poll();\n for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i+1)){\n String res = sb+(char)(i+'a');\n if (check(k, res)){\n ans = res;\n queue.offer(res);\n }\n }\n }\n return ans;\n }\n\n private boolean check(int k, String s){\n int cnt = 0;\n for (char ch : A){\n if (s.charAt(cnt%s.length()) == ch && ++cnt >= k * s.length()){\n return true;\n }\n }\n return false;\n }\n}", + "title": "2014. Longest Subsequence Repeated k Times", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of length n , and an integer k . You are tasked to find the longest subsequence repeated k times in string s . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s , where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s . If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"bba\" is repeated 2 times in the string \"bababcba\" , because the string \"bbabba\" , constructed by concatenating \"bba\" 2 times, is a subsequence of the string \" b a bab c ba \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"letsleetcode\", k = 2Output:\"let\"Explanation:There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.", + "image": "https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png" + }, + { + "text": "Example 2: Input:s = \"bb\", k = 2Output:\"b\"Explanation:The longest subsequence repeated 2 times is \"b\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\", k = 2Output:\"\"Explanation:There is no subsequence repeated 2 times. Empty string is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n n = len(s)\n max_chunk_sz = n // k\n \n d = collections.Counter(s)\n chars = sorted([c for c in d if d[c] >= k], reverse=True)\n if not chars:\n return ''\n \n old_cand = chars\n for m in range(2, max_chunk_sz+1):\n new_cand = []\n for t in self.get_next_level(old_cand, chars):\n if self.find(s, t*k):\n new_cand.append(t)\n \n if len(new_cand) == 0:\n break\n old_cand = new_cand\n return old_cand[0]\n \n def get_next_level(self, cand, chars):\n for s in cand:\n for ch in chars:\n yield s + ch\n \n def find(self, s, t):\n # find subsequence t in s\n j = 0\n for i in range(len(s)):\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n return True\n return False\n", + "title": "2014. Longest Subsequence Repeated k Times", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is considered beautiful if it satisfies the following conditions: For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful , but \"uaeio\" , \"aeoiu\" , and \"aaaeeeooo\" are not beautiful . Given a string word consisting of English vowels, return the length of the longest beautiful substring of word . If no such substring exists, return 0 . A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each of the 5 English vowels ( 'a' , 'e' , 'i' , 'o' , 'u' ) must appear at least once in it.", + "The letters must be sorted in alphabetical order (i.e. all 'a' s before 'e' s, all 'e' s before 'i' s, etc.)." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"Output:13Explanation:The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.", + "image": null + }, + { + "text": "Example 2: Input:word = \"aeeeiiiioooauuuaeiou\"Output:5Explanation:The longest beautiful substring in word is \"aeiou\" of length 5.", + "image": null + }, + { + "text": "Example 3: Input:word = \"a\"Output:0Explanation:There is no beautiful substring, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 192 ms (Top 11.20%) | Memory: 65.5 MB (Top 18.15%)\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n for(int i = 1;i verify = new HashSet<>();\n verify.add(word.charAt(i-1));\n while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){\n temp++;\n verify.add(word.charAt(i));\n i++;\n }\n max = verify.size() == 5 ? Math.max(max,temp) : max ;\n }\n\n return max;\n }\n}", + "title": "1839. Longest Substring Of All Vowels in Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A string is considered beautiful if it satisfies the following conditions: For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful , but \"uaeio\" , \"aeoiu\" , and \"aaaeeeooo\" are not beautiful . Given a string word consisting of English vowels, return the length of the longest beautiful substring of word . If no such substring exists, return 0 . A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each of the 5 English vowels ( 'a' , 'e' , 'i' , 'o' , 'u' ) must appear at least once in it.", + "The letters must be sorted in alphabetical order (i.e. all 'a' s before 'e' s, all 'e' s before 'i' s, etc.)." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"Output:13Explanation:The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.", + "image": null + }, + { + "text": "Example 2: Input:word = \"aeeeiiiioooauuuaeiou\"Output:5Explanation:The longest beautiful substring in word is \"aeiou\" of length 5.", + "image": null + }, + { + "text": "Example 3: Input:word = \"a\"Output:0Explanation:There is no beautiful substring, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n g = ''\n count = m = 0\n for x in word:\n if g and x < g[-1]:\n count = 0\n g = ''\n if not g or x > g[-1]:\n g += x\n count += 1\n if g == 'aeiou':\n m = max(m, count)\n return m\n", + "title": "1839. Longest Substring Of All Vowels in Order", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string s . You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k , both of which are used to describe k queries. The i th query updates the character in s at index queryIndices[i] to the character queryCharacters[i] . Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the i th query is performed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "k == queryCharacters.length == queryIndices.length", + "1 <= k <= 10^5", + "queryCharacters consists of lowercase English letters.", + "0 <= queryIndices[i] < s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babacc\", queryCharacters = \"bcb\", queryIndices = [1,3,3]Output:[3,3,4]Explanation:- 1stquery updates s = \"bbbacc\". The longest substring consisting of one repeating character is \"bbb\" with length 3.\n- 2ndquery updates s = \"bbbccc\". \n The longest substring consisting of one repeating character can be \"bbb\" or \"ccc\" with length 3.\n- 3rdquery updates s = \"bbbbcc\". The longest substring consisting of one repeating character is \"bbbb\" with length 4.\nThus, we return [3,3,4].", + "image": null + }, + { + "text": "Example 2: Input:s = \"abyzz\", queryCharacters = \"aa\", queryIndices = [2,1]Output:[2,3]Explanation:- 1stquery updates s = \"abazz\". The longest substring consisting of one repeating character is \"zz\" with length 2.\n- 2ndquery updates s = \"aaazz\". The longest substring consisting of one repeating character is \"aaa\" with length 3.\nThus, we return [2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 87 ms (Top 83.33%) | Memory: 76.70 MB (Top 22.22%)\n\nclass Solution {\n class TreeNode {\n //range\n int start;\n int end;\n \n //conti left char\n char leftChar;\n int leftCharLen;\n \n //conti right char\n char rightChar;\n int rightCharLen;\n \n int max;\n \n TreeNode left;\n TreeNode right;\n \n TreeNode(int start, int end) {\n this.start = start;\n this.end = end;\n left = null;\n right = null;\n }\n }\n\n public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) {\n char[] sChar = s.toCharArray();\n char[] qChar = queryCharacters.toCharArray();\n \n TreeNode root = buildTree(sChar, 0, sChar.length - 1);\n \n int[] result = new int[qChar.length];\n \n for (int i = 0; i < qChar.length; i++) {\n updateTree(root, queryIndices[i], qChar[i]);\n result[i] = root.max;\n }\n return result;\n }\n \n private TreeNode buildTree(char[] s, int from, int to) {\n if (from > to) return null;\n TreeNode root = new TreeNode(from, to);\n if (from == to) {\n root.max = 1;\n root.rightChar = root.leftChar = s[from];\n root.leftCharLen = root.rightCharLen = 1;\n return root;\n }\n \n int middle = from + (to - from) / 2;\n \n root.left = buildTree(s, from, middle);\n root.right = buildTree(s, middle + 1, to);\n \n updateNode(root);\n return root;\n \n }\n \n private void updateTree(TreeNode root, int index, char c) {\n if (root == null || root.start > index || root.end < index) {\n return;\n }\n if (root.start == index && root.end == index) {\n root.leftChar = root.rightChar = c;\n return;\n }\n updateTree(root.left, index, c);\n updateTree(root.right, index, c);\n \n updateNode(root);\n \n }\n \n private void updateNode(TreeNode root) {\n if (root == null) return;\n root.leftChar = root.left.leftChar;\n root.leftCharLen = root.left.leftCharLen;\n root.rightChar = root.right.rightChar;\n root.rightCharLen = root.right.rightCharLen;\n root.max = Math.max(root.left.max, root.right.max);\n if (root.left.rightChar == root.right.leftChar) {\n int len = root.left.rightCharLen + root.right.leftCharLen;\n if (root.left.leftChar == root.left.rightChar && root.left.leftCharLen == root.left.end - root.left.start + 1) {\n root.leftCharLen = len;\n }\n if (root.right.leftChar == root.right.rightChar && root.right.leftCharLen == root.right.end - root.right.start + 1) {\n root.rightCharLen = len;\n }\n root.max = Math.max(root.max, len);\n }\n }\n}\n", + "title": "2213. Longest Substring of One Repeating Character", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed string s . You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k , both of which are used to describe k queries. The i th query updates the character in s at index queryIndices[i] to the character queryCharacters[i] . Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the i th query is performed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "k == queryCharacters.length == queryIndices.length", + "1 <= k <= 10^5", + "queryCharacters consists of lowercase English letters.", + "0 <= queryIndices[i] < s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babacc\", queryCharacters = \"bcb\", queryIndices = [1,3,3]Output:[3,3,4]Explanation:- 1stquery updates s = \"bbbacc\". The longest substring consisting of one repeating character is \"bbb\" with length 3.\n- 2ndquery updates s = \"bbbccc\". \n The longest substring consisting of one repeating character can be \"bbb\" or \"ccc\" with length 3.\n- 3rdquery updates s = \"bbbbcc\". The longest substring consisting of one repeating character is \"bbbb\" with length 4.\nThus, we return [3,3,4].", + "image": null + }, + { + "text": "Example 2: Input:s = \"abyzz\", queryCharacters = \"aa\", queryIndices = [2,1]Output:[2,3]Explanation:- 1stquery updates s = \"abazz\". The longest substring consisting of one repeating character is \"zz\" with length 2.\n- 2ndquery updates s = \"aaazz\". The longest substring consisting of one repeating character is \"aaa\" with length 3.\nThus, we return [2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3460 ms (Top 87.5%) | Memory: 38.10 MB (Top 67.5%)\n\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n sl = SortedList()\n length = SortedList()\n curr = 0\n for char, it in itertools.groupby(s):\n c = sum(1 for _ in it)\n length.add(c)\n sl.add((curr, curr + c, char))\n curr += c\n ans = []\n for char, i in zip(queryCharacters, queryIndices):\n t = (i, math.inf, 'a')\n index = sl.bisect_right(t) - 1\n to_remove = [sl[index]]\n to_add = []\n left, right, original_char = to_remove[0]\n if original_char != char:\n length.remove(right - left)\n if right - left > 1:\n if i == left:\n left += 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n elif i == right - 1:\n right -= 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n else:\n to_add.append((left, i, original_char))\n length.add(i - left)\n to_add.append((i + 1, right, original_char))\n length.add(right - (i + 1))\n \n l, r = i, i + 1\n if index - 1 >= 0 and sl[index - 1][1:3] == (i, char):\n l, old_r, _ = sl[index - 1]\n to_remove.append(sl[index - 1])\n length.remove(old_r - l)\n if index + 1 < len(sl) and sl[index + 1][0] == i + 1 and sl[index + 1][2] == char:\n old_l, r, old_length = sl[index + 1]\n to_remove.append(sl[index + 1])\n length.remove(r - old_l)\n length.add(r - l)\n sl.add((l, r, char))\n for t in to_remove:\n sl.remove(t)\n sl.update(to_add)\n # print(sl)\n # print(length)\n ans.append(length[-1])\n\n return ans\n", + "title": "2213. Longest Substring of One Repeating Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabb\", k = 3Output:3Explanation:The longest substring is \"aaa\", as 'a' is repeated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababbc\", k = 2Output:5Explanation:The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1034 ms (Top 5.0%) | Memory: 40.34 MB (Top 79.2%)\n\n// Solution 1: O(n^2) brute force\n// time O(n^2)\n// space O(1)\nclass Solution {\n public int longestSubstring(String s, int k) {\n if (s == null || s.isEmpty() || k > s.length()) {\n return 0;\n }\n \n int[] map = new int[26]; // letter -> freq\n int n = s.length();\n int max = 0; // length of longest substring T so far\n for (int i = 0; i < n; i++) {\n Arrays.fill(map, 0);\n for (int j = i; j < n; j++) {\n map[s.charAt(j) - 'a']++; \n if (isValid(s, i, j, k, map)) {\n max = Math.max(max, j - i + 1);\n }\n }\n }\n \n return max;\n }\n \n // return true if each distinct character in the substring s[left..right] appear >= k times\n private boolean isValid(String s, int left, int right, int k, int[] map) {\n int numLetters = 0; // number of distinct letters\n int numLettersAtLeastK = 0;\n for (int num : map) {\n if (num > 0) {\n numLetters++;\n }\n \n if (num >= k) {\n numLettersAtLeastK++;\n }\n }\n \n return numLettersAtLeastK == numLetters;\n }\n}", + "title": "395. Longest Substring with At Least K Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s and an integer k , return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only lowercase English letters.", + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabb\", k = 3Output:3Explanation:The longest substring is \"aaa\", as 'a' is repeated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"ababbc\", k = 2Output:5Explanation:The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 57 ms (Top 73.85%) | Memory: 14.4 MB (Top 21.39%)\nfrom collections import Counter\n\nclass Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n return get_longest_substring(s, k)\n\ndef get_longest_substring(s, k):\n if len(s) == 0: return 0\n c = Counter(s)\n low_freq_char = set([char for char, freq in c.items() if freq < k])\n # base case\n if len(low_freq_char) == 0:\n return len(s)\n # recursively split str into substr\n division_points = [i for i in range(len(s)) if s[i] in low_freq_char]\n substr_lst = []\n # start\n substr_lst.append(s[:division_points[0]])\n # middle\n for i in range(len(division_points) - 1):\n substr_lst.append(s[division_points[i] + 1: division_points[i + 1]])\n # end\n substr_lst.append(s[division_points[-1] + 1:])\n return max([get_longest_substring(substr, k) for substr in substr_lst])", + "title": "395. Longest Substring with At Least K Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the length of the longest substring without repeating characters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"Output:3Explanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"Output:1Explanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"Output:3Explanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 310 ms (Top 7.97%) | Memory: 117.9 MB (Top 6.60%)\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Map hash = new HashMap<>();\n int count = 0;\n int ans = 0;\n for(int i=0; i < s.length(); i++){\n if(hash.containsKey(s.charAt(i))){\n i = hash.get(s.charAt(i)) + 1;\n hash.clear();\n count = 0;\n }\n if(!hash.containsKey(s.charAt(i))){\n hash.put(s.charAt(i), i);\n count++;\n ans = Math.max(ans, count);\n }\n }\n return ans;\n }\n}", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , find the length of the longest substring without repeating characters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"Output:3Explanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"Output:1Explanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"Output:3Explanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \n longest_s = ''\n curr_s = ''\n for i in s:\n if i not in curr_s:\n curr_s += i\n if len(curr_s) >= len(longest_s):\n longest_s = curr_s\n else:\n curr_s = curr_s[curr_s.index(i)+1:]+i\n \n return len(longest_s)\n", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For i <= k < j : arr[k] > arr[k + 1] when k is odd, and arr[k] < arr[k + 1] when k is even.", + "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.", + "arr[k] > arr[k + 1] when k is even, and", + "arr[k] < arr[k + 1] when k is odd." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,4,2,10,7,8,8,1,9]Output:5Explanation:arr[1] > arr[2] < arr[3] > arr[4] < arr[5]", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,12,16]Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [100]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxTurbulenceSize(int[] arr) {\n if(arr.length == 1) {\n return 1;\n } \n int l = 0, r = 1;\n int diff = arr[l] - arr[r];\n int max;\n if(diff == 0) {\n l = 1;\n r = 1;\n max = 1;\n } else {\n l = 0;\n r = 1;\n max = 2;\n }\n for(int i = 1; r < arr.length-1; i++) {\n int nextdiff = arr[i] - arr[i+1];\n if(diff < 0) {\n if(nextdiff > 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n } else {\n if(nextdiff < 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n }\n diff = nextdiff;\n max = Math.max(max, r-l+1);\n }\n return max;\n }\n}\n", + "title": "978. Longest Turbulent Subarray", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For i <= k < j : arr[k] > arr[k + 1] when k is odd, and arr[k] < arr[k + 1] when k is even.", + "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.", + "arr[k] > arr[k + 1] when k is even, and", + "arr[k] < arr[k + 1] when k is odd." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [9,4,2,10,7,8,8,1,9]Output:5Explanation:arr[1] > arr[2] < arr[3] > arr[4] < arr[5]", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,12,16]Output:2", + "image": null + }, + { + "text": "Example 3: Input:arr = [100]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1152 ms (Top 13.10%) | Memory: 18.7 MB (Top 31.75%)\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n def cmp(a,b):\n if a == b: return 0\n if a > b : return 1\n return -1\n\n n = len(arr)\n ans = 1\n prev = 0\n for i in range(1,n):\n c = cmp(arr[i-1],arr[i])\n if c == 0:\n # we shift prev to i\n prev = i\n elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1:\n ans = ans if ans > i - prev + 1 else i - prev + 1\n prev = i\n return ans", + "title": "978. Longest Turbulent Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings a and b , return the length of the longest uncommon subsequence between a and b . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between two strings is a string that is a subsequence of one but not the other . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"cdc\"Output:3Explanation:One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.", + "image": null + }, + { + "text": "Example 2: Input:a = \"aaa\", b = \"bbb\"Output:3Explanation:The longest uncommon subsequences are \"aaa\" and \"bbb\".", + "image": null + }, + { + "text": "Example 3: Input:a = \"aaa\", b = \"aaa\"Output:-1Explanation:Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.7 MB (Top 58.87%)\nclass Solution {\n public int findLUSlength(String a, String b) {\n if(a.equals(b)) return -1;\n return Math.max(a.length(),b.length());\n }\n}", + "title": "521. Longest Uncommon Subsequence I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings a and b , return the length of the longest uncommon subsequence between a and b . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between two strings is a string that is a subsequence of one but not the other . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"aba\", b = \"cdc\"Output:3Explanation:One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.", + "image": null + }, + { + "text": "Example 2: Input:a = \"aaa\", b = \"bbb\"Output:3Explanation:The longest uncommon subsequences are \"aaa\" and \"bbb\".", + "image": null + }, + { + "text": "Example 3: Input:a = \"aaa\", b = \"aaa\"Output:-1Explanation:Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 54.94%) | Memory: 13.9 MB (Top 58.35%)\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a == b:\n return -1\n\n else:\n return max(len(a), len(b))", + "title": "521. Longest Uncommon Subsequence I", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of strings strs , return the length of the longest uncommon subsequence between them . If the longest uncommon subsequence does not exist, return -1 . An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others . A subsequence of a string s is a string that can be obtained after deleting any number of characters from s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"a e b d c\" to get \"abc\" . Other subsequences of \"aebdc\" include \"aebdc\" , \"aeb\" , and \"\" (empty string)." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"aba\",\"cdc\",\"eae\"]Output:3", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"aaa\",\"aaa\",\"aa\"]Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 84.32%) | Memory: 39.8 MB (Top 90.27%)\nclass Solution {\n public int findLUSlength(String[] strs) {\n Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length\n // store the frequency of all strings in array\n Map map = new HashMap<>();\n for(String s : strs) map.put(s,map.getOrDefault(s,0)+1);\n\n for(int i=0;i int:\n def isSubseq(a, b):\n j = 0\n for i in range(len(b)):\n if a[j] == b[i]:\n j += 1\n if j == len(a):\n return True\n return False\n c = Counter(strs)\n s = sorted(c.keys(), key=len, reverse=True)\n for i in range(len(s)):\n if c[s[i]] > 1:\n continue\n if i == 0 or not any(isSubseq(s[i], s[j]) for j in range(i)): \n return len(s[i])\n return -1 \n", + "title": "522. Longest Uncommon Subsequence II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value . This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000", + "The depth of the tree will not exceed 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,5,1,1,null,5]Output:2Explanation:The shown image shows that the longest path of the same value (i.e. 5).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [1,4,5,4,4,null,5]Output:2Explanation:The shown image shows that the longest path of the same value (i.e. 4).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxLen = 0;\n public int longestUnivaluePath(TreeNode root) {\n lup(root);\n return maxLen;\n }\n public int lup(TreeNode root) {\n if (root == null) {\n return 0;\n }\n int left = lup(root.left);\n int right = lup(root.right);\n int leftMax = 0;\n int rightMax = 0;\n if (root.left != null && root.val == root.left.val) {\n leftMax = left + 1;\n }\n if (root.right != null && root.val == root.right.val) {\n rightMax = right + 1;\n }\n maxLen = Math.max(maxLen, leftMax + rightMax);\n return Math.max(leftMax, rightMax);\n }\n}\n", + "title": "687. Longest Univalue Path", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value . This path may or may not pass through the root. The length of the path between two nodes is represented by the number of edges between them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000", + "The depth of the tree will not exceed 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,5,1,1,null,5]Output:2Explanation:The shown image shows that the longest path of the same value (i.e. 5).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg" + }, + { + "text": "Example 2: Input:root = [1,4,5,4,4,null,5]Output:2Explanation:The shown image shows that the longest path of the same value (i.e. 4).", + "image": "https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tmax_path=0\n\tdef longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n\t\tself.dfs(root);\n\t\treturn self.max_path\n\n\tdef dfs(self,root):\n\t\tif root is None:return 0\n\t\tleft=self.dfs(root.left)\n\t\tright=self.dfs(root.right)\n\n\t\tif root.left and root.left.val == root.val:\n\t\t\tleftPath=left+1\n\t\telse:\n\t\t\tleftPath=0\n\n\t\tif root.right and root.right.val == root.val:\n\t\t\trightPath=right+1\n\t\telse:\n\t\t\trightPath=0\n\n\t\tself.max_path = max(self.max_path, leftPath + rightPath)\n\t\treturn max(leftPath, rightPath)\n", + "title": "687. Longest Univalue Path", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string containing just the characters '(' and ')' , find the length of the longest valid (well-formed) parentheses substring. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"Output:2Explanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"Output:4Explanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1644 ms (Top 5.15%) | Memory: 43.1 MB (Top 65.80%)\nclass Solution {\n public int longestValidParentheses(String s) {\n int i=0;\n int len=0;\n while(iopen) break;\n if(open==closed) len=Math.max(len,j-i+1);\n\n j++;\n }\n i++;\n }\n return len;\n }\n}", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string containing just the characters '(' and ')' , find the length of the longest valid (well-formed) parentheses substring. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"Output:2Explanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"Output:4Explanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 48.14%) | Memory: 14.8 MB (Top 24.60%)\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n\n maxi = 0\n stack = [-1]\n\n for i in range(len(s)) :\n if s[i] == \"(\" : stack.append(i)\n else :\n stack.pop()\n if len(stack) == 0 : stack.append(i)\n else : maxi = max(maxi, i - stack[-1])\n\n return maxi", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given hours , a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8 . A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= hours.length <= 10^4", + "0 <= hours[i] <= 16" + ], + "examples": [ + { + "text": "Example 1: Input:hours = [9,9,6,0,6,6,9]Output:3Explanation:The longest well-performing interval is [9,9,6].", + "image": null + }, + { + "text": "Example 2: Input:hours = [6,6,6]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)\n// For Longest Well Performing Interval/Window\n// T.C. = O(n^2) , S.C. = O(n)\nclass Solution {\n \n public int longestWPI(int[] hours) {\n int n = hours.length;\n \n int[] prefixSumTiringDaysMinusNonTiringDaysArr = new int[n + 1];\n prefixSumTiringDaysMinusNonTiringDaysArr[0] = 0;\n \n int prefixSumTiringDaysCount = 0;\n int prefixSumNonTiringDaysCount = 0;\n \n for (int i = 0 ; i < n ; i++) {\n int noOfHoursWorkedToday = hours[i];\n \n if (noOfHoursWorkedToday > 8) {\n prefixSumTiringDaysCount++;\n }\n else {\n prefixSumNonTiringDaysCount++;\n }\n \n prefixSumTiringDaysMinusNonTiringDaysArr[i + 1] = prefixSumTiringDaysCount - prefixSumNonTiringDaysCount;\n // System.out.print(prefixSumTiringDaysMinusNonTiringDaysArr[i] + \" \");\n }\n // System.out.println(prefixSumTiringDaysMinusNonTiringDaysArr[n]);\n \n int longestLengthOfContinuousPositiveSequence = 0;\n \n for (int currentSlidingWindowLength = 1 ; currentSlidingWindowLength <= n ; currentSlidingWindowLength++) {\n // System.out.print(currentSlidingWindowLength + \" - \");\n for (int i = 0 ; i <= n - currentSlidingWindowLength ; i++) {\n int j = i + currentSlidingWindowLength - 1;\n // System.out.print(i + \",\" + j + \" \");\n int currentIntervalNoOfTiringDaysMinusNonTiringDays = prefixSumTiringDaysMinusNonTiringDaysArr[j + 1] - prefixSumTiringDaysMinusNonTiringDaysArr[i];\n if (currentIntervalNoOfTiringDaysMinusNonTiringDays > 0) { // => currentInterval = Well Performing Interval\n longestLengthOfContinuousPositiveSequence = Math.max(currentSlidingWindowLength, longestLengthOfContinuousPositiveSequence);\n }\n }\n // System.out.println();\n }\n // System.out.println();\n \n int lengthOfLongestWellPerformingInterval = longestLengthOfContinuousPositiveSequence;\n \n return lengthOfLongestWellPerformingInterval;\n }\n \n}\n", + "title": "1124. Longest Well-Performing Interval", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We are given hours , a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8 . A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= hours.length <= 10^4", + "0 <= hours[i] <= 16" + ], + "examples": [ + { + "text": "Example 1: Input:hours = [9,9,6,0,6,6,9]Output:3Explanation:The longest well-performing interval is [9,9,6].", + "image": null + }, + { + "text": "Example 2: Input:hours = [6,6,6]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n #accumulative count\n #+1 when > 8, -1 when less than 8. \n #find strictly increasing length.\n \n p = [] #number of tiring days vs not\n c = 0\n for e in hours:\n if e > 8:\n c +=1\n else:\n c-=1\n \n p.append(c)\n \n \n \n #for every moment: we want earliest moment which could be positive overall tiring days.\n a = []\n #a is sorted by tiringnes. At day 8 have -2, want earliest point that could get us to at least 1.\n #so up until that point we have -3, -4, etc, and we want earliest out of it to get longest well performing interval. Which is when prefix comes in.\n \n a1 =[]\n for i in range(len(p)):\n a.append([p[i], i])\n a1.append(p[i])\n \n a1.sort() #bisectable list\n a.sort()\n \n prefix = []\n currearly = float('inf')\n for t, day in a:\n currearly = min(currearly, day)\n prefix.append(currearly)\n \n \n res = 0\n \n # print(p)\n \n for i in range(len(hours)):\n if p[i] > 0:\n res = max(res, i + 1) \n \n else:\n #find earliest \n #value must be less than -1-p[i] \n loc = bisect_right(a1, -1+p[i]) #bisect right means anything before this is less than or equals to\n \n \n \n if loc == 0: #the rightmost place to put it is at the beginning...\n \n continue\n \n \n else:\n earliest = prefix[loc - 1]\n \n if earliest >= i: continue\n \n interval = i - earliest #notice: we're not including the starting index, since its also technically being removed!\n\n # print(\"From day\", earliest, \"to\", i)\n \n res = max(res, interval)\n \n \n \n return res\n \n \n \n \n", + "title": "1124. Longest Well-Performing Interval", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words . If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. Note that the word should be built from left to right with each additional character being added to the end of a previous word. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length <= 30", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]Output:\"world\"Explanation:The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]Output:\"apple\"Explanation:Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private class Node{\n Node[] sub;\n Node(){\n sub = new Node[26];\n }\n }\n Node root;\n StringBuilder ans;\n private void buildTire(String word){\n Node temp = root;\n int n = word.length();\n for(int i = 0; i < n-1; i++){\n int index = word.charAt(i)-'a';\n if(temp.sub[index] == null) return;\n temp = temp.sub[index];\n }\n int index = word.charAt(n-1)-'a';\n temp.sub[index] = new Node();\n \n if(word.length() > ans.length())\n ans = new StringBuilder(word);\n }\n public String longestWord(String[] words) {\n this.ans = new StringBuilder();\n this.root = new Node();\n PriorityQueue pq = new PriorityQueue<>();\n pq.addAll(Arrays.asList(words));\n while(!pq.isEmpty()) buildTire(pq.poll());\n return ans.toString();\n }\n}\n", + "title": "720. Longest Word in Dictionary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words . If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. Note that the word should be built from left to right with each additional character being added to the end of a previous word. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 1000", + "1 <= words[i].length <= 30", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]Output:\"world\"Explanation:The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]Output:\"apple\"Explanation:Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 240 ms (Top 36.59%) | Memory: 15.2 MB (Top 46.59%)\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n TrieNode = lambda: defaultdict(TrieNode)\n root = TrieNode()\n for i,s in enumerate(words):\n cur = root\n for c in s: cur=cur[c]\n cur['$']=i\n\n ans = ''\n st = list(root.values())\n while st:\n cur = st.pop()\n if '$' in cur:\n w = words[cur['$']]\n if len(ans) dictionary) {\n \n int[] fre=new int[26];\n \n \n String ans=\"\";\n int flag=0;\n int[] fff=new int[26];\n char[] ch = s.toCharArray();\n for(char c : ch)\n fre[c-'a']+=1;\n \n for(String s1 : dictionary)\n { \n fff=fre.clone();\n int[] fre1=new int[26];\n char[] ch1 = s1.toCharArray();\n for(char c : ch1)\n {\n \n fre1[c-'a']+=1;\n }\n \n for(char c : ch1)\n {\n if(fre1[c-'a'] <= fff[c-'a'])\n { flag=0;\n fff[c-'a']-=1; \n fre1[c-'a']-=1;\n }\n else\n {flag=1;\n break;} \n }\n if(flag==0)\n {\n if(ans != \"\")\n {\n if(ans.length() s1.charAt(m))\n {\n f=1;\n break;\n }\n \n }\n if(f==1)\n ans=s1;\n }\n }\n }\n else\n ans =s1;\n }\n else\n {\n flag=0;\n }\n }\n \n return ans;\n \n }\n}\n\n", + "title": "524. Longest Word in Dictionary through Deleting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and a string array dictionary , return the longest string in the dictionary that can be formed by deleting some of the given string characters . If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 1000", + "s and dictionary[i] consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]Output:\"apple\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]Output:\"a\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLongestWord(self, s: str, dictionary: list[str]) -> str:\n solution = \"\"\n for word in dictionary:\n j = 0\n for i in range(len(s)):\n if s[i] == word[j]:\n j+=1\n if j == len(word):\n solution = word if len(word) > len(solution) or len(word) == len(solution) and word < solution else solution\n break\n return solution", + "title": "524. Longest Word in Dictionary through Deleting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]Output:3Explanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]Output:4Explanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 84.82%) | Memory: 54.1 MB (Top 87.52%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n static class Pair{\n int left=-1;\n int right=-1;\n int maxLen=0;\n }\n public int longestZigZag(TreeNode root) {\n Pair ans=longestZigZag_(root);\n return ans.maxLen;\n }\n\n public Pair longestZigZag_(TreeNode root) {\n if(root==null)\n return new Pair();\n Pair l=longestZigZag_(root.left);\n Pair r=longestZigZag_(root.right);\n\n Pair myAns=new Pair();\n myAns.left=l.right+1;\n myAns.right=r.left+1;\n int max=Math.max(myAns.left,myAns.right);\n myAns.maxLen=Math.max(max,Math.max(l.maxLen,r.maxLen));\n return myAns;\n\n }\n\n}", + "title": "1372. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]Output:3Explanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]Output:4Explanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 437 ms (Top 91.25%) | Memory: 59.8 MB (Top 86.06%)\n\nclass Solution:\n def longestZigZag(self, root: Optional[TreeNode]) -> int:\n self.res = 0\n\n def helper(root):\n if root is None:\n return -1, -1\n\n leftRight = helper(root.left)[1] + 1\n rightLeft = helper(root.right)[0] + 1\n self.res = max(self.res, leftRight, rightLeft)\n return leftRight, rightLeft\n\n helper(root)\n return self.res", + "title": "1372. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness. You are given an array richer where richer[i] = [a i , b i ] indicates that a i has more money than b i and an integer array quiet where quiet[i] is the quietness of the i th person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y] ) among all people who definitely have equal to or more money than the person x . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == quiet.length", + "1 <= n <= 500", + "0 <= quiet[i] < n", + "All the values of quiet are unique .", + "0 <= richer.length <= n * (n - 1) / 2", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs of richer are unique .", + "The observations in richer are all logically consistent." + ], + "examples": [ + { + "text": "Example 1: Input:richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]Output:[5,5,2,5,4,5,6,7]Explanation:answer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.", + "image": null + }, + { + "text": "Example 2: Input:richer = [], quiet = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 42.47%) | Memory: 65.2 MB (Top 60.25%)\nclass Solution {\n ArrayList> adj =new ArrayList<>();\n int res[];\n public int[] loudAndRich(int[][] richer, int[] quiet) {\n int n=quiet.length;\n res=new int[n];\n Arrays.fill(res,-1);\n for(int i=0;i());\n for(int i=0;i());\n adj.get(richer[i][1]).add(richer[i][0]);\n }\n for(int i=0;i List[int]:\n length = len(quiet)\n arr = [i for i in range(length)]\n indegree = [0 for _ in range(length)]\n graph = collections.defaultdict(list)\n dq = collections.deque([])\n \n for a, b in richer:\n # Note that the graph is uni-directional\n graph[a].append(b)\n indegree[b] += 1\n\n for i in range(length):\n if not indegree[i]: \n dq.append(i)\n \n while dq:\n node = dq.popleft()\n \n for vertex in graph[node]:\n indegree[vertex] -= 1\n if quiet[arr[node]] < quiet[arr[vertex]]:\n arr[vertex] = arr[node]\n if not indegree[vertex]:\n dq.append(vertex)\n return arr\n", + "title": "851. Loud and Rich", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8Output:6Explanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4Output:2Explanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 35.9%) | Memory: 43.95 MB (Top 54.7%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n if(root == null || root == p || root == q)return root;\n\n TreeNode left = lowestCommonAncestor(root.left, p , q);\n TreeNode right = lowestCommonAncestor(root.right, p ,q);\n\n if(left == null)return right;\n if(right == null)return left;\n else{\n return root;\n }\n }\n}", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8Output:6Explanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4Output:2Explanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \n if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)):\n return root\n elif (root.val > p.val):\n return self.lowestCommonAncestor(root.left, p, q)\n else:\n return self.lowestCommonAncestor(root.right, p , q)\n", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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: Example 2: Example 3:", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1Output:3Explanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4Output:5Explanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n List path_to_p= new ArrayList<>();\n List path_to_q= new ArrayList<>();\n getPath(root,p,path_to_p);\n getPath(root,q,path_to_q);\n int n=path_to_q.size()>path_to_p.size()?path_to_p.size():path_to_q.size();\n TreeNode anscesstor=root;\n for(int i=0;i list){\n if(root==null) return false;\n list.add(root);\n if(root==target) return true;\n if(getPath(root.left,target,list) || getPath(root.right,target,list)){\n return true;\n }\n list.remove(list.size()-1);\n return false;\n }\n}\n", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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: Example 2: Example 3:", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1Output:3Explanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4Output:5Explanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 197 ms (Top 13.70%) | Memory: 26.4 MB (Top 30.94%)\nclass Solution:\n # @param {TreeNode} root\n # @param {TreeNode} p\n # @param {TreeNode} q\n # @return {TreeNode}\n def lowestCommonAncestor(self, root, p, q):\n # escape condition\n if (not root) or (root == p) or (root == q):\n return root\n # search left and right subtree\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if left and right:\n # both found, root is the LCA\n return root\n return left or right", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves . Recall that: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The node of a binary tree is a leaf if and only if it has no children", + "The depth of the root of the tree is 0 . if the depth of a node is d , the depth of each of its children is d + 1 .", + "The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]Output:[2,7,4]Explanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:[1]Explanation:The root is the deepest node in the tree, and it's the lca of itself.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]Output:[2]Explanation:The deepest leaf node in the tree is 2, the lca of one node is itself.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 8.73%) | Memory: 45 MB (Top 22.93%)\nclass Solution {\n public TreeNode lcaDeepestLeaves(TreeNode root) {\n if (root.left == null && root.right == null) return root;\n int depth = findDepth(root);\n Queue q = new LinkedList<>();\n q.offer(root);\n int count = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n count++;\n if (count == depth) {\n break;\n }\n for (int i = 0; i < size; i++) {\n TreeNode cur = q.poll();\n if (cur.left != null) q.offer(cur.left);\n if (cur.right != null) q.offer(cur.right);\n }\n }\n Set set = new HashSet<>();\n while (!q.isEmpty()) {\n set.add(q.poll().val);\n }\n return find(root, set);\n }\n\n public int findDepth(TreeNode root) {\n if (root == null) return 0;\n int left = findDepth(root.left);\n int right = findDepth(root.right);\n return 1 + Math.max(left, right);\n }\n\n public TreeNode find(TreeNode root, Set set) {\n if (root == null) return root;\n if (set.contains(root.val)) return root;\n TreeNode left = find(root.left, set);\n TreeNode right = find(root.right, set);\n if (left != null && right != null) return root;\n else if (left != null) return left;\n else if (right != null) return right;\n else return null;\n }\n}\n", + "title": "1123. Lowest Common Ancestor of Deepest Leaves", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves . Recall that: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The node of a binary tree is a leaf if and only if it has no children", + "The depth of the root of the tree is 0 . if the depth of a node is d , the depth of each of its children is d + 1 .", + "The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]Output:[2,7,4]Explanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:[1]Explanation:The root is the deepest node in the tree, and it's the lca of itself.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]Output:[2]Explanation:The deepest leaf node in the tree is 2, the lca of one node is itself.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 112 ms (Top 7.97%) | Memory: 14.4 MB (Top 40.85%)\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n\n self.max_lvl = (0,[])\n self.pathes = {}\n def rec(root,parent,lvl):\n if not root:\n return\n if lvl > self.max_lvl[0]:\n self.max_lvl = (lvl,[root])\n elif lvl == self.max_lvl[0]:\n self.max_lvl = (lvl,self.max_lvl[1]+[root])\n self.pathes[root] = parent\n rec(root.left,root,lvl+1)\n rec(root.right,root,lvl+1)\n rec(root,None,0)\n print(self.max_lvl)\n # for key in self.pathes:\n # if key!=None and self.pathes[key]!=None:\n # print(key.val,\"-\",self.pathes[key].val)\n if len(self.max_lvl[1]) < 2:\n return self.max_lvl[1][0]\n parent = self.max_lvl[1]\n while len(parent) > 1:\n temp = set()\n for p in parent:\n temp.add(self.pathes.get(p,None))\n parent = temp\n return parent.pop()\n", + "title": "1123. Lowest Common Ancestor of Deepest Leaves", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n // Declare Node class for Doubly Linked List \n class Node{\n int key,value;// to store key and value \n Node next,prev; // Next and Previous Pointers\n Node(int k, int v){\n key=k;\n value=v;\n }\n }\n Node head=new Node(-1,-1); // Default values \n Node tail=new Node(-1,-1);\n Mapmp; // to store key and Node\n int cap;\n public LRUCache(int capacity) {\n // initializing in constructor\n cap=capacity;\n head.next=tail;\n tail.prev=head;\n mp=new HashMap();\n }\n \n public int get(int key) {\n // if map contains the specific key \n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n del(existing);\n ins(existing);// reinserting to keep key after the head pointer and to update LRU list\n return existing.value;\n }\n //otherwise\n return -1;\n }\n \n public void put(int key, int value) {\n // if map contains the key\n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n // remove from the map and delete from the LRU list\n mp.remove(key);\n del(existing);\n }\n // if map size is equal to spcified capacity of the LRU list\n if(mp.size()==cap){\n // remove from the map and delete from the LRU list\n mp.remove(tail.prev.key);\n del(tail.prev);\n }\n Node newNode = new Node(key,value);\n ins(newNode); \n mp.put(key,head.next); \n }\n public void ins(Node newNode){\n //Insert always after the head of the linkedList\n Node temp=head.next;\n head.next=newNode;\n newNode.prev=head;\n newNode.next=temp;\n temp.prev=newNode;\n }\n public void del(Node newNode){\n //Remove the specified node using previous and next pointers\n Node pr=newNode.prev;\n Node nx=newNode.next;\n pr.next=nx;\n nx.prev=pr;\n \n }\n}\n\n", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n int N;\n list pages;\n unordered_map::iterator>> cache;\npublic:\n LRUCache(int capacity) : N(capacity) {\n \n }\n \n int get(int key) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n pages.push_front(key);\n cache[key].second = pages.begin();\n return cache[key].first;\n }\n \n return -1;\n }\n \n void put(int key, int value) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n } else {\n if (pages.size() == N) {\n int lru = pages.back();\n cache.erase(lru);\n pages.pop_back();\n }\n }\n \n pages.push_front(key);\n cache[key] = {value, pages.begin()};\n }\n};\n", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order . A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= n, m <= 50", + "1 <= matrix[i][j] <= 10^5 .", + "All elements in the matrix are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[3,7,8],[9,11,13],[15,16,17]]Output:[15]Explanation:15 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]Output:[12]Explanation:12 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[7,8],[1,2]]Output:[7]Explanation:7 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List luckyNumbers (int[][] matrix) {\n List luckyNums = new ArrayList();\n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int[] row : matrix){\n int min = row[0];\n int index = 0;\n boolean lucky = true;\n for(int col = 0; col < m; col++){\n if(min > row[col]){\n min = row[col];\n index = col;\n }\n }\n \n for(int r = 0; r < n; r++){\n if(min < matrix[r][index]){\n lucky = false;\n break;\n }\n }\n if(lucky){\n luckyNums.add(min);\n }\n \n }\n \n return luckyNums;\n \n }\n}\n", + "title": "1380. Lucky Numbers in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order . A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= n, m <= 50", + "1 <= matrix[i][j] <= 10^5 .", + "All elements in the matrix are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[3,7,8],[9,11,13],[15,16,17]]Output:[15]Explanation:15 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]Output:[12]Explanation:12 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[7,8],[1,2]]Output:[7]Explanation:7 is the only lucky number since it is the minimum in its row and the maximum in its column.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n min_, max_ = 0, 0\n min_temp = []\n max_temp = []\n m = len(matrix)\n n = len(matrix[0])\n for i in matrix:\n min_temp.append(min(i))\n print(min_temp)\n if n >= m:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))\n elif n == 1:\n for i in range(m):\n max_check = []\n for j in range(n):\n max_check.append(matrix[i][j])\n max_temp.append(max(max_check))\n return [max(max_temp)]\n else:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))\n", + "title": "1380. Lucky Numbers in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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?  (Each subgrid is contiguous). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 10", + "0 <= grid[i][j] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]Output:1Explanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/09/11/magic_main.jpg" + }, + { + "text": "Example 2: Input:grid = [[8]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int numMagicSquaresInside(int[][] grid) {\n\t\tint n=grid.length,m=grid[0].length,count=0;\n\t\tfor(int i=0;i9 ||count[grid[x+i][y+j]]!=0)\n\t\t\t\t\treturn false;\n\t\t\t\tcount[grid[x+i][y+j]]=1;\n\n\t\t\t}\n\t\t\tif(sum1!=sum || sum!=sum2 || sum1!=sum2)\n\t\t\t\treturn false;\n\t\t}\n\t\tsum1=grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2];\n\t\tsum2=grid[x][y+2]+grid[x+1][y+1]+grid[x+2][y];\n\t\tif(sum1!=sum2 || sum1!=sum)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n", + "title": "840. Magic Squares In Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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?  (Each subgrid is contiguous). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "row == grid.length", + "col == grid[i].length", + "1 <= row, col <= 10", + "0 <= grid[i][j] <= 15" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]Output:1Explanation: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.", + "image": "https://assets.leetcode.com/uploads/2020/09/11/magic_main.jpg" + }, + { + "text": "Example 2: Input:grid = [[8]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n @classmethod\n def magic_3_3(cls, square: List[List[int]]) -> bool:\n if set(sum(square, [])) != Solution.digits:\n return False\n sum_row0 = sum(square[0])\n for r in range(1, 3):\n if sum(square[r]) != sum_row0:\n return False\n if any(sum(col) != sum_row0 for col in zip(*square)):\n return False\n sum_main_diagonal = sum_second_diagonal = 0\n for i in range(3):\n sum_main_diagonal += square[i][i]\n sum_second_diagonal += square[i][2 - i]\n return sum_main_diagonal == sum_second_diagonal == sum_row0\n\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n count = 0\n rows, cols = len(grid), len(grid[0])\n for r in range(rows - 2):\n for c in range(cols - 2):\n if Solution.magic_3_3([grid[row_idx][c: c + 3]\n for row_idx in range(r, r + 3)]):\n count += 1\n return count\n", + "title": "840. Magic Squares In Grid", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A magical string s consists of only '1' and '2' and obeys the following rules: The first few elements of s is s = \"1221121221221121122……\" . If we group the consecutive 1 's and 2 's in s , it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1 's or 2 's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\" . You can see that the occurrence sequence is s itself. Given an integer n , return the number of 1 's in the first n number in the magical string s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6Output:3Explanation:The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 32.48%) | Memory: 43.8 MB (Top 21.66%)\nclass Solution {\n public int magicalString(int n) {\n if(n <= 3)\n return 1;\n Magical m = new Magical();\n int ans = 1;\n for(int i = 3; i < n; ++i)\n if(m.next() == 1)\n ++ans;\n return ans;\n }\n}\n\nclass Magical{\n\n private Deque nums;\n private int n;\n\n public Magical(){\n nums = new ArrayDeque<>();\n nums.offerLast(1);\n nums.offerLast(1);\n n = 1;\n }\n\n public int next(){\n if(n-- < 0){\n int c = nums.pollFirst();\n n = c - 2;\n int curr = 3 - nums.peekLast();\n for(; c > 0; --c)\n nums.offerLast(curr);\n return curr;\n }\n return nums.peekLast();\n }\n}", + "title": "481. Magical String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A magical string s consists of only '1' and '2' and obeys the following rules: The first few elements of s is s = \"1221121221221121122……\" . If we group the consecutive 1 's and 2 's in s , it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1 's or 2 's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\" . You can see that the occurrence sequence is s itself. Given an integer n , return the number of 1 's in the first n number in the magical string s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6Output:3Explanation:The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 489 ms (Top 6.14%) | Memory: 14.1 MB (Top 72.07%)\nclass Solution:\n def magicalString(self, n: int) -> int:\n queue, ans, i = deque([2]), 1, 1\n\n while i <= n - 2:\n m = queue.popleft()\n ans += (m == 1)\n queue.extend([1 + (i % 2 == 0)] * m)\n i += 1\n\n return ans", + "title": "481. Magical String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the i th basket is at position[i] , Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum . Rick stated that magnetic force between two different balls at positions x and y is |x - y| . Given the integer array position and the integer m . Return the required force . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == position.length", + "2 <= n <= 10^5", + "1 <= position[i] <= 10^9", + "All integers in position are distinct .", + "2 <= m <= position.length" + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3,4,7], m = 3Output:3Explanation:Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.", + "image": "https://assets.leetcode.com/uploads/2020/08/11/q3v1.jpg" + }, + { + "text": "Example 2: Input:position = [5,4,3,2,1,1000000000], m = 2Output:999999999Explanation:We can use baskets 1 and 1000000000.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 68.1%) | Memory: 57.23 MB (Top 20.3%)\n\nclass Solution {\n public int maxDistance(int[] position, int m) {\n Arrays.sort(position);\n int low=Integer.MAX_VALUE;\n int high=0;\n for(int i=1;i=maxPossibleDist){\n prevballplace=position[i];\n balls++;\n }\n }\n if(balls>=m){\n return true;\n }\n return false;\n }\n}", + "title": "1552. Magnetic Force Between Two Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the i th basket is at position[i] , Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum . Rick stated that magnetic force between two different balls at positions x and y is |x - y| . Given the integer array position and the integer m . Return the required force . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == position.length", + "2 <= n <= 10^5", + "1 <= position[i] <= 10^9", + "All integers in position are distinct .", + "2 <= m <= position.length" + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3,4,7], m = 3Output:3Explanation:Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.", + "image": "https://assets.leetcode.com/uploads/2020/08/11/q3v1.jpg" + }, + { + "text": "Example 2: Input:position = [5,4,3,2,1,1000000000], m = 2Output:999999999Explanation:We can use baskets 1 and 1000000000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def possible (self,distance,positions,M):\n ball = 1 \n lastPos = positions[0] \n for pos in positions:\n if pos-lastPos >= distance:\n ball+=1 \n if ball == M: return True \n lastPos=pos \n \n return False \n \n \n \n def maxDistance(self, positions,M):\n positions.sort()\n low = 0 \n high = positions [-1] \n ans = 0\n while low<=high:\n distance = low+(high-low)//2 \n \n if self.possible(distance,positions,M):\n ans = distance\n low=distance+1 \n else:\n high=distance-1 \n return ans \n", + "title": "1552. Magnetic Force Between Two Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]Output:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 14 ms (Top 32.93%) | Memory: 56.8 MB (Top 19.67%)\nclass Solution {\n public int majorityElement(int[] nums) {\n // Base case...\n if (nums.length == 1) {\n return nums[0];\n }\n // Sort nums array...\n Arrays.sort(nums);\n // Since the majority element appears more than n / 2 times...\n // The n/2 -th element in the sorted nums must be the majority element...\n return nums[nums.length / 2];\n }\n}", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]Output:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution(object):\n def majorityElement(self, nums):\n sol = None\n cnt = 0\n for i in nums:\n if cnt == 0:\n sol = i\n cnt += (1 if i == sol else -1)\n return sol\n", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array of size n , find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]Output:[3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List majorityElement(int[] nums) {\n int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;\n for(int i = 1; i < nums.length; i++){\n if(val1 == nums[i]){\n cnt1++;\n } else if(val2 == nums[i]){\n cnt2++;\n } else{\n if(cnt1 == 0){\n val1 = nums[i];\n cnt1++;\n } else if(cnt2 == 0){\n val2 = nums[i];\n cnt2++;\n } else{\n cnt1--;\n cnt2--;\n }\n }\n }\n int check1 = 0, check2 = 0;\n for(int i = 0; i < nums.length; i++){\n if(val1 == nums[i])check1++;\n else if(val2 == nums[i])check2++;\n }\n List ans = new ArrayList<>();\n if(check1 > nums.length / 3) ans.add(val1);\n if(check2 > nums.length / 3) ans.add(val2);\n return ans;\n }\n}\n", + "title": "229. Majority Element II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array of size n , find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]Output:[3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n \n #Boyer Moore Voting Algo (As used in ME1 ques) \n #now we can observe that there cannot be more than two elements occuring more than n//3 times in an array\n #so find two majority elements(me=majority element)\n \n\n n=len(nums)\n req=n//3 #for an element to be ME required number of times present \n\n c1=0 #count 1\n c2=0 #count 2\n me1=None #majority element 1\n me2=None #majority element 2\n\n for i in nums:\n if i == me1:\n c1+=1\n\n elif i == me2:\n c2+=1\n\n elif c1 == 0:\n me1=i\n c1=1\n\n elif c2 == 0:\n me2=i\n c2=1\n\n else:\n c1-=1\n c2-=1\n #here we have found our majority elements now check if the found majority element is ME\n # print(me1,me2)\n\n #check if the found majority element is ME\n c1=0\n c2=0\n for i in nums:\n if i==me1:\n c1+=1\n if i==me2:\n c2+=1\n # print(c1,c2)\n\n if c1 > req and c2 > req:\n\n return [me1,me2]\n\n elif c1> req :\n return [me1]\n\n elif c2> req :\n return [me2]\n\n", + "title": "229. Majority Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays arr1 and arr2 , return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j] . If there is no way to make arr1 strictly increasing, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 2000", + "0 <= arr1[i], arr2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]Output:1Explanation:Replace5with2, thenarr1 = [1, 2, 3, 6, 7].", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,5,3,6,7], arr2 = [4,3,1]Output:2Explanation:Replace5with3and then replace3with4.arr1 = [1, 3, 4, 6, 7].", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]Output:-1Explanation:You can't makearr1strictly increasing.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 329 ms (Top 20.6%) | Memory: 44.12 MB (Top 82.6%)\n\nclass Solution {\n public int makeArrayIncreasing(int[] A, int[] B) { // A = arr1, B = arr2\n TreeSet set = new TreeSet<>(Arrays.stream(B).boxed().toList());\n int[] dp = new int[B.length+1];\n dp[0]=-1;\n int INF = (int)2e9;\n for (int i = 0; i < A.length; i++){\n for (int j = B.length; j >= 0; j--){\n int a = A[i] > dp[j]? A[i] : INF; // option A - don't swap\n Integer b = set.higher(j==0?INF:dp[j-1]); // option B - swap\n dp[j]=Math.min(a, b==null?INF:b); // take the min of A and B\n }\n }\n for (int i = 0; i <= B.length; i++) if (dp[i] != INF){\n return i;\n }\n return -1;\n }\n}", + "title": "1187. Make Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays arr1 and arr2 , return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j] . If there is no way to make arr1 strictly increasing, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 2000", + "0 <= arr1[i], arr2[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]Output:1Explanation:Replace5with2, thenarr1 = [1, 2, 3, 6, 7].", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,5,3,6,7], arr2 = [4,3,1]Output:2Explanation:Replace5with3and then replace3with4.arr1 = [1, 3, 4, 6, 7].", + "image": null + }, + { + "text": "Example 3: Input:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]Output:-1Explanation:You can't makearr1strictly increasing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n1 , n2, dp = len(arr1) , len(arr2) , {}\n arr2.sort()\n \n def solve(i , j , prev):\n \n if i == n1:return 0\n \n if (i,j,prev) in dp: return dp[(i,j,prev)]\n \n k = bisect.bisect_right(arr2[j:],prev) + j\n \n ans = float('inf') if k == n2 else solve(i+1,k+1,arr2[k]) + 1\n \n if arr1[i] > prev:ans = min(ans,solve(i+1 , j ,arr1[i]))\n \n dp[(i,j,prev)] = ans\n \n return ans\n \n \n ans = solve(0,0,-float('inf'))\n \n return ans if ans != float('inf') else -1", + "title": "1187. Make Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a non-negative integer array nums . In one operation, you must: Return the minimum number of operations to make every element in nums equal to 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums .", + "Subtract x from every positive element in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,0,3,5]Output:3Explanation:In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:0Explanation:Each element in nums is already 0 so no operations are needed.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.28%) | Memory: 40.90 MB (Top 7.16%)\n\nclass Solution {\n public int minimumOperations(int[] nums) {\n Set s = new HashSet<>();\n int result = 0;\n if(nums[0] == 0 && nums.length == 1){\n return 0;\n }\n else{\n for (int num : nums) {\n s.add(num);\n }\n for (int num : nums) {\n s.remove(0);\n }\n result = s.size();;\n }\n return result;\n }\n}\n", + "title": "2357. Make Array Zero by Subtracting Equal Amounts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a non-negative integer array nums . In one operation, you must: Return the minimum number of operations to make every element in nums equal to 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums .", + "Subtract x from every positive element in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,0,3,5]Output:3Explanation:In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:0Explanation:Each element in nums is already 0 so no operations are needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n return len(set(nums) - {0})\n", + "title": "2357. Make Array Zero by Subtracting Equal Amounts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers nums , remove the smallest subarray (possibly empty ) such that the sum of the remaining elements is divisible by p . It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible . A subarray is defined as a contiguous block of elements in the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= p <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,4,2], p = 6Output:1Explanation:The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,5,2], p = 9Output:2Explanation:We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3], p = 3Output:0Explanation:Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 457 ms (Top 46.03%) | Memory: 34.70 MB (Top 85.36%)\n\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n n = len(nums)\n target = sum(nums)%p\n if not target:\n return 0\n answer = n\n prefix_sum = 0\n hashmap = {0: -1}\n for i, num in enumerate(nums):\n prefix_sum += num\n key = (prefix_sum%p - target)%p\n if key in hashmap:\n answer = min(answer, i-hashmap[key])\n hashmap[prefix_sum%p] = i\n return answer if answer < n else -1\n", + "title": "1590. Make Sum Divisible by P", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abBAcC\"Output:\"\"Explanation:We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"s\"Output:\"s\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic String makeGood(String s) {\n char[] res = s.toCharArray();\n int i = 0;\n for( char n: s.toCharArray())\n {\n res[i] = n;\n \n if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32)\n {\n i-=2;\n }\n i++;\n }\n return new String(res, 0, i);\n}\n}\n", + "title": "1544. Make The String Great", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: 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\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abBAcC\"Output:\"\"Explanation:We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"s\"Output:\"s\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 76 ms (Top 13.82%) | Memory: 13.8 MB (Top 62.06%)\nclass Solution:\n def makeGood(self, s: str) -> str:\n while True:\n for i in range(len(s)-1):\n if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()):\n s = s[:i]+s[i+2:]\n break\n else:\n break\n return s", + "title": "1544. Make The String Great", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums ​​​ and an integer k ​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right , inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right] . Return the minimum number of elements to change in the array such that the XOR of all segments of size k ​​​​​​ is equal to zero. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 2000", + "​​​​​​0 <= nums[i] < 2 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0,3,0], k = 1Output:3Explanation:Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,5,2,1,7,3,4,7], k = 3Output:3Explanation:Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,4,1,2,5,1,2,6], k = 3Output:3Explanation:Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 100.0%) | Memory: 43.98 MB (Top 84.6%)\n\nclass Solution {\n public int minChanges(int[] nums, int k) {\n // solution (sequence) is uniquely defined by the first k elements, because a[i] == a[i+k] == a[i+2k] == ... for any offset i\n int v = 1 << 10;\n // best[pattern] is the highest number of relevant (ie. those with offsets between 0 and i) elements in nums\n // that can be left unchanged to achieve a[0] ^ a[1] ^ ... ^ a[i] == pattern\n int[] best = new int[v];\n // iterate over over each offset i of the solution\n for (int i = 0; i < k; i++) {\n // find frequencies of distinct element values present in the subsequence with offset i\n Map n2c = new HashMap();\n for (int p = i; p < nums.length; p += k) {\n n2c.put(nums[p],1+n2c.getOrDefault(nums[p],0));\n }\n // treat initial subsequence (i = 0) correctly\n if (i == 0) {\n for (int vv : n2c.keySet()) {\n best[vv] = n2c.get(vv);\n }\n continue;\n }\n int[] next = new int[v];\n int max = 0;\n for (int j : best) max = Math.max(max, j);\n // elements previously unchanged (ie. from subsequences with offsets 0, 1, 2, .., i-1) can be carried to the current offset i\n // max of all best[] is used\n for (int j = 0; j < v; j++) next[j] = max;\n // for elements present in the subsequnce with offset i next[] can be improved accordingly\n for (int vv : n2c.keySet()) {\n int cnt = n2c.get(vv);\n for (int j = 0; j < v; j++) {\n next[j ^ vv] = Math.max(next[j ^ vv], best[j] + cnt);\n }\n }\n best = next;\n }\n // solution is for pattern == 0, hence best[0]. Report minimum number of elements to change rather than maximum that can be left unchanged.\n return nums.length - best[0];\n }\n}", + "title": "1787. Make the XOR of All Segments Equal to Zero", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two integer arrays of equal length target and arr . In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "target.length == arr.length", + "1 <= target.length <= 1000", + "1 <= target[i] <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,4], arr = [2,4,1,3]Output:trueExplanation:You can follow the next steps to convert arr to target:\n1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.", + "image": null + }, + { + "text": "Example 2: Input:target = [7], arr = [7]Output:trueExplanation:arr is equal to target without any reverses.", + "image": null + }, + { + "text": "Example 3: Input:target = [3,7,9], arr = [3,7,11]Output:falseExplanation:arr does not have value 9 and it can never be converted to target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canBeEqual(int[] target, int[] arr) {\n HashMaphm1=new HashMap();\n for(int i: arr){\n if(hm1.containsKey(i))\n hm1.put(i,hm1.get(i)+1);\n else\n hm1.put(i,1);\n }\n for(int i: target){\n if(hm1.containsKey(i)){\n hm1.put(i,hm1.getOrDefault(i,0)-1);\n if(hm1.get(i)==0)\n hm1.remove(i);\n }\n else\n return false;\n \n }\n if(hm1.size()==0)\n return true;\n \n return false;\n }\n}\n", + "title": "1460. Make Two Arrays Equal by Reversing Sub-arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays of equal length target and arr . In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return true if you can make arr equal to target or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "target.length == arr.length", + "1 <= target.length <= 1000", + "1 <= target[i] <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,4], arr = [2,4,1,3]Output:trueExplanation:You can follow the next steps to convert arr to target:\n1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]\n2- Reverse sub-array [4,2], arr becomes [1,2,4,3]\n3- Reverse sub-array [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.", + "image": null + }, + { + "text": "Example 2: Input:target = [7], arr = [7]Output:trueExplanation:arr is equal to target without any reverses.", + "image": null + }, + { + "text": "Example 3: Input:target = [3,7,9], arr = [3,7,11]Output:falseExplanation:arr does not have value 9 and it can never be converted to target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n target.sort()\n arr.sort()\n if len(target)==len(arr):\n if target==arr:\n return True\n else:\n return False\n", + "title": "1460. Make Two Arrays Equal by Reversing Sub-arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary matrix grid . You are allowed to change at most one 0 to be 1 . Return the size of the largest island in grid after applying this operation . An island is a 4-directionally connected group of 1 s. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]Output:3Explanation:Change one 0 to 1 and connect two 1s, then we get an island with area = 3.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1],[1,0]]Output:4Explanation:Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1],[1,1]]Output:4Explanation:Can't change any 0 to 1, only one island with area = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int dir[][] = new int[][]{\n {1, 0},\n {-1,0},\n {0,1},\n {0,-1}\n };\n private int countArea(int grid[][], int i, int j, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)\n return 0;\n \n if(grid[i][j] != 1) return 0;\n \n grid[i][j] = num;\n int count = 0;\n for(int d[] : dir){\n count += countArea(grid, i + d[0], j + d[1], num);\n }\n \n return 1 + count;\n }\n \n private void fillDP(int grid[][], int dp[][], int i, int j, int count, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return ;\n \n if(grid[i][j] != num) return;\n \n if(dp[i][j] != 0) return ;\n dp[i][j] = count;\n for(int d[] : dir){\n fillDP(grid, dp, i + d[0], j + d[1], count, num);\n }\n \n }\n \n \n public int largestIsland(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n int dp[][] = new int[n][m];\n \n int num = 1;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] == 1){\n ++num;\n int count1 = countArea(grid, i, j, num);\n fillDP(grid, dp, i, j, count1, num);\n }\n }\n }\n \n int max = 0;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] != 0) continue;\n int val = 1;\n Set set = new HashSet<>();\n for(int d[] : dir){\n int newRow = i + d[0];\n int newCol = j + d[1];\n \n if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= m) continue;\n if(set.contains(grid[newRow][newCol])) continue;\n \n val += dp[newRow][newCol];\n set.add(grid[newRow][newCol]);\n }\n max = Math.max(max, val);\n }\n }\n \n if(max == 0) return n * m;\n return max;\n \n }\n}\n", + "title": "827. Making A Large Island", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n binary matrix grid . You are allowed to change at most one 0 to be 1 . Return the size of the largest island in grid after applying this operation . An island is a 4-directionally connected group of 1 s. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0],[0,1]]Output:3Explanation:Change one 0 to 1 and connect two 1s, then we get an island with area = 3.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,1],[1,0]]Output:4Explanation:Change the 0 to 1 and make the island bigger, only one island with area = 4.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1],[1,1]]Output:4Explanation:Can't change any 0 to 1, only one island with area = 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n # parent array to keey track\n parent = list(range(m*n))\n # rank array used for union by rank and size calculation\n rank = [1 for _ in range(m*n)]\n \n # standard DSU find function\n def find(x):\n while x != parent[x]:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n \n # standard DSU union by rank function\n def union(x,y):\n parX, parY = find(x), find(y)\n if parX == parY: return\n if rank[parX] >= rank[parY]:\n rank[parX] += rank[parY]\n parent[parY] = parX\n else:\n rank[parY] += rank[parX]\n parent[parX] = parY\n \n # Step 1: join the land\n\n # for each island we perform union operation\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # important condition: if we have a water body, we set its rank to 0 (will be used in the next step)\n if not val: \n rank[i*m+j] = 0\n continue\n \n # performing union of land bodies\n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n if grid[x][y]: union(i*m+j, x*m+y)\n \n # Step 2: convert a water body (if present)\n \n # the minimum final ans will always be the size of the largest land present \n ans = max(rank)\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # we dont need to do anything if we encounter a land\n if val: continue\n \n neighbours = set()\n res = 0\n \n # \n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n # checking unique neighbours by adding the parent to the set\n # here we dont care if the neighbour is water as its rank is 0 so it contributes nothing\n idx = x*m+y\n neighbours.add(find(idx))\n \n # Once we have all unique neighbours, just add their ranks\n for idx in neighbours:\n res += rank[idx]\n \n # res + 1 because we convert the current cell (i,j) to land too\n ans = max(ans, res+1)\n \n return ans\n", + "title": "827. Making A Large Island", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings names of size n . You will create n folders in your file system such that , at the i th minute, you will create a folder with the name names[i] . Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k) , where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the i th folder when you create it. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= names.length <= 5 * 10^4", + "1 <= names[i].length <= 20", + "names[i] consists of lowercase English letters, digits, and/or round brackets." + ], + "examples": [ + { + "text": "Example 1: Input:names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]Output:[\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]Explanation:Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"", + "image": null + }, + { + "text": "Example 2: Input:names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]Output:[\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]Explanation:Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"", + "image": null + }, + { + "text": "Example 3: Input:names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]Output:[\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]Explanation:When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Map map = new HashMap<>();\n \n public String[] getFolderNames(String[] names) {\n String[] op = new String[names.length];\n int i = 0;\n \n for(String cur : names){\n if(map.containsKey(cur)) {\n cur = generateCopyName(cur);\n op[i++] = cur;\n // System.out.println(map.toString());\n continue;\n }\n \n op[i++] = cur;\n map.put(cur, 0);\n // System.out.println(map.toString());\n }\n \n return op;\n }\n \n private String generateCopyName(String s) {\n int count = map.get(s) + 1;\n \n String postfix = \"(\" + count + \")\";\n StringBuilder sb = new StringBuilder(s);\n sb.append(postfix);\n \n boolean isChanged = false;\n while(map.containsKey(sb.toString())) {\n sb = new StringBuilder(s);\n sb.append(\"(\" + count + \")\");\n count++;\n isChanged = true;\n }\n String res = sb.toString();\n //System.out.println(res);\n \n \n if(isChanged)\n count = count -1;\n \n map.put(s, count);\n map.put(res, 0);\n \n return res;\n }\n}\n", + "title": "1487. Making File Names Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings names of size n . You will create n folders in your file system such that , at the i th minute, you will create a folder with the name names[i] . Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k) , where, k is the smallest positive integer such that the obtained name remains unique. Return an array of strings of length n where ans[i] is the actual name the system will assign to the i th folder when you create it. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= names.length <= 5 * 10^4", + "1 <= names[i].length <= 20", + "names[i] consists of lowercase English letters, digits, and/or round brackets." + ], + "examples": [ + { + "text": "Example 1: Input:names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]Output:[\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]Explanation:Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"", + "image": null + }, + { + "text": "Example 2: Input:names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]Output:[\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]Explanation:Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"", + "image": null + }, + { + "text": "Example 3: Input:names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]Output:[\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]Explanation:When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1004 ms (Top 5.08%) | Memory: 28.1 MB (Top 35.29%)\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # Hashmap will store the name as key and the number of times that name has duplicated so fas as value.\n hashmap = {}\n\n for name in names:\n modified = name\n # Check whether the name has already been used\n if name in hashmap:\n # Get the number of times the {name} has been used\n k = hashmap[name]\n # Calculate the next available suffix.\n while modified in hashmap:\n k += 1\n modified = f'{name}({k})'\n # Update the number of times the original {name} is used. This will help to efficiently check for next available suffix if the {name} again comes in future.\n hashmap[name] = k\n # Store the modified {name} with 0 as it is not duplicated yet.\n hashmap[modified] = 0\n\n # Return the keys of hashmap as that would be the unique file names.\n return hashmap.keys()", + "title": "1487. Making File Names Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]Output:[[1,0],[2,1]]Explanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]Output:[[1,1,0],[0,1,1],[1,2,2]]Explanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};\n int rows;\n int cols;\n int[][] isWater;\n\n \n public int[][] highestPeak(int[][] isWater) {\n this.isWater = isWater;\n rows = isWater.length;\n cols = isWater[0].length;\n \n\n int[][] heightCells = new int[rows][cols];\n \n //store the coordinate of water cell\n Queue queue = new LinkedList();\n \n for(int r = 0; r < rows; r++){\n for(int c = 0; c < cols; c++){\n if(isWater[r][c] == 1){\n \n //mark as water\n heightCells[r][c] = 0;\n \n //add water coordinate\n queue.add(new int[]{r, c});\n } else{\n //mark default value for land\n heightCells[r][c] = -1; \n }\n }\n }\n\n \n /*\n * Approach\n * 1. start from every water source, \n update their neighbor height\n * 2. add each neighbours which was not processed earlier\n 3. do it every cell is processed\n */\n bfs(queue, heightCells);\n \n \n return heightCells;\n }\n \n private void bfs(Queue queue, int[][] heightCells){\n \n while(!queue.isEmpty()){\n int[] cell = queue.remove();\n \n //increment height of neighbor cell in all 4 direction \n //e.g, left, right, up, down\n for(int[] dir : DIRECTION){\n \n int newRow = cell[0] + dir[0];\n int newCol = cell[1] + dir[1]; \n \n //check new coordinate of cell inside the grid or not\n if(!isInsideGrid(newRow, newCol)) continue;\n \n //check already handled\n if(heightCells[newRow][newCol] != -1) continue;\n\n //increament, \n heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1;\n \n //to handle the neighbour of this new cell\n queue.add(new int[]{newRow, newCol});\n }\n \n }\n }\n \n private boolean isInsideGrid(int row, int col){\n return row >= 0 && row < rows && col >= 0 && col < cols;\n } \n}\n", + "title": "1765. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]Output:[[1,0],[2,1]]Explanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]Output:[[1,1,0],[0,1,1],[1,2,2]]Explanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = collections.deque()\n m, n = len(isWater), len(isWater[0])\n for i in range(m):\n for j in range(n):\n if isWater[i][j] == 1:\n arr.append((0, i, j))\n \n ans = [[-1] * n for _ in range(m)]\n while arr:\n val, x, y = arr.popleft() \n if ans[x][y] != -1: continue\n ans[x][y] = val\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n xx, yy = x+dx, y+dy\n if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1:\n arr.append((val+1, xx, yy))\n return ans\n", + "title": "1765. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a map that allows you to do the following: Implement the MapSum class: Example 1:", + "description_images": [], + "constraints": [ + "Maps a string key to a given value.", + "Returns the sum of the values that have a key with a prefix equal to a given string." + ], + "examples": [ + { + "text": "Example 1: Input[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]Output[null, null, 3, null, 5]ExplanationMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3); \nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2); \nmapSum.sum(\"ap\"); // return 5 (apple +app = 3 + 2 = 5)", + "image": null + } + ], + "follow_up": null, + "solution": "class MapSum {\n private Map map;\n private Map words;\n\n public MapSum() {\n this.map = new HashMap<>();\n this.words = new HashMap<>();\n }\n \n public void insert(String key, int val) {\n Integer lookup = this.words.getOrDefault(key, null);\n int diff;\n if (lookup == null)\n diff = val;\n else\n diff = val - lookup;\n \n int k = key.length();\n \n StringBuilder sb = new StringBuilder(); \n for (int i = 0; i < k; i++) {\n sb.append(key.charAt(i));\n \n String prefix = sb.toString();\n map.put(prefix, map.getOrDefault(prefix, 0) + diff);\n }\n \n this.words.put(key, val);\n }\n \n public int sum(String prefix) {\n return this.map.getOrDefault(prefix, 0);\n }\n}\n\n/**\n * Your MapSum object will be instantiated and called as such:\n * MapSum obj = new MapSum();\n * obj.insert(key,val);\n * int param_2 = obj.sum(prefix);\n */\n", + "title": "677. Map Sum Pairs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a map that allows you to do the following: Implement the MapSum class: Example 1:", + "description_images": [], + "constraints": [ + "Maps a string key to a given value.", + "Returns the sum of the values that have a key with a prefix equal to a given string." + ], + "examples": [ + { + "text": "Example 1: Input[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]Output[null, null, 3, null, 5]ExplanationMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3); \nmapSum.sum(\"ap\"); // return 3 (apple = 3)\nmapSum.insert(\"app\", 2); \nmapSum.sum(\"ap\"); // return 5 (apple +app = 3 + 2 = 5)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 97.14%) | Memory: 17.50 MB (Top 9.54%)\n\nclass MapSum:\n\n def __init__(self):\n self.trie = {}\n\n def insert(self, key: str, val: int) -> None:\n node = self.trie\n for ch in key:\n node = node.setdefault(ch, {})\n node['val'] = val\n return\n\n def sum(self, prefix: str) -> int:\n def traverse(node):\n nonlocal res\n if not node:\n return\n if 'val' in node:\n res += node['val']\n for child in node:\n if child == 'val': continue\n traverse(node[child])\n return\n \n node = self.trie\n for ch in prefix:\n node = node.get(ch, {})\n if not node:\n return 0\n res = 0\n traverse(node)\n return res\n", + "title": "677. Map Sum Pairs", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a personal information string s , representing either an email address or a phone number . Return the masked personal information using the below rules . Email address: An email address is: To mask an email: Phone number: A phone number is formatted as follows: To mask a phone number: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A name consisting of uppercase and lowercase English letters, followed by", + "The '@' symbol, followed by", + "The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetCode@LeetCode.com\"Output:\"l*****e@leetcode.com\"Explanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AB@qq.com\"Output:\"a*****b@qq.com\"Explanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1(234)567-890\"Output:\"***-***-7890\"Explanation:s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.55%) | Memory: 42.3 MB (Top 50.00%)\nclass Solution {\n public String maskPII(String s) {\n StringBuilder sb = new StringBuilder();\n //email handeling\n if((s.charAt(0) >= 97 && s.charAt(0) <= 122) || (s.charAt(0) >= 65 && s.charAt(0) <= 90)){\n\n s = s.toLowerCase();\n int indexofAt = s.indexOf('@');\n String firstName = s.substring(0, indexofAt);\n sb.append(firstName.charAt(0)).append(\"*****\").append(firstName.charAt(firstName.length()-1));\n sb.append(s.substring(indexofAt,s.length()));\n }\n //phone number handeling\n else{\n int digits = 0;\n for(int i = 0 ; i < s.length(); i++){\n if(Character.isDigit(s.charAt(i))){\n digits++;\n }\n }\n if(digits > 10){\n sb.append('+');\n }\n while(digits > 10){\n sb.append('*');\n digits--;\n }\n if(sb.toString().isEmpty() == false){\n sb.append('-');\n }\n sb.append(\"***\").append('-').append(\"***-\");\n StringBuilder last4 = new StringBuilder();\n int count = 0;\n for(int i = s.length()-1; i >=0; --i){\n if(count == 4){\n break;\n }\n if(Character.isDigit(s.charAt(i))){\n last4.append(s.charAt(i));\n count++;\n }\n }\n sb.append(last4.reverse());\n }\n\n return sb.toString();\n }\n}", + "title": "831. Masking Personal Information", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a personal information string s , representing either an email address or a phone number . Return the masked personal information using the below rules . Email address: An email address is: To mask an email: Phone number: A phone number is formatted as follows: To mask a phone number: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A name consisting of uppercase and lowercase English letters, followed by", + "The '@' symbol, followed by", + "The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"LeetCode@LeetCode.com\"Output:\"l*****e@leetcode.com\"Explanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.", + "image": null + }, + { + "text": "Example 2: Input:s = \"AB@qq.com\"Output:\"a*****b@qq.com\"Explanation:s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1(234)567-890\"Output:\"***-***-7890\"Explanation:s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maskPII(self, s: str) -> str:\n res=''\n if '@' in s:\n \n l=s.split('@')\n \n a=l[0]\n b=l[1]\n \n c=b.split('.')\n \n \n res=a[0].lower()+'*'*5+a[-1].lower()+'@'+c[0].lower()+'.'+c[1].lower()\n return res\n else:\n l=0\n res=''\n flag=False\n f=False\n c=0\n for i in range(len(s)-1,-1,-1):\n if s[i]==\"(\" or s[i]==')' or s[i]=='-' or s[i]=='+' or s[i]==' ':\n continue\n \n if f==True:\n c+=1\n continue\n \n if flag==False:\n res=s[i]+res\n else:\n res='*'+res\n \n \n \n if l==3 or l==6:\n if l==3:\n flag=True\n res='-'+res\n l+=1\n \n if len(res)==12:\n f=True\n if c==1:\n res='+*-'+res\n elif c==2:\n res=\"+**-\"+res\n elif c==3:\n res=\"+***-\"+res\n \n \n return res\n \n \n \n \n \n \n", + "title": "831. Masking Personal Information", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s and sub . You are also given a 2D character array mappings where mappings[i] = [old i , new i ] indicates that you may perform the following operation any number of times: Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings . Otherwise, return false . A substring is a contiguous non-empty sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Replace a character old i of sub with new i ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]Output:trueExplanation:Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = \"l3e7\" is a substring of s, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]Output:falseExplanation:The string \"f00l\" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]Output:trueExplanation:Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = \"l33tb\" is a substring of s, so we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean matchReplacement(String s, String sub, char[][] mappings) {\n HashMap> m = new HashMap<>();\n for(char[] carr: mappings) {\n if (!m.containsKey(carr[0])){\n m.put(carr[0], new HashSet());\n }\n m.get(carr[0]).add(carr[1]);\n }\n int len_s = s.length();\n int len_sub = sub.length();\n for (int pos = 0; pos < s.length(); pos++ ){\n int i = pos;\n int j = 0;\n boolean cont = false; \n while (j <= sub.length()) {\n if ( j == sub.length()) return true;\n int lenlefts = len_s - i;\n int lenleftsub = len_sub - j;\n if (lenlefts < lenleftsub) {\n break;\n } else if ((s.charAt(i) == sub.charAt(j)) || \n\t\t\t\t (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) {\n i += 1;\n j += 1;\n } else {\n break;\n }\n }\n }\n return false;\n }\n}\n", + "title": "2301. Match Substring After Replacement", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and sub . You are also given a 2D character array mappings where mappings[i] = [old i , new i ] indicates that you may perform the following operation any number of times: Each character in sub cannot be replaced more than once. Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings . Otherwise, return false . A substring is a contiguous non-empty sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Replace a character old i of sub with new i ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]Output:trueExplanation:Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = \"l3e7\" is a substring of s, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]Output:falseExplanation:The string \"f00l\" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]Output:trueExplanation:Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = \"l33tb\" is a substring of s, so we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nimport re\n\nclass Solution:\n def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n reachable = defaultdict(set)\n for a, b in mappings:\n reachable[a].add(b)\n for c in sub:\n reachable[c].add(c)\n regex = \"\"\n for c in sub:\n if len(reachable[c]) > 1:\n regex += \"(\"\n regex += \"|\".join(reachable[c])\n regex += \")\"\n else:\n regex += c\n return re.compile(regex).search(s)\n", + "title": "2301. Match Substring After Replacement", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the i th matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time . Return true if you can make this square and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= matchsticks.length <= 15", + "1 <= matchsticks[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matchsticks = [1,1,2,2,2]Output:trueExplanation:You can form a square with length 2, one side of the square came two sticks with length 1.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg" + }, + { + "text": "Example 2: Input:matchsticks = [3,3,3,3,4]Output:falseExplanation:You cannot find a way to form a square with all the matchsticks.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 41.50 MB (Top 26.55%)\n\nclass Solution {\n public boolean makesquare(int[] M) {\n Arrays.sort(M);\n int total = 0;\n for (int i = 0; i < M.length; i++)\n total += M[i];\n side = total / 4;\n if ((float)total / 4 > side || M[M.length-1] > side)\n return false;\n return btrack(M.length-1, side, 0, M);\n }\n private int side;\n private boolean btrack(int i, int space, int done, int[] M) {\n if (done == 3)\n return true;\n for (; i >= 0; i--) {\n int num = M[i];\n boolean res;\n if (num > space)\n continue;\n M[i] = side + 1;\n if (num == space)\n res = btrack(M.length-2, side, done+1, M);\n else\n res = btrack(i-1, space-num, done, M);\n if (res)\n return true;\n M[i] = num;\n while (i > 0 && M[i-1] == num)\n i--;\n }\n return false;\n }\n}\n", + "title": "473. Matchsticks to Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array matchsticks where matchsticks[i] is the length of the i th matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time . Return true if you can make this square and false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= matchsticks.length <= 15", + "1 <= matchsticks[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matchsticks = [1,1,2,2,2]Output:trueExplanation:You can form a square with length 2, one side of the square came two sticks with length 1.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg" + }, + { + "text": "Example 2: Input:matchsticks = [3,3,3,3,4]Output:falseExplanation:You cannot find a way to form a square with all the matchsticks.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makesquare(self, matchsticks: List[int]) -> bool:\n target,m=divmod(sum(matchsticks),4)\n if m:return False\n targetLst=[0]*4\n length=len(matchsticks)\n matchsticks.sort(reverse=True)\n def bt(i):\n if i==length:\n return len(set(targetLst))==1\n for j in range(4):\n if matchsticks[i]+targetLst[j]>target:\n continue\n targetLst[j]+=matchsticks[i]\n if bt(i+1):\n return True\n targetLst[j]-=matchsticks[i]\n if not targetLst[j]:break\n return False\n return matchsticks[0]<=target and bt(0)\n", + "title": "473. Matchsticks to Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a m x n matrix mat and an integer k , return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "i - k <= r <= i + k,", + "j - k <= c <= j + k , and", + "(r, c) is a valid position in the matrix." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1Output:[[12,21,16],[27,45,33],[24,39,28]]", + "image": null + }, + { + "text": "Example 2: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2Output:[[45,45,45],[45,45,45],[45,45,45]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 88 ms (Top 26.15%) | Memory: 43.2 MB (Top 92.07%)\nclass Solution {\n public int[][] matrixBlockSum(int[][] mat, int k) {\n int m = mat.length,n = mat[0].length;\n int[][] answer = new int[m][n];\n for(int i=0;i List[List[int]]:\n ROWS, COLS = len(matrix), len(matrix[0])\n\n prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)]\n\n for r in range(1, ROWS + 1):\n for c in range(1, COLS + 1):\n prefix_sums[r][c] = prefix_sums[r - 1][c] + prefix_sums[r][c - 1] + \\\n matrix[r - 1][c - 1] - prefix_sums[r - 1][c - 1]\n\n res = [[0] * COLS for _ in range(ROWS)]\n for r in range(ROWS):\n for c in range(COLS):\n res[r][c] = prefix_sums[min(r + k + 1, ROWS)][min(c + k + 1, COLS)] - \\\n prefix_sums[max(r - k, 0)][min(c + k + 1, COLS)] - \\\n prefix_sums[min(r + k + 1, ROWS)][max(c - k, 0)] + \\\n prefix_sums[max(r - k, 0)][max(c - k, 0)]\n\n return res", + "title": "1314. Matrix Block Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given four integers row , cols , rCenter , and cCenter . There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter) . Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance . You may return the answer in any order that satisfies this condition. The distance between two cells (r 1 , c 1 ) and (r 2 , c 2 ) is |r 1 - r 2 | + |c 1 - c 2 | . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rows, cols <= 100", + "0 <= rCenter < rows", + "0 <= cCenter < cols" + ], + "examples": [ + { + "text": "Example 1: Input:rows = 1, cols = 2, rCenter = 0, cCenter = 0Output:[[0,0],[0,1]]Explanation:The distances from (0, 0) to other cells are: [0,1]", + "image": null + }, + { + "text": "Example 2: Input:rows = 2, cols = 2, rCenter = 0, cCenter = 1Output:[[0,1],[0,0],[1,1],[1,0]]Explanation:The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.", + "image": null + }, + { + "text": "Example 3: Input:rows = 2, cols = 3, rCenter = 1, cCenter = 2Output:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]Explanation:The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 88.98%) | Memory: 44.4 MB (Top 93.55%)\n//--------------------Method 1----------------------\n\nclass Solution {\n public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n int [][]res=new int[rows*cols][2];\n\n int idx=0;\n\n for(int i=0;i{\n int d1=Math.abs(a[0]-rCenter)+Math.abs(a[1]-cCenter);\n int d2=Math.abs(b[0]-rCenter)+Math.abs(b[1]-cCenter);\n\n return d1-d2;\n });\n\n return res;\n }\n}\n\n//--------------------Method 2--------------------\n\n// class Solution {\n// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n// boolean [][]vis=new boolean[rows][cols];\n// int [][]ans=new int[rows*cols][2];\n\n// Queue q=new LinkedList<>();\n// q.add(new Pair(rCenter,cCenter));\n// int idx=0;\n// vis[rCenter][cCenter]=true;\n// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};\n\n// while(!q.isEmpty()){\n// Pair curr=q.remove();\n// ans[idx][0]=curr.r;\n// ans[idx][1]=curr.c;\n// idx++;\n\n// for(int []d:dir){\n// int nr=curr.r+d[0];\n// int nc=curr.c+d[1];\n\n// if(nr>=0 && nr=0 && nc List[List[int]]:\n # create a r, c matrix given the rows & cols\n # each element represents a list [r, c] where r is the row & c the col\n # find find the distances of all cells from the center (append to res)\n # sort the result by distance function\n # Time O(M + N) Space O(M + N)\n \n \n def distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n \n matrix = [[i, j] for i in range(rows) for j in range(cols)]\n center = [rCenter, cCenter]\n matrix.sort(key=lambda c: distance(c, center))\n \n return matrix\n", + "title": "1030. Matrix Cells in Distance Order", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a square matrix mat , return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == mat.length == mat[i].length", + "1 <= n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]Output:25Explanation:Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" + }, + { + "text": "Example 2: Input:mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]Output:8", + "image": null + }, + { + "text": "Example 3: Input:mat = [[5]]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int diagonalSum(int[][] mat) {\n int sum1 = 0;\n int sum2 = 0;\n int n = mat.length;\n for(int i = 0 ; i < n ; i++)\n {\n sum1 += mat[i][i];\n sum2 += mat[i][n-i-1];\n }\n int res = sum1 + sum2;\n if(n%2 != 0)\n {\n res -= mat[n/2][n/2];\n }\n return res;\n }\n}\n", + "title": "1572. Matrix Diagonal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a square matrix mat , return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == mat.length == mat[i].length", + "1 <= n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]Output:25Explanation:Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png" + }, + { + "text": "Example 2: Input:mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]Output:8", + "image": null + }, + { + "text": "Example 3: Input:mat = [[5]]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 89.16%) | Memory: 17.60 MB (Top 5.05%)\n\nclass Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n \n n = len(mat)\n \n mid = n // 2\n \n summation = 0\n \n for i in range(n):\n \n # primary diagonal\n summation += mat[i][i]\n \n # secondary diagonal\n summation += mat[n-1-i][i]\n \n \n if n % 2 == 1:\n # remove center element (repeated) on odd side-length case\n summation -= mat[mid][mid]\n \n \n return summation\n", + "title": "1572. Matrix Diagonal Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 50", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: 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:6Explanation:The answer is not 11, because the island must be connected 4-directionally.", + "image": "https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,0,0,0,0,0,0,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 93 ms (Top 5.05%) | Memory: 72.8 MB (Top 5.08%)\nclass Solution {\n public int maxAreaOfIsland(int[][] grid) {\n\n final int rows=grid.length;\n final int cols=grid[0].length;\n final int[][] dirrections=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};\n Map> adj=new HashMap<>();\n boolean[][] visited=new boolean[rows][cols];\n Queue queue=new LinkedList<>();\n int res=0;\n\n for(int i=0;i list=new ArrayList<>();\n for(int[] dirrection:dirrections)\n {\n int newRow=dirrection[0]+i;\n int newCol=dirrection[1]+j;\n\n boolean isInBoard=newRow>=rows||newRow<0||newCol>=cols||newCol<0;\n if(!isInBoard)\n {\n list.add(new int[]{newRow,newCol,grid[newRow][newCol]});\n }\n }\n\n adj.put(getNodeStringFormat(i,j,grid[i][j]),list);\n }\n }\n\n for(int i=0;i int:\n if not grid:\n return 0\n \n maxArea = 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1: # run dfs only when we find a land\n maxArea = max(maxArea, self.dfs(grid, i, j))\n \n return maxArea\n \n \n def dfs(self, grid, i, j):\n\t\t# conditions for out of bound and when we encounter water\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:\n return 0\n \n maxArea = 1\n grid[i][j] = '#' # this will act as visited set\n maxArea += self.dfs(grid, i+1, j)\n maxArea += self.dfs(grid, i-1, j)\n maxArea += self.dfs(grid, i, j+1)\n maxArea += self.dfs(grid, i, j-1)\n \n return maxArea\n", + "title": "695. Max Area of Island", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1] . We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == arr.length", + "1 <= n <= 10", + "0 <= arr[i] < n", + "All the elements of arr are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,3,2,1,0]Output:1Explanation:Splitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,0,2,3,4]Output:4Explanation:We can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.9 MB (Top 81.61%)\nclass Solution {\n public int maxChunksToSorted(int[] arr) {\n\n int max=0, count=0;\n for(int i=0; i. 0 1 2 3 4 5 6 7\n\nInput --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70\n <------------> <--> <-------> <------->\nLeft Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75\n\nRight Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max\n\n1. At pos 2 , left_max 30 is smaller than right_min 40 at pos 3\n2. That means , all the elements in the right side of 30 are bigger than all the elements of left side of 30 , including 30\n3. Hence we can break it at pos 2 into a chunk and sort this whole sub-array( 0 - 2 )\n\n*/\n\nclass Solution {\n\n public int maxChunksToSorted(int[] arr) {\n\n // 1. Generate Right min\n\n int[] min_from_right = new int[arr.length+1] ;\n min_from_right[arr.length] = Integer.MAX_VALUE ;\n\n for(int i=arr.length-1 ; i>=0 ; i--){\n min_from_right[i] = Math.min(arr[i] , min_from_right[i+1]);\n }\n\n // 2. Generate Left Max and Count chunks\n int chunk_count = 0 ;\n int max_cur = Integer.MIN_VALUE ;\n\n for(int i=0 ; i int:\n sortedArr = sorted(arr)\n\n posMap = defaultdict(list)\n for i in range(len(sortedArr)):\n posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position\n\n idx = len(arr) - 1\n cnt = 0\n for i in range(len(arr) - 1, -1, -1):\n idx = min(idx, posMap[arr[i]][-1]) # the smallest position need to move arr[i] to correct position\n posMap[arr[i]].pop()\n if i == idx:\n cnt += 1\n idx -= 1\n return cnt", + "title": "768. Max Chunks To Make Sorted II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , return the maximum number of consecutive 1 's in the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1,1,1]Output:3Explanation:The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1,0,1]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 25.35%) | Memory: 56.8 MB (Top 44.29%)\nclass Solution {\n public int findMaxConsecutiveOnes(int[] nums) {\n int max = 0;\n int new_max = 0;\n for(int i=0;inew_max){\n new_max = max;\n }\n max = 0;\n }\n }\n if(max int:\n \n count = maxCount = 0\n \n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n else:\n maxCount = max(count, maxCount)\n count = 0\n \n return max(count, maxCount)\n", + "title": "485. Max Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2Output:6Explanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3Output:10Explanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 43.4 MB (Top 96.24%)\n\nclass Solution {\n public int longestOnes(int[] nums, int k) {\n int ans = 0;\n int j = -1;\n int count = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n count++;\n }\n while (count > k) {\n j++;\n if (nums[j] == 0) {\n count--;\n }\n }\n int len = i - j;\n if (len > ans) ans = len;\n }\n return ans;\n }\n}", + "title": "1004. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2Output:6Explanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3Output:10Explanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 398 ms (Top 99.0%) | Memory: 17.90 MB (Top 17.54%)\n\nclass Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n l=r=0 \n for r in range(len(nums)):\n if nums[r] == 0:\n k-=1\n if k<0:\n if nums[l] == 0:\n k+=1\n l+=1\n return r-l+1\n", + "title": "1004. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer num . You will apply the following steps exactly two times: Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Pick a digit x (0 <= x <= 9) .", + "Pick another digit y (0 <= y <= 9) . The digit y can be equal to x .", + "Replace all the occurrences of x in the decimal representation of num by y .", + "The new integer cannot have any leading zeros, also the new integer cannot be 0." + ], + "examples": [ + { + "text": "Example 1: Input:num = 555Output:888Explanation:The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888", + "image": null + }, + { + "text": "Example 2: Input:num = 9Output:8Explanation:The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDiff(int num) {\n int[] arr = new int[String.valueOf(num).length()];\n for (int i = arr.length - 1; i >= 0; i--){\n arr[i] = num % 10;\n num /= 10;\n }\n return max(arr.clone()) - min(arr);\n }\n\n private int max(int[] arr){ // find max\n for (int i = 0, t = -1; i < arr.length; i++){\n if (t == -1 && arr[i] != 9){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = 9;\n }\n }\n return parse(arr);\n }\n\n private int min(int[] arr){ // find min\n int re = arr[0] == 1? 0 : 1;\n int t = arr[0] == 1? -1 : arr[0];\n for (int i = 0; i < arr.length; i++){\n if (t == -1 && arr[i] != 0 && arr[i] != arr[0]){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = re;\n }\n }\n return parse(arr);\n }\n\n private int parse(int[] arr){\n int ans = 0;\n for (int i = 0; i < arr.length; i++){\n ans = 10 * ans + arr[i];\n }\n return ans;\n }\n}\n", + "title": "1432. Max Difference You Can Get From Changing an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer num . You will apply the following steps exactly two times: Let a and b be the results of applying the operations to num the first and second times, respectively. Return the max difference between a and b . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Pick a digit x (0 <= x <= 9) .", + "Pick another digit y (0 <= y <= 9) . The digit y can be equal to x .", + "Replace all the occurrences of x in the decimal representation of num by y .", + "The new integer cannot have any leading zeros, also the new integer cannot be 0." + ], + "examples": [ + { + "text": "Example 1: Input:num = 555Output:888Explanation:The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888", + "image": null + }, + { + "text": "Example 2: Input:num = 9Output:8Explanation:The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 82.14%) | Memory: 16.40 MB (Top 63.78%)\n\nclass Solution:\n def maxDiff(self, num: int) -> int:\n num = str(num)\n \n i = next((i for i in range(len(num)) if num[i] != \"9\"), -1) #first non-9 digit\n hi = int(num.replace(num[i], \"9\"))\n \n if num[0] != \"1\": lo = int(num.replace(num[0], \"1\"))\n else: \n i = next((i for i in range(len(num)) if num[i] not in \"01\"), -1)\n lo = int(num.replace(num[i], \"0\") if i > 0 else num)\n \n return hi - lo\n", + "title": "1432. Max Difference You Can Get From Changing an Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two arrays nums1 and nums2 . Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 500", + "-1000 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,1,-2,5], nums2 = [3,0,-6]Output:18Explanation:Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,-2], nums2 = [2,-6,7]Output:21Explanation:Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-1,-1], nums2 = [1,1]Output:-1Explanation:Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDotProduct(int[] nums1, int[] nums2) {\n int N = nums1.length, M = nums2.length;\n int[][] dp = new int[N][M];\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n dp[i][j] = nums1[i] * nums2[j];\n if (i > 0 && j > 0 && dp[i - 1][j - 1] > 0) {\n dp[i][j] += dp[i - 1][j - 1];\n }\n if (i > 0 && dp[i - 1][j] > dp[i][j]) {\n dp[i][j] = dp[i - 1][j];\n }\n if (j > 0 && dp[i][j - 1] > dp[i][j]) {\n dp[i][j] = dp[i][j - 1];\n }\n }\n }\n return dp[N - 1][M - 1];\n }\n}", + "title": "1458. Max Dot Product of Two Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two arrays nums1 and nums2 . Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 500", + "-1000 <= nums1[i], nums2[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [2,1,-2,5], nums2 = [3,0,-6]Output:18Explanation:Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,-2], nums2 = [2,-6,7]Output:21Explanation:Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [-1,-1], nums2 = [1,1]Output:-1Explanation:Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 435 ms (Top 93.00%) | Memory: 13.8 MB (Top 100.00%)\nclass Solution:\n def maxDotProduct(self, A, B):\n dp = [float('-inf')] * (len(B)+1)\n for i in range(len(A)):\n prev = float('-inf')\n for j in range(len(B)):\n product = A[i] * B[j]\n prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product)\n return dp[-1]", + "title": "1458. Max Dot Product of Two Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c . A city's skyline is the the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0 -height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction. Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[r].length", + "2 <= n <= 50", + "0 <= grid[r][c] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]Output:35Explanation:The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]", + "image": "https://assets.leetcode.com/uploads/2021/06/21/807-ex1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[0,0,0],[0,0,0]]Output:0Explanation:Increasing the height of any building will result in the skyline changing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] row = new int[n];\n int[] col = new int[n];\n int ans = 0;\n for(int i=0;i int:\n\t\tmxr = [max(i) for i in grid]\n\t\tmxc = [0 for _ in range(len(grid[0]))]\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[0])):\n\t\t\t\tmxc[j] = max(grid[i][j],mxc[j])\n\t\tans =0 \n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid)):\n\t\t\t\tans+=(min(mxr[i],mxc[j]) - grid[i][j]) \n\t\treturn ans", + "title": "807. Max Increase to Keep City Skyline", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5Output:2Explanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6Output:1Explanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxOperations(int[] nums, int k) {\n HashMapmap=new HashMap<>();\n int count=0;\n for(int i=0;i0){\n count++;\n map.put(k-nums[i],map.get(k-nums[i])-1);\n }else{\n //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1\n //and if some value is present then it return that value \"similar to map.get(i)\" and I added 1 on it \n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n }\n return count;\n }\n}\n", + "title": "1679. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5Output:2Explanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6Output:1Explanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n nums.sort()\n left = 0\n right = len(nums) - 1\n ans = 0\n while left < right:\n cur = nums[left] + nums[right]\n if cur == k:\n ans += 1\n left += 1\n right -= 1\n elif cur < k:\n left += 1\n else:\n right -= 1\n \n return ans\n", + "title": "1679. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of points where points[i] = [x i , y i ] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 300", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[3,3]]Output:3", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" + }, + { + "text": "Example 2: Input:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 45.59%) | Memory: 42 MB (Top 92.59%)\nclass Solution {\n public int maxPoints(int[][] points) {\n int n = points.length;\n if(n == 1) return n;\n int result = 0;\n for(int i = 0; i< n; i++){\n for(int j = i+1; j< n; j++){\n result = Math.max(result, getPoints(i, j, points));\n }\n }\n return result;\n }\n private int getPoints(int pt1, int pt2, int[][] points){\n int[] point1 = points[pt1], point2 = points[pt2];\n double slope = (point1[1] - point2[1])/(double)(point1[0] - point2[0]);\n int result = 0;\n for(int i = 0; i int:\n ans = 0\n n = len(points)\n \n for i in range(n):\n d = collections.defaultdict(int)\n for j in range(n):\n if i != j:\n slope = float(\"inf\")\n if (points[j][1] - points[i][1] != 0):\n slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1])\n d[slope] += 1\n if d:\n ans = max(ans, max(d.values())+1)\n else:\n ans = max(ans, 1)\n \n return ans", + "title": "149. Max Points on a Line", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j , such that i != j , and the sum of digits of the number nums[i] is equal to that of nums[j] . Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [18,43,36,13,7]Output:54Explanation:The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,12,19,14]Output:-1Explanation:There are no two numbers that satisfy the conditions, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 33.41%) | Memory: 82.2 MB (Top 27.68%)\nclass Solution {\n public int maximumSum(int[] nums) {\n HashMap map = new HashMap<>();\n int result = -1;\n\n for (int item : nums) {\n int key = getNumberTotal(item);\n\n if (!map.containsKey(key))\n map.put(key, item);\n else {\n result = Math.max(result, map.get(key) + item);\n map.put(key, Math.max(map.get(key), item));\n }\n }\n\n return result;\n }\n\n int getNumberTotal(int num) {\n int result = 0;\n while (num > 0) {\n result += num % 10;\n num /= 10;\n }\n\n return result;\n }\n}", + "title": "2342. Max Sum of a Pair With Equal Sum of Digits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j , such that i != j , and the sum of digits of the number nums[i] is equal to that of nums[j] . Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [18,43,36,13,7]Output:54Explanation:The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,12,19,14]Output:-1Explanation:There are no two numbers that satisfy the conditions, so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: # The plan here is to:\n # \n # • sort the elements of nums into a dict of maxheaps,\n # according to sum-of-digits.\n #\n # • For each key, determine whether there are at least two \n # elements in that key's values, and if so, compute the\n # product of the greatest two elements.\n #\n # • return the the greatest such product as the answer.\n\n # For example:\n\t\t\t\t\t\n # nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}\n\t\t\t\t\t\n # Only two keys qualify, 3 and 6, for which the greatest two elements\n # are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,\n # so the answer is 39.\n\n def maximumSum(self, nums: List[int]) -> int:\n d, mx = defaultdict(list), -1\n digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function\n \n for n in nums: # <-- construct max-heaps\n heappush(d[digits(n)],-n) # (note \"-n\") \n\n for i in d: # <-- pop the two greatest values off\n if len(d[i]) > 1: # each maxheap (when possible) and\n mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value.\n \n return mx", + "title": "2342. Max Sum of a Pair With Equal Sum of Digits", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2Output:2Explanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 388 ms (Top 6.05%) | Memory: 45.20 MB (Top 6.85%)\n\nclass Solution {\n public int maxSumSubmatrix(int[][] matrix, int tar) {\n int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar;\n for(i=0;i0) dp[i][j]+=dp[i][j-1];\n }\n }\n for(i=0;i0) dp[i][j]+=dp[i-1][j];\n }\n }\n for(i=0;i=0 && (j-1)>=0) val += dp[i-1][j-1];\n if((i-1)>=0) val=val-dp[i-1][l];\n if((j-1)>=0) val=val-dp[k][j-1];\n if(val>max && val<=target) max=val;\n }\n }\n }\n }\n return max;\n }\n}\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2Output:2Explanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maxSumSubmatrix(int[][] matrix, int k) {\n final int m = matrix.length;\n if (m < 1) {\n throw new IllegalArgumentException(\"empty matrix - no rows\");\n }\n final int n = matrix[0].length;\n if (n < 1) {\n throw new IllegalArgumentException(\"empty matrix - no columns\");\n }\n // Let's make our bottom-right sum matrix wider and higher by 1 each, so we don't go out of range.\n // All of the values r >= m and c >= n should be 0 (and will default to 0 during array construction).\n final int[][] brsum = new int[m + 1][n + 1];\n // Build up from bottom right, bottom to top and right to left.\n for (int r = (m - 1); r >= 0; --r) {\n for (int c = (n - 1); c >= 0; --c) {\n final int val = matrix[r][c];\n // did we happen to find a 1x1 rectangle at (r, c) which sums to k?\n if (val == k) {\n return val;\n }\n // Extend the sum: value + right + down - rightAndDown (because rightAndDown was added twice)\n brsum[r][c] = matrix[r][c] + brsum[r][c + 1] + brsum[r + 1][c] - brsum[r + 1][c + 1];\n }\n }\n // Now, we search.\n int maxSum = Integer.MIN_VALUE;\n for (int r0 = 0; r0 < m; ++r0) {\n for (int rf = r0; rf < m; ++rf) {\n final int rfp1 = rf + 1; // Let's avoid computing rf + 1 many times.\n for (int c0 = 0; c0 < n; ++c0) {\n for (int cf = c0; cf < n; ++cf) {\n final int cfp1 = cf + 1; // Let's avoid computing cf + 1 multiple times.\n\t\t\t\t\t\t// Compute the sum for this rectangle: complete - right - lower + lower_right.\n final int sum = brsum[r0][c0] + brsum[rfp1][cfp1] - brsum[r0][cfp1] - brsum[rfp1][c0];\n\t\t\t\t\t\t// Did we happen to find a sum adding to k? If not, did we find a larger sum less than k?\n if (sum == k) {\n return sum;\n } else if (sum < k && sum > maxSum) {\n maxSum = sum;\n }\n }\n }\n }\n }\n return maxSum;\n }\n\n}\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix matrix and an integer k , return the max sum of a rectangle in the matrix such that its sum is no larger than k . It is guaranteed that there will be a rectangle with a sum no larger than k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 100", + "-100 <= matrix[i][j] <= 100", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,0,1],[0,-2,3]], k = 2Output:2Explanation:Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[2,2,-1]], k = 3Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n import numpy as np\n \n matrix = np.array(matrix, dtype=np.int32)\n \n M,N = matrix.shape\n \n ret = float(\"-inf\")\n \n CUM = np.zeros((M,N), dtype=np.int32)\n for shift_r in range(M):\n CUM[:M-shift_r] += matrix[shift_r:]\n \n _CUM = np.zeros((M-shift_r,N), dtype=np.int32)\n for shift_c in range(N):\n _CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]\n tmp = _CUM[(_CUM<=k) & (_CUM>ret)]\n if tmp.size:\n ret = tmp.max()\n if ret == k:\n return ret\n \n return ret\n\n'''\n", + "title": "363. Max Sum of Rectangle No Larger Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [x i , y i ] such that x i < x j for all 1 <= i < j <= points.length . You are also given an integer k . Return the maximum value of the equation y i + y j + |x i - x j | where |x i - x j | <= k and 1 <= i < j <= points.length . It is guaranteed that there exists at least one pair of points that satisfy the constraint |x i - x j | <= k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= points.length <= 10^5", + "points[i].length == 2", + "-10^8 <= x i , y i <= 10^8", + "0 <= k <= 2 * 10^8", + "x i < x j for all 1 <= i < j <= points.length", + "x i form a strictly increasing sequence." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[2,0],[5,10],[6,-10]], k = 1Output:4Explanation:The first two points satisfy the condition |xi- xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.", + "image": null + }, + { + "text": "Example 2: Input:points = [[0,0],[3,0],[9,2]], k = 3Output:3Explanation:Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 80.93%) | Memory: 104.9 MB (Top 83.74%)\nclass Solution {\n public int findMaxValueOfEquation(int[][] points, int k) {\n int ans=Integer.MIN_VALUE;\n int i=0;\n int f=1;\n while(i < points.length) {\n if(f(points[i][0]+k))\n break;\n if((points[i][1]+points[j][1]+points[j][0]-points[i][0])>ans){\n ans=points[i][1]+points[j][1]+points[j][0]-points[i][0];\n f=j-1;\n }\n }\n i++;\n }\n return ans;\n }\n}", + "title": "1499. Max Value of Equation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [x i , y i ] such that x i < x j for all 1 <= i < j <= points.length . You are also given an integer k . Return the maximum value of the equation y i + y j + |x i - x j | where |x i - x j | <= k and 1 <= i < j <= points.length . It is guaranteed that there exists at least one pair of points that satisfy the constraint |x i - x j | <= k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= points.length <= 10^5", + "points[i].length == 2", + "-10^8 <= x i , y i <= 10^8", + "0 <= k <= 2 * 10^8", + "x i < x j for all 1 <= i < j <= points.length", + "x i form a strictly increasing sequence." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[2,0],[5,10],[6,-10]], k = 1Output:4Explanation:The first two points satisfy the condition |xi- xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.", + "image": null + }, + { + "text": "Example 2: Input:points = [[0,0],[3,0],[9,2]], k = 3Output:3Explanation:Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n \"\"\"\n Eqn is: yi + yj + |xi - xj|\n Since points is sorted by x values, \n therefore, xj will always be greater than xi\n therefore xi - xj will always be negative\n So the above eqn can be rewritten as,\n (yj+xj) + (yi-xi)\n Now the problem boils down to finding maximum in sliding window of k size.\n (https://leetcode.com/problems/sliding-window-maximum/discuss/1911533/Python-or-Dequeue-or-Sliding-Window-or-Simple-Solution)\n \"\"\"\n queue = deque()\n maxVal = -sys.maxsize\n for x,y in points:\n while queue and abs(queue[0][0] - x) > k:\n queue.popleft()\n \n if queue:\n maxVal = max(maxVal, y+x+queue[0][1])\n \n while queue and queue[-1][1] <= y-x:\n queue.pop()\n \n queue.append((x, y-x))\n \n return maxVal\n", + "title": "1499. Max Value of Equation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]Output:4Explanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]Output:5Explanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]Output:5Explanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 12.52%) | Memory: 44.60 MB (Top 24.53%)\n\nclass Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n int[] degree = new int[n];\n Set roadSet = new HashSet<>();\n \n for (int[] road : roads) {\n degree[road[0]]++;\n degree[road[1]]++;\n roadSet.add(road[0] + \",\" + road[1]);\n roadSet.add(road[1] + \",\" + road[0]);\n }\n\n int maxRank = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i+1; j < n; j++) {\n int rank = degree[i] + degree[j];\n if (roadSet.contains(i + \",\" + j)) {\n rank--;\n }\n maxRank = Math.max(maxRank, rank);\n }\n }\n\n return maxRank;\n }\n}\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]Output:4Explanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]Output:5Explanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]Output:5Explanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n \n //number of road connected to city\n int[] numRoadsConnectedCity = new int[100 + 1];\n \n //road exist between two two cities\n boolean[][] raadExist = new boolean[n][n];\n \n for(int[] cities : roads){\n \n //increment the count of numbers of connected city\n numRoadsConnectedCity[cities[0]]++;\n numRoadsConnectedCity[cities[1]]++;\n \n //mark road exist, between two cities\n raadExist[cities[0]][cities[1]] = true;\n raadExist[cities[1]][cities[0]] = true;\n }\n \n \n \n int maxRank = 0;\n for(int city1 = 0; city1 < n - 1; city1++){\n for(int city2 = city1 + 1; city2 < n; city2++){\n \n //count total number of road connected to both city\n int rank = numRoadsConnectedCity[city1] + numRoadsConnectedCity[city2];\n \n //just decrement the rank, if both city connected\n if(raadExist[city1][city2]) rank--;\n \n maxRank = Math.max(maxRank, rank);\n }\n }\n \n \n return maxRank;\n }\n}\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [a i , b i ] indicates that there is a bidirectional road between cities a i and b i . The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once . The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer n and the array roads , return the maximal network rank of the entire infrastructure . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/09/21/ex1.png", + "https://assets.leetcode.com/uploads/2020/09/21/ex2.png" + ], + "constraints": [ + "2 <= n <= 100", + "0 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 2", + "0 <= a i , b i <= n-1", + "a i != b i", + "Each pair of cities has at most one road connecting them." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]Output:4Explanation:The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]Output:5Explanation:There are 5 roads that are connected to cities 1 or 2.", + "image": null + }, + { + "text": "Example 3: Input:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]Output:5Explanation:The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximalNetworkRank(self, n: int, roads) -> int:\n max_rank = 0\n connections = {i: set() for i in range(n)}\n for i, j in roads:\n connections[i].add(j)\n connections[j].add(i)\n for i in range(n - 1):\n for j in range(i + 1, n):\n max_rank = max(max_rank, len(connections[i]) +\n len(connections[j]) - (j in connections[i]))\n return max_rank\n", + "title": "1615. Maximal Network Rank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a rows x cols binary matrix filled with 0 's and 1 's, find the largest rectangle containing only 1 's and return its area . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "rows == matrix.length", + "cols == matrix[i].length", + "1 <= row, cols <= 200", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]Output:6Explanation:The maximal rectangle is shown in the above picture.", + "image": "https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\"]]Output:0", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[\"1\"]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 29.92%) | Memory: 46.6 MB (Top 92.25%)\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n ArrayList list = new ArrayList<>();\n int n = matrix[0].length;\n for(int i=0; i heights) {\n Stack stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.size();\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n\n for(int i=0; i= heights.get(i))\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n\n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights.get(stack2.peek()) >= heights.get(i))\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n\n for(int i=0; i int:\n maxA = 0 #local max variable to return max area of a 1D array\n stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing\n arr.append(-1) # value for stack index -1 and one extra iteration to empty the stack\n for i in range(len(arr)): # traversing for stack from left to right\n arr[i] = int(arr[i]) # we are getting str value from matrix\n while stack and arr[stack[-1]] >= int(arr[i]): #stack is non empty and stack top is greater or equal to current element\n index = stack.pop() #pop greater element from stack and finds its area\n width = i - stack[-1] - 1 if stack else i # for empty stack width is len of 1D arr, and after poping if we have element in stack then it becomes left boundary and current index as right boundary\n maxA = max(maxA, width * arr[index]) # geting max area (L * B)\n stack.append(int(i)) # inserting each element in stack\n return maxA # return the max area\n \"\"\"Below is the code for adding each row one by one and passing it to above function to get the max area for each row\"\"\"\n # r1 - 1 0 1 0 0\n # r2 - 1 0 1 1 1\n # r = 2 0 2 1 1 This is for else condition\n\n # r1 - 1 1 1 0 1\n # r2 - 1 0 1 1 0\n # r = 2 0 2 1 0 This is for if condition\n\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n result = [0] * len(matrix[0])\n maxReact = 0\n maxReact = self.maxArea(result)\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = int(matrix[i][j])\n if matrix[i][j] == 0:\n result[j] = 0\n else:\n result[j] = result[j] + matrix[i][j]\n maxReact = max(maxReact,self.maxArea(result)) #after getting max area for 1D arr we are getting max value from those 1D arr for the 2D arr\n return maxReact\n", + "title": "85. Maximal Rectangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]Output:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 98.27%) | Memory: 53.6 MB (Top 98.31%)\nclass Solution {\n public int maximalSquare(char[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] dp = new int[m][n];\n\n int max = 0;\n\n for (int i = 0; i < m; i++) {\n dp[i][0] = matrix[i][0] - 48;\n if (matrix[i][0] == '1') max = 1;\n }\n for (int i = 0; i < n; i++) {\n dp[0][i] = matrix[0][i] - 48;\n if (matrix[0][i] == '1') max = 1;\n }\n\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][j] == '1') {\n dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;\n if (dp[i][j] > max) {\n max = dp[i][j];\n }\n }\n }\n }\n\n return max * max;\n }\n}", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]Output:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 499 ms (Top 97.16%) | Memory: 19.30 MB (Top 88.93%)\n\nclass Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n m, n = len(matrix), len(matrix[0])\n result = 0\n dp = [[0]*n for _ in range(m)] # dp[x][y] is the length of the maximal square at (x, y)\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == '1': # ensure this condition first\n # perform computation, mind border restrictions\n dp[i][j] = min(dp[i-1][j] if i > 0 else 0,\n dp[i][j-1] if j > 0 else 0,\n dp[i-1][j-1] if i > 0 and j > 0 else 0) + 1\n if dp[i][j] > result:\n result = dp[i][j]\n return result*result\n", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the i th seat, and seats[i] = 0 represents that the i th seat is empty (0-indexed) . There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return that maximum distance to the closest person . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= seats.length <= 2 * 10^4", + "seats[i] is 0 or 1 .", + "At least one seat is empty .", + "At least one seat is occupied ." + ], + "examples": [ + { + "text": "Example 1: Input:seats = [1,0,0,0,1,0,1]Output:2Explanation:If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/distance.jpg" + }, + { + "text": "Example 2: Input:seats = [1,0,0,0]Output:3Explanation:If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.", + "image": null + }, + { + "text": "Example 3: Input:seats = [0,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 6.92%) | Memory: 49.9 MB (Top 21.03%)\n\nclass Solution {\n public int maxDistToClosest(int[] seats) {\n int size = seats.length;\n int max = 0;\n int start = -1;\n int end = -1;\n\n for(int i = 0; i int:\n # strategy is greedy solution:\n # calculate local maximum for each interval: (b-a)//2\n # then take max of local maximums\n # the solution is O(n)\n # I find this solution clear, but uses 5 passes\n \n # get all the occupied seat nums\n seat_nums = [ix for ix, val in enumerate(seats) if val == 1]\n \n # check the ends\n left_max, right_max = min(seat_nums), len(seats)-max(seat_nums)-1\n \n # calculate max distance for each gap\n dists = [(y-x)//2 for x, y in zip(seat_nums, seat_nums[1:])]\n \n # take max of sitting on either end + each gap\n return max([left_max, right_max, *dists])\n", + "title": "849. Maximize Distance to Closest Person", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given four integers, m , n , introvertsCount , and extrovertsCount . You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).", + "Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert)." + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2Output:240Explanation:Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/grid_happiness.png" + }, + { + "text": "Example 2: Input:m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1Output:260Explanation:Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.", + "image": null + }, + { + "text": "Example 3: Input:m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0Output:240", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) {\n // introvert = -1, extrovert = 1\n return dfs(m, n, 0, introvertsCount, extrovertsCount, 0, 0, new Integer[m+1][introvertsCount+1][extrovertsCount+1][(1 << (n+1))][(1 << (n+1))]);\n }\n public int dfs(int m, int n, int row, int in_count, int ex_count, int prev_in_pos, int prev_ex_pos, Integer[][][][][] dp) {\n if(dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos] != null)\n return dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos];\n if((in_count == 0 && ex_count == 0) || (row == m)) \n return 0;\n List possible_permutations = new ArrayList(); // get all possible ways to fill a row**** with given number of introverts & extroverts\n int[] aux = new int[n];\n getPermutations(in_count, ex_count, aux, 0, possible_permutations, n);\n \n int ans = 0;\n for(int[] possible : possible_permutations) {\n int curr_in_count = in_count, curr_ex_count = ex_count;\n int curr_in_pos = 0, curr_ex_pos = 0;\n for(int i = 0; i < n; i++) {\n if(possible[i] == 0)\n continue;\n if(possible[i] == -1) {\n curr_in_count--;\n curr_in_pos |= (1 << i);\n }\n else {\n curr_ex_count--;\n curr_ex_pos |= (1 << i);\n }\n }\n int curr_row_val = calculate(possible, prev_in_pos, prev_ex_pos, n); \n int rest_rows_val = dfs(m, n, row+1, curr_in_count, curr_ex_count, curr_in_pos, curr_ex_pos, dp);\n ans = Math.max(ans, curr_row_val + rest_rows_val);\n }\n return dp[row][in_count][ex_count][prev_in_pos][prev_ex_pos] = ans;\n }\n // for each row, find happiness (keeping in account : left, right and upper neighors, for people in this row) and\n // (keeping in account : lower neighbors for people in previous row)\n public int calculate(int[] currRow, int prev_in_pos, int prev_ex_pos, int columns) {\n int res = 0;\n // vertical neighbors\n for(int i = 0; i < columns; i++) {\n if(currRow[i] == 0) continue;\n if(currRow[i] == 1) {\n res += 40;\n if( (prev_in_pos & (1 << i)) != 0) res += (20 - 30); // -30 : because previous upper neighbor is introvert\n else if( (prev_ex_pos & (1 << i)) != 0 ) res += (20 + 20);\n }\n else {\n res += 120;\n if( (prev_in_pos & (1 << i)) != 0) res += (-30 - 30);\n else if( (prev_ex_pos & (1 << i)) != 0 ) res += (-30 + 20);\n }\n }\n // horizontal neighbors\n for(int i = 0; i < columns; i++) {\n if(currRow[i] == 0) continue;\n if(currRow[i] == -1) {\n if(i-1 >= 0 && currRow[i-1] != 0) res += (-30);\n if(i+1 < columns && currRow[i+1] != 0) res += (-30);\n }\n else {\n if(i-1 >= 0 && currRow[i-1] != 0) res += (20);\n if(i+1 < columns && currRow[i+1] != 0) res += (20);\n }\n }\n return res;\n }\n public void getPermutations(int in_count, int ex_count, int[] curr, int index, List possible_permutations, int len) {\n if((in_count == 0 && ex_count == 0) || index == len) {\n int[] arr = new int[len];\n for(int i = 0; i < len; i++)\n arr[i] = curr[i];\n possible_permutations.add(arr);\n return;\n }\n if(in_count > 0) {\n curr[index] = -1;\n getPermutations(in_count-1, ex_count, curr, index+1, possible_permutations, len);\n curr[index] = 0;\n }\n if(ex_count > 0) {\n curr[index] = 1;\n getPermutations(in_count, ex_count-1, curr, index+1, possible_permutations, len);\n curr[index] = 0;\n }\n getPermutations(in_count, ex_count, curr, index+1, possible_permutations, len);\n }\n}\n", + "title": "1659. Maximize Grid Happiness", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given four integers, m , n , introvertsCount , and extrovertsCount . You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid. The happiness of each person is calculated as follows: Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell. The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).", + "Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert)." + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2Output:240Explanation:Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/grid_happiness.png" + }, + { + "text": "Example 2: Input:m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1Output:260Explanation:Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.", + "image": null + }, + { + "text": "Example 3: Input:m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0Output:240", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n \n @cache\n def fn(prev, i, j, intro, extro): \n \"\"\"Return max grid happiness at (i, j).\"\"\"\n if i == m: return 0 # no more position\n if j == n: return fn(prev, i+1, 0, intro, extro)\n if intro == extro == 0: return 0 \n \n prev0 = prev[:j] + (0,) + prev[j+1:]\n ans = fn(prev0, i, j+1, intro, extro)\n if intro: \n val = 120 \n if i and prev[j]: # neighbor from above \n val -= 30 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: # neighbor from left \n val -= 30 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (1,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro-1, extro))\n if extro: \n val = 40 \n if i and prev[j]: \n val += 20 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: \n val += 20 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (2,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro, extro-1))\n return ans \n \n return fn((0,)*n, 0, 0, introvertsCount, extrovertsCount)", + "title": "1659. Maximize Grid Happiness", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer primeFactors . You are asked to construct a positive integer n that satisfies the following conditions: Return the number of nice divisors of n . Since that number can be too large, return it modulo 10^9 + 7 . Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of prime factors of n (not necessarily distinct) is at most primeFactors .", + "The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n . For example, if n = 12 , then its prime factors are [2,2,3] , then 6 and 12 are nice divisors, while 3 and 4 are not." + ], + "examples": [ + { + "text": "Example 1: Input:primeFactors = 5Output:6Explanation:200 is a valid value of n.\nIt has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\nThere is not other value of n that has at most 5 prime factors and more nice divisors.", + "image": null + }, + { + "text": "Example 2: Input:primeFactors = 8Output:18", + "image": null + } + ], + "follow_up": null, + "solution": "MOD = 10**9 + 7\nclass Solution:\n def maxNiceDivisors(self, n: int) -> int:\n if n <= 2: return n\n i, c = divmod(n, 3)\n if not c: return pow(3, i, MOD)\n return (self.maxNiceDivisors(n-2)*2) % MOD\n", + "title": "1808. Maximize Number of Nice Divisors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2 , both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once . Note that the character can be added even at the beginning or at the end of text . Return the maximum number of times pattern can occur as a subsequence of the modified text . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^5", + "pattern.length == 2", + "text and pattern consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abdcdbc\", pattern = \"ac\"Output:4Explanation:If we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aabb\", pattern = \"ab\"Output:6Explanation:Some of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 83 ms (Top 15.87%) | Memory: 54.4 MB (Top 56.08%)\nclass Solution {\n public long maximumSubsequenceCount(String text, String pattern) {\n //when pattern[0] == pattern[1]\n if (pattern.charAt(0) == pattern.charAt(1)) {\n long freq = 1;\n //O(N)\n for (int i = 0; i < text.length(); i++) {\n if (text.charAt(i) == pattern.charAt(0)) {\n freq++;\n }\n }\n //number of subsequences : choose any two characters from freq nC2\n return (freq * (freq - 1)) / 2;\n }\n\n //choice 1\n String text1 = pattern.charAt(0) + text;\n\n int freq = 0;\n long count1 = 0;\n //O(N)\n for (int i = 0; i < text1.length(); i++) {\n if (text1.charAt(i) == pattern.charAt(0)) {\n freq++;\n } else if (text1.charAt(i) == pattern.charAt(1)) {\n count1 += freq;\n }\n }\n\n //choice 2\n String text2 = text + pattern.charAt(1);\n freq = 0;\n long count2 = 0;\n //O(N)\n for (int i = text2.length() - 1; i>= 0; i--) {\n if (text2.charAt(i) == pattern.charAt(1)) {\n freq++;\n } else if (text2.charAt(i) == pattern.charAt(0)) {\n count2 += freq;\n }\n }\n\n return Math.max(count1, count2);\n }\n}", + "title": "2207. Maximize Number of Subsequences in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2 , both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once . Note that the character can be added even at the beginning or at the end of text . Return the maximum number of times pattern can occur as a subsequence of the modified text . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^5", + "pattern.length == 2", + "text and pattern consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"abdcdbc\", pattern = \"ac\"Output:4Explanation:If we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aabb\", pattern = \"ab\"Output:6Explanation:Some of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n total = count_a = count_b = 0\n for c in text:\n if c == pattern[1]:\n total += count_a\n count_b += 1\n if c == pattern[0]:\n count_a += 1\n \n return total + max(count_a, count_b)\n", + "title": "2207. Maximize Number of Subsequences in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings, word1 and word2 . You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0 . A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose some non-empty subsequence subsequence1 from word1 .", + "Choose some non-empty subsequence subsequence2 from word2 .", + "Concatenate the subsequences: subsequence1 + subsequence2 , to make the string." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cacb\", word2 = \"cbba\"Output:5Explanation:Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"ab\"Output:3Explanation:Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"aa\", word2 = \"bb\"Output:0Explanation:You cannot construct a palindrome from the described method, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 545 ms (Top 8.4%) | Memory: 230.95 MB (Top 8.4%)\n\nclass Solution {\n public int longestPalindrome(String word1, String word2) {\n String lWord = word1 + word2;\n return palindrome(lWord, 0, lWord.length()-1, word1.length(), false, \n new int[lWord.length()][lWord.length()][2]);\n }\n \n private int palindrome(String word, int start, int end, int boundary, boolean isFound, int[][][] dp) {\n if ((!isFound && (start >= boundary || end < boundary)) || (start > end))\n return 0;\n \n if (dp[start][end][isFound?0:1] != 0)\n return dp[start][end][isFound?0:1];\n \n return dp[start][end][isFound?0:1] = word.charAt(start) == word.charAt(end) ? \n ((start == end ? 1: 2) + palindrome(word, start+1, end-1, boundary, true, dp)) : \n Math.max(palindrome(word, start+1, end, boundary, isFound, dp), \n palindrome(word, start, end-1, boundary, isFound, dp));\n }\n}\n", + "title": "1771. Maximize Palindrome Length From Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings, word1 and word2 . You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0 . A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose some non-empty subsequence subsequence1 from word1 .", + "Choose some non-empty subsequence subsequence2 from word2 .", + "Concatenate the subsequences: subsequence1 + subsequence2 , to make the string." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"cacb\", word2 = \"cbba\"Output:5Explanation:Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"ab\"Output:3Explanation:Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"aa\", word2 = \"bb\"Output:0Explanation:You cannot construct a palindrome from the described method, so return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 932 ms (Top 96.15%) | Memory: 70.20 MB (Top 90.38%)\n\nclass Solution:\n\tdef longestPalindrome(self, word1: str, word2: str) -> int:\n\t\tres=0\n\t\tnew_word=word1+word2\n\t\tn,mid=len(word1)+len(word2),len(word1)\n\t\tdp=[[0]*n for _ in range(n)]\n\t\tfor i in range(n):\n\t\t\tdp[i][i]=1\n\t\tfor l in range(n-2,-1,-1):\n\t\t\tfor r in range(l+1,n,1):\n\t\t\t\tif new_word[l]==new_word[r]:\n\t\t\t\t\tdp[l][r]=(dp[l+1][r-1] if r-1>=l+1 else 0)+2\n\t\t\t\t\tif l=mid:\n\t\t\t\t\t\tres=max(res,dp[l][r])\n\t\t\t\telse:\n\t\t\t\t\tdp[l][r]=max(dp[l+1][r],dp[l][r-1])\n\t\treturn res", + "title": "1771. Maximize Palindrome Length From Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given nums , an array of positive integers of size 2 * n . You must perform n operations on this array. In the i th operation (1-indexed) , you will: Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two elements, x and y .", + "Receive a score of i * gcd(x, y) .", + "Remove x and y from nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2]Output:1Explanation:The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,6,8]Output:11Explanation:The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6]Output:14Explanation:The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxScore(int[] nums) {\n int n = nums.length;\n Map gcdVal = new HashMap<>();\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n gcdVal.put((1 << i) + (1 << j), gcd(nums[i], nums[j]));\n }\n }\n \n int[] dp = new int[1 << n];\n \n for (int i = 0; i < (1 << n); ++i) {\n int bits = Integer.bitCount(i); // how many numbers are used\n if (bits % 2 != 0) // odd numbers, skip it\n continue;\n for (int k : gcdVal.keySet()) {\n if ((k & i) != 0) // overlapping used numbers\n continue;\n dp[i ^ k] = Math.max(dp[i ^ k], dp[i] + gcdVal.get(k) * (bits / 2 + 1));\n }\n }\n \n return dp[(1 << n) - 1];\n }\n \n public int gcd(int a, int b) {\n if (b == 0) \n return a; \n return gcd(b, a % b); \n }\n}\n\n// Time: O(2^n * n^2)\n// Space: O(2 ^ n)\n", + "title": "1799. Maximize Score After N Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given nums , an array of positive integers of size 2 * n . You must perform n operations on this array. In the i th operation (1-indexed) , you will: Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two elements, x and y .", + "Receive a score of i * gcd(x, y) .", + "Remove x and y from nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2]Output:1Explanation:The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,6,8]Output:11Explanation:The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6]Output:14Explanation:The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6454 ms (Top 9.35%) | Memory: 24.7 MB (Top 37.40%)\nfrom functools import lru_cache\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n def gcd(a, b):\n while a:\n a, b = b%a, a\n return b\n halfplus = len(nums)//2 + 1\n @lru_cache(None)\n def dfs(mask, k):\n if k == halfplus:\n return 0\n res = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if not(mask & (1< minHeap = new PriorityQueue<>();\n for(int val : nums) minHeap.add(val);\n\n while(k > 0){\n\n int curr = minHeap.poll();\n minHeap.add(-curr);\n k--;\n }\n\n int sum = 0;\n while(!minHeap.isEmpty()){\n sum += minHeap.poll();\n }\n return sum;\n }\n}", + "title": "1005. Maximize Sum Of Array After K Negations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , modify the array in the following way: You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "choose an index i and replace nums[i] with -nums[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3], k = 1Output:5Explanation:Choose index 1 and nums becomes [4,-2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,-1,0,2], k = 3Output:6Explanation:Choose indices (1, 2, 2) and nums becomes [3,1,0,2].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-3,-1,5,-4], k = 2Output:13Explanation:Choose indices (1, 4) and nums becomes [2,3,-1,5,4].", + "image": null + } + ], + "follow_up": null, + "solution": "from heapq import heapify, heapreplace\n\nclass Solution:\n def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:\n heapify(nums)\n while k and nums[0] < 0:\n heapreplace(nums, -nums[0])\n k -= 1\n if k % 2:\n heapreplace(nums, -nums[0])\n return sum(nums)", + "title": "1005. Maximize Sum Of Array After K Negations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey , where answerKey[i] is the original answer to the i th question. In addition, you are given an integer k , the maximum number of times you may perform the following operation: Return the maximum number of consecutive 'T' s or 'F' s in the answer key after performing the operation at most k times . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F' )." + ], + "examples": [ + { + "text": "Example 1: Input:answerKey = \"TTFF\", k = 2Output:4Explanation:We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.", + "image": null + }, + { + "text": "Example 2: Input:answerKey = \"TFFT\", k = 1Output:3Explanation:We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.", + "image": null + }, + { + "text": "Example 3: Input:answerKey = \"TTFTTFTT\", k = 1Output:5Explanation:We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 6.64%) | Memory: 48.1 MB (Top 51.04%)\n\nclass Solution {\n\n // Binary Search + Sliding Window fixed\n\n public int maxConsecutiveAnswers(String answerKey, int k) {\n\n int start = 1 ;\n int end = answerKey.length();\n int max_length = 0 ;\n\n while(start <= end) {\n int mid = start+(end-start)/2 ;\n if(isMax(answerKey , k , mid)) {\n max_length = mid ;\n start = mid+1 ;\n }else {\n end = mid-1 ;\n }\n }\n\n return max_length ;\n }\n\n public boolean isMax(String answerKey , int k , int max_val) {\n\n int T_count = 0 ;\n int F_count = 0 ;\n\n int i = 0 ;\n int j = 0 ;\n\n while(j < answerKey.length()) {\n\n if(answerKey.charAt(j) == 'T') {\n T_count++ ;\n }else {\n F_count++ ;\n }\n\n if(j-i+1 == max_val) {\n\n if(Math.max(T_count, F_count)+k >= max_val) {\n return true ;\n }\n\n if(answerKey.charAt(i) == 'T') {\n T_count-- ;\n }else {\n F_count-- ;\n }\n\n i++ ;\n }\n\n j++ ;\n }\n\n return false ;\n }\n}\n", + "title": "2024. Maximize the Confusion of an Exam", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey , where answerKey[i] is the original answer to the i th question. In addition, you are given an integer k , the maximum number of times you may perform the following operation: Return the maximum number of consecutive 'T' s or 'F' s in the answer key after performing the operation at most k times . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F' )." + ], + "examples": [ + { + "text": "Example 1: Input:answerKey = \"TTFF\", k = 2Output:4Explanation:We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.", + "image": null + }, + { + "text": "Example 2: Input:answerKey = \"TFFT\", k = 1Output:3Explanation:We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.", + "image": null + }, + { + "text": "Example 3: Input:answerKey = \"TTFTTFTT\", k = 1Output:5Explanation:We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 482 ms (Top 77.29%) | Memory: 14.4 MB (Top 36.09%)\nclass Solution:\n def maxConsecutiveAnswers(self, string: str, k: int) -> int:\n result = 0\n j = 0\n count1 = k\n for i in range(len(string)):\n if count1 == 0 and string[i] == \"F\":\n while string[j] != \"F\":\n j+=1\n count1+=1\n j+=1\n\n if string[i] == \"F\":\n if count1 > 0:\n count1-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n j = 0\n count2 = k\n for i in range(len(string)):\n if count2 == 0 and string[i] == \"T\":\n while string[j] != \"T\":\n j+=1\n count2+=1\n j+=1\n\n if string[i] == \"T\":\n if count2 > 0:\n count2-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n return result", + "title": "2024. Maximize the Confusion of an Exam", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed integer array nums representing the contents of a pile , where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: You are also given an integer k , which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves . In case it is not possible to obtain a non-empty pile after k moves, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the pile is not empty, remove the topmost element of the pile.", + "If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,2,4,0,6], k = 4Output:5Explanation:One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2], k = 1Output:-1Explanation:In the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 85.6 MB (Top 12.35%)\nclass Solution {\n public int maximumTop(int[] nums, int k) {\n int n = nums.length, max = -1;\n\n if(n==1){\n if(k%2==1) return -1;\n else return nums[0];\n }\n\n if(kn) k = n+1;\n\n for (int i = 0; i < k-1; i++) {\n max = Math.max(max, nums[i]);\n }\n return max;\n }\n}", + "title": "2202. Maximize the Topmost Element After K Moves", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums representing the contents of a pile , where nums[0] is the topmost element of the pile. In one move, you can perform either of the following: You are also given an integer k , which denotes the total number of moves to be made. Return the maximum value of the topmost element of the pile possible after exactly k moves . In case it is not possible to obtain a non-empty pile after k moves, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the pile is not empty, remove the topmost element of the pile.", + "If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,2,4,0,6], k = 4Output:5Explanation:One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2], k = 1Output:-1Explanation:In the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 498 ms (Top 63.4%) | Memory: 30.38 MB (Top 40.6%)\n\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n if k%2 != 0:\n return -1\n return nums[0]\n \n if k == 0:\n return nums[0]\n if k == len(nums):\n return max(nums[:-1])\n if k > len(nums):\n return max(nums)\n if k == 1:\n return nums[1]\n m = max(nums[:k-1])\n m = max(m, nums[k])\n return m", + "title": "2202. Maximize the Topmost Element After K Moves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer num consisting only of digits 6 and 9 . Return the maximum number you can get by changing at most one digit ( 6 becomes 9 , and 9 becomes 6 ) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num <= 10^4", + "num consists of only 6 and 9 digits." + ], + "examples": [ + { + "text": "Example 1: Input:num = 9669Output:9969Explanation:Changing the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.", + "image": null + }, + { + "text": "Example 2: Input:num = 9996Output:9999Explanation:Changing the last digit 6 to 9 results in the maximum number.", + "image": null + }, + { + "text": "Example 3: Input:num = 9999Output:9999Explanation:It is better not to apply any change.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximum69Number (int num) {\n int i;\n String s=String.valueOf(num);\n int l=s.length();\n int max=num;\n \n for(i=0;i 0)\n currentMinSum = 0;\n }\n return Math.max(maxSum, -minSum);\n }\n}\n", + "title": "1749. Maximum Absolute Sum of Any Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . The absolute sum of a subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is abs(nums l + nums l+1 + ... + nums r-1 + nums r ) . Return the maximum absolute sum of any (possibly empty) subarray of nums . Note that abs(x) is defined as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If x is a negative integer, then abs(x) = -x .", + "If x is a non-negative integer, then abs(x) = x ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-3,2,3,-4]Output:5Explanation:The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,-5,1,-4,3,-2]Output:8Explanation:The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef maxAbsoluteSum(self, A):\n\n\t\tma,mi,res = 0,0,0\n\t\tfor a in A:\n\t\t\tma = max(0,ma+a)\n\t\t\tmi = min(0,mi+a)\n\t\t\tres = max(res,ma,-mi)\n\t\treturn res\n", + "title": "1749. Maximum Absolute Sum of Any Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]Output:7Explanation:It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,7,8]Output:8Explanation:It is optimal to choose the subsequence [8] with alternating sum 8.", + "image": null + }, + { + "text": "Example 3: Input:nums = [6,2,1,2,4,5]Output:10Explanation:It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxAlternatingSum(int[] nums) {\n int n = nums.length;\n long dp[][] = new long[n][2];\n dp[0][0] = nums[0];\n for(int i=1;i int:\n ans = 0\n direction = 'down'\n n = len(nums)\n for i in range(n-1):\n if direction == 'down' and nums[i] >= nums[i+1]:\n ans += nums[i]\n direction = 'up'\n elif direction == 'up' and nums[i] <= nums[i+1]:\n ans -= nums[i]\n direction = 'down'\n if direction == 'up':\n return ans\n return ans + nums[-1]", + "title": "1911. Maximum Alternating Subsequence Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n . There are numSlots slots numbered from 1 to numSlots . You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1 ) + (3 AND 1 ) + (4 AND 2 ) + (6 AND 2 ) = 1 + 1 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6], numSlots = 3Output:9Explanation:One possible placement is [1, 4] into slot1, [2, 6] into slot2, and [3, 5] into slot3. \nThis gives the maximum AND sum of (1 AND1) + (4 AND1) + (2 AND2) + (6 AND2) + (3 AND3) + (5 AND3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,10,4,7,1], numSlots = 9Output:24Explanation:One possible placement is [1, 1] into slot1, [3] into slot3, [4] into slot4, [7] into slot7, and [10] into slot9.\nThis gives the maximum AND sum of (1 AND1) + (1 AND1) + (3 AND3) + (4 AND4) + (7 AND7) + (10 AND9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 93.9%) | Memory: 44.11 MB (Top 57.7%)\n\nclass Solution {\n int[] memo;\n int[] nums;\n int numSlots;\n public int maximumANDSum(int[] nums, int numSlots) {\n this.memo=new int[1<<(2*numSlots)];\n this.nums=nums;\n this.numSlots=numSlots;\n return helper(0,0);\n }\n int helper(int numIndex, int set) {\n // Base case when we used all the numbers \n if(numIndex==nums.length) return 0;\n // Set informs BOTH the slots used and the numIndex. If the later\n // statement surprises you, think it like this: We must place all\n // the numbers in a slot, so how many slots are used in numIndex=10?\n // yes! 9 slots (because we will use the 10th now!), so the set will\n // have 10 ones. No other numIndex will have 9 ones. So having memo\n // with 2 dimentions would be redundant, as you would naver have a\n // combination of numIndex 3 with sets 1, 2, 4, 6.. etc, only\n // numIndex 2 will have those sets.\n if(memo[set]>0) return memo[set]-1; // I use memo-1 so I dont have to fill it with -1\n int max=0;\n for(int i=0;i-1?firstHalfSlot:secondHalfSlot;\n if(slotChosen<0) continue; // both slots are used\n int andSum=0;\n if(slotChosen>=numSlots) andSum=((slotChosen-numSlots)+1)&nums[numIndex];\n else andSum=(slotChosen+1)&nums[numIndex];\n // By adjusting the set in the recursion signature\n // I am backtracking in an elegant way.\n max=Math.max(max, andSum+ helper(numIndex+1,set|1<= n . There are numSlots slots numbered from 1 to numSlots . You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1 ) + (3 AND 1 ) + (4 AND 2 ) + (6 AND 2 ) = 1 + 1 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6], numSlots = 3Output:9Explanation:One possible placement is [1, 4] into slot1, [2, 6] into slot2, and [3, 5] into slot3. \nThis gives the maximum AND sum of (1 AND1) + (4 AND1) + (2 AND2) + (6 AND2) + (3 AND3) + (5 AND3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,10,4,7,1], numSlots = 9Output:24Explanation:One possible placement is [1, 1] into slot1, [3] into slot3, [4] into slot4, [7] into slot7, and [10] into slot9.\nThis gives the maximum AND sum of (1 AND1) + (1 AND1) + (3 AND3) + (4 AND4) + (7 AND7) + (10 AND9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1881 ms (Top 9.44%) | Memory: 23.9 MB (Top 80.86%)\nfrom functools import lru_cache, cache\n\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n @cache\n def dp(i=0, m1=0, m2=0): # mask1, mask2\n if i == len(nums):\n return 0\n ans = 0\n for s in range(numSlots):\n if m2 & (1 << s) == 0: # i.e. 0b0?, implying the slot is not full\n if m1 & (1 << s) == 0: # 0b00 + 1 => 0b01\n nm1 = m1 | (1 << s); nm2 = m2\n else: # 0b01 + 1 => 0b10\n nm1 = m1 & ~(1 << s); nm2 = m2 | (1 << s)\n ans = max(ans, dp(i + 1, nm1, nm2) + ((s + 1) & nums[i])) # s + 1 is the actual slot no.\n return ans\n return dp()", + "title": "2172. Maximum AND Sum of Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts . Since the answer can be a large number, return this modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "horizontalCuts[i] is the distance from the top of the rectangular cake to the i th horizontal cut and similarly, and", + "verticalCuts[j] is the distance from the left of the rectangular cake to the j th vertical cut." + ], + "examples": [ + { + "text": "Example 1: Input:h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]Output:4Explanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png" + }, + { + "text": "Example 2: Input:h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]Output:6Explanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png" + }, + { + "text": "Example 3: Input:h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.BigInteger;\nclass Solution {\n public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {\n Arrays.sort(horizontalCuts);\n Arrays.sort(verticalCuts);\n int i;\n int hMax=horizontalCuts[0];\n for(i=1;i hMax)\n hMax= h-horizontalCuts[horizontalCuts.length-1];\n int vMax=verticalCuts[0];\n for(i=1;i vMax)\n vMax= w-verticalCuts[verticalCuts.length-1];\n return (int)((long)hMax*vMax%1000000007);\n }\n}\n", + "title": "1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where: Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts . Since the answer can be a large number, return this modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "horizontalCuts[i] is the distance from the top of the rectangular cake to the i th horizontal cut and similarly, and", + "verticalCuts[j] is the distance from the left of the rectangular cake to the j th vertical cut." + ], + "examples": [ + { + "text": "Example 1: Input:h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]Output:4Explanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png" + }, + { + "text": "Example 2: Input:h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]Output:6Explanation:The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.", + "image": "https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png" + }, + { + "text": "Example 3: Input:h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n horizontalCuts.sort()\n verticalCuts.sort()\n \n mxHr = 0\n prev = 0\n for i in horizontalCuts:\n mxHr = max(mxHr, i-prev)\n prev = i\n mxHr = max(mxHr, h-horizontalCuts[-1])\n \n mxVr = 0\n prev = 0\n for i in verticalCuts:\n mxVr = max(mxVr, i-prev)\n prev = i\n mxVr = max(mxVr, w-verticalCuts[-1])\n \n return (mxHr * mxVr) % ((10 ** 9) + 7)\n", + "title": "1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers nums , return the maximum possible sum of an ascending subarray in nums . A subarray is defined as a contiguous sequence of numbers in an array. A subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is ascending if for all i where l <= i < r , nums i < nums i+1 . Note that a subarray of size 1 is ascending . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20,30,5,10,50]Output:65Explanation:[5,10,50] is the ascending subarray with the maximum sum of 65.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30,40,50]Output:150Explanation:[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "image": null + }, + { + "text": "Example 3: Input:nums = [12,17,15,13,10,11,12]Output:33Explanation:[10,11,12] is the ascending subarray with the maximum sum of 33.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.10 MB (Top 28.39%)\n\nclass Solution {\n public int maxAscendingSum(int[] nums) {\n int res = nums[0],temp = nums[0];\n for(int i = 1;i nums[i-1])\n temp+=nums[i];\n else\n temp = nums[i];\n res = Math.max(res,temp);\n }\n return res;\n }\n}\n", + "title": "1800. Maximum Ascending Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of positive integers nums , return the maximum possible sum of an ascending subarray in nums . A subarray is defined as a contiguous sequence of numbers in an array. A subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] is ascending if for all i where l <= i < r , nums i < nums i+1 . Note that a subarray of size 1 is ascending . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20,30,5,10,50]Output:65Explanation:[5,10,50] is the ascending subarray with the maximum sum of 65.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30,40,50]Output:150Explanation:[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.", + "image": null + }, + { + "text": "Example 3: Input:nums = [12,17,15,13,10,11,12]Output:33Explanation:[10,11,12] is the ascending subarray with the maximum sum of 33.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n count=nums[0]\n final=nums[0]\n for i in range(1,len(nums)):\n if nums[i]>nums[i-1]:\n count+=nums[i]\n else:\n count=nums[i]\n final=max(final,count)\n return final\n", + "title": "1800. Maximum Ascending Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes , where classes[i] = [pass i , total i ] . You know beforehand that in the i th class, there are total i total students, but only pass i number of students will pass the exam. You are also given an integer extraStudents . There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= classes.length <= 10^5", + "classes[i].length == 2", + "1 <= pass i <= total i <= 10^5", + "1 <= extraStudents <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:classes = [[1,2],[3,5],[2,2]],extraStudents= 2Output:0.78333Explanation:You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.", + "image": null + }, + { + "text": "Example 2: Input:classes = [[2,4],[3,9],[4,5],[2,10]],extraStudents= 4Output:0.53485", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 575 ms (Top 86.89%) | Memory: 100.8 MB (Top 90.16%)\nclass Solution {\n public double maxAverageRatio(int[][] classes, int extraStudents) {\n PriorityQueue pq = new PriorityQueue<>(new Comparator(){\n public int compare(double[] a, double[] b){\n double adiff = (a[0]+1)/(a[1]+1) - (a[0]/a[1]);\n double bdiff = (b[0]+1)/(b[1]+1) - (b[0]/b[1]);\n if(adiff==bdiff) return 0;\n return adiff>bdiff? -1:1;\n }\n });\n\n for(int[] c:classes) pq.add(new double[]{c[0],c[1]});\n\n for(int i =0;i float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n\n", + "title": "1792. Maximum Average Pass Ratio", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums consisting of n elements, and an integer k . Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value . Any answer with a calculation error less than 10 -5 will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= k <= n <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,12,-5,-6,50,3], k = 4Output:12.75000Explanation:Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 1Output:5.00000", + "image": null + } + ], + "follow_up": null, + "solution": "//O(N) Time and O(1) Space - SLIDING WINDOW\n\nclass Solution {\npublic:\n double findMaxAverage(vector& nums, int k) {\n \n double ans = INT_MIN;\n \n int i = 0;\n int j = 0;\n int sum = 0;\n \n while(j int:\n v, c, l = [], 0, len(rocks)\n for i in range(l):\n p = capacity[i]-rocks[i]\n if(p>0):\n v.append(p)\n else: c += 1\n v.sort()\n k=0\n while(additionalRocks>0 and k \" 10 010 \"", + "For example, \" 00 010\" -> \" 10 010 \"", + "Operation 2: If the number contains the substring \"10\" , you can replace it with \"01\" . For example, \"000 10 \" -> \"000 01 \"", + "For example, \"000 10 \" -> \"000 01 \"" + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"000110\"Output:\"111011\"Explanation:A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"", + "image": null + }, + { + "text": "Example 2: Input:binary = \"01\"Output:\"01\"Explanation:\"01\" cannot be transformed any further.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 32.6%) | Memory: 45.01 MB (Top 8.1%)\n\nclass Solution {\n public String maximumBinaryString(String binary) {\n int n = binary.length();\n StringBuffer ans = new StringBuffer(\"\");\n StringBuffer buffer = new StringBuffer(\"\");\n int onesAfter1stZero = 0;\n boolean found1stZero = false;\n for(int i=0;i \" 10 010 \"", + "For example, \" 00 010\" -> \" 10 010 \"", + "Operation 2: If the number contains the substring \"10\" , you can replace it with \"01\" . For example, \"000 10 \" -> \"000 01 \"", + "For example, \"000 10 \" -> \"000 01 \"" + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"000110\"Output:\"111011\"Explanation:A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"", + "image": null + }, + { + "text": "Example 2: Input:binary = \"01\"Output:\"01\"Explanation:\"01\" cannot be transformed any further.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 128 ms (Top 57.69%) | Memory: 15.4 MB (Top 69.23%)\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n zero = binary.count('0') # count number of '0'\n zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists\n one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's)\n return f\"{binary[:zero_idx]}{'1'*(zero-1)}{'0'*min(zero, 1)}{'1'*one}\"", + "title": "1702. Maximum Binary String After Change", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Return the maximum binary tree built from nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000", + "All integers in nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,6,0,5]Output:[6,3,5,null,2,0,null,null,1]Explanation:The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg" + }, + { + "text": "Example 2: Input:nums = [3,2,1]Output:[3,null,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode constructMaximumBinaryTree(int[] nums) {\n TreeNode root = construct(nums,0,nums.length-1);\n return root;\n }\n \n private TreeNode construct(int []nums, int start, int end) {\n if(start > end)\n return null;\n if(start == end)\n return new TreeNode(nums[start]);\n \n int maxIdx = findMax(nums,start,end);\n TreeNode root = new TreeNode(nums[maxIdx]);\n \n root.left = construct(nums,start,maxIdx-1);\n root.right = construct(nums,maxIdx+1,end);\n \n return root;\n }\n \n private int findMax(int []arr, int low, int high) {\n int idx = -1, max = Integer.MIN_VALUE;\n for(int i=low;i<=high;++i) \n if(arr[i]>max) {\n max = arr[i];\n idx = i;\n }\n return idx;\n }\n}\n", + "title": "654. Maximum Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Return the maximum binary tree built from nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000", + "All integers in nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,6,0,5]Output:[6,3,5,null,2,0,null,null,1]Explanation:The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg" + }, + { + "text": "Example 2: Input:nums = [3,2,1]Output:[3,null,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n\t\tif not nums:\n\t\t\treturn None\n\t\tm = max(nums)\n\t\tidx = nums.index(m)\n\t\troot = TreeNode(m)\n\t\troot.left = self.constructMaximumBinaryTree(nums[:idx])\n\t\troot.right = self.constructMaximumBinaryTree(nums[idx+1:])\n\t\treturn root", + "title": "654. Maximum Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val . Just as in the previous problem , the given tree was constructed from a list a ( root = Construct(a) ) recursively with the following Construct(a) routine: Note that we were not given a directly, only a root node root = Construct(a) . Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If a is empty, return null .", + "Otherwise, let a[i] be the largest element of a . Create a root node with the value a[i] .", + "The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]) .", + "The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]) .", + "Return root ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,3,null,null,2], val = 5Output:[5,4,null,1,3,null,null,2]Explanation:a = [1,4,2,3], b = [1,4,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG" + }, + { + "text": "Example 2: Input:root = [5,2,4,null,1], val = 3Output:[5,2,4,null,1,null,3]Explanation:a = [2,1,5,4], b = [2,1,5,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG" + }, + { + "text": "Example 3: Input:root = [5,2,3,null,1], val = 4Output:[5,2,4,null,1,3]Explanation:a = [2,1,5,3], b = [2,1,5,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode insertIntoMaxTree(TreeNode root, int val) {\n if (root==null) return new TreeNode(val);\n if (val > root.val) {\n TreeNode newRoot = new TreeNode(val);\n newRoot.left = root;\n return newRoot;\n }\n root.right = insertIntoMaxTree(root.right, val);\n return root;\n }\n}\n", + "title": "998. Maximum Binary Tree II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val . Just as in the previous problem , the given tree was constructed from a list a ( root = Construct(a) ) recursively with the following Construct(a) routine: Note that we were not given a directly, only a root node root = Construct(a) . Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If a is empty, return null .", + "Otherwise, let a[i] be the largest element of a . Create a root node with the value a[i] .", + "The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]) .", + "The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]) .", + "Return root ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,1,3,null,null,2], val = 5Output:[5,4,null,1,3,null,null,2]Explanation:a = [1,4,2,3], b = [1,4,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG" + }, + { + "text": "Example 2: Input:root = [5,2,4,null,1], val = 3Output:[5,2,4,null,1,null,3]Explanation:a = [2,1,5,4], b = [2,1,5,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG" + }, + { + "text": "Example 3: Input:root = [5,2,3,null,1], val = 4Output:[5,2,4,null,1,3]Explanation:a = [2,1,5,3], b = [2,1,5,3,4]", + "image": "https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n approach:\n given a, we can get the inorder traversal of it, then append val to it and\n then construct the tree back\n \"\"\"\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n inorder_list = []\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n inorder_list.append(root.val)\n inorder(root.right)\n \n inorder(root)\n inorder_list.append(val)\n \n def get_maximum(val_list):\n max_index = -1\n max_val = -1\n for i, val in enumerate(val_list):\n if val > max_val:\n max_val = val\n max_index = i\n return max_index, max_val\n \n def create_tree(val_list):\n if not len(val_list):\n return None\n index, val = get_maximum(val_list)\n node = TreeNode(val)\n node.left = create_tree(val_list[:index])\n node.right = create_tree(val_list[index+1:])\n return node\n \n b = create_tree(inorder_list)\n return b\n", + "title": "998. Maximum Binary Tree II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n . However, there are city restrictions on the heights of the new buildings: Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [id i , maxHeight i ] indicates that building id i must have a height less than or equal to maxHeight i . It is guaranteed that each building will appear at most once in restrictions , and building 1 will not be in restrictions . Return the maximum possible height of the tallest building . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The height of each building must be a non-negative integer.", + "The height of the first building must be 0 .", + "The height difference between any two adjacent buildings cannot exceed 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, restrictions = [[2,1],[4,1]]Output:2Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex1-1.png" + }, + { + "text": "Example 2: Input:n = 6, restrictions = []Output:5Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex2.png" + }, + { + "text": "Example 3: Input:n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]Output:5Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 143 ms (Top 19.44%) | Memory: 114.3 MB (Top 55.56%)\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n List list=new ArrayList<>();\n list.add(new int[]{1,0});\n for(int[] restriction:restrictions){\n list.add(restriction);\n }\n Collections.sort(list,new IDSorter());\n\n if(list.get(list.size()-1)[0]!=n){\n list.add(new int[]{n,n-1});\n }\n\n for(int i=1;i=0;i--){\n list.get(i)[1]=Math.min(list.get(i)[1],list.get(i+1)[1] + list.get(i+1)[0] - list.get(i)[0]);\n }\n\n int result=0;\n for(int i=1;i{\n @Override\n public int compare(int[] myself,int[] other){\n return myself[0]-other[0];\n }\n }\n}", + "title": "1840. Maximum Building Height", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n . However, there are city restrictions on the heights of the new buildings: Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [id i , maxHeight i ] indicates that building id i must have a height less than or equal to maxHeight i . It is guaranteed that each building will appear at most once in restrictions , and building 1 will not be in restrictions . Return the maximum possible height of the tallest building . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The height of each building must be a non-negative integer.", + "The height of the first building must be 0 .", + "The height difference between any two adjacent buildings cannot exceed 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, restrictions = [[2,1],[4,1]]Output:2Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex1-1.png" + }, + { + "text": "Example 2: Input:n = 6, restrictions = []Output:5Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex2.png" + }, + { + "text": "Example 3: Input:n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]Output:5Explanation:The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/ic236-q4-ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1203 ms (Top 88.37%) | Memory: 55.60 MB (Top 9.3%)\n\n#Readability version\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # Set the initial height for the 1st building\n restrictions.append([1, 0])\n restrictions.sort()\n\n # Process restrictions to find the valid ones for reaching previous restrictions\n valid_restrictions_forward = []\n temp_diff = 0\n for id, ht in restrictions:\n current_diff = id - ht\n if current_diff >= temp_diff:\n temp_diff = current_diff\n valid_restrictions_forward.append([id, ht])\n\n # Process valid restrictions backward to find the ones for reaching next restrictions\n valid_restrictions_backward = []\n temp_sum = n + n - 1\n for id, ht in valid_restrictions_forward[::-1]:\n current_sum = id + ht\n if current_sum <= temp_sum:\n temp_sum = current_sum\n valid_restrictions_backward.append([id, ht])\n\n # Reverse the backward valid restrictions to get the correct order\n valid_restrictions_backward.reverse()\n\n # Add maximum height for the last building due to the last restriction\n if valid_restrictions_backward[-1][0] != n:\n valid_restrictions_backward.append([n, valid_restrictions_backward[-1][1] + n - valid_restrictions_backward[-1][0]])\n\n # Calculate the maximum height\n max_height = 0\n for i in range(len(valid_restrictions_backward) - 1):\n x1, y1 = valid_restrictions_backward[i]\n x2, y2 = valid_restrictions_backward[i + 1]\n available_height = (-x1 + y1 + x2 + y2) // 2\n if available_height > max_height:\n max_height = available_height\n\n return max_height\n\n", + "title": "1840. Maximum Building Height", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array candies . Each element in the array denotes a pile of candies of size candies[i] . You can divide each pile into any number of sub piles , but you cannot merge two piles together. You are also given an integer k . You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candies.length <= 10^5", + "1 <= candies[i] <= 10^7", + "1 <= k <= 10^12" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [5,8,6], k = 3Output:5Explanation:We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.", + "image": null + }, + { + "text": "Example 2: Input:candies = [2,5], k = 11Output:0Explanation:There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canSplit(int[] candies, long k, long mid) {\n long split = 0;\n for(int i = 0; i < candies.length; ++i) {\n split += candies[i]/mid;\n } \n if(split >= k)\n return true;\n else\n return false;\n }\n \n public int maximumCandies(int[] candies, long k) {\n long sum = 0;\n for(int i = 0; i < candies.length; ++i) {\n sum += candies[i];\n }\n long start = 1, end = sum;\n long ans = 0;\n while(start <= end) {\n long mid = (start + end)/2;\n if(canSplit(candies, k, mid)) {\n ans = mid;\n start = mid + 1;\n } else {\n end = mid-1;\n }\n }\n return (int)ans;\n }\n}\n", + "title": "2226. Maximum Candies Allocated to K Children", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array candies . Each element in the array denotes a pile of candies of size candies[i] . You can divide each pile into any number of sub piles , but you cannot merge two piles together. You are also given an integer k . You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. Return the maximum number of candies each child can get. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candies.length <= 10^5", + "1 <= candies[i] <= 10^7", + "1 <= k <= 10^12" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [5,8,6], k = 3Output:5Explanation:We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.", + "image": null + }, + { + "text": "Example 2: Input:candies = [2,5], k = 11Output:0Explanation:There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3294 ms (Top 14.29%) | Memory: 27.4 MB (Top 62.05%)\ndef canSplit(candies, mid, k):\n split = 0\n for i in candies:\n split += i//mid\n if split >= k:\n return True\n else:\n return False\n\nclass Solution:\n def maximumCandies(self, candies: List[int], k: int) -> int:\n end = sum(candies)//k\n start = 1\n ans = 0\n while start <= end:\n mid = (start + end)//2\n if canSplit(candies, mid, k):\n start = mid + 1\n ans = mid\n else:\n end = mid - 1\n return ans\n", + "title": "2226. Maximum Candies Allocated to K Children", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n boxes labeled from 0 to n - 1 . You are given four arrays: status , candies , keys , and containedBoxes where: You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "status[i] is 1 if the i th box is open and 0 if the i th box is closed,", + "candies[i] is the number of candies in the i th box,", + "keys[i] is a list of the labels of the boxes you can open after opening the i th box.", + "containedBoxes[i] is a list of the boxes you found inside the i th box." + ], + "examples": [ + { + "text": "Example 1: Input:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]Output:16Explanation:You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.", + "image": null + }, + { + "text": "Example 2: Input:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]Output:6Explanation:You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 61.19%) | Memory: 57.10 MB (Top 59.7%)\n\nclass Solution {\n\t\tpublic int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes)\n\t\t{\n\t\t\tint n=initialBoxes.length;\n\n\t\t\tif(n==0)\n\t\t\t\treturn 0;\n\n\t\t\tQueue q=new LinkedList<>();\n\t\t\tint totalCandies=0;\n\n\t\t\tfor(int i:initialBoxes)\n\t\t\t{\n if(status[i]==0)\n {\n q.add(i);\n }\n else\n {\n totalCandies+=candies[i]; // Add all Candies of intial box;\n for(int j=0;j0 && isValid(q,status))\n\t\t\t{\n\t\t\t\tint b=q.poll();\n\t\t\t\tif(status[b]==1)\n\t\t\t\t{\n\t\t\t\t\ttotalCandies+=candies[b]; // Add all Candies of selected box;\n\n\n\t\t\t\t\tfor(int j=0;j q,int[] status) \n\t\t{\n\t\t\tQueue cq=new LinkedList<>(q);\n\n\t\t\twhile(cq.size()>0)\n\t\t\t{\n\t\t\t\tif(status[cq.poll()]==1)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n", + "title": "1298. Maximum Candies You Can Get from Boxes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n boxes labeled from 0 to n - 1 . You are given four arrays: status , candies , keys , and containedBoxes where: You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "status[i] is 1 if the i th box is open and 0 if the i th box is closed,", + "candies[i] is the number of candies in the i th box,", + "keys[i] is a list of the labels of the boxes you can open after opening the i th box.", + "containedBoxes[i] is a list of the boxes you found inside the i th box." + ], + "examples": [ + { + "text": "Example 1: Input:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]Output:16Explanation:You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.", + "image": null + }, + { + "text": "Example 2: Input:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]Output:6Explanation:You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n count = 0 # Found candy. Class variable to keep found candy\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n boxes = [] # Newly found boxes\n progress = False\n for box in initialBoxes:\n if status[box]: # The box is open\n progress = True\n boxes.extend(containedBoxes[box]) # Add newly found boxes\n self.count += candies[box] # Count found candy\n for key in keys[box]:\n status[key] = 1 # Use found keys to open boxes even if we don't have them.\n else:\n boxes.append(box) # The box is closed. Keep it for the next iteration.\n if not progress: # Nothing happened. return.\n return self.count\n\t\t# Run another iteration with the new 'boxes'\n return self.maxCandies(status, candies, keys, containedBoxes, boxes)\n", + "title": "1298. Maximum Candies You Can Get from Boxes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1 . The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the i th student ( 0-indexed ). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the j th mentor ( 0-indexed ). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores . Given students and mentors , return the maximum compatibility score sum that can be achieved. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the student's answers were [1, 0 , 1 ] and the mentor's answers were [0, 0 , 1 ] , then their compatibility score is 2 because only the second and the third answers are the same." + ], + "examples": [ + { + "text": "Example 1: Input:students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]Output:8Explanation:We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.", + "image": null + }, + { + "text": "Example 2: Input:students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]Output:0Explanation:The compatibility score of any student-mentor pair is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 29.11%) | Memory: 42.3 MB (Top 38.61%)\nclass Solution {\n int max;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n boolean[] visited = new boolean[students.length];\n helper(visited, students, mentors, 0, 0);\n return max;\n }\n public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos, int score){\n if(pos >= students.length){\n max = Math.max(max, score);\n return;\n }\n for(int i = 0; i < mentors.length; i++)\n if(!visited[i]){\n visited[i] = true;\n helper(visited, students, mentors, pos + 1, score + score(students[pos], mentors[i]));\n visited[i] = false;\n }\n }\n public int score(int[] a, int[] b){\n int count = 0;\n\n for(int i = 0; i < b.length; i++)\n if(a[i] == b[i]) count += 1;\n return count;\n }\n}", + "title": "1947. Maximum Compatibility Score Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1 . The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the i th student ( 0-indexed ). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the j th mentor ( 0-indexed ). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores . Given students and mentors , return the maximum compatibility score sum that can be achieved. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the student's answers were [1, 0 , 1 ] and the mentor's answers were [0, 0 , 1 ] , then their compatibility score is 2 because only the second and the third answers are the same." + ], + "examples": [ + { + "text": "Example 1: Input:students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]Output:8Explanation:We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.", + "image": null + }, + { + "text": "Example 2: Input:students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]Output:0Explanation:The compatibility score of any student-mentor pair is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 104 ms (Top 82.18%) | Memory: 13.9 MB (Top 66.34%)\nimport heapq\nfrom collections import defaultdict\n\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m, n = len(students), len(students[0])\n def hamming(student, mentor):\n return sum([int(student[i] != mentor[i]) for i in range(n)])\n\n pq = [(0, 0, '0'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)\n optimal = defaultdict(lambda:float('inf'))\n\n while pq: # O(V)\n cost, i, mentor_status = heapq.heappop(pq) # O(logV)\n\n # early stopping with termination condition\n if i == m:\n return m * n - cost\n\n # generate successors. The next student to be assigned is at index i\n for j, mentor in enumerate(mentors): # O(m)\n if mentor_status[j] != '1':\n new_cost = cost + hamming(students[i], mentor)\n new_mentor_status = mentor_status[:j] + '1' + mentor_status[j+1:]\n\n # update optimal cost if a new successor appears with lower cost to the same node\n if new_cost < optimal[(i+1, new_mentor_status)]:\n optimal[(i+1, new_mentor_status)] = new_cost\n heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV)\n\n return 0", + "title": "1947. Maximum Compatibility Score Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors , used for relaxation only. You are given two integers bottom and top , which denote that Alice has rented all the floors from bottom to top ( inclusive ). You are also given the integer array special , where special[i] denotes a special floor that Alice has designated for relaxation. Return the maximum number of consecutive floors without a special floor . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= special.length <= 10^5", + "1 <= bottom <= special[i] <= top <= 10^9", + "All the values of special are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = 2, top = 9, special = [4,6]Output:3Explanation:The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.", + "image": null + }, + { + "text": "Example 2: Input:bottom = 6, top = 8, special = [7,6,8]Output:0Explanation:Every floor rented is a special floor, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 13.68%) | Memory: 77.1 MB (Top 37.46%)\nclass Solution {\n public int maxConsecutive(int bottom, int top, int[] special) {\n int max = Integer.MIN_VALUE;\n\n Arrays.sort(special);\n\n // from bottom to the first special floor\n max = Math.max(max, special[0] - bottom);\n\n // middle floors\n for(int i = 1; i < special.length; i++) {\n max = Math.max(max, special[i] - special[i - 1] - 1);\n }\n\n // from last special floor to the top\n max = Math.max(max, top - special[special.length - 1]);\n\n return max;\n }\n}", + "title": "2274. Maximum Consecutive Floors Without Special Floors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors , used for relaxation only. You are given two integers bottom and top , which denote that Alice has rented all the floors from bottom to top ( inclusive ). You are also given the integer array special , where special[i] denotes a special floor that Alice has designated for relaxation. Return the maximum number of consecutive floors without a special floor . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= special.length <= 10^5", + "1 <= bottom <= special[i] <= top <= 10^9", + "All the values of special are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = 2, top = 9, special = [4,6]Output:3Explanation:The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.", + "image": null + }, + { + "text": "Example 2: Input:bottom = 6, top = 8, special = [7,6,8]Output:0Explanation:Every floor rented is a special floor, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n special.sort()\n special.insert(0, bottom - 1)\n special.append(top + 1)\n \n ans = 0\n for i in range(len(special)-1):\n ans = max(ans, special[i+1] - special[i] - 1)\n return ans\n", + "title": "2274. Maximum Consecutive Floors Without Special Floors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(TreeNode root) {\n // Base Condition\n if(root == null) return 0;\n // Hypothesis\n int left = maxDepth(root.left);\n int right = maxDepth(root.right);\n // Induction\n return Math.max(left, right) + 1;\n }\n}\n", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 88.16%) | Memory: 16.3 MB (Top 23.73%)\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n depths = []\n self.handler(root, result, depths)\n return max(depths)\n\n def handler(self, root, result, depths):\n if root:\n result += 1\n self.handler(root.left, result, depths)\n self.handler(root.right, result, depths)\n else:\n depths.append(result)", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:3", + "image": null + }, + { + "text": "Example 2: 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:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(Node root) {\n if (root == null) return 0;\n int[] max = new int[]{0};\n dfs(root,1,max);\n return max[0];\n }\n public static void dfs(Node root, int depth, int[] max) {\n if (depth>max[0]) max[0] = depth;\n if(root==null){\n return;\n }\n ++depth;\n for(Node n:root.children) dfs(n, depth, max);\n }\n}\n", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:3", + "image": null + }, + { + "text": "Example 2: 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:5", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\n#DFS\nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n if root is None:\n return 0\n def dfs(r):\n \n if not r.children:\n return 1\n depth = 0\n for child in r.children:\n depth = max(depth, dfs(child) + 1)\n \n return depth\n\n return dfs(root)\n\t\t\n\t\t\n#BFS \nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n if root is None:\n return 0\n def bfs(r):\n \n q = []\n q.append(root)\n level = 0\n while q != []:\n num_nodes = len(q)\n level += 1\n for _ in range(num_nodes):\n node = q.pop(0)\n\n for child in node.children:\n q.append(child)\n return level\n\n return bfs(root)\n\n", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The total number of nodes is in the range [0, 10^4 ] .", + "The depth of the n-ary tree is less than or equal to 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:3", + "image": null + }, + { + "text": "Example 2: 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:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDepth(self, root: 'Node') -> int:\n \n if not root : return 0\n \n if root.children :\n return 1 + max([self.maxDepth(x) for x in root.children])\n else :\n return 1 ", + "title": "559. Maximum Depth of N-ary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a 0-indexed integer array nums of size n , find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i] ), such that 0 <= i < j < n and nums[i] < nums[j] . Return the maximum difference . If no such i and j exists, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 1000", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,1,5,4]Output:4Explanation:The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,3,2]Output:-1Explanation:There is no i and j such that i < j and nums[i] < nums[j].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,2,10]Output:9Explanation:The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 99.17%)\nclass Solution {\n public int maximumDifference(int[] nums) {\n if(nums.length < 2)\n return -1;\n int result = Integer.MIN_VALUE;\n int minValue = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > minValue)\n result = Math.max(result, nums[i] - minValue);\n minValue = Math.min(minValue, nums[i]);\n }\n return result == Integer.MIN_VALUE ? -1 : result;\n }\n}", + "title": "2016. Maximum Difference Between Increasing Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 0-indexed integer array nums of size n , find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i] ), such that 0 <= i < j < n and nums[i] < nums[j] . Return the maximum difference . If no such i and j exists, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 1000", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,1,5,4]Output:4Explanation:The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,3,2]Output:-1Explanation:There is no i and j such that i < j and nums[i] < nums[j].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,5,2,10]Output:9Explanation:The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curmin = nums[0]\n diff = 0\n for num in nums:\n diff = max(diff, num - curmin)\n curmin = min(curmin, num)\n return diff or -1\n", + "title": "2016. Maximum Difference Between Increasing Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b . A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5000] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [8,3,10,1,6,null,14,null,null,4,7,13]Output:7Explanation:We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2,null,0,3]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 70.91%) | Memory: 41.7 MB (Top 98.42%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxAncestorDiff(TreeNode root) {\n\n if (root == null) return 0;\n\n return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n\n public int find(TreeNode root, int min, int max) {\n if (root == null) return Math.abs(max-min);\n\n min = Math.min(min, root.val);\n max = Math.max(max, root.val);\n\n return Math.max(find(root.left, min, max), find(root.right, min, max));\n }\n\n}", + "title": "1026. Maximum Difference Between Node and Ancestor", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b . A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5000] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [8,3,10,1,6,null,14,null,null,4,7,13]Output:7Explanation:We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2,null,0,3]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n self.max_diff = float('-inf')\n \n def dfs(node,prev_min,prev_max):\n if not node:\n return\n dfs(node.left,min(prev_min,node.val),max(prev_max,node.val))\n dfs(node.right,min(prev_min,node.val),max(prev_max,node.val))\n self.max_diff = max(abs(node.val-prev_min),abs(node.val-prev_max),self.max_diff)\n dfs(root,root.val,root.val)\n return self.max_diff\n", + "title": "1026. Maximum Difference Between Node and Ancestor", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 ​​​​​​ and nums2 ​​​​​​. A pair of indices (i, j) , where 0 <= i < nums1.length and 0 <= j < nums2.length , is valid if both i <= j and nums1[i] <= nums2[j] . The distance of the pair is j - i ​​​​. Return the maximum distance of any valid pair (i, j) . If there are no valid pairs, return 0 . An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[j] <= 10^5", + "Both nums1 and nums2 are non-increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]Output:2Explanation:The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,2,2], nums2 = [10,10,1]Output:1Explanation:The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]Output:2Explanation:The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 16.02%) | Memory: 101.7 MB (Top 80.40%)\nclass Solution {\n public int maxDistance(int[] nums1, int[] nums2) {\n int max = 0;\n for (int i = 0; i < nums1.length; i++) {\n int r = nums2.length - 1;\n int l = i;\n int m = i;\n while (l <= r) {\n m = l + (r - l) / 2;\n if (nums1[i] > nums2[m]) {\n r = m - 1;\n } else if (nums1[i] == nums2[m]) {\n l = m + 1;\n } else {\n l = m + 1;\n }\n }\n if (r < 0) {\n continue;\n }\n max = Math.max(max, r - i);\n }\n return max;\n }\n}", + "title": "1855. Maximum Distance Between a Pair of Values", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two non-increasing 0-indexed integer arrays nums1 ​​​​​​ and nums2 ​​​​​​. A pair of indices (i, j) , where 0 <= i < nums1.length and 0 <= j < nums2.length , is valid if both i <= j and nums1[i] <= nums2[j] . The distance of the pair is j - i ​​​​. Return the maximum distance of any valid pair (i, j) . If there are no valid pairs, return 0 . An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "1 <= nums1[i], nums2[j] <= 10^5", + "Both nums1 and nums2 are non-increasing ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]Output:2Explanation:The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,2,2], nums2 = [10,10,1]Output:1Explanation:The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]Output:2Explanation:The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDistance(self, n1: List[int], n2: List[int]) -> int:\n i = j = res = 0\n while i < len(n1) and j < len(n2):\n if n1[i] > n2[j]:\n i += 1\n else:\n res = max(res, j - i)\n j += 1\n return res\n", + "title": "1855. Maximum Distance Between a Pair of Values", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides , where rides[i] = [start i , end i , tip i ] denotes the i th passenger requesting a ride from point start i to point end i who is willing to give a tip i dollar tip. For each passenger i you pick up, you earn end i - start i + tip i dollars. You may only drive at most one passenger at a time. Given n and rides , return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= rides.length <= 3 * 10^4", + "rides[i].length == 3", + "1 <= start i < end i <= n", + "1 <= tip i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, rides = [[2,5,4],[1,5,1]]Output:7Explanation:We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.", + "image": null + }, + { + "text": "Example 2: Input:n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]Output:20Explanation:We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 72.84%) | Memory: 71.20 MB (Top 35.03%)\n\nclass Solution {\n private static class Job {\n\t\tprivate int start;\n\t\tprivate int end;\n\t\tprivate int profit;\n\n\t\tpublic Job(int start, int end, int profit) {\n\t\t\tthis.start = start;\n\t\t\tthis.end = end;\n\t\t\tthis.profit = profit;\n\t\t}\n\t}\n \n private int binarySearch(Job jobs[], int index) {\n\t\tint low = 0;\n\t\tint high = index - 1;\n\t\tint ans = -1;\n\t\twhile (low <= high) {\n\t\t\tint mid = low + (high - low) / 2;\n\t\t\tif (jobs[mid].end <= jobs[index].start) {\n\t\t\t\tans = mid;\n\t\t\t\tlow = mid + 1;\n\t\t\t} else {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n \n public long maxTaxiEarnings(int n, int[][] rides) {\n\t\tJob jobs[] = new Job[rides.length];\n\t\tfor (int i = 0; i < rides.length; i++) {\n\t\t\tjobs[i] = new Job(rides[i][0], rides[i][1], rides[i][1] - rides[i][0] + rides[i][2]);\n\t\t}\n\t\tArrays.sort(jobs, (j1, j2) -> (j1.end - j2.end));\n\t\tlong[] dp = new long[rides.length];\n\t\tdp[0] = jobs[0].profit;\n\t\tfor (int i = 1; i < jobs.length; i++) {\n\t\t\tlong include = jobs[i].profit;\n\t\t\tint index = binarySearch(jobs, i);\n\t\t\tif (index != -1) {\n\t\t\t\tinclude += dp[index];\n\t\t\t}\n\t\t\tdp[i] = Math.max(include, dp[i - 1]);\n\t\t}\n\t\treturn dp[rides.length - 1];\n }\n}\n", + "title": "2008. Maximum Earnings From Taxi", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides , where rides[i] = [start i , end i , tip i ] denotes the i th passenger requesting a ride from point start i to point end i who is willing to give a tip i dollar tip. For each passenger i you pick up, you earn end i - start i + tip i dollars. You may only drive at most one passenger at a time. Given n and rides , return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= rides.length <= 3 * 10^4", + "rides[i].length == 3", + "1 <= start i < end i <= n", + "1 <= tip i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, rides = [[2,5,4],[1,5,1]]Output:7Explanation:We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.", + "image": null + }, + { + "text": "Example 2: Input:n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]Output:20Explanation:We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: \n rides.sort()\n for job in rides:\n job[2]+=job[1]-job[0]\n \n heap=[]\n cur=ans=0\n for start,e,p in rides:\n \n while heap and heap[0][0]<=start: \n _,val=heappop(heap)\n cur=max(cur,val)\n heappush(heap,(e,cur+p))\n \n ans=max(ans,cur+p)\n \n return ans\n", + "title": "2008. Maximum Earnings From Taxi", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of positive integers arr . Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The value of the first element in arr must be 1 .", + "The absolute difference between any 2 adjacent elements must be less than or equal to 1 . In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length ( 0-indexed ). abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,1,2,1]Output:2Explanation:We can satisfy the conditions by rearrangingarrso it becomes[1,2,2,2,1].\nThe largest element inarris 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,1,1000]Output:3Explanation:One possible way to satisfy the conditions is by doing the following:\n1. Rearrangearrso it becomes[1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNowarr = [1,2,3], whichsatisfies the conditions.\nThe largest element inarr is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5]Output:5Explanation:The array already satisfies the conditions, and the largest element is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n arr[0] = 1;\n for(int i = 1;i 1)\n arr[i] = arr[i-1] + 1; \n }\n return arr[arr.length-1];\n }\n}", + "title": "1846. Maximum Element After Decreasing and Rearranging", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of positive integers arr . Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The value of the first element in arr must be 1 .", + "The absolute difference between any 2 adjacent elements must be less than or equal to 1 . In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length ( 0-indexed ). abs(x) is the absolute value of x ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,1,2,1]Output:2Explanation:We can satisfy the conditions by rearrangingarrso it becomes[1,2,2,2,1].\nThe largest element inarris 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,1,1000]Output:3Explanation:One possible way to satisfy the conditions is by doing the following:\n1. Rearrangearrso it becomes[1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNowarr = [1,2,3], whichsatisfies the conditions.\nThe largest element inarr is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5]Output:5Explanation:The array already satisfies the conditions, and the largest element is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\t\tcounter = collections.Counter(arr)\n available = sum(n > len(arr) for n in arr)\n i = ans = len(arr)\n while i > 0:\n # This number is not in arr\n if not counter[i]:\n # Use another number to fill in its place. If we cannot, we have to decrease our max\n if available: available -= 1 \n else: ans -= 1\n # Other occurences can be used for future.\n else:\n available += counter[i] - 1\n i -= 1\n return ans\n", + "title": "1846. Maximum Element After Decreasing and Rearranging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1 . Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite , where favorite[i] denotes the favorite person of the i th employee, return the maximum number of employees that can be invited to the meeting . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == favorite.length", + "2 <= n <= 10^5", + "0 <= favorite[i] <= n - 1", + "favorite[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:favorite = [2,2,1,2]Output:3Explanation:The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex1.png" + }, + { + "text": "Example 2: Input:favorite = [1,2,0]Output:3Explanation:Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": null + }, + { + "text": "Example 3: Input:favorite = [3,0,1,4,1]Output:4Explanation:The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 107 ms (Top 43.06%) | Memory: 139.6 MB (Top 38.28%)\nclass Solution {\n public int maximumInvitations(int[] favorite) {\n List> graph = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n graph.add(new ArrayList<>());\n }\n\n int answer = 0;\n\n List> pairs = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n if (i == favorite[favorite[i]]) {\n if (i < favorite[i]) {\n List pair = new ArrayList<>();\n pair.add(i);\n pair.add(favorite[i]);\n pairs.add(pair);\n }\n } else {\n graph.get(favorite[i]).add(i);\n }\n }\n\n boolean[] visited = new boolean[favorite.length];\n for (List pair: pairs) {\n answer += dfs(graph, pair.get(0), visited) + dfs(graph, pair.get(1), visited);\n }\n\n int[] counter = new int[favorite.length];\n int[] round = new int[favorite.length];\n\n int rnd = 1;\n\n int circleMax = 0;\n\n for (int i = 0; i < favorite.length; i++) {\n if (visited[i]) {\n continue;\n }\n if (round[i] != 0) {\n continue;\n }\n\n int cnt = 1;\n int j = i;\n while (counter[j] == 0) {\n counter[j] = cnt;\n round[j] = rnd;\n j = favorite[j];\n cnt++;\n }\n if (round[j] == rnd) {\n circleMax = Math.max(circleMax, cnt - counter[j]);\n }\n rnd++;\n }\n return Math.max(circleMax, answer);\n }\n\n private int dfs(List> graph, int node, boolean[] visited) {\n visited[node] = true;\n int max = 0;\n for (int neighbor: graph.get(node)) {\n max = Math.max(max, dfs(graph, neighbor, visited));\n }\n return max + 1;\n }\n}", + "title": "2127. Maximum Employees to Be Invited to a Meeting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1 . Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite , where favorite[i] denotes the favorite person of the i th employee, return the maximum number of employees that can be invited to the meeting . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == favorite.length", + "2 <= n <= 10^5", + "0 <= favorite[i] <= n - 1", + "favorite[i] != i" + ], + "examples": [ + { + "text": "Example 1: Input:favorite = [2,2,1,2]Output:3Explanation:The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex1.png" + }, + { + "text": "Example 2: Input:favorite = [1,2,0]Output:3Explanation:Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.", + "image": null + }, + { + "text": "Example 3: Input:favorite = [3,0,1,4,1]Output:4Explanation:The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.", + "image": "https://assets.leetcode.com/uploads/2021/12/14/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n visited_time = [0] * n\n inpath = [False] * n\n cur_time = 1\n def get_max_len_cycle(cur) :\n nonlocal cur_time\n inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]\n cur_time += 1\n ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1\n if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))\n inpath[cur] = False\n return ret\n \n ret_cycle = 0\n for i in range(n) :\n if visited_time[i] == 0 :\n ret_cycle = max(ret_cycle, get_max_len_cycle(i))\n \n ret_not_cycle = 0\n back_edge_graph = [[] for _ in range(n)]\n for i in range(n) : back_edge_graph[favorite[i]].append(i)\n def get_max_depth(cur) :\n ret = 0\n for nxt in back_edge_graph[cur] :\n if favorite[cur] != nxt :\n ret = max(ret, get_max_depth(nxt) + 1)\n return ret\n \n for i in range(n) :\n if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1\n \n ret = max(ret_cycle, ret_not_cycle)\n return ret\n", + "title": "2127. Maximum Employees to Be Invited to a Meeting", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums , such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1,1,5,3,3,5]Output:7Explanation:For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]Output:13", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.TreeMap;\nimport java.util.NavigableMap;\nclass Solution {\n public int maxEqualFreq(int[] nums) {\n Map F = new HashMap<>(); //Frequencies\n NavigableMap V = new TreeMap<>(); //Values for frequencies\n int max = 0;\n for (int i = 0; i < nums.length; i++) {\n increaseCount(F, nums[i]);\n int frequency = F.get(nums[i]);\n decreaseCount(V, frequency - 1);\n increaseCount(V, frequency);\n if (isPossibleToRemove(V)) max = i;\n }\n return max + 1;\n }\n \n public boolean isPossibleToRemove(NavigableMap frequenciesMap) {\n if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies\n Map.Entry first = frequenciesMap.firstEntry();\n Map.Entry last = frequenciesMap.lastEntry();\n if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d]\n int firstReduced = removeElement(first);\n int lastReduced = removeElement(last);\n if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false;\n return true;\n }\n \n //Try to remove element which contributes to this frequency:\n //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1\n //if there are more than 1 occurences of such frequency, removing 1 element will not change it\n public int removeElement(Map.Entry frequencyValue) {\n if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1;\n return frequencyValue.getKey();\n }\n \n public void decreaseCount(Map map, int element) {\n if (!map.containsKey(element)) return;\n map.put(element, map.get(element) - 1);\n if (map.get(element) == 0) map.remove(element);\n }\n \n public void increaseCount(Map map, int element) {\n if (!map.containsKey(element)) map.put(element, 0);\n map.put(element, map.get(element) + 1);\n }\n}\n", + "title": "1224. Maximum Equal Frequency", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums , such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1,1,5,3,3,5]Output:7Explanation:For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]Output:13", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ans = 0\n n = len(nums)\n countToFreq = defaultdict(int)\n # key = count value = Freq ex 2 occured 3 times in nums so 2 : 3\n freqToCount = defaultdict(int)\n # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3\n \n for i,val in enumerate(nums):\n \n x = countToFreq[val] + 1\n freqToCount[x - 1] -= 1\n if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)\n freqToCount[x] += 1\n countToFreq[val] = x\n \n # if a single item is repeated for i + 1 times like [1,1,1]\n if countToFreq[val] == i + 1 :ans = i + 1\n \n # if all items are having same frequency like [2,2,1,1,3,3]\n elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1\n \n # if all items have same frequency except one having 1 freq like [2,2,3,3,1]\n elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1\n \n # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]\n elif len(freqToCount) == 2:\n keys,values = [],[]\n for j in freqToCount:keys.append(j) , values.append(freqToCount[j])\n if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1\n return ans\n", + "title": "1224. Maximum Equal Frequency", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of positive integers nums and want to erase a subarray containing unique elements . The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a , that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,4,5,6]Output:17Explanation:The optimal subarray here is [2,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,1,2,5,2,1,2,5]Output:8Explanation:The optimal subarray here is [5,2,1] or [1,2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 95.0%) | Memory: 59.10 MB (Top 35.8%)\n\nclass Solution {\n public int maximumUniqueSubarray(int[] nums) {\n short[] nmap = new short[10001];\n int total = 0, best = 0;\n for (int left = 0, right = 0; right < nums.length; right++) {\n nmap[nums[right]]++;\n total += nums[right];\n while (nmap[nums[right]] > 1) {\n nmap[nums[left]]--;\n total -= nums[left++];\n }\n best = Math.max(best, total);\n }\n return best;\n }\n}", + "title": "1695. Maximum Erasure Value", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of positive integers nums and want to erase a subarray containing unique elements . The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a , that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,4,5,6]Output:17Explanation:The optimal subarray here is [2,4,5,6].", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,1,2,5,2,1,2,5]Output:8Explanation:The optimal subarray here is [5,2,1] or [1,2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 796 ms (Top 99.64%) | Memory: 29.60 MB (Top 94.86%)\n\nclass Solution:\n\tdef maximumUniqueSubarray(self, nums: List[int]) -> int:\n\t\tlow = 0\n\t\tvisited = set()\n\t\tresult = 0\n\t\tcurSum = 0\n\t\tfor high in range(len(nums)):\n\t\t\twhile nums[high] in visited:\n\t\t\t\tvisited.remove(nums[low])\n\t\t\t\tcurSum -= nums[low]\n\t\t\t\tlow+=1\n\n\t\t\tvisited.add(nums[high])\n\t\t\tcurSum += nums[high]\n\n\t\t\tif curSum > result:\n\t\t\t\tresult = curSum\n\n\t\treturn result\n", + "title": "1695. Maximum Erasure Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: Example 1:", + "description_images": [], + "constraints": [ + "FreqStack() constructs an empty frequency stack.", + "void push(int val) pushes an integer val onto the top of the stack.", + "int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.", + "If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]Output[null, null, null, null, null, null, null, 5, 7, 5, 4]ExplanationFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 83.25%) | Memory: 51.6 MB (Top 94.52%)\nclass Node{\n int data, freq, time;\n Node(int data, int freq, int time){\n this.data=data;\n this.freq=freq;\n this.time=time;\n }\n}\n\nclass CompareNode implements Comparator{\n @Override\n public int compare(Node a, Node b){\n if(a.freq-b.freq==0){\n return b.time-a.time;\n }\n return b.freq-a.freq;\n }\n}\n\nclass FreqStack {\n PriorityQueue pq;\n Map map;\n int c=0;\n public FreqStack(){\n pq=new PriorityQueue<>(new CompareNode());\n map=new HashMap<>();\n }\n\n public void push(int val){\n c++;\n int freq=1;\n if(map.containsKey(val)){\n freq+=map.get(val).freq;\n }\n map.put(val, new Node(val, freq, c));\n pq.add(new Node(val,freq,c++));\n }\n\n public int pop() {\n Node r=pq.remove();\n Node a=map.get(r.data);\n a.freq--;\n return r.data;\n }\n}", + "title": "895. Maximum Frequency Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: Example 1:", + "description_images": [], + "constraints": [ + "FreqStack() constructs an empty frequency stack.", + "void push(int val) pushes an integer val onto the top of the stack.", + "int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.", + "If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]Output[null, null, null, null, null, null, null, 5, 7, 5, 4]ExplanationFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 347 ms (Top 94.76%) | Memory: 22.7 MB (Top 60.86%)\nclass FreqStack:\n\n def __init__(self):\n self.cnt = {}\n self.maxcount = 0\n self.stack = {}\n\n def push(self, val: int) -> None:\n count = self.cnt.get(val,0)+1\n self.cnt[val] = count\n if count>self.maxcount:\n self.maxcount = count\n self.stack[count] = []\n self.stack[count].append(val)\n\n def pop(self) -> int:\n res = self.stack[self.maxcount].pop()\n self.cnt[res]-=1\n if not self.stack[self.maxcount]:\n self.maxcount-=1\n return res\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()", + "title": "895. Maximum Frequency Stack", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [position i , amount i ] depicts amount i fruits at the position position i . fruits is already sorted by position i in ascending order , and each position i is unique . You are also given an integer startPos and an integer k . Initially, you are at the position startPos . From any position, you can either walk to the left or right . It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= fruits.length <= 10^5", + "fruits[i].length == 2", + "0 <= startPos, position i <= 2 * 10^5", + "position i-1 < position i for any i > 0 ( 0-indexed )", + "1 <= amount i <= 10^4", + "0 <= k <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4Output:9Explanation:The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/1.png" + }, + { + "text": "Example 2: Input:fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4Output:14Explanation:You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/2.png" + }, + { + "text": "Example 3: Input:fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2Output:0Explanation:You can move at most k = 2 steps and cannot reach any position with fruits.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 54.24%) | Memory: 127.9 MB (Top 64.41%)\nclass Solution {\n public int maxTotalFruits(int[][] fruits, int startPos, int k) {\n int n = fruits.length;\n int posOfLastFruit = fruits[n-1][0];\n int prefixArr[] = new int[posOfLastFruit + 1];\n int start = Math.max(startPos - k, 0);\n int end = Math.min(startPos + k, prefixArr.length-1);\n\n if(startPos > posOfLastFruit) {\n int diff = startPos - posOfLastFruit;\n startPos = posOfLastFruit;\n k = k - diff;\n if(k == 0)\n return fruits[posOfLastFruit][1];\n else if(k < 0)\n return 0;\n }\n\n for(int i = 0 ; i < n ; i++) {\n prefixArr[fruits[i][0]] = fruits[i][1];\n }\n\n int curr = 0;\n for(int i = startPos-1 ; i >= start ; i--) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n curr = 0;\n for(int i = startPos+1 ; i <= end ; i++) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n int minimum = prefixArr[startPos];\n prefixArr[startPos] = 0;\n int ans = 0;\n\n for(int i = start ; i < startPos ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = startPos - i;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i + stepsRemaining;\n\n if(endIndex > startPos && endIndex < prefixArr.length) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex >= prefixArr.length) {\n maxCurrPossible += prefixArr[prefixArr.length-1];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n for(int i = startPos+1 ; i <= end ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = i - startPos;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i - stepsRemaining;\n\n if(endIndex < startPos && endIndex >= 0) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex < 0) {\n maxCurrPossible += prefixArr[0];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n return ans + minimum;\n }\n}", + "title": "2106. Maximum Fruits Harvested After at Most K Steps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [position i , amount i ] depicts amount i fruits at the position position i . fruits is already sorted by position i in ascending order , and each position i is unique . You are also given an integer startPos and an integer k . Initially, you are at the position startPos . From any position, you can either walk to the left or right . It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= fruits.length <= 10^5", + "fruits[i].length == 2", + "0 <= startPos, position i <= 2 * 10^5", + "position i-1 < position i for any i > 0 ( 0-indexed )", + "1 <= amount i <= 10^4", + "0 <= k <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4Output:9Explanation:The optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/1.png" + }, + { + "text": "Example 2: Input:fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4Output:14Explanation:You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/2.png" + }, + { + "text": "Example 3: Input:fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2Output:0Explanation:You can move at most k = 2 steps and cannot reach any position with fruits.", + "image": "https://assets.leetcode.com/uploads/2021/11/21/3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 5941 ms (Top 24.26%) | Memory: 59.9 MB (Top 86.39%)\nclass Solution:\n def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n arr = [0 for _ in range(2*k+1)]\n for pos, numOfFruit in fruits:\n if pos < startPos-k or pos > startPos+k:\n continue\n arr[pos-(startPos-k)] += numOfFruit\n\n left, right = sum(arr[:k+1]), sum(arr[k:])\n maxSeen = max(left, right)\n\n turn = 1 # turning point\n for i in range(2, k+1, 2):\n left = left-arr[i-2]-arr[i-1]+arr[k+turn]\n right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn]\n maxSeen = max(maxSeen, left, right)\n turn += 1\n\n return maxSeen", + "title": "2106. Maximum Fruits Harvested After at Most K Steps", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the maximum difference between two successive elements in its sorted form . If the array contains less than two elements, return 0 . You must write an algorithm that runs in linear time and uses linear extra space. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,9,1]Output:3Explanation:The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10]Output:0Explanation:The array contains less than 2 elements, therefore return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumGap(int[] nums) {\n Arrays.sort(nums);\n int res=0;\n if(nums.length==0){\n return 0;\n }\n for (int i =0;i int:\n if len(nums)<2: return 0\n \n #radix sort\n #N = length of nums\n #find number of digits in largest number - O(K) where K = length of largest number\n longest = 0\n for i in nums:\n longest = max(longest,len(str(i)))\n \n #normalize so that all numbers have same number of digits by adding 0s at the start of shorter numbers - O(N*K)\n for i in range(len(nums)):\n if len(str(nums[i]))!=longest:\n nums[i] = '0'*(longest-len(str(nums[i]))) + str(nums[i])\n else:\n nums[i] = str(nums[i])\n \n #apply counting sort starting with each digit from the end of the last digits - O(K*N)\n for digit in range(longest-1,-1,-1):\n vals = [[] for k in range(10)]\n for num in nums:\n vals[int(num[digit])] += [num]\n\t\t\t#join list sorted by that digit position together:\n new = []\n for i in vals:\n new += i\n nums = new.copy()\n \n #find the largest difference in the now sorted nums - O(N)\n best_diff = 0\n for i in range(1,len(nums)):\n best_diff = max(best_diff,int(nums[i])-int(nums[i-1]))\n return best_diff\n \n#Overall complexity is O(N*K) but K is at most 10 so O(10*N) = O(N) so linear\n#Please correct me if I am wrong!\n", + "title": "164. Maximum Gap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a rooted tree consisting of n nodes numbered 0 to n - 1 . Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x ). The genetic difference between two genetic values is defined as the bitwise- XOR of their values. You are given the integer array parents , where parents[i] is the parent for node i . If node x is the root of the tree, then parents[x] == -1 . You are also given the array queries where queries[i] = [node i , val i ] . For each query i , find the maximum genetic difference between val i and p i , where p i is the genetic value of any node that is on the path between node i and the root (including node i and the root). More formally, you want to maximize val i XOR p i . Return an array ans where ans[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= parents.length <= 10^5", + "0 <= parents[i] <= parents.length - 1 for every node i that is not the root.", + "parents[root] == -1", + "1 <= queries.length <= 3 * 10^4", + "0 <= node i <= parents.length - 1", + "0 <= val i <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]Output:[2,3,7]Explanation:The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/c1.png" + }, + { + "text": "Example 2: Input:parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]Output:[6,14,7]Explanation:The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/c2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 6663 ms (Top 46.4%) | Memory: 339.09 MB (Top 7.1%)\n\nclass Solution:\n def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:\n adj_map = collections.defaultdict(set)\n root = None\n for i, node in enumerate(parents):\n if node == -1:\n root = i\n else:\n adj_map[node].add(i)\n queries_map = collections.defaultdict(set)\n\n for q in queries:\n queries_map[q[0]].add(q[1])\n self.res_map = {}\n def helperDFS(curr_root,prefix_map):\n\n if curr_root in queries_map:\n for val in queries_map[curr_root]:\n bin_rep = format(val, '020b')\n best_bin = \"\"\n print(bin_rep)\n for i in range(20):\n if prefix_map[best_bin+str(1-int(bin_rep[i]))]:\n best_bin += str(1-int(bin_rep[i]))\n else:\n best_bin += bin_rep[i]\n self.res_map[(curr_root,val)] = int(best_bin,2) ^ val \n for child in adj_map[curr_root]:\n bin_rep = format(child, '020b')\n for i in range(1, len(bin_rep)+1):\n prefix_map[bin_rep[0:i]].add(child)\n helperDFS(child, prefix_map)\n for i in range(1, len(bin_rep)+1):\n prefix_map[bin_rep[0:i]].remove(child)\n\n initial_prefixmap = collections.defaultdict(set)\n root_rep = format(root, '020b')\n for i in range(1,21):\n initial_prefixmap[root_rep[0:i]].add(root)\n helperDFS(root, initial_prefixmap)\n res = []\n for q in queries:\n res.append(self.res_map[(q[0],q[1])])\n return res\n \n", + "title": "1938. Maximum Genetic Difference Query", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n . Return the maximum number of people who can be good based on the statements made by the n people . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The good person : The person who always tells the truth.", + "The bad person : The person who might tell the truth and might lie." + ], + "examples": [ + { + "text": "Example 1: Input:statements = [[2,1,2],[1,2,2],[2,0,2]]Output:2Explanation:Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n - Based on the statement made by person 2, person 1 is a bad person.\n - Now we know for sure that person 1 is bad and person 2 is good.\n - Based on the statement made by person 1, and since person 1 is bad, they could be:\n - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n - lying. In this case, person 0 is also a bad person and lied in their statement.\n -Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n - Based on the statement made by person 2, and since person 2 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n -Following that person 2 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Since person 1 is a good person, person 0 is also a good person.\n -Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic1.jpg" + }, + { + "text": "Example 2: Input:statements = [[2,0],[0,2]]Output:1Explanation:Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n - Based on the statement made by person 0, person 1 is a bad person and was lying.\n -Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n - Based on the statement made by person 0, and since person 0 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad.\n -Following that person 0 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n -Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.48%) | Memory: 42.5 MB (Top 63.64%)\nclass Solution {\n public int maximumGood(int[][] statements) {\n int[] result = { 0 };\n maximumGood(statements, new boolean[statements.length], 0, 0, result);\n return result[0];\n }\n\n /*\n This function uses backtracking to do the DFS. We are basically constructing all possible scenarios and verifying them.\n\n statements (int[][]): This is the input statements.\n goodPeople (boolean[]): This array tells who are good and bad in the group.\n currentPerson (int): This is the current person that we are verifying.\n currentGoodPeople (int): This is the number of the good people identified so far.\n result (int[]): This array holds the result, the total number of good people.\n */\n private void maximumGood(int[][] statements, boolean[] goodPeople, int currentPerson, int currentGoodPeople, int[] result) {\n if (currentPerson == goodPeople.length) {\n result[0] = Math.max(result[0], currentGoodPeople);\n return;\n }\n\n // Now we are going to use backtracking to do DFS.\n\n // Scenario 1: Assume the current person is good and verify it.\n goodPeople[currentPerson] = true;\n // Prune the tree if the sum of unverified people (goodPeople.length - currentPerson) and verifyied good people (currentGoodPeople) is less than the result.\n if (goodPeople.length - currentPerson + currentGoodPeople < result[0]) {\n return;\n }\n if (isValid(statements, goodPeople, currentPerson)) {\n maximumGood(statements, goodPeople, currentPerson + 1, currentGoodPeople + 1, result);\n }\n\n // Scenario 2: Assume the current person is bad and verify it.\n goodPeople[currentPerson] = false;\n // Prune the tree for the same reason mentioned earlier.\n if (goodPeople.length - currentPerson - 1 + currentGoodPeople < result[0]) {\n return;\n }\n if (isValid(statements, goodPeople, currentPerson)) {\n maximumGood(statements, goodPeople, currentPerson + 1, currentGoodPeople, result);\n }\n\n return;\n }\n\n private boolean isValid(int[][] statements, boolean[] goodPeople, int currentPerson) {\n // To verify if the current assumption of good/bad people is correct, we need to do 2 things.\n // 1. We need to verify the statements from all processed good people. What they said about the current person should be correct.\n for (int i = 0; i < currentPerson; ++i) {\n if (goodPeople[i]) {\n if (goodPeople[currentPerson] && statements[i][currentPerson] == 0) {\n return false;\n }\n if (!goodPeople[currentPerson] && statements[i][currentPerson] == 1) {\n return false;\n }\n }\n }\n\n // 2. We need to verify the statement from the current person if he is good. What he said about other people should be correct.\n if (goodPeople[currentPerson]) {\n for (int i = 0; i < currentPerson; ++i) {\n if (goodPeople[i] && statements[currentPerson][i] == 0) return false;\n if (!goodPeople[i] && statements[currentPerson][i] == 1) return false;\n }\n }\n\n return true;\n }\n}", + "title": "2151. Maximum Good People Based on Statements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n . Return the maximum number of people who can be good based on the statements made by the n people . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The good person : The person who always tells the truth.", + "The bad person : The person who might tell the truth and might lie." + ], + "examples": [ + { + "text": "Example 1: Input:statements = [[2,1,2],[1,2,2],[2,0,2]]Output:2Explanation:Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n - Based on the statement made by person 2, person 1 is a bad person.\n - Now we know for sure that person 1 is bad and person 2 is good.\n - Based on the statement made by person 1, and since person 1 is bad, they could be:\n - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n - lying. In this case, person 0 is also a bad person and lied in their statement.\n -Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n - Based on the statement made by person 2, and since person 2 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n -Following that person 2 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Since person 1 is a good person, person 0 is also a good person.\n -Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic1.jpg" + }, + { + "text": "Example 2: Input:statements = [[2,0],[0,2]]Output:1Explanation:Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n - Based on the statement made by person 0, person 1 is a bad person and was lying.\n -Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n - Based on the statement made by person 0, and since person 0 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad.\n -Following that person 0 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n -Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.", + "image": "https://assets.leetcode.com/uploads/2022/01/15/logic2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumGood(self, S):\n n, ans = len(S), 0\n def valid(cur):\n for i in range(n):\n if cur[i]:\n for j in range(n):\n if S[i][j] != 2 and S[i][j] != cur[j]: return False\n return True;\n def dfs(cur, i, cnt):\n nonlocal ans\n if i == n:\n if valid(cur): ans = max(ans, cnt)\n return\n cur.append(0)\n dfs(cur, i+1, cnt)\n cur[-1] = 1\n dfs(cur, i+1, cnt+1)\n cur.pop()\n \n dfs([], 0, 0)\n return ans\n \n", + "title": "2151. Maximum Good People Based on Statements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given n cuboids where the dimensions of the i th cuboid is cuboids[i] = [width i , length i , height i ] ( 0-indexed ). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if width i <= width j and length i <= length j and height i <= height j . You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/21/image.jpg" + ], + "constraints": [ + "n == cuboids.length", + "1 <= n <= 100", + "1 <= width i , length i , height i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cuboids = [[50,45,20],[95,37,53],[45,23,12]]Output:190Explanation:Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.", + "image": null + }, + { + "text": "Example 2: Input:cuboids = [[38,25,45],[76,35,3]]Output:76Explanation:You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.", + "image": null + }, + { + "text": "Example 3: Input:cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]Output:102Explanation:After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 37.8%) | Memory: 41.26 MB (Top 83.6%)\n\nclass Solution {\n public int maxHeight(int[][] cuboids) {\n // Sorting all Dimensions\n for(int[] arr : cuboids) Arrays.sort(arr);\n\n // sort all cuboids on basis of height, if same then breadth,\n // if same then length\n Arrays.sort(cuboids, (a, b) -> (b[2] - a[2] == 0 ? (b[1] - a[1] == 0 ? b[0] - a[0] : b[1] - a[1]) : b[2] - a[2]));\n\n // use logic of LIS(Longest Increasing Subsequence)\n return helperTab(cuboids);\n\n }\n public int helperTab(int[][] nums){\n int n = nums.length;\n int[] currRow = new int[n + 1];\n int[] nextRow = new int[n + 1];\n\n for(int curr = n - 1; curr >= 0; curr--){\n for(int prev = curr - 1; prev >= -1; prev--){\n int take = 0;\n if(prev == -1 || check(nums[curr], nums[prev])) take = nums[curr][2] + nextRow[curr + 1];\n int notTake = 0 + nextRow[prev + 1];\n currRow[prev + 1] = Math.max(take, notTake);\n }\n nextRow = currRow;\n }\n return nextRow[0];\n }\n // These function checks whether current cuboid can be placed above \n //the below one or not, on the basis on condition given in question.\n public boolean check(int[] a, int[] b){\n if(a[0] <= b[0] && a[1] <= b[1] && a[2] <= b[2]) return true;\n else return false;\n }\n}", + "title": "1691. Maximum Height by Stacking Cuboids", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given n cuboids where the dimensions of the i th cuboid is cuboids[i] = [width i , length i , height i ] ( 0-indexed ). Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if width i <= width j and length i <= length j and height i <= height j . You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid. Return the maximum height of the stacked cuboids . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/21/image.jpg" + ], + "constraints": [ + "n == cuboids.length", + "1 <= n <= 100", + "1 <= width i , length i , height i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cuboids = [[50,45,20],[95,37,53],[45,23,12]]Output:190Explanation:Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.", + "image": null + }, + { + "text": "Example 2: Input:cuboids = [[38,25,45],[76,35,3]]Output:76Explanation:You can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.", + "image": null + }, + { + "text": "Example 3: Input:cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]Output:102Explanation:After rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 199 ms (Top 36.11%) | Memory: 13.8 MB (Top 87.22%)\n\nclass Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n dp=[0]*len(cuboids)\n max_value=0\n for i in range(len(cuboids)):\n cuboids[i].sort()\n cuboids.sort()\n for i in range(len(cuboids)):\n dp[i]=cuboids[i][2]\n for j in range(i):\n if cuboids[i][0]>=cuboids[j][0] and cuboids[i][1]>=cuboids[j][1] and cuboids[i][2]>=cuboids[j][2]:\n dp[i]=max(dp[i],dp[j]+cuboids[i][2])\n if dp[i]>max_value:\n max_value=dp[i]\n return max_value", + "title": "1691. Maximum Height by Stacking Cuboids", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n , where costs[i] is the price of the i th ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "costs.length == n", + "1 <= n <= 10^5", + "1 <= costs[i] <= 10^5", + "1 <= coins <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [1,3,2,4,1], coins = 7Output:4Explanation:The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.", + "image": null + }, + { + "text": "Example 2: Input:costs = [10,6,8,7,7,8], coins = 5Output:0Explanation:The boy cannot afford any of the ice cream bars.", + "image": null + }, + { + "text": "Example 3: Input:costs = [1,6,3,1,2,5], coins = 20Output:6Explanation:The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 62.29%) | Memory: 74.7 MB (Top 66.20%)\nclass Solution {\n public int maxIceCream(int[] costs, int coins) {\n\n //Greedy Approach\n //a. sort cost in increasing order\n\n Arrays.sort(costs);\n\n int count = 0;\n for(int cost : costs){\n\n //b. check remainig coin is greater or equal than cuurent ice - cream cost\n if(coins - cost >= 0) {\n coins -= cost;\n count++;\n }\n }\n\n return count;\n }\n}", + "title": "1833. Maximum Ice Cream Bars", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n , where costs[i] is the price of the i th ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "costs.length == n", + "1 <= n <= 10^5", + "1 <= costs[i] <= 10^5", + "1 <= coins <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [1,3,2,4,1], coins = 7Output:4Explanation:The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.", + "image": null + }, + { + "text": "Example 2: Input:costs = [10,6,8,7,7,8], coins = 5Output:0Explanation:The boy cannot afford any of the ice cream bars.", + "image": null + }, + { + "text": "Example 3: Input:costs = [1,6,3,1,2,5], coins = 20Output:6Explanation:The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n costs.sort()\n i= 0\n for price in costs:\n if price<= coins:\n i+= 1\n coins-= price\n else:\n break\n return i", + "title": "1833. Maximum Ice Cream Bars", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings arr . A string s is formed by the concatenation of a subsequence of arr that has unique characters . Return the maximum possible length of s . A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 16", + "1 <= arr[i].length <= 26", + "arr[i] contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [\"un\",\"iq\",\"ue\"]Output:4Explanation:All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [\"cha\",\"r\",\"act\",\"ers\"]Output:6Explanation:Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").", + "image": null + }, + { + "text": "Example 3: Input:arr = [\"abcdefghijklmnopqrstuvwxyz\"]Output:26Explanation:The only string in arr has all 26 characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 61.57%) | Memory: 49.1 MB (Top 67.72%)\nclass Solution {\n public int maxLength(List arr) {\n String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);\n int[] dp = new int[1< int:\n ans = 0\n count = [0]*26\n counts = []\n new_arr = []\n\n for string in arr:\n flag = True\n tmp = [0]*26\n for ch in string:\n if tmp[ord(ch) - 97] == True:\n flag = False\n break\n else:\n tmp[ord(ch) - 97] = True\n\n if flag == False:continue\n counts.append(tmp)\n new_arr.append(string)\n\n n = len(new_arr)\n\n def compatible(a,b):\n for i in range(26):\n if a[i] == True and b[i] == True: return False\n return True\n\n def addUp(a,b):\n for i in range(26):\n if b[i] == True: a[i] = True\n\n def solve(index,count):\n if index == n:return 0\n cpy = count.copy()\n ch1 = -inf\n if compatible(count,counts[index]):\n addUp(count,counts[index])\n ch1 = solve(index+1,count) + len(new_arr[index])\n ch2 = solve(index+1 , cpy)\n ans = max(ch1,ch2)\n return ans\n\n return solve(0,count)", + "title": "1239. Maximum Length of a Concatenated String with Unique Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of n pairs pairs where pairs[i] = [left i , right i ] and left i < right i . A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c . A chain of pairs can be formed in this fashion. Return the length longest chain which can be formed . You do not need to use up all the given intervals. You can select pairs in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == pairs.length", + "1 <= n <= 1000", + "-1000 <= left i < right i <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3],[3,4]]Output:2Explanation:The longest chain is [1,2] -> [3,4].", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,2],[7,8],[4,5]]Output:3Explanation:The longest chain is [1,2] -> [4,5] -> [7,8].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n int findLongestChain(vector>& arr) {\n \n if(arr.size()==1)\n {\n return 1;\n }\n vector>v;\n for(int i=0;idp(v.size(),0);\n int ans=INT_MIN; \n dp[0]=1;\n for(int i=1;i=0;j--)\n {\n if(v[j].second=0;i--){\n for(int j = m-1 ;j>=0;j--){\n if(nums1[i]==nums2[j]){\n dp[i][j] = dp[i+1][j+1]+1;\n if(ans int:\n dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)]\n max_len = 0\n for row in range(len(nums2)):\n for col in range(len(nums1)):\n if nums2[row] == nums1[col]:\n dp[row][col] = 1 + dp[row - 1][col - 1]\n max_len = max(max_len,dp[row][col])\n else:\n dp[row][col] = 0\n return max_len\n \n", + "title": "718. Maximum Length of Repeated Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,-3,4]Output:4Explanation:The array nums already has a positive product of 24.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,-2,-3,-4]Output:3Explanation:The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3,0,1]Output:2Explanation:The longest subarray with positive product is [-1,-2] or [-2,-3].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 27.34%) | Memory: 84.2 MB (Top 12.92%)\nclass Solution {\n public int getMaxLen(int[] nums)\n {\n int first_negative=-1;\n int zero_position=-1;\n int count_neg=0;\n int res=0;\n for(int i=0;i int:\n n=len(arr)\n def solve(nums):\n i,j,last_neg,neg,ans=0,0,None,0,0\n while j map = new HashMap<>();\n\n public void go(TreeNode root, int level) {\n if(root == null) return;\n if(map.containsKey(level)) {\n map.put(level, map.get(level) + root.val);\n }\n else {\n map.put(level, root.val);\n }\n\n go(root.left, level+1);\n go(root.right, level+1);\n }\n public int maxLevelSum(TreeNode root) {\n go(root, 0);\n int max = Integer.MIN_VALUE, ind = -1;\n for (var i : map.entrySet()) {\n if(max < i.getValue()) {\n max = i.getValue();\n ind = i.getKey();\n }\n }\n return ind+1;\n }\n}", + "title": "1161. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, the level of its root is 1 , the level of its children is 2 , and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,7,0,7,-8,null,null]Output:2Explanation:Level 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" + }, + { + "text": "Example 2: Input:root = [989,null,10250,98693,-89388,null,null,null,-32127]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n global_max = float('-inf')\n res = -1\n q = deque([root])\n lvl = 1\n while q:\n total = 0\n for _ in range(len(q)):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n total+=node.val\n if total>global_max:\n res = lvl\n global_max = total\n lvl+=1\n return res\n", + "title": "1161. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix . You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border . Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose any two adjacent elements of matrix and multiply each of them by -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,-1],[-1,1]]Output:4Explanation:We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]Output:16Explanation:We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxMatrixSum(int[][] matrix) {\n long ans = 0;\n int neg = 0;\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] < 0) {\n neg++;\n }\n ans += Math.abs(matrix[i][j]);\n if(min > Math.abs(matrix[i][j]))\n \tmin = Math.abs(matrix[i][j]);\n }\n }\n if(neg % 2 == 0)\n \treturn ans;\n else\n \treturn ans - 2*min;\n }\n}\n", + "title": "1975. Maximum Matrix Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n integer matrix . You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border . Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose any two adjacent elements of matrix and multiply each of them by -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,-1],[-1,1]]Output:4Explanation:We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]Output:16Explanation:We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.", + "image": "https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n # count -'s\n count = 0\n for row in matrix:\n for col_num in row:\n if col_num < 0:\n count += 1\n tot_sum = sum([sum([abs(x) for x in row])\n for row in matrix])\n if count % 2 == 0:\n return tot_sum\n else:\n min_val = min([min([abs(x) for x in row])\n for row in matrix])\n return tot_sum - 2 * min_val\n", + "title": "1975. Maximum Matrix Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A string is a valid parentheses string (denoted VPS ) if it meets one of the following: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS 's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS 's. Given a VPS represented as string s , return the nesting depth of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is an empty string \"\" , or a single character not equal to \"(\" or \")\" ,", + "It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or", + "It can be written as (A) , where A is a VPS ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(1+(2*3)+((8)/4))+1\"Output:3Explanation:Digit 8 is inside of 3 nested parentheses in the string.", + "image": null + }, + { + "text": "Example 2: Input:s = \"(1)+((2))+(((3)))\"Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxDepth(String s) {\n int count = 0; //count current dept of \"()\"\n int max = 0; //count max dept of \"()\"\n\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == '(') {\n count++;\n } else if (s.charAt(i) == ')') {\n count--;\n }\n max = Math.max(count, max);\n }\n return max;\n }\n}\n", + "title": "1614. Maximum Nesting Depth of the Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A string is a valid parentheses string (denoted VPS ) if it meets one of the following: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS 's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS 's. Given a VPS represented as string s , return the nesting depth of s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is an empty string \"\" , or a single character not equal to \"(\" or \")\" ,", + "It can be written as AB ( A concatenated with B ), where A and B are VPS 's, or", + "It can be written as (A) , where A is a VPS ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(1+(2*3)+((8)/4))+1\"Output:3Explanation:Digit 8 is inside of 3 nested parentheses in the string.", + "image": null + }, + { + "text": "Example 2: Input:s = \"(1)+((2))+(((3)))\"Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxDepth(self, s: str) -> int:\n ans = cur = 0\n for c in s:\n if c == '(':\n cur += 1\n ans = max(ans, cur)\n elif c == ')':\n cur -= 1\n return ans \n", + "title": "1614. Maximum Nesting Depth of the Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and: We can similarly define the nesting depth depth(S) of any VPS S as follows: For example, \"\" , \"()()\" , and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's. Given a VPS seq , split it into two disjoint subsequences A and B , such that A and B are VPS's (and A.length + B.length = seq.length ). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length ) that encodes such a choice of A and B : answer[i] = 0 if seq[i] is part of A , else answer[i] = 1 .  Note that even though multiple answers may exist, you may return any of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB ( A concatenated with B ), where A and B are VPS's, or", + "It can be written as (A) , where A is a VPS." + ], + "examples": [ + { + "text": "Example 1: Input:seq = \"(()())\"Output:[0,1,1,1,1,0]", + "image": null + }, + { + "text": "Example 2: Input:seq = \"()(())()\"Output:[0,0,0,1,1,0,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxDepthAfterSplit(String seq) {\n int[] res = new int[seq.length()];\n for(int i=0; i List[int]:\n ans = []\n last = 1\n for i in seq:\n if i == '(':\n if last == 0: ans.append(1)\n else:ans.append(0)\n else:\n ans.append(last)\n last = (last + 1) % 2\n return ans\n", + "title": "1111. Maximum Nesting Depth of Two Valid Parentheses Strings", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a m x n matrix grid . Initially, you are located at the top-left corner (0, 0) , and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1) , find the path with the maximum non-negative product . The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7 . If the maximum product is negative , return -1 . Notice that the modulo is performed after getting the maximum product. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 15", + "-4 <= grid[i][j] <= 4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]Output:-1Explanation:It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,-2,1],[1,-2,1],[3,-4,1]]Output:8Explanation:Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,3],[0,-4]]Output:0Explanation:Maximum non-negative product is shown (1 * 0 * -4 = 0).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 41.67%) | Memory: 43.3 MB (Top 29.76%)\nclass Solution {\n public class Pair{\n long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;\n Pair(){\n\n }\n Pair(long min,long max){\n this.min=min;\n this.max=max;\n }\n }\n public int maxProductPath(int[][] grid) {\n Pair[][] dp=new Pair[grid.length][grid[0].length];\n for(int r=grid.length-1;r>=0;r--){\n for(int c=grid[0].length-1;c>=0;c--){\n if(r==grid.length-1 && c==grid[0].length-1){\n dp[r][c]=new Pair(grid[r][c],grid[r][c]);\n }else{\n Pair hor=(c==grid[0].length-1)?new Pair():dp[r][c+1];\n Pair ver=(r==grid.length-1)?new Pair():dp[r+1][c];\n long min,max;\n if(grid[r][c]>=0){\n max=Math.max(hor.max,ver.max);\n min=Math.min(hor.min,ver.min);\n }else{\n min=Math.max(hor.max,ver.max);\n max=Math.min(hor.min,ver.min);\n }\n dp[r][c]=new Pair(min*grid[r][c],max*grid[r][c]);\n }\n }\n }\n int mod=(int)1e9 +7;\n return dp[0][0].max<0?-1:(int)(dp[0][0].max%mod);\n }\n}", + "title": "1594. Maximum Non Negative Product in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a m x n matrix grid . Initially, you are located at the top-left corner (0, 0) , and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1) , find the path with the maximum non-negative product . The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7 . If the maximum product is negative , return -1 . Notice that the modulo is performed after getting the maximum product. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 15", + "-4 <= grid[i][j] <= 4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]Output:-1Explanation:It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,-2,1],[1,-2,1],[3,-4,1]]Output:8Explanation:Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,3],[0,-4]]Output:0Explanation:Maximum non-negative product is shown (1 * 0 * -4 = 0).", + "image": "https://assets.leetcode.com/uploads/2021/12/23/product3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 63 ms (Top 56.0%) | Memory: 16.84 MB (Top 17.4%)\n\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n \"\"\"Return maximum & minimum products ending at (i, j).\"\"\"\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007", + "title": "1594. Maximum Non Negative Product in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "We have n buildings numbered from 0 to n - 1 . Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [from i , to i ] represents an employee's request to transfer from building from i to building to i . All buildings are full , so a list of requests is achievable only if for each building, the net change in employee transfers is zero . This means the number of employees leaving is equal to the number of employees moving in . For example if n = 3 and two employees are leaving building 0 , one is leaving building 1 , and one is leaving building 2 , there should be two employees moving to building 0 , one employee moving to building 1 , and one employee moving to building 2 . Return the maximum number of achievable requests . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= requests.length <= 16", + "requests[i].length == 2", + "0 <= from i , to i < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]Output:5Explantion:Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move1.jpg" + }, + { + "text": "Example 2: Input:n = 3, requests = [[0,0],[1,2],[2,1]]Output:3Explantion:Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move2.jpg" + }, + { + "text": "Example 3: Input:n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 65.52%) | Memory: 42.2 MB (Top 56.90%)\nclass Solution {\n int max = 0;\n public int maximumRequests(int n, int[][] requests) {\n helper(requests, 0, new int[n], 0);\n return max;\n }\n\n private void helper(int[][] requests, int index, int[] count, int num) {\n // Traverse all n buildings to see if they are all 0. (means balanced)\n if (index == requests.length) {\n for (int i : count) {\n if (0 != i) {\n return;\n }\n }\n max = Math.max(max, num);\n return;\n }\n // Choose this request\n count[requests[index][0]]++;\n count[requests[index][1]]--;\n helper(requests, index + 1, count, num + 1);\n count[requests[index][0]]--;\n count[requests[index][1]]++;\n\n // Not Choose the request\n helper(requests, index + 1, count, num);\n }\n}", + "title": "1601. Maximum Number of Achievable Transfer Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We have n buildings numbered from 0 to n - 1 . Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array requests where requests[i] = [from i , to i ] represents an employee's request to transfer from building from i to building to i . All buildings are full , so a list of requests is achievable only if for each building, the net change in employee transfers is zero . This means the number of employees leaving is equal to the number of employees moving in . For example if n = 3 and two employees are leaving building 0 , one is leaving building 1 , and one is leaving building 2 , there should be two employees moving to building 0 , one employee moving to building 1 , and one employee moving to building 2 . Return the maximum number of achievable requests . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= requests.length <= 16", + "requests[i].length == 2", + "0 <= from i , to i < n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]Output:5Explantion:Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move1.jpg" + }, + { + "text": "Example 2: Input:n = 3, requests = [[0,0],[1,2],[2,1]]Output:3Explantion:Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.", + "image": "https://assets.leetcode.com/uploads/2020/09/10/move2.jpg" + }, + { + "text": "Example 3: Input:n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4533 ms (Top 17.14%) | Memory: 13.9 MB (Top 48.57%)\nclass Solution:\n def maximumRequests(self, n: int, r: List[List[int]]) -> int:\n k=len(r)\n deg=[0 for i in range(n)]\n\n def check(i,res,s):\n if i==k:\n #print(deg,s)\n if max(deg)==min(deg)==0:\n res[0]=max(res[0],s)\n return\n\n u,v=r[i]\n deg[u]-=1\n deg[v]+=1\n check(i+1,res,s+1)\n deg[u]+=1\n deg[v]-=1\n check(i+1,res,s)\n res=[0]\n check(0,res,0)\n return res[0]\n", + "title": "1601. Maximum Number of Achievable Transfer Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string text , you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once . Return the maximum number of instances that can be formed. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex1_upd.JPG", + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex2_upd.JPG" + ], + "constraints": [ + "1 <= text.length <= 10^4", + "text consists of lower case English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"nlaebolko\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:text = \"loonbalxballpoon\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:text = \"leetcode\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 74.74%) | Memory: 42.3 MB (Top 69.99%)\nclass Solution {\n\n public int maxNumberOfBalloons(String text) {\n return maxNumberOfWords(text, \"balloon\");\n }\n\n private int maxNumberOfWords(String text, String word) {\n final int[] tFrequencies = new int[26];\n for (int i = 0; i < text.length(); ++i) {\n tFrequencies[text.charAt(i) - 'a']++;\n }\n final int[] wFrequencies = new int[26];\n for (int i = 0; i < word.length(); ++i) {\n wFrequencies[word.charAt(i) - 'a']++;\n }\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < 26; ++i) {\n if (wFrequencies[i] > 0) {\n final int count = (tFrequencies[i] / wFrequencies[i]);\n if (count < min) {\n min = count;\n }\n }\n }\n return min;\n }\n\n}", + "title": "1189. Maximum Number of Balloons", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string text , you want to use the characters of text to form as many instances of the word \"balloon\" as possible. You can use each character in text at most once . Return the maximum number of instances that can be formed. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex1_upd.JPG", + "https://assets.leetcode.com/uploads/2019/09/05/1536_ex2_upd.JPG" + ], + "constraints": [ + "1 <= text.length <= 10^4", + "text consists of lower case English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"nlaebolko\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:text = \"loonbalxballpoon\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:text = \"leetcode\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}\n \n for char in text:\n if not char in freq:\n continue\n \n step = 0.5 if char == 'l' or char == 'o' else 1\n \n freq[char] += step\n \n result = min(freq.values())\n \n return floor(result)", + "title": "1189. Maximum Number of Balloons", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1 ), and an infinite number of boxes numbered from 1 to infinity . Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1 . Given two integers lowLimit and highLimit , return the number of balls in the box with the most balls. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= lowLimit <= highLimit <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:lowLimit = 1, highLimit = 10Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.", + "image": null + }, + { + "text": "Example 2: Input:lowLimit = 5, highLimit = 15Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.", + "image": null + }, + { + "text": "Example 3: Input:lowLimit = 19, highLimit = 28Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 20.04%) | Memory: 49.5 MB (Top 50.90%)\nclass Solution {\n public int countBalls(int lowLimit, int highLimit) {\n Map map = new HashMap<>();\n int count = Integer.MIN_VALUE;\n for(int i = lowLimit;i<=highLimit;i++){\n int value = 0;\n int temp = i;\n while (temp!=0){\n value += temp%10;\n temp/=10;\n }\n map.put(value,map.getOrDefault(value,0)+1);\n count = map.get(value) > count ? map.get(value) : count;\n }\n return count;\n }\n}", + "title": "1742. Maximum Number of Balls in a Box", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1 ), and an infinite number of boxes numbered from 1 to infinity . Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1 . Given two integers lowLimit and highLimit , return the number of balls in the box with the most balls. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= lowLimit <= highLimit <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:lowLimit = 1, highLimit = 10Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.", + "image": null + }, + { + "text": "Example 2: Input:lowLimit = 5, highLimit = 15Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.", + "image": null + }, + { + "text": "Example 3: Input:lowLimit = 19, highLimit = 28Output:2Explanation:Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n boxes = [0] * 100\n \n for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number \"i\", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n boxes[sum([int(j) for j in str(i)])] += 1\n \n return max(boxes)", + "title": "1742. Maximum Number of Balls in a Box", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: Given an array of integers piles where piles[i] is the number of coins in the i th pile. Return the maximum number of coins that you can have. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "In each step, you will choose any 3 piles of coins (not necessarily consecutive).", + "Of your choice, Alice will pick the pile with the maximum number of coins.", + "You will pick the next pile with the maximum number of coins.", + "Your friend Bob will pick the last pile.", + "Repeat until there are no more piles of coins." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [2,4,1,2,7,8]Output:9Explanation:Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with7coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with2coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1,2, 8), (2,4, 7) you only get 2 + 4 = 6 coins which is not optimal.", + "image": null + }, + { + "text": "Example 2: Input:piles = [2,4,5]Output:4", + "image": null + }, + { + "text": "Example 3: Input:piles = [9,8,7,6,5,1,2,3,4]Output:18", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 37.50%) | Memory: 77.8 MB (Top 8.89%)\nclass Solution {\n public int maxCoins(int[] piles) {\n Arrays.sort(piles);\n int s=0,n=piles.length;\n for(int i=n/3;i int:\n piles.sort()\n n = len(piles)\n k = n // 3\n i, j = 0, 2\n ans = 0\n while i < k:\n ans += piles[n-j]\n j += 2\n i +=1\n return ans", + "title": "1561. Maximum Number of Coins You Can Get", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the i th coin is coins[i] . You can make some value x if you can choose some of your n coins such that their values sum up to x . Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0 . Note that you may have multiple coins of the same value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "coins.length == n", + "1 <= n <= 4 * 10^4", + "1 <= coins[i] <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,3]Output:2Explanation:You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 2: Input:coins = [1,1,1,4]Output:8Explanation:You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,10,3,1]Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getMaximumConsecutive(int[] coins) {\n if(coins.length==0 && coins==null)\n return 0;\n TreeMap map=new TreeMap();\n for(int i:coins)\n map.put(i,map.getOrDefault(i,0)+1);\n int range=0;\n for(int i:map.keySet()){\n if(range==0 && i==1)\n range=i*map.get(i);\n else if(range!=0 && range+1>=i)\n range+=i*map.get(i);\n else \n break;\n }\n return range+1;\n }\n}\n", + "title": "1798. Maximum Number of Consecutive Values You Can Make", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array coins of length n which represents the n coins that you own. The value of the i th coin is coins[i] . You can make some value x if you can choose some of your n coins such that their values sum up to x . Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0 . Note that you may have multiple coins of the same value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "coins.length == n", + "1 <= n <= 4 * 10^4", + "1 <= coins[i] <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,3]Output:2Explanation:You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 2: Input:coins = [1,1,1,4]Output:8Explanation:You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,10,3,1]Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 576 ms (Top 97.83%) | Memory: 23.00 MB (Top 5.22%)\n\nclass Solution:\n def getMaximumConsecutive(self, coins: List[int]) -> int:\n cur_max = 0\n coins.sort()\n \n for coin in coins:\n if coin == 1:\n cur_max += 1\n elif coin <= cur_max+1:\n cur_max += coin\n else: #coin > cur_max + 1\n break\n \n return cur_max+1\n", + "title": "1798. Maximum Number of Consecutive Values You Can Make", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [x i , y i ] is the position of the i th dart that Alice threw on the wall. Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lies on the dartboard. Given the integer r , return the maximum number of darts that can lie on the dartboard . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= darts.length <= 100", + "darts[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "1 <= r <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2Output:4Explanation:Circle dartboard with center in (0,0) and radius = 2 contain all points.", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_1_1806.png" + }, + { + "text": "Example 2: Input:darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5Output:5Explanation:Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).", + "image": "https://assets.leetcode.com/uploads/2020/04/29/sample_2_1806.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 275 ms (Top 78.13%) | Memory: 14.5 MB (Top 9.38%)\nclass Solution:\n def numPoints(self, points: List[List[int]], r: int) -> int:\n\n def getPointsInside(i, r, n):\n # This vector stores alpha and beta and flag\n # is marked true for alpha and false for beta\n angles = []\n\n for j in range(n):\n\n if i != j and distance[i][j] <= 2 * r:\n # acos returns the arc cosine of the complex\n # used for cosine inverse\n B = math.acos(distance[i][j] / (2 * r))\n\n # arg returns the phase angle of the complex\n x1, y1 = points[i]\n x2, y2 = points[j]\n\n A = math.atan2(y1 - y2, x1 - x2)\n\n alpha = A - B\n\n beta = A + B\n\n angles.append((alpha, False))\n\n angles.append((beta, True))\n\n # angles vector is sorted and traversed\n angles.sort()\n # count maintains the number of points inside\n # the circle at certain value of theta\n # res maintains the maximum of all count\n cnt, res = 1, 1\n for angle in angles:\n # entry angle\n if angle[1] == False:\n cnt += 1\n # exit angle\n else:\n cnt -= 1\n\n res = max(cnt, res)\n\n return res\n\n # Returns count of maximum points that can lie\n # in a circle of radius r.\n #a dis array stores the distance between every\n # pair of points\n n = len(points)\n max_pts = n\n distance = [[0 for _ in range(max_pts)] for _ in range(max_pts)]\n for i in range(n - 1):\n for j in range(i + 1, n):\n # abs gives the magnitude of the complex\n # number and hence the distance between\n # i and j\n x1, y1 = points[i]\n x2, y2 = points[j]\n distance[i][j] = distance[j][i] = sqrt((x1 - x2)**2 + (y1 - y2)**2)\n\n # This loop picks a point p\n ans = 0\n # maximum number of points for point arr[i]\n for i in range(n):\n ans = max(ans, getPointsInside(i, r, n))\n\n return ans", + "title": "1453. Maximum Number of Darts Inside of a Circular Dartboard", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a special kind of apple tree that grows apples every day for n days. On the i th day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0 . You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n , return the maximum number of apples you can eat. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == apples.length == days.length", + "1 <= n <= 2 * 10^4", + "0 <= apples[i], days[i] <= 2 * 10^4", + "days[i] = 0 if and only if apples[i] = 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:apples = [1,2,3,5,2], days = [3,2,1,4,2]Output:7Explanation:You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.", + "image": null + }, + { + "text": "Example 2: Input:apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]Output:5Explanation:You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 95.27%) | Memory: 45.90 MB (Top 56.76%)\n\nclass Solution {\n class Basket{\n int appleCount;\n int day;\n Basket(int appleCount, int day){\n this.appleCount = appleCount;\n this.day = day;\n }\n }\n public int eatenApples(int[] apples, int[] days) {\n int n = apples.length;\n PriorityQueue q = new PriorityQueue<>(n,(b1,b2) -> b1.day-b2.day);\n int i; // counter for day \n\t\tint apple = 0; // count of consumed apple\n \n for(i=0; i 0:\n cnt, apple = heapq.heappop(heap)\n if apple > 0 and cnt > day :\n rtn +=1\n day +=1\n if apple > 1 and cnt > day:\n heapq.heappush(heap, (cnt, apple-1))\n if day < len(days) and apples[day] > 0 :\n heapq.heappush(heap, (day +days[day], apples[day]))\n return rtn ", + "title": "1705. Maximum Number of Eaten Apples", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of events where events[i] = [startDay i , endDay i ] . Every event i starts at startDay i and ends at endDay i . You can attend an event i at any day d where startTime i <= d <= endTime i . You can only attend one event at any time d . Return the maximum number of events you can attend . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= events.length <= 10^5", + "events[i].length == 2", + "1 <= startDay i <= endDay i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2],[2,3],[3,4]]Output:3Explanation:You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/05/e1.png" + }, + { + "text": "Example 2: Input:events= [[1,2],[2,3],[3,4],[1,2]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "\n\nclass Solution {\n public int maxEvents(int[][] events) {\n Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]);\n // here sorting the array on ths basis of last day because we want to finish the events which happens first,fist.\n \n TreeSet set =new TreeSet<>();\n for(int i =1;i<=100000;i++){\n set.add(i);\n }\n //initliasing a tree set to check available days ;\n // a day can go maximum to 100000;\n int ans =0;\n for(int i =0;ievents[i][1])\n continue;\n else{\n set.remove(temp);\n ans +=1;\n }\n }\n return ans; \n }\n}\n", + "title": "1353. Maximum Number of Events That Can Be Attended", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of events where events[i] = [startDay i , endDay i ] . Every event i starts at startDay i and ends at endDay i . You can attend an event i at any day d where startTime i <= d <= endTime i . You can only attend one event at any time d . Return the maximum number of events you can attend . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= events.length <= 10^5", + "events[i].length == 2", + "1 <= startDay i <= endDay i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2],[2,3],[3,4]]Output:3Explanation:You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/05/e1.png" + }, + { + "text": "Example 2: Input:events= [[1,2],[2,3],[3,4],[1,2]]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1160 ms (Top 93.22%) | Memory: 61.6 MB (Top 51.45%)\nclass Solution(object):\n def maxEvents(self, events):\n \"\"\"\n :type events: List[List[int]]\n :rtype: int\n \"\"\"\n events = sorted(events, key=lambda x: x[0])\n current_day = 0\n min_heap = []\n event_id = 0\n total_number_of_days = max(end for start, end in events)\n total_events_attended = 0\n #total_number_of_days+1 because I want to include the last day\n for day in range(1, total_number_of_days+1):\n\n #Add all the events that can be started on that day\n while event_id < len(events) and events[event_id][0] == day:\n heapq.heappush(min_heap, events[event_id][1])\n event_id+=1\n\n #while there is something in heap and the event should have been completed before the current day\n #remove those evenets and consider them not attended\n while min_heap and min_heap[0] < day :\n heapq.heappop(min_heap)\n\n #if theere is an event present in heap\n #lets mark 1 of those events as complted today and add it to\n #total_events_attended\n\n if min_heap:\n heapq.heappop(min_heap)\n total_events_attended+=1\n return total_events_attended\n", + "title": "1353. Maximum Number of Events That Can Be Attended", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of events where events[i] = [startDay i , endDay i , value i ] . The i th event starts at startDay i and ends at endDay i , and if you attend this event, you will receive a value of value i . You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive : that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png" + ], + "constraints": [ + "1 <= k <= events.length", + "1 <= k * events.length <= 10^6", + "1 <= startDay i <= endDay i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2,4],[3,4,3],[2,3,1]], k = 2Output:7Explanation:Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:events = [[1,2,4],[3,4,3],[2,3,10]], k = 2Output:10Explanation:Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you donothave to attend k events.", + "image": null + }, + { + "text": "Example 3: Input:events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3Output:9Explanation:Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 99 ms (Top 53.72%) | Memory: 100.9 MB (Top 52.07%)\nclass Solution {\n public int maxValue(int[][] events, int k) {\n Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0]));\n return maxValue(events, 0, k, 0, new int[k+1][events.length]);\n }\n\n private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEndDay, int[][] dp) {\n // Return 0 if no events are left or maximum choice is reached\n if (index >= events.length || remainingEvents == 0)\n return 0;\n\n // An Event cannot be picked if the previous event has not completed before current event\n if (lastEventEndDay >= events[index][0])\n return maxValue(events, index+1, remainingEvents, lastEventEndDay, dp);\n\n // Return the value if the solution is already available\n if (dp[remainingEvents][index] != 0)\n return dp[remainingEvents][index];\n\n // There are 2 choices that we can make,\n // SKIP this meeting or PICK this meeting\n return dp[remainingEvents][index] = Math.max(\n maxValue(events, index+1, remainingEvents, lastEventEndDay, dp), // skip\n maxValue(events, index+1, remainingEvents-1, events[index][1], dp) + events[index][2] // pick\n );\n }\n}", + "title": "1751. Maximum Number of Events That Can Be Attended II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of events where events[i] = [startDay i , endDay i , value i ] . The i th event starts at startDay i and ends at endDay i , and if you attend this event, you will receive a value of value i . You are also given an integer k which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive : that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png" + ], + "constraints": [ + "1 <= k <= events.length", + "1 <= k * events.length <= 10^6", + "1 <= startDay i <= endDay i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,2,4],[3,4,3],[2,3,1]], k = 2Output:7Explanation:Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:events = [[1,2,4],[3,4,3],[2,3,10]], k = 2Output:10Explanation:Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you donothave to attend k events.", + "image": null + }, + { + "text": "Example 3: Input:events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3Output:9Explanation:Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nfrom functools import lru_cache\n\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n if k == 1: # optimization for TLE test case 57/67\n return max([event[2] for event in events])\n \n events.sort()\n event_starts = [event[0] for event in events] # enables binary search\n \n @lru_cache(None)\n def dp(i, j):\n if j == 0: # out of turns\n return 0\n if i >= len(events): # end of events array\n return 0\n max_score = events[i][2]\n \n # get minimum index where start day is greater than current end day\n next_index_minimum = bisect.bisect_left(event_starts, events[i][1] + 1)\n \n # check each possibility from the minimum next index until end of the array\n for k in range(next_index_minimum, len(events)):\n max_score = max(max_score, events[i][2] + dp(k, j - 1))\n \n # check if we can get a better score if we skip this index altogether\n max_score = max(max_score, dp(i + 1, j))\n return max_score\n return dp(0, k)\n", + "title": "1751. Maximum Number of Events That Can Be Attended II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: Return the maximum number of groups that can be formed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The sum of the grades of students in the i th group is less than the sum of the grades of students in the (i + 1) th group, for all groups (except the last).", + "The total number of students in the i th group is less than the total number of students in the (i + 1) th group, for all groups (except the last)." + ], + "examples": [ + { + "text": "Example 1: Input:grades = [10,6,12,7,3,5]Output:3Explanation:The following is a possible way to form 3 groups of students:\n- 1stgroup has the students with grades = [12]. Sum of grades: 12. Student count: 1\n- 2ndgroup has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2\n- 3rdgroup has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3\nIt can be shown that it is not possible to form more than 3 groups.", + "image": null + }, + { + "text": "Example 2: Input:grades = [8,8]Output:1Explanation:We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 58.70 MB (Top 6.47%)\n\nclass Solution {\n public int maximumGroups(int[] grades) {\n int len = grades.length;\n int groups = (int)(-1 + Math.sqrt(1 + 8*len))/2;\n return groups;\n }\n}", + "title": "2358. Maximum Number of Groups Entering a Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a donuts shop that bakes donuts in batches of batchSize . They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups , where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= batchSize <= 9", + "1 <= groups.length <= 30", + "1 <= groups[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:batchSize = 3, groups = [1,2,3,4,5,6]Output:4Explanation:You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6thgroups will be happy.", + "image": null + }, + { + "text": "Example 2: Input:batchSize = 4, groups = [1,3,2,5,2,2,1,6]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 209 ms (Top 60.0%) | Memory: 21.90 MB (Top 65.0%)\n\nclass Solution:\n def maxHappyGroups(self, B, groups):\n ans = sum(g%B == 0 for g in groups)\n groups = [g for g in groups if g%B != 0]\n\n pos = [0]*B\n for g in groups: pos[g%B] += 1\n\n for i in range(1, B):\n t = min(pos[i], pos[B-i]) if 2*i != B else pos[i]//2\n ans += t\n pos[i] -= t\n pos[B-i] -= t\n \n if sum(pos) == 0: return ans\n\n @lru_cache(None)\n def dfs(position, last):\n if sum(position) == 0: return 0\n\n ans = float(\"-inf\")\n for i in range(B):\n if position[i] > 0:\n t = [j for j in position]\n t[i] -= 1\n U = (last - i) % B\n ans = max(ans, dfs(tuple(t), U) + (U == 0))\n \n return ans\n\n return max(dfs(tuple(pos), i) for i in range(1, B)) + ans\n", + "title": "1815. Maximum Number of Groups Getting Fresh Donuts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums and an integer target , return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "0 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 2Output:2Explanation:There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,3,5,1,4,2,-9], target = 6Output:2Explanation:There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxNonOverlapping(int[] nums, int target) {\n Map valToPos = new HashMap<>();\n int sums = 0;\n int count = 0;\n int lastEndPos = 0;\n valToPos.put(0, 0);\n for (int i = 0; i < nums.length; i++) {\n sums += nums[i];\n int pos = valToPos.getOrDefault(sums - target, -1);\n if (pos >= lastEndPos) {\n count += 1;\n lastEndPos = i + 1;\n }\n valToPos.put(sums, i + 1);\n }\n return count;\n }\n}\n", + "title": "1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums and an integer target , return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "0 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 2Output:2Explanation:There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,3,5,1,4,2,-9], target = 6Output:2Explanation:There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "'''\ngreedy, prefix sum with hashtable\nO(n), O(n)\n'''\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n # hash set to record previously encountered prefix sums\n prefix_sums = {0}\n \n res = prefix_sum = 0\n for num in nums:\n prefix_sum += num\n if prefix_sum - target in prefix_sums:\n res += 1\n # greedily discard prefix sums before num\n # thus not considering subarrays that start at before num \n prefix_sums = {prefix_sum} \n else:\n prefix_sums.add(prefix_sum)\n return res\n", + "title": "1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: Find the maximum number of substrings that meet the above conditions . If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"adefaddaccc\"Output:[\"e\",\"f\",\"ccc\"]Explanation:The following are all the possible substrings that meet the conditions:\n[\n  \"adefaddaccc\"\n  \"adefadda\",\n  \"ef\",\n  \"e\",\n \"f\",\n  \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbaccd\"Output:[\"d\",\"bb\",\"cc\"]Explanation:Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 132 ms (Top 24.51%) | Memory: 55.2 MB (Top 53.55%)\nclass Solution {\n public List maxNumOfSubstrings(String s) {\n int n = s.length();\n int[] R = new int[26];\n int[] L = new int[26];\n Arrays.fill(R, -1);\n Arrays.fill(L, -1);\n BitSet[] bit = new BitSet[26];\n Arrays.setAll(bit, o -> new BitSet());\n for (int i = 0; i < n; i++){\n R[s.charAt(i)-'a']=i; // last character index position\n }\n for (int i = n-1; i >= 0; i--){\n L[s.charAt(i)-'a']=i; // first character index position\n }\n for (int i = 0; i < 26; i++){ // add all characters between a character range.\n for (int j = L[i]+1; j < R[i] && L[i] >= 0; j++){\n bit[i].set(s.charAt(j)-'a');\n }\n }\n boolean go = true;\n while(go){ // keep merging until there is no more range change.\n go = false;\n for (int i = 0; i < 26; i++){\n for (int j = bit[i].nextSetBit(0); j >= 0; j = bit[i].nextSetBit(j+1)){\n bit[i].or(bit[j]); // add all characters from character j to i.\n int l = Math.min(L[i], L[j]);\n int r = Math.max(R[i], R[j]);\n go |= l != L[i] || r != R[i];\n L[i] = l;\n R[i] = r;\n }\n }\n }\n List ans = new ArrayList<>();\n boolean[] seen = new boolean[n];\n for (int i = 0; i < 26; i++){ // populate the answer\n boolean ok = L[i] >= 0 && !seen[L[i]];\n for (int j = 0; j < 26 && ok; j++){\n if (i != j && L[j] >= 0){ // only take those that has no smaller valid ranges.\n ok &= !(L[i]R[j]);\n }\n }\n if (ok){\n ans.add(s.substring(L[i], R[i]+1));\n seen[L[i]]=true;\n }\n }\n return ans;\n }\n}", + "title": "1520. Maximum Number of Non-Overlapping Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions: Find the maximum number of substrings that meet the above conditions . If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length. Notice that you can return the substrings in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"adefaddaccc\"Output:[\"e\",\"f\",\"ccc\"]Explanation:The following are all the possible substrings that meet the conditions:\n[\n  \"adefaddaccc\"\n  \"adefadda\",\n  \"ef\",\n  \"e\",\n \"f\",\n  \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abbaccd\"Output:[\"d\",\"bb\",\"cc\"]Explanation:Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n st = defaultdict(lambda : -1)\n ed = defaultdict(int)\n for i, c in enumerate(s):\n if st[c]==-1:\n st[c] = i\n ed[c] = i\n else:\n ed[c] = i\n ints = []\n for c in set(s):\n b, e = st[c], ed[c]\n i = b\n while i <= e and b == st[c]:\n b = min(b, st[s[i]])\n e = max(e, ed[s[i]])\n i += 1\n if b == st[c]:\n ints.append((b,e))\n ints.sort(key = lambda e: e[1])\n res = []\n prev = -1\n for i in range(len(ints)):\n j,k = ints[i]\n if j > prev:\n res.append(s[j:k+1])\n prev = k\n return res", + "title": "1520. Maximum Number of Non-Overlapping Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the maximum number of ocurrences of any substring under the following rules: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of unique characters in the substring must be less than or equal to maxLetters .", + "The substring size must be between minSize and maxSize inclusive." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4Output:2Explanation:Substring \"aab\" has 2 ocurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3Output:2Explanation:Substring \"aaa\" occur 2 times in the string. It can overlap.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {\n Map count = new HashMap<>();\n int ans = 0;\n int n = s.length();\n \n for(int i=0;i+minSize-1 hs = new HashSet<>();\n for(int j=0;j int:\n #dict to store valid substrings and their respective occurences count\n d = defaultdict(int)\n #find longest substrings that has k unique chars\n #counter dict for char count and make sure unique char count is not exceeded\n counter = defaultdict(int)\n #init left and right pointers of sliding window\n r = l = 0\n #iterate right pointer\n while r < len(s):\n counter[s[r]] += 1\n \n #invalid window found, so make it valid again\n #len of window is greater than minSize\n while (r - l + 1) > minSize:\n counter[s[l]] -= 1\n #remove the key from dict for unique char count if it becomes zero\n if counter[s[l]] == 0:\n del counter[s[l]]\n #increment the left pointer to make it a valid window\n l += 1\n\n #valid window size (minSize) and unique char count is lesser than or equal to maxLetters\n if r - l + 1 == minSize and len(counter) <= maxLetters:\n #increment count of the occurence of the substring\n d[s[l:r+1]] += 1\n \n #make sure to update right pointer only after an iteration\n r += 1\n \n #return the count of substring with max occurence\n #edge case with no substring\n return max(d.values()) if d else 0\n", + "title": "1297. Maximum Number of Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one operation, you may do the following: The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two integers in nums that are equal .", + "Remove both integers from nums , forming a pair ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,1,3,2,2]Output:[3,1]Explanation:Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[1,0]Explanation:Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0]Output:[0,1]Explanation:No pairs can be formed, and there is 1 number leftover in nums.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 21.09%) | Memory: 42.4 MB (Top 76.38%)\nclass Solution {\n public int[] numberOfPairs(int[] nums) {\n\n if(nums.length == 1)\n return new int[]{0,1};\n\n HashSet set = new HashSet<>();\n\n int pairs=0;\n for(int i : nums){\n if(!set.contains(i)){\n set.add(i); // No pair present\n }else{\n set.remove(i); // Pair found\n pairs++;\n }\n }\n\n return new int[]{pairs,set.size()};\n }\n}", + "title": "2341. Maximum Number of Pairs in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one operation, you may do the following: The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two integers in nums that are equal .", + "Remove both integers from nums , forming a pair ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,1,3,2,2]Output:[3,1]Explanation:Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[1,0]Explanation:Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0]Output:[0,1]Explanation:No pairs can be formed, and there is 1 number leftover in nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfPairs(self, nums: List[int]) -> List[int]:\n ans = [0] * 2\n c = Counter(nums)\n \n for v in c.values():\n ans[0] += (v // 2)\n ans[1] += (v % 2)\n \n return ans\n", + "title": "2341. Maximum Number of Pairs in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix points ( 0-indexed ). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row . Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1 ), picking cells at coordinates (r, c 1 ) and (r + 1, c 2 ) will subtract abs(c 1 - c 2 ) from your score. Return the maximum number of points you can achieve . abs(x) is defined as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "x for x >= 0 .", + "-x for x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2,3],[1,5,1],[3,1,1]]Output:9Explanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:points = [[1,5],[2,3],[4,2]]Output:11Explanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "/* \n -> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get \n\tadded to next values from next row.\n\n -> conditions to update values in frame \n\t\t* we will keep only those values which will contribute maximum in next row addition\n\n\te.g-->\n\t\tpoints --->[[1,2,3]\n\t\t\t\t\t[1,5,1]\n\t\t\t\t\t[3,1,1]]\n\n\t\tfor 1st iteration frame <--- [1,2,3] rest of two loops will not affect frame so in \n\t\t2nd itreration frame <--------[2,7,4] <-------- [1,2,3] + [1,5,1]\n\t\tnow we have to update frame so it can give max values for next row addition\n\t\t 0 1 2 \n\t\t[2,7,4] \n\t\t \\ \n\t\t[2,7,4] check left to right--> just check value at index 0 can contribute more than curr_sum at index 1 but to do so it has to give up (1-0) a penalty,here 7 can contribute more than 2-1=1 in next sum.\n\t\t2 7 4 now check for index 2,where (7-1)>4\n\t\t \\\n\t\t2 7 6\n\t\t\t\t\tnow do in reverse,can 6 contribute more than 7 no ( 7 >(6-1) ) \n\t\t\t\t\tcan 7 contibute more than 2 yes (2<(7-1)),so now frame will be\n\t\t6 7 6 now we can cal optimal-frame for rest of the matrix.\n\t+ 3 1 1\n ------------------- \n\t\t9 8 7 check left to right--> can 9 can contibute 8>(9-1) no; can 8 can contibute for index 2 no simlier for right to left\n*/\n\nclass Solution {\n\tpublic long maxPoints(int[][] points) {\n\t\tlong[] frame = new long[points[0].length];\n\n\t\tfor (int i = 0; i < points.length; i++) {\n\t\t\tfor (int j = 0; j =0;j--) frame[j] = Math.max(frame[j], frame[j + 1] - 1);\n\n\t\t\tfor(long k:frame) System.out.println(k);\n\t\t}\n\n\n\t\tlong ans = 0;\n\t\tfor (int i = 0; i < frame.length; i ++) {\n\t\t\tans = Math.max(ans, frame[i]);\n\t\t}\n\t\treturn ans;\n\t}\n}\n", + "title": "1937. Maximum Number of Points with Cost", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix points ( 0-indexed ). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row . Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1 ), picking cells at coordinates (r, c 1 ) and (r + 1, c 2 ) will subtract abs(c 1 - c 2 ) from your score. Return the maximum number of points you can achieve . abs(x) is defined as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "x for x >= 0 .", + "-x for x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2,3],[1,5,1],[3,1,1]]Output:9Explanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png" + }, + { + "text": "Example 2: Input:points = [[1,5],[2,3],[4,2]]Output:11Explanation:The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.", + "image": "https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n for i in range(m - 1):\n for j in range(1, n):\n points[i][j] = max(points[i][j], points[i][j - 1] - 1)\n \n for j in range(n - 2, -1, -1):\n points[i][j] = max(points[i][j], points[i][j + 1] - 1)\n \n for j in range(n):\n points[i + 1][j] += points[i][j]\n \n return max(points[m - 1])", + "title": "1937. Maximum Number of Points with Cost", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings s and p where p is a subsequence of s . You are also given a distinct 0-indexed integer array removable containing a subset of indices of s ( s is also 0-indexed ). You want to choose an integer k ( 0 <= k <= removable.length ) such that, after removing k characters from s using the first k indices in removable , p is still a subsequence of s . More formally, you will mark the character at s[removable[i]] for each 0 <= i < k , then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals . 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. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= p.length <= s.length <= 10^5", + "0 <= removable.length < s.length", + "0 <= removable[i] < s.length", + "p is a subsequence of s .", + "s and p both consist of lowercase English letters.", + "The elements in removable are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcacb\", p = \"ab\", removable = [3,1,0]Output:2Explanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]Output:1Explanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]Output:0Explanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumRemovals(String s, String p, int[] removable) {\n int left = 0, right = removable.length;\n\n while (left < right) {\n int middle = (right + left + 1) / 2;\n String afterRemoval = remove(s, removable, middle);\n if (isSubsequence(p, afterRemoval, p.length(), afterRemoval.length()))\n left = middle;\n else\n right = middle - 1;\n }\n\n return left;\n }\n\n private String remove(String s, int[] removable, int k) {\n char[] symbols = s.toCharArray();\n for (int i = 0; i < k; i++) {\n symbols[removable[i]] = Character.MIN_VALUE;\n }\n return String.valueOf(symbols);\n }\n\n private boolean isSubsequence(String subSequence, String word, int subSequenceChar, int wordChar) {\n if (subSequenceChar == 0) return true;\n if (wordChar == 0) return false;\n\n if (subSequence.charAt(subSequenceChar - 1) == word.charAt(wordChar - 1))\n return isSubsequence(subSequence, word, subSequenceChar - 1, wordChar - 1);\n\n return isSubsequence(subSequence, word, subSequenceChar, wordChar - 1);\n }\n}\n", + "title": "1898. Maximum Number of Removable Characters", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings s and p where p is a subsequence of s . You are also given a distinct 0-indexed integer array removable containing a subset of indices of s ( s is also 0-indexed ). You want to choose an integer k ( 0 <= k <= removable.length ) such that, after removing k characters from s using the first k indices in removable , p is still a subsequence of s . More formally, you will mark the character at s[removable[i]] for each 0 <= i < k , then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals . 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. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= p.length <= s.length <= 10^5", + "0 <= removable.length < s.length", + "0 <= removable[i] < s.length", + "p is a subsequence of s .", + "s and p both consist of lowercase English letters.", + "The elements in removable are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcacb\", p = \"ab\", removable = [3,1,0]Output:2Explanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]Output:1Explanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]Output:0Explanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 957 ms (Top 98.8%) | Memory: 28.80 MB (Top 96.39%)\n\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n\n def isEnough(k):\n s_arr = list(s)\n for i in removable[:k]:\n s_arr[i] = ''\n return isSubsequence(p, s_arr)\n \n def isSubsequence(s, t):\n t = iter(t)\n return all(c in t for c in s)\n\n while l < r:\n m = (l+r+1)//2\n if isEnough(m):\n l = m\n else:\n r = m - 1\n \n return l\n", + "title": "1898. Maximum Number of Removable Characters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks , with the i th task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers , with the j th worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i] ). Additionally, you have pills magical pills that will increase a worker's strength by strength . You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength , return the maximum number of tasks that can be completed. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == tasks.length", + "m == workers.length", + "1 <= n, m <= 5 * 10^4", + "0 <= pills <= m", + "0 <= tasks[i], workers[j], strength <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1Output:3Explanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5Output:1Explanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)", + "image": null + }, + { + "text": "Example 3: Input:tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10Output:2Explanation:We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) { \n Arrays.sort(tasks);\n Arrays.sort(workers);\n \n int st = 0;\n int end = Math.min(tasks.length, workers.length)-1;\n int ans =0;\n while(st<=end){\n int mid = (st+end)/2;\n if(isPossible(tasks, workers, pills, strength, mid)){\n st = mid+1;\n ans = Math.max(ans, mid+1);\n }else{\n end = mid-1;\n }\n }\n return ans;\n }\n \nboolean isPossibleToComplete(int[] tasks, int[] workers, int pills, int strength, int mid) {\n int n = workers.length;\n TreeMap map = new TreeMap<>();\n \n for (int i = n - 1, count = 0; count <= mid && i >= 0; i--, count++) {\n map.merge(workers[i], 1, (a, b) -> a + b);\n }\n int done = n - 1;\n int count = mid;\n for (int i = mid; i >= 0; i--) {\n int val = tasks[i];\n Integer kv = map.ceilingKey(val);\n if (kv != null) {\n updateMap(map, kv);\n } else {\n if(pills>0){\n int newStrg = val-strength;\n Integer newKv = map.ceilingKey(newStrg);\n if(newKv!=null){\n updateMap(map, newKv);\n pills--;\n }else {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }\n void updateMap(TreeMap map, int key){\n int vl = map.get(key);\n map.put(key, vl - 1);\n if (vl - 1 == 0) {\n map.remove(key);\n }\n }\n}\n", + "title": "2071. Maximum Number of Tasks You Can Assign", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks , with the i th task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers , with the j th worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i] ). Additionally, you have pills magical pills that will increase a worker's strength by strength . You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill. Given the 0-indexed integer arrays tasks and workers and the integers pills and strength , return the maximum number of tasks that can be completed. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == tasks.length", + "m == workers.length", + "1 <= n, m <= 5 * 10^4", + "0 <= pills <= m", + "0 <= tasks[i], workers[j], strength <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1Output:3Explanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5Output:1Explanation:We can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)", + "image": null + }, + { + "text": "Example 3: Input:tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10Output:2Explanation:We can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n from sortedcontainers import SortedList\n \n tasks.sort()\n workers.sort()\n \n def check_valid(ans):\n \n # _tasks = SortedList(tasks[:ans])\n _tasks = deque(tasks[:ans])\n _workers = workers[-ans:]\n remain_pills = pills\n \n for worker in _workers:\n task = _tasks[0]\n if worker >= task:\n # the worker can finish the min task without pill, just move on\n # _tasks.pop(0)\n _tasks.popleft()\n elif worker + strength >= task and remain_pills:\n # the worker cannot finish the min task without pill, but can solve it with pill\n # remove the max task that the strengthened worker can finish instead\n # remove_task_idx = _tasks.bisect_right(worker + strength)\n remove_task_idx = bisect.bisect_right(_tasks, worker + strength)\n # _tasks.pop(remove_task_idx - 1)\n del _tasks[remove_task_idx - 1]\n remain_pills -= 1\n else:\n return False\n return True\n \n lo, hi = 0, min(len(workers), len(tasks))\n while lo < hi:\n mid = (lo + hi + 1) // 2\n if check_valid(mid):\n lo = mid\n else:\n hi = mid - 1\n return lo\n", + "title": "2071. Maximum Number of Tasks You Can Assign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array points , an integer angle , and your location , where location = [pos x , pos y ] and points[i] = [x i , y i ] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate . In other words, pos x and pos y cannot be changed. Your field of view in degrees is represented by angle , determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2] . Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view . There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "location.length == 2", + "0 <= angle < 360", + "0 <= pos x , pos y , x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]Output:3Explanation:The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/89a07e9b-00ab-4967-976a-c723b2aa8656.png" + }, + { + "text": "Example 2: Input:points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]Output:4Explanation:All points can be made visible in your field of view, including the one at your location.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,0],[2,1]], angle = 13, location = [1,1]Output:1Explanation:You can only see one of the two points, as shown above.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/5010bfd3-86e6-465f-ac64-e9df941d2e49.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 251 ms (Top 43.04%) | Memory: 144 MB (Top 24.17%)\nclass Solution {\n public int visiblePoints(List> points, int angle, List location) {\n int overlap = 0;\n List list = new ArrayList<>(points.size());\n for (List p : points) {\n if (p.get(0) == location.get(0) && p.get(1) == location.get(1)) {\n overlap++;\n } else {\n list.add(angle(p.get(1) - location.get(1),\n p.get(0) - location.get(0)));\n }\n }\n Collections.sort(list);\n int max = 0;\n int n = list.size();\n int i2 = 0;\n // list.get(i1) is first angle leg\n // list.get(i2) is second angle leg\n for (int i1 = 0; i1 < n; i1++) {\n // let's grow i1-i2 angle as much as possible\n // edge case example: angle = 30, i1 = 350 degrees, i2 = 10 degrees\n // edge case handling: allow i2 to circle around and calculate second leg as (360 + list.get(i2 % n))\n // then i1 = 350, i2 = 370, delta = 20 degrees < 30 degrees\n while ((i2 < n && list.get(i2) - list.get(i1) <= angle) ||\n (i2 >= n && 360 + list.get(i2 % n) - list.get(i1) <= angle)) {\n i2++;\n }\n // after i2 went as far as possible away from i1 under allowed limit - check if a new maximum found\n max = Math.max(max, i2-i1);\n }\n return max + overlap;\n }\n\n private double angle(int dy, int dx) {\n double a = Math.toDegrees(Math.atan2(dy, dx));\n return (a < 0 ? a + 360 : a);\n }\n}", + "title": "1610. Maximum Number of Visible Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array points , an integer angle , and your location , where location = [pos x , pos y ] and points[i] = [x i , y i ] both denote integral coordinates on the X-Y plane. Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate . In other words, pos x and pos y cannot be changed. Your field of view in degrees is represented by angle , determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2] . Your browser does not support the video tag or this video format. You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view . There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points. Return the maximum number of points you can see . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "location.length == 2", + "0 <= angle < 360", + "0 <= pos x , pos y , x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]Output:3Explanation:The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/89a07e9b-00ab-4967-976a-c723b2aa8656.png" + }, + { + "text": "Example 2: Input:points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]Output:4Explanation:All points can be made visible in your field of view, including the one at your location.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,0],[2,1]], angle = 13, location = [1,1]Output:1Explanation:You can only see one of the two points, as shown above.", + "image": "https://assets.leetcode.com/uploads/2020/09/30/5010bfd3-86e6-465f-ac64-e9df941d2e49.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 5206 ms (Top 8.11%) | Memory: 46.3 MB (Top 98.26%)\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n\n arr, extra = [], 0\n xx, yy = location\n\n for x, y in points:\n if x == xx and y == yy:\n extra += 1\n continue\n arr.append(math.atan2(y - yy, x - xx))\n\n arr.sort()\n arr = arr + [x + 2.0 * math.pi for x in arr]\n angle = math.pi * angle / 180\n\n l = ans = 0\n for r in range(len(arr)):\n while arr[r] - arr[l] > angle:\n l += 1\n ans = max(ans, r - l + 1)\n\n return ans + extra", + "title": "1610. Maximum Number of Visible Points", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3Output:3Explanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2Output:2Explanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3Output:2Explanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 97.98%) | Memory: 45.20 MB (Top 9.52%)\n\nclass Solution {\n public int maxVowels(String s, int k) {\n int n = s.length();\n int maxVowels = 0;\n int count = 0;\n\n int[] vowels = new int[128];\n vowels['a'] = 1;\n vowels['e'] = 1;\n vowels['i'] = 1;\n vowels['o'] = 1;\n vowels['u'] = 1;\n\n for (int i = 0; i < k; i++) {\n count += vowels[s.charAt(i)];\n }\n\n maxVowels = count;\n for (int i = k; i < n; i++) {\n count += vowels[s.charAt(i)] - vowels[s.charAt(i - k)];\n maxVowels = Math.max(maxVowels, count);\n //System.out.println(Arrays.toString(vowels));\n if (maxVowels == k) {\n return maxVowels; \n }\n }\n return maxVowels;\n }\n}\n\n", + "title": "1456. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3Output:3Explanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2Output:2Explanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3Output:2Explanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxVowels(self, s: str, k: int) -> int:\n \n def find_count_vowels(string):\n lst_vowels= ['a', 'e', 'i', 'o', 'u']\n c=0\n for i in string:\n if i in lst_vowels:\n c+=1\n return c\n \n \n lst_vowels= ['a', 'e', 'i', 'o', 'u']\n if k>len(s):\n return find_count_vowels(s)\n dp = [0]*(len(s)-k+1)\n dp[0] = find_count_vowels(s[:k])\n for i in range(1,len(s)-k+1):\n \n \n if s[i-1] in lst_vowels and s[i+k-1] in lst_vowels:\n dp[i] = dp[i-1]\n elif s[i-1] in lst_vowels and s[i+k-1] not in lst_vowels:\n dp[i] = dp[i-1] - 1\n\n elif s[i-1] not in lst_vowels and s[i+k-1] in lst_vowels:\n dp[i] = dp[i-1] + 1\n else:\n dp[i] = dp[i-1]\n return max(dp)\n \n", + "title": "1456. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k . You can choose to change the value of one element of nums to k , or to leave the array unchanged . Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pivot < n", + "nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,2], k = 3Output:1Explanation:One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], k = 1Output:2Explanation:The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33Output:4Explanation:One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 532 ms (Top 32.98%) | Memory: 178.2 MB (Top 67.02%)\nclass Solution {\n //time - O(n), space - O(n)\n public int waysToPartition(int[] nums, int k) {\n int n = nums.length;\n\n int[] pref = new int[n];\n pref[0] = nums[0];\n Map count = new HashMap<>(); //contribution of prefixes without changing\n count.put(pref[0], 1);\n\n for (int i = 1; i < n - 1; i++){\n pref[i] += pref[i - 1] + nums[i];\n count.put(pref[i], count.getOrDefault(pref[i], 0) + 1);\n }\n pref[n - 1] += pref[n - 2] + nums[n - 1]; //last step doesn't add into 'count' map, because we're trying to find at least two parts.\n\n int sum = pref[n - 1];\n int max = 0;\n if (sum % 2 == 0)\n max = count.getOrDefault(sum / 2, 0); //max without changing\n\n Map countPrev = new HashMap<>(); //contribution of prefixes before current step\n for (int i = 0; i < n; i++){\n int diff = k - nums[i];\n int changedSum = sum + diff;\n if (changedSum % 2 == 0)\n max = Math.max(max, count.getOrDefault(changedSum / 2 - diff, 0) + countPrev.getOrDefault(changedSum / 2, 0));\n count.put(pref[i], count.getOrDefault(pref[i], 0) - 1);\n countPrev.put(pref[i], countPrev.getOrDefault(pref[i], 0) + 1);\n }\n return max;\n }\n}", + "title": "2025. Maximum Number of Ways to Partition an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k . You can choose to change the value of one element of nums to k , or to leave the array unchanged . Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pivot < n", + "nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,-1,2], k = 3Output:1Explanation:One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], k = 1Output:2Explanation:The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33Output:4Explanation:One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3346 ms (Top 89.52%) | Memory: 46.9 MB (Top 30.64%)\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix_sums = list(accumulate(nums))\n total_sum = prefix_sums[-1]\n best = 0\n if total_sum % 2 == 0:\n best = prefix_sums[:-1].count(total_sum // 2) # If no change\n\n after_counts = Counter(total_sum - 2 * prefix_sum\n for prefix_sum in prefix_sums[:-1])\n before_counts = Counter()\n\n best = max(best, after_counts[k - nums[0]]) # If we change first num\n\n for prefix, x in zip(prefix_sums, nums[1:]):\n gap = total_sum - 2 * prefix\n after_counts[gap] -= 1\n before_counts[gap] += 1\n\n best = max(best, after_counts[k - x] + before_counts[x - k])\n\n return best", + "title": "2025. Maximum Number of Ways to Partition an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n projects numbered from 0 to n - 1 . You are given an integer array milestones where each milestones[i] denotes the number of milestones the i th project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working . Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every week, you will finish exactly one milestone of one project. You must work every week.", + "You cannot work on two milestones from the same project for two consecutive weeks." + ], + "examples": [ + { + "text": "Example 1: Input:milestones = [1,2,3]Output:6Explanation:One possible scenario is:\n​​​​- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 2.\n- During the 3rdweek, you will work on a milestone of project 1.\n- During the 4thweek, you will work on a milestone of project 2.\n- During the 5thweek, you will work on a milestone of project 1.\n- During the 6thweek, you will work on a milestone of project 2.\nThe total number of weeks is 6.", + "image": null + }, + { + "text": "Example 2: Input:milestones = [5,2,1]Output:7Explanation:One possible scenario is:\n- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 1.\n- During the 3rdweek, you will work on a milestone of project 0.\n- During the 4thweek, you will work on a milestone of project 1.\n- During the 5thweek, you will work on a milestone of project 0.\n- During the 6thweek, you will work on a milestone of project 2.\n- During the 7thweek, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8thweek because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 73.74%) | Memory: 55.50 MB (Top 96.97%)\n\nclass Solution {\n public long numberOfWeeks(int[] milestones) {\n long sum = 0;\n int max = Integer.MIN_VALUE;\n for(int milestone: milestones) {\n sum += milestone;\n max = Math.max(milestone, max);\n }\n if((sum - max) < max)\n return ((sum - max) * 2) + 1;\n else\n return sum;\n }\n}\n", + "title": "1953. Maximum Number of Weeks for Which You Can Work", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n projects numbered from 0 to n - 1 . You are given an integer array milestones where each milestones[i] denotes the number of milestones the i th project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working . Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every week, you will finish exactly one milestone of one project. You must work every week.", + "You cannot work on two milestones from the same project for two consecutive weeks." + ], + "examples": [ + { + "text": "Example 1: Input:milestones = [1,2,3]Output:6Explanation:One possible scenario is:\n​​​​- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 2.\n- During the 3rdweek, you will work on a milestone of project 1.\n- During the 4thweek, you will work on a milestone of project 2.\n- During the 5thweek, you will work on a milestone of project 1.\n- During the 6thweek, you will work on a milestone of project 2.\nThe total number of weeks is 6.", + "image": null + }, + { + "text": "Example 2: Input:milestones = [5,2,1]Output:7Explanation:One possible scenario is:\n- During the 1stweek, you will work on a milestone of project 0.\n- During the 2ndweek, you will work on a milestone of project 1.\n- During the 3rdweek, you will work on a milestone of project 0.\n- During the 4thweek, you will work on a milestone of project 1.\n- During the 5thweek, you will work on a milestone of project 0.\n- During the 6thweek, you will work on a milestone of project 2.\n- During the 7thweek, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8thweek because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1032 ms (Top 59.60%) | Memory: 25.7 MB (Top 80.23%)\nclass Solution:\n def numberOfWeeks(self, m: List[int]) -> int:\n return min(sum(m), 2 * (sum(m) - max(m)) + 1)", + "title": "1953. Maximum Number of Weeks for Which You Can Work", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences , where each sentences[i] represents a single sentence . Return the maximum number of words that appear in a single sentence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= sentences.length <= 100", + "1 <= sentences[i].length <= 100", + "sentences[i] consists only of lowercase English letters and ' ' only.", + "sentences[i] does not have leading or trailing spaces.", + "All the words in sentences[i] are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:sentences = [\"alice and bob love leetcode\", \"i think so too\",\"this is great thanks very much\"]Output:6Explanation:- The first sentence, \"alice and bob love leetcode\", has 5 words in total.\n- The second sentence, \"i think so too\", has 4 words in total.\n- The third sentence, \"this is great thanks very much\", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.", + "image": null + }, + { + "text": "Example 2: Input:sentences = [\"please wait\",\"continue to fight\",\"continue to win\"]Output:3Explanation:It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 54.44%) | Memory: 45.2 MB (Top 33.72%)\nclass Solution {\n public int mostWordsFound(String[] sentences) {\n int max=0;\n for(int i=0; i int:\n mx=0\n for i in sentences:\n c=i.split()\n if len(c)>mx:\n mx=len(c)\n return mx\n\t\t\n", + "title": "2114. Maximum Number of Words Found in Sentences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^4", + "0 <= brokenLetters.length <= 26", + "text consists of words separated by a single space without any leading or trailing spaces.", + "Each word only consists of lowercase English letters.", + "brokenLetters consists of distinct lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"hello world\", brokenLetters = \"ad\"Output:1Explanation:We cannot type \"world\" because the 'd' key is broken.", + "image": null + }, + { + "text": "Example 2: Input:text = \"leet code\", brokenLetters = \"lt\"Output:1Explanation:We cannot type \"leet\" because the 'l' and 't' keys are broken.", + "image": null + }, + { + "text": "Example 3: Input:text = \"leet code\", brokenLetters = \"e\"Output:0Explanation:We cannot type either word because the 'e' key is broken.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 25.13%) | Memory: 42.1 MB (Top 88.13%)\nclass Solution {\n public int canBeTypedWords(String text, String brokenLetters) {\n int count = 1;\n boolean isBad = false;\n for (char c : text.toCharArray()) {\n if (c == ' ') {\n isBad = false;\n count++;\n } else {\n if (!isBad && brokenLetters.indexOf(c) != -1) {\n isBad = true;\n count--;\n }\n }\n }\n return count;\n }\n}", + "title": "1935. Maximum Number of Words You Can Type", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 10^4", + "0 <= brokenLetters.length <= 26", + "text consists of words separated by a single space without any leading or trailing spaces.", + "Each word only consists of lowercase English letters.", + "brokenLetters consists of distinct lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"hello world\", brokenLetters = \"ad\"Output:1Explanation:We cannot type \"world\" because the 'd' key is broken.", + "image": null + }, + { + "text": "Example 2: Input:text = \"leet code\", brokenLetters = \"lt\"Output:1Explanation:We cannot type \"leet\" because the 'l' and 't' keys are broken.", + "image": null + }, + { + "text": "Example 3: Input:text = \"leet code\", brokenLetters = \"e\"Output:0Explanation:We cannot type either word because the 'e' key is broken.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n text = text.split()\n length = len(text)\n brokenLetters = set(brokenLetters)\n\n for word in text:\n for char in word:\n if char in brokenLetters:\n length -= 1\n break\n\t\t\t\t\t\n return length\n", + "title": "1935. Maximum Number of Words You Can Type", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr1.length == arr2.length <= 40000", + "-10^6 <= arr1[i], arr2[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]Output:13", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 33.52%) | Memory: 58.1 MB (Top 8.52%)\nclass Solution {\n public int maxAbsValExpr(int[] arr1, int[] arr2) {\n\n //1. remove the modulas -\n //i & j are interchangable because they are inside the modulas\n // A[i] - A[j] + B[i] -B[j] + i-j\n // A[i] + B[i] + i - B[j] - A[j] - j\n // (A[i] + B[i] + i) ->X\n // (B[j] - A[j] - j) -> y\n // X - Y;\n //to get max value X should be max & Y should min\n\n // Possible cases (Since both arrays have same number of indexes, we can use single for loop & i as index)\n //A[i] + B[i] + i ->1\n //A[i] - B[i] + i ->2\n //A[i] + B[i] - i ->3\n //A[i] - B[i] - i ->4\n\n // Find out max of all response\n\n int arrayLength =arr1.length;\n int v1[] = new int [arrayLength];\n int v2[] = new int [arrayLength] ;\n int v3[] = new int [arrayLength] ;\n int v4[] = new int [arrayLength] ;\n int res = 0;\n for(int i = 0 ; i< arrayLength; i++)\n {\n v1[i] = i + arr1[i] + arr2[i];\n v2[i] = i + arr1[i] - arr2[i];\n v3[i] = i - arr1[i] + arr2[i];\n v4[i] = i - arr1[i] - arr2[i];\n }\nres = Math.max(res,Arrays.stream(v1).max().getAsInt()-Arrays.stream(v1).min().getAsInt());\n res = Math.max(res,Arrays.stream(v2).max().getAsInt()-Arrays.stream(v2).min().getAsInt());\n res = Math.max(res,Arrays.stream(v3).max().getAsInt()-Arrays.stream(v3).min().getAsInt());\n res = Math.max(res,Arrays.stream(v4).max().getAsInt()-Arrays.stream(v4).min().getAsInt());\n return res;\n }\n}", + "title": "1131. Maximum of Absolute Value Expression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr1.length == arr2.length <= 40000", + "-10^6 <= arr1[i], arr2[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]Output:13", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxAbsValExpr(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf')\n min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),float('inf'),float('inf'),float('inf')\n for i,(a,b) in enumerate(zip(arr1,arr2)):\n ppp=a+b+i\n if ppp>max_ppp:max_ppp=ppp\n if pppmax_ppm:max_ppm=ppm\n if ppmmax_pmp:max_pmp=pmp\n if pmpmax_pmm:max_pmm=pmm\n if pmm 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex1drawio.png" + }, + { + "text": "Example 2: Input:values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30Output:25Explanation:One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex2drawio.png" + }, + { + "text": "Example 3: Input:values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50Output:7Explanation:One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex31drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 301 ms (Top 63.32%) | Memory: 101.4 MB (Top 52.55%)\nclass Solution {\n public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {\n int n = values.length;\n List[] adj = new List[n];\n for (int i = 0; i < n; ++i) adj[i] = new LinkedList();\n for (int[] e : edges) {\n int i = e[0], j = e[1], t = e[2];\n adj[i].add(new int[]{j, t});\n adj[j].add(new int[]{i, t});\n }\n int[] res = new int[1];\n int[] seen = new int[n];\n seen[0]++;\n dfs(adj, 0, values, maxTime, seen, res, values[0]);\n return res[0];\n }\n private void dfs(List[] adj, int src, int[] values, int maxTime, int[] seen, int[] res, int sum) {\n if (0 == src) {\n res[0] = Math.max(res[0], sum);\n }\n if (0 > maxTime) return;\n for (int[] data : adj[src]) {\n int dst = data[0], t = data[1];\n if (0 > maxTime - t) continue;\n seen[dst]++;\n dfs(adj, dst, values, maxTime - t, seen, res, sum + (1 == seen[dst] ? values[dst] : 0));\n seen[dst]--;\n }\n }\n}", + "title": "2065. Maximum Path Quality of a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected graph with n nodes numbered from 0 to n - 1 ( inclusive ). You are given a 0-indexed integer array values where values[i] is the value of the i th node. You are also given a 0-indexed 2D integer array edges , where each edges[j] = [u j , v j , time j ] indicates that there is an undirected edge between the nodes u j and v j , and it takes time j seconds to travel between the two nodes. Finally, you are given an integer maxTime . A valid path in the graph is any path that starts at node 0 , ends at node 0 , and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path . Note: There are at most four edges connected to each node. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == values.length", + "1 <= n <= 1000", + "0 <= values[i] <= 10^8", + "0 <= edges.length <= 2000", + "edges[j].length == 3", + "0 <= u j < v j <= n - 1", + "10 <= time j , maxTime <= 100", + "All the pairs [u j , v j ] are unique .", + "There are at most four edges connected to each node.", + "The graph may not be connected." + ], + "examples": [ + { + "text": "Example 1: Input:values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49Output:75Explanation:One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex1drawio.png" + }, + { + "text": "Example 2: Input:values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30Output:25Explanation:One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex2drawio.png" + }, + { + "text": "Example 3: Input:values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50Output:7Explanation:One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.", + "image": "https://assets.leetcode.com/uploads/2021/10/19/ex31drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n graph = defaultdict(list)\n\t\t# build graph\n for edge in edges:\n graph[edge[0]].append((edge[1], edge[2]))\n graph[edge[1]].append((edge[0], edge[2]))\n \n q = deque()\n q.append((0, 0, values[0], set([0])))\n cache = {}\n maxPoint = 0\n\t\t\n while q:\n currV, currTime, currPoints, currSet = q.popleft()\n if currV in cache:\n\t\t\t\t# if vertex has been visited, and if the previousTime is \n\t\t\t\t# less or equal to current time but current points is lower?\n\t\t\t\t# then this path can't give us better quality so stop proceeding.\n prevTime, prevPoints = cache[currV]\n if prevTime <= currTime and prevPoints > currPoints:\n continue\n cache[currV] = (currTime, currPoints)\n\t\t\t# can't go over the maxTime limit\n if currTime > maxTime:\n continue\n\t\t\t# collect maxPoint only if current vertex is 0\n if currV == 0:\n maxPoint = max(maxPoint, currPoints)\n for neigh, neighTime in graph[currV]:\n newSet = currSet.copy()\n\t\t\t\t# collects quality only if not collected before\n if neigh not in currSet:\n newSet.add(neigh)\n newPoint = currPoints + values[neigh]\n else:\n newPoint = currPoints\n q.append((neigh, currTime + neighTime, newPoint, newSet))\n return maxPoint\n", + "title": "2065. Maximum Path Quality of a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n . There are n engineers numbered from 1 to n . speed[i] and efficiency[i] represent the speed and efficiency of the i th engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance . The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team . Since the answer can be a huge number, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^5", + "speed.length == n", + "efficiency.length == n", + "1 <= speed[i] <= 10^5", + "1 <= efficiency[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2Output:60Explanation:We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3Output:68Explanation:This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "image": null + }, + { + "text": "Example 3: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4Output:72", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 90 ms (Top 75.46%) | Memory: 69.9 MB (Top 33.86%)\nclass Engineer {\n int speed, efficiency;\n Engineer(int speed, int efficiency) {\n this.speed = speed;\n this.efficiency = efficiency;\n }\n}\n\nclass Solution {\n public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {\n List engineers = new ArrayList<>();\n for(int i=0;i b.efficiency - a.efficiency);\n PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> a.speed - b.speed);\n long maxPerformance = 0l, totalSpeed = 0l;\n for(Engineer engineer: engineers) {\n if(maxHeap.size() == k) {\n totalSpeed -= maxHeap.poll().speed;\n }\n totalSpeed += engineer.speed;\n maxHeap.offer(engineer);\n maxPerformance = Math.max(maxPerformance, totalSpeed * (long)engineer.efficiency);\n }\n return (int)(maxPerformance % 1_000_000_007);\n }\n}", + "title": "1383. Maximum Performance of a Team", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integers n and k and two integer arrays speed and efficiency both of length n . There are n engineers numbered from 1 to n . speed[i] and efficiency[i] represent the speed and efficiency of the i th engineer respectively. Choose at most k different engineers out of the n engineers to form a team with the maximum performance . The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. Return the maximum performance of this team . Since the answer can be a huge number, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 10^5", + "speed.length == n", + "efficiency.length == n", + "1 <= speed[i] <= 10^5", + "1 <= efficiency[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2Output:60Explanation:We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3Output:68Explanation:This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.", + "image": null + }, + { + "text": "Example 3: Input:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4Output:72", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n l = list(zip(efficiency,speed))\n l.sort(reverse=True)\n h = []\n res = 0\n mod = 1000000007\n mx_sum = 0\n print(l)\n for i in range(n):\n res = max(res , (mx_sum+l[i][1])*l[i][0])\n if len(h) 0)\n bob[0] += remainArr;\n if(point > bobPoint) { // Update the max points and result output\n bobPoint = point;\n maxbob = bob.clone();\n }\n return;\n }\n //part 1: assign 1 more arrow than alice\n if(remainArr >= alice[index]+1) {\n bob[index] = alice[index] + 1;\n calculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index);\n bob[index] = 0;\n }\n //part 2: assign no arrow and move to next point\n calculate(alice, bob, index-1, remainArr, point);\n bob[index] = 0;\n }\n }", + "title": "2212. Maximum Points in an Archery Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11 , then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12 , which represents the number of arrows Alice shot on each scoring section from 0 to 11 . Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11 . The sum of the values in bobArrows should equal numArrows . If there are multiple ways for Bob to earn the maximum total points, return any one of them. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if Alice and Bob both shot 2 arrows on the section with score 11 , then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points." + ], + "examples": [ + { + "text": "Example 1: Input:numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]Output:[0,0,0,0,1,1,0,0,1,2,3,1]Explanation:The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.", + "image": "https://assets.leetcode.com/uploads/2022/02/24/ex1.jpg" + }, + { + "text": "Example 2: Input:numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]Output:[0,0,0,0,0,0,0,0,1,1,1,0]Explanation:The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.", + "image": "https://assets.leetcode.com/uploads/2022/02/24/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 114 ms (Top 97.78%) | Memory: 16.60 MB (Top 73.33%)\n\nclass Solution:\n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n max_score = [0, None]\n def calc(i, remaining, score, arrows):\n\t\t # Base case. Update max score.\n if remaining == 0 or i == -1:\n if score > max_score[0]:\n max_score[0] = score\n max_score[1] = arrows[:]\n return\n\n\t\t\t# Special handling for the last section. Use up all the arrows.\n if i == 0:\n arrows[i] = remaining\n calc(i - 1, 0, score + i, arrows)\n arrows[i] = 0\n return\n\n\t\t # Try to compete with Alice if there are enough arrows.\n arrowsNeeded = aliceArrows[i] + 1\n if remaining >= arrowsNeeded:\n arrows[i] = arrowsNeeded\n calc(i - 1, remaining - arrowsNeeded, score + i, arrows)\n arrows[i] = 0\n\n # Skip this section and go to the next section.\n calc(i - 1, remaining, score, arrows)\n \n\t\t# Kick off the recursion\n calc(len(aliceArrows) - 1, numArrows, 0, [0 for _ in aliceArrows])\n return max_score[1]\n", + "title": "2212. Maximum Points in an Archery Competition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are several cards arranged in a row , and each card has an associated number of points. The points are given in the integer array cardPoints . In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k , return the maximum score you can obtain. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= cardPoints.length <= 10^5", + "1 <= cardPoints[i] <= 10^4", + "1 <= k <= cardPoints.length" + ], + "examples": [ + { + "text": "Example 1: Input:cardPoints = [1,2,3,4,5,6,1], k = 3Output:12Explanation:After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.", + "image": null + }, + { + "text": "Example 2: Input:cardPoints = [2,2,2], k = 2Output:4Explanation:Regardless of which two cards you take, your score will always be 4.", + "image": null + }, + { + "text": "Example 3: Input:cardPoints = [9,7,7,9,7,7,9], k = 7Output:55Explanation:You have to take all the cards. Your score is the sum of points of all cards.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 20.60%) | Memory: 66.5 MB (Top 16.04%)\nclass Solution {\n public int maxScore(int[] cardPoints, int k) {\n int n = cardPoints.length;\n int[] totalSum = new int[n];\n int sum = 0;\n for(int i=0;i int:\n n = len(cardPoints)\n total = sum(cardPoints)\n \n remaining_length = n - k\n subarray_sum = sum(cardPoints[:remaining_length])\n \n min_sum = subarray_sum\n for i in range(remaining_length, n):\n # Update the sliding window sum to the subarray ending at index i\n subarray_sum += cardPoints[i]\n subarray_sum -= cardPoints[i - remaining_length]\n # Update min_sum to track the overall minimum sum so far\n min_sum = min(min_sum, subarray_sum)\n return total - min_sum\n", + "title": "1423. Maximum Points You Can Obtain from Cards", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array logs where each logs[i] = [birth i , death i ] indicates the birth and death years of the i th person. The population of some year x is the number of people alive during that year. The i th person is counted in year x 's population if x is in the inclusive range [birth i , death i - 1] . Note that the person is not counted in the year that they die. Return the earliest year with the maximum population . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 100", + "1950 <= birth i < death i <= 2050" + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[1993,1999],[2000,2010]]Output:1993Explanation:The maximum population is 1, and 1993 is the earliest year with this population.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1950,1961],[1960,1971],[1970,1981]]Output:1960Explanation:The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 78.61%) | Memory: 42.6 MB (Top 29.91%)\nclass Solution {\n public int maximumPopulation(int[][] logs) {\n\n int[] year = new int[2051];\n\n // O(n) -> n is log.length\n\n for(int[] log : logs){\n\n year[log[0]] += 1;\n year[log[1]] -= 1;\n }\n\n int maxNum = year[1950], maxYear = 1950;\n\n // O(100) -> 2050 - 1950 = 100\n\n for(int i = 1951; i < year.length; i++){\n year[i] += year[i - 1]; // Generating Prefix Sum\n\n if(year[i] > maxNum){\n maxNum = year[i];\n maxYear = i;\n }\n }\n\n return maxYear;\n }\n}", + "title": "1854. Maximum Population Year", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array logs where each logs[i] = [birth i , death i ] indicates the birth and death years of the i th person. The population of some year x is the number of people alive during that year. The i th person is counted in year x 's population if x is in the inclusive range [birth i , death i - 1] . Note that the person is not counted in the year that they die. Return the earliest year with the maximum population . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= logs.length <= 100", + "1950 <= birth i < death i <= 2050" + ], + "examples": [ + { + "text": "Example 1: Input:logs = [[1993,1999],[2000,2010]]Output:1993Explanation:The maximum population is 1, and 1993 is the earliest year with this population.", + "image": null + }, + { + "text": "Example 2: Input:logs = [[1950,1961],[1960,1971],[1970,1981]]Output:1960Explanation:The maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n logs.sort(key=lambda x: x[0])\n print(logs)\n living = 0\n max_living = 0\n year = 0\n\n for ind, (start, stop) in enumerate(logs):\n born = ind+1\n dead = 0\n for i in range(ind):\n if logs[i][1] <= start:\n dead += 1\n \n living = born - dead\n # print(born, dead, living, max_living)\n if living > max_living:\n max_living = living\n year = start\n\n \n \n return year", + "title": "1854. Maximum Population Year", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array of non-negative integers nums and an integer k . In one operation, you may choose any element from nums and increment it by 1 . Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7 . Note that you should maximize the product before taking the modulo. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,4], k = 5Output:20Explanation:Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,3,2], k = 2Output:216Explanation:Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumProduct(int[] nums, int k) {\n \n Queue pq = new PriorityQueue<>();\n for (int num : nums) pq.add(num);\n \n while (k-->0) {\n int top = pq.poll() + 1 ;\n pq.add(top);\n }\n\n long res = 1;\n while (!pq.isEmpty()) {\n res = (res*pq.poll()) % 1000000007;\n }\n\n return (int)(res);\n }\n}\n", + "title": "2233. Maximum Product After K Increments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of non-negative integers nums and an integer k . In one operation, you may choose any element from nums and increment it by 1 . Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10^9 + 7 . Note that you should maximize the product before taking the modulo. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length, k <= 10^5", + "0 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,4], k = 5Output:20Explanation:Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,3,2], k = 2Output:216Explanation:Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 985 ms (Top 85.38%) | Memory: 27.10 MB (Top 71.7%)\n\nclass Solution:\n def maximumProduct(self, nums: List[int], k: int) -> int:\n heap = nums.copy()\n heapify(heap)\n for i in range(k):\n t = heappop(heap)\n heappush(heap, t + 1)\n ans = 1\n mod = 1000000007\n for i in heap:\n ans = (ans*i) % mod\n return ans\n", + "title": "2233. Maximum Product After K Increments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d) . Given an integer array nums , choose four distinct indices w , x , y , and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized . Return the maximum such product difference . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,6,2,7,4]Output:34Explanation:We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,5,9,7,4,8]Output:64Explanation:We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProductDifference(int[] nums) {\n int max1 = Integer.MIN_VALUE;\n int max2 = max1;\n\n int min1 = Integer.MAX_VALUE;\n int min2 = min1;\n for (int i = 0; i < nums.length; i++) {\n if (max1 < nums[i]) {\n max2 = max1;\n max1 = nums[i];\n } else if(nums[i] > max2)\n max2 = nums[i];\n\n if(min1 > nums[i]){\n min2 = min1;\n min1 = nums[i];\n }else if (nums[i] < min2)\n min2 = nums[i];\n }\n \n return (max1 * max2) - (min1 * min2);\n }\n}\n", + "title": "1913. Maximum Product Difference Between Two Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d) . Given an integer array nums , choose four distinct indices w , x , y , and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized . Return the maximum such product difference . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,6,2,7,4]Output:34Explanation:We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,5,9,7,4,8]Output:64Explanation:We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n max_1 = 0\n max_2 = 0\n min_1 = 10001\n min_2 = 10001\n for i in nums:\n if i >= max_1:\n max_2,max_1 = max_1,i\n elif i > max_2:\n max_2 = i\n if i <= min_1:\n min_2,min_1 = min_1,i\n elif i < min_2:\n min_2 = i\n \n return max_1*max_2 - min_1*min_2\n", + "title": "1913. Maximum Product Difference Between Two Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees . Since the answer may be too large, return it modulo 10^9 + 7 . Note that you need to maximize the answer before taking the mod and not after taking it. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5 * 10^4 ] .", + "1 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:110Explanation:Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" + }, + { + "text": "Example 2: Input:root = [1,null,2,3,4,null,null,5,6]Output:90Explanation:Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 82.12%) | Memory: 70.1 MB (Top 38.32%)\nclass Solution {\n public void findMaxSum(TreeNode node,long sum[]){\n if(node==null) return ;\n\n findMaxSum(node.left,sum);\n findMaxSum(node.right,sum);\n\n sum[0]+=node.val;\n\n }\n\n public long findProd(TreeNode node,long sum[],long []max){\n if(node==null) return 0;\n\n long left=findProd(node.left, sum, max);\n long right=findProd(node.right,sum,max);\n\n long val=left+right+node.val;\n\n max[0]=Math.max(max[0],val*(sum[0]-val));\n\n return val;\n }\n public int maxProduct(TreeNode root) {\n\n long max[]=new long[1];\n long sum[]=new long[1];\n\n findMaxSum(root,sum);\n\n long n= findProd(root,sum,max);\n\n return (int)(max[0]%((int)1e9+7));\n }\n}", + "title": "1339. Maximum Product of Splitted Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees . Since the answer may be too large, return it modulo 10^9 + 7 . Note that you need to maximize the answer before taking the mod and not after taking it. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 5 * 10^4 ] .", + "1 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:110Explanation:Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" + }, + { + "text": "Example 2: Input:root = [1,null,2,3,4,null,null,5,6]Output:90Explanation:Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)", + "image": "https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, root: Optional[TreeNode]) -> int:\n def findTotalSum(node, totalSum):\n if node is None:\n return totalSum\n totalSum = findTotalSum(node.left,totalSum)\n totalSum += node.val\n totalSum = findTotalSum(node.right,totalSum)\n return totalSum\n \n def dfs(node,maxProd,totalSum):\n if node is None:\n return maxProd,0\n if not node.left and not node.right:\n return maxProd,node.val\n maxProd, lSum = dfs(node.left,maxProd,totalSum)\n maxProd, rSum = dfs(node.right,maxProd,totalSum)\n subTreeSum = lSum+rSum+node.val\n maxProd = max(maxProd,(totalSum-lSum)*lSum,(totalSum-rSum)*rSum,(totalSum-subTreeSum)*subTreeSum)\n return maxProd, subTreeSum\n \n totalSum = findTotalSum(root, 0)\n product,_ = dfs(root,1,totalSum)\n return product % (pow(10,9)+7)\n", + "title": "1339. Maximum Product of Splitted Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find two disjoint palindromic subsequences of s such that the product of their lengths is maximized . The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 12", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcodecom\"Output:9Explanation: An optimal solution is to choose \"ete\" for the 1stsubsequence and \"cdc\" for the 2ndsubsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png" + }, + { + "text": "Example 2: Input:s = \"bb\"Output:1Explanation: An optimal solution is to choose \"b\" (the first character) for the 1stsubsequence and \"b\" (the second character) for the 2ndsubsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"accbcaxxcxx\"Output:25Explanation: An optimal solution is to choose \"accca\" for the 1stsubsequence and \"xxcxx\" for the 2ndsubsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 952 ms (Top 21.5%) | Memory: 44.16 MB (Top 54.1%)\n\nclass Solution {\n int res = 0;\n \n public int maxProduct(String s) {\n char[] strArr = s.toCharArray();\n dfs(strArr, 0, \"\", \"\");\n return res;\n }\n\n public void dfs(char[] strArr, int i, String s1, String s2){\n if(i >= strArr.length){\n if(isPalindromic(s1) && isPalindromic(s2))\n res = Math.max(res, s1.length()*s2.length());\n return;\n }\n dfs(strArr, i+1, s1 + strArr[i], s2);\n dfs(strArr, i+1, s1, s2 + strArr[i]);\n dfs(strArr, i+1, s1, s2);\n }\n\n public boolean isPalindromic(String str){\n int j = str.length() - 1;\n char[] strArr = str.toCharArray();\n for (int i = 0; i < j; i ++){\n if (strArr[i] != strArr[j])\n return false;\n j--;\n }\n return true;\n }\n}", + "title": "2002. Maximum Product of the Length of Two Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , find two disjoint palindromic subsequences of s such that the product of their lengths is maximized . The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences . A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 12", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcodecom\"Output:9Explanation: An optimal solution is to choose \"ete\" for the 1stsubsequence and \"cdc\" for the 2ndsubsequence.\nThe product of their lengths is: 3 * 3 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png" + }, + { + "text": "Example 2: Input:s = \"bb\"Output:1Explanation: An optimal solution is to choose \"b\" (the first character) for the 1stsubsequence and \"b\" (the second character) for the 2ndsubsequence.\nThe product of their lengths is: 1 * 1 = 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"accbcaxxcxx\"Output:25Explanation: An optimal solution is to choose \"accca\" for the 1stsubsequence and \"xxcxx\" for the 2ndsubsequence.\nThe product of their lengths is: 5 * 5 = 25.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, s: str) -> int:\n # n <= 12, which means the search space is small\n n = len(s)\n arr = []\n \n for mask in range(1, 1< 0:\n subseq += s[i]\n if subseq == subseq[::-1]:\n arr.append((mask, len(subseq)))\n \n result = 1\n for (mask1, len1), (mask2, len2) in product(arr, arr):\n # disjoint\n if mask1 & mask2 == 0:\n result = max(result, len1 * len2)\n return result\n", + "title": "2002. Maximum Product of the Length of Two Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i , j , k , l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive . Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababbb\"Output:9Explanation:Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zaaaxbbby\"Output:9Explanation:Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 65.22%) | Memory: 61.1 MB (Top 39.13%)\n// using manachers algorithm\n\nclass Solution {\n\n public long maxProduct(String s) {\n int n = s.length();\n if (n == 2) return 1;\n int[] len = manachers(s); // get lengths of palindromes at each element\n\n long left[] = new long[n]; // stores the max length of palindrome to left of each index\n\n int max = 1;\n left[0] = max;\n for (int i = 1; i <= n - 1; i++) {\n // does any palindrome end at i with length greater than max\n if (len[(i - max - 1 + i)/2] > max) max += 2;\n left[i] = max;\n }\n max = 1;\n long[] right = new long[n]; // stores the max length of palindrome to right of each index\n right[n - 1] = max;\n\n for (int i = n - 2; i >= 0; i--) {\n // does any palindrome start at i with length greater than max\n if (len[(i + max + 1 + i)/2] > max) max += 2;\n right[i] = max;\n }\n\n long res = 1;\n\n for (int i = 1; i < n; i++) {\n res = Math.max(res, left[i - 1] * right[i]);\n }\n return res;\n }\n\n // credit : https://hackernoon.com/manachers-algorithm-explained-longest-palindromic-substring-22cb27a5e96f\n private int[] manachers(String s) {\n\n int len = s.length();\n int[] P = new int[len];\n int c = 0; //stores the center of the longest palindromic substring until now\n int r = 0; //stores the right boundary of the longest palindromic substring until now\n int maxLen = 0;\n\n for(int i = 0; i < len; i++) {\n //get mirror index of i\n int mirror = (2 * c) - i;\n\n //see if the mirror of i is expanding beyond the left boundary of current longest palindrome at center c\n //if it is, then take r - i as P[i]\n //else take P[mirror] as P[i]\n if(i < r) {\n P[i] = Math.min(r - i, P[mirror]);\n }\n\n //expand at i\n int a = i + (1 + P[i]);\n int b = i - (1 + P[i]);\n while(a < len && b >= 0 && s.charAt(a) == s.charAt(b)) {\n P[i]++;\n a++;\n b--;\n }\n\n //check if the expanded palindrome at i is expanding beyond the right boundary of current longest palindrome at center c\n //if it is, the new center is i\n if(i + P[i] > r) {\n c = i;\n r = i + P[i];\n }\n }\n for (int i = 0; i < len; i++) P[i] = 1 + 2*P[i];\n return P;\n }\n\n}", + "title": "1960. Maximum Product of the Length of Two Palindromic Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. More formally, you want to choose four integers i , j , k , l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive . Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababbb\"Output:9Explanation:Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"zaaaxbbby\"Output:9Explanation:Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, s: str) -> int:\n n = len(s)\n \n # Manacher's algo\n hlen = [0]*n # half-length\n center = right = 0 \n for i in range(n): \n if i < right: hlen[i] = min(right - i, hlen[2*center - i])\n while 0 <= i-1-hlen[i] and i+1+hlen[i] < len(s) and s[i-1-hlen[i]] == s[i+1+hlen[i]]: \n hlen[i] += 1\n if right < i+hlen[i]: center, right = i, i+hlen[i]\n \n prefix = [0]*n\n suffix = [0]*n\n for i in range(n): \n prefix[i+hlen[i]] = max(prefix[i+hlen[i]], 2*hlen[i]+1)\n suffix[i-hlen[i]] = max(suffix[i-hlen[i]], 2*hlen[i]+1)\n \n for i in range(1, n): \n prefix[~i] = max(prefix[~i], prefix[~i+1]-2)\n suffix[i] = max(suffix[i], suffix[i-1]-2)\n \n for i in range(1, n): \n prefix[i] = max(prefix[i-1], prefix[i])\n suffix[~i] = max(suffix[~i], suffix[~i+1])\n \n return max(prefix[i-1]*suffix[i] for i in range(1, n))", + "title": "1960. Maximum Product of the Length of Two Palindromic Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , find three numbers whose product is maximum and return the maximum product . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:24", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3]Output:-6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 99.90%) | Memory: 54.7 MB (Top 23.03%)\nclass Solution {\n public int maximumProduct(int[] nums) {\n int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;\n for (int n: nums) {\n if (n <= min1) {\n min2 = min1;\n min1 = n;\n } else if (n <= min2) { // n lies between min1 and min2\n min2 = n;\n }\n if (n >= max1) { // n is greater than max1, max2 and max3\n max3 = max2;\n max2 = max1;\n max1 = n;\n } else if (n >= max2) { // n lies betweeen max1 and max2\n max3 = max2;\n max2 = n;\n } else if (n >= max3) { // n lies betwen max2 and max3\n max3 = n;\n }\n }\n return Math.max(min1 * min2 * max1, max1 * max2 * max3);\n }\n}", + "title": "628. Maximum Product of Three Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , find three numbers whose product is maximum and return the maximum product . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:24", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,-2,-3]Output:-6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n # TC = O(NlogN) because sorting the array \n # SC = O(1); no extra space needed; sorting was done in place.\n \n # sorting the array in descending order\n nums.sort(reverse = True)\n \n # maximum product can only occur for:\n # 1. positive no * positive no * positive no\n # 2. negative no * negative no * positive no\n \n # one negative and two positives and all negatives wont give max product\n # case where all numbers in the array are negative \n # eg : [-4,-3,-2,-1] is covered in all positives \n \n return max(nums[0]*nums[1]*nums[2],nums[-1]*nums[-2]*nums[0])\n", + "title": "628. Maximum Product of Three Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,2]Output:12Explanation:If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,4,5]Output:16Explanation:Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,7]Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProduct(int[] nums) {\n int max = Integer.MIN_VALUE;\n int maxi = -1;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] > max) {\n max = nums[i];\n maxi = i;\n }\n }\n nums[maxi] = Integer.MIN_VALUE;\n int nextmax = Integer.MIN_VALUE;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] > nextmax) nextmax = nums[i];\n }\n return max*nextmax-max-nextmax+1;\n }\n}\n", + "title": "1464. Maximum Product of Two Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 500", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,2]Output:12Explanation:If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,4,5]Output:16Explanation:Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,7]Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n # mx1 - max element, mx2 - second max element\n mx1 = nums[0] if nums[0] > nums[1] else nums[1]\n mx2 = nums[1] if nums[0] > nums[1] else nums[0]\n for num in nums[2:]:\n if num > mx1:\n mx1, mx2 = num, mx1\n elif num > mx2:\n mx2 = num\n\n return (mx1 - 1) * (mx2 - 1)\n\n", + "title": "1464. Maximum Product of Two Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string array words , return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters . If no such two words exist, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= words.length <= 1000", + "1 <= words[i].length <= 1000", + "words[i] consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]Output:16Explanation:The two words can be \"abcw\", \"xtfn\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]Output:4Explanation:The two words can be \"ab\", \"cd\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]Output:0Explanation:No such pair of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 91.40%) | Memory: 44.6 MB (Top 93.55%)\nclass Solution {\n public int maxProduct(String[] words) {\n int n = words.length;\n int[] masks = new int[n];\n\n for (int i=0; i int:\n n=len(words)\n \n bit_masks = [0] * n\n lengths = [0] * n\n \n for i in range(n): \n for c in words[i]:\n bit_masks[i]|=1<<(ord(c) - ord('a')) # set the character bit \n lengths[i]=len(words[i])\n \n max_val = 0\n for i in range(n):\n for j in range(i+1, n):\n if not (bit_masks[i] & bit_masks[j]):\n max_val=max(max_val, lengths[i] * lengths[j])\n \n return max_val \n", + "title": "318. Maximum Product of Word Lengths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find a contiguous non-empty subarray within the array 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. A subarray is a contiguous subsequence of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10 <= nums[i] <= 10", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]Output:6Explanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]Output:0Explanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.73%) | Memory: 44.9 MB (Top 43.86%)\nclass Solution {\n public int maxProduct(int[] nums) {\n int ans = Integer.MIN_VALUE;\n int m = 1;\n for(int i=0; i< nums.length; i++){\n m*=nums[i];\n ans = Math.max(m, ans);\n if(m == 0) m=1;\n }\n int n = 1;\n for(int i=nums.length-1; i>=0; i--){\n n*=nums[i];\n ans = Math.max(n, ans);\n if(n == 0) n=1;\n }\n return ans;\n }\n}", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , find a contiguous non-empty subarray within the array 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. A subarray is a contiguous subsequence of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-10 <= nums[i] <= 10", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]Output:6Explanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]Output:0Explanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prod=1\n maxprod=-100000000\n for i in range(len(nums)): # traverse from L-R so that we get max \n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n prod=1\n for i in range(len(nums)-1,-1,-1): #if 0 or -ve present at starting then find from back\n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n return maxprod\n", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i] , obtaining a profit of profit[i] . You're given the startTime , endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/10/sample1_1584.png", + "https://assets.leetcode.com/uploads/2019/10/10/sample22_1584.png", + "https://assets.leetcode.com/uploads/2019/10/10/sample3_1584.png" + ], + "constraints": [ + "1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4", + "1 <= startTime[i] < endTime[i] <= 10^9", + "1 <= profit[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]Output:120Explanation:The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]Output:150Explanation:The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.", + "image": null + }, + { + "text": "Example 3: Input:startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 990 ms (Top 41.71%) | Memory: 47.5 MB (Top 21.04%)\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n n = len(startTime)\n jobs = list(zip(startTime, endTime, profit))\n jobs.sort()\n startTime.sort()\n @lru_cache(None)\n def recur(i):\n if i == n:\n return 0\n j = bisect_left(startTime, jobs[i][1])\n one = jobs[i][2] + recur(j)\n two = recur(i+1)\n return max(one, two)\n return recur(0)", + "title": "1235. Maximum Profit in Job Scheduling", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are the operator of a Centennial Wheel that has four gondolas , and each gondola has room for up to four people . You have the ability to rotate the gondolas counterclockwise , which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the i th rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive . You cannot make customers wait if there is room in the gondola . Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers . If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation . Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == customers.length", + "1 <= n <= 10^5", + "0 <= customers[i] <= 50", + "1 <= boardingCost, runningCost <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:customers = [8,3], boardingCost = 5, runningCost = 6Output:3Explanation:The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.", + "image": "https://assets.leetcode.com/uploads/2020/09/09/wheeldiagram12.png" + }, + { + "text": "Example 2: Input:customers = [10,9,6], boardingCost = 6, runningCost = 4Output:7Explanation:1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.", + "image": null + }, + { + "text": "Example 3: Input:customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92Output:-1Explanation:1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 80.7%) | Memory: 55.64 MB (Top 69.2%)\n\nclass Solution {\n public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {\n int rotatn = 0;\n int cust = 0;\n int profit = Integer.MIN_VALUE;\n int prRotn = 0;\n int cSit = 0;\n\n for(int i = 0 ; i < customers.length ; i++){\n cust += customers[i];\n rotatn++;\n\n int prof = 0;\n if(cust >= 4){\n \n cust = cust - 4;\n cSit += 4;\n }else{\n cSit += cust;\n cust = 0;\n }\n prof = cSit*boardingCost - rotatn*runningCost ;\n if(prof > profit){\n profit = prof;\n prRotn = rotatn;\n } \n }\n while(cust > 0){\n rotatn++;\n\n int prof = 0;\n if(cust >= 4){\n cust = cust - 4;\n cSit += 4;\n }else{\n cSit += cust;\n cust = 0;\n }\n prof = cSit*boardingCost - rotatn*runningCost ;\n\n if(prof > profit){\n profit = prof;\n\n prRotn = rotatn;\n } \n }\n if(profit > 0) return prRotn;\n return -1;\n }\n}", + "title": "1599. Maximum Profit of Operating a Centennial Wheel", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are the operator of a Centennial Wheel that has four gondolas , and each gondola has room for up to four people . You have the ability to rotate the gondolas counterclockwise , which costs you runningCost dollars. You are given an array customers of length n where customers[i] is the number of new customers arriving just before the i th rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive . You cannot make customers wait if there is room in the gondola . Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including before serving all customers . If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation . Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == customers.length", + "1 <= n <= 10^5", + "0 <= customers[i] <= 50", + "1 <= boardingCost, runningCost <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:customers = [8,3], boardingCost = 5, runningCost = 6Output:3Explanation:The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.", + "image": "https://assets.leetcode.com/uploads/2020/09/09/wheeldiagram12.png" + }, + { + "text": "Example 2: Input:customers = [10,9,6], boardingCost = 6, runningCost = 4Output:7Explanation:1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.", + "image": null + }, + { + "text": "Example 3: Input:customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92Output:-1Explanation:1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "import sys\nMIN_INT = -sys.maxsize-1\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n maxx = MIN_INT\n rotate = total = ans = money = num = i = 0\n for i in range(len(customers)):\n total += customers[i]\n rotate = i+1\n if total >= 4:\n num += 4\n total -= 4\n else: \n num += total\n total = 0\n money = num * boardingCost - rotate * runningCost\n if maxx < money:\n maxx = money\n ans = rotate\n i+=1\n while(total > 0):\n rotate = i+1\n if total >= 4:\n num += 4\n total -= 4\n else: \n num += total\n total = 0\n money = num * boardingCost - rotate * runningCost\n if maxx < money:\n maxx = money\n ans = rotate\n i+=1\n if maxx < 0: return -1\n return ans\n", + "title": "1599. Maximum Profit of Operating a Centennial Wheel", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For a string sequence , a string word is k -repeating if word concatenated k times is a substring of sequence . The word 's maximum k -repeating value is the highest value k where word is k -repeating in sequence . If word is not a substring of sequence , word 's maximum k -repeating value is 0 . Given strings sequence and word , return the maximum k -repeating value of word in sequence . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= sequence.length <= 100", + "1 <= word.length <= 100", + "sequence and word contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sequence = \"ababc\", word = \"ab\"Output:2Explanation:\"abab\" is a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 2: Input:sequence = \"ababc\", word = \"ba\"Output:1Explanation:\"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 3: Input:sequence = \"ababc\", word = \"ac\"Output:0Explanation:\"ac\" is not a substring in \"ababc\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxRepeating(String s, String w) {\n if(w.length()>s.length()) return 0;\n int ans=0;\n StringBuilder sb=new StringBuilder(\"\");\n while(sb.length()<=s.length()){\n sb.append(w);\n if(s.contains(sb)) ans++;\n else break;\n }\n return ans;\n }\n}", + "title": "1668. Maximum Repeating Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "For a string sequence , a string word is k -repeating if word concatenated k times is a substring of sequence . The word 's maximum k -repeating value is the highest value k where word is k -repeating in sequence . If word is not a substring of sequence , word 's maximum k -repeating value is 0 . Given strings sequence and word , return the maximum k -repeating value of word in sequence . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= sequence.length <= 100", + "1 <= word.length <= 100", + "sequence and word contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:sequence = \"ababc\", word = \"ab\"Output:2Explanation:\"abab\" is a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 2: Input:sequence = \"ababc\", word = \"ba\"Output:1Explanation:\"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".", + "image": null + }, + { + "text": "Example 3: Input:sequence = \"ababc\", word = \"ac\"Output:0Explanation:\"ac\" is not a substring in \"ababc\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 15.28%) | Memory: 13.8 MB (Top 62.83%)\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n if word not in sequence:\n return 0\n\n left = 1\n right = len(sequence) // len(word)\n while left <= right:\n mid = (left + right) // 2\n if word * mid in sequence:\n left = mid + 1\n else:\n right = mid - 1\n\n return left - 1", + "title": "1668. Maximum Repeating Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the i th battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times . The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= batteries.length <= 10^5", + "1 <= batteries[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, batteries = [3,3,3]Output:4Explanation:Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example1-fit.png" + }, + { + "text": "Example 2: Input:n = 2, batteries = [1,1,1,1]Output:2Explanation:Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 70.5%) | Memory: 56.31 MB (Top 66.2%)\n\nclass Solution {\n\n private boolean canFit(int n, long k, int[] batteries) {\n long currBatSum = 0;\n long target = n * k;\n\n for (int bat : batteries) {\n if (bat < k) {\n currBatSum += bat;\n } else {\n currBatSum += k;\n }\n\n if (currBatSum >= target) {\n return true;\n }\n }\n\n return currBatSum >= target;\n\n }\n\n public long maxRunTime(int n, int[] batteries) {\n long batSum = 0;\n for (int bat : batteries) {\n batSum += bat;\n }\n \n long lower = 0;\n long upper = batSum / n;\n long res = -1;\n\n\t\t// binary search\n while (lower <= upper) {\n long mid = lower + (upper - lower) / 2;\n\n if (canFit(n, mid, batteries)) {\n res = mid;\n lower = mid + 1;\n } else {\n upper = mid - 1;\n }\n }\n\n return res;\n }\n}", + "title": "2141. Maximum Running Time of N Computers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the i th battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times . The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= batteries.length <= 10^5", + "1 <= batteries[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, batteries = [3,3,3]Output:4Explanation:Initially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example1-fit.png" + }, + { + "text": "Example 2: Input:n = 2, batteries = [1,1,1,1]Output:2Explanation:Initially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/01/06/example2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1321 ms (Top 44.04%) | Memory: 28.7 MB (Top 24.77%)\nclass Solution:\n def maxRunTime(self, n: int, batteries: List[int]) -> int:\n batteries.sort()\n total=sum(batteries)\n while batteries[-1]>total//n:\n n-=1\n total-=batteries.pop()\n return total//n", + "title": "2141. Maximum Running Time of N Computers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= s.length <= 500", + "The string s consists of characters '0' and '1' only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"011101\"Output:5Explanation:All possible ways of splitting s into two non-empty substrings are:\nleft = \"0\" and right = \"11101\", score = 1 + 4 = 5 \nleft = \"01\" and right = \"1101\", score = 1 + 3 = 4 \nleft = \"011\" and right = \"101\", score = 1 + 2 = 3 \nleft = \"0111\" and right = \"01\", score = 1 + 1 = 2 \nleft = \"01110\" and right = \"1\", score = 2 + 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:s = \"00111\"Output:5Explanation:When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 14.4%) | Memory: 44.28 MB (Top 5.7%)\n\nclass Solution {\n public int maxScore(String s) {\n int max =0;\n for(int i =0; i int:\n m0=0\n m1=0\n for i in s:\n if i==\"0\":\n m0+=1\n else:\n m1+=1\n if m0==0 or m1==0:\n return max(m0-1,m1-1)\n l=len(s)\n i=0\n max_=0\n c0=0\n c1=m1\n idx=-1\n while i = m . The arrays are 1-indexed . You begin with a score of 0 . You want to perform exactly m operations. On the i th operation (1-indexed) , you will: Return the maximum score after performing m operations. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose one integer x from either the start or the end of the array nums .", + "Add multipliers[i] * x to your score.", + "Remove x from the array nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], multipliers = [3,2,1]Output:14Explanation:An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]Output:102Explanation:An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 360 ms (Top 22.12%) | Memory: 168.2 MB (Top 19.45%)\nclass Solution {\n public int maximumScore(int[] nums, int[] multipliers) {\n int n = nums.length, m = multipliers.length;\n return helper(nums, multipliers, 0, 0, n-1, new Integer[m][m]);\n }\n\n public int helper(int[] nums, int[] multipliers, int idx, int left, int right, Integer[][] memo){\n if(idx == multipliers.length) return 0;\n if(memo[idx][left] != null) return memo[idx][left];\n\n int takeLeft = nums[left] * multipliers[idx] +\n helper(nums, multipliers, idx + 1, left + 1, right, memo);\n\n int takeRight = nums[right] * multipliers[idx] +\n helper(nums, multipliers, idx + 1, left, right - 1, memo);\n\n return memo[idx][left] = Math.max(takeLeft, takeRight);\n }\n}", + "title": "1770. Maximum Score from Performing Multiplication Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m . The arrays are 1-indexed . You begin with a score of 0 . You want to perform exactly m operations. On the i th operation (1-indexed) , you will: Return the maximum score after performing m operations. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose one integer x from either the start or the end of the array nums .", + "Add multipliers[i] * x to your score.", + "Remove x from the array nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3], multipliers = [3,2,1]Output:14Explanation:An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]Output:102Explanation:An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n = len(nums)\n m = len(multipliers)\n \n @lru_cache(None)\n #To Save Computed Result\n \n def X(i, left):\n \n if i==m:\n return 0\n \n return max ( (multipliers[i] * nums[left]) + X(i + 1, left + 1), \n (multipliers[i] * nums[n-1-(i-left)]) + X(i + 1, left) ) \n \n #Start from Zero operations\n return X(0,0)\n", + "title": "1770. Maximum Score from Performing Multiplication Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are playing a solitaire game with three piles of stones of sizes a ​​​​​​, b ,​​​​​​ and c ​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a ​​​​​, b ,​​​​​ and c ​​​​​, return the maximum score you can get. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a, b, c <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 4, c = 6Output:6Explanation:The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 4, c = 6Output:7Explanation:The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 8, c = 8Output:8Explanation:One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.30 MB (Top 77.67%)\n\nclass Solution {\n public int maximumScore(int a, int b, int c) {\n // Make sure a <= b <= c\n if (a>b) return maximumScore(b,a,c);\n if (b>c) return maximumScore(a,c,b);\n \n // if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c\n if (a+b<=c) return a+b;\n \n // if sum of smallest numbers is greater than c, then we can (a+b)/2 pairs after making c empty\n return c+(a+b-c)/2;\n }\n}\n", + "title": "1753. Maximum Score From Removing Stones", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing a solitaire game with three piles of stones of sizes a ​​​​​​, b ,​​​​​​ and c ​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a ​​​​​, b ,​​​​​ and c ​​​​​, return the maximum score you can get. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a, b, c <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 4, c = 6Output:6Explanation:The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 4, c = 6Output:7Explanation:The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 8, c = 8Output:8Explanation:One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted([a, b, c], reverse=True)\n ans = 0\n while a > 0 and b > 0:\n a -= 1\n b -= 1\n ans += 1\n a, b, c = sorted([a, b, c], reverse=True)\n return ans\n", + "title": "1753. Maximum Score From Removing Stones", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and two integers x and y . You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Remove substring \"ab\" and gain x points. For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "Remove substring \"ba\" and gain y points. For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" .", + "For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cdbcbbaaabab\", x = 4, y = 5Output:19Explanation:- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaaxybbaabb\", x = 5, y = 4Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumGain(String s, int x, int y) {\n \n int aCount = 0;\n int bCount = 0;\n int lesser = Math.min(x, y);\n int result = 0;\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c > 'b') {\n result += Math.min(aCount, bCount) * lesser;\n aCount = 0;\n bCount = 0;\n } else if (c == 'a') {\n if (x < y && bCount > 0) {\n bCount--;\n result += y;\n } else {\n aCount++;\n }\n } else {\n if (x > y && aCount > 0) {\n aCount--;\n result += x;\n } else {\n bCount++;\n };\n }\n }\n \n result += Math.min(aCount, bCount) * lesser;\n \n return result;\n }\n}\n", + "title": "1717. Maximum Score From Removing Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s and two integers x and y . You can perform two types of operations any number of times. Return the maximum points you can gain after applying the above operations on s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Remove substring \"ab\" and gain x points. For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "For example, when removing \"ab\" from \"c ab xbae\" it becomes \"cxbae\" .", + "Remove substring \"ba\" and gain y points. For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" .", + "For example, when removing \"ba\" from \"cabx ba e\" it becomes \"cabxe\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cdbcbbaaabab\", x = 4, y = 5Output:19Explanation:- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaaxybbaabb\", x = 5, y = 4Output:20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n a = 'a'\n b = 'b'\n if x < y:\n x, y = y, x\n a, b = b, a\n seen = Counter()\n ans = 0\n for c in s + 'x':\n if c in 'ab':\n if c == b and 0 < seen[a]:\n ans += x\n seen[a] -= 1\n else:\n seen[c] += 1\n else:\n ans += y * min(seen[a], seen[b])\n seen = Counter()\n\n return ans\n", + "title": "1717. Maximum Score From Removing Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers nums (0-indexed) and an integer k . The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1) . A good subarray is a subarray where i <= k <= j . Return the maximum possible score of a good subarray. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 2 * 10^4", + "0 <= k < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,7,4,5], k = 3Output:15Explanation:The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,5,4,5,4,1,1,1], k = 0Output:20Explanation:The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 75.40%) | Memory: 51.5 MB (Top 97.59%)\nclass Solution {\n public int maximumScore(int[] nums, int k) {\n int n = nums.length;\n int i = k - 1, j = k + 1;\n int min = nums[k];\n int ans = min;\n\n while(i >= 0 || j < n) {\n int v1 = 0, v2 = 0;\n int min1 = min, min2 = min;\n\n if(i >= 0) {\n min1 = Math.min(min, nums[i]);\n v1 = min1 * (j - i);\n }\n\n if(j < n) {\n min2 = Math.min(min, nums[j]);\n v2 = min2 * (j - i);\n }\n\n if(v1 > v2) {\n --i;\n ans = Math.max(v1, ans);\n min = Math.min(min1, min);\n }\n else {\n ++j;\n ans = Math.max(ans, v2);\n min = Math.min(min, min2);\n }\n }\n\n return ans;\n }\n}", + "title": "1793. Maximum Score of a Good Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of integers nums (0-indexed) and an integer k . The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1) . A good subarray is a subarray where i <= k <= j . Return the maximum possible score of a good subarray. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 2 * 10^4", + "0 <= k < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,4,3,7,4,5], k = 3Output:15Explanation:The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,5,4,5,4,1,1,1], k = 0Output:20Explanation:The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextSmallerElement(self, nums):\n nextSmaller = [None] * len(nums)\n stack = [[-sys.maxsize, -1]]\n for i in range(len(nums)-1, -1, -1):\n while nums[i] <= stack[-1][0]:\n stack.pop()\n nextSmaller[i] = stack[-1][1]\n stack.append([nums[i], i])\n return nextSmaller\n \n \n def previousSmallerElement(self, nums):\n previousSmaller = [None] * len(nums)\n stack = [[-sys.maxsize, -1]]\n for i in range(len(nums)):\n while nums[i] <= stack[-1][0]:\n stack.pop()\n previousSmaller[i] = stack[-1][1]\n stack.append([nums[i], i])\n return previousSmaller\n \n def maximumScore(self, nums: List[int], k: int) -> int:\n nextSmaller = self.nextSmallerElement(nums)\n previousSmaller = self.previousSmallerElement(nums)\n\n score = 0\n for idx, num in enumerate(nums):\n\t\t\t# previousSmaller[idx] (let's say i) and nextSmaller[idx] (let's say j) ensures that the element present at idx is the minimum in range (i -> j)\n i = previousSmaller[idx]\n i += 1\n j = nextSmaller[idx]\n if j == -1:\n j = len(nums)\n j -= 1\n if i <= k <= j:\n score = max(score, num * (j-i+1))\n \n return score\n \n", + "title": "1793. Maximum Score of a Good Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i . You are also given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . A node sequence is valid if it meets the following conditions: The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4 . If no such sequence exists, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "There is an edge connecting every pair of adjacent nodes in the sequence.", + "No node appears more than once in the sequence." + ], + "examples": [ + { + "text": "Example 1: Input:scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]Output:24Explanation:The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.", + "image": "https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" + }, + { + "text": "Example 2: Input:scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]Output:-1Explanation:The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.", + "image": "https://assets.leetcode.com/uploads/2022/03/17/ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 99.80%) | Memory: 131.6 MB (Top 18.36%)\nclass Solution {\n public int maximumScore(int[] scores, int[][] edges) {\n int n = scores.length;\n\n int[][] count = new int[n][6];\n for (int[] edge : edges) {\n int s = edge[0];\n int e = edge[1];\n if (count[s][0] == 0) {\n count[s][1] = e;\n count[s][0] = scores[e];\n } else if (count[s][2] == 0) {\n if (scores[e] > count[s][0]) {\n count[s][3] = count[s][1];\n count[s][2] = count[s][0];\n count[s][1] = e;\n count[s][0] = scores[e];\n } else {\n count[s][3] = e;\n count[s][2] = scores[e];\n }\n } else if (scores[e] > count[s][4]) {\n if (scores[e] > count[s][0]) {\n count[s][5] = count[s][3];\n count[s][4] = count[s][2];\n count[s][3] = count[s][1];\n count[s][2] = count[s][0];\n count[s][1] = e;\n count[s][0] = scores[e];\n } else if (scores[e] > count[s][2]) {\n count[s][5] = count[s][3];\n count[s][4] = count[s][2];\n count[s][3] = e;\n count[s][2] = scores[e];\n } else {\n count[s][5] = e;\n count[s][4] = scores[e];\n }\n }\n if (count[e][0] == 0) {\n count[e][1] = s;\n count[e][0] = scores[s];\n } else if (count[e][2] == 0) {\n if (scores[s] > count[e][0]) {\n count[e][3] = count[e][1];\n count[e][2] = count[e][0];\n count[e][1] = s;\n count[e][0] = scores[s];\n } else {\n count[e][3] = s;\n count[e][2] = scores[s];\n }\n } else if (scores[s] > count[e][4]) {\n if (scores[s] > count[e][0]) {\n count[e][5] = count[e][3];\n count[e][4] = count[e][2];\n count[e][3] = count[e][1];\n count[e][2] = count[e][0];\n count[e][1] = s;\n count[e][0] = scores[s];\n } else if (scores[s] > count[e][2]) {\n count[e][5] = count[e][3];\n count[e][4] = count[e][2];\n count[e][3] = s;\n count[e][2] = scores[s];\n } else {\n count[e][5] = s;\n count[e][4] = scores[s];\n }\n }\n }\n int max = -1;\n for (int[] edge : edges) {\n int s = edge[0];\n int e = edge[1];\n int pos = scores[s] + scores[e];\n int p1 = -1;\n int p2 = -1;\n boolean fine = true;\n if (count[s][1] == e) {\n if (count[s][2] == 0)\n fine = false;\n p1 = count[s][3];\n if (count[s][4] > 0)\n p2 = count[s][5];\n } else if (count[s][3] == e) {\n if (count[s][0] == 0)\n fine = false;\n p1 = count[s][1];\n if (count[s][4] > 0)\n p2 = count[s][5];\n } else {\n p1 = count[s][1];\n if (count[s][0] == 0)\n fine = false;\n if (count[s][2] > 0)\n p2 = count[s][3];\n }\n int p3 = -1;\n int p4 = -1;\n if (count[e][1] == s) {\n if (count[e][2] == 0)\n fine = false;\n p3 = count[e][3];\n if (count[e][4] > 0)\n p4 = count[e][5];\n } else if (count[e][3] == s) {\n if (count[e][0] == 0)\n fine = false;\n p3 = count[e][1];\n if (count[e][4] > 0)\n p4 = count[e][5];\n } else {\n p3 = count[e][1];\n if (count[e][0] == 0)\n fine = false;\n if (count[e][2] > 0)\n p4 = count[e][3];\n }\n if (fine) {\n if (p1 == p3) {\n if (p4 > -1)\n max = Math.max(max, pos + scores[p1] + scores[p4]);\n if (p2 > -1)\n max = Math.max(max, pos + scores[p1] + scores[p2]);\n } else {\n max = Math.max(max, pos + scores[p1] + scores[p3]);\n }\n }\n }\n return max;\n }\n}", + "title": "2242. Maximum Score of a Node Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected graph with n nodes, numbered from 0 to n - 1 . You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i . You are also given a 2D integer array edges where edges[i] = [a i , b i ] denotes that there exists an undirected edge connecting nodes a i and b i . A node sequence is valid if it meets the following conditions: The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of 4 . If no such sequence exists, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "There is an edge connecting every pair of adjacent nodes in the sequence.", + "No node appears more than once in the sequence." + ], + "examples": [ + { + "text": "Example 1: Input:scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]Output:24Explanation:The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.", + "image": "https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" + }, + { + "text": "Example 2: Input:scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]Output:-1Explanation:The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.", + "image": "https://assets.leetcode.com/uploads/2022/03/17/ex2.png" + } + ], + "follow_up": null, + "solution": "# defaultdict is the same as Python's usual dictionary, but if an\n# element doesn't exist, you can give it a default value to initialize with. \nfrom collections import defaultdict\n# nlargest(n, l) - returns the n largest values of collection l.\nfrom heapq import nlargest\n# \"product\" is a function that takes two collections and \n# returns every pair between them.\n# product(\"ab\", \"cd\") = [(a, c), (a, d), (b, c), (b, d)].\nfrom itertools import product\n\nLet V be the number of nodes and E = len(edges).\n# Time complexity: O(V + E) - we iterate through every vertex \n# and every edge a constant number of times.\n# Space complexity: O(V) - we save a constant \n# number of neighbors (3) for every node.\nclass Solution:\n def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n # Turn the edge list into an adjacency graph.\n m = defaultdict(list)\n for u, v in edges:\n m[u].append((scores[v], v)) \n m[v].append((scores[u], u))\n \n # Cut down all neighbors of each node to the three\n # that have the highest value.\n for u in m:\n m[u] = nlargest(3, m[u])\n\n ret = -1\n # Consider each edge to potentially be (B, C) for a quadruplet.\n for b, c in edges:\n # For every possible A and D in the neighbors of B and C...\n for (aWeight, a), (dWeight, d) in product(m[b], m[c]):\n # ... If we have no redundant nodes, it's a quadruplet.\n # Since it's the highest value quadruplet we could\n # possibly make with B and C, this solution is always accurate.\n if a not in [b, c] and d not in [b, c] and a != d:\n ret = max(ret, scores[b] + scores[c] + aWeight + dWeight)\n \n return ret\n", + "title": "2242. Maximum Score of a Node Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 , both of length n . You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right] . You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2) , where sum(arr) is the sum of all the elements in the array arr . Return the maximum possible score . A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2 , nums1 becomes [1, 12,13 ,4,5] and nums2 becomes [11, 2,3 ,14,15] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [60,60,60], nums2 = [10,90,10]Output:210Explanation:Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]Output:220Explanation:Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,11,13], nums2 = [1,1,1]Output:31Explanation:We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maximumsSplicedArray(int[] nums1, int[] nums2) {\n int ans = 0, sum1 = 0, sum2 = 0;\n\n for (int i : nums1) sum1 += i;\n for (int i : nums2) sum2 += i;\n\n ans = Math.max(sum1, sum2);\n\n int first = 0, second = 0, max1 = 0, max2 = 0;\n\n for (int i = 0; i < nums1.length; i++) {\n first += (nums2[i] - nums1[i]);\n second += (nums1[i] - nums2[i]);\n \n max1 = Math.max(max1, first);\n max2 = Math.max(max2, second);\n \n if (first < 0) first = 0;\n if (second < 0) second = 0;\n }\n\n ans = Math.max(ans, sum1 + max1);\n ans = Math.max(ans, sum2 + max2);\n\n return ans;\n }\n}\n", + "title": "2321. Maximum Score Of Spliced Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 , both of length n . You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right] . You may choose to apply the mentioned operation once or not do anything. The score of the arrays is the maximum of sum(nums1) and sum(nums2) , where sum(arr) is the sum of all the elements in the array arr . Return the maximum possible score . A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2 , nums1 becomes [1, 12,13 ,4,5] and nums2 becomes [11, 2,3 ,14,15] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [60,60,60], nums2 = [10,90,10]Output:210Explanation:Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]Output:220Explanation:Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,11,13], nums2 = [1,1,1]Output:31Explanation:We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n\t\tnums3 = [0]*n\n\t\tnums4 = [0]*n\n\t\tfor i in range(n):\n\t\t\tnums3[i] = nums1[i]-nums2[i]\n\t\t\tnums4[i] = nums2[i]-nums1[i]\n\t\tmaxsubseq1 = maxsubseq2 = 0\n\t\tv1 = v2 = 0 \n\t\t# use kadane algorithm to solve this max subseq problem\n\t\tfor i in range(n):\n\t\t\tmaxsubseq1 = max(maxsubseq1 + nums3[i], nums3[i])\n\t\t\tmaxsubseq2 = max(maxsubseq2 + nums4[i], nums4[i])\n\t\t\tv1 = max(v1, maxsubseq1)\n\t\t\tv2 = max(v2, maxsubseq2)\n\t\t_sum1 = sum(nums1)\n\t\t_sum2 = sum(nums2)\n\t\treturn max(_sum1 + v2, _sum2 + v1)\n", + "title": "2321. Maximum Score Of Spliced Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of words , list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters ( words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a' , 'b' , 'c' , ... , 'z' is given by score[0] , score[1] , ... , score[25] respectively. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 14", + "1 <= words[i].length <= 15", + "1 <= letters.length <= 100", + "letters[i].length == 1", + "score.length == 26", + "0 <= score[i] <= 10", + "words[i] , letters[i] contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]Output:23Explanation:Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]Output:27Explanation:Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]Output:0Explanation:Letter \"e\" can only be used once.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 32.14%) | Memory: 44.3 MB (Top 16.39%)\nclass Solution {\n int[] memo;\n public int maxScoreWords(String[] words, char[] letters, int[] score) {\n memo = new int[words.length];\n Arrays.fill(memo,-1);\n HashMap hm = new HashMap<>();\n for(char c : letters){\n int t = hm.getOrDefault(c,0);\n t++;\n hm.put(c,t);\n }\n //return dp(words,hm,score,0,0);\n int res = dp(words,hm,score,0,0);\n //for(int i : memo) System.out.println(i);\n return res;\n }\n\n public int dp(String[] words, Map hm, int[] score, int index, int cs){//cs-current Score\n if(index==words.length) return cs;\n if(memo[index]!=-1) return memo[index];\n HashMap temp = new HashMap<>(hm);\n int tcs=cs; //tcs = temporory current score\n\n for(char c : words[index].toCharArray()){\n int t = temp.getOrDefault(c,0);\n t--;\n if(t<0){\n return dp(words,hm,score,index+1,cs);\n // memo[index] = dp(words,hm,score,index+1,cs);\n // return memo[index];\n }\n tcs+=score[c-'a'];\n temp.put(c,t);\n }\n return Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // memo[index] = Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // return memo[index];\n }\n}", + "title": "1255. Maximum Score Words Formed by Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a list of words , list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters ( words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a' , 'b' , 'c' , ... , 'z' is given by score[0] , score[1] , ... , score[25] respectively. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 14", + "1 <= words[i].length <= 15", + "1 <= letters.length <= 100", + "letters[i].length == 1", + "score.length == 26", + "0 <= score[i] <= 10", + "words[i] , letters[i] contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]Output:23Explanation:Score a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]Output:27Explanation:Score a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]Output:0Explanation:Letter \"e\" can only be used once.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 61 ms (Top 55.33%) | Memory: 17.40 MB (Top 11.89%)\n\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n\n f, ans = lambda x : sum(score[ord(c) - 97] for c in x), 0\n\n def dfs(words,letters, tally):\n nonlocal ans\n \n for i in range(len(words)):\n cWord=Counter(words[i])\n\t\t\t\t\n if all(letters[c] >= cWord[c] for c in cWord):\n dfs(words[i+1:], letters - cWord, tally + f(words[i]))\n\n ans = max(ans,tally)\n return ans\n\n return dfs(words, Counter(letters), 0)\n", + "title": "1255. Maximum Score Words Formed by Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a m x n matrix mat and an integer threshold , return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 300", + "0 <= mat[i][j] <= 10^4", + "0 <= threshold <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4Output:2Explanation:The maximum side length of square with sum less than 4 is 2 as shown.", + "image": "https://assets.leetcode.com/uploads/2019/12/05/e1.png" + }, + { + "text": "Example 2: Input:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSideLength(int[][] mat, int threshold) {\n int rows = mat.length;\n int cols = mat[0].length;\n int[][] preSum = new int[rows+1][cols+1];\n for(int i=1;i<=rows;i++){\n for(int j=1;j<=cols;j++){\n preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + mat[i-1][j-1];\n }\n }\n int lo=1,hi=Math.min(rows,cols);\n while(lo<=hi){\n int m = (lo+hi)>>1;\n if(fun(preSum,threshold,rows,cols,m)) lo=m+1;\n else hi=m-1;\n }\n return lo-1;\n }\n private boolean fun(int[][] preSum, int maxSum,int rows, int cols, int size){\n for(int r=size;r<=rows;r++){\n for(int c=size;c<=cols;c++){\n int sum = preSum[r][c] - preSum[r-size][c] - preSum[r][c-size] + preSum[r-size][c-size];\n if(sum <= maxSum) return true;\n }\n }\n return false;\n }\n}\n", + "title": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a m x n matrix mat and an integer threshold , return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 300", + "0 <= mat[i][j] <= 10^4", + "0 <= threshold <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4Output:2Explanation:The maximum side length of square with sum less than 4 is 2 as shown.", + "image": "https://assets.leetcode.com/uploads/2019/12/05/e1.png" + }, + { + "text": "Example 2: Input:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n # prefix matrix\n dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)]\n \n for i in range(1, len(mat)+1):\n for j in range(1, len(mat[0])+1):\n dp[i][j] = dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1] + mat[i-1][j-1]\n \n #bin search\n max_side = 0\n for i in range(1, len(mat) + 1):\n for j in range(1, len(mat[0]) + 1):\n if min(i, j) < max_side:\n continue\n left = 0\n right = min(i,j)\n while left <= right:\n mid = (left+right)//2\n pref_sum = dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid]\n if pref_sum <= threshold:\n max_side = max(max_side, mid)\n left = mid + 1\n else:\n right = mid - 1\n return max_side\n \n", + "title": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer finalSum . Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers . If no valid split exists for finalSum , return an empty list . You may return the integers in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given finalSum = 12 , the following splits are valid (unique positive even integers summing up to finalSum ): (12) , (2 + 10) , (2 + 4 + 6) , and (4 + 8) . Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique." + ], + "examples": [ + { + "text": "Example 1: Input:finalSum = 12Output:[2,4,6]Explanation:The following are valid splits:(12),(2 + 10),(2 + 4 + 6), and(4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.", + "image": null + }, + { + "text": "Example 2: Input:finalSum = 7Output:[]Explanation:There are no valid splits for the given finalSum.\nThus, we return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:finalSum = 28Output:[6,8,2,12]Explanation:The following are valid splits:(2 + 26),(6 + 8 + 2 + 12), and(4 + 24).(6 + 8 + 2 + 12)has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List maximumEvenSplit(long finalSum) {\n List res = new ArrayList();\n //odd sum cannot be divided into even numbers\n if(finalSum % 2 != 0) {\n return res;\n }\n //Greedy approach, try to build the total sum using minimum unique even nos\n long currNum = 2;\n long remainingSum = finalSum;\n //as long as we can add subtract this number from remaining sum\n while(currNum <= remainingSum) {\n res.add(currNum);\n remainingSum -= currNum;//reducing remaining sum\n currNum += 2;//next even number\n }\n //now, remaining sum cannot be fulfilled by any larger even number\n //so extract the largest even number we added to the last index of res, and make it even larger by adding this current remaining sum\n //add remaining sum to the last element\n long last = res.remove(res.size()-1);\n res.add(last+remainingSum);\n return res;\n }\n}\n", + "title": "2178. Maximum Split of Positive Even Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer finalSum . Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers . If no valid split exists for finalSum , return an empty list . You may return the integers in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given finalSum = 12 , the following splits are valid (unique positive even integers summing up to finalSum ): (12) , (2 + 10) , (2 + 4 + 6) , and (4 + 8) . Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique." + ], + "examples": [ + { + "text": "Example 1: Input:finalSum = 12Output:[2,4,6]Explanation:The following are valid splits:(12),(2 + 10),(2 + 4 + 6), and(4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.", + "image": null + }, + { + "text": "Example 2: Input:finalSum = 7Output:[]Explanation:There are no valid splits for the given finalSum.\nThus, we return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:finalSum = 28Output:[6,8,2,12]Explanation:The following are valid splits:(2 + 26),(6 + 8 + 2 + 12), and(4 + 24).(6 + 8 + 2 + 12)has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1817 ms (Top 5.05%) | Memory: 26.8 MB (Top 41.50%)\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n l=[]\n if finalSum%2!=0:\n return l\n else:\n s=0\n i=2 # even pointer 2, 4, 6, 8, 10, 12...........\n while(s> 1);\n ans = Math.max(ans, cnt + dfs(nxt, i + 1));\n }\n }\n return f[seat][i] = ans;\n }\n}", + "title": "1349. Maximum Students Taking Exam", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "seats contains only characters '.' and '#'.", + "m == seats.length", + "n == seats[i].length", + "1 <= m <= 8", + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n  [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n  [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]Output:4Explanation:Teacher can place 4 students in available seats so they don't cheat on the exam.", + "image": "https://assets.leetcode.com/uploads/2020/01/29/image.png" + }, + { + "text": "Example 2: Input:seats = [[\".\",\"#\"],\n  [\"#\",\"#\"],\n  [\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\".\",\"#\"]]Output:3Explanation:Place all students in available seats.", + "image": null + }, + { + "text": "Example 3: Input:seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\".\",\".\",\"#\",\".\",\".\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\"#\",\".\",\".\",\".\",\"#\"]]Output:10Explanation:Place students in available seats in column 1, 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n m, n = len(seats), len(seats[0])\n match = [[-1]*n for _ in range(m)]\n def dfs(i, j, visited):\n for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]:\n if 0 <= x < m and 0 <= y < n and seats[x][y] == \".\" and (x, y) not in visited:\n visited.add((x, y))\n if match[x][y] == -1 or dfs(*match[x][y], visited):\n match[x][y] = (i, j)\n match[i][j] = (x, y)\n return True\n return False\n def max_matching():\n cnt = 0\n for i in range(m):\n for j in range(0,n,2):\n if seats[i][j] == '.' and match[i][j] == -1:\n visited = set()\n cnt += dfs(i, j, visited)\n return cnt\n\t\t#returns the number of elements of the maximum independent set in the bipartite set\n return sum(seats[i][j]=='.' for i in range(m) for j in range(n)) - max_matching()", + "title": "1349. Maximum Students Taking Exam", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , find the contiguous subarray (containing at least one number) which has the largest sum and return its sum . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,1,-3,4,-1,2,1,-5,4]Output:6Explanation:[4,-1,2,1] has the largest sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,4,-1,7,8]Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubArray(int[] nums) {\n int n = nums.length;\n int currmax = 0;\n int gmax = nums[0];\n for(int i=0;i int:\n def kadane(i):\n if F[i] != None:\n return F[i]\n F[i] = max(nums[i],kadane(i-1) + nums[i])\n return F[i]\n n = len(nums)\n F = [None for _ in range(n)]\n F[0] = nums[0]\n kadane(n-1)\n return max(F)", + "title": "53. Maximum Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The min-product of an array is equal to the minimum value in the array multiplied by the array's sum . Given an array of integers nums , return the maximum min-product of any non-empty subarray of nums . Since the answer may be large, return it modulo 10^9 + 7 . Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the array [3,2,5] (minimum value is 2 ) has a min-product of 2 * (3+2+5) = 2 * 10 = 20 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,2]Output:14Explanation:The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,3,1,2]Output:18Explanation:The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,1,5,6,4,2]Output:60Explanation:The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSumMinProduct(int[] nums) {\n int mod=(int)Math.pow(10,9)+7;\n int n=nums.length;\n \n //next smaller on left\n int[] left=new int[n];\n Stack st=new Stack<>();\n left[0]=-1;\n st.push(0);\n for(int i=1;i0 && nums[st.peek()]>=nums[i]){\n st.pop();\n }\n \n if(st.size()==0) left[i]=-1;\n else left[i]=st.peek();\n \n st.push(i);\n }\n \n //next smaller on right\n int[] right=new int[n];\n st=new Stack<>();\n right[n-1]=n;\n st.push(n-1);\n for(int i=n-2;i>=0;i--){\n while(st.size()>0 && nums[st.peek()]>=nums[i]) st.pop();\n \n if(st.size()>0) right[i]=st.peek();\n else right[i]=n;\n \n st.push(i);\n }\n \n long[] prefixSum=new long[n];\n prefixSum[0]=nums[0];\n for(int i=1;i= 0; j--){\n leftPrefixSum = Math.max(leftPrefixSum, prefixSum[i-1] -prefixSum[j]);\n }\n \n int rightPrefixSum = 0;\n // find max in i to n\n for(int j = i+1; j <= n; j++){\n rightPrefixSum = Math.max(rightPrefixSum, prefixSum[j] -prefixSum[i]);\n } \n ans = Math.max(ans, leftPrefixSum + rightPrefixSum);\n }\n }\n return Math.max(ans, prefixSum[n]);\n }\n}\n", + "title": "1186. Maximum Subarray Sum with One Deletion", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,-2,0,3]Output:4Explanation:Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,-2,-2,3]Output:3Explanation:We just choose [3] and it's the maximum sum.", + "image": null + }, + { + "text": "Example 3: Input:arr = [-1,-1,-1,-1]Output:-1Explanation:The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSum(self, arr: List[int]) -> int:\n n = len(arr)\n if n ==1:\n return arr[0]\n dpLeft = [-10**4-1 for _ in range(n)]\n dpLeft[0] = arr[0]\n i = 1 \n while i < n :\n dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])\n i += 1\n dpRight = [-10**4-1 for _ in range(n)]\n dpRight[-1] = arr[-1]\n j = n-2 \n while j >= 0:\n dpRight[j] = max(arr[j],dpRight[j+1]+arr[j])\n j -= 1\n k = 0\n maxi = -10**4-1\n while k < n:\n # if we take it \n curr_maxi_with = dpRight[k] + dpLeft[k] - arr[k]\n \n if k==0:\n curr_maxi_without = dpRight[k+1]\n elif k==n-1:\n curr_maxi_without = dpLeft[k-1]\n else:\n if dpLeft[k-1]>=0 and dpRight[k+1]>=0:\n curr_maxi_without = dpRight[k+1] + dpLeft[k-1]\n else:\n curr_maxi_without = max(dpLeft[k-1],dpRight[k+1])\n \n maxi= max(maxi,curr_maxi_without, curr_maxi_with)\n k += 1\n \n return maxi \n\n", + "title": "1186. Maximum Subarray Sum with One Deletion", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree root , return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST) . Assume a BST is defined as follows: Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png", + "https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" + ], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]Output:20Explanation:Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:root = [4,3,null,1,2]Output:2Explanation:Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.", + "image": null + }, + { + "text": "Example 3: Input:root = [-4,-2,-5]Output:0Explanation:All values are negatives. Return an empty BST.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 57.67%) | Memory: 71 MB (Top 82.51%)\nclass Solution {\n\n int ans = 0;\n public int maxSumBST(TreeNode root) {\n solve(root);\n return ans;\n }\n // int[] = { min, max, sum };\n private int[] solve(TreeNode root) {\n if(root == null)\n return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 };\n\n int[] left = solve(root.left);\n int[] right = solve(root.right);\n\n if(root.val > left[1] && root.val < right[0]) {\n int sum = left[2] + right[2] + root.val;\n ans = Math.max(ans, sum);\n return new int[] { Math.min(left[0], root.val), Math.max(root.val, right[1]), sum };\n }\n\n return new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };\n }\n\n}", + "title": "1373. Maximum Sum BST in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree root , return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST) . Assume a BST is defined as follows: Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png", + "https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" + ], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]Output:20Explanation:Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:root = [4,3,null,1,2]Output:2Explanation:Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.", + "image": null + }, + { + "text": "Example 3: Input:root = [-4,-2,-5]Output:0Explanation:All values are negatives. Return an empty BST.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 22.49%) | Memory: 35.50 MB (Top 99.31%)\n\nclass Solution:\n def maxSumBST(self, root: TreeNode) -> int:\n res = 0\n def traverse(root):\n '''return status_of_bst, size_of_bst, left_bound, right_bound'''\n nonlocal res\n if not root: return 1, 0, None, None # this subtree is empty\n \n ls, l, ll, lr = traverse(root.left)\n rs, r, rl, rr = traverse(root.right)\n \n if ((ls == 2 and lr < root.val) or ls == 1) and ((rs == 2 and rl > root.val) or rs == 1):\n\t\t # this subtree is a BST\n size = root.val + l + r\n res = max(res, size)\n return 2, size, (ll if ll is not None else root.val), (rr if rr is not None else root.val)\n return 0, None, None, None # this subtree is not a BST\n \n traverse(root)\n return res\n", + "title": "1373. Maximum Sum BST in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]Output:3Explanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]Output:10Explanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]Output:-2Explanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 96.02%) | Memory: 64.4 MB (Top 41.15%)\nclass Solution {\n public int maxSubarraySumCircular(int[] nums) {\n int ans = kadane(nums);\n int sum = 0;\n for (int i = 0; i < nums.length; i++) {\n sum += nums[i];\n nums[i] = -nums[i];\n }\n int kadane_sum = kadane(nums) + sum;\n if (kadane_sum == 0) {\n return ans;\n }\n return Math.max(ans, kadane_sum);\n }\n public int kadane(int[] nums) {\n int sum = 0;\n int ans = Integer.MIN_VALUE;\n for (int i : nums) {\n sum += i;\n ans = Math.max(ans, sum);\n if (sum < 0) {\n sum = 0;\n }\n }\n return ans;\n }\n}", + "title": "918. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]Output:3Explanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]Output:10Explanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]Output:-2Explanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 729 ms (Top 66.43%) | Memory: 18.9 MB (Top 76.46%)\nclass Solution:\n\n def kadanes(self,nums):\n\n #kadanes algo\n\n max_till_now = nums[0]\n curr_max = nums[0]\n\n for i in range(1,len(nums)):\n curr_max = max(curr_max+nums[i],nums[i])\n max_till_now = max(max_till_now,curr_max)\n\n return max_till_now\n\n def maxSubarraySumCircular(self, nums: List[int]) -> int:\n\n #there will be 2 case\n #case 1 : our max subarray is not wrapping i.e not circular\n #case 2: our max subarray is wrapping i.e circular\n\n # case 1 is easy to find\n # to find case 2 what we can do is if we multiply each nums element by -1 and\n # on that find kadanes then we will get sum of elements which is not part of maxsubarray in case2 (not part because we negate)\n # now subtract this newmax in case 2 from total nums sum, we get wrapping sum\n # max of case1 and case is our ans\n\n total = sum(nums)\n\n nonwrappingsum = self.kadanes(nums)\n\n # edge case when all elements are -ve then return max negative\n if nonwrappingsum<0:\n return nonwrappingsum\n\n #negate\n for i in range(len(nums)):\n nums[i]*=-1\n\n wrappingsum = total-(-self.kadanes(nums)) #-ve because originally it was negated\n\n return max(nonwrappingsum,wrappingsum)\n", + "title": "918. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We have an array of integers, nums , and an array of requests where requests[i] = [start i , end i ] . The i th request asks for the sum of nums[start i ] + nums[start i + 1] + ... + nums[end i - 1] + nums[end i ] . Both start i and end i are 0-indexed . Return the maximum total sum of all requests among all permutations of nums . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^5", + "0 <= nums[i] <= 10^5", + "1 <= requests.length <= 10^5", + "requests[i].length == 2", + "0 <= start i <= end i < n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], requests = [[1,3],[0,1]]Output:19Explanation:One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6], requests = [[0,1]]Output:11Explanation:A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]Output:47Explanation:A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 87 ms (Top 13.18%) | Memory: 134 MB (Top 44.96%)\nclass Solution {\n public int maxSumRangeQuery(int[] nums, int[][] requests) {\n int n = nums.length;\n int[] pref = new int[n];\n for(int i=0;i nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5,6], requests = [[0,1]]Output:11Explanation:A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]Output:47Explanation:A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1436 ms (Top 61.0%) | Memory: 50.25 MB (Top 70.4%)\n\nclass Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n count = [0] * len(nums)\n for i, j in requests:\n count[i] += 1\n if j + 1 < len(count):\n count[j+1] -= 1\n cur = 0\n for i in range(len(count)):\n count[i] += cur\n cur = count[i]\n return sum(n * c for n, c in zip(sorted(nums, reverse=True), sorted(count, reverse=True))) % (10 ** 9 + 7)", + "title": "1589. Maximum Sum Obtained of Any Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval ( 0-indexed ). If there are multiple answers, return the lexicographically smallest one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] < 2 16", + "1 <= k <= floor(nums.length / 3)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,6,7,5,1], k = 2Output:[0,3,5]Explanation:Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,2,1,2,1,2,1], k = 2Output:[0,2,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSumOfThreeSubarrays(int[] nums, int k) {\n int n = nums.length;\n int[] ans = new int[3];\n int[] pre = new int[n];\n int[] third = new int[n];\n for (int i=0;i=2*k;--i){ // find the best index for the last part\n int cur = pre[i+k-1]-pre[i-1];\n max=Math.max(max, cur);\n third[i]=cur==max?i:third[i+1];\n }\n for (int i=k,first=0,fmax=0,max=0;i+2*k-1 fmax){ // compute the best index for the first part on the fly\n fmax=cur;\n first=i-k;\n }\n int a = fmax; // first\n int b = pre[i+k-1]-pre[i-1]; // middle\n int c = pre[third[i+k]+k-1]-pre[third[i+k]-1]; // last\n if (a+b+c>max){\n max=a+b+c;\n ans[0]=first;\n ans[1]=i;\n ans[2]=third[i+k];\n }\n }\n return ans;\n }\n}\n", + "title": "689. Maximum Sum of 3 Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , find three non-overlapping subarrays of length k with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval ( 0-indexed ). If there are multiple answers, return the lexicographically smallest one. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "1 <= nums[i] < 2 16", + "1 <= k <= floor(nums.length / 3)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,6,7,5,1], k = 2Output:[0,3,5]Explanation:Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,2,1,2,1,2,1], k = 2Output:[0,2,4]", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\nfrom functools import lru_cache\n\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n n = len(nums)\n windows = list(accumulate(nums))\n windows = [windows[i+k-1]-(windows[i-1] if i>0 else 0) for i in range(len(windows)-k+1)]\n \n @lru_cache(None)\n def dfs(i, t):\n if t == 0:\n return 0, []\n if i >= len(windows):\n return float('-inf'), []\n cost1, sol1 = dfs(i+k, t-1)\n cost2, sol2 = dfs(i+1, t)\n if windows[i] + cost1 < cost2:\n return cost2, sol2\n return windows[i] + cost1, [i]+sol1\n return dfs(0, 3)[1]", + "title": "689. Maximum Sum of 3 Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and two integers firstLen and secondLen , return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen . The array with length firstLen could occur before or after the array with length secondLen , but they have to be non-overlapping. A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= firstLen, secondLen <= 1000", + "2 <= firstLen + secondLen <= 1000", + "firstLen + secondLen <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2Output:20Explanation:One choice of subarrays is [9] with length 1, and [6,5] with length 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2Output:29Explanation:One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3Output:31Explanation:One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {\n int []dp1=new int[nums.length];\n int []dp2=new int[nums.length];\n \n int sum=0;\n for(int i=0;i=0;i--){\n if(i+secondLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+secondLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n int max=0;\n \n for(int i=firstLen-1;i=0;i--){\n if(i+firstLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+firstLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n max=0;\n \n for(int i=secondLen-1;i int:\n n = len(nums)\n p = [0]\n for el in nums:\n p.append(p[-1] + el)\n msum = 0\n for f, s in [(firstLen, secondLen), (secondLen, firstLen)]:\n for i in range(f - 1, n - s + 1):\n for j in range(i + 1, n - s + 1):\n l = p[i + 1] - p[i - f + 1]\n r = p[j + s] - p[j]\n msum = max(msum, l + r)\n return msum\n", + "title": "1031. Maximum Sum of Two Non-Overlapping Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer num . You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 2736Output:7236Explanation:Swap the number 2 and the number 7.", + "image": null + }, + { + "text": "Example 2: Input:num = 9973Output:9973Explanation:No swap.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.26%) | Memory: 41.4 MB (Top 23.64%)\nclass Solution {\n public int maximumSwap(int num) {\n char str[]=String.valueOf(num).toCharArray();\n char arr[]=str.clone();\n Arrays.sort(arr);\n int i=0;\n int j=str.length-1;\n while(i=0 && arr[j]==str[i]){i++;j--;}\n int search=j;\n if(i==str.length) return num;\n j=str.length-1;\n while(arr[search]!=str[j]){j--;}\n\n char c=str[i];\n str[i]=str[j];\n str[j]=c;\n return Integer.parseInt(new String(str));\n }\n}", + "title": "670. Maximum Swap", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer num . You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 2736Output:7236Explanation:Swap the number 2 and the number 7.", + "image": null + }, + { + "text": "Example 2: Input:num = 9973Output:9973Explanation:No swap.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumSwap(self, num: int) -> int:\n digits = [int(x) for x in str(num)]\n n = len(digits)\n \n for i in range(n):\n maxx = digits[i]\n indx = i\n \n for j in range(i+1,n):\n if digits[j]>=maxx and digits[j]!=digits[i]:\n maxx = digits[j]\n indx = j\n \n if indx!=i:\n digits[i],digits[indx] = digits[indx],digits[i]\n \n #only one swap allowed\n return \"\".join([str(x) for x in digits])\n \n #already sorted\n return num\n", + "title": "670. Maximum Swap", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n , where flowers[i] is the number of flowers already planted in the i th garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers , which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target , full , and partial . A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of complete gardens multiplied by full .", + "The minimum number of flowers in any of the incomplete gardens multiplied by partial . If there are no incomplete gardens, then this value will be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1Output:14Explanation:Alice can plant\n- 2 flowers in the 0thgarden\n- 3 flowers in the 1stgarden\n- 1 flower in the 2ndgarden\n- 1 flower in the 3rdgarden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.", + "image": null + }, + { + "text": "Example 2: Input:flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6Output:30Explanation:Alice can plant\n- 3 flowers in the 0thgarden\n- 0 flowers in the 1stgarden\n- 0 flowers in the 2ndgarden\n- 2 flowers in the 3rdgarden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) {\n int n = flowers.length;\n long[] prefix = new long[n + 1];\n Arrays.sort(flowers);\n for (int i = 0; i < n; ++i) prefix[i + 1] = prefix[i] + Math.min(flowers[i], target);\n long res = 0;\n for (int c = 0, i = n - 1; c <= n; ++c) {\n long remain = prefix[n] - prefix[n - c] + newFlowers - c * (long) target, min = 0;\n if (0 > remain) break;\n i = Math.min(i, n - c - 1);\n while (0 <= i && (target <= flowers[i] || flowers[i] * (long) (i + 1) - prefix[i + 1] > remain)) i--;\n if (0 <= i) {\n long dif = flowers[i] * (long) (i + 1) - prefix[i + 1];\n min = Math.min(target - 1, flowers[i] + (remain - dif) / (i + 1));\n if (i + 1 < n - c) min = Math.min(min, flowers[i + 1]);\n }\n res = Math.max(res, c * (long) full + min * (long) partial);\n }\n return res;\n }\n}\n", + "title": "2234. Maximum Total Beauty of the Gardens", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n , where flowers[i] is the number of flowers already planted in the i th garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers , which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target , full , and partial . A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of complete gardens multiplied by full .", + "The minimum number of flowers in any of the incomplete gardens multiplied by partial . If there are no incomplete gardens, then this value will be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1Output:14Explanation:Alice can plant\n- 2 flowers in the 0thgarden\n- 3 flowers in the 1stgarden\n- 1 flower in the 2ndgarden\n- 1 flower in the 3rdgarden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.", + "image": null + }, + { + "text": "Example 2: Input:flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6Output:30Explanation:Alice can plant\n- 3 flowers in the 0thgarden\n- 0 flowers in the 1stgarden\n- 0 flowers in the 2ndgarden\n- 2 flowers in the 3rdgarden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 865 ms (Top 94.12%) | Memory: 32.60 MB (Top 7.84%)\n\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n \n\t\t# move out already completed garden\n already_complete = 0\n temp = []\n for f in flowers:\n if f >= target:\n already_complete += 1\n else:\n temp.append(f)\n\n max_beauty = 0\n \n flowers = temp\n flowers.sort()\n \n presum = [0] + list(accumulate(flowers))\n N = len(flowers)\n \n dp_arr = []\n \n for i in range(N+1):\n # iterate all index: left part is all partial, right part (>= i) is all complete\n \n # update the dp arr for binary search below\n if i < N:\n dp_arr.append((i+1) * flowers[i] - presum[i+1])\n \n right_sum = presum[-1] - presum[i]\n right_count = N - i\n \n # if can't make the right part all complete, go to next index\n if right_sum + newFlowers < right_count * target:\n continue\n \n # remaining flowers after making right part all complete\n rem_flowers = newFlowers - (right_count * target - right_sum)\n \n # binary search to find the maximum possible min flowers in the left part (named 'min_partial')\n if i == 0:\n min_partial = 0\n else:\n j = min(bisect.bisect_right(dp_arr, rem_flowers) - 1, i-1)\n min_partial = min((rem_flowers + presum[j+1]) // (j+1), target-1)\n \n complete = right_count + already_complete\n max_beauty = max(max_beauty, complete * full + min_partial * partial)\n\n \n return max_beauty\n", + "title": "2234. Maximum Total Beauty of the Gardens", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1 . You are also given a 2D integer array roads where roads[i] = [a i , b i ] denotes that there exists a bidirectional road connecting cities a i and b i . You need to assign each city with an integer value from 1 to n , where each value can only be used once . The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "1 <= roads.length <= 5 * 10^4", + "roads[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no duplicate roads." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]Output:43Explanation:The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,3],[2,4],[1,3]]Output:20Explanation:The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 55.58%) | Memory: 124.3 MB (Top 45.11%)\nclass Solution {\n public long maximumImportance(int n, int[][] roads) {\n long ans = 0, x = 1;\n long degree[] = new long[n];\n for(int road[] : roads){\n degree[road[0]]++;\n degree[road[1]]++;\n }\n Arrays.sort(degree);\n for(long i : degree) ans += i * (x++) ;\n return ans;\n }\n}", + "title": "2285. Maximum Total Importance of Roads", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1 . You are also given a 2D integer array roads where roads[i] = [a i , b i ] denotes that there exists a bidirectional road connecting cities a i and b i . You need to assign each city with an integer value from 1 to n , where each value can only be used once . The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "1 <= roads.length <= 5 * 10^4", + "roads[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i", + "There are no duplicate roads." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]Output:43Explanation:The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 5, roads = [[0,3],[2,4],[1,3]]Output:20Explanation:The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.", + "image": "https://assets.leetcode.com/uploads/2022/04/07/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1313 ms (Top 92.99%) | Memory: 41.50 MB (Top 72.32%)\n\nclass Solution:\n def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n Arr = [0] * n # i-th city has Arr[i] roads\n for A,B in roads:\n Arr[A] += 1 # Each road increase the road count\n Arr[B] += 1\n Arr.sort() # Cities with most road should receive the most score\n summ = 0\n for i in range(len(Arr)):\n summ += Arr[i] * (i+1) # Multiply city roads with corresponding score\n \n return summ\n", + "title": "2285. Maximum Total Importance of Roads", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array grid of size m x n , where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Horizontal movement means moving in either the left or right direction.", + "Vertical movement means moving in either the up or down direction." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]Output:3Explanation:The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.", + "image": "https://assets.leetcode.com/uploads/2022/03/23/ex1new2.jpg" + }, + { + "text": "Example 2: Input:grid = [[4,3,2],[7,6,1],[8,8,8]]Output:0Explanation:The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 84 ms (Top 75.61%) | Memory: 82.50 MB (Top 26.83%)\n\nclass Solution {\n public int maxTrailingZeros(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[][] two = new int[m][n];\n int[][] five = new int[m][n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n two[i][j] = getFactorNum(grid[i][j], 2);\n five[i][j] = getFactorNum(grid[i][j], 5);\n }\n }\n \n int[][] left2 = new int[m][n];\n int[][] left5 = new int[m][n];\n for (int i = 0; i < m; ++i) {\n int sum2 = 0;\n int sum5 = 0;\n for (int j = 0; j < n; ++j) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n left2[i][j] = sum2;\n left5[i][j] = sum5;\n }\n }\n \n int[][] right2 = new int[m][n];\n int[][] right5 = new int[m][n];\n for (int i = 0; i < m; ++i) {\n int sum2 = 0;\n int sum5 = 0;\n for (int j = n - 1; j >= 0; --j) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n right2[i][j] = sum2;\n right5[i][j] = sum5;\n }\n }\n \n int[][] up2 = new int[m][n];\n int[][] up5 = new int[m][n];\n for (int j = 0; j < n; ++j) {\n int sum2 = 0;\n int sum5 = 0;\n for (int i = 0; i < m; ++i) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n up2[i][j] = sum2;\n up5[i][j] = sum5;\n }\n }\n \n int[][] down2 = new int[m][n];\n int[][] down5 = new int[m][n];\n for (int j = 0; j < n; ++j) {\n int sum2 = 0;\n int sum5 = 0;\n for (int i = m - 1; i >= 0; --i) {\n sum2 += two[i][j];\n sum5 += five[i][j];\n down2[i][j] = sum2;\n down5[i][j] = sum5;\n }\n }\n \n int res = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n // left-up\n if (i != 0 || j != 0) {\n int cur = Math.min(left2[i][j] + up2[i][j] - two[i][j], left5[i][j] + up5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // up-right\n if (i != 0 || j != n - 1) {\n int cur = Math.min(right2[i][j] + up2[i][j] - two[i][j], right5[i][j] + up5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // right-down\n if (i != m - 1 || j != n - 1) {\n int cur = Math.min(right2[i][j] + down2[i][j] - two[i][j], right5[i][j] + down5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n \n // down-left\n if (i != m - 1 || j != 0) {\n int cur = Math.min(left2[i][j] + down2[i][j] - two[i][j], left5[i][j] + down5[i][j] - five[i][j]);\n res = Math.max(res, cur);\n }\n }\n }\n return res;\n }\n \n private int getFactorNum(int input, int factor) {\n int res = 0;\n while (input != 0 && input % factor == 0) {\n ++res;\n input /= factor;\n }\n return res;\n }\n}\n", + "title": "2245. Maximum Trailing Zeros in a Cornered Path", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D integer array grid of size m x n , where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Horizontal movement means moving in either the left or right direction.", + "Vertical movement means moving in either the up or down direction." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]Output:3Explanation:The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.", + "image": "https://assets.leetcode.com/uploads/2022/03/23/ex1new2.jpg" + }, + { + "text": "Example 2: Input:grid = [[4,3,2],[7,6,1],[8,8,8]]Output:0Explanation:The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/ex2.jpg" + } + ], + "follow_up": null, + "solution": "import numpy as np\n\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n A = np.array(grid)\n def cumdivs(d):\n D = sum(A % d**i == 0 for i in range(1, 10))\n return D.cumsum(0) + D.cumsum(1) - D\n return max(np.minimum(cumdivs(2), cumdivs(5)).max()\n for _ in range(4)\n if [A := np.rot90(A)])\n", + "title": "2245. Maximum Trailing Zeros in a Cornered Path", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]Output:6Explanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]Output:7Explanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]Output:100001Explanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int pairSum(ListNode head) {\n if (head == null) {\n return 0;\n }\n if (head.next == null) {\n return head.val;\n }\n ListNode slow = head;\n ListNode fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n slow = reverse(slow);\n fast = head;\n int sum = Integer.MIN_VALUE;\n while (slow != null) {\n sum = Math.max(slow.val + fast.val, sum);\n slow = slow.next;\n fast = fast.next;\n }\n return sum;\n }\n \n public ListNode reverse(ListNode node) {\n if (node == null) {\n return null;\n }\n ListNode current = node;\n ListNode previous = null;\n while (current != null) {\n ListNode next = current.next;\n current.next = previous;\n previous = current;\n current = next;\n }\n return previous;\n }\n}\n", + "title": "2130. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]Output:6Explanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]Output:7Explanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]Output:100001Explanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2246 ms (Top 8.54%) | Memory: 54.1 MB (Top 58.68%)\nclass Solution:\n def pairSum(self, head: Optional[ListNode]) -> int:\n nums = []\n curr = head\n while curr:\n nums.append(curr.val)\n curr = curr.next\n\n N = len(nums)\n res = 0\n for i in range(N // 2):\n res = max(res, nums[i] + nums[N - i - 1])\n return res", + "title": "2130. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are assigned to put some amount of boxes onto one truck . You are given a 2D array boxTypes , where boxTypes[i] = [numberOfBoxes i , numberOfUnitsPerBox i ] : You are also given an integer truckSize , which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize . Return the maximum total number of units that can be put on the truck. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "numberOfBoxes i is the number of boxes of type i .", + "numberOfUnitsPerBox i is the number of units in each box of the type i ." + ], + "examples": [ + { + "text": "Example 1: Input:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4Output:8Explanation:There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.", + "image": null + }, + { + "text": "Example 2: Input:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10Output:91", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int maximumUnits(int[][] boxTypes, int truckSize) {\n\t\tArrays.sort(boxTypes, Comparator.comparingInt(o -> -o[1]));\n\t\tint ans = 0, i = 0, n = boxTypes.length;\n\t\twhile (i < n && truckSize > 0) {\n\t\t\tint maxi = Math.min(boxTypes[i][0], truckSize);\n\t\t\tans += maxi * boxTypes[i][1];\n\t\t\ti++;\n\t\t\ttruckSize -= maxi;\n\t\t}\n\t\treturn ans;\n\t}\n}", + "title": "1710. Maximum Units on a Truck", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are assigned to put some amount of boxes onto one truck . You are given a 2D array boxTypes , where boxTypes[i] = [numberOfBoxes i , numberOfUnitsPerBox i ] : You are also given an integer truckSize , which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize . Return the maximum total number of units that can be put on the truck. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "numberOfBoxes i is the number of boxes of type i .", + "numberOfUnitsPerBox i is the number of units in each box of the type i ." + ], + "examples": [ + { + "text": "Example 1: Input:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4Output:8Explanation:There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.", + "image": null + }, + { + "text": "Example 2: Input:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10Output:91", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumUnits(self, B: List[List[int]], T: int) -> int:\n B.sort(key=lambda x: x[1], reverse=True)\n ans = 0\n for b,n in B:\n boxes = min(b, T)\n ans += boxes * n\n T -= boxes\n if T == 0: return ans\n return ans\n", + "title": "1710. Maximum Units on a Truck", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a very large integer n , represented as a string,​​​​​​ and an integer digit x . The digits in n and the digit x are in the inclusive range [1, 9] , and n may represent a negative number. You want to maximize n 's numerical value by inserting x anywhere in the decimal representation of n ​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n ​​​​​​ after the insertion . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if n = 73 and x = 6 , it would be best to insert it between 7 and 3 , making n = 763 .", + "If n = -55 and x = 2 , it would be best to insert it before the first 5 , making n = -255 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"99\", x = 9Output:\"999\"Explanation:The result is the same regardless of where you insert 9.", + "image": null + }, + { + "text": "Example 2: Input:n = \"-13\", x = 2Output:\"-123\"Explanation:You can make n one of {-213, -123, -132}, and the largest of those three is -123.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String maxValue(String n, int x) {\n StringBuilder res= new StringBuilder();\n int i=0, j=0;\n if(n.charAt(0)=='-'){\n res.append(n.charAt(0));\n for(j=1; j= x){ \n res.append(ch);\n }else{\n res.append(x);\n res.append(ch);\n res.append(n.substring(i+1));\n break;\n }\n }\n if(i==n.length()){\n res.append(x);\n }\n }\n return res.toString();\n }\n}", + "title": "1881. Maximum Value after Insertion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a very large integer n , represented as a string,​​​​​​ and an integer digit x . The digits in n and the digit x are in the inclusive range [1, 9] , and n may represent a negative number. You want to maximize n 's numerical value by inserting x anywhere in the decimal representation of n ​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n ​​​​​​ after the insertion . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if n = 73 and x = 6 , it would be best to insert it between 7 and 3 , making n = 763 .", + "If n = -55 and x = 2 , it would be best to insert it before the first 5 , making n = -255 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"99\", x = 9Output:\"999\"Explanation:The result is the same regardless of where you insert 9.", + "image": null + }, + { + "text": "Example 2: Input:n = \"-13\", x = 2Output:\"-123\"Explanation:You can make n one of {-213, -123, -132}, and the largest of those three is -123.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValue(self, n: str, x: int) -> str:\n if int(n)>0:\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])>=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n else:\n n = n[1:]\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])<=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n ans = \"-\"+ans\n \n return ans\n \n", + "title": "1881. Maximum Value after Insertion", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given three positive integers: n , index , and maxSum . You want to construct an array nums ( 0-indexed ) that satisfies the following conditions: Return nums[index] of the constructed array . Note that abs(x) equals x if x >= 0 , and -x otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length == n", + "nums[i] is a positive integer where 0 <= i < n .", + "abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1 .", + "The sum of all the elements of nums does not exceed maxSum .", + "nums[index] is maximized ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, index = 2, maxSum = 6Output:2Explanation:nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].", + "image": null + }, + { + "text": "Example 2: Input:n = 6, index = 1, maxSum = 10Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "\n/* Intuition:\nAs the number of elements is 10^9 so we can't actually create the array\nAnd by seeing the limit we can judge that the complexity should be O(logn)\nSo it will become obvious that binary search can only help to solve this prob\n\nWe have to put the maximum possible value in the index position and then all \nthe values to its right and left should decrease by 1 until the value reaches 1\nfor Ex in n = 6, index = 1, maxSum = 10\n\nour index at 1 should be 3 and the array will look like\n2 3 2 1 1\n+ max - - same\n\nmeans you have to make an array which is strictly increasing and it attains its max (which is answer)\nthen strictly decreasing till value becomes 1 and then continues it as 1. Like\n1 ... 1, 2, 3, 4, 5, 6(if answer is 6), 5, 4, 3, 2, 1, .... 1\n\nWhy this solution?\nBecause our objective is to maximize our index position value i.e. ans. So to maximize it\nwe all the other elements other than index position should be as low as possible (so that sum of our array\nis less than maxSum), which will lead to this solution of \"Get the max element on index given and decrease strictly\non both sides of the array till our value is 1, and then continue it to 1\"\n*/\n\nclass Solution {\n public int maxValue(int n, int index, int maxSum) {\n // Setting the initial values is very important, our ans can never be 0 so set low as 1\n int low = 1, mid = 0, high = 1000000000;\n while(low <= high) {\n mid = (low + high) / 2;\n \n // If our ans (which is mid) is making the sum of array more than maxSum means we have to decrease our high\n if(calcAns(mid, index, n) > maxSum) { \n high = mid - 1;\n } \n \n // If our ans (which is mid) is so low that even ans + 1 (i.e. mid + 1) is giving better result that means increase our low\n else if(calcAns(mid + 1, index, n) <= maxSum) {\n low = mid + 1;\n } \n \n // If our ans (== mid) is such that the sum of array is less than maxSum and even increasing 1 to mid will result the total\n // sum to increase from maxSum, that signifies that we have the answer as mid\n else {\n break;\n }\n }\n \n return mid;\n }\n \n public int calcAns(int max, int idx, int n) {\n \n // This method will give you answer of the setup where our peak element is ans at index idx and we have n elements\n // So we have two part of array one is the left part (1, 1... 2, 3 ... max - 1) and then (max, max - 1, max - 2, 1 ... 1)\n // so you can think of it as we have few extraOnes on both left and right parts and then an AP array which goes upto max\n \n // Left part I have taken till max - 1 and right part I have taken from max.\n // calcPart takes (first value of AP, number of elements)\n \n long ret = calcPart(max - 1, idx) + calcPart(max, n - idx);\n if(ret > 1000000000) {\n // Seeing the constraints, if you chose to take high mid value then it might overflow from int. And our answer can never\n // be greater than 10^9 so limit it to that.\n return 1000000001;\n } else {\n \n // This is the sum of the array where max is taken as answer\n return (int)ret;\n }\n }\n \n public long calcPart(int a, int num) {\n \n // For AP we need first element (which is \"a\") and last element (which we calculate in an)\n long an = 0, extraOnes = 0;\n long ans = 0;\n if(num >= a) {\n \n // If total number of elements is more than a which means it will look like\n // a, a - 1, a - 2, ... , 2, 1 ... followed by extraOnes\n an = 1;\n extraOnes = num - a;\n } else if(num < a) {\n \n // If total number of elements is such that we never reach 1 as our last element means\n // a, a - 1, a - 2 ... a - x, then extraOnes will be 0\n extraOnes = 0;\n an = a - num + 1;\n }\n \n // Sum of AP where we know first and last element = ((first + last) * n) / 2\n ans = ((an + a) * (a - an + 1)) / 2;\n \n // Add extra ones\n ans += extraOnes;\n \n return ans;\n }\n}\n", + "title": "1802. Maximum Value at a Given Index in a Bounded Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given three positive integers: n , index , and maxSum . You want to construct an array nums ( 0-indexed ) that satisfies the following conditions: Return nums[index] of the constructed array . Note that abs(x) equals x if x >= 0 , and -x otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length == n", + "nums[i] is a positive integer where 0 <= i < n .", + "abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1 .", + "The sum of all the elements of nums does not exceed maxSum .", + "nums[index] is maximized ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, index = 2, maxSum = 6Output:2Explanation:nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].", + "image": null + }, + { + "text": "Example 2: Input:n = 6, index = 1, maxSum = 10Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n l = 1\n r = int(1e9)\n ans = 0\n\n while l<=r:\n mid = (l+r)//2\n total = 0\n\n # add left numbers\n if mid>=index+1:\n first = mid-index\n size = index+1\n total += first*size + size*(size-1)/2\n else:\n total += mid*(mid+1)/2\n total += index+1-mid\n\n\n # add right numbers\n size = n-index\n if mid >= size:\n last = mid - (n-index-1)\n total += last*size + size*(size-1)/2\n else:\n total += mid*(mid+1)/2\n total += (size-mid) \n\n # deduct mid because it was added twice \n total -= mid\n \n if total <= maxSum:\n ans = max(ans, mid)\n l = mid+1\n else:\n r = mid-1\n\n return ans", + "title": "1802. Maximum Value at a Given Index in a Bounded Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles , where piles[i] is a list of integers denoting the composition of the i th pile from top to bottom , and a positive integer k , return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == piles.length", + "1 <= n <= 1000", + "1 <= piles[i][j] <= 10^5", + "1 <= k <= sum(piles[i].length) <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [[1,100,3],[7,8,9]], k = 2Output:101Explanation:The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.", + "image": "https://assets.leetcode.com/uploads/2019/11/09/e1.png" + }, + { + "text": "Example 2: Input:piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7Output:706Explanation:The maximum total can be obtained if we choose all coins from the last pile.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 223 ms (Top 73.40%) | Memory: 55.8 MB (Top 38.07%)\nclass Solution {\n public int maxValueOfCoins(List> piles, int k) {\n int n = piles.size();\n int[][] ans = new int[n+1][2001];\n Collections.sort(piles, (List a, List b) -> b.size() - a.size());\n for(int i = 1; i <= k; i++) {\n for(int j = 1; j <= n; j++) {\n int sizeOfPile = piles.get(j-1).size();\n List pile = piles.get(j-1);\n int sum = 0;\n ans[j][i] = ans[j-1][i];\n for(int l = 1; l <= Math.min(i, sizeOfPile); l++) {\n // Take K from this pile + remaining from previous piles\n sum += pile.get(l-1);\n int rem = i - l;\n ans[j][i] = Math.max(ans[j][i], sum + ans[j-1][rem]);\n }\n }\n }\n\n return ans[n][k];\n }\n}", + "title": "2218. Maximum Value of K Coins From Piles", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations. In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet. Given a list piles , where piles[i] is a list of integers denoting the composition of the i th pile from top to bottom , and a positive integer k , return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == piles.length", + "1 <= n <= 1000", + "1 <= piles[i][j] <= 10^5", + "1 <= k <= sum(piles[i].length) <= 2000" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [[1,100,3],[7,8,9]], k = 2Output:101Explanation:The above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.", + "image": "https://assets.leetcode.com/uploads/2019/11/09/e1.png" + }, + { + "text": "Example 2: Input:piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7Output:706Explanation:The maximum total can be obtained if we choose all coins from the last pile.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n n = len(piles)\n prefixSum = []\n for i in range(n):\n temp = [0]\n for j in range(len(piles[i])):\n temp.append(temp[-1] + piles[i][j])\n prefixSum.append(temp)\n \n dp = [[0] * (k + 1) for _ in range(n)]\n for j in range(1, k + 1):\n if j < len(prefixSum[0]):\n dp[0][j] = prefixSum[0][j]\n \n for i in range(1, n):\n for j in range(1, k + 1):\n for l in range(len(prefixSum[i])):\n if l > j:\n break\n dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l])\n return dp[n - 1][k]\n", + "title": "2218. Maximum Value of K Coins From Piles", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array tiles where tiles[i] = [l i , r i ] represents that every tile j in the range l i <= j <= r i is colored white. You are also given an integer carpetLen , the length of a single carpet that can be placed anywhere . Return the maximum number of white tiles that can be covered by the carpet . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 5 * 10^4", + "tiles[i].length == 2", + "1 <= l i <= r i <= 10^9", + "1 <= carpetLen <= 10^9", + "The tiles are non-overlapping ." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10Output:9Explanation:Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/example1drawio3.png" + }, + { + "text": "Example 2: Input:tiles = [[10,11],[1,1]], carpetLen = 2Output:2Explanation:Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/03/24/example2drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 71.1%) | Memory: 71.05 MB (Top 47.1%)\n\nclass Solution\n{\n public int maximumWhiteTiles(int[][] tiles, int carpetLen)\n {\n Arrays.sort(tiles,(a,b)->{return a[0]-b[0];});\n int x = 0;\n int y = 0;\n long maxCount = 0;\n long count = 0;\n \n while(y < tiles.length && x <= y)\n {\n long start = tiles[x][0];\n long end = tiles[y][1];\n \n if(end-start+1 <= carpetLen) \n {\n count += tiles[y][1] - tiles[y][0]+1;\n maxCount = Math.max(maxCount,count);\n y++;\n }\n else \n {\n long midDist = start+carpetLen-1;\n long s = tiles[y][0];\n long e = tiles[y][1];\n if(midDist <= e && midDist >= s) maxCount = Math.max(maxCount,count+midDist-s+1);\n count -= tiles[x][1] - tiles[x][0] + 1;\n x++;\n }\n }\n return (int)maxCount;\n }\n}", + "title": "2271. Maximum White Tiles Covered by a Carpet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array tiles where tiles[i] = [l i , r i ] represents that every tile j in the range l i <= j <= r i is colored white. You are also given an integer carpetLen , the length of a single carpet that can be placed anywhere . Return the maximum number of white tiles that can be covered by the carpet . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= tiles.length <= 5 * 10^4", + "tiles[i].length == 2", + "1 <= l i <= r i <= 10^9", + "1 <= carpetLen <= 10^9", + "The tiles are non-overlapping ." + ], + "examples": [ + { + "text": "Example 1: Input:tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10Output:9Explanation:Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.", + "image": "https://assets.leetcode.com/uploads/2022/03/25/example1drawio3.png" + }, + { + "text": "Example 2: Input:tiles = [[10,11],[1,1]], carpetLen = 2Output:2Explanation:Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.", + "image": "https://assets.leetcode.com/uploads/2022/03/24/example2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n tiles.sort()\n\t\t#j: window index\n j = cover = res = 0\n for i in range(len(tiles)):\n\t\t\t#slide the window as far as we can to cover fully the intervals with the carpet\n while j int:\n q = deque([(root, 0)])\n res = 0\n\n while q:\n res = max(res, q[-1][1] - q[0][1] + 1)\n for _ in range(len(q)):\n curr, pos = q.popleft()\n\n if curr.left:\n q.append((curr.left, pos*2))\n if curr.right:\n q.append((curr.right, pos*2 + 1))\n\n return res", + "title": "662. Maximum Width of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j] . The width of such a ramp is j - i . Given an integer array nums , return the maximum width of a ramp in nums . If there is no ramp in nums , return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,0,8,2,1,5]Output:4Explanation:The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,1,0,1,9,4,0,4,1]Output:7Explanation:The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxWidthRamp(int[] nums) {\n Stack s = new Stack<>();\n int res = 0;\n for(int i = 0; i< nums.length; i++){\n if(!s.isEmpty() && nums[s.peek()]<=nums[i]) {\n res = Math.max(res, i-s.peek());\n continue;\n }\n s.push(i);\n }\n int i = nums.length-1;\n while(!s.isEmpty() && i>=0){\n if(nums[s.peek()]<=nums[i]){\n res = Math.max(res, i-s.peek());\n s.pop();\n }else{\n i--;\n }\n }\n return res;\n }\n}\n", + "title": "962. Maximum Width Ramp", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j] . The width of such a ramp is j - i . Given an integer array nums , return the maximum width of a ramp in nums . If there is no ramp in nums , return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,0,8,2,1,5]Output:4Explanation:The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,8,1,0,1,9,4,0,4,1]Output:7Explanation:The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 635 ms (Top 30.72%) | Memory: 21.1 MB (Top 46.08%)\nclass Solution:\n def maxWidthRamp(self, nums: List[int]):\n st=[]\n n=len(nums)\n for i in range(n):\n if len(st)==0 or nums[st[-1]]>=nums[i]:\n st.append(i)\n print(st)\n max_idx=-1\n for j in range(n-1,-1,-1):\n while len(st) and nums[st[-1]]<=nums[j]:\n prev=st.pop()\n max_idx=max(max_idx,j-prev)\n\n return max_idx\n", + "title": "962. Maximum Width Ramp", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one operation, select any non-negative integer x and an index i , then update nums[i] to be equal to nums[i] AND (nums[i] XOR x) . Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,4,6]Output:7Explanation:Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,9,2]Output:11Explanation:Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int i=0; i int:\n res=0\n for i in nums:\n res |= i\n return res\n", + "title": "2317. Maximum XOR After Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a sorted array nums of n non-negative integers and an integer maximumBit . You want to perform the following query n times : Return an array answer , where answer[i] is the answer to the i th query . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums.length == n", + "1 <= n <= 10^5", + "1 <= maximumBit <= 20", + "0 <= nums[i] < 2 maximumBit", + "nums ​​​ is sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,1,3], maximumBit = 2Output:[0,3,2,3]Explanation: The queries are answered as follows:\n1stquery: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n2ndquery: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n3rdquery: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n4thquery: nums = [0], k = 3 since 0 XOR 3 = 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,4,7], maximumBit = 3Output:[5,2,6,5]Explanation: The queries are answered as follows:\n1stquery: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n2ndquery: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n3rdquery: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n4thquery: nums = [2], k = 5 since 2 XOR 5 = 7.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,1,2,2,5,7], maximumBit = 3Output:[4,3,6,4,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 736 ms (Top 100.0%) | Memory: 34.71 MB (Top 50.5%)\n\nclass Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n ans = [(1 << maximumBit) - 1]\n for n in nums:\n ans.append(ans[-1] ^ n)\n\n return ans[len(ans)-1:0:-1]", + "title": "1829. Maximum XOR for Each Query", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the maximum result of nums[i] XOR nums[j] , where 0 <= i <= j < n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^5", + "0 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,10,5,25,2,8]Output:28Explanation:The maximum result is 5 XOR 25 = 28.", + "image": null + }, + { + "text": "Example 2: Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]Output:127", + "image": null + } + ], + "follow_up": null, + "solution": "class Node {\n Node[] links = new Node[2];\n \n public Node () {\n \n }\n \n boolean containsKey(int ind) {\n return links[ind] != null;\n }\n \n Node get(int ind) {\n return links[ind];\n }\n \n void put(int ind, Node node) {\n links[ind] = node;\n }\n}\n\nclass Trie {\n private static Node root;\n \n public Trie() {\n root = new Node();\n }\n \n public static void insert(int num) {\n Node node = root;\n for (int i = 31; i >= 0; i--) {\n int bit = (num >> i) & 1;\n if (!node.containsKey(bit)) {\n node.put(bit, new Node());\n }\n node = node.get(bit);\n }\n }\n \n public static int getMax(int num) {\n Node node = root;\n int maxNum = 0;\n \n for (int i = 31; i >= 0; i--) {\n int bit = (num >> i) & 1;\n if (node.containsKey(1 - bit)) {\n maxNum = maxNum | (1 << i);\n node = node.get(1 - bit);\n }\n else {\n node = node.get(bit);\n }\n }\n return maxNum;\n }\n}\n\n\nclass Solution {\n public int findMaximumXOR(int[] nums) {\n Trie trie = new Trie();\n \n for (int i = 0; i < nums.length; i++) {\n trie.insert(nums[i]);\n }\n \n int maxi = 0;\n for (int i = 0; i < nums.length; i++) {\n maxi = Math.max(maxi, trie.getMax(nums[i]));\n }\n return maxi;\n }\n}\n", + "title": "421. Maximum XOR of Two Numbers in an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the maximum result of nums[i] XOR nums[j] , where 0 <= i <= j < n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^5", + "0 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,10,5,25,2,8]Output:28Explanation:The maximum result is 5 XOR 25 = 28.", + "image": null + }, + { + "text": "Example 2: Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]Output:127", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef findMaximumXOR(self, nums: List[int]) -> int:\n\t\tTrieNode = lambda: defaultdict(TrieNode)\n\t\troot = TrieNode()\n\t\tfor n in nums:\n\t\t\tcur = root\n\t\t\tfor i in range(31,-1,-1):\n\t\t\t\tbit = 1 if n&(1< {\n public int compare(int[] a, int[] b) {\n return Integer.compare(a[1], b[1]);\n }\n }\n \n class Node {\n Node zero;\n Node one;\n \n public Node() {\n this.zero = null;\n this.one = null;\n }\n }\n \n public int[] maximizeXor(int[] nums, int[][] queries) {\n Arrays.sort(nums);\n \n int len = queries.length;\n int[][] queryWithIndex = new int[len][3];\n for(int i = 0; i < len; i++) {\n queryWithIndex[i][0] = queries[i][0];\n queryWithIndex[i][1] = queries[i][1];\n queryWithIndex[i][2] = i;\n }\n Arrays.sort(queryWithIndex, new QueryComparator());\n \n int numId = 0;\n int[] ans = new int[len];\n \n Node root = new Node();\n for(int i = 0; i < len; i++) {\n while(numId < nums.length && nums[numId] <= queryWithIndex[i][1]) {\n addNumToTree(nums[numId], root);\n numId++;\n }\n \n ans[queryWithIndex[i][2]] = maxXOR(queryWithIndex[i][0], root);\n }\n \n return ans;\n }\n \n private void addNumToTree(int num, Node node) {\n for(int i = 31; i >= 0; i--) {\n int digit = (num >> i) & 1;\n if (digit == 1) {\n if (node.one == null) {\n node.one = new Node();\n }\n node = node.one;\n } else {\n if (node.zero == null) {\n node.zero = new Node();\n }\n node = node.zero;\n }\n }\n }\n \n private int maxXOR(int num, Node node) {\n if (node.one == null && node.zero == null) {\n return -1;\n }\n\n int ans = 0;\n for(int i = 31; i >= 0 && node != null; i--) {\n int digit = (num >> i) & 1;\n if (digit == 1) {\n if (node.zero != null) {\n ans += (1 << i);\n node = node.zero;\n } else {\n node = node.one;\n }\n } else {\n if (node.one != null) {\n ans += (1 << i);\n node = node.one;\n } else {\n node = node.zero;\n }\n }\n }\n \n return ans;\n }\n}\n", + "title": "1707. Maximum XOR With an Element From Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [x i , m i ] . The answer to the i th query is the maximum bitwise XOR value of x i and any element of nums that does not exceed m i . In other words, the answer is max(nums[j] XOR x i ) for all j such that nums[j] <= m i . If all elements in nums are larger than m i , then the answer is -1 . Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the i th query. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length, queries.length <= 10^5", + "queries[i].length == 2", + "0 <= nums[j], x i , m i <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]Output:[3,3,7]Explanation:1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]Output:[15,-1,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Trie:\n def __init__(self):\n self.root = {}\n \n def insert(self, num):\n p = self.root\n for i in range(31, -1, -1):\n cur = (num >> i) & 1\n if cur not in p:\n p[cur] = {}\n p = p[cur]\n \n def query(self, num):\n if not self.root: \n return -1\n p, ans = self.root, 0\n for i in range(31, -1, -1):\n cur = (num >> i) & 1\n if 1 - cur in p:\n p = p[1 - cur]\n ans |= (1 << i)\n else:\n p = p[cur]\n return ans\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted(enumerate(queries), key=lambda x: x[1][1])\n trie = Trie()\n ans = [-1] * len(queries)\n j = 0\n for i, (x, m) in queries:\n while j < len(nums) and nums[j] <= m:\n trie.insert(nums[j])\n j += 1\n ans[i] = trie.query(x)\n return ans\n", + "title": "1707. Maximum XOR With an Element From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array arr , return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10 -5 of the actual answer will be considered accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "20 <= arr.length <= 1000", + "arr.length is a multiple of 20 .", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]Output:2.00000Explanation:After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]Output:4.00000", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]Output:4.77778", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double trimMean(int[] arr) {\n Arrays.sort(arr);\n int length = arr.length;\n int toRemove = length * 5 / 100;\n int total = 0;\n for (int number: arr) {\n total += number;\n }\n for (int i=0; i= length-toRemove; i--)\n total -= arr[i];\n length -= (2 * toRemove);\n return (double) ((double)total / (double)length);\n }\n}\n", + "title": "1619. Mean of Array After Removing Some Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10 -5 of the actual answer will be considered accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "20 <= arr.length <= 1000", + "arr.length is a multiple of 20 .", + "0 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]Output:2.00000Explanation:After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.", + "image": null + }, + { + "text": "Example 2: Input:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]Output:4.00000", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]Output:4.77778", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 11.43%) | Memory: 14.1 MB (Top 36.03%)\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n\n return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])\n", + "title": "1619. Mean of Array After Removing Some Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]Output:2.00000Explanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]Output:2.50000Explanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 46.02%) | Memory: 50.6 MB (Top 18.35%)\n\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0;\n int i = 0;\n int j = 0;\n int k = 0;\n int nums[] = new int[nums1.length + nums2.length];\n if(nums1.length !=0 && nums2.length != 0){\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] < nums2[j]){\n nums[k] = nums1[i];\n i++;\n k++;\n }else{\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n while(i < nums1.length){\n nums[k] = nums1[i];\n i++;\n k++;\n }\n while(j < nums2.length){\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n if(nums1.length==0){\n for(int h: nums2){\n nums[k] = h;\n k++;\n }\n }\n\n if(nums2.length==0){\n for(int d : nums1){\n nums[k] = d;\n k++;\n }\n }\n\n int mid = (nums.length / 2);\n\n if (nums.length % 2 == 0) {\n return ((double) nums[mid] + (double) nums[mid - 1]) / 2.0;\n } else {\n return nums[mid];\n }\n }\n}", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]Output:2.00000Explanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]Output:2.50000Explanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n lis = nums1 + nums2\n lis.sort()\n hi = len(lis)\n print(5/2)\n if hi%2 == 0:\n if (lis[hi/2] + lis[hi/2-1])%2 == 0:\n return (lis[hi/2] + lis[hi/2-1] )/2\n return (lis[hi/2] + lis[hi/2-1])/2 + 0.5\n else:\n return lis[hi//2]\n", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees ( 0-indexed ). Each BST in trees has at most 3 nodes , and no two roots have the same value. In one operation, you can: Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST . A BST (binary search tree) is a binary tree where each node satisfies the following property: A leaf is a node that has no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j] .", + "Replace the leaf node in trees[i] with trees[j] .", + "Remove trees[j] from trees ." + ], + "examples": [ + { + "text": "Example 1: Input:trees = [[2,1],[3,2,5],[5,4]]Output:[3,2,5,1,null,4]Explanation:In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].The resulting tree, shown above, is a valid BST, so return its root.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d1.png" + }, + { + "text": "Example 2: Input:trees = [[5,3,8],[3,2,6]]Output:[]Explanation:Pick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d2.png" + }, + { + "text": "Example 3: Input:trees = [[5,4],[3]]Output:[]Explanation:It is impossible to perform any operations.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 179 ms (Top 13.99%) | Memory: 158.1 MB (Top 58.04%)\n\nclass Solution {\n public TreeNode canMerge(List trees) {\n //Map root value to tree\n HashMap map = new HashMap<>();\n for(TreeNode t : trees){\n map.put(t.val, t);\n }\n\n // Merge trees\n for(TreeNode t : trees){\n if(map.containsKey(t.val)){\n merger(t, map);\n }\n }\n\n //After merging we should have only one tree left else return null\n if(map.size() != 1) return null;\n else {\n //Return the one tree left after merging\n for(int c : map.keySet()) {\n //Check if final tree is valid else return null\n if(isValidBST(map.get(c))){\n return map.get(c);\n } else return null;\n }\n }\n\n return null;\n\n }\n\n void merger(TreeNode t, HashMap map){\n map.remove(t.val); // Remove current tree to prevent cyclical merging For. 2->3(Right) and 3->2(Left)\n //Merge on left\n if(t.left != null && map.containsKey(t.left.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.left.val), map);\n t.left = map.get(t.left.val);\n map.remove(t.left.val);\n }\n\n // Merge on right\n if(t.right!=null && map.containsKey(t.right.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.right.val), map);\n t.right = map.get(t.right.val);\n map.remove(t.right.val);\n }\n // Add tree back to map once right and left merge is complete\n map.put(t.val, t);\n }\n\n // Validate BST\n public boolean isValidBST(TreeNode root) {\n return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n\n public boolean helper(TreeNode root, long min, long max){\n if(root == null) return true;\n if(root.val <= min || root.val >= max) return false;\n return helper(root.left, min, root.val) && helper(root.right, root.val, max);\n }\n}", + "title": "1932. Merge BSTs to Create Single BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees ( 0-indexed ). Each BST in trees has at most 3 nodes , and no two roots have the same value. In one operation, you can: Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST . A BST (binary search tree) is a binary tree where each node satisfies the following property: A leaf is a node that has no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j] .", + "Replace the leaf node in trees[i] with trees[j] .", + "Remove trees[j] from trees ." + ], + "examples": [ + { + "text": "Example 1: Input:trees = [[2,1],[3,2,5],[5,4]]Output:[3,2,5,1,null,4]Explanation:In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].The resulting tree, shown above, is a valid BST, so return its root.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d1.png" + }, + { + "text": "Example 2: Input:trees = [[5,3,8],[3,2,6]]Output:[]Explanation:Pick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d2.png" + }, + { + "text": "Example 3: Input:trees = [[5,4],[3]]Output:[]Explanation:It is impossible to perform any operations.", + "image": "https://assets.leetcode.com/uploads/2021/06/08/d3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2457 ms (Top 91.30%) | Memory: 66.7 MB (Top 52.17%)\nclass Solution:\n def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n n = len(trees)\n if n == 1: return trees[0]\n\n value_to_root = {} # Map each integer root value to its node\n appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf\n self.saw_conflict = False # If this is ever true, break out of function and return None\n leaf_value_to_parent_node = {}\n\n def is_leaf_node(curr: TreeNode) -> bool:\n return curr.left is None and curr.right is None\n\n def get_size(curr: TreeNode) -> int: # DFS to count Binary Tree Size\n if curr is None: return 0\n return 1 + get_size(curr.left) + get_size(curr.right)\n\n def is_valid_bst(curr: TreeNode, lo=-math.inf, hi=math.inf) -> bool: # Standard BST validation code\n if curr is None: return True\n return all((lo < curr.val < hi,\n is_valid_bst(curr.left, lo, curr.val),\n is_valid_bst(curr.right, curr.val, hi)))\n\n def process_child(child_node: TreeNode, parent: TreeNode) -> None:\n if child_node is None:\n return None\n elif child_node.val in leaf_value_to_parent_node or child_node.val in appeared_as_middle_child:\n self.saw_conflict = True # Already saw this child node's value in a non-root node\n elif is_leaf_node(child_node):\n leaf_value_to_parent_node[child_node.val] = parent\n elif child_node.val in value_to_root:\n self.saw_conflict = True\n else:\n appeared_as_middle_child.add(child_node.val)\n process_child(child_node.left, child_node)\n process_child(child_node.right, child_node)\n\n def process_root(curr_root: TreeNode) -> None:\n value_to_root[curr_root.val] = curr_root\n\n if curr_root.val in appeared_as_middle_child:\n self.saw_conflict = True\n else:\n process_child(curr_root.left, curr_root)\n process_child(curr_root.right, curr_root)\n\n for root_here in trees:\n process_root(root_here)\n if self.saw_conflict: return None\n\n final_expected_size = len(leaf_value_to_parent_node) + len(appeared_as_middle_child) + 1\n\n final_root = None # The root of our final BST will be stored here\n while value_to_root:\n root_val, root_node_to_move = value_to_root.popitem()\n\n if root_val not in leaf_value_to_parent_node: # Possibly found main root\n if final_root is None:\n final_root = root_node_to_move\n else:\n return None # Found two main roots\n else:\n new_parent = leaf_value_to_parent_node.pop(root_val)\n if new_parent.left is not None and new_parent.left.val == root_val:\n new_parent.left = root_node_to_move\n continue\n elif new_parent.right is not None and new_parent.right.val == root_val:\n new_parent.right = root_node_to_move\n else:\n return None # Didn't find a place to put this node\n\n # Didn't find any candidates for main root, or have a cycle, or didn't use all trees\n if final_root is None or not is_valid_bst(final_root) or get_size(final_root) != final_expected_size:\n return None\n\n return final_root", + "title": "1932. Merge BSTs to Create Single BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= list1.length <= 10^4", + "1 <= a <= b < list1.length - 1", + "1 <= list2.length <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]Output:[0,1,2,1000000,1000001,1000002,5]Explanation:We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png" + }, + { + "text": "Example 2: Input:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]Output:[0,1,1000000,1000001,1000002,1000003,1000004,6]Explanation:The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n ListNode left = list1;\n for (int i = 1; i < a; i++)\n left = left.next;\n \n ListNode middle = left;\n for (int i = a; i <= b; i++)\n middle = middle.next;\n \n\t\tleft.next = list2;\n while (list2.next != null)\n list2 = list2.next;\n \n list2.next = middle.next;\n return list1;\n }\n}\n", + "title": "1669. Merge In Between Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= list1.length <= 10^4", + "1 <= a <= b < list1.length - 1", + "1 <= list2.length <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]Output:[0,1,2,1000000,1000001,1000002,5]Explanation:We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png" + }, + { + "text": "Example 2: Input:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]Output:[0,1,1000000,1000001,1000002,1000003,1000004,6]Explanation:The blue edges and nodes in the above figure indicate the result.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 44.4%) | Memory: 22.60 MB (Top 86.42%)\n\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n head = list1\n for _ in range(a-1):\n head = head.next\n cur = head.next\n for _ in range(b-a):\n cur = cur.next\n head.next = list2\n while head.next:\n head = head.next\n if cur.next:\n head.next = cur.next\n return list1\n", + "title": "1669. Merge In Between Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]Output:[[1,5]]Explanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 74.73%) | Memory: 55.4 MB (Top 43.78%)\nclass Solution {\n public int[][] merge(int[][] intervals) {\n // sort\n // unknown size of ans = use ArrayList\n // insert from back\n // case 1 : Merging\n // start of new interval is less that end of old interval\n // new end = Math.max(new intervals end, old intervals end)\n // case 2 : Non-merging\n // seperate interval\n // convert ArrayList to array and return\n\n Arrays.sort(intervals, (a,b) -> a[0]-b[0]);\n ArrayList list = new ArrayList<>();\n for(int i = 0; i < intervals.length; i++) {\n if(i == 0) {\n list.add(intervals[i]);\n } else {\n int[] prev = list.get(list.size()-1);\n int[] curr = intervals[i];\n if(curr[0] <= prev[1]) {\n prev[1] = Math.max(curr[1], prev[1]);\n }else {\n list.add(curr);\n }\n }\n }\n return list.toArray(new int[list.size()][2]);\n }\n}", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]Output:[[1,5]]Explanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def merge(self, A: List[List[int]]) -> List[List[int]]:\n\t#sort array wrt its 0'th index\n A.sort(key=lambda x:x[0])\n i=0\n while i<(len(A)-1):\n if A[i][1]>=A[i+1][0]:\n A[i][1]=max(A[i+1][1],A[i][1])\n A.pop(i+1)\n else:\n i+=1\n return(A)\n \n", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]Output:[1,1,2,3,4,4,5,6]Explanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 392 ms (Top 5.94%) | Memory: 46.8 MB (Top 77.33%)\nclass Solution {\npublic ListNode mergeKLists(ListNode[] lists) {\n if(lists == null || lists.length < 1) return null;\n\n //add the first chunk of linkedlist to res,\n //so later we started from index 1\n ListNode res = lists[0];\n\n //traverse the lists and start merge by calling mergeTwo\n for(int i = 1; i < lists.length; i++){\n res = mergeTwo(res, lists[i]);\n }\n\n return res;\n}\n //leetcode 21 technics\n private ListNode mergeTwo(ListNode l1, ListNode l2){\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n\n if(l1.val < l2.val){\n l1.next = mergeTwo(l1.next, l2);\n return l1;\n } else{\n l2.next = mergeTwo(l2.next, l1);\n return l2;\n }\n }\n}", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]Output:[1,1,2,3,4,4,5,6]Explanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nfrom heapq import heappush,heappop\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n heap = []\n heapq.heapify(heap)\n start = end = ListNode(-1)\n for i in lists:\n if i:\n heappush(heap,(i.val,id(i),i))\n while heap:\n val,iD,node = heappop(heap)\n end.next = node\n node = node.next\n end = end.next\n if node:\n heappush(heap,(node.val,id(node),node))\n \n return start.next\n", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0 's. The beginning and end of the linked list will have Node.val == 0 . For every two consecutive 0 's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0 's. Return the head of the modified linked list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [3, 2 * 10^5 ] .", + "0 <= Node.val <= 1000", + "There are no two consecutive nodes with Node.val == 0 .", + "The beginning and end of the linked list have Node.val == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,3,1,0,4,5,2,0]Output:[4,11]Explanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" + }, + { + "text": "Example 2: Input:head = [0,1,0,3,0,2,2,0]Output:[1,3,4]Explanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeNodes(ListNode head) {\n ListNode newList=new ListNode(0);\n ListNode newHead=newList;\n ListNode newtemp= newList;\n/*---------------------------------------------------------------*/\n ListNode temp=head.next;\n int sum=0;\n if(head==null && head.next==null) return head;\n/*---------------------------------------------------------------*/ \n while(temp!=null){ //traverse linkelist\n sum +=temp.val; //sum elements until zero\n if(temp.val==0){\n ListNode node=new ListNode(sum); //create a new node; \n newtemp.next=node; //connect with dummy node which is created initially\n newtemp=newtemp.next; //shift pointer to newly created node\n sum=0; //reset sum\n }\n temp=temp.next;\n }\n/*---------------------------------------------------------------*/\n return newHead.next; //skip dummy node which is created initially\n }\n}\n", + "title": "2181. Merge Nodes in Between Zeros", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the head of a linked list, which contains a series of integers separated by 0 's. The beginning and end of the linked list will have Node.val == 0 . For every two consecutive 0 's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0 's. Return the head of the modified linked list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [3, 2 * 10^5 ] .", + "0 <= Node.val <= 1000", + "There are no two consecutive nodes with Node.val == 0 .", + "The beginning and end of the linked list have Node.val == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [0,3,1,0,4,5,2,0]Output:[4,11]Explanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" + }, + { + "text": "Example 2: Input:head = [0,1,0,3,0,2,2,0]Output:[1,3,4]Explanation:The above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n d=ListNode(0)\n t=0\n r=ListNode(0,d)\n while head:\n if head.val!=0:\n t+=head.val\n else:\n print(t)\n if t!=0:\n d.next=ListNode(t)\n d=d.next\n t=0\n head=head.next\n return r.next.next\n", + "title": "2181. Merge Nodes in Between Zeros", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 2D integer arrays, items1 and items2 , representing two sets of items. Each array items has the following properties: Return a 2D integer array ret where ret[i] = [value i , weight i ] , with weight i being the sum of weights of all items with value value i . Note: ret should be returned in ascending order by value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "items[i] = [value i , weight i ] where value i represents the value and weight i represents the weight of the i th item.", + "The value of each item in items is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]Output:[[1,6],[3,9],[4,5]]Explanation:The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.\nThe item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.\nThe item with value = 4 occurs in items1 with weight = 5, total weight = 5. \nTherefore, we return [[1,6],[3,9],[4,5]].", + "image": null + }, + { + "text": "Example 2: Input:items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]Output:[[1,4],[2,4],[3,4]]Explanation:The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.\nThe item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.\nThe item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.\nTherefore, we return [[1,4],[2,4],[3,4]].", + "image": null + }, + { + "text": "Example 3: Input:items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]Output:[[1,7],[2,4],[7,1]]Explanation:The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. \nThe item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. \nThe item with value = 7 occurs in items2 with weight = 1, total weight = 1.\nTherefore, we return [[1,7],[2,4],[7,1]].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 72.74%) | Memory: 18.10 MB (Top 7.4%)\n\nclass Solution:\n\tdef mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n\n\t\tmerge_item = items1 + items2\n\n\t\td = defaultdict(int)\n\n\t\tfor i in merge_item:\n\t\t\tvalue,weight = i\n\t\t\td[value] = d[value] + weight\n\n\t\tresult = []\n\n\t\tfor j in sorted(d):\n\t\t\tresult.append([j,d[j]])\n\n\t\treturn result\n", + "title": "2363. Merge Similar Items", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3Output:[1,2,2,3,5,6]Explanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0Output:[1]Explanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1Output:[1]Explanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n int i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n int k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n }\n}\n", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3Output:[1,2,2,3,5,6]Explanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0Output:[1]Explanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1Output:[1]Explanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def merge(self, nums1, m, nums2, n):\n # Initialize nums1's index\n i = m - 1\n # Initialize nums2's index\n j = n - 1\n # Initialize a variable k to store the last index of the 1st array...\n k = m + n - 1\n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n k -= 1\n i -= 1\n else:\n nums1[k] = nums2[j]\n k -= 1\n j -= 1\n", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two strings word1 and word2 . Merge the strings by adding letters in alternating order, starting with word1 . If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 100", + "word1 and word2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"pqr\"Output:\"apbqcr\"Explanation:The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"pqrs\"Output:\"apbqrs\"Explanation:Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"abcd\", word2 = \"pq\"Output:\"apbqcd\"Explanation:Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.63%) | Memory: 41.7 MB (Top 86.60%)\nclass Solution {\n public String mergeAlternately(String word1, String word2) {\n StringBuilder sb = new StringBuilder();\n int lenmax = Math.max(word1.length(),word2.length());\n for(int i=0;i<=lenmax-1;i++)\n {\n if(i bool:\n \n a, b, c = 0, 0, 0\n for i, (x, y, z) in enumerate(triplets):\n if not( x > target[0] or y > target[1] or z > target[2]):\n a, b, c = max(a, x), max(b, y), max(c, z)\n \n return [a, b, c] == target\n \n", + "title": "1899. Merge Triplets to Form Target Triplet", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two binary trees root1 and root2 . Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return the merged tree . Note: The merging process must start from the root nodes of both trees. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 2000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]Output:[3,4,5,5,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/05/merge.jpg" + }, + { + "text": "Example 2: Input:root1 = [1], root2 = [1,2]Output:[2,2]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {\n if(root1==NULL) return root2;\n if(root2==NULL) return root1;\n root1->val+=root2->val;\n root1->left=mergeTrees(root1->left,root2->left);\n root1->right=mergeTrees(root1->right,root2->right);\n return root1;\n }\n};\n", + "title": "617. Merge Two Binary Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the heads of two sorted linked lists list1 and list2 . Merge the two lists in a 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]Output:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 80.18%) | Memory: 43.5 MB (Top 22.48%)\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2)\n {\n if(list1==null && list2==null)\n return null;\n if(list1 == null)\n return list2;\n if(list2 == null)\n return list1;\n\n ListNode newHead = new ListNode();\n ListNode newNode = newHead;\n\n while(list1!=null && list2!=null)\n {\n //ListNode newNode = new ListNode();\n if(list1.val <= list2.val)\n {\n newNode.next = list1;\n list1 = list1.next;\n }\n else if(list1.val >= list2.val)\n {\n newNode.next = list2;\n list2 = list2.next;\n }\n newNode = newNode.next;\n }\n if(list1!=null)\n newNode.next = list1;\n else if(list2!=null)\n newNode.next = list2;\n return newHead.next;\n }\n}", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the heads of two sorted linked lists list1 and list2 . Merge the two lists in a 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]Output:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 43 ms (Top 67.2%) | Memory: 16.18 MB (Top 97.5%)\n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n cur = dummy = ListNode()\n while list1 and list2: \n if list1.val < list2.val:\n cur.next = list1\n list1, cur = list1.next, list1\n else:\n cur.next = list2\n list2, cur = list2.next, list2\n \n if list1 or list2:\n cur.next = list1 if list1 else list2\n \n return dummy.next", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return the middle node of the linked list . If there are two middle nodes, return the second middle node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 100] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[3,4,5]Explanation:The middle node of the list is node 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6]Output:[4,5,6]Explanation:Since the list has two middle nodes with values 3 and 4, we return the second one.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode middleNode(ListNode head) {\n \n ListNode temp = head;\n int size = 0;\n while(temp!=null){\n size++;\n temp = temp.next;\n }\n int mid = size/2;\n temp = head;\n for(int i=0;i int:\n\t\tcur = 0 \n\t\tdp0 = cost[0]\n\t\tif len(cost) >= 2:\n\t\t\tdp1 = cost[1]\n\n\t\tfor i in range(2, len(cost)):\n\t\t\tcur = cost[i] + min(dp0, dp1)\n\t\t\tdp0 = dp1\n\t\t\tdp1 = cur\n\n\t\treturn min(dp0, dp1)\n", + "title": "746. Min Cost Climbing Stairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 1000", + "-10^6 <= x i , y i <= 10^6", + "All pairs (x i , y i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]Output:20Explanation:We can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.", + "image": "https://assets.leetcode.com/uploads/2020/08/26/d.png" + }, + { + "text": "Example 2: Input:points = [[3,12],[-2,5],[-4,1]]Output:18", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 99.32%) | Memory: 42.90 MB (Top 99.2%)\n\nclass Solution {\n public int minCostConnectPoints(int[][] points) {\n int len = points.length;\n // array that keep track of the shortest distance from mst to each node\n int[] disArr = new int[len];\n for (int i = 1; i < len; ++i) {\n disArr[i] = Integer.MAX_VALUE;\n }\n // visited[node] == true if node in mst\n boolean[] visited = new boolean[len];\n visited[0] = true;\n \n int numEdge = 0;\n // current node, used to update the disArr\n int cur = 0;\n // result\n int res = 0;\n \n while (numEdge++ < len - 1) {\n int minEdge = Integer.MAX_VALUE;\n int next = -1;\n for (int i = 0; i < len; ++i) {\n // if the node i is not in mst\n if (!visited[i]) {\n // find the distance between cur and i\n int dis = Math.abs(points[cur][0] - points[i][0]) + Math.abs(points[cur][1] - points[i][1]);\n // update distance array\n disArr[i] = Math.min(dis, disArr[i]);\n // find the shortest edge\n if (disArr[i] < minEdge) {\n minEdge = disArr[i];\n next = i;\n }\n }\n }\n cur = next;\n visited[cur] = true;\n res += minEdge;\n }\n \n return res;\n }\n}\n", + "title": "1584. Min Cost to Connect All Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 1000", + "-10^6 <= x i , y i <= 10^6", + "All pairs (x i , y i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]Output:20Explanation:We can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.", + "image": "https://assets.leetcode.com/uploads/2020/08/26/d.png" + }, + { + "text": "Example 2: Input:points = [[3,12],[-2,5],[-4,1]]Output:18", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2922 ms (Top 60.17%) | Memory: 79.1 MB (Top 76.18%)\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n\n cost = 0\n heap = []\n\n #set to store past points to prevent cycle\n visited = set([0])\n\n #i == the index of current point\n i = 0\n\n while len(visited) < len(points):\n #Add all costs from current point to unreached points to min heap\n for j in range(len(points)):\n if j == i or j in visited:\n continue\n distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])\n heapq.heappush(heap, (distance, j))\n\n #Add new min cost edge\n while True:\n dist, point = heapq.heappop(heap)\n if point not in visited:\n cost += dist\n #Add point to visited to prevent cycle\n visited.add(point)\n #Update point\n i = point\n break\n\n return cost", + "title": "1584. Min Cost to Connect All Points", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums whose length is a power of 2 . Apply the following algorithm on nums : Return the last number that remains in nums after applying the algorithm. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1024", + "1 <= nums[i] <= 10^9", + "nums.length is a power of 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,2,4,8,2,2]Output:1Explanation:The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.", + "image": "https://assets.leetcode.com/uploads/2022/04/13/example1drawio-1.png" + }, + { + "text": "Example 2: Input:nums = [3]Output:3Explanation:3 is already the last remaining number, so we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.60 MB (Top 22.49%)\n\nclass Solution {\n public int minMaxGame(int[] nums) {\n int len=nums.length;\n if(len==1)\n return nums[0];\n int[] newNums=new int[len/2];\n int index=0;\n for(int i=0;i int:\n \n def solve(n):\n if n==1:\n return\n for i in range(n//2):\n if i%2:\n a[i] = max (a[2*i], a[2*i+1])\n else:\n a[i] = min (a[2*i], a[2*i+1])\n solve(n//2)\n return\n solve(len(a))\n return a[0]\n", + "title": "2293. Min Max Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: You must implement a solution with O(1) time complexity for each function. Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n[[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 117 ms (Top 35.13%) | Memory: 18.5 MB (Top 10.03%)\nclass MinStack:\n\n def __init__(self):\n self.stack = []\n\n def push(self, val: int) -> None:\n if not self.stack:\n self.stack.append((val, val))\n else:\n self.stack.append((val, min(val, self.stack[-1][1])))\n\n def pop(self) -> None:\n if self.stack:\n self.stack.pop()\n\n def top(self) -> int:\n if self.stack:\n return self.stack[-1][0]\n else:\n return None\n\n def getMin(self) -> int:\n if self.stack:\n return self.stack[-1][1]\n else:\n return None", + "title": "155. Min Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Let's play the minesweeper game ( Wikipedia , online game )! You are given an m x n char matrix board representing the game board where: You are also given an integer array click where click = [click r , click c ] represents the next click position among all the unrevealed squares ( 'M' or 'E' ). Return the board after revealing this position according to the following rules : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'M' represents an unrevealed mine,", + "'E' represents an unrevealed empty square,", + "'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),", + "digit ( '1' to '8' ) represents how many mines are adjacent to this revealed square, and", + "'X' represents a revealed mine." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]Output:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" + }, + { + "text": "Example 2: Input:board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]Output:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 100.00%)\nclass Solution {\n public char[][] updateBoard(char[][] board, int[] click) {\n int r = click[0];\n int c = click[1];\n if(board[r][c] == 'M')\n {\n board[r][c] = 'X';\n return board;\n }\n dfs(board, r, c);\n return board;\n }\n\n private void dfs(char[][]board, int r, int c)\n {\n if(r < 0 || r >= board.length || c >= board[0].length || c < 0 || board[r][c] == 'B')//Stop case\n return;\n int num = countMine(board, r, c);//count how many adjacent mines\n if(num != 0)\n {\n board[r][c] = (char)('0' + num);\n return;\n }\n else\n {\n board[r][c] = 'B';\n dfs(board, r + 1, c);//recursively search all neighbors\n dfs(board, r - 1, c);\n dfs(board, r, c + 1);\n dfs(board, r, c - 1);\n dfs(board, r - 1, c - 1);\n dfs(board, r + 1, c - 1);\n dfs(board, r - 1, c + 1);\n dfs(board, r + 1, c + 1);\n }\n }\n\n private int countMine(char[][]board, int r, int c)\n {\n int count = 0;\n for(int i = r - 1; i <= r + 1; ++i)\n {\n for(int j = c - 1; j <= c + 1; ++j)\n {\n if(i >= 0 && i < board.length && j >= 0 && j < board[0].length)\n {\n if(board[i][j] == 'M')\n count++;\n }\n }\n }\n return count;\n }\n}", + "title": "529. Minesweeper", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Let's play the minesweeper game ( Wikipedia , online game )! You are given an m x n char matrix board representing the game board where: You are also given an integer array click where click = [click r , click c ] represents the next click position among all the unrevealed squares ( 'M' or 'E' ). Return the board after revealing this position according to the following rules : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'M' represents an unrevealed mine,", + "'E' represents an unrevealed empty square,", + "'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),", + "digit ( '1' to '8' ) represents how many mines are adjacent to this revealed square, and", + "'X' represents a revealed mine." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]Output:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" + }, + { + "text": "Example 2: Input:board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]Output:[[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def calMines(self,board,x,y):\n directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]\n mines = 0\n for d in directions:\n r, c = x+d[0],y+d[1]\n if self.isValid(board,r,c) and (board[r][c] == 'M' or board[r][c] == 'X'):\n mines+=1\n return mines\n\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n x,y = click[0],click[1]\n options = []\n if board[x][y] == \"M\":\n board[x][y] = \"X\"\n else:\n count = self.calMines(board,x,y)\n if count == 0:\n board[x][y] = \"B\"\n for r in range(x-1,x+2):\n for c in range(y-1,y+2):\n if self.isValid(board,r,c) and board[r][c]!='B':\n self.updateBoard(board,[r,c])\n else:\n board[x][y] = str(count)\n\n return board\n \n \n def isValid(self,board,a,b):\n return 0<=a NestedInteger:\n if s[0] == '[':\n res, i = self.dfs(1, s)\n return res\n else:\n num = int(s)\n res = NestedInteger()\n res.setInteger(num)\n return res\n", + "title": "385. Mini Parser", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the element is even , divide it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "If the element is odd , multiply it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:1Explanation:You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,5,20,3]Output:3Explanation:You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,8]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 97.34%) | Memory: 51 MB (Top 91.49%)\nclass Solution {\n public int minimumDeviation(int[] nums) {\n TreeSet temp = new TreeSet<>();\n for(int i: nums){\n if(i % 2 == 0){\n temp.add(i);\n }\n else{\n temp.add(i * 2);\n }\n }\n\n int md = temp.last() - temp.first();\n int m = 0;\n\n while(temp.size() > 0 && temp.last() % 2 == 0){\n m = temp.last();\n temp.remove(m);\n temp.add(m / 2);\n\n md = Math.min(md, temp.last() - temp.first());\n }\n return md;\n }\n}", + "title": "1675. Minimize Deviation in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the element is even , divide it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the last element, and the array will be [1,2,3, 2 ].", + "If the element is odd , multiply it by 2 . For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4].", + "For example, if the array is [1,2,3,4] , then you can do this operation on the first element, and the array will be [ 2 ,2,3,4]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:1Explanation:You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,5,20,3]Output:3Explanation:You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,8]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef minimumDeviation(self, nums: List[int]) -> int:\n\n\t\tfrom sortedcontainers import SortedList\n\n\t\tfor i in range(len(nums)):\n\n\t\t\tif nums[i]%2!=0:\n\t\t\t\tnums[i]=nums[i]*2\n\n\t\tnums = SortedList(nums)\n\n\t\tresult = 100000000000\n\n\t\twhile True:\n\t\t\tmin_value = nums[0]\n\t\t\tmax_value = nums[-1]\n\n\t\t\tif max_value % 2 == 0:\n\t\t\t\tnums.pop()\n\t\t\t\tnums.add(max_value // 2)\n\t\t\t\tmax_value = nums[-1]\n\t\t\t\tmin_value = nums[0]\n\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\telse:\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\t\tbreak\n\n\t\treturn result\n", + "title": "1675. Minimize Deviation in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays, source and target , both of length n . You are also given an array allowedSwaps where each allowedSwaps[i] = [a i , b i ] indicates that you are allowed to swap the elements at index a i and index b i (0-indexed) of array source . Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target , is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed) . Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == source.length == target.length", + "1 <= n <= 10^5", + "1 <= source[i], target[i] <= 10^5", + "0 <= allowedSwaps.length <= 10^5", + "allowedSwaps[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]Output:1Explanation:source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.", + "image": null + }, + { + "text": "Example 2: Input:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []Output:2Explanation:There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.", + "image": null + }, + { + "text": "Example 3: Input:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 98.25%) | Memory: 87.50 MB (Top 31.58%)\n\nclass Solution {\n public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {\n int[] line = new int[source.length];\n Arrays.fill(line, 100001);\n for (int[] swap : allowedSwaps) {\n int root0 = getRoot(line, swap[0]);\n int root1 = getRoot(line, swap[1]);\n int min = Integer.min(root0, root1);\n line[root0] = min;\n line[root1] = min;\n // for speed up\n line[swap[0]] = min;\n line[swap[1]] = min;\n }\n HashMap> pool = new HashMap<>();\n int different = 0;\n int noSwap = 0;\n for (int i = 0; i < line.length; i++) {\n if (line[i] == 100001) {\n if (source[i] != target[i]) {\n // not allow swap distance\n noSwap++;\n }\n continue;\n }\n Integer root = getRoot(line, i);\n if (!pool.containsKey(root)) {\n pool.put(root, new HashMap<>());\n }\n HashMap freq = pool.get(root);\n freq.put(source[i], freq.getOrDefault(source[i], 0)+1);\n freq.put(target[i], freq.getOrDefault(target[i], 0)-1);\n }\n for (HashMap freq : pool.values()) {\n for (Integer value : freq.values()) {\n different += Math.abs(value);\n }\n }\n // two different number mean one hamming distance\n return different/2+noSwap;\n }\n \n private int getRoot(int[] line, int index) {\n if (line[index] == 100001) {\n line[index] = index;\n return index;\n }\n if (line[index] == index) {\n return index;\n }\n return getRoot(line, line[index]);\n }\n}\n", + "title": "1722. Minimize Hamming Distance After Swap Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays, source and target , both of length n . You are also given an array allowedSwaps where each allowedSwaps[i] = [a i , b i ] indicates that you are allowed to swap the elements at index a i and index b i (0-indexed) of array source . Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target , is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed) . Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == source.length == target.length", + "1 <= n <= 10^5", + "1 <= source[i], target[i] <= 10^5", + "0 <= allowedSwaps.length <= 10^5", + "allowedSwaps[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]Output:1Explanation:source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.", + "image": null + }, + { + "text": "Example 2: Input:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []Output:2Explanation:There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.", + "image": null + }, + { + "text": "Example 3: Input:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1385 ms (Top 99.43%) | Memory: 59.9 MB (Top 71.02%)\nclass UnionFind:\n def __init__(self, n):\n self.roots = [i for i in range(n)]\n\n def find(self, v):\n if self.roots[v] != v:\n self.roots[v] = self.find(self.roots[v])\n\n return self.roots[v]\n\n def union(self, u, v):\n self.roots[self.find(u)] = self.find(v)\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for idx1, idx2 in allowedSwaps:\n uf.union(idx1, idx2)\n\n m = collections.defaultdict(set)\n for i in range(len(source)):\n m[uf.find(i)].add(i)\n\n res = 0\n for indices in m.values():\n freq = {}\n for i in indices:\n freq[source[i]] = freq.get(source[i], 0)+1\n freq[target[i]] = freq.get(target[i], 0)-1\n res += sum(val for val in freq.values() if val > 0)\n\n return res", + "title": "1722. Minimize Hamming Distance After Swap Operations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length <= n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]Output:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]Output:0", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 23.81%) | Memory: 127.5 MB (Top 49.76%)\nclass Solution {\n int[]parent;\n int[]size;\n\n public int minMalwareSpread(int[][] graph, int[] initial) {\n parent = new int[graph.length];\n size = new int[graph.length];\n for(int i=0;i ans_size){\n ans_i = i;\n ans_size = size[ri];\n }else if(size[ri] == ans_size){\n if(i < ans_i){\n ans_i = i;\n ans_size = size[ri];\n }\n }\n }\n }\n\n if(ans_i == -1){\n ans_i = graph.length;\n for(int i : initial){\n if(i < ans_i){\n ans_i = i;\n }\n }\n }\n\n return ans_i;\n\n }\n\n int find(int x){\n if(parent[x] == x){\n return x;\n }else{\n parent[x] = find(parent[x]);\n return parent[x];\n }\n }\n\n void unionHelper(int x,int y){\n int xl = find(x);\n int yl = find(y);\n\n if(size[xl] < size[yl]){\n parent[xl] = yl;\n size[yl] += size[xl];\n }else{\n parent[yl] = xl;\n size[xl] += size[yl];\n }\n }\n}", + "title": "924. Minimize Malware Spread", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length <= n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]Output:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]Output:0", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1782 ms (Top 87.91%) | Memory: 16.6 MB (Top 91.21%)\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n uf = UnionFind(n)\n for i in range(n):\n for j in range(n):\n if graph[i][j]:\n uf.union(i, j)\n\n max_remove = 0\n\n initial.sort()\n min_index = initial[0]\n for i in range(len(initial)):\n cur_remove = 0\n linked = False\n for j in range(len(initial)):\n if i == j: continue\n if uf.find(initial[i]) == uf.find(initial[j]):\n linked = True\n if not linked:\n cur_remove = uf.rank[uf.find(initial[i])]\n if max_remove < cur_remove:\n max_remove = cur_remove\n min_index = initial[i]\n\n return min_index\n\nclass UnionFind:\n def __init__(self, size):\n self.parent = {}\n self.rank = {}\n for i in range(size):\n self.parent[i] = i\n self.rank[i] = 1\n\n def find(self, x):\n if x != self.parent[x]:\n x = self.find(self.parent[x])\n return x\n\n def union(self, x, y):\n px, py = self.find(x), self.find(y)\n if px == py: return\n if self.rank[px] >= self.rank[py]:\n self.parent[py] = px\n self.rank[px] += self.rank[py]\n else:\n self.parent[px] = py\n self.rank[py] += self.rank[px]", + "title": "924. Minimize Malware Spread", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial , completely removing it and any connections from this node to any other node . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length < n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]Output:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]Output:1", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n int[] size;\n \n public int find(int x){\n if(parent[x]==x) return x;\n int f = find(parent[x]);\n parent[x] = f;\n return f;\n }\n \n void merge(int x, int y){\n if(size[x]>size[y]){\n parent[y] = x;\n size[x] += size[y];\n }else{\n parent[x] =y;\n size[y] +=size[x];\n }\n }\n \n public int minMalwareSpread(int[][] graph, int[] initial) {\n int n =graph.length;\n \n parent = new int[n];\n size= new int[n];\n // putting initially infected nodes in hashset to ignore them while making graph\n HashSet hs = new HashSet<>();\n for(int a : initial){\n hs.add(a);\n }\n //initializing Parent for DSU\n for(int i=0;i> map = new HashMap<>();\n //We need to ensure increase the count whenever a parent is influenced by initial Nodes...because if it influenced by more than one infectious node then it would still remain infectious.\n int[] infected = new int[n]; \n for(int e: initial){\n map.put(e,new HashSet<>());\n for(int j=0;j par = map.get(e);\n int total =0;\n for(int p: par){\n if(infected[p]==1){ //add to total only if influenced by only one infectious node.\n total+=size[p];\n }\n }\n if(total>=max){\n if(max==total){\n ans = Math.min(ans,e);\n }else{\n ans =e;\n }\n max =total;\n }\n }\n \n if(ans!=-1) return ans;\n //for returining smallest element.\n Arrays.sort(initial);\n \n return initial[0];\n \n }\n}\n", + "title": "928. Minimize Malware Spread II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a network of n nodes represented as an n x n adjacency matrix graph , where the i th node is directly connected to the j th node if graph[i][j] == 1 . Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial , completely removing it and any connections from this node to any other node . Return the node that, if removed, would minimize M(initial) . If multiple nodes could be removed to minimize M(initial) , return such a node with the smallest index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == graph.length", + "n == graph[i].length", + "2 <= n <= 300", + "graph[i][j] is 0 or 1 .", + "graph[i][j] == graph[j][i]", + "graph[i][i] == 1", + "1 <= initial.length < n", + "0 <= initial[i] <= n - 1", + "All the integers in initial are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]Output:0", + "image": null + }, + { + "text": "Example 2: Input:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]Output:1", + "image": null + }, + { + "text": "Example 3: Input:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nfrom collections import deque\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n G = defaultdict(list)\n for v in range(n):\n for w in range(n):\n if graph[v][w]:\n G[v].append(w)\n \n affect = defaultdict(list)\n for s in initial:\n visited = set([v for v in initial if v != s])\n que = deque([s])\n while que:\n v = que.popleft()\n if v in visited: continue\n visited.add(v)\n affect[v].append(s)\n for w in G[v]:\n que.append(w)\n res = [0]*n\n for v in affect:\n if len(affect[v]) == 1:\n res[affect[v].pop()] += 1\n if not max(res): return min(initial)\n return res.index(max(res))", + "title": "928. Minimize Malware Spread II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The pair sum of a pair (a,b) is equal to a + b . The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n , pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if we have pairs (1,5) , (2,3) , and (4,4) , the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,2,3]Output:7Explanation:The elements can be paired up into pairs (3,3) and (5,2).\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,4,2,4,6]Output:8Explanation:The elements can be paired up into pairs (3,5), (4,4), and (6,2).\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 89 ms (Top 12.88%) | Memory: 106.2 MB (Top 42.39%)\nclass Solution {\n public int minPairSum(int[] nums) {\n Arrays.sort(nums);\n\n int output = Integer.MIN_VALUE;\n\n //This is greedy, so n/2 pairs must be from start and end and move inwards\n for(int i=0, j=nums.length - 1; i int:\n pair_sum = []\n nums.sort()\n for i in range(len(nums)//2):\n pair_sum.append(nums[i]+nums[len(nums)-i-1])\n return max(pair_sum)\n", + "title": "1877. Minimize Maximum Pair Sum in Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed string expression of the form \"+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+' . Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= expression.length <= 10", + "expression consists of digits from '1' to '9' and '+' .", + "expression starts and ends with digits.", + "expression contains exactly one '+' .", + "The original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"247+38\"Output:\"2(47+38)\"Explanation:Theexpressionevaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the'+'.\nIt can be shown that 170 is the smallest possible value.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"12+34\"Output:\"1(2+3)4\"Explanation:The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"999+999\"Output:\"(999+999)\"Explanation:Theexpressionevaluates to 999 + 999 = 1998.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 39.1%) | Memory: 41.03 MB (Top 42.0%)\n\nclass Solution {\n public String minimizeResult(String expression) {\n String[] sp = expression.split(\"\\\\+\");\n String left = sp[0];\n String right = sp[1];\n \n int min = Integer.MAX_VALUE;\n String result = \"(\" + expression + \")\";\n\t\t\n for(int i=0; i+\" where and represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+' . Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= expression.length <= 10", + "expression consists of digits from '1' to '9' and '+' .", + "expression starts and ends with digits.", + "expression contains exactly one '+' .", + "The original value of expression , and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"247+38\"Output:\"2(47+38)\"Explanation:Theexpressionevaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the'+'.\nIt can be shown that 170 is the smallest possible value.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"12+34\"Output:\"1(2+3)4\"Explanation:The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"999+999\"Output:\"(999+999)\"Explanation:Theexpressionevaluates to 999 + 999 = 1998.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimizeResult(self, expression: str) -> str:\n plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression] \n def evaluate(exps: str):\n return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*'))\n for l in range(plus_index):\n for r in range(plus_index+1, n):\n exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}'\n res = evaluate(exps)\n if ans[0] > res:\n ans[0], ans[1] = res, exps\n return ans[1]\n", + "title": "2232. Minimize Result by Adding Parentheses to Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix mat and an integer target . Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized . Return the minimum absolute difference . The absolute difference between two numbers a and b is the absolute value of a - b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 70", + "1 <= mat[i][j] <= 70", + "1 <= target <= 800" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13Output:0Explanation:One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1.png" + }, + { + "text": "Example 2: Input:mat = [[1],[2],[3]], target = 100Output:94Explanation:The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-1.png" + }, + { + "text": "Example 3: Input:mat = [[1,2,9,8,7]], target = 6Output:1Explanation:The best choice is to choose 7 from the first row.\nThe absolute difference is 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1407 ms (Top 25.79%) | Memory: 92.6 MB (Top 35.19%)\nclass Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Integer[][] dp = new Integer[mat.length][5001];\n return minDiff(mat, 0, target,0, dp);\n }\n\n public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){\n if(index == mat.length){\n return Math.abs(val - target);\n }\n if(dp[index][val] != null){\n return dp[index][val];\n }\n\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < mat[0].length; i++){\n res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));\n }\n\n return dp[index][val] = res;\n }\n}", + "title": "1981. Minimize the Difference Between Target and Chosen Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n integer matrix mat and an integer target . Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized . Return the minimum absolute difference . The absolute difference between two numbers a and b is the absolute value of a - b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 70", + "1 <= mat[i][j] <= 70", + "1 <= target <= 800" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13Output:0Explanation:One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1.png" + }, + { + "text": "Example 2: Input:mat = [[1],[2],[3]], target = 100Output:94Explanation:The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-1.png" + }, + { + "text": "Example 3: Input:mat = [[1,2,9,8,7]], target = 6Output:1Explanation:The best choice is to choose 7 from the first row.\nThe absolute difference is 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/03/matrix1-3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 2497 ms (Top 82.35%) | Memory: 20.40 MB (Top 18.04%)\n\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float(\"inf\")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float(\"inf\")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float(\"inf\")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)\n", + "title": "1981. Minimize the Difference Between Target and Chosen Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities , where quantities[i] represents the number of products of the i th product type. You need to distribute all products to the retail stores following these rules: Return the minimum possible x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A store can only be given at most one product type but can be given any amount of it.", + "After distribution, each store will have been given some number of products (possibly 0 ). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, quantities = [11,6]Output:3Explanation:One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 7, quantities = [15,10,10]Output:5Explanation:One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.", + "image": null + }, + { + "text": "Example 3: Input:n = 1, quantities = [100000]Output:100000Explanation:The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimizedMaximum(int n, int[] quantities) {\n \n int lo = 1;\n int hi = (int)1e5;\n \n int ans = -1;\n \n while(lo <= hi){\n \n int mid = (lo + hi)/2;\n \n if(isItPossible(mid, quantities, n)){\n ans = mid;\n hi = mid-1;\n }else{\n lo = mid+1;\n }\n }\n \n return ans;\n }\n \n private boolean isItPossible(int x, int[] quantities, int n){\n \n // isItPossible to distribute <= x products to each of the n shops\n for(int i=0; i int:\n def cond(m, n):\n return sum([(q // m) + (q % m > 0) for q in quantities]) <= n\n \n l, r = 1, max(quantities)\n while l < r:\n m = (l + r) // 2\n if cond(m, n):\n r = m\n else:\n l = m + 1\n return l\n", + "title": "2064. Minimized Maximum of Products Distributed to Any Store", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of distinct integers arr , find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "a, b are from arr", + "a < b", + "b - a equals to the minimum absolute difference of any two elements in arr" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,1,3]Output:[[1,2],[2,3],[3,4]]Explanation:The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,6,10,15]Output:[[1,3]]", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,8,-10,23,19,-4,-14,27]Output:[[-14,-10],[19,23],[23,27]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 78.7%) | Memory: 55.94 MB (Top 56.9%)\n\nclass Solution {\n public List> minimumAbsDifference(int[] arr) {\n List> ans=new ArrayList<>();\n Arrays.sort(arr);\n int min=Integer.MAX_VALUE;\n for(int i=0;i pair=new ArrayList<>(2);\n pair.add(arr[i]);\n pair.add(arr[i+1]);\n ans.add(pair);\n }\n }\n return ans;\n }\n}", + "title": "1200. Minimum Absolute Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of distinct integers arr , find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "a, b are from arr", + "a < b", + "b - a equals to the minimum absolute difference of any two elements in arr" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,2,1,3]Output:[[1,2],[2,3],[3,4]]Explanation:The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,3,6,10,15]Output:[[1,3]]", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,8,-10,23,19,-4,-14,27]Output:[[-14,-10],[19,23],[23,27]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 574 ms (Top 47.47%) | Memory: 28.9 MB (Top 58.47%)\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n diff=float(inf)\n for i in range(0,len(arr)-1):\n if arr[i+1]-arr[i] int:\n cur, stack, minDiff, prev = root, [], 10**5, -10**5\n \n while stack or cur:\n while cur:\n stack.append(cur)\n cur = cur.left\n node = stack.pop()\n minDiff = min(minDiff, node.val - prev)\n prev = node.val\n cur = node.right\n \n return minDiff", + "title": "530. Minimum Absolute Difference in BST", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]| , where 0 <= i < j < a.length and a[i] != a[j] . If all elements of a are the same , the minimum absolute difference is -1 . You are given an integer array nums and the array queries where queries[i] = [l i , r i ] . For each query i , compute the minimum absolute difference of the subarray nums[l i ...r i ] containing the elements of nums between the 0-based indices l i and r i ( inclusive ). Return an array ans where ans[i] is the answer to the i th query . A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the minimum absolute difference of the array [5, 2 , 3 ,7,2] is |2 - 3| = 1 . Note that it is not 0 because a[i] and a[j] must be different." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]Output:[2,1,4,1]Explanation:The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]Output:[-1,1,1,3]Explanation:The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 152 ms (Top 66.6%) | Memory: 154.57 MB (Top 22.2%)\n\nclass Solution {\n public int[] minDifference(int[] nums, int[][] queries) {\n int n = nums.length;\n int[][] count = new int[n + 1][100];\n int q = queries.length;\n int ans[] = new int[q];\n \n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < 100; ++j)\n count[i + 1][j] = count[i][j];\n \n ++count[i + 1][nums[i] - 1];\n }\n \n for(int i = 0; i < q; ++i) {\n int low = queries[i][0];\n int high = queries[i][1] + 1;\n List present = new ArrayList<>();\n int min = 100;\n \n for(int j = 0; j < 100; ++j)\n if(count[high][j] - count[low][j] != 0)\n present.add(j);\n \n for(int j = 1; j < present.size(); ++j)\n min = Math.min(min, present.get(j) - present.get(j - 1));\n \n if(present.size() == 1)\n min = -1;\n \n ans[i] = min;\n }\n \n return ans;\n }\n}", + "title": "1906. Minimum Absolute Difference Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]| , where 0 <= i < j < a.length and a[i] != a[j] . If all elements of a are the same , the minimum absolute difference is -1 . You are given an integer array nums and the array queries where queries[i] = [l i , r i ] . For each query i , compute the minimum absolute difference of the subarray nums[l i ...r i ] containing the elements of nums between the 0-based indices l i and r i ( inclusive ). Return an array ans where ans[i] is the answer to the i th query . A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the minimum absolute difference of the array [5, 2 , 3 ,7,2] is |2 - 3| = 1 . Note that it is not 0 because a[i] and a[j] must be different." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]Output:[2,1,4,1]Explanation:The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]Output:[-1,1,1,3]Explanation:The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n # location of number\n loc = defaultdict(list)\n for i, num in enumerate(nums):\n loc[num].append(i)\n \n # start from sorted key thus keep tracking minimum difference\n k = sorted(loc)\n \n res = []\n for a, b in queries:\n cands = []\n ans = float('inf')\n for c in k:\n # left and right range overlap means no available locations in range\n if bisect.bisect_left(loc[c], a) == bisect.bisect(loc[c], b): continue\n if cands: \n\t\t\t\t\tans = min(ans, c - cands[-1])\n cands.append(c)\n if ans == float('inf'): ans = -1\n res.append(ans)\n return res", + "title": "1906. Minimum Absolute Difference Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two positive integer arrays nums1 and nums2 , both of length n . The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n ( 0-indexed ). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1 . Since the answer may be large, return it modulo 10^9 + 7 . |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0 , or", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,5], nums2 = [2,3,5]Output:3Explanation:There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of|1-2| + (|1-3| or |5-3|) + |5-5| =3.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]Output:0Explanation:nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]Output:20Explanation:Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {\n int mod = (int)1e9+7;\n\n // Sorted copy of nums1 to use for binary search\n int[] snums1 = nums1.clone();\n Arrays.sort(snums1);\n \n int maxDiff = 0; // maximum difference between original and new absolute diff\n int pos = 0; // where the maximum difference occurs\n int newn1 = 0; // nums1 value to copy to nums1[pos]\n\n // For each array position i from 0 to n-1, find up to two elements\n // in nums1 that are closest to nums2[i] (one on each side of nums2[i]).\n // Calculate a new absolute difference for each of these elements.\n for (int i=0; i Integer.MIN_VALUE) {\n // If a valid element exists, calculate a new absolute difference\n // at the current position, and calculate how much smaller this is\n // than the current absolute difference. If the result is better\n // than what we have seen so far, update the maximum difference and\n // save the data for the current position.\n int newDiff = Math.abs(floor - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = floor;\n maxDiff = diff;\n }\n }\n \n // Find the smallest element in nums1 that is greater than or equal to\n // the current element in nums2, if such an element exists.\n int ceiling = arrayCeiling(snums1, n2);\n if (ceiling < Integer.MAX_VALUE) {\n // Same as above\n int newDiff = Math.abs(ceiling - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = ceiling;\n maxDiff = diff;\n }\n }\n }\n\n // If we found a replacement value, overwrite the original value.\n if (newn1 > 0) {\n nums1[pos] = newn1;\n }\n \n // Calculate the absolute sum difference with the replaced value.\n int sum = 0;\n for (int i=0; i= val) {\n min = arr[mid];\n hi = mid-1;\n } else {\n lo = mid+1;\n }\n }\n \n return min;\n }\n}\n", + "title": "1818. Minimum Absolute Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive integer arrays nums1 and nums2 , both of length n . The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n ( 0-indexed ). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1 . Since the answer may be large, return it modulo 10^9 + 7 . |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0 , or", + "-x if x < 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,5], nums2 = [2,3,5]Output:3Explanation:There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of|1-2| + (|1-3| or |5-3|) + |5-5| =3.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]Output:0Explanation:nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]Output:20Explanation:Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2682 ms (Top 14.06%) | Memory: 30 MB (Top 26.09%)\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n diff = []\n sum = 0\n for i in range(n):\n temp = abs(nums1[i]-nums2[i])\n diff.append(temp)\n sum += temp\n nums1.sort()\n best_diff = []\n for i in range(n):\n idx = bisect.bisect_left(nums1, nums2[i])\n if idx != 0 and idx != n:\n best_diff.append(\n min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n elif idx == 0:\n best_diff.append(abs(nums2[i]-nums1[idx]))\n else:\n best_diff.append(abs(nums2[i]-nums1[idx-1]))\n saved = 0\n for i in range(n):\n saved = max(saved, diff[i]-best_diff[i])\n return (sum-saved) % ((10**9)+(7))", + "title": "1818. Minimum Absolute Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A parentheses string is valid if and only if: You are given a parentheses string s . In one move, you can insert a parenthesis at any position of the string. Return the minimum number of moves required to make s valid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "It is the empty string,", + "It can be written as AB ( A concatenated with B ), where A and B are valid strings, or", + "It can be written as (A) , where A is a valid string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"())\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(((\"Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minAddToMakeValid(String s) {\n int open = 0;\n int extra = 0;\n for(int i=0;i int:\n l, r = list(), list()\n for i in s:\n if i == \"(\":\n l.append(i)\n else:\n if l:\n l.pop()\n else:\n r.append(i)\n return len(l) + len(r)\n", + "title": "921. Minimum Add to Make Parentheses Valid", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array, nums , and an integer k . nums comprises of only 0 's and 1 's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1 's . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is 0 or 1 .", + "1 <= k <= sum(nums)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,0,1,0,1], k = 2Output:1Explanation:In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,0,0,0,0,1,1], k = 3Output:5Explanation:In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,1], k = 2Output:0Explanation:nums already has 2 consecutive 1's.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 32.47%) | Memory: 112.8 MB (Top 59.74%)\nclass Solution {\n public int minMoves(int[] nums, int k) {\n var gaps = new ArrayList();\n for(int i = 0, last = -1; i < nums.length; ++i){\n if (nums[i] == 1){\n if (last > -1){\n gaps.add(i-1-last);\n }\n last = i;\n }\n }\n int lsum = 0, rsum = 0, wlsum = 0, wrsum = 0;\n for(int i = k/2-1; i >= 0; --i){\n lsum += gaps.get(i);//lsum = 3+0\n wlsum += lsum;//wlsum = 1*3+2*0\n }\n for(int i = k/2; i < k-1; ++i){\n rsum += gaps.get(i);//rsum = 2+5\n wrsum += rsum;//wrsum = 2*2+1*5\n }\n int ans = wlsum+wrsum;\n for(int p = 0, q = k/2, r = k-1; r < gaps.size(); ++p, ++q, ++r){\n wlsum += (k/2)*gaps.get(q) - lsum;\n lsum += gaps.get(q) - gaps.get(p);\n\n rsum += gaps.get(r) - gaps.get(q);\n wrsum += rsum-((k-1)/2)*gaps.get(q);\n\n ans = Math.min(ans,wlsum+wrsum);\n }\n return ans;\n }\n}", + "title": "1703. Minimum Adjacent Swaps for K Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array, nums , and an integer k . nums comprises of only 0 's and 1 's. In one move, you can choose two adjacent indices and swap their values. Return the minimum number of moves required so that nums has k consecutive 1 's . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is 0 or 1 .", + "1 <= k <= sum(nums)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,0,1,0,1], k = 2Output:1Explanation:In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,0,0,0,0,1,1], k = 3Output:5Explanation:In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,1], k = 2Output:0Explanation:nums already has 2 consecutive 1's.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n p = [i for i, v in enumerate(nums) if v == 1]\n # p[i]: the position of i-th 1\n n = len(p)\n presum = [0]*(n+1)\n # presum[i]: sum(p[0]...p[i-1])\n for i in range(n):\n presum[i+1] = presum[i]+p[i]\n\n res = inf\n\n # sliding window\n if k % 2 == 1:\n # if odd\n radius = (k-1)//2\n for i in range(radius, n-radius):\n # i-radius ... i ... i+radius\n # move radius to i\n # i+1, ..., i+radius\n right = presum[i+radius+1]-presum[i+1]\n # i-radius, ..., i-1\n left = presum[i]-presum[i-radius]\n res = min(res, right-left)\n return res-radius*(radius+1)\n else:\n # even\n radius = (k-2)//2\n for i in range(radius, n-radius-1):\n # i-radius ... i i+1 ... i+radius+1\n # move radius to i (moving to i+1 is also OK)\n # i+1, ..., i+radius+1\n right = presum[i+radius+2]-presum[i+1]\n # i-radius, ..., i-1\n left = presum[i]-presum[i-radius]\n res = min(res, right-left-p[i])\n return res-radius*(radius+1)-(radius+1)\n", + "title": "1703. Minimum Adjacent Swaps for K Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num , representing a large integer, and an integer k . We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num . There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k th smallest wonderful integer . The tests are generated in such a way that k th smallest wonderful integer exists. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, when num = \"5489355142\" : The 1 st smallest wonderful integer is \"5489355214\" . The 2 nd smallest wonderful integer is \"5489355241\" . The 3 rd smallest wonderful integer is \"5489355412\" . The 4 th smallest wonderful integer is \"5489355421\" .", + "The 1 st smallest wonderful integer is \"5489355214\" .", + "The 2 nd smallest wonderful integer is \"5489355241\" .", + "The 3 rd smallest wonderful integer is \"5489355412\" .", + "The 4 th smallest wonderful integer is \"5489355421\" ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5489355142\", k = 4Output:2Explanation:The 4thsmallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"", + "image": null + }, + { + "text": "Example 2: Input:num = \"11112\", k = 4Output:4Explanation:The 4thsmallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"", + "image": null + }, + { + "text": "Example 3: Input:num = \"00123\", k = 1Output:1Explanation:The 1stsmallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 61.80%) | Memory: 42.9 MB (Top 13.48%)\nclass Solution {\n public int getMinSwaps(String num, int k) {\n int[] nums=new int[num.length()];\n int[] org=new int[num.length()];\n\n for(int i=0;i0 && j!=i){\n swap(org,j,j-1);\n ans++;\n j--;\n }\n\n }\n\n }\n\n return ans;\n\n }\n\npublic void nextPermutation(int[] nums) {\n\n if(nums.length<=1)\n return;\n\n int j=nums.length-2;\n while(j>=0 && nums[j]>=nums[j+1])\n j--;\n\n if(j>=0){\n int k=nums.length-1;\n while(nums[j]>=nums[k])\n k--;\n\n swap(nums,j,k);\n\n }\n\n reverse(nums,j+1,nums.length-1);\n\n }\n\n public void swap(int[] nums,int j,int k){\n int temp=nums[j];\n nums[j]=nums[k];\n nums[k]=temp;\n }\n\n public void reverse(int[] nums,int i,int j){\n while(i<=j){\n swap(nums,i,j);\n i++;\n j--;\n }\n }\n}", + "title": "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num , representing a large integer, and an integer k . We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num . There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k th smallest wonderful integer . The tests are generated in such a way that k th smallest wonderful integer exists. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, when num = \"5489355142\" : The 1 st smallest wonderful integer is \"5489355214\" . The 2 nd smallest wonderful integer is \"5489355241\" . The 3 rd smallest wonderful integer is \"5489355412\" . The 4 th smallest wonderful integer is \"5489355421\" .", + "The 1 st smallest wonderful integer is \"5489355214\" .", + "The 2 nd smallest wonderful integer is \"5489355241\" .", + "The 3 rd smallest wonderful integer is \"5489355412\" .", + "The 4 th smallest wonderful integer is \"5489355421\" ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5489355142\", k = 4Output:2Explanation:The 4thsmallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"", + "image": null + }, + { + "text": "Example 2: Input:num = \"11112\", k = 4Output:4Explanation:The 4thsmallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"", + "image": null + }, + { + "text": "Example 3: Input:num = \"00123\", k = 1Output:1Explanation:The 1stsmallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1243 ms (Top 52.9%) | Memory: 16.52 MB (Top 32.4%)\n\nclass Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n num = list(num)\n orig = num.copy()\n \n for _ in range(k): \n for i in reversed(range(len(num)-1)): \n if num[i] < num[i+1]: \n ii = i+1 \n while ii < len(num) and num[i] < num[ii]: ii += 1\n num[i], num[ii-1] = num[ii-1], num[i]\n lo, hi = i+1, len(num)-1\n while lo < hi: \n num[lo], num[hi] = num[hi], num[lo]\n lo += 1\n hi -= 1\n break \n \n ans = 0\n for i in range(len(num)): \n ii = i\n while orig[i] != num[i]: \n ans += 1\n ii += 1\n num[i], num[ii] = num[ii], num[i]\n return ans ", + "title": "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0] , amount[1] , and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "amount.length == 3", + "0 <= amount[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:amount = [1,4,2]Output:4Explanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.", + "image": null + }, + { + "text": "Example 2: Input:amount = [5,4,4]Output:7Explanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.", + "image": null + }, + { + "text": "Example 3: Input:amount = [5,0,0]Output:5Explanation:Every second, we fill up a cold cup.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 59.66%) | Memory: 41.5 MB (Top 48.39%)\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z){return sum/2 +sum%2;}\n if(x==0&&y==0){return z;}\n else{return z;}\n }\n}", + "title": "2335. Minimum Amount of Time to Fill Cups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0] , amount[1] , and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "amount.length == 3", + "0 <= amount[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:amount = [1,4,2]Output:4Explanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.", + "image": null + }, + { + "text": "Example 2: Input:amount = [5,4,4]Output:7Explanation:One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.", + "image": null + }, + { + "text": "Example 3: Input:amount = [5,0,0]Output:5Explanation:Every second, we fill up a cold cup.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 62.11%) | Memory: 13.9 MB (Top 56.09%)\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n\n count = 0\n amount = sorted(amount, reverse=True)\n while amount[0] > 0:\n amount[0] -= 1\n amount[1] -= 1\n count += 1\n amount = sorted(amount, reverse=True)\n return count", + "title": "2335. Minimum Amount of Time to Fill Cups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes . If there is not any such rectangle, return 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 500", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[1,3],[3,1],[3,3],[2,2]]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/08/03/rec1.JPG" + }, + { + "text": "Example 2: Input:points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/08/03/rec2.JPG" + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 98.98%) | Memory: 45.00 MB (Top 39.53%)\n\nclass Solution {\n public int minAreaRect(int[][] points) {\n HashMap> hm = new HashMap<>();\n int area=Integer.MAX_VALUE;\n \n for(int[] point: points)\n { \n if(!hm.containsKey(point[0]))\n hm.put(point[0],new HashSet()); \n hm.get(point[0]).add(point[1]); // x-coordinate already exits, just add the y-coordinate to the set\n }\n \n for(int i=0;iMath.abs((x2-x1) * (y2-y1))) //pre-calulate the area to avoid unecessary lookup. This step reduced the time from 186ms to 57ms.\n {\n if(hm.get(x1).contains(y2) && hm.get(x2).contains(y1)) // learnt from other leetcoders. Thank you.\n area=Math.abs((x2-x1) * (y2-y1)); \n }\n }\n \n }\n }\n \n return area int:\n points = sorted(points, key=lambda item: (item[0], item[1]))\n cols = defaultdict(list)\n \n for x,y in points:\n cols[x].append(y)\n \n lastx = {}\n ans = float('inf')\n \n for x in cols:\n col = cols[x]\n for i, y1 in enumerate(col):\n for j in range(i):\n y2 = col[j]\n if (y2,y1) in lastx:\n ans = min(ans, abs((x-lastx[y2,y1])*(y2-y1)))\n lastx[y2,y1] = x\n \n return 0 if ans==float('inf') else ans", + "title": "939. Minimum Area Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes . If there is not any such rectangle, return 0 . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 50", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2],[2,1],[1,0],[0,1]]Output:2.00000Explanation:The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.", + "image": "https://assets.leetcode.com/uploads/2018/12/21/1a.png" + }, + { + "text": "Example 2: Input:points = [[0,1],[2,1],[1,1],[1,0],[2,0]]Output:1.00000Explanation:The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/2.png" + }, + { + "text": "Example 3: Input:points = [[0,3],[1,2],[3,1],[1,3],[2,1]]Output:0Explanation:There is no possible rectangle to form from these points.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 66.67%) | Memory: 56.7 MB (Top 16.67%)\nclass Solution {\n public double minAreaFreeRect(int[][] points) {\n Map, Map>> map = new HashMap<>();\n\n double res = Double.MAX_VALUE;\n for (int i = 0; i < points.length; i++) {\n int[] p1 = points[i];\n for (int j = i+1; j < points.length; j++) {\n int[] p2 = points[j];\n // get mid point\n Pair pm = new Pair((p1[0]+p2[0])/2d, (p1[1]+p2[1])/2d);\n if (!map.containsKey(pm))\n map.put(pm, new HashMap<>());\n // get diagonal length\n double dist2 = dist2(p1, p2);\n if (!map.get(pm).containsKey(dist2))\n map.get(pm).put(dist2, new ArrayList<>());\n\n // calculate area for each pair of p3/p4 and check min\n // Worst case is each pair has same mid point with same length\n // At worst case, below operation costs O(N)\n for (int[][] ps : map.get(pm).get(dist2)) {\n double d1 = dist2(p1, ps[0]);\n double d2 = dist2(p1, ps[1]);\n res = Math.min(res, Math.sqrt(d1 * d2));\n }\n map.get(pm).get(dist2).add(new int[][]{p1, p2});\n }\n }\n\n return res == Double.MAX_VALUE ? 0 : res;\n }\n\n private double dist2(int[] p1, int[] p2) {\n return (p2[0]-p1[0])*(p2[0]-p1[0]) + (p2[1]-p1[1])*(p2[1]-p1[1]);\n }\n}", + "title": "963. Minimum Area Rectangle II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of points in the X-Y plane points where points[i] = [x i , y i ] . Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes . If there is not any such rectangle, return 0 . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 50", + "points[i].length == 2", + "0 <= x i , y i <= 4 * 10^4", + "All the given points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,2],[2,1],[1,0],[0,1]]Output:2.00000Explanation:The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.", + "image": "https://assets.leetcode.com/uploads/2018/12/21/1a.png" + }, + { + "text": "Example 2: Input:points = [[0,1],[2,1],[1,1],[1,0],[2,0]]Output:1.00000Explanation:The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/2.png" + }, + { + "text": "Example 3: Input:points = [[0,3],[1,2],[3,1],[1,3],[2,1]]Output:0Explanation:There is no possible rectangle to form from these points.", + "image": "https://assets.leetcode.com/uploads/2018/12/22/3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n N = len(points)\n \n seen = set()\n for point in points:\n seen.add(tuple(point))\n\n # length^2\n def length2(a, b):\n return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])\n \n best = 1e30\n for i in range(N):\n for j in range(N):\n if i == j:\n continue\n \n lij = length2(points[i], points[j])\n for k in range(N):\n if i == k or j == k:\n continue\n \n # given i->j line, add to k to find l\n dx, dy = points[j][0] - points[i][0], points[j][1] - points[i][1]\n \n pl = (points[k][0] + dx, points[k][1] + dy)\n if pl not in seen:\n continue\n \n lik = length2(points[i], points[k])\n ljk = length2(points[j], points[k])\n\n lil = length2(points[i], pl)\n ljl = length2(points[j], pl)\n lkl = length2(points[k], pl)\n \n if lij == lkl and lik == ljl and lil == ljk:\n best = min(best, sqrt(lij * lik * lil) / sqrt(max(lij, lik, lil)))\n \n if best >= 1e29:\n return 0\n return best\n", + "title": "963. Minimum Area Rectangle II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings s1 and s2 , return the lowest ASCII sum of deleted characters to make two strings equal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 1000", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"sea\", s2 = \"eat\"Output:231Explanation:Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\nDeleting \"t\" from \"eat\" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"delete\", s2 = \"leet\"Output:403Explanation:Deleting \"dee\" from \"delete\" to turn the string into \"let\",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting \"e\" from \"leet\" adds 101[e] to the sum.\nAt the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4020 ms (Top 5.03%) | Memory: 205.5 MB (Top 14.36%)\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n m, n, lookup = len(s1), len(s2), {}\n def fun(i, j):\n if (i,j) in lookup:\n return lookup[(i,j)]\n if i < 0:\n return sum([ord(char) for char in s2[:j+1]])\n if j < 0:\n return sum([ord(char) for char in s1[:i+1]])\n if s1[i] == s2[j]:\n res = fun(i-1, j-1)\n else:\n res = min(ord(s1[i]) + fun(i-1,j), ord(s2[j]) + fun(i,j-1))\n lookup[(i,j)] = res\n return lookup[(i,j)]\n return fun(m-1, n-1)", + "title": "712. Minimum ASCII Delete Sum for Two Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimum average difference . If there are multiple such indices, return the smallest one. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The absolute difference of two numbers is the absolute value of their difference.", + "The average of n elements is the sum of the n elements divided ( integer division ) by n .", + "The average of 0 elements is considered to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,3,9,5,3]Output:3Explanation:- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:0Explanation:The only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 34.34%) | Memory: 76.7 MB (Top 35.00%)\nclass Solution {\n public int minimumAverageDifference(int[] nums) {\n if(nums.length == 1){\n return 0;\n }\n int idx = -1;\n long min = Integer.MAX_VALUE;\n long suml = nums[0];\n long sumr = 0;\n for(int i = 1; i < nums.length; i++){\n sumr += nums[i];\n }\n int i = 1;\n int calc = 0;\n int left = 1;\n int right = nums.length - left;\n long[] arr = new long[nums.length];\n while(i < nums.length){\n long diff = Math.abs((suml/left) - (sumr/right));\n arr[calc] = diff;\n if(diff < min){\n min = diff;\n idx = calc;\n }\n suml += nums[i];\n sumr -= nums[i];\n left++;\n right--;\n calc++;\n i++;\n }\n arr[calc] = suml/nums.length;\n if(arr[calc] < min){\n min = arr[calc];\n idx = nums.length - 1;\n }\n // for(i = 0; i < nums.length; i++){\n // System.out.println(arr[i]);\n // }\n return (int)idx;\n }\n}", + "title": "2256. Minimum Average Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. Return the index with the minimum average difference . If there are multiple such indices, return the smallest one. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The absolute difference of two numbers is the absolute value of their difference.", + "The average of n elements is the sum of the n elements divided ( integer division ) by n .", + "The average of 0 elements is considered to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,3,9,5,3]Output:3Explanation:- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:0Explanation:The only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "from itertools import accumulate\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n size = len(nums)\n\n nums[::] = list(accumulate(nums))\n total = nums[-1]\n \n min_tuple = [0, sys.maxsize]\n \n for (i, n) in enumerate(nums):\n i = i + 1\n avg_i = floor(n/i)\n \n diff = size - i\n total_avg = floor((total - n) / (diff if diff>0 else 1))\n\n avg = abs( avg_i - total_avg) \n if min_tuple[1] > avg:\n min_tuple[1] = avg\n min_tuple[0] = i - 1\n \n return min_tuple[0]\n", + "title": "2256. Minimum Average Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Given two integers start and goal , return the minimum number of bit flips to convert start to goal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:start = 10, goal = 7Output:3Explanation:The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010-> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right:1111 ->0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:start = 3, goal = 4Output:3Explanation:The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011-> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right:000 ->100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic static int minBitFlips(int a1, int a2) {\n\t\tint n = (a1 ^ a2);\n\t\tint res = 0;\n\t\twhile (n != 0) {\n\t\t\tres++;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn res;\n\t}\n}", + "title": "2220. Minimum Bit Flips to Convert Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 . Given two integers start and goal , return the minimum number of bit flips to convert start to goal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:start = 10, goal = 7Output:3Explanation:The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010-> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right:1111 ->0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:start = 3, goal = 4Output:3Explanation:The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011-> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right:000 ->100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minBitFlips(self, s: int, g: int) -> int:\n count = 0 \n while s or g:\n if s%2 != g%2: count+=1\n s, g = s//2, g//2\n return count", + "title": "2220. Minimum Bit Flips to Convert Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting only of the characters '0' and '1' . In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0100\"Output:1Explanation:If you change the last character to '1', s will be \"0101\", which is alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"Output:0Explanation:s is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"Output:2Explanation:You need two operations to reach \"0101\" or \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 86.00%) | Memory: 41.7 MB (Top 99.33%)\nclass Solution {\n public int minOperations(String s) {\n int count0 = 0; // changes required when the string starts from 0\n int count1 = 0; // changes required when the string starts from 1\n\n for(int i = 0; i < s.length(); i++){\n\n // string starts with 1 => all chars at even places should be 1 and that at odd places should be 0\n if((i % 2 == 0 && s.charAt(i) == '0') || (i % 2 != 0 && s.charAt(i) == '1'))\n count1++;\n\n // string starts with 0 => all chars at even places should be 0 and that at odd places should be 1\n else if((i % 2 == 0 && s.charAt(i) == '1') || (i % 2 != 0 && s.charAt(i) == '0'))\n count0++;\n }\n\n // return minimum of the two\n return Math.min(count0, count1);\n }\n}\n", + "title": "1758. Minimum Changes To Make Alternating Binary String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s consisting only of the characters '0' and '1' . In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not. Return the minimum number of operations needed to make s alternating . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0100\"Output:1Explanation:If you change the last character to '1', s will be \"0101\", which is alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"Output:0Explanation:s is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1111\"Output:2Explanation:You need two operations to reach \"0101\" or \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 52 ms (Top 66.2%) | Memory: 16.53 MB (Top 16.1%)\n\nclass Solution:\n def minOperations(self, s: str) -> int:\n count = 0\n count1 = 0\n for i in range(len(s)):\n if i % 2 == 0:\n if s[i] == '1':\n count += 1\n if s[i] == '0':\n count1 += 1\n else:\n if s[i] == '0':\n count += 1\n if s[i] == '1':\n count1 += 1\n return min(count, count1)", + "title": "1758. Minimum Changes To Make Alternating Binary String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array cards where cards[i] represents the value of the i th card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= cards.length <= 10^5", + "0 <= cards[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:cards = [3,4,2,3,4,7]Output:4Explanation:We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,0,5,3]Output:-1Explanation:There is no way to pick up a set of consecutive cards that contain a pair of matching cards.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 92.02%) | Memory: 61 MB (Top 90.10%)\n\nclass Solution\n{\n public int minimumCardPickup(int[] cards)\n {\n Map map = new HashMap<>();\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < cards.length; i++)\n {\n if(map.containsKey(cards[i]))\n min = Math.min(i-map.get(cards[i])+1,min); // Check if the difference in indices is smaller than minimum\n map.put(cards[i],i); // Update the last found index of the card\n }\n return min == Integer.MAX_VALUE?-1:min; // Repetition found or not\n }\n}", + "title": "2260. Minimum Consecutive Cards to Pick Up", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array cards where cards[i] represents the value of the i th card. A pair of cards are matching if the cards have the same value. Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= cards.length <= 10^5", + "0 <= cards[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:cards = [3,4,2,3,4,7]Output:4Explanation:We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.", + "image": null + }, + { + "text": "Example 2: Input:cards = [1,0,5,3]Output:-1Explanation:There is no way to pick up a set of consecutive cards that contain a pair of matching cards.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n d={}\n x=[]\n for i in range(len(cards)):\n if cards[i] not in d:\n d[cards[i]]=i\n else:\n x.append(i-d[cards[i]])\n d[cards[i]]=i\n if len(x)<=0:\n return -1\n return min(x)+1\n", + "title": "2260. Minimum Consecutive Cards to Pick Up", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days . Each day is an integer from 1 to 365 . Train tickets are sold in three different ways : The passes allow that many days of consecutive travel. Return the minimum number of dollars you need to travel every day in the given list of days . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "a 1-day pass is sold for costs[0] dollars,", + "a 7-day pass is sold for costs[1] dollars, and", + "a 30-day pass is sold for costs[2] dollars." + ], + "examples": [ + { + "text": "Example 1: Input:days = [1,4,6,7,8,20], costs = [2,7,15]Output:11Explanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.", + "image": null + }, + { + "text": "Example 2: Input:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]Output:17Explanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mincostTickets(int[] days, int[] costs) {\n HashSet set = new HashSet<>();\n for(int day: days) set.add(day);\n int n = days[days.length - 1];\n int[] dp = new int[n + 1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n for(int i = 1; i <= n; i++){\n if(!set.contains(i)){\n dp[i] = dp[i - 1];\n continue;\n }\n int a = dp[Math.max(0, i - 1)] + costs[0];\n int b = dp[Math.max(0, i - 7)] + costs[1];\n int c = dp[Math.max(0, i - 30)] + costs[2];\n dp[i] = Math.min(a, Math.min(b, c));\n }\n return dp[n];\n }\n}", + "title": "983. Minimum Cost For Tickets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days . Each day is an integer from 1 to 365 . Train tickets are sold in three different ways : The passes allow that many days of consecutive travel. Return the minimum number of dollars you need to travel every day in the given list of days . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "a 1-day pass is sold for costs[0] dollars,", + "a 7-day pass is sold for costs[1] dollars, and", + "a 30-day pass is sold for costs[2] dollars." + ], + "examples": [ + { + "text": "Example 1: Input:days = [1,4,6,7,8,20], costs = [2,7,15]Output:11Explanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.", + "image": null + }, + { + "text": "Example 2: Input:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]Output:17Explanation:For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 83.24%) | Memory: 17.30 MB (Top 40.22%)\n\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n", + "title": "983. Minimum Cost For Tickets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [start row , start col ] indicates that initially , a robot is at the cell (start row , start col ) . You are also given an integer array homePos where homePos = [home row , home col ] indicates that its home is at the cell (home row , home col ) . The robot needs to go to its home. It can move one cell in four directions: left , right , up , or down , and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n . Return the minimum total cost for this robot to return home . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the robot moves up or down into a cell whose row is r , then this move costs rowCosts[r] .", + "If the robot moves left or right into a cell whose column is c , then this move costs colCosts[c] ." + ], + "examples": [ + { + "text": "Example 1: Input:startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]Output:18Explanation:One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2,1). This move costs colCosts[1] = 2.\n-> It goes right to (2,2). This move costs colCosts[2] = 6.\n-> It goes right to (2,3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18", + "image": "https://assets.leetcode.com/uploads/2021/10/11/eg-1.png" + }, + { + "text": "Example 2: Input:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]Output:0Explanation:The robot is already at its home. Since no moves occur, the total cost is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {\n int total = 0;\n \n // if home is to the down of start move, down till there\n if(homePos[0]>startPos[0]){\n int i = startPos[0]+1;\n while(i<=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is up from the start, move up till there\n else if(homePos[0]=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n // if home is right to the start, move right till there\n if(homePos[1]>startPos[1]){\n int i = startPos[1]+1;\n while(i<=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is left to the start, move left till there\n else if(homePos[1]=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n return total;\n }\n}\n\n", + "title": "2087. Minimum Cost Homecoming of a Robot in a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [start row , start col ] indicates that initially , a robot is at the cell (start row , start col ) . You are also given an integer array homePos where homePos = [home row , home col ] indicates that its home is at the cell (home row , home col ) . The robot needs to go to its home. It can move one cell in four directions: left , right , up , or down , and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n . Return the minimum total cost for this robot to return home . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the robot moves up or down into a cell whose row is r , then this move costs rowCosts[r] .", + "If the robot moves left or right into a cell whose column is c , then this move costs colCosts[c] ." + ], + "examples": [ + { + "text": "Example 1: Input:startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]Output:18Explanation:One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2,1). This move costs colCosts[1] = 2.\n-> It goes right to (2,2). This move costs colCosts[2] = 6.\n-> It goes right to (2,3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18", + "image": "https://assets.leetcode.com/uploads/2021/10/11/eg-1.png" + }, + { + "text": "Example 2: Input:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]Output:0Explanation:The robot is already at its home. Since no moves occur, the total cost is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n def getRange(left, right, array):\n if left > right:\n right, left = left, right\n return sum((array[i] for i in range(left,right+1)))\n \n totalRowCost = getRange(startPos[0], homePos[0], rowCosts)\n totalColCost = getRange(startPos[1], homePos[1], colCosts)\n \n #Don't pay for the position you start out on\n return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]]\n", + "title": "2087. Minimum Cost Homecoming of a Robot in a Grid", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free . The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost , where cost[i] denotes the cost of the i th candy, return the minimum cost of buying all the candies . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if there are 4 candies with costs 1 , 2 , 3 , and 4 , and the customer buys candies with costs 2 and 3 , they can take the candy with cost 1 for free, but not the candy with cost 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [1,2,3]Output:5Explanation:We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is theonlyway we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.", + "image": null + }, + { + "text": "Example 2: Input:cost = [6,5,7,9,2,2]Output:23Explanation:The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.", + "image": null + }, + { + "text": "Example 3: Input:cost = [5,5]Output:10Explanation:Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 83.40%) | Memory: 42.5 MB (Top 73.57%)\nclass Solution {\n /** Algorithm\n * 1. Sort the cost array.\n * 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.\n * 3. Decrement the position by 3 and continue. stop when you reach 1.\n * 4. From 1, add the remaining 1 or 2 items.\n *\n */\n public int minimumCost(int[] cost) {\n int minCost = 0;\n int index = cost.length -1;\n Arrays.sort(cost);\n // add items in pairs of 2, the 3rd one getting it for free.\n while (index > 1) {\n minCost += cost[index] + cost[index -1];\n index -= 3;\n }\n // add the remaining 1, 2 items, if any.\n while(index >= 0) {\n minCost += cost[index--];\n }\n return minCost;\n }\n}", + "title": "2144. Minimum Cost of Buying Candies With Discount", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free . The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost , where cost[i] denotes the cost of the i th candy, return the minimum cost of buying all the candies . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if there are 4 candies with costs 1 , 2 , 3 , and 4 , and the customer buys candies with costs 2 and 3 , they can take the candy with cost 1 for free, but not the candy with cost 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:cost = [1,2,3]Output:5Explanation:We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is theonlyway we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.", + "image": null + }, + { + "text": "Example 2: Input:cost = [6,5,7,9,2,2]Output:23Explanation:The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.", + "image": null + }, + { + "text": "Example 3: Input:cost = [5,5]Output:10Explanation:Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 72 ms (Top 49.84%) | Memory: 13.8 MB (Top 58.81%)\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n cost.sort(reverse=True)\n res, i, N = 0, 0, len(cost)\n while i < N:\n res += sum(cost[i : i + 2])\n i += 3\n return res", + "title": "2144. Minimum Cost of Buying Candies With Discount", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a valid boolean expression as a string expression consisting of the characters '1' , '0' , '&' (bitwise AND operator), '|' (bitwise OR operator), '(' , and ')' . Return the minimum cost to change the final value of the expression . The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Note: '&' does not take precedence over '|' in the order of calculation . Evaluate parentheses first , then in left-to-right order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"()1|1\" and \"(1)&()\" are not valid while \"1\" , \"(((1))|(0))\" , and \"1|(0&(1))\" are valid expressions." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"1&(0|1)\"Output:1Explanation:We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(0&0)&(0&0&0)\"Output:3Explanation:We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(0|(1|0&1))\"Output:1Explanation:We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 57.69%) | Memory: 45.50 MB (Top 76.92%)\n\nclass Solution {\n Deque stack = new ArrayDeque<>();\n Deque opStack = new ArrayDeque<>();\n public int minOperationsToFlip(String expression) {\n for (char ch : expression.toCharArray()){\n if (ch == '('){\n opStack.push(ch);\n }else if (ch == ')'){\n while(opStack.peek()!='('){\n go();\n }\n opStack.pop(); // remove '('\n }else if (ch == '&' || ch == '|'){\n while(!opStack.isEmpty() && opStack.peek() != '('){\n go();\n }\n opStack.push(ch);\n }else{ // num\n stack.push(new int[]{ch, 1});\n }\n }\n while(!opStack.isEmpty()){\n go();\n }\n\n return stack.peek()[1];\n }\n \n private void go(){\n stack.push(check(opStack.pop(), stack.pop(), stack.pop()));\n }\n\n private int[] check(char op, int[] r, int[] l){\n int[] ans;\n int rval = r[0], rcost = r[1];\n int lval = l[0], lcost = l[1];\n if (op == '|' && rval == '0' && lval == '0'){\n ans = new int[]{'0', Math.min(rcost, lcost)};\n }else if (op == '|' && rval == '1' && lval == '0'){\n ans = new int[]{'1', 1};\n }else if (op == '|' && rval == '0' && lval == '1'){\n ans = new int[]{'1', 1};\n }else if (op == '|' && rval == '1' && lval == '1'){\n ans = new int[]{'1', 1 + Math.min(rcost, lcost)};\n }else if (op == '&' && rval == '0' && lval == '0'){\n ans = new int[]{'0', 1 + Math.min(rcost, lcost)};\n }else if (op == '&' && rval == '1' && lval == '0'){\n ans = new int[]{'0', 1};\n }else if (op == '&' && rval == '0' && lval == '1'){\n ans = new int[]{'0', 1};\n }else{ // &, 1, 1\n ans = new int[]{'1', Math.min(rcost, lcost)};\n }\n return ans;\n }\n}\n", + "title": "1896. Minimum Cost to Change the Final Value of Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a valid boolean expression as a string expression consisting of the characters '1' , '0' , '&' (bitwise AND operator), '|' (bitwise OR operator), '(' , and ')' . Return the minimum cost to change the final value of the expression . The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: Note: '&' does not take precedence over '|' in the order of calculation . Evaluate parentheses first , then in left-to-right order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"()1|1\" and \"(1)&()\" are not valid while \"1\" , \"(((1))|(0))\" , and \"1|(0&(1))\" are valid expressions." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"1&(0|1)\"Output:1Explanation:We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(0&0)&(0&0&0)\"Output:3Explanation:We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(0|(1|0&1))\"Output:1Explanation:We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n loc = {}\n stack = []\n for i in reversed(range(len(expression))):\n if expression[i] == \")\": stack.append(i)\n elif expression[i] == \"(\": loc[stack.pop()] = i \n \n def fn(lo, hi): \n \"\"\"Return value and min op to change value.\"\"\"\n if lo == hi: return int(expression[lo]), 1\n if expression[hi] == \")\" and loc[hi] == lo: return fn(lo+1, hi-1) # strip parenthesis \n mid = loc.get(hi, hi) - 1 \n v, c = fn(mid+1, hi)\n vv, cc = fn(lo, mid-1)\n if expression[mid] == \"|\": \n val = v | vv \n if v == vv == 0: chg = min(c, cc)\n elif v == vv == 1: chg = 1 + min(c, cc)\n else: chg = 1 \n else: # expression[k] == \"&\"\n val = v & vv\n if v == vv == 0: chg = 1 + min(c, cc)\n elif v == vv == 1: chg = min(c, cc)\n else: chg = 1\n return val, chg\n \n return fn(0, len(expression)-1)[1]\n", + "title": "1896. Minimum Cost to Change the Final Value of Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two groups of points where the first group has size 1 points, the second group has size 2 points, and size 1 >= size 2 . The cost of the connection between any two points are given in an size 1 x size 2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group . In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return the minimum cost it takes to connect the two groups . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "size 1 == cost.length", + "size 2 == cost[i].length", + "1 <= size 1 , size 2 <= 12", + "size 1 >= size 2", + "0 <= cost[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:cost = [[15, 96], [36, 2]]Output:17Explanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.", + "image": "https://assets.leetcode.com/uploads/2020/09/03/ex1.jpg" + }, + { + "text": "Example 2: Input:cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]Output:4Explanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.", + "image": "https://assets.leetcode.com/uploads/2020/09/03/ex2.jpg" + }, + { + "text": "Example 3: Input:cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]Output:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 345 ms (Top 92.68%) | Memory: 29.40 MB (Top 24.39%)\n\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group \n \n @lru_cache(None)\n def fn(i, mask):\n \"\"\"Return min cost of connecting group1[i:] and group2 represented as mask.\"\"\"\n if i == m: return sum(mn[j] for j in range(n) if not (mask & (1< j)\n return 0;\n \n if(dp[i][j] != -1)\n return dp[i][j];\n \n int mini = Integer.MAX_VALUE;\n for(int k = i ; k <= j ; k++){\n int cost = cuts[j+1]-cuts[i-1] + cut(cuts , i , k-1 , dp) + cut(cuts , k+1 , j , dp);\n mini = Math.min(cost , mini);\n }\n \n return dp[i][j] = mini;\n }\n}\n", + "title": "1547. Minimum Cost to Cut a Stick", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a wooden stick of length n units. The stick is labelled from 0 to n . For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return the minimum total cost of the cuts. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^6", + "1 <= cuts.length <= min(n - 1, 100)", + "1 <= cuts[i] <= n - 1", + "All the integers in cuts array are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, cuts = [1,3,4,5]Output:16Explanation:Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).", + "image": "https://assets.leetcode.com/uploads/2020/07/23/e1.jpg" + }, + { + "text": "Example 2: Input:n = 9, cuts = [5,6,1,4,2]Output:22Explanation:If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts = [0] + sorted(cuts) + [n]\n k = len(cuts)\n dp = [[float('inf')] * k for _ in range(k)]\n for l in range(1, k + 1):\n for beg in range(k - l):\n end = beg + l\n if l == 1:\n dp[beg][end] = 0\n continue\n for i in range(beg + 1, end):\n currcost = cuts[end] - cuts[beg]\n currcost += dp[beg][i] + dp[i][end]\n dp[beg][end] = min(dp[beg][end], currcost)\n return dp[0][k - 1]\n", + "title": "1547. Minimum Cost to Cut a Stick", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the i th worker and wage[i] is the minimum wage expectation for the i th worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Given the integer k , return the least amount of money needed to form a paid group satisfying the above conditions . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == quality.length == wage.length", + "1 <= k <= n <= 10^4", + "1 <= quality[i], wage[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:quality = [10,20,5], wage = [70,50,30], k = 2Output:105.00000Explanation:We pay 70 to 0thworker and 35 to 2ndworker.", + "image": null + }, + { + "text": "Example 2: Input:quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3Output:30.66667Explanation:We pay 4 to 0thworker, 13.33333 to 2ndand 3rdworkers separately.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 87.91%) | Memory: 46.20 MB (Top 6.51%)\n\nclass Worker implements Comparable {\n final int q, w;\n public Worker(int q, int w) {\n this.q = q;\n this.w = w;\n }\n @Override\n public int compareTo(Worker other) {\n return Integer.compare(w * other.q, q * other.w);\n }\n}\nclass Solution {\n public double mincostToHireWorkers(int[] quality, int[] wage, int k) {\n int n = quality.length;\n Worker[] a = new Worker[n];\n for (int i = 0; i < n; ++i) {\n a[i] = new Worker(quality[i], wage[i]);\n }\n Arrays.sort(a);\n int s = 0;\n double res = 1e15;\n PriorityQueue q = new PriorityQueue<>();\n for (Worker worker: a) {\n q.add(-worker.q);\n s += worker.q;\n if (q.size() > k) s += q.poll();\n if (q.size() == k) res = Math.min(res, (double) s * worker.w / worker.q);\n }\n return res;\n }\n}\n", + "title": "857. Minimum Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the i th worker and wage[i] is the minimum wage expectation for the i th worker. We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules: Given the integer k , return the least amount of money needed to form a paid group satisfying the above conditions . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == quality.length == wage.length", + "1 <= k <= n <= 10^4", + "1 <= quality[i], wage[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:quality = [10,20,5], wage = [70,50,30], k = 2Output:105.00000Explanation:We pay 70 to 0thworker and 35 to 2ndworker.", + "image": null + }, + { + "text": "Example 2: Input:quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3Output:30.66667Explanation:We pay 4 to 0thworker, 13.33333 to 2ndand 3rdworkers separately.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 147 ms (Top 96.67%) | Memory: 19.20 MB (Top 63.7%)\n\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n n=len(wage)\n arr=[[wage[i]/quality[i],quality[i]] for i in range(n)]\n arr.sort(key=lambda x:x[0])\n kSmallest=0\n pq=[]\n for i in range(k):\n heapq.heappush(pq,-arr[i][1])\n kSmallest+=arr[i][1]\n minCost=arr[k-1][0]*kSmallest\n for c in range(k,n):\n if pq and abs(pq[0])>arr[c][1]:\n qRem=-heappop(pq)\n kSmallest-=qRem\n kSmallest+=arr[c][1]\n heappush(pq,-arr[c][1])\n minCost=min(minCost,arr[c][0]*kSmallest)\n return minCost\n \n \n \n", + "title": "857. Minimum Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell (0, 0) . A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with cost = 1 . You can modify the sign on a cell one time only . Return the minimum cost to make the grid have at least one valid path . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1] )", + "2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1] )", + "3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j] )", + "4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j] )" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]Output:3Explanation:You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,3],[3,2,2],[1,1,4]]Output:0Explanation:You can follow the path from (0, 0) to (2, 2).", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid2.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[4,3]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 40.43%) | Memory: 53.4 MB (Top 83.19%)\nclass Solution {\n\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n\n private boolean isValid(int i,int j,int n,int m) {\n return i=0 && j>=0;\n }\n\n private boolean isValidDirection(int [][]grid,int []currEle,int nx,int ny) {\n int nextX=currEle[0],nextY = currEle[1];\n int n =grid.length,m = grid[0].length;\n\n switch(grid[currEle[0]][currEle[1]]) {\n case 1: nextY++; break;\n case 2: nextY--; break;\n case 3: nextX++; break;\n case 4: nextX--; break;\n }\n\n return nextX==nx && nextY==ny;\n }\n\n public int minCost(int[][] grid) {\n\n int n = grid.length;\n int m = grid[0].length;\n\n int dist[][] = new int[n][m];\n boolean vis[][] = new boolean[n][m];\n\n LinkedList queue = new LinkedList<>(); // for performing 01 BFS\n\n for(int i=0;i (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,3],[3,2,2],[1,1,4]]Output:0Explanation:You can follow the path from (0, 0) to (2, 2).", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid2.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[4,3]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/02/13/grid3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n changes = [[float(\"inf\") for _ in range(len(grid[0]))] for _ in range(len(grid))]\n heap = [(0,0,0)]\n dirn = [(0,1),(0,-1),(1,0),(-1,0)]\n while heap:\n dist,r,c = heapq.heappop(heap)\n if r >= len(grid) or r < 0 or c >= len(grid[0]) or c < 0 or changes[r][c] <= dist:\n continue\n if r == len(grid) - 1 and c == len(grid[0]) - 1:\n return dist\n changes[r][c] = dist\n for i in range(1,5):\n if i == grid[r][c]:\n heapq.heappush(heap,(dist,r+dirn[i-1][0],c+dirn[i-1][1]))\n else:\n heapq.heappush(heap,(dist+1,r+dirn[i-1][0],c+dirn[i-1][1]))\n return dist\n \n", + "title": "1368. Minimum Cost to Make at Least One Valid Path in a Grid", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n piles of stones arranged in a row. The i th pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all piles of stones into one pile . If it is impossible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == stones.length", + "1 <= n <= 30", + "1 <= stones[i] <= 100", + "2 <= k <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [3,2,4,1], k = 2Output:20Explanation:We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible.", + "image": null + }, + { + "text": "Example 2: Input:stones = [3,2,4,1], k = 3Output:-1Explanation:After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:stones = [3,5,1,2,6], k = 3Output:25Explanation:We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.04%) | Memory: 41.60 MB (Top 27.41%)\n\nclass Solution {\n int prefix[];\n public int mergeStones(int[] stones, int k) {\n int n=stones.length;\n if((n-1)%(k-1) != 0) return -1;\n prefix=new int[stones.length+1];\n prefix[0]=0;\n int sum=0;\n for(int i=0;i=j){\n return 0;\n }\n if(dp[i][j]!=-1){\n return dp[i][j];\n }\n int min=Integer.MAX_VALUE;\n for(int t=i;t 0) return -1;\n\n int[] prefix = new int[n+1];\n for (int i = 0; i < n; i++)\n prefix[i + 1] = prefix[i] + stones[i];\n\n int[][] dp = new int[n][n];\n for (int m = K; m <= n; ++m)\n for (int i = 0; i + m <= n; ++i) {\n int j = i + m - 1;\n dp[i][j] = Integer.MAX_VALUE;\n for (int mid = i; mid < j; mid += K - 1)\n dp[i][j] = Math.min(dp[i][j], dp[i][mid] + dp[mid + 1][j]);\n if ((j - i) % (K - 1) == 0)\n dp[i][j] += prefix[j + 1] - prefix[i];\n }\n return dp[0][n - 1];\n }\n}\n", + "title": "1000. Minimum Cost to Merge Stones", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We have n chips, where the position of the i th chip is position[i] . We need to move all the chips to the same position . In one step, we can change the position of the i th chip from position[i] to: Return the minimum cost needed to move all the chips to the same position. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "position[i] + 2 or position[i] - 2 with cost = 0 .", + "position[i] + 1 or position[i] - 1 with cost = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:position = [1,2,3]Output:1Explanation:First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.", + "image": "https://assets.leetcode.com/uploads/2020/08/15/chips_e1.jpg" + }, + { + "text": "Example 2: Input:position = [2,2,2,3,3]Output:2Explanation:We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.", + "image": "https://assets.leetcode.com/uploads/2020/08/15/chip_e2.jpg" + }, + { + "text": "Example 3: Input:position = [1,1000000000]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 34.98%)\nclass Solution {\n public int minCostToMoveChips(int[] position) {\n int even = 0;\n int odd = 0;\n for(int i=0;i int:\n count_even=0\n count_odd=0\n for i in position:\n if i%2==0:\n count_even+=1\n else:\n count_odd+=1\n return min(count_even,count_odd)\n", + "title": "1217. Minimum Cost to Move Chips to The Same Position", + "topic": "Database" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [x i , y i , time i ] denotes a road between cities x i and y i that takes time i minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j . In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less . The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey ( including the source and destination cities). Given maxTime , edges , and passingFees , return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/04/leetgraph1-1.png", + "https://assets.leetcode.com/uploads/2021/06/04/copy-of-leetgraph1-1.png" + ], + "constraints": [ + "1 <= maxTime <= 1000", + "n == passingFees.length", + "2 <= n <= 1000", + "n - 1 <= edges.length <= 1000", + "0 <= x i , y i <= n - 1", + "1 <= time i <= 1000", + "1 <= passingFees[j] <= 1000", + "The graph may contain multiple edges between two nodes.", + "The graph does not contain self loops." + ], + "examples": [ + { + "text": "Example 1: Input:maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:11Explanation:The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.", + "image": null + }, + { + "text": "Example 2: Input:maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:48Explanation:The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.", + "image": null + }, + { + "text": "Example 3: Input:maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:-1Explanation:There is no way to reach city 5 from city 0 within 25 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 94.1%) | Memory: 44.35 MB (Top 43.8%)\n\nclass Solution {\n record Node(int i, int t) {}\n record Cell(int i, int t, int c) {}\n public int minCost(int maxTime, int[][] edges, int[] fees) {\n int n = fees.length;\n\n // create the adjacency list graph\n List[] g = new List[n];\n for (int i = 0; i < n; i++) g[i] = new ArrayList<>();\n for (var e : edges) {\n g[e[0]].add(new Node(e[1], e[2]));\n g[e[1]].add(new Node(e[0], e[2]));\n }\n\n // Dijkstra\n Queue q = new PriorityQueue<>((a, b) -> a.c == b.c ? a.t - b.t : a.c - b.c);\n int[] T = new int[n]; // 1. visited: de-dup 2. de-dup on worst time\n\n q.offer(new Cell(0, 0, fees[0]));\n Arrays.fill(T, maxTime + 1);\n T[0] = 0;\n\n while (!q.isEmpty()) {\n var cur = q.poll();\n if (cur.i == n-1) return cur.c;\n \n for (var nei : g[cur.i]) {\n int t2 = cur.t + nei.t;\n if (t2 >= T[nei.i]) continue; // if time is worst, no reason to continue\n T[nei.i] = t2;\n q.offer(new Cell(nei.i, t2, cur.c + fees[nei.i]));\n }\n }\n\n return -1;\n }\n}", + "title": "1928. Minimum Cost to Reach Destination in Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [x i , y i , time i ] denotes a road between cities x i and y i that takes time i minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j . In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less . The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey ( including the source and destination cities). Given maxTime , edges , and passingFees , return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/04/leetgraph1-1.png", + "https://assets.leetcode.com/uploads/2021/06/04/copy-of-leetgraph1-1.png" + ], + "constraints": [ + "1 <= maxTime <= 1000", + "n == passingFees.length", + "2 <= n <= 1000", + "n - 1 <= edges.length <= 1000", + "0 <= x i , y i <= n - 1", + "1 <= time i <= 1000", + "1 <= passingFees[j] <= 1000", + "The graph may contain multiple edges between two nodes.", + "The graph does not contain self loops." + ], + "examples": [ + { + "text": "Example 1: Input:maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:11Explanation:The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.", + "image": null + }, + { + "text": "Example 2: Input:maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:48Explanation:The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.", + "image": null + }, + { + "text": "Example 3: Input:maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]Output:-1Explanation:There is no way to reach city 5 from city 0 within 25 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:\n '''\n Time: O((m+n)* maxtime), where m is length of edges\n Space: O(n*maxtime)\n '''\n n = len(passingFees)\n dp = [[math.inf]*(n) for _ in range(maxTime+1)]\n dp[0][0] = passingFees[0]\n\n ans = math.inf\n for k in range(1, maxTime+1):\n for x, y, time in edges:\n if k >= time:\n # dual direction\n dp[k][y] = min(dp[k][y], dp[k-time][x] + passingFees[y])\n dp[k][x] = min(dp[k][x], dp[k-time][y] + passingFees[x])\n \n ans = min(ans, dp[k][n-1])\n \n if ans == math.inf:\n return -1\n return ans\n", + "title": "1928. Minimum Cost to Reach Destination in Time", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A generic microwave supports cooking times for: To set the cooking time, you push at most four digits . The microwave normalizes what you push as four digits by prepending zeroes . It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You are given integers startAt , moveCost , pushCost , and targetSeconds . Initially , your finger is on the digit startAt . Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time . Remember that one minute consists of 60 seconds. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "at least 1 second.", + "at most 99 minutes and 99 seconds." + ], + "examples": [ + { + "text": "Example 1: Input:startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600Output:6Explanation:The following are the possible ways to set the cooking time.\n- 1 0 0 0, interpreted as 10 minutes and 0 seconds.\n  The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).\n  The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost.\n- 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.\n  The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12.\n- 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.\n  The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/1.png" + }, + { + "text": "Example 2: Input:startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76Output:6Explanation:The optimal way is to push two digits: 7 6, interpreted as 76 seconds.\nThe finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6\nNote other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.", + "image": "https://assets.leetcode.com/uploads/2021/12/30/2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.7%) | Memory: 39.44 MB (Top 55.0%)\n\nclass Solution {\n public int minCostSetTime(int startAt, int moveCost, int pushCost, int tar) {\n \n int min=tar/60, sec=tar%60, minCost=(moveCost+pushCost)*4;\n \n if(min>99) { min--; sec+=60; } // this is required to do because if tar>=6000 then min is 100 which is not possible as it atmost can be 99mins\n \n while(min>=0&&sec<=99) { // this while loop will work for atmost 2 iterations\n tar=min*100+sec;\n char arr[]=(\"\"+tar).toCharArray();\n int sameMove=0;\n for(int i=0;i int:\n poss = [(targetSeconds // 60, targetSeconds % 60)] # store possibilities as (minutes, seconds)\n \n if poss[0][0] > 99: # for when targetSeconds >= 6000\n poss = [(99, poss[0][1]+60)]\n \n if poss[0][0] >= 1 and (poss[0][1]+60) <= 99:\n\t\t\t# adding a second possibility e.g. (01, 16) -> (0, 76)\n poss.append((poss[0][0]-1, poss[0][1]+60))\n \n costs = list()\n \n for i in poss:\n curr_start = startAt\n curr_cost = 0\n \n minutes = str(i[0])\n if i[0] != 0: # 0s are prepended, so no need to push 0s\n for j in minutes:\n if int(j) != curr_start:\n curr_cost += moveCost\n curr_start = int(j)\n curr_cost += pushCost\n \n seconds = str(i[1])\n if len(seconds) == 1 and i[0] != 0: # seconds is a single digit, prepend a \"0\" to it\n seconds = \"0\" + seconds\n \n for j in seconds:\n if int(j) != curr_start:\n curr_cost += moveCost\n curr_start = int(j)\n curr_cost += pushCost\n costs.append(curr_cost)\n \n return min(costs)", + "title": "2162. Minimum Cost to Set Cooking Time", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array arr of positive integers, consider all binary trees such that: Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node . It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each node has either 0 or 2 children;", + "The values of arr correspond to the values of each leaf in an in-order traversal of the tree.", + "The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,2,4]Output:32Explanation:There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree1.jpg" + }, + { + "text": "Example 2: Input:arr = [4,11]Output:44", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 95.15%) | Memory: 41.70 MB (Top 26.54%)\n\nclass Solution {\n // Use stack. Similar to trapping the rain water problem and the largest rectangle under histogram\n // Use stack to keep a decreasing order by adding smaller values, while there is bigger value \n //arr[i] than the peek, pop it and store as mid and calculate the multiplication mid*min(arr[i], \n //stack.peek()).\n \n // NOTE: if we observe the number array, in order to obtain the smallest sum of all non-leaf\n // values, we want to merge those small values first. In order words, the smaller a value\n // is, the lower leaf it should stay because this way as we are building the tree up, \n // we are building smaller multiplication/parent node first as it is only going to get bigger\n\t// as we build the tree up. \n \n // Ex: 4 3 2 1 5\n // There are many ways we can build a tree following the problem's requirement. However, to \n // gain smallest sum. We need to merge 2 and 1 first as they are the two smallest ones. To\n\t// do that, we use the stack mentioned above as a decreasing order. After\n // that we get a parent node with value 2. This node could be a left or right child of its parent\n // but what we want is that its parent needs also be as small as possible. We also know that its\n // parent has one mutiplier already: 2. Note: this 2 is not from the product of 1 * 2, but from the max of child\n // 1 and 2 as the problem requires. So, we see what values next to the leaf 2 could be a \n\t// candidate. Obviously, 3 since it is the smallest one in the stack Then, 3\n // becomes the left child and 1*2 = 2 becomes right child. See below: \n // ...\n // / \\\n // 3 2\n // / \\\n // 2 1\n // \n \n // If we observe carefully, 3 2 1 is decreasing... So how about every time we see a \"dip\" point\n // in the array we calculate its multiplication. To do that, say we are at arr[i] and their \n // relations are arr[i-1] <= arr[i] <= arr[i+1]. The min multiplication is a[i] * min(arr[i-1], \n // arr[i+1]). Then the example above is arr[i] = 1, arr[i-1] = 2, arr[i+1] = 5\n \n public int mctFromLeafValues(int[] arr) {\n if(arr == null || arr.length < 2){\n return 0;\n }\n \n int res = 0;\n Stack stack = new Stack<>(); \n for(int num : arr){\n \n // while num is bigger than peek(), pop and calculate\n while(!stack.isEmpty() && stack.peek() <= num){\n int mid = stack.pop();\n if(stack.isEmpty()) \n res += mid * num;\n else\n res += mid * Math.min(stack.peek(), num);\n }\n \n stack.push(num); // if num is smaller, push into stack\n }\n \n // if there are values left in the stack, they sure will be mutiplied anyway\n // and added to the result. \n while(stack.size() > 1){ // > 1 because we have a peek() after pop() below\n res += stack.pop() * stack.peek();\n }\n \n return res;\n }\n}\n", + "title": "1130. Minimum Cost Tree From Leaf Values", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array arr of positive integers, consider all binary trees such that: Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node . It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each node has either 0 or 2 children;", + "The values of arr correspond to the values of each leaf in an in-order traversal of the tree.", + "The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [6,2,4]Output:32Explanation:There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree1.jpg" + }, + { + "text": "Example 2: Input:arr = [4,11]Output:44", + "image": "https://assets.leetcode.com/uploads/2021/08/10/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 472 ms (Top 12.37%) | Memory: 14 MB (Top 32.41%)\nclass Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n n = len(arr)\n d = {}\n def findMax(start,end):\n if (start,end) in d: return d[(start,end)]\n maxx = start\n for i in range(start+1,end+1):\n if arr[maxx] < arr[i] : maxx = i\n d[(start,end)] = arr[maxx]\n return arr[maxx]\n\n dp = [[float('inf') for i in range(n)] for j in range(n)]\n for gap in range(n):\n for row in range(n - gap):\n col = row + gap\n if gap == 0:\n dp[row][col] = 0\n elif gap == 1:\n dp[row][col] = arr[row] * arr[col]\n else:\n for k in range(row,col):\n val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]\n if val < dp[row][col]: dp[row][col] = val\n\n return dp[0][-1]\n", + "title": "1130. Minimum Cost Tree From Leaf Values", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges , where each edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 400", + "edges[i].length == 2", + "1 <= edges.length <= n * (n-1) / 2", + "1 <= u i , v i <= n", + "u i != v i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]Output:3Explanation:There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]Output:0Explanation:There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\npublic int minTrioDegree(int n, int[][] edges) {\n\t// to store edge information\n boolean[][] graph = new boolean[n+1][n+1];\n\t//to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph)\n int[] inDegree = new int[n+1];\n \n for(int[] edge : edges) {\n graph[edge[0]][edge[1]] = true;\n graph[edge[1]][edge[0]] = true;\n \n inDegree[edge[0]]++;\n inDegree[edge[1]]++;\n }\n \n int result = Integer.MAX_VALUE;\n for(int i=1; i<=n; i++) {\n for(int j=i+1; j<=n; j++) {\n if(graph[i][j]) {\n for(int k=j+1; k<=n; k++) {\n if(graph[i][k] && graph[j][k]) {\n result = Math.min(result, inDegree[i] + inDegree[j] + inDegree[k] - 6);\n }\n }\n }\n }\n }\n \n \n return result == Integer.MAX_VALUE ? -1 : result;\n}\n}", + "title": "1761. Minimum Degree of a Connected Trio in a Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges , where each edges[i] = [u i , v i ] indicates that there is an undirected edge between u i and v i . A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 400", + "edges[i].length == 2", + "1 <= edges.length <= n * (n-1) / 2", + "1 <= u i , v i <= n", + "u i != v i", + "There are no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]Output:3Explanation:There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]Output:0Explanation:There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.", + "image": "https://assets.leetcode.com/uploads/2021/01/26/trios2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 4822 ms (Top 24.41%) | Memory: 38.50 MB (Top 62.2%)\n\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = True\n degree[u-1] += 1\n degree[v-1] += 1\n \n ans = inf\n for i in range(n): \n for j in range(i+1, n):\n if graph[i][j]: \n for k in range(j+1, n):\n if graph[j][k] and graph[k][i]: \n ans = min(ans, degree[i] + degree[j] + degree[k] - 6)\n return ans if ans < inf else -1\n", + "title": "1761. Minimum Degree of a Connected Trio in a Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . The array nums is beautiful if: Note that an empty array is considered beautiful. You can delete any number of elements from nums . When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged . Return the minimum number of elements to delete from nums to make it beautiful. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length is even.", + "nums[i] != nums[i + 1] for all i % 2 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,3,5]Output:1Explanation:You can delete eithernums[0]ornums[1]to makenums= [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to makenumsbeautiful.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,2,2,3,3]Output:2Explanation:You can deletenums[0]andnums[5]to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 50.94%) | Memory: 58.2 MB (Top 89.06%)\nclass Solution {\n public int minDeletion(int[] nums) {\n\n int deletion = 0, n = nums.length;\n\n for (int i=0; i int:\n # Greedy !\n # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n # at the begining, we consider the num on the even index\n # when we delete a num, we need consider the num on the odd index\n # then repeat this process\n # at the end we check the requirement 1: nums.length is even or not\n \n n = len(nums)\n count = 0\n # flag is true then check the even index\n # flag is false then check the odd index\n flag = True\n \n for i in range(n):\n # check the even index\n if flag:\n if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = False\n # check the odd index\n elif not flag:\n if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = True\n \n curLength = n - count\n \n return count if curLength % 2 == 0 else count + 1", + "title": "2216. Minimum Deletions to Make Array Beautiful", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive integer arrays nums and numsDivide . You can delete any number of elements from nums . Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide . If this is not possible, return -1 . Note that an integer x divides y if y % x == 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length, numsDivide.length <= 10^5", + "1 <= nums[i], numsDivide[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]Output:2Explanation:The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.\nWe use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].\nThe smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.\nIt can be shown that 2 is the minimum number of deletions needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,6], numsDivide = [8,2,6,10]Output:-1Explanation:We want the smallest element in nums to divide all the elements of numsDivide.\nThere is no way to delete elements from nums to allow this.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1147 ms (Top 45.35%) | Memory: 25.8 MB (Top 79.68%)\nclass Solution:\n def minOperations(self, nums: List[int], divs: List[int]) -> int:\n div = reduce(gcd, divs)\n return next((i for i, n in enumerate(sorted(nums)) if div % n == 0), -1)", + "title": "2344. Minimum Deletions to Make Array Divisible", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A string s is called good if there are no two different characters in s that have the same frequency . Given a string s , return the minimum number of characters you need to delete to make s good . The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\" , the frequency of 'a' is 2 , while the frequency of 'b' is 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:0Explanation:sis already good.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabbbcc\"Output:2Explanation:You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ceabaacb\"Output:2Explanation:You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int N = 26;\n public int minDeletions(String s) {\n int[] array = new int[N];\n for (char ch : s.toCharArray()) {\n array[ch - 'a']++;\n }\n int ans = 0;\n Set set = new HashSet<>();\n for (int i : array) {\n if (i == 0) continue;\n while (set.contains(i)) {\n i--;\n ans++;\n }\n if (i != 0) {\n set.add(i);\n }\n }\n return ans;\n }\n}\n", + "title": "1647. Minimum Deletions to Make Character Frequencies Unique", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A string s is called good if there are no two different characters in s that have the same frequency . Given a string s , return the minimum number of characters you need to delete to make s good . The frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\" , the frequency of 'a' is 2 , while the frequency of 'b' is 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:0Explanation:sis already good.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaabbbcc\"Output:2Explanation:You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"ceabaacb\"Output:2Explanation:You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDeletions(self, s: str) -> int:\n # Get the frequency of each character sorted in reverse order\n frequencies = sorted(Counter(s).values(), reverse=True)\n \n total_deletions = 0\n next_unused_freq = len(s)\n for freq in frequencies:\n # It is impossible for the frequency to be higher\n next_unused_freq = min(next_unused_freq, freq)\n total_deletions += freq - next_unused_freq\n\n # We cannot have another character with this frequency,\n # so decrement next_unused_freq\n if next_unused_freq > 0:\n next_unused_freq -= 1\n\n return total_deletions\n", + "title": "1647. Minimum Deletions to Make Character Frequencies Unique", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of characters 'a' and 'b' ​​​​. You can delete any number of characters in s to make s balanced . s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a' . Return the minimum number of deletions needed to make s balanced . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is 'a' or 'b' ​​." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababbab\"Output:2Explanation:You can either:\nDelete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -> \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbaaaaabb\"Output:2Explanation:The only solution is to delete the first two characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 70.64%) | Memory: 68.2 MB (Top 24.02%)\nclass Solution {\n public int minimumDeletions(String s) {\n //ideal case : bbbbbbbbb\n int[] dp = new int[s.length()+1];\n int idx =1;\n int bCount=0;\n\n for(int i =0 ;i \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbaaaaabb\"Output:2Explanation:The only solution is to delete the first two characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef minimumDeletions(self, s: str) -> int:\n\t\tpreSum = [0] * (len(s) + 1)\n\t\tsufSum = [0] * (len(s) + 1)\n\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == \"a\":\n\t\t\t\tpreSum[i] += 1 + preSum[i-1]\n\n\t\t\telse:\n\t\t\t\tpreSum[i] = preSum[i-1]\n\n\t\t\tif s[len(s)-i-1] == \"b\":\n\t\t\t\tsufSum[len(s)-i-1] += 1 + sufSum[len(s)-i]\n\n\t\t\telse:\n\t\t\t\tsufSum[len(s)-i-1] += sufSum[len(s)-i]\n\n\t\tmaxStringLength = 0\n\t\tfor i in range(len(s)):\n\t\t\tif preSum[i] + sufSum[i] > maxStringLength:\n\t\t\t\tmaxStringLength = preSum[i] + sufSum[i]\n\n\t\treturn len(s) - maxStringLength", + "title": "1653. Minimum Deletions to Make String Balanced", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int minDepth(TreeNode root) {\n if(root == null)\n return 0;\n \n int left = minDepth(root.left);\n int right = minDepth(root.right);\n if(root.left == null)\n return right+1;\n if(root.right == null)\n return left+1;\n return Math.min(left, right)+1;\n }\n}\n", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minDepth(self, root):\n # Base case...\n # If the subtree is empty i.e. root is NULL, return depth as 0...\n if root is None: return 0\n # Initialize the depth of two subtrees...\n leftDepth = self.minDepth(root.left)\n rightDepth = self.minDepth(root.right)\n # If the both subtrees are empty...\n if root.left is None and root.right is None:\n return 1\n # If the left subtree is empty, return the depth of right subtree after adding 1 to it...\n if root.left is None:\n return 1 + rightDepth\n # If the right subtree is empty, return the depth of left subtree after adding 1 to it...\n if root.right is None:\n return 1 + leftDepth\n # When the two child function return its depth...\n # Pick the minimum out of these two subtrees and return this value after adding 1 to it...\n return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees...", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums , where nums[i] represents the score of the i th student. You are also given an integer k . Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized . Return the minimum possible difference . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 1000", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [90], k = 1Output:0Explanation:There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,1,7], k = 2Output:2Explanation:There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 73.44%) | Memory: 47.5 MB (Top 27.33%)\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k == 1)return 0;\n int i = 0,j = k-1,res = Integer.MAX_VALUE;\n\n Arrays.sort(nums);\n while(j < nums.length){\n res = Math.min(res,nums[j] - nums[i]);\n j++;\n i++;\n }\n\n return res;\n }\n}", + "title": "1984. Minimum Difference Between Highest and Lowest of K Scores", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums , where nums[i] represents the score of the i th student. You are also given an integer k . Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized . Return the minimum possible difference . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 1000", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [90], k = 1Output:0Explanation:There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [9,4,1,7], k = 2Output:2Explanation:There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 118 ms (Top 7.93%) | Memory: 17.50 MB (Top 9.64%)\n\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n m,n=100001,len(nums)\n i,j=0,k-1\n while j int:\n if len(nums) <= 3:\n return 0\n\n nums.sort()\n t1 = nums[-1] - nums[3]\n t2 = nums[-4] - nums[0]\n t3 = nums[-2] - nums[2]\n t4 = nums[-3] - nums[1]\n\n return min(t1,t2,t3,t4)", + "title": "1509. Minimum Difference Between Largest and Smallest Value in Three Moves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums . The remaining 2 * n elements will be divided into two equal parts: The difference in sums of the two parts is denoted as sum first - sum second . Return the minimum difference possible between the sums of the two parts after the removal of n elements . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The first n elements belonging to the first part and their sum is sum first .", + "The next n elements belonging to the second part and their sum is sum second ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2]Output:-1Explanation:Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,9,5,8,1,3]Output:1Explanation:Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 405 ms (Top 41.21%) | Memory: 218.6 MB (Top 5.49%)\n\nclass Solution {\n public long minimumDifference(int[] nums) {\n int n=nums.length; //length of nums\n int len3=n/3; // 1/3 length\n long res=Long.MAX_VALUE; // final result;\n //Try to make first part as min as possible;\n //first[m] store the value, the min value of the size=len3, from[0,1,..., m];\n long[] first=new long[n];\n //Try to make second part as max as possible;\n //second[m] store the value, the max value of the size=len3, from[m,...,n-1];\n long[] second=new long[n];\n\n//--------------------for first part compute -------------------------------------\n //Build max heap for first part;\n PriorityQueue max=new PriorityQueue(Comparator.reverseOrder());\n\n long sum=0;\n\n // Initialize with the first 1/3 n part.\n for(int i=0;i min=new PriorityQueue();\n // Initialize with the last 1/3 n part.\n for(int i=0;i int:\n h=heapq\n k=len(nums)//3\n min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, []\n h.heapify(max_heap) , h.heapify(min_heap)\n for x in nums[:-k]:\n h.heappush(min_heap,-x)\n min_sum+=x\n if len(min_heap)>k: min_sum+=h.heappop(min_heap)\n min_sol.append(min_sum)\n for x in nums[::-1][:-k]:\n h.heappush(max_heap,x)\n max_sum+=x\n if len(max_heap)>k: max_sum-=h.heappop(max_heap)\n max_sol.append(max_sum)\n min_sol =min_sol[k-1:]\n max_sol=max_sol[k-1:][::-1]\n return min( min_value - max_value for min_value , max_value in zip(min_sol,max_sol) )\n", + "title": "2163. Minimum Difference in Sums After Removal of Elements", + "topic": "Array" + }, + { + "difficulty": "1335. Minimum Difficulty of a Job Schedule", + "language": "java", + "description": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i th job, you have to finish all the jobs j where 0 <= j < i ). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d . The difficulty of the i th job is jobDifficulty[i] . Return the minimum difficulty of a job schedule . If you cannot find a schedule for the jobs return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= jobDifficulty.length <= 300", + "0 <= jobDifficulty[i] <= 1000", + "1 <= d <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:jobDifficulty = [6,5,4,3,2,1], d = 2Output:7Explanation:First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7", + "image": "https://assets.leetcode.com/uploads/2020/01/16/untitled.png" + }, + { + "text": "Example 2: Input:jobDifficulty = [9,9,9], d = 4Output:-1Explanation:If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.", + "image": null + }, + { + "text": "Example 3: Input:jobDifficulty = [1,1,1], d = 3Output:3Explanation:The schedule is one job per day. total difficulty will be 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray.\n public int minDifficulty(int[] jobDifficulty, int d) {\n if(d>jobDifficulty.length){\n return -1;\n }\n \n int[][] memo = new int[d+1][jobDifficulty.length];\n for(int[] m : memo){\n Arrays.fill(m, -1);\n }\n \n return getMinDays(jobDifficulty, d, memo, 0);\n }\n \n private int getMinDays(int[] jobDifficulty, int d, int[][] memo, int idx){\n if(d==1){\n int max=0;\n while(idx < jobDifficulty.length){\n max=Math.max(max, jobDifficulty[idx]);\n idx++;\n }\n return max;\n }\n \n if(memo[d][idx] != -1) return memo[d][idx];\n \n int max=0;\n int res=Integer.MAX_VALUE;\n // [6,5,4,3,2,1], d=5 => we don't want the cut at 4th position in the array because we won't be able to divide it into 5 parts\n for(int i=idx; i length:\n return -1\n\n min_difficulties = [[float('inf')] * length for _ in range(days)]\n\n max_diff = 0\n i = 0\n while i <= length - days:\n max_diff = max(max_diff, jobDifficulty[i])\n min_difficulties[0][i] = max_diff\n i += 1\n\n current_day = 1\n while current_day < days:\n to = current_day\n while to <= length - days + current_day:\n current_job_difficulty = jobDifficulty[to]\n result = float('inf')\n j = to - 1\n while j >= current_day - 1:\n result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty)\n current_job_difficulty = max(current_job_difficulty, jobDifficulty[j])\n j -= 1\n min_difficulties[current_day][to] = result\n to += 1\n current_day += 1\n\n return min_difficulties[days - 1][length - 1]\n\n\n\n", + "title": "1335. Minimum Difficulty of a Job Schedule", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.00 MB (Top 72.0%)\n\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n \n int mini=Integer.MAX_VALUE;\n\n public void find(TreeNode root,ArrayListarr){\n \n if(root==null){\n return;\n }\n \n \n arr.add(root.val);\n \n find(root.left,arr);\n \n for(int i=arr.size()-2;i>=0;i--){\n \n mini=Math.min(mini,Math.abs(root.val-arr.get(i)));\n }\n \n find(root.right,arr);\n \n arr.remove(arr.size()-1);\n }\n\n public int minDiffInBST(TreeNode root) {\n ArrayListarr=new ArrayList<>();\n find(root,arr);\n return mini; \n }\n}", + "title": "783. Minimum Distance Between BST Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 100] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n if root is None:\n return 0\n temp1=float(inf)\n from collections import deque\n a=deque([root])\n b=[]\n while a:\n node=a.popleft()\n b.append(node.val)\n if node.left:\n a.append(node.left)\n if node.right:\n a.append(node.right)\n b.sort()\n for i in range(0,len(b)-1):\n if b[i+1]-b[i]", + "title": "783. Minimum Distance Between BST Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums (0-indexed) and two integers target and start , find an index i such that nums[i] == target and abs(i - start) is minimized . Note that abs(x) is the absolute value of x . Return abs(i - start) . It is guaranteed that target exists in nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "0 <= start < nums.length", + "target is in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], target = 5, start = 3Output:1Explanation:nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1, start = 0Output:0Explanation:nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0Output:0Explanation:Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 8.87%) | Memory: 43.1 MB (Top 80.91%)\nclass Solution {\n public int getMinDistance(int[] nums, int target, int start) {\n int ans = Integer.MAX_VALUE;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == target) {\n ans = Math.min(ans, Math.abs(i - start));\n }\n }\n return ans;\n }\n}", + "title": "1848. Minimum Distance to the Target Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums (0-indexed) and two integers target and start , find an index i such that nums[i] == target and abs(i - start) is minimized . Note that abs(x) is the absolute value of x . Return abs(i - start) . It is guaranteed that target exists in nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "0 <= start < nums.length", + "target is in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5], target = 5, start = 3Output:1Explanation:nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1, start = 0Output:0Explanation:nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0Output:0Explanation:Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n if nums[start] == target: return 0\n left, right = start-1, start+1\n N = len(nums)\n while True:\n if left >=0 and nums[left] == target:\n return start - left\n if right < N and nums[right] == target:\n return right - start\n left -= 1\n right += 1\n", + "title": "1848. Minimum Distance to the Target Element", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word , return the minimum total distance to type such string using only two fingers . The distance between coordinates (x 1 , y 1 ) and (x 2 , y 2 ) is |x 1 - x 2 | + |y 1 - y 2 | . Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the letter 'A' is located at coordinate (0, 0) , the letter 'B' is located at coordinate (0, 1) , the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"CAKE\"Output:3Explanation:Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3", + "image": null + }, + { + "text": "Example 2: Input:word = \"HAPPY\"Output:6Explanation:Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap pos;\n int [][][]memo;\n int type(String word,int index,char finger1,char finger2){\n if (index==word.length()) return 0;\n int ans=9999999;\n if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];\n if (finger1=='['){\n \n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));\n }\n else{\n \n Integer [] prev=pos.get(finger1);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);\n }\n if (finger2=='['){\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));\n }\n else{\n Integer [] prev=pos.get(finger2);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);\n }\n memo[index][finger1-'A'][finger2-'A']=ans;\n return ans;\n }\n public int minimumDistance(String word) {\n pos=new HashMap();\n for (int i=0;i<26;i++){\n Integer [] coord={i/6,i%6};\n pos.put((char)('A'+i),coord);\n }\n memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];\n for (int[][] row : memo) {\n for (int[] rowColumn : row) {\n Arrays.fill(rowColumn, -1);\n }\n }\n return type(word,0,'[','[');\n }\n}", + "title": "1320. Minimum Distance to Type a Word Using Two Fingers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. Given the string word , return the minimum total distance to type such string using only two fingers . The distance between coordinates (x 1 , y 1 ) and (x 2 , y 2 ) is |x 1 - x 2 | + |y 1 - y 2 | . Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the letter 'A' is located at coordinate (0, 0) , the letter 'B' is located at coordinate (0, 1) , the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1) ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"CAKE\"Output:3Explanation:Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3", + "image": null + }, + { + "text": "Example 2: Input:word = \"HAPPY\"Output:6Explanation:Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import cache\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n COL = 6\n index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}\n def dist(a, b):\n return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])\n @cache\n def dfs(lhand, rhand, i):\n if i == len(word): return 0\n res = float('inf')\n res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))\n res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))\n return res\n return dfs(-1, -1, 0)", + "title": "1320. Minimum Distance to Type a Word Using Two Fingers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i th domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= tops.length <= 2 * 10^4", + "bottoms.length == tops.length", + "1 <= tops[i], bottoms[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]Output:2Explanation:The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.", + "image": "https://assets.leetcode.com/uploads/2021/05/14/domino.png" + }, + { + "text": "Example 2: Input:tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]Output:-1Explanation:In this case, it is not possible to rotate the dominoes to make one row of values equal.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 32.99%) | Memory: 94.3 MB (Top 24.39%)\nclass Solution {\n public int minDominoRotations(int[] tops, int[] bottoms) {\n\n int[][] c = new int[6][2];\n\n for (int i : tops) {\n c[i - 1][0]++;\n }\n for (int i : bottoms) {\n c[i - 1][1]++;\n }\n int[] common = new int[6];\n for (int i = 0; i < tops.length; i++) {\n if (tops[i] == bottoms[i]) {\n common[tops[i] - 1]++;\n }\n }\n int min = Integer.MAX_VALUE;\n for (int i = 1; i <= 6; i++) {\n if (c[i - 1][0] + c[i - 1][1] >= tops.length) {\n if (c[i - 1][0] >= c[i - 1][1] && c[i - 1][1] - common[i - 1] + c[i - 1][0] == tops.length) {\n min = Math.min(min, c[i - 1][1] - common[i - 1]);\n }\n else if (c[i - 1][1] >= c[i - 1][0] && c[i - 1][0] - common[i - 1] + c[i - 1][1] == tops.length) {\n int left = c[i - 1][0] - common[i - 1];\n min = Math.min(min, c[i - 1][0] - common[i - 1]);\n }\n }\n }\n\n return min == Integer.MAX_VALUE ? -1 : min;\n }\n}", + "title": "1007. Minimum Domino Rotations For Equal Row", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the i th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i th domino, so that tops[i] and bottoms[i] swap values. Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same. If it cannot be done, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= tops.length <= 2 * 10^4", + "bottoms.length == tops.length", + "1 <= tops[i], bottoms[i] <= 6" + ], + "examples": [ + { + "text": "Example 1: Input:tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]Output:2Explanation:The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.", + "image": "https://assets.leetcode.com/uploads/2021/05/14/domino.png" + }, + { + "text": "Example 2: Input:tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]Output:-1Explanation:In this case, it is not possible to rotate the dominoes to make one row of values equal.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]\n\t\t\n same_count = collections.Counter(sames)\n bottom_count = collections.Counter(bottoms)\n top_count = collections.Counter(tops)\n \n for n in range(1,7):\n if bottom_count[n] + top_count[n] - same_count[n] == len(tops):\n return min(bottom_count[n], top_count[n]) - same_count[n]\n \n return -1\n", + "title": "1007. Minimum Domino Rotations For Equal Row", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and two integers limit and goal . The array nums has an interesting property that abs(nums[i]) <= limit . Return the minimum number of elements you need to add to make the sum of the array equal to goal . The array must maintain its property that abs(nums[i]) <= limit . Note that abs(x) equals x if x >= 0 , and -x otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= limit <= 10^6", + "-limit <= nums[i] <= limit", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,1], limit = 3, goal = -4Output:2Explanation:You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-10,9,1], limit = 100, goal = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 11.82%) | Memory: 74.9 MB (Top 84.55%)\nclass Solution {\n public int minElements(int[] nums, int limit, int goal) {\n long sum = 0;\n for(int num: nums)\n sum += num;\n long diff = Math.abs(sum-goal);\n return (int) (diff/limit) + (diff%limit>0?1:0);\n }\n}", + "title": "1785. Minimum Elements to Add to Form a Given Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and two integers limit and goal . The array nums has an interesting property that abs(nums[i]) <= limit . Return the minimum number of elements you need to add to make the sum of the array equal to goal . The array must maintain its property that abs(nums[i]) <= limit . Note that abs(x) equals x if x >= 0 , and -x otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= limit <= 10^6", + "-limit <= nums[i] <= limit", + "-10^9 <= goal <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-1,1], limit = 3, goal = -4Output:2Explanation:You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-10,9,1], limit = 100, goal = 0Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n", + "title": "1785. Minimum Elements to Add to Form a Given Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n array of integers matrix , return the minimum sum of any falling path through matrix . A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1) , (row + 1, col) , or (row + 1, col + 1) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 100", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[2,1,3],[6,5,4],[7,8,9]]Output:13Explanation:There are two falling paths with a minimum sum as shown.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[-19,57],[-40,-5]]Output:-59Explanation:The falling path with a minimum sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 82.59%) | Memory: 46.9 MB (Top 82.02%)\n\nclass Solution {\n public int min(int[][] matrix, int[][]dp, int i, int j)\n {\n int a,b,c;\n if(i==0)\n return matrix[i][j];\n if(dp[i][j] != Integer.MAX_VALUE)\n return dp[i][j];\n if(j==0)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1))+matrix[i][j];\n }\n else if(j==matrix.length -1)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n else\n {\n dp[i][j] = Math.min(Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1)),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n return dp[i][j];\n }\n\n public int minFallingPathSum(int[][] matrix) {\n int dp[][] = new int[matrix.length][matrix.length];\n if(matrix.length == 1)\n return matrix[0][0];\n for(int i=0;i int:\n for row in range(1, len(matrix)):\n for col in range(0, len(matrix[row])):\n if col == 0:\n matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col])\n elif col == len(matrix[row]) - 1:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col])\n else:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col], matrix[row-1][col+1])\n \n return min(matrix[-1])\n", + "title": "931. Minimum Falling Path Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an n x n integer matrix grid , return the minimum sum of a falling path with non-zero shifts . A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "-99 <= grid[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [[1,2,3],[4,5,6],[7,8,9]]Output:13Explanation:The possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/falling-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[7]]Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Recursion\n /* public int minFallingPathSum(int[][] grid) {\n int n=grid.length;\n if(n==1) return grid[0][0];\n int ans = 10000000;\n for(int i=0 ; i int:\n m, n = len(grid), len(grid[0])\n if m == 1 and n == 1:\n return grid[0][0]\n min_arr = [0 for _ in range(n)]\n for i in range(m):\n prefix = [float('inf') for _ in range(n)]\n suffix = [float('inf') for _ in range(n)]\n current_row = [elem1+elem2 for elem1, elem2 in zip(grid[i], min_arr)]\n for i in range(1, n):\n prefix[i] = min(prefix[i-1], current_row[i-1])\n for i in range(n-2, -1, -1):\n suffix[i] = min(suffix[i+1], current_row[i+1])\n min_arr = [min(pre, suff) for pre, suff in zip(prefix, suffix)]\n return min(min_arr)\n", + "title": "1289. Minimum Falling Path Sum II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given 3 positives numbers a , b and c . Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png" + ], + "constraints": [ + "1 <= a <= 10^9", + "1 <= b <= 10^9", + "1 <= c <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 6, c = 5Output:3Explanation:After flips a = 1 , b = 4 , c = 5 such that (aORb==c)", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 2, c = 7Output:1", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 2, c = 3Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.2 MB (Top 89.45%)\nclass Solution {\n public int minFlips(int a, int b, int c) {\n int j=-1;\n int x=a|b;\n int count=0;\n while(c!=0 || x!=0){\n j++;\n int aa=x%2;\n int bb=c%2;\n if(aa==0 && bb==1)count++;\n else if(aa==1 && bb==0) count+=funcount(j,a,b);\n x=x>>1;\n c=c>>1;\n }\n return count;\n }\n public static int funcount(int shift,int a,int b){\n int cc=0;\n int mask=1< int:\n res = 0\n for i in range(32):\n if (a & 1) | (b & 1) != (c & 1):\n if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1\n res += 1\n else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1\n res += (a & 1) + (b & 1)\n a, b, c = a>>1, b>>1, c>>1 # right-shift by 1\n\n return res\n\n# Time: O(1)\n# Space: O(1)", + "title": "1318. Minimum Flips to Make a OR b Equal to c", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0) . Given an integer neededApples , return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot . The value of |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0", + "-x if x < 0" + ], + "examples": [ + { + "text": "Example 1: Input:neededApples = 1Output:8Explanation:A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.", + "image": "https://assets.leetcode.com/uploads/2019/08/30/1527_example_1_2.png" + }, + { + "text": "Example 2: Input:neededApples = 13Output:16", + "image": null + }, + { + "text": "Example 3: Input:neededApples = 1000000000Output:5040", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumPerimeter(long neededApples) {\n long n = 0;\n long count = 0;\n while(count < neededApples) {\n n++;\n count += (12 * n * n);\n }\n return n * 8;\n }\n}\n", + "title": "1954. Minimum Garden Perimeter to Collect Enough Apples", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it. You will buy an axis-aligned square plot of land that is centered at (0, 0) . Given an integer neededApples , return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot . The value of |x| is defined as: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x if x >= 0", + "-x if x < 0" + ], + "examples": [ + { + "text": "Example 1: Input:neededApples = 1Output:8Explanation:A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.", + "image": "https://assets.leetcode.com/uploads/2019/08/30/1527_example_1_2.png" + }, + { + "text": "Example 2: Input:neededApples = 13Output:16", + "image": null + }, + { + "text": "Example 3: Input:neededApples = 1000000000Output:5040", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumPerimeter(self, nap: int) -> int:\n \n \n# here for n = 2 , there are two series : \n# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6\n# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2\n \n# how to solve:\n \n# here 3 = sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) = 0.5*2n*(2n-1)-0.5*n*n-1\n# (3) so our final 2,3,3 = 3*2+2 = (0.5*2n*(2n-1)-0.5*n*n-1)*2+n\n# (4) so final 2,3,3 = 3*n*n - 2*n\n# (5) we have 4 times repitation of (2,3,3) = 4*(2,3,3) = 4*(3*n*n - 2*n) = 12*n*n - 8*n\n# (6) we have 4 diagnal points so their sum(4 diagnal) = 4*(2*n)\n# (7) so final sum(total) = 4 diagnal sum + 4(2,3,3) = 4(2*n) + 12*n*n - 8*n = 12*n*n\n \n# so at nth distance we have total 12*n*n apples at the circumfrance\n \n# so net sum = sigma(12*n*n) = 2*n*(n+1)*(2*n+1)\n \n \n n=1\n val=2*n*(n+1)*(2*n+1)\n while(val \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]Output:1", + "image": null + }, + { + "text": "Example 2: Input:start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]Output:2", + "image": null + }, + { + "text": "Example 3: Input:start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.87%) | Memory: 42.6 MB (Top 7.49%)\nclass Solution {\n public int minMutation(String start, String end, String[] bank) {\n Set set = new HashSet<>();\n for(String tmp: bank){\n set.add(tmp);\n }\n if(!set.contains(end)) return -1;\n if(start.equals(end)) return 0;\n char[] var = {'A','C','G','T'};\n Queue q = new LinkedList<>();\n q.add(start);\n int count = 0;\n while(!q.isEmpty()){\n int size = q.size();\n for(int i = 0; i < size; i ++){\n String str = q.poll();\n char[] tmp = str.toCharArray();\n if(str.equals(end)) return count;\n for(int j = 0; j < 8; j ++){\n char ch = tmp[j];\n for(int k = 0; k < 4; k ++){\n tmp[j] = var[k];\n String node = new String(tmp);\n if(set.contains(node)){\n q.add(node);\n set.remove(node);\n }\n }\n tmp[j] = ch;\n }\n }\n count++;\n }\n return -1;\n }\n}", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A' , 'C' , 'G' , and 'T' . Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings start and end and the gene bank bank , return the minimum number of mutations needed to mutate from start to end . If there is no such a mutation, return -1 . Note that the starting point is assumed to be valid, so it might not be included in the bank. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]Output:1", + "image": null + }, + { + "text": "Example 2: Input:start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]Output:2", + "image": null + }, + { + "text": "Example 3: Input:start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n q = deque()\n q.append(start)\n n = len(bank)\n last = 0\n used = [False] * n\n for i, x in enumerate(bank):\n if start == x:\n used[i] = True\n if end == x:\n last = i\n dist = 0\n while q:\n dist += 1\n for _ in range(len(q)):\n w = q.popleft()\n for i, x in enumerate(bank):\n if used[i]:\n continue\n bad = 0\n for j in range(8):\n if w[j] != x[j]:\n bad += 1\n if bad == 2:\n break\n if bad == 1:\n if last == i:\n return dist\n used[i] = True\n q.append(x)\n return -1\n", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]Output:[1]Explanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]Output:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 13.14%) | Memory: 86.2 MB (Top 13.59%)\nclass Solution {\n public List findMinHeightTrees(int n, int[][] edges) {\n if(edges.length == 0) {\n List al = new ArrayList<>();\n al.add(0);\n return al;\n }\n HashMap> map = new HashMap<>(); // map == graph\n int [] degree = new int[n];\n for(int [] edge : edges){\n int src = edge[0];\n int dest = edge[1];\n map.putIfAbsent(src, new HashSet<>());\n map.get(src).add(dest);\n map.putIfAbsent(dest, new HashSet<>());\n map.get(dest).add(src);\n degree[src]++;\n degree[dest]++;\n }\n Queue q = new ArrayDeque<>();\n for(int i = 0; i < degree.length; i++){\n if(degree[i] == 1){\n q.offer(i);\n }\n }\n int count = n;\n while(count > 2){\n int size = q.size();\n count -= size;\n while(size-- > 0){\n Integer src = q.poll();\n\n for(Integer connection : map.get(src)){\n degree[connection]--;\n if(degree[connection] == 1){\n q.offer(connection);\n }\n }\n }\n }\n return new ArrayList<>(q);\n }\n}", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]Output:[1]Explanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]Output:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n==0:\n return []\n if n==1:return [0]\n adj=[[] for i in range (n)]\n degree=[0]*n\n for i in edges:\n adj[i[0]].append(i[1])\n adj[i[1]].append(i[0])\n degree[i[0]]+=1\n degree[i[1]]+=1\n \n print(adj)\n q=[]\n for i in range(n):\n if degree[i]==1:\n q.append(i)\n \n while n>2:\n size=len(q)\n n-=size\n while size>0:\n v=q.pop(0)\n for i in adj[v]:\n degree[i]-=1\n if degree[i]==1:\n q.append(i)\n size-=1\n return q\n \n \n \n", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums ​​​ and an integer k . You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible. A subset is a group integers that appear in the array with no particular order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "nums.length is divisible by k", + "1 <= nums[i] <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,4], k = 2Output:4Explanation:The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,3,8,1,3,1,2,2], k = 4Output:6Explanation:The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,3,3,6,3,3], k = 3Output:-1Explanation:It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumIncompatibility(int[] nums, int k) {\n Arrays.sort(nums);\n k=nums.length/k;\n int n = nums.length,INF=100;\n int[][] dp = new int[1<0;w++){\n if ((i&1<0;w++){\n if ((i&1<= 2: break\n return flag != 0\n if max(collections.Counter(nums).values()) > k: return -1\n assign(0)\n return self.res\n", + "title": "1681. Minimum Incompatibility", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]Output:1Explanation:After 1 move, the array could be [1, 2, 3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,1,7]Output:6Explanation:After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minIncrementForUnique(int[] nums) {\n \n //Approach - 1 : Using a Count array\n \n // TC : O(N)\n // SC : O(N)\n \n int max = 0;\n for(int i : nums)\n max = Math.max(max, i);\n \n int count[] = new int[nums.length + max];\n\t\t\n for(int c : nums)\n count[c]++;\n\t\t\t\n int answer = 0, choosen = 0;\n\t\tint len = count.length;\n\t\t\n for(int i = 0; i< len; i++)\n {\n if(count[i] >= 2)\n {\n choosen += count[i] - 1;\n answer -= i * (count[i] - 1);\n }\n else if(choosen > 0 && count[i] == 0)\n {\n answer += i;\n choosen--;\n }\n }\n\t\t\n return answer;\n \n \n //Approach - 2:\n \n // TC : O(nlogn)\n // SC : O(1)\n \n Arrays.sort(nums);\n int answer = 0;\n for(int i=1; i= nums[i]){\n answer += nums[i-1]- nums[i] +1;\n nums[i] = nums[i-1] + 1; \n }\n }\n return answer;\n }\n}\n", + "title": "945. Minimum Increment to Make Array Unique", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]Output:1Explanation:After 1 move, the array could be [1, 2, 3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,2,1,7]Output:6Explanation:After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n c=0\n i=1\n num=[]\n \n while i list2.length) {\n return findRestaurant(list2, list1);\n }\n \n Map map1 = new HashMap<>();\n for (int i = 0; i < list1.length; i++) {\n map1.put(list1[i], i);\n }\n \n List mins = new ArrayList<>();\n int minSum = Integer.MAX_VALUE;\n for (int i = 0; i < list2.length; i++) {\n String rest2 = list2[i];\n if (map1.containsKey(rest2)) {\n int sum = map1.get(rest2) + i;\n if (sum < minSum) {\n mins = new ArrayList<>();\n minSum = sum;\n }\n if (sum == minSum) {\n mins.add(rest2);\n }\n }\n }\n \n return mins.toArray(new String[mins.size()]);\n }\n}\n", + "title": "599. Minimum Index Sum of Two Lists", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum . If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= list1.length, list2.length <= 1000", + "1 <= list1[i].length, list2[i].length <= 30", + "list1[i] and list2[i] consist of spaces ' ' and English letters.", + "All the stings of list1 are unique .", + "All the stings of list2 are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]Output:[\"Shogun\"]Explanation:The only restaurant they both like is \"Shogun\".", + "image": null + }, + { + "text": "Example 2: Input:list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"KFC\",\"Shogun\",\"Burger King\"]Output:[\"Shogun\"]Explanation:The restaurant they both like and have the least index sum is \"Shogun\" with index sum 1 (0+1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n \n \n hashmap1 = {}\n hashmap2 = {}\n common = {}\n for i in range(len(list1)):\n \n hashmap1[list1[i]] = i \n \n \n for j in range(len(list2)):\n hashmap2[list2[j]] = j \n \n \n \n for i in hashmap1:\n \n if i in hashmap2:\n print(1)\n common[i] = hashmap1[i] + hashmap2[i]\n \n \n common = list(common.items())\n \n answer =[]\n minimum = float(\"inf\")\n \n for i in range(0,len(common)):\n \n if common[i][1] < minimum:\n minimum = common[i][1]\n \n for i in range(len(common)):\n \n if common[i][1] == minimum:\n answer.append(common[i][0])\n \n return answer\n \n \n \n", + "title": "599. Minimum Index Sum of Two Lists", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array tasks where tasks[i] = [actual i , minimum i ] : For example, if the task is [10, 12] and your current energy is 11 , you cannot start this task. However, if your current energy is 13 , you can complete this task, and your energy will be 3 after finishing it. You can finish the tasks in any order you like. Return the minimum initial amount of energy you will need to finish all the tasks . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "actual i is the actual amount of energy you spend to finish the i th task.", + "minimum i is the minimum amount of energy you require to begin the i th task." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [[1,2],[2,4],[4,8]]Output:8Explanation:Starting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]Output:32Explanation:Starting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]Output:27Explanation:Starting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\nclass Solution {\n public int minimumEffort(int[][] tasks)\n {\n Arrays.sort(tasks, new Comparator(){\n @Override\n public int compare(int[] a, int[] b)\n {\n return (b[1]-b[0])-(a[1]-a[0]);\n }\n });\n int sum=0, max=0;\n for(int i=0;i int:\n tasks.sort(key=lambda x: x[0]-x[1])\n def ok(mid):\n for actual, minimum in tasks:\n if minimum > mid or actual > mid: return False\n if minimum <= mid: mid -= actual\n return True\n l, r = 0, 10 ** 9\n while l <= r:\n mid = (l+r) // 2\n if ok(mid): r = mid - 1\n else: l = mid + 1\n return l", + "title": "1665. Minimum Initial Energy to Finish Tasks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s . In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"zzazz\"Output:0Explanation:The string \"zzazz\" is already palindrome we don't need any insertions.", + "image": null + }, + { + "text": "Example 2: Input:s = \"mbadm\"Output:2Explanation:String can be \"mbdadbm\" or \"mdbabdm\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\"Output:5Explanation:Inserting 5 characters the string becomes \"leetcodocteel\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 71.55%) | Memory: 43.3 MB (Top 97.03%)\nclass Solution {\n public int minInsertions(String s) {\n StringBuilder sb = new StringBuilder(s);\n String str = sb.reverse().toString();\n int m=s.length();\n int n=str.length();\n System.out.println(str);\n return LCS(s,str,m,n);\n\n }\n public int LCS(String x, String y,int m,int n){\n int [][] t = new int [m+1][n+1];\n for(int i=0;i int:\n n = len(s)\n prev_prev = [0]*n\n prev = [0]*n\n curr = [0] * n\n\n for l in range(1, n):\n for i in range(l, n):\n if s[i] == s[i-l]:\n curr[i] = prev_prev[i-1]\n else:\n curr[i] = min(prev[i-1], prev[i])+1\n # print(curr)\n prev_prev, prev, curr = prev, curr, prev_prev\n \n return prev[-1]", + "title": "1312. Minimum Insertion Steps to Make a String Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a parentheses string s containing only the characters '(' and ')' . A parentheses string is balanced if: In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))' .", + "Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()))\"Output:1Explanation:The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"())\"Output:0Explanation:The string is already balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"))())(\"Output:3Explanation:Add '(' to match the first '))', Add '))' to match the last '('.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 44.46%) | Memory: 51.9 MB (Top 75.57%)\nclass Solution {\n public int minInsertions(String s) {\n int open=0;\n int ans=0;\n\n for(int i=0;i0){\n open--;\n }\n else{\n ans++;\n }\n }\n else{\n if(open>0){\n open--;\n ans++;\n }\n else{\n ans+=2;\n }\n }\n }\n }\n ans+=2*open;\n return ans;\n }\n}", + "title": "1541. Minimum Insertions to Balance a Parentheses String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a parentheses string s containing only the characters '(' and ')' . A parentheses string is balanced if: In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the minimum number of insertions needed to make s balanced. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))' .", + "Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()))\"Output:1Explanation:The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"())\"Output:0Explanation:The string is already balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"))())(\"Output:3Explanation:Add '(' to match the first '))', Add '))' to match the last '('.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minInsertions(self, s: str) -> int:\n leftbrackets = insertions = 0\n i, n = 0, len(s)\n\n while i < n:\n if s[i] == '(':\n leftbrackets += 1\n elif s[i] == ')':\n if i == n-1 or s[i+1] != ')': insertions += 1\n else: i += 1\n \n if not leftbrackets: insertions += 1\n else: leftbrackets -= 1\n \n i += 1\n \n return leftbrackets * 2 + insertions", + "title": "1541. Minimum Insertions to Balance a Parentheses String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: 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:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.", + "image": null + }, + { + "text": "Example 2: 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:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 250 ms (Top 27.92%) | Memory: 125.9 MB (Top 80.67%)\nclass Solution {\n public int[] minInterval(int[][] intervals, int[] queries) {\n //sort intervals\n Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n //add [index,query]\n int[][] q = new int[queries.length][2];\n for (int i=0;i a[1]-b[1]);\n //store the minimum intervals in the priority queue, min heap\n Queue pq = new PriorityQueue<>((a,b) -> (a[1]-a[0])-(b[1]-b[0]));\n int[] result = new int[queries.length];\n int j = 0;\n for (int i=0;i List[int]:\n \n # sort queries from small to large\n q = deque(sorted([(x, i) for i, x in enumerate(queries)]))\n \n # answer to queries, initial state set to -1\n ans = [-1] * len(queries)\n\n # sort intervals by low, high and size\n ivals = deque(sorted([(a, b, b - a + 1) for a, b in intervals]))\n \n # available intervals\n cands = []\n\n \n while q:\n x, i = q.popleft()\n \n # if lower bound of intervals on the top of stack <= current query\n while ivals and x >= ivals[0][0]:\n a, b, c = ivals.popleft()\n # if higher bound of intervals also meets the requirements\n # if not then discard the interval\n if x <= b:\n heappush(cands, (c, b, a))\n \n # udpate available intervals by removing old ones which no longer has a eligible higher bound\n while cands:\n c, b, a = heappop(cands)\n if x <= b:\n ans[i] = c\n heappush(cands, (c, b, a))\n break\n\n return ans", + "title": "1851. Minimum Interval to Include Each Query", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A certain bug's home is on the x-axis at position x . Help them get there from position 0 . The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden , where forbidden[i] means that the bug cannot jump to the position forbidden[i] , and integers a , b , and x , return the minimum number of jumps needed for the bug to reach its home . If there is no possible sequence of jumps that lands the bug on position x , return -1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It can jump exactly a positions forward (to the right).", + "It can jump exactly b positions backward (to the left).", + "It cannot jump backward twice in a row.", + "It cannot jump to any forbidden positions." + ], + "examples": [ + { + "text": "Example 1: Input:forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9Output:3Explanation:3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.", + "image": null + }, + { + "text": "Example 2: Input:forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11Output:-1", + "image": null + }, + { + "text": "Example 3: Input:forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7Output:2Explanation:One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumJumps(int[] forbidden, int a, int b, int x) {\n \n // Visited Set\n Set visited = new HashSet();\n \n // Add forbidden coordinates to visited\n for (int i = 0; i < forbidden.length; i++) {\n visited.add(forbidden[i]);\n }\n \n // Distance/ Jumps map\n Map jumps = new HashMap<>();\n jumps.put(0, 0);\n \n // BFS Queue\n Queue q = new LinkedList<>();\n q.add(new Integer[] {0, 1});\n \n // BFS \n while (q.size() != 0) {\n \n Integer[] ud = q.poll();\n \n int u = ud[0], d = ud[1];\n \n // x found\n if (u == x) {\n return jumps.get(u);\n }\n \n // jump right\n if (u + a < 6001 && !visited.contains(u+a)) {\n q.add(new Integer[] {u+a, 1});\n visited.add(u+a);\n jumps.put(u+a, jumps.get(u) + 1);\n }\n \n // jump left\n if (d != -1 && u - b > -1 && !visited.contains(u-b)) {\n q.add(new Integer[] {u-b, -1});\n jumps.put(u-b, jumps.get(u) + 1);\n }\n \n }\n \n return -1;\n \n }\n}\n", + "title": "1654. Minimum Jumps to Reach Home", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A certain bug's home is on the x-axis at position x . Help them get there from position 0 . The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden , where forbidden[i] means that the bug cannot jump to the position forbidden[i] , and integers a , b , and x , return the minimum number of jumps needed for the bug to reach its home . If there is no possible sequence of jumps that lands the bug on position x , return -1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It can jump exactly a positions forward (to the right).", + "It can jump exactly b positions backward (to the left).", + "It cannot jump backward twice in a row.", + "It cannot jump to any forbidden positions." + ], + "examples": [ + { + "text": "Example 1: Input:forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9Output:3Explanation:3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.", + "image": null + }, + { + "text": "Example 2: Input:forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11Output:-1", + "image": null + }, + { + "text": "Example 3: Input:forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7Output:2Explanation:One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int:\n fb = set(fb)\n q = deque([[0,0,True]])\n while(q):\n n,l,isf = q.popleft()\n if(n<0 or n in fb or n>2000+2*b):\n continue\n fb.add(n)\n if(n==x):\n return l\n if isf and n-b>0:\n q.append([n-b,l+1,False]) \n q.append([n+a,l+1,True])\n return -1", + "title": "1654. Minimum Jumps to Reach Home", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting only of characters 'a' , 'b' , and 'c' . You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s only consists of characters 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ca\"Output:2Explanation:You can't remove any characters, so the string stays as is.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cabaabac\"Output:0Explanation:An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabccabba\"Output:3Explanation:An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 45.06%) | Memory: 54.1 MB (Top 20.99%)\nclass Solution {\n public int minimumLength(String s) {\n int length = s.length();\n char[] chars = s.toCharArray();\n for(int left = 0,right = chars.length-1;left < right;){\n if(chars[left] == chars[right]){\n char c = chars[left];\n while(left < right && chars[left] == c ){\n left++;\n length--;\n\n }\n\n while (right >= left && chars[right] == c){\n right--;\n length--;\n\n }\n }else {\n break;\n }\n }\n return length;\n }\n}", + "title": "1750. Minimum Length of String After Deleting Similar Ends", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s consisting only of characters 'a' , 'b' , and 'c' . You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s only consists of characters 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ca\"Output:2Explanation:You can't remove any characters, so the string stays as is.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cabaabac\"Output:0Explanation:An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"aabccabba\"Output:3Explanation:An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumLength(self, s: str) -> int:\n while(len(s)>1 and s[0]==s[-1]):\n s=s.strip(s[0])\n else:\n return len(s)\n", + "title": "1750. Minimum Length of String After Deleting Similar Ends", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums where the i th bag contains nums[i] balls. You are also given an integer maxOperations . You can perform the following operation at most maxOperations times: Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.", + "For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9], maxOperations = 2Output:3Explanation:- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,8,2], maxOperations = 4Output:2Explanation:- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,17], maxOperations = 2Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 86.75%) | Memory: 59.70 MB (Top 45.73%)\n\nclass Solution {\n\npublic int minimumSize(int[] nums, int maxOperations) {\n//initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at the price of time consumption.\n//The answer should be the minimized max value.\n int min = 0;\n int max = 1000000000;\n\t//Compared with min math.ceil(a/mid) gives the number of divided bags, we subtract the number by 1 to get the subdivision operation times.\n count+=(a-1)/mid;\n }\n\t\t//if count < maxOperations, max WOULD be further minimized and set to mid; \n\t\t//if count = maxOperations, max still COULD be further minimized and set to mid. \n\t\t//so we combine < and = cases together in one if condition\n if (count <= maxOperations) {\n\t\t//max = mid - 1 will not work in this case becasue mid could be the correct answer. \n\t\t//To not miss the correct answer we set a relatively \"loose\" boundary for max and min.\n max = mid;\n } else{\n min = mid;\n }\n }\n\t//Now we find the minimized max value\n return max;\n}\n}", + "title": "1760. Minimum Limit of Balls in a Bag", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums where the i th bag contains nums[i] balls. You are also given an integer maxOperations . You can perform the following operation at most maxOperations times: Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations. Return the minimum possible penalty after performing the operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Take any bag of balls and divide it into two new bags with a positive number of balls. For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.", + "For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9], maxOperations = 2Output:3Explanation:- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,8,2], maxOperations = 4Output:2Explanation:- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,17], maxOperations = 2Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n l, r = 1, max(nums)\n while l < r:\n mid = (l + r) // 2\n if sum([(n - 1) // mid for n in nums]) > maxOperations: \n l = mid + 1\n else:\n r = mid\n return l\n", + "title": "1760. Minimum Limit of Balls in a Bag", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 2D integer array stockPrices where stockPrices[i] = [day i , price i ] indicates the price of the stock on day day i is price i . A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below: Return the minimum number of lines needed to represent the line chart . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= stockPrices.length <= 10^5", + "stockPrices[i].length == 2", + "1 <= day i , price i <= 10^9", + "All day i are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]Output:3Explanation:The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.\nThe following 3 lines can be drawn to represent the line chart:\n- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).\n- Line 2 (in blue) from (4,4) to (5,4).\n- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).\nIt can be shown that it is not possible to represent the line chart using less than 3 lines.", + "image": "https://assets.leetcode.com/uploads/2022/03/30/ex0.png" + }, + { + "text": "Example 2: Input:stockPrices = [[3,4],[1,2],[7,8],[2,3]]Output:1Explanation:As shown in the diagram above, the line chart can be represented with a single line.", + "image": "https://assets.leetcode.com/uploads/2022/03/30/ex1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 57 ms (Top 71.43%) | Memory: 109.9 MB (Top 23.21%)\nclass Solution {\n public int minimumLines(int[][] stockPrices) {\n if(stockPrices.length == 1) return 0;\n int count = 1;\n Arrays.sort(stockPrices,(o1,o2)->o1[0]-o2[0]);\n for(int i=1;i int:\n if len(prices) == 1:\n return 0\n else:\n prices.sort(key=itemgetter(0))\n\n return self.using_slope(prices)\n # return self.using_cross_product(prices)\n\n @staticmethod\n def using_slope(prices: list[Point]) -> int:\n output, slope = 1, Solution.dy_by_dx\n\n ab = next(pairs := pairwise(prices))\n\n for bc in pairs:\n if slope(ab) != slope(bc):\n output += 1\n\n ab = bc\n\n return output\n\n @staticmethod\n def dy_by_dx(ab: tuple[Point, Point]) -> float | Fraction:\n (x1, y1), (x2, y2) = ab\n\n dx, dy = x2 - x1, y2 - y1\n\n if dx == 0:\n # 1. dx is 0, it means we have a vertical line going from (x1, y1). So whether dy is positive or\n # negative, it does not matter\n # 2. infinity can not be represented by fraction module so returning it directly from math module\n return inf\n else:\n # To avoid floating point error, we use fraction module.\n\n # (Simple divisions can give same results for example (apparently one of the test cases),\n # 499999998/499999999 and 499999999/500000000 gives same result, and that is where Fraction\n # class shines)\n return Fraction(dy, dx)\n\n @staticmethod\n def using_cross_product(prices: list[Point]) -> int:\n output, on_line = 1, Solution.lie_on_same_line\n\n a = next(itr := iter(prices))\n\n for b, c in pairwise(itr):\n if not on_line(a, b, c):\n output += 1\n\n a = b\n\n return output\n\n @staticmethod\n def lie_on_same_line(a: Point, b: Point, c: Point) -> bool:\n (x1, y1), (x2, y2), (x3, y3) = a, b, c\n\n return (y2 - y1) * (x3 - x2) == (x2 - x1) * (y3 - y2)", + "title": "2280. Minimum Lines to Represent a Line Chart", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s consisting of n characters which are either 'X' or 'O' . A move is defined as selecting three consecutive characters of s and converting them to 'O' . Note that if a move is applied to the character 'O' , it will stay the same . Return the minimum number of moves required so that all the characters of s are converted to 'O' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= s.length <= 1000", + "s[i] is either 'X' or 'O' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"XXX\"Output:1Explanation:XXX-> OOO\nWe select all the 3 characters and convert them in one move.", + "image": null + }, + { + "text": "Example 2: Input:s = \"XXOX\"Output:2Explanation:XXOX -> OOOX-> OOOO\nWe select the first 3 characters in the first move, and convert them to'O'.\nThen we select the last 3 characters and convert them so that the final string contains all'O's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"OOOO\"Output:0Explanation:There are no'X'sinsto convert.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 83.6%) | Memory: 41.00 MB (Top 8.7%)\n\nclass Solution {\n public int minimumMoves(String s) {\n int i=0;\n int step=0;\n while(i OOO\nWe select all the 3 characters and convert them in one move.", + "image": null + }, + { + "text": "Example 2: Input:s = \"XXOX\"Output:2Explanation:XXOX -> OOOX-> OOOO\nWe select the first 3 characters in the first move, and convert them to'O'.\nThen we select the last 3 characters and convert them so that the final string contains all'O's.", + "image": null + }, + { + "text": "Example 3: Input:s = \"OOOO\"Output:0Explanation:There are no'X'sinsto convert.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 64 ms (Top 5.43%) | Memory: 17.30 MB (Top 11.89%)\n\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n ans = i = 0\n while i < len(s): \n if s[i] == \"X\": \n ans += 1\n i += 3\n else: i += 1\n return ans \n", + "title": "2027. Minimum Moves to Convert String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of size n , return the minimum number of moves required to make all array elements equal . In one move, you can increment n - 1 elements of the array by 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "The answer is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:3Explanation:Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves(int[] nums) {\n int min=Integer.MAX_VALUE;\n int count=0;\n for(int i:nums)\n min=Math.min(i,min);\n \n for(int i=0;i [2,3,3] => [3,4,3] => [4,4,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves(self, nums: List[int]) -> int:\n return sum(nums)-min(nums)*len(nums)\n", + "title": "453. Minimum Moves to Equal Array Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of size n , return the minimum number of moves required to make all array elements equal . In one move, you can increment or decrement an element of the array by 1 . Test cases are designed so that the answer will fit in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:2Explanation:Only two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,10,2,9]Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves2(int[] nums) {\n Arrays.sort(nums);\n int idx=(nums.length-1)/2;\n int sum=0;\n for(int i=0;i [2,2,3] => [2,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,10,2,9]Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n \n n=len(nums)\n nums.sort()\n \n if n%2==1:\n median=nums[n//2]\n else:\n median = (nums[n//2 - 1] + nums[n//2]) // 2\n \n ans=0\n \n for val in nums:\n ans+=abs(val-median)\n \n return ans\n \n", + "title": "462. Minimum Moves to Equal Array Elements II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of even length n and an integer limit . In one move, you can replace any integer from nums with another integer between 1 and limit , inclusive. The array nums is complementary if for all indices i ( 0-indexed ), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i , nums[i] + nums[n - 1 - i] = 5 . Return the minimum number of moves required to make nums complementary . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^5", + "1 <= nums[i] <= limit <= 10^5", + "n is even." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,3], limit = 4Output:1Explanation:In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,1], limit = 2Output:2Explanation:In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,1,2], limit = 2Output:0Explanation:nums is already complementary.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMoves(int[] nums, int limit) {\n int[] oneMove = new int[2 * limit + 2];\n Map noMove = new HashMap<>();\n\n for (int i = 0; i < nums.length / 2; i++){\n int j = nums.length - 1 - i;\n noMove.merge(nums[i] + nums[j], 1, Integer::sum);\n oneMove[Math.min(nums[i], nums[j]) + 1]++;\n oneMove[Math.max(nums[i], nums[j]) + limit + 1]--;\n }\n\n int ans = nums.length, one = 0;\n for (int i = 2; i <= 2 * limit; i++){\n one += oneMove[i];\n ans = Math.min(ans, one + 2 * (nums.length / 2 - one) - noMove.getOrDefault(i, 0));\n }\n\n return ans;\n }\n}\n", + "title": "1674. Minimum Moves to Make Array Complementary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums of even length n and an integer limit . In one move, you can replace any integer from nums with another integer between 1 and limit , inclusive. The array nums is complementary if for all indices i ( 0-indexed ), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i , nums[i] + nums[n - 1 - i] = 5 . Return the minimum number of moves required to make nums complementary . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "2 <= n <= 10^5", + "1 <= nums[i] <= limit <= 10^5", + "n is even." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,3], limit = 4Output:1Explanation:In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,1], limit = 2Output:2Explanation:In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,1,2], limit = 2Output:0Explanation:nums is already complementary.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def minMoves(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n overlay_arr = [0] * (2*limit+2)\n for i in range(n//2):\n left_boundary = min(nums[i], nums[n-1-i]) + 1\n no_move_value = nums[i] + nums[n-1-i]\n right_boundary = max(nums[i], nums[n-1-i]) + limit\n overlay_arr[left_boundary] -= 1\n overlay_arr[no_move_value] -= 1\n overlay_arr[no_move_value+1] += 1\n overlay_arr[right_boundary+1] += 1\n curr_moves = n #initial assumption of two moves for each pair\n res = float(\"inf\")\n\t\t# start Sweeping\n for i in range(2, 2*limit+1):\n curr_moves += overlay_arr[i]\n res = min(res, curr_moves)\n return res\n", + "title": "1674. Minimum Moves to Make Array Complementary", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target . If there is no way to reach the target, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).", + "The character '.' represents the floor which means a free cell to walk.", + "The character '#' represents the wall which means an obstacle (impossible to walk there).", + "There is only one box 'B' and one target cell 'T' in the grid .", + "The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push .", + "The player cannot walk through the box." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:3Explanation:We return only the number of times the box is pushed.", + "image": "https://assets.leetcode.com/uploads/2019/11/06/sample_1_1620.png" + }, + { + "text": "Example 2: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:-1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:5Explanation:push the box down, left, left, up and up.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 51 ms (Top 51.89%) | Memory: 54.4 MB (Top 47.17%)\n/**\n Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves)\n Uses BFS/A* Algorithm to visit valid transition states\n Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations\n*/\nclass Solution {\n private int targetRow;\n private int targetCol;\n private char[][] grid;\n private static int[][] DIRS = {\n {1,0}, //Down\n {-1,0},//Up\n {0,1}, //Right\n {0,-1} //Left\n };\n\n /**\n State holds shopkeeper and box location, as well as how many times the box has been pushed\n */\n class State implements Comparable{\n int personRow;\n int personCol;\n int boxRow;\n int boxCol;\n int boxPushes;\n\n public State(int personRow, int personCol, int boxRow, int boxCol, int boxPushes){\n this.personRow = personRow;\n this.personCol = personCol;\n this.boxRow = boxRow;\n this.boxCol = boxCol;\n this.boxPushes = boxPushes;\n }\n\n // Override equals - used along with hashcode when we have visited HashSet\n public boolean equals(Object o){\n State other = (State) o;\n return\n this.personRow == other.personRow &&\n this.personCol == other.personCol &&\n this.boxRow == other.boxRow &&\n this.boxCol == other.boxCol;\n }\n\n // Override the hashCode - Note: it's okay for this to have collisions\n // But it won't due to the problem constraint that there is a bound on NxM dimensions\n public int hashCode(){\n return personRow *10_000 + personCol * 1_000 + boxRow * 100 + boxCol;\n }\n\n // Override to string method - helpful in debugging state.\n public String toString(){\n return \"ShopKeeper:{row:\"+personRow+\", col:\"+personCol+\"}\" +\n \"Box:{row:\"+boxRow+\", col:\"+boxCol+\"}\";\n }\n\n // Implement comparable interface such that we return the state that\n // has the possibility of lowest distance using box push count + Manhattan distance\n public int compareTo(State other){\n int minDistanceThis = this.boxPushes + distanceToTarget(this);\n int minDistanceOther = other.boxPushes + distanceToTarget(other);\n return Integer.compare(minDistanceThis, minDistanceOther);\n }\n\n }\n\n // Calculates Manhattan distance\n private int distanceToTarget(State state){\n int yDiff = Math.abs(state.boxCol - targetCol);\n int xDiff = Math.abs(state.boxRow - targetRow);\n return yDiff + xDiff;\n }\n\n /**\n Given a state, compare box location to target location to determine if it is\n a solution state.\n */\n private boolean isSolutionState(State state){\n return state.boxRow == targetRow && state.boxCol == targetCol;\n }\n\n /**\n Given a state, finds all valid transition states.\n This is accomplished by moving the ShopKeeper in all 4 directions and validate\n - Next ShopKeeper location is in bounds and is not a wall\n\n We have additional logic for when the next shopkeeper location is the box location:\n - Get next box location, by pushing the same direction, again validate that\n the next box location is in bounds, and is not a wall.\n\n If it's a valid transition, create the new state with the new shop keeper location\n and if the box moved, the new box location (also increment the number of box moves).\n\n **/\n private List getNeighbors(State state){\n\n int personRow = state.personRow;\n int personCol = state.personCol;\n int boxRow = state.boxRow;\n int boxCol = state.boxCol;\n\n List states = new ArrayList<>();\n for(int[] dir : DIRS){\n int rowMove = dir[0];\n int colMove = dir[1];\n int personRowNew = personRow + rowMove;\n int personColNew = personCol + colMove;\n // Shopkeeper cannot move into wall or go out of bounds skip to next direction\n if(!inBounds(personRowNew, personColNew) ||\n isWall(personRowNew, personColNew)){\n continue;\n }\n // Whether or not person will collide with box\n boolean willPushBox = personRowNew == boxRow && personColNew == boxCol;\n\n if(willPushBox){\n int boxRowNew = boxRow + rowMove;\n int boxColNew = boxCol + colMove;\n // Validate box can be pushed - if so push box and add to neighbor states\n if(inBounds(boxRowNew, boxColNew) &&\n !isWall(boxRowNew, boxColNew)){\n states.add(new State(personRowNew, personColNew, boxRowNew, boxColNew, state.boxPushes + 1));\n }\n } else {\n //Shop keeper moved, but not box\n states.add(new State(personRowNew, personColNew, boxRow, boxCol, state.boxPushes));\n }\n }\n return states;\n\n }\n\n // Given row/col, return whether it is wall\n private boolean isWall(int row, int col){\n char cell = grid[row][col];\n return cell == '#';\n }\n\n // Given row/col return whether is inBounds\n private boolean inBounds(int row, int col){\n int rows = grid.length;\n int cols = grid[0].length;\n if(row < 0 || col < 0 || row > rows-1 || col > cols-1){\n return false;\n }\n return true;\n }\n\n /**\n Returns initial state. Also finds and stores the target location.\n */\n private State getInitialState(){\n\n int shopKeeperRow=0;\n int shopKeeperCol=0;\n\n int boxRow = 0;\n int boxCol = 0;\n\n for(int r=0; r queue = new PriorityQueue<>();\n Set visited = new HashSet<>();\n queue.offer(initialState);\n\n // Explore every state using BSF and keep track of the best solution\n while(!queue.isEmpty()){\n State state = queue.poll();\n if(visited.contains(state)){\n continue;\n }\n visited.add(state);\n /*\n Note: the reason we can return the first solution state we find, is because we are\n using priority queue with minDistance heuristic which means the first solution we find\n is guaranteed to be the optimal solution - (A* Algorithm)\n */\n if(isSolutionState(state)){\n return state.boxPushes;\n }\n for(State neighbor : getNeighbors(state)){\n if(!visited.contains(neighbor)){\n queue.offer(neighbor);\n }\n };\n }\n // No solution - return -1\n return -1;\n }\n\n}", + "title": "1263. Minimum Moves to Move a Box to Their Target Location", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target . If there is no way to reach the target, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).", + "The character '.' represents the floor which means a free cell to walk.", + "The character '#' represents the wall which means an obstacle (impossible to walk there).", + "There is only one box 'B' and one target cell 'T' in the grid .", + "The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push .", + "The player cannot walk through the box." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:3Explanation:We return only the number of times the box is pushed.", + "image": "https://assets.leetcode.com/uploads/2019/11/06/sample_1_1620.png" + }, + { + "text": "Example 2: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:-1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]Output:5Explanation:push the box down, left, left, up and up.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n m,n=len(grid),len(grid[0])\n q=deque()\n start,target,box=(0,0),(0,0),(0,0)\n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"B\":\n box=(i,j)\n elif grid[i][j]==\"T\":\n target=(i,j)\n elif grid[i][j]==\"S\":\n start=(i,j)\n q.append((box[0],box[1],0,start[0],start[1]))\n visited=set()\n directions=((1,0,-1,0),(0,1,0,-1),(-1,0,1,0),(0,-1,0,1))\n visited.add(box+box)\n def solve(i,j,bi,bj):\n nonlocal seen\n if (i,j)==(bi,bj):\n return True\n ans=False\n for d in directions:\n ni,nj=i+d[0],j+d[1]\n if 0<=nim+n:\n return -1\n for d in directions:\n ni,nj,bi,bj=i+d[0],j+d[1],i+d[2],j+d[3]\n if 0<=ni int:\n c=0\n while(maxDoubles>0 and target>1):\n c += target%2\n target //= 2\n c += 1\n maxDoubles -=1\n return c + target-1", + "title": "2139. Minimum Moves to Reach Target Score", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1) . The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1) . In one move the snake can: Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1 . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/image.png" + ], + "constraints": [ + "Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c) .", + "Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]Output:11Explanation:One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 25.8%) | Memory: 45.52 MB (Top 12.9%)\n\nclass Solution {\n public int minimumMoves(int[][] grid) {\n \n int n = grid.length; \n //boolean[][][][] visited = new boolean[n][n][n][n];\n Set set = new HashSet<>();\n \n Queue q = new LinkedList<>();\n q.offer(new Position(0,0,0,1)); \n int count = 0;\n \n if(grid[n-1][n-2] == 1 || grid[n-1][n-1] == 1)\n return -1;\n \n while(!q.isEmpty()){\n ++count;\n Queue nextq = new LinkedList<>();\n while(!q.isEmpty()){\n \n Position p = q.poll();\n\n int r1 = p.getr1();\n int r2 = p.getr2();\n int c1 = p.getc1();\n int c2 = p.getc2();\n \n if(r1 == n-1 && r2 == n-1 && c1 == n-2 && c2==n-1)\n return count-1;\n \n if(set.contains(p))\n continue;\n \n if(c1+1 < n && grid[r1] [c1+1] != 1 && c2+1 < n && grid[r2] [c2+1] != 1)\n nextq.offer(new Position(r1, c1+1, r2, c2+1));\n if(r1+1 < n && grid[r1+1] [c1] != 1 && r2+1 < n && grid[r2+1] [c2] != 1)\n nextq.offer(new Position(r1+1, c1, r2+1, c2));\n \n if(r1 == r2 && r1+1 < n && r2+1 < n && grid[r1+1][c1] == 0 && grid[r2+1][c2] == 0 && grid[r1+1][c1] == 0)\n nextq.offer(new Position(r1,c1, r1+1, c1));\n \n if(c1 == c2 && c1+1 < n && c2+1 < n && grid[r1][c1+1] == 0 && grid[r2][c1+1] == 0 && grid[r1][c1+1] == 0)\n nextq.offer(new Position(r1,c1, r1, c1+1));\n set.add(p);\n }\n q = nextq;\n }\n return -1;\n }\n \n private class Position{\n int r1;\n int c1;\n int r2;\n int c2;\n \n public Position(int r1, int c1, int r2, int c2){\n this.r1 = r1;\n this.r2 = r2;\n this.c1 =c1;\n this.c2 = c2;\n }\n \n public int getr1(){\n return this.r1;\n }\n public int getr2(){\n return this.r2;\n }\n public int getc1(){\n return this.c1;\n }\n public int getc2(){\n return this.c2;\n }\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * r1 + c1 + prime *r2 + c2;\n return result;\n }\n \n @Override\n public boolean equals(Object obj) {\n Position p = (Position) obj;\n if(this.r1 == p.getr1() && this.r2 ==p.getr2() && this.c1 == p.getc1() && this.c2==p.getc2())\n return true;\n else\n return false;\n }\n } \n}", + "title": "1210. Minimum Moves to Reach Target with Rotations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1) . The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1) . In one move the snake can: Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1 . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/image.png" + ], + "constraints": [ + "Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.", + "Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c) .", + "Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1) ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]Output:11Explanation:One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n queue , vis , n = [(0,1,0,0)] , {} , len(grid)\n while queue:\n x,y,pos,moves = queue.pop(0)\n if x == y == n-1 and pos == 0: return moves\n if pos == 0:\n if y + 1 < n and grid[x][y+1] == 0 and (x,y+1,0) not in vis:\n vis[(x,y+1,0)] = True\n queue.append((x,y+1,0,moves+1))\n \n if x + 1 < n and grid[x+1][y-1] == 0 and grid[x+1][y] == 0:\n if (x+1,y-1,1) not in vis:\n vis[(x+1,y-1,1)] = True\n queue.append((x+1,y-1,1,moves+1))\n if (x+1,y,0) not in vis:\n vis[(x+1,y,0)] = True\n queue.append((x+1,y,0,moves+1))\n else:\n if x + 1 < n and grid[x+1][y] == 0 and (x+1,y,1) not in vis:\n vis[(x+1,y,1)] = True\n queue.append((x+1,y,1,moves+1))\n if y + 1 < n and grid[x-1][y+1] == grid[x][y+1] == 0:\n if (x-1,y+1,0) not in vis:\n vis[(x-1,y+1,0)] = True\n queue.append((x-1,y+1,0,moves+1))\n if (x,y+1,1) not in vis:\n vis[(x,y+1,1)] = True\n queue.append((x,y+1,1,moves+1))\n return -1\n", + "title": "1210. Minimum Moves to Reach Target with Rotations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a positive integer p . Consider an array nums ( 1-indexed ) that consists of the integers in the inclusive range [1, 2 p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 11 0 1 and y = 00 1 1 , after swapping the 2 nd bit from the right, we have x = 11 1 1 and y = 00 0 1 . Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7 . Note: The answer should be the minimum product before the modulo operation is done. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two elements x and y from nums .", + "Choose a bit in x and swap it with its corresponding bit in y . Corresponding bit refers to the bit that is in the same position in the other integer." + ], + "examples": [ + { + "text": "Example 1: Input:p = 1Output:1Explanation:nums = [1].\nThere is only one element, so the product equals that element.", + "image": null + }, + { + "text": "Example 2: Input:p = 2Output:6Explanation:nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.", + "image": null + }, + { + "text": "Example 3: Input:p = 3Output:1512Explanation:nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001,110, 011, 100,001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mod = 1_000_000_007;\n public int minNonZeroProduct(int p) {\n if (p == 1) return 1;\n \n long mx = (long)(Math.pow(2, p)) - 1;\n long sm = mx - 1;\n long n = sm/2;\n long sum = rec(sm, n);\n \n return (int)(sum * (mx % mod) % mod); \n }\n \n public long rec(long val, long n) {\n if (n == 0) return 1;\n if (n == 1) return (val % mod);\n \n long newVal = ((val % mod) * (val % mod)) % mod;\n \n if (n % 2 != 0) {\n return ((rec(newVal, n/2) % mod) * (val % mod)) % mod;\n }\n \n return rec(newVal, n/2) % mod;\n }\n}\n", + "title": "1969. Minimum Non-Zero Product of the Array Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a positive integer p . Consider an array nums ( 1-indexed ) that consists of the integers in the inclusive range [1, 2 p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 11 0 1 and y = 00 1 1 , after swapping the 2 nd bit from the right, we have x = 11 1 1 and y = 00 0 1 . Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7 . Note: The answer should be the minimum product before the modulo operation is done. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose two elements x and y from nums .", + "Choose a bit in x and swap it with its corresponding bit in y . Corresponding bit refers to the bit that is in the same position in the other integer." + ], + "examples": [ + { + "text": "Example 1: Input:p = 1Output:1Explanation:nums = [1].\nThere is only one element, so the product equals that element.", + "image": null + }, + { + "text": "Example 2: Input:p = 2Output:6Explanation:nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.", + "image": null + }, + { + "text": "Example 3: Input:p = 3Output:1512Explanation:nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001,110, 011, 100,001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minNonZeroProduct(self, p: int) -> int:\n mod = 10**9+7\n return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod\n", + "title": "1969. Minimum Non-Zero Product of the Array Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]Output:4Explanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 56 ms (Top 51.6%) | Memory: 74.38 MB (Top 92.9%)\n\nclass Solution {\n public int findMinArrowShots(int[][] points) {\n \n int minNumArrows = 1;\n Arrays.sort(points, new Comparator(){\n @Override\n public int compare(int[] i1, int[] i2)\n {\n if(i1[0] < i2[0])\n return -1;\n else if (i1[0] > i2[0])\n return 1;\n return 0;\n }\n });\n \n // This is where they will trip you up ( at the merge stage )\n // Wait ... do we actually have to merge here? The intervals have been sorted already\n // No you must merge\n // See if they can be merged\n // If mergeable - overwrite OR write into a new subintervals code ( new ArrayList ) \n // Ok ... so first we compare (a1,a2) and then next step compare (a2,a3)\n // Now if (a1,a2) had an overlap -> why not make the next a2 = merged(a1,a2)? \n // That would do a carry over effect then\n int n = points.length;\n int[] candid = new int[2]; // always first interval anyways\n candid[0] = points[0][0];\n candid[1] = points[0][1];\n for(int i = 1; i < n; i++)\n {\n // System.out.printf(\"Current set = (%d,%d)\\n\", candid[0], candid[1]);\n int[] next = points[i];\n if(hasOverlap(candid,next))\n {\n int[] merged = mergeInterval(candid,next);\n candid[0] = merged[0];\n candid[1] = merged[1];\n }\n else\n {\n candid[0] = next[0];\n candid[1] = next[1]; \n minNumArrows++;\n }\n }\n \n return minNumArrows;\n }\n \n public boolean hasOverlap(int[] i1, int[] i2)\n {\n boolean hasOverlap = false;\n if(i1[0] <= i2[0] && i2[0] <= i1[1])\n hasOverlap = true;\n if(i2[0] <= i1[0] && i1[0] <= i2[1])\n hasOverlap = true;\n return hasOverlap;\n }\n \n public int[] mergeInterval(int[] i1, int[] i2)\n {\n int[] merged = new int[2];\n merged[0] = Math.max(i1[0],i2[0]);\n merged[1] = Math.min(i1[1],i2[1]);\n return merged;\n }\n}", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]Output:4Explanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points.sort()\n \n ans=[points[0]]\n for i in points[1:]:\n if(i[0]<=ans[-1][1]):\n ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])]\n else:\n ans.append(i)\n return len(ans)\n \n", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-index ed string street . Each character in street is either 'H' representing a house or '.' representing an empty space. You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at index i - 1 and/or index i + 1 . A single bucket, if placed adjacent to two houses, can collect the rainwater from both houses. Return the minimum number of buckets needed so that for every house, there is at least one bucket collecting rainwater from it, or -1 if it is impossible. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= street.length <= 10^5", + "street[i] is either 'H' or '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:street = \"H..H\"Output:2Explanation:We can put buckets at index 1 and index 2.\n\"H..H\" -> \"HBBH\" ('B' denotes where a bucket is placed).\nThe house at index 0 has a bucket to its right, and the house at index 3 has a bucket to its left.\nThus, for every house, there is at least one bucket collecting rainwater from it.", + "image": null + }, + { + "text": "Example 2: Input:street = \".H.H.\"Output:1Explanation:We can put a bucket at index 2.\n\".H.H.\" -> \".HBH.\" ('B' denotes where a bucket is placed).\nThe house at index 1 has a bucket to its right, and the house at index 3 has a bucket to its left.\nThus, for every house, there is at least one bucket collecting rainwater from it.", + "image": null + }, + { + "text": "Example 3: Input:street = \".HHH.\"Output:-1Explanation:There is no empty space to place a bucket to collect the rainwater from the house at index 2.\nThus, it is impossible to collect the rainwater from all the houses.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumBuckets(self, street: str) -> int:\n street = list(street)\n print(street)\n num = 0\n for i in range(len(street)):\n if street[i] == \"H\":\n if i > 0 and street[i-1] == \"B\":\n continue\n if i < len(street) - 1 and street[i+1] == \".\":\n street[i+1] = \"B\"\n num += 1\n continue\n if i > 0 and street[i-1] == \".\":\n street[i-1] = \"B\"\n num += 1\n continue\n return -1\n return num", + "title": "2086. Minimum Number of Buckets Required to Collect Rainwater from Houses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1 's. The grid is said to be connected if we have exactly one island , otherwise is said disconnected . In one day, we are allowed to change any single land cell (1) into a water cell (0) . Return the minimum number of days to disconnect the grid . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 30", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]Output:2Explanation:We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/land1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1]]Output:2Explanation:Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/land2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 98.46%) | Memory: 18.30 MB (Top 33.85%)\n\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n\n disc_time = [[-1 for _ in range(cols)] for _ in range(rows)]\n low_value = [[-1 for _ in range(cols)] for _ in range(rows)]\n parents = [[(-1, -1) for _ in range(cols)] for _ in range(rows)]\n is_ap = [[False for _ in range(cols)] for _ in range(rows)]\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\n time = 0\n has_ap = False\n def dfs(i, j):\n if grid[i][j] == 0:\n return\n nonlocal time\n nonlocal has_ap\n disc_time[i][j] = time\n low_value[i][j] = time\n time += 1\n\n child = 0\n for di, dj in dirs:\n ni, nj = i + di, j + dj\n if not (0 <= ni < rows) or not (0 <= nj < cols):\n continue\n if grid[ni][nj] != 1:\n continue\n\n if disc_time[ni][nj] == -1: # not visited\n child += 1\n parents[ni][nj] = (i, j)\n dfs(ni, nj)\n low_value[i][j] = min(low_value[i][j], low_value[ni][nj])\n\n if parents[i][j] == (-1, -1) and child > 1:\n is_ap[i][j] = True\n has_ap = True\n\n if parents[i][j] != (-1, -1) and low_value[ni][nj] >= disc_time[i][j]:\n is_ap[i][j] = True\n has_ap = True\n elif (ni, nj) != parents[i][j]:\n low_value[i][j] = min(low_value[i][j], disc_time[ni][nj])\n\n sccs = 0\n num_ones = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n num_ones += 1\n if disc_time[i][j] == -1 and grid[i][j] == 1:\n dfs(i, j)\n sccs += 1\n\n\n if sccs > 1:\n return 0\n elif has_ap:\n return 1\n else:\n if num_ones == 1:\n return 1\n elif num_ones == 0:\n return 0\n return 2\n\n\n", + "title": "1568. Minimum Number of Days to Disconnect Island", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: You can only choose one of the actions per day. Given the integer n , return the minimum number of days to eat n oranges . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Eat one orange.", + "If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.", + "If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:4Explanation:You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:3Explanation:You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 97.62%) | Memory: 41.6 MB (Top 89.76%)\nclass Solution {\n HashMapmap;\n public int minDays(int n) {\n map = new HashMap<>();\n map.put(0,0);\n map.put(1,1);\n return dp(n);\n }\n public int dp(int n){\n if(map.get(n)!=null)\n return map.get(n);\n int one = 1+(n%2)+dp(n/2);\n int two = 1+(n%3)+dp(n/3);\n map.put(n,Math.min(one,two));\n return map.get(n);\n}\n }\n // int one = 1+(n%2)+cache(n/2);\n // int two = 1+(n%3)+cache(n/3);\n", + "title": "1553. Minimum Number of Days to Eat N Oranges", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: You can only choose one of the actions per day. Given the integer n , return the minimum number of days to eat n oranges . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Eat one orange.", + "If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.", + "If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:4Explanation:You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:3Explanation:You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import deque\nfrom math import log2, ceil\nclass Solution:\n def minDays(self, n: int) -> int:\n maxd = 2*ceil(log2(n))\n que = deque([(1,1)])\n seen = set()\n while que:\n v, d = que.popleft()\n seen.add(v)\n if v == n:\n return d\n for w in [v+1, 2*v, 3*v]:\n if w not in seen and d <= maxd and w <= n:\n que.append((w,d+1))\n", + "title": "1553. Minimum Number of Days to Eat N Oranges", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array bloomDay , an integer m and an integer k . You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the i th flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden . If it is impossible to make m bouquets return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "bloomDay.length == n", + "1 <= n <= 10^5", + "1 <= bloomDay[i] <= 10^9", + "1 <= m <= 10^6", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:bloomDay = [1,10,3,10,2], m = 3, k = 1Output:3Explanation:Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:bloomDay = [1,10,3,10,2], m = 3, k = 2Output:-1Explanation:We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.", + "image": null + }, + { + "text": "Example 3: Input:bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3Output:12Explanation:We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDays(int[] bloomDay, int m, int k) {\n if(m*k > bloomDay.length) return -1;\n \n int low = Integer.MAX_VALUE, high = 0;\n for(int i:bloomDay){\n low = Math.min(low,i);\n high = Math.max(high,i);\n }\n while(low<=high){\n int mid = low + (high-low)/2;\n if(isPossible(bloomDay,mid,m,k)) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private boolean isPossible(int[] bloomDay,int maxDays,int m,int k){\n for(int i=0;i int:\n \n def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking):\n \n currentListOfAdjacentBloomedFlowers = []\n numberOfBouquetsWeCanMakeOnThisDay = 0\n \n for dayThatFlowerBlooms in listOfFlowerBloomDays:\n \n # check if the flower has bloomed on this day \n if dayThatFlowerBlooms <= dayThatWeAreChecking:\n \n # add to the list an adjacent bloomed flowers, I use 'x' because the description uses an 'x'\n currentListOfAdjacentBloomedFlowers.append('x')\n \n else:\n # we've hit a day where we don't have a bloomed flower, so the list of adjacent bloomed flowers has to be reset\n # BUT FIRST figure out how many bouquets we can make with this list of adjacent bloomed flowers\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n # RESET list of adjacent bloomed flowers cause we're on a day where the a flower has not bloomed yet\n currentListOfAdjacentBloomedFlowers = []\n \n # we've gone through the entire listOfFlowerBloomDays list and need to check if the \"residual\" current list \n # of adjacent bloomed flowers can make a bouquet ... so handle it here\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n return numberOfBouquetsWeCanMakeOnThisDay\n \n \n # if the TOTAL amount of flowers we need doesn't match the number of possible flowers we can grow,\n # then the given inputs are impossible for making enough bouquets (we don't have enough flowers)\n totalNumberOfFlowersNeeded = targetNumberOfBouquets*flowersPerBouquet\n numberOfFlowersWeCanGrow = len(listOfFlowerBloomDays)\n if numberOfFlowersWeCanGrow < totalNumberOfFlowersNeeded: \n return -1\n \n # no need to go past the day of the flower with the longest bloom date\n leftDay = 0\n rightDay = max(listOfFlowerBloomDays)\n \n while leftDay < rightDay:\n \n # currentDay is functioning as the \"mid\" of a binary search\n currentDay = leftDay + (rightDay-leftDay)//2\n \n # as in most binary searches, we check if the mid (which I'm calling 'currentDay') satisfies the constraint\n # that is, if we can make the target amount of bouquets on this day\n if numberOfBouquetsWeCanMakeOnThisDay(currentDay) < targetNumberOfBouquets:\n \n # womp womp, we can't make enough bouquets on this day, so set up for next iteration\n # the \"correct day\" is on the right side, so we get rid of all the \"incorrect days\" on the left side\n # by updating the left to the currentDay+1\n leftDay = currentDay+1\n else:\n \n # yay, we can make enough bouquets on this day, but we don't know if this is the \"minimum day\"\n # we discard the right side to keep searching\n rightDay = currentDay\n \n # leftDay >= rightDay, so we've found the \"minimum day\"\n return leftDay\n\t\t", + "title": "1482. Minimum Number of Days to Make m Bouquets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a m x n binary matrix mat . In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1 ). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 3", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0],[0,1]]Output:3Explanation:One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.", + "image": "https://assets.leetcode.com/uploads/2019/11/28/matrix.png" + }, + { + "text": "Example 2: Input:mat = [[0]]Output:0Explanation:Given matrix is a zero matrix. We do not need to change it.", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,0,0],[1,0,0]]Output:-1Explanation:Given matrix cannot be a zero matrix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(int[][] mat) {\n int m = mat.length, n = mat[0].length;\n Set visited = new HashSet<>();\n Queue queue = new LinkedList<>();\n int steps = 0;\n \n int initialState = toBinary(mat);\n queue.add(initialState);\n visited.add(initialState);\n \n while (!queue.isEmpty()) {\n int size = queue.size();\n \n for (int i = 0; i < size; i++) {\n int state = queue.poll();\n if (state == 0) return steps;\n int mask = 1;\n\n for (int y = 0; y < m; y++) {\n for (int x = 0; x < n; x++) {\n int nextState = flip(state, x, y, n, m);\n if (!visited.contains(nextState)) {\n visited.add(nextState);\n queue.add(nextState);\n }\n mask = mask << 1;\n }\n }\n }\n steps++;\n }\n return -1;\n }\n \n private int toBinary(int[][] M) {\n int bin = 0;\n for (int y = 0; y < M.length; y++) {\n for (int x = 0; x < M[0].length; x++) {\n bin = (bin << 1) + M[y][x];\n }\n }\n return bin;\n }\n \n private int flip(int state, int x, int y, int n, int m) {\n int flip = 1 << ((y*n) + x);\n flip += (x > 0) ? 1 << ((y*n) + (x-1)) : 0;\n flip += (x < n-1) ? 1 << ((y*n) + (x+1)) : 0;\n flip += (y > 0) ? 1 << (((y-1)*n) + x) : 0;\n flip += (y < m-1) ? 1 << (((y+1)*n) + x) : 0;\n return state ^ flip;\n }\n}\n", + "title": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a m x n binary matrix mat . In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1 ). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot. A binary matrix is a matrix with all cells equal to 0 or 1 only. A zero matrix is a matrix with all cells equal to 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 3", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0],[0,1]]Output:3Explanation:One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.", + "image": "https://assets.leetcode.com/uploads/2019/11/28/matrix.png" + }, + { + "text": "Example 2: Input:mat = [[0]]Output:0Explanation:Given matrix is a zero matrix. We do not need to change it.", + "image": null + }, + { + "text": "Example 3: Input:mat = [[1,0,0],[1,0,0]]Output:-1Explanation:Given matrix cannot be a zero matrix.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n flips = [11, 23, 38, 89, 186, 308, 200, 464, 416]\n \n def minFlips(self, mat: List[List[int]]) -> int:\n mask = self.make_mask(mat)\n check = self.make_mask([[1 for c in r] for r in mat])\n min_steps = -1\n last = 0\n for x in range(2**9):\n x = x & check\n flips = last ^ x\n last = x\n if not flips:\n continue\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n index = (i * 3 + j)\n if 1 << index & flips:\n mask ^= self.flips[index]\n if check & ~mask == check:\n steps = self.count_bits(x & check)\n if min_steps < 0 or steps < min_steps:\n min_steps = steps\n return min_steps\n \n def make_mask(self, mat):\n d = 0\n for i in range(3):\n for j in range(3):\n if i < len(mat) and j < len(mat[0]):\n d |= mat[i][j] << (i * 3 + j)\n return d\n\n def count_bits(self, x):\n count = 0\n i = 1\n while i <= x:\n count += int(bool(x & i))\n i <<= 1\n return count\n", + "title": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a binary string s . You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating . The string is called alternating if no two adjacent characters are equal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Type-1: Remove the character at the start of the string s and append it to the end of the string.", + "Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"Output:2Explanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"Output:0Explanation: The string is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"Output:1Explanation: Use the second operation on the second element to make s = \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(String s) {\n /*\n * Sliding Window Approach\n */\n \n \n int n = s.length();\n \n int mininumFlip = Integer.MAX_VALUE;\n \n int misMatchCount = 0;\n for(int i = 0; i < (2 * n); i++){\n \n int r = i % n;\n \n //add mis watch count in current window\n if((s.charAt(r) - '0') != (i % 2 == 0 ? 1 : 0)) misMatchCount++;\n \n //remove mismatch count which are not relvent for current window\n if(i >= n && (s.charAt(r) - '0') != (r % 2 == 0 ? 1 : 0)) misMatchCount--;\n \n \n //misMatchCount : when valid binary string start from 1\n //n - misMatchCount : when valid binary string start from 0\n if(i >= n - 1) mininumFlip = Math.min(mininumFlip, Math.min(misMatchCount, n - misMatchCount));\n }\n \n return mininumFlip;\n }\n}\n\n", + "title": "1888. Minimum Number of Flips to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a binary string s . You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating . The string is called alternating if no two adjacent characters are equal. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Type-1: Remove the character at the start of the string s and append it to the end of the string.", + "Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"Output:2Explanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"Output:0Explanation: The string is already alternating.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"Output:1Explanation: Use the second operation on the second element to make s = \"1010\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 631 ms (Top 87.94%) | Memory: 14.8 MB (Top 94.52%)\nclass Solution:\n def minFlips(self, s: str) -> int:\n prev = 0\n start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n odd = len(s)%2\n for val in s:\n val = int(val)\n if val == prev:\n if odd:\n start_0_odd = min(start_0_odd, start_1)\n start_1_odd += 1\n start_1 += 1\n else:\n if odd:\n start_1_odd = min(start_1_odd, start_0)\n start_0_odd += 1\n start_0 += 1\n prev = 1 - prev\n return min([start_1, start_0, start_1_odd, start_0_odd])", + "title": "1888. Minimum Number of Flips to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the string croakOfFrogs , which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c' , 'r' , 'o' , 'a' , and 'k' sequentially . The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= croakOfFrogs.length <= 10^5", + "croakOfFrogs is either 'c' , 'r' , 'o' , 'a' , or 'k' ." + ], + "examples": [ + { + "text": "Example 1: Input:croakOfFrogs = \"croakcroak\"Output:1Explanation:One frog yelling \"croak\"twice.", + "image": null + }, + { + "text": "Example 2: Input:croakOfFrogs = \"crcoakroak\"Output:2Explanation:The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".", + "image": null + }, + { + "text": "Example 3: Input:croakOfFrogs = \"croakcrook\"Output:-1Explanation:The given string is an invalid combination of \"croak\"from different frogs.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 80.36%) | Memory: 46.5 MB (Top 68.93%)\nclass Solution {\n public int minNumberOfFrogs(String croakOfFrogs) {\n int[] index = new int[26];\n String corak = \"croak\";\n\n // Giving index to each characters\n for (int i = 0; i < corak.length(); ++i)\n index[corak.charAt(i) - 'a'] = i;\n\n int ans = 0, sum = 0;\n int[] count = new int[5];\n\n for (char c : croakOfFrogs.toCharArray()) {\n int i = index[c - 'a'];\n // If it is not 'c' it will decrease the sum\n if (c != 'c') {\n if (count[i - 1]-- <= 0) return -1;\n sum--;\n }\n // If it is not 'k' it will increase the sum\n if (c != 'k') {\n count[i]++;\n sum++;\n }\n ans = Math.max(ans, sum);\n }\n return sum == 0 ? ans : -1;\n }\n}", + "title": "1419. Minimum Number of Frogs Croaking", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the string croakOfFrogs , which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid \"croak\" means a frog is printing five letters 'c' , 'r' , 'o' , 'a' , and 'k' sequentially . The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= croakOfFrogs.length <= 10^5", + "croakOfFrogs is either 'c' , 'r' , 'o' , 'a' , or 'k' ." + ], + "examples": [ + { + "text": "Example 1: Input:croakOfFrogs = \"croakcroak\"Output:1Explanation:One frog yelling \"croak\"twice.", + "image": null + }, + { + "text": "Example 2: Input:croakOfFrogs = \"crcoakroak\"Output:2Explanation:The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".", + "image": null + }, + { + "text": "Example 3: Input:croakOfFrogs = \"croakcrook\"Output:-1Explanation:The given string is an invalid combination of \"croak\"from different frogs.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 137 ms (Top 87.7%) | Memory: 17.15 MB (Top 48.6%)\n\nclass Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n c = r = o = a = k = max_frog_croak = present_frog_croak = 0\n # need to know, at particular point,\n # what are the max frog are croaking,\n\n for i, v in enumerate(croakOfFrogs):\n if v == 'c':\n c += 1\n\t\t\t\t# c gives a signal for a frog\n present_frog_croak += 1\n elif v == 'r':\n r += 1\n elif v == 'o':\n o += 1\n elif v == 'a':\n a += 1\n else:\n k += 1\n\t\t\t\t# frog stop croaking\n present_frog_croak -= 1\n\n max_frog_croak = max(max_frog_croak, present_frog_croak)\n # if any inoder occurs;\n if c < r or r < o or o < a or a < k:\n return -1\n\n # if all good, else -1\n if present_frog_croak == 0 and c == r and r == o and o == a and a == k:\n return max_frog_croak\n return -1\n", + "title": "1419. Minimum Number of Frogs Croaking", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array target . You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target.length <= 10^5", + "1 <= target[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,2,1]Output:3Explanation:We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.", + "image": null + }, + { + "text": "Example 2: Input:target = [3,1,1,2]Output:4Explanation:[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]", + "image": null + }, + { + "text": "Example 3: Input:target = [3,1,5,4,2]Output:7Explanation:[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 98.94%) | Memory: 51.4 MB (Top 94.35%)\n// Imagine 3 cases\n// Case 1. [3,2,1], we need 3 operations.\n// Case 2. [1,2,3], we need 3 operations.\n// Case 3. [3,2,1,2,3], we need 5 operations.\n// What we need to add is actually the diff (cur - prev)\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int minNumberOperations(int[] target) {\n int res = 0;\n int prev = 0;\n for (int cur : target) {\n if (cur > prev) {\n res += cur - prev;\n }\n prev = cur;\n }\n return res;\n }\n}", + "title": "1526. Minimum Number of Increments on Subarrays to Form a Target Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array target . You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target.length <= 10^5", + "1 <= target[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:target = [1,2,3,2,1]Output:3Explanation:We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.", + "image": null + }, + { + "text": "Example 2: Input:target = [3,1,1,2]Output:4Explanation:[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]", + "image": null + }, + { + "text": "Example 3: Input:target = [3,1,5,4,2]Output:7Explanation:[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minNumberOperations(self, nums: List[int]) -> int:\n res=nums[0]\n prev=nums[0]\n for i in range(1,len(nums)):\n res += max(0,nums[i]-prev)\n prev=nums[i]\n return res\n", + "title": "1526. Minimum Number of Increments on Subarrays to Form a Target Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary array nums and an integer k . A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1 , and every 1 in the subarray to 0 . Return the minimum number of k-bit flips required so that there is no 0 in the array . If it is not possible, return -1 . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0], k = 1Output:2Explanation:Flip nums[0], then flip nums[2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,0], k = 2Output:-1Explanation:No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0,1,0,1,1,0], k = 3Output:3Explanation:Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 24.69%) | Memory: 90.8 MB (Top 76.54%)\nclass Solution {\n public int minKBitFlips(int[] nums, int k) {\n int target = 0, ans = 0;;\n boolean[] flip = new boolean[nums.length+1];\n for (int i = 0; i < nums.length; i++){\n if (flip[i]){\n target^=1;\n }\n if (inums.length-k&&nums[i]==target){\n return -1;\n }\n }\n return ans;\n }\n}", + "title": "995. Minimum Number of K Consecutive Bit Flips", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a binary array nums and an integer k . A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1 , and every 1 in the subarray to 0 . Return the minimum number of k-bit flips required so that there is no 0 in the array . If it is not possible, return -1 . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0], k = 1Output:2Explanation:Flip nums[0], then flip nums[2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,0], k = 2Output:-1Explanation:No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0,1,0,1,1,0], k = 3Output:3Explanation:Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2365 ms (Top 19.91%) | Memory: 17.1 MB (Top 67.10%)\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n flips = [0]*len(nums)\n csum = 0\n\n for left in range(0, len(nums)-k+1):\n if (nums[left] + csum) % 2 == 0:\n flips[left] += 1\n csum += 1\n if left >= k-1:\n csum -= flips[left-k+1]\n\n for check in range(len(nums)-k+1, len(nums)):\n if (nums[check] + csum) % 2 == 0:\n return -1\n if check >= k-1:\n csum -= flips[check-k+1]\n\n return sum(flips)\n", + "title": "995. Minimum Number of K Consecutive Bit Flips", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of lowercase English letters. In one move , you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome . Note that the input will be generated such that s can always be converted to a palindrome. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists only of lowercase English letters.", + "s can be converted to a palindrome using a finite number of moves." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabb\"Output:2Explanation:We can obtain two palindromes from s, \"abba\" and \"baab\". \n- We can obtain \"abba\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"abba\".\n- We can obtain \"baab\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"baab\".\nThus, the minimum number of moves needed to make s a palindrome is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"letelt\"Output:2Explanation:One of the palindromes we can obtain from s in 2 moves is \"lettel\".\nOne of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\nOther palindromes such as \"tleelt\" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n\tpublic int minMovesToMakePalindrome(String s) {\n\t\tint len = s.length();\n\t\tchar[] strArr = s.toCharArray(); \n\t\tint steps = 0;\n\t\tint l = 0, r = len-1; // use two pointers l for left and r for right. \n\n\t\twhile(l < r){ \n\t\t\tif(strArr[l] == strArr[r]){ // Both characters are equal. so keep going futher.\n\t\t\t\tl++; r--;\n\t\t\t}else{ // Both characters are not equal. \n\t\t\t\tint k = r;\n\t\t\t\tk = findKthIndexMatchingwithLthIndex(strArr, l, k); // loop through k, until char at index k = char at index l \n\n\t\t\t\tif(k == l){ // we did not find any char at k = char at index l \n\t\t\t\t\tswap(strArr, l);\n\t\t\t\t\tsteps++; \n\t\t\t\t}else{ \n\t\t\t\t\twhile(k < r){ \n\t\t\t\t\t\tswap(strArr, k);\n\t\t\t\t\t\tsteps++;\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\t\t\t\t\tl++; r--;\n\t\t\t\t} \n\t\t\t}// end of else\n\n\t\t} // end of while\n\t\tSystem.out.println(\"palindrome: \"+String.valueOf(strArr));\n\t\treturn steps;\n\n\t}\n\n\tpublic int findKthIndexMatchingwithLthIndex(char[] strArr, int l, int k){\n\t\twhile(k > l){\n\t\t\tif(strArr[k] == strArr[l]){ return k; } \n\t\t\tk--;\n\t\t}\n\t\treturn k;\n\t}\n\n\tpublic void swap(char[] strArr, int l){\n\t\tif(l+1 < strArr.length){\n\t\t\tchar tempCh = strArr[l];\n\t\t\tstrArr[l] = strArr[l+1];\n\t\t\tstrArr[l+1] = tempCh;\n\t\t}\n\t}\n}\n", + "title": "2193. Minimum Number of Moves to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s consisting only of lowercase English letters. In one move , you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome . Note that the input will be generated such that s can always be converted to a palindrome. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists only of lowercase English letters.", + "s can be converted to a palindrome using a finite number of moves." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabb\"Output:2Explanation:We can obtain two palindromes from s, \"abba\" and \"baab\". \n- We can obtain \"abba\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"abba\".\n- We can obtain \"baab\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"baab\".\nThus, the minimum number of moves needed to make s a palindrome is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"letelt\"Output:2Explanation:One of the palindromes we can obtain from s in 2 moves is \"lettel\".\nOne of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\nOther palindromes such as \"tleelt\" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minMovesToMakePalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count, length_of_s = 0, len(s)\n if length_of_s <= 2:\n return count\n for i in reversed(range(length_of_s)):\n if s[i] != s[0]:\n continue\n if i == 0:\n\t\t\t\t# move to middle is a speical case which takes len(s)/2 moves then do recursive for remaining part\n count += len(s)/2 + self.minMovesToMakePalindrome(s[1:]) \n else:\n\t\t\t # this move takes len(s)-1 - i (move from i to last index len(s)-1)and then do recursive for remaining part\n count += len(s)-1-i + self.minMovesToMakePalindrome(s[1:i]+s[i+1:])\n break\n return count\n", + "title": "2193. Minimum Number of Moves to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n seats and n students in a room. You are given an array seats of length n , where seats[i] is the position of the i th seat. You are also given the array students of length n , where students[j] is the position of the j th student. You may perform the following move any number of times: Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Increase or decrease the position of the i th student by 1 (i.e., moving the i th student from position x to x + 1 or x - 1 )" + ], + "examples": [ + { + "text": "Example 1: Input:seats = [3,1,5], students = [2,7,4]Output:4Explanation:The students are moved as follows:\n- The first student is moved from from position 2 to position 1 using 1 move.\n- The second student is moved from from position 7 to position 5 using 2 moves.\n- The third student is moved from from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.", + "image": null + }, + { + "text": "Example 2: Input:seats = [4,1,5,9], students = [1,3,2,6]Output:7Explanation:The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from from position 3 to position 4 using 1 move.\n- The third student is moved from from position 2 to position 5 using 3 moves.\n- The fourth student is moved from from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.", + "image": null + }, + { + "text": "Example 3: Input:seats = [2,2,6,6], students = [1,3,2,6]Output:4Explanation:Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from from position 1 to position 2 using 1 move.\n- The second student is moved from from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 99.78%) | Memory: 41.7 MB (Top 99.11%)\nclass Solution {\n public int minMovesToSeat(int[] seats, int[] students) {\n Arrays.sort(seats);\n Arrays.sort(students);\n int diff = 0;\n for(int i=0; i int:\n seats.sort()\n students.sort()\n return sum(abs(seat - student) for seat, student in zip(seats, students))\n", + "title": "2037. Minimum Number of Moves to Seat Everyone", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings current and correct representing two 24-hour times . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . In one operation you can increase the time current by 1 , 5 , 15 , or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "current and correct are in the format \"HH:MM\"", + "current <= correct" + ], + "examples": [ + { + "text": "Example 1: Input:current = \"02:30\", correct = \"04:35\"Output:3Explanation:We can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:current = \"11:00\", correct = \"11:01\"Output:1Explanation:We only have to add one minute to current, so the minimum number of operations needed is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.73%) | Memory: 42.8 MB (Top 23.55%)\nclass Solution {\n public int HHMMToMinutes(String s){\n return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;\n }\n public int convertTime(String current, String correct) {\n int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);\n int[] order = {60,15,5,1};\n int i = 0;\n int ops = 0;\n while(i < 4){\n ops+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n return ops;\n }\n}", + "title": "2224. Minimum Number of Operations to Convert Time", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given two strings current and correct representing two 24-hour times . 24-hour times are formatted as \"HH:MM\" , where HH is between 00 and 23 , and MM is between 00 and 59 . The earliest 24-hour time is 00:00 , and the latest is 23:59 . In one operation you can increase the time current by 1 , 5 , 15 , or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "current and correct are in the format \"HH:MM\"", + "current <= correct" + ], + "examples": [ + { + "text": "Example 1: Input:current = \"02:30\", correct = \"04:35\"Output:3Explanation:We can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:current = \"11:00\", correct = \"11:01\"Output:1Explanation:We only have to add one minute to current, so the minimum number of operations needed is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 83.44%) | Memory: 17.40 MB (Top 22.74%)\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def get_time(t):\n hh, mm = t.split(':')\n return int(hh) * 60 + int(mm)\n \n current, correct = get_time(current), get_time(correct)\n operations = 0\n diff = correct - current\n \n for mins in [60, 15, 5, 1]:\n quotient, remainder = divmod(diff, mins)\n operations += quotient\n diff = remainder\n \n return operations\n", + "title": "2224. Minimum Number of Operations to Convert Time", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous , but nums = [1, 2, 3, 5, 6] is not continuous . Return the minimum number of operations to make nums continuous . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All elements in nums are unique .", + "The difference between the maximum element and the minimum element in nums equals nums.length - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]Output:0Explanation:nums is already continuous.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5,6]Output:1Explanation:One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,10,100,1000]Output:3Explanation:One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n TreeSet set = new TreeSet<>();\n int threshold = nums.length-1;\n int max = 0;\n Arrays.sort(nums);\n for(int num:nums) {\n while(!set.isEmpty() && num-set.first()>threshold) {\n set.remove(set.first());\n } \n set.add(num);\n max = Math.max(max, set.size()); \n }\n return nums.length-max;\n }\n}\n", + "title": "2009. Minimum Number of Operations to Make Array Continuous", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous , but nums = [1, 2, 3, 5, 6] is not continuous . Return the minimum number of operations to make nums continuous . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All elements in nums are unique .", + "The difference between the maximum element and the minimum element in nums equals nums.length - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,3]Output:0Explanation:nums is already continuous.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5,6]Output:1Explanation:One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,10,100,1000]Output:3Explanation:One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n end = 0\n ans = -1\n for i in range(len(nums)):\n while end < len(nums):\n if nums[i] + n > nums[end]:\n end+=1\n else:\n break\n ans = max(ans,end - i)\n return n - ans\n", + "title": "2009. Minimum Number of Operations to Make Array Continuous", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s ( 0-indexed )​​​​​​. You are asked to perform the following operation on s ​​​​​​ until you get a sorted string: Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cba\"Output:5Explanation:The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabaa\"Output:2Explanation:The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.*;\n\nclass Solution {\n public int makeStringSorted(String s) {\n BigInteger res = new BigInteger(\"0\");\n BigInteger mod = new BigInteger(\"1000000007\");\n \n int[] count = new int[26];\n BigInteger[] fact = factory(s.length(), mod);\n \n int n = s.length();\n BigInteger div = new BigInteger(\"1\");\n \n for (int i = n - 1; i >= 0; --i) {\n char c = s.charAt(i);\n count[c-'a'] ++;\n BigInteger c1 = countInverse(count, c); \n BigInteger ans = c1.multiply(fact[n-i-1]);\n div = div.multiply(new BigInteger(String.valueOf(count[c-'a'])));\n ans = ans.multiply(div.modPow(mod.subtract(new BigInteger(String.valueOf(2))), mod)).mod(mod);\n res = res.add(ans).mod(mod);\n }\n \n return res.intValue();\n }\n \n public BigInteger countInverse(int[] count, char c) {\n long cnt = 0;\n for (int i = 0; i < (c - 'a'); ++i) {\n cnt += count[i];\n }\n \n return new BigInteger(String.valueOf(cnt));\n }\n \n public BigInteger[] factory(int n, BigInteger mod) {\n BigInteger[] fact = new BigInteger[n+1];\n fact[0] = new BigInteger(\"1\");\n for (int i = 1; i <= n; ++i) {\n fact[i] = fact[i-1].multiply(new BigInteger(String.valueOf(i))).mod(mod);\n }\n \n return fact;\n }\n}\n", + "title": "1830. Minimum Number of Operations to Make String Sorted", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s ( 0-indexed )​​​​​​. You are asked to perform the following operation on s ​​​​​​ until you get a sorted string: Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cba\"Output:5Explanation:The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabaa\"Output:2Explanation:The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".", + "image": null + } + ], + "follow_up": null, + "solution": "from math import gcd\n\nclass Solution:\n def makeStringSorted(self, s: str) -> int:\n s = [ord(c) - ord('a') for c in s]\n ans, MOD = 0, 10 ** 9 + 7\n cnt, t, d, step = [0] * 26, 1, 1, 1\n cnt[s[-1]] = 1\n for c in reversed(s[:-1]):\n d *= (cnt[c] + 1)\n t *= step\n g = gcd(d, t)\n d //= g\n t //= g\n ans = (ans + t * sum(cnt[i] for i in range(c)) // d) % MOD\n cnt[c] += 1\n step += 1\n return ans", + "title": "1830. Minimum Number of Operations to Make String Sorted", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == boxes.length", + "1 <= n <= 2000", + "boxes[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:boxes = \"110\"Output:[1,1,3]Explanation:The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) 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.", + "image": null + }, + { + "text": "Example 2: Input:boxes = \"001011\"Output:[11,8,5,4,3,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 135 ms (Top 50.7%) | Memory: 44.02 MB (Top 24.4%)\n\nclass Solution{\n public int[] minOperations(String boxes){\n int n = boxes.length();\n int[] ans = new int[n];\n for(int i=0; i List[int]:\n ans = [0]*len(boxes)\n leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n for i in range(1, n):\n if boxes[i-1] == '1': leftCount += 1\n leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n ans[i] = leftCost\n for i in range(n-2, -1, -1):\n if boxes[i+1] == '1': rightCount += 1\n rightCost += rightCount\n ans[i] += rightCost\n return ans", + "title": "1769. Minimum Number of Operations to Move All Balls to Each Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an even integer n ​​​​​​. You initially have a permutation perm of size n ​​ where perm[i] == i ​ (0-indexed) ​​​​. In one operation, you will create a new array arr , and for each i : You will then assign arr ​​​​ to perm . Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If i % 2 == 0 , then arr[i] = perm[i / 2] .", + "If i % 2 == 1 , then arr[i] = perm[n / 2 + (i - 1) / 2] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:perm = [0,1] initially.\nAfter the 1stoperation, perm = [0,1]\nSo it takes only 1 operation.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:2Explanation:perm = [0,1,2,3] initially.\nAfter the 1stoperation, perm = [0,2,1,3]\nAfter the 2ndoperation, perm = [0,1,2,3]\nSo it takes only 2 operations.", + "image": null + }, + { + "text": "Example 3: Input:n = 6Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reinitializePermutation(int n) {\n int ans = 1;\n int num = 2;\n if(n == 2) return 1;\n while(true){\n if(num % (n-1) == 1)break; \n else {\n ans++;\n num = (num * 2) % (n-1);\n }\n }\n return ans;\n \n }\n}\n", + "title": "1806. Minimum Number of Operations to Reinitialize a Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an even integer n ​​​​​​. You initially have a permutation perm of size n ​​ where perm[i] == i ​ (0-indexed) ​​​​. In one operation, you will create a new array arr , and for each i : You will then assign arr ​​​​ to perm . Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If i % 2 == 0 , then arr[i] = perm[i / 2] .", + "If i % 2 == 1 , then arr[i] = perm[n / 2 + (i - 1) / 2] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:1Explanation:perm = [0,1] initially.\nAfter the 1stoperation, perm = [0,1]\nSo it takes only 1 operation.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:2Explanation:perm = [0,1,2,3] initially.\nAfter the 1stoperation, perm = [0,2,1,3]\nAfter the 2ndoperation, perm = [0,1,2,3]\nSo it takes only 2 operations.", + "image": null + }, + { + "text": "Example 3: Input:n = 6Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 341 ms (Top 53.7%) | Memory: 16.20 MB (Top 72.22%)\n\nclass Solution:\n def reinitializePermutation(self, n: int) -> int:\n ans = 0\n perm = list(range(n))\n while True: \n ans += 1\n perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]\n if all(perm[i] == i for i in range(n)): return ans\n", + "title": "1806. Minimum Number of Operations to Reinitialize a Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer n , an array languages , and an array friendships where: You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "There are n languages numbered 1 through n ,", + "languages[i] is the set of languages the i ​​​​​​th ​​​​ user knows, and", + "friendships[i] = [u ​​​​​​i ​​​, v ​​​​​​i ] denotes a friendship between the users u ​​​​​ ​​​​​​i ​​​​​ and v i ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]Output:1Explanation:You can either teach user 1 the second language or user 2 the first language.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]Output:2Explanation:Teach the third language to users 1 and 3, yielding two users to teach.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2444 ms (Top 20.45%) | Memory: 28.6 MB (Top 5.68%)\nclass Solution:\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n \"\"\"\n 1. Find out users who need to be taught\n 2. If no user needs to be taught, return 0\n 3. For all users who need to be taught a language, find the most popular language among them\n 4. Teach that language to rest of the users who need to be taught.\n \"\"\"\n need_to_be_taught = set()\n languages = [set(language) for language in languages]\n\n # 1. Find out users who needs to be taught\n for user1, user2 in friendships:\n # Adjust the 1 based indexing to 0 based indexing\n user1 = user1 - 1\n user2 = user2 - 1\n if not (languages[user1] & languages[user2]):\n need_to_be_taught.update([user1, user2])\n\n # 2. If no user needs to be taught, return 0\n if not need_to_be_taught:\n return 0\n\n # 3. For all users who needs to be taught a language, find the most popular language among them\n language_spoken_by = collections.defaultdict(int)\n for user in need_to_be_taught:\n # for each user increment the count of languages he can speak\n for language in languages[user]:\n language_spoken_by[language] += 1\n\n # find occurrence of language spoken by maximum users who can't communicate with each other\n popular_language_count = max(language_spoken_by.values())\n\n # 4. Teach that language to rest of the users who need to be taught.\n return len(need_to_be_taught)- popular_language_count\n", + "title": "1733. Minimum Number of People to Teach", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [position i , fuel i ] indicates that the i th gas station is position i miles east of the starting position and has fuel i liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination . If it cannot reach the destination, return -1 . Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target, startFuel <= 10^9", + "0 <= stations.length <= 500", + "0 <= position i <= position i+1 < target", + "1 <= fuel i < 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:target = 1, startFuel = 1, stations = []Output:0Explanation:We can reach the target without refueling.", + "image": null + }, + { + "text": "Example 2: Input:target = 100, startFuel = 1, stations = [[10,100]]Output:-1Explanation:We can not reach the target (or even the first gas station).", + "image": null + }, + { + "text": "Example 3: Input:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]Output:2Explanation:We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 28.3%) | Memory: 45.04 MB (Top 8.2%)\n\nclass Solution {\n public int minRefuelStops(int target, int startFuel, int[][] stations) {\n if(startFuel >= target) return 0;\n int[][] dp = new int[stations.length + 1][stations.length + 1];\n for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel;\n for (int j = 1; j < dp.length; j++) {\n for (int i = j; i < dp.length; i++) {\n dp[i][j] = Math.max(dp[i-1][j], stations[i-1][0] > dp[i-1][j-1] ?\n Integer.MIN_VALUE : dp[i-1][j-1] + stations[i-1][1]);\n if(dp[i][j] >= target) return j;\n }\n }\n return -1;\n }\n}", + "title": "871. Minimum Number of Refueling Stops", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [position i , fuel i ] indicates that the i th gas station is position i miles east of the starting position and has fuel i liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination . If it cannot reach the destination, return -1 . Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target, startFuel <= 10^9", + "0 <= stations.length <= 500", + "0 <= position i <= position i+1 < target", + "1 <= fuel i < 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:target = 1, startFuel = 1, stations = []Output:0Explanation:We can reach the target without refueling.", + "image": null + }, + { + "text": "Example 2: Input:target = 100, startFuel = 1, stations = [[10,100]]Output:-1Explanation:We can not reach the target (or even the first gas station).", + "image": null + }, + { + "text": "Example 3: Input:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]Output:2Explanation:We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minRefuelStops(self, t, F, S):\n S.append([t, 0])\n heap, ans = [], 0\n for p,f in S:\n while heap and p > F:\n F -= heapq.heappop(heap)\n ans += 1\n if p > F: return -1\n heapq.heappush(heap, -f)\n return ans\n", + "title": "871. Minimum Number of Refueling Stops", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array nums ​​​, return the minimum number of elements to remove to make nums ​​​ a mountain array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1]Output:0Explanation:The array itself is a mountain array so we do not need to remove any elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,1,5,6,2,3,1]Output:3Explanation:One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 103 ms (Top 13.29%) | Memory: 45.9 MB (Top 81.01%)\nclass Solution {\n public int minimumMountainRemovals(int[] nums) {\n\n int n = nums.length;\n int[] LIS = new int[n];\n int[] LDS = new int[n];\n\n Arrays.fill(LIS, 1);\n Arrays.fill(LDS, 1);\n // calculate the longest increase subsequence (LIS) for every index i\n for(int i=1 ; i < n ; i++)\n {\n for(int j = 0 ; j < i ; j++)\n {\n if(nums[i] > nums[j] && LIS[j]+1 > LIS[i])\n LIS[i] = LIS[j]+1;\n }\n }\n\n // calculate the longest decreasing subsequence(LDS) for every index i and keep track of the maximum of LIS+LDS\n int max = 0;\n for(int i=n-2 ; i >= 0 ; i--)\n {\n for(int j = n-1 ; j > i ; j--)\n {\n if(nums[i] > nums[j] && LDS[j]+1 > LDS[i])\n LDS[i] = LDS[j]+1;\n }\n\n if(LIS[i] > 1 && LDS[i] > 1)\n max = Math.max(LIS[i]+LDS[i]-1, max);\n }\n return n - max;\n }\n}", + "title": "1671. Minimum Number of Removals to Make Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You may recall that an array arr is a mountain array if and only if: Given an integer array nums ​​​, return the minimum number of elements to remove to make nums ​​​ a mountain array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some index i ( 0-indexed ) with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,1]Output:0Explanation:The array itself is a mountain array so we do not need to remove any elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,1,5,6,2,3,1]Output:3Explanation:One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n n = len(nums)\n inc = [0] * n\n dec = [0] * n\n \n# Longest Increasing Subsequence\n for i in range(1,n):\n for j in range(0,i):\n if nums[i] > nums[j]:\n inc[i] = max(inc[i], inc[j] + 1)\n \n# Longest Decreasing Subsequence\n for i in range(n-2,-1,-1):\n for j in range(n-1,i,-1):\n if nums[i] > nums[j]:\n dec[i] = max(dec[i], dec[j] + 1)\n \n# Final calculation\n res = 0\n for i in range(0,n):\n if inc[i] > 0 and dec[i] > 0:\n res = max(res, inc[i] + dec[i])\n \n# Final conclusion \n return n - res - 1\n", + "title": "1671. Minimum Number of Removals to Make Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings of the same length s and t . In one step you can choose any character of t and replace it with another character . Return the minimum number of steps to make t an anagram of s . An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s.length == t.length", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bab\", t = \"aba\"Output:1Explanation:Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", t = \"practice\"Output:5Explanation:Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"anagram\", t = \"mangaar\"Output:0Explanation:\"anagram\" and \"mangaar\" are anagrams.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 64.38%) | Memory: 54.3 MB (Top 67.83%)\n//find the frequency of every letter and check diffrence between the frequency of each letter then divide it by 2 to calculate the minimum number of letter to be changed.\nclass Solution {\n public int minSteps(String s, String t) {\n int sf[]=new int[26];\n int tf[]=new int[26];\n int diff=0;\n for(char c:s.toCharArray()){\n sf[c-'a']++;\n }\n for(char c:t.toCharArray()){\n tf[c-'a']++;\n }\n for(int i=0;i<26;i++){\n diff+=(int)Math.abs(sf[i]-tf[i]);\n }\n return diff/2;\n }\n}", + "title": "1347. Minimum Number of Steps to Make Two Strings Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings of the same length s and t . In one step you can choose any character of t and replace it with another character . Return the minimum number of steps to make t an anagram of s . An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s.length == t.length", + "s and t consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bab\", t = \"aba\"Output:1Explanation:Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", t = \"practice\"Output:5Explanation:Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"anagram\", t = \"mangaar\"Output:0Explanation:\"anagram\" and \"mangaar\" are anagrams.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n for ch in s:\n\t\t # Find and replace only one occurence of this character in t\n t = t.replace(ch, '', 1)\n \n return len(t)", + "title": "1347. Minimum Number of Steps to Make Two Strings Anagram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings s and t . In one step, you can append any character to either s or t . Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 2 * 10^5", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", t = \"coats\"Output:7Explanation:- In 2 steps, we can append the letters in \"as\" onto s = \"leetcode\", forming s = \"leetcodeas\".\n- In 5 steps, we can append the letters in \"leede\" onto t = \"coats\", forming t = \"coatsleede\".\n\"leetcodeas\" and \"coatsleede\" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"night\", t = \"thing\"Output:0Explanation:The given strings are already anagrams of each other. Thus, we do not need any further steps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 246 ms (Top 18.10%) | Memory: 118.1 MB (Top 5.07%)\nclass Solution {\n public int minSteps(String s, String t) {\n HashMap hmap = new HashMap<>();\n for(char ch:s.toCharArray())\n hmap.put(ch,hmap.getOrDefault(ch,0)+1);\n for(char ch:t.toCharArray())\n hmap.put(ch,hmap.getOrDefault(ch,0)-1);\n int count=0;\n for(char key:hmap.keySet())\n if(hmap.get(key)!=0)\n count+=(Math.abs(hmap.get(key)));\n return count;\n }\n}", + "title": "2186. Minimum Number of Steps to Make Two Strings Anagram II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings s and t . In one step, you can append any character to either s or t . Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 2 * 10^5", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", t = \"coats\"Output:7Explanation:- In 2 steps, we can append the letters in \"as\" onto s = \"leetcode\", forming s = \"leetcodeas\".\n- In 5 steps, we can append the letters in \"leede\" onto t = \"coats\", forming t = \"coatsleede\".\n\"leetcodeas\" and \"coatsleede\" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"night\", t = \"thing\"Output:0Explanation:The given strings are already anagrams of each other. Thus, we do not need any further steps.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n sMap = dict()\n tMap = dict()\n \n for character in s:\n sMap[character] = sMap.get(character, 0) + 1\n \n for character in t:\n tMap[character] = tMap.get(character, 0) + 1\n \n count = 0\n \n for key, value in sMap.items():\n if value >= tMap.get(key, 0):\n count += (value - tMap.get(key, 0))\n \n for key, value in tMap.items():\n if value >= sMap.get(key, 0):\n count += (value - sMap.get(key, 0))\n \n return count\n", + "title": "2186. Minimum Number of Steps to Make Two Strings Anagram II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s , return the minimum number of character swaps to make it alternating , or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not. Any two characters may be swapped, even if they are not adjacent . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"111000\"Output:1Explanation:Swap positions 1 and 4: \"111000\" -> \"101010\"\nThe string is now alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"Output:0Explanation:The string is already alternating, no swaps are needed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwaps(String s) {\n int cntZero=0 , cntOne=0;\n for(char ch:s.toCharArray()){\n if(ch=='0') cntZero++;\n else cntOne++;\n }\n \n //Invalid\n if(Math.abs(cntOne-cntZero)>1) return -1;\n \n \n if(cntOne>cntZero){ //one must be at even posotion\n return countSwaps(s,'1'); \n }else if(cntOne \"101010\"\nThe string is now alternating.", + "image": null + }, + { + "text": "Example 2: Input:s = \"010\"Output:0Explanation:The string is already alternating, no swaps are needed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1110\"Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef minSwaps(self, st: str) -> int:\n \n def swap(st,c):\n n = len(st)\n mis = 0\n for i in range(n):\n if i%2==0 and st[i]!=c:\n mis+=1\n if i%2==1 and st[i]==c:\n mis+=1\n return mis//2\n \n dic = Counter(st)\n z = dic['0']\n o = dic['1']\n res=0\n if abs(z-o)>1:\n return -1\n elif z>o:\n res = swap(st,'0')\n elif o>z:\n res = swap(st,'1')\n else:\n res = min(swap(st,'0'),swap(st,'1'))\n \n return res\n", + "title": "1864. Minimum Number of Swaps to Make the Binary String Alternating", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed string s of even length n . The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']' . A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB , where both A and B are balanced strings, or", + "It can be written as [C] , where C is a balanced string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"][][\"Output:1Explanation:You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"]]][[[\"Output:2Explanation:You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"[]\"Output:0Explanation:The string is already balanced.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 414 ms (Top 6.65%) | Memory: 100.2 MB (Top 5.02%)\nclass Solution {\n public int minSwaps(String s) {\n // remove the balanced part from the given string\n Stack stack = new Stack<>();\n for(char ch : s.toCharArray()) {\n if(ch == '[')\n stack.push(ch);\n else {\n if(!stack.isEmpty() && stack.peek() == '[')\n stack.pop();\n else\n stack.push(ch);\n }\n }\n int unb = stack.size()/2; // # of open or close bracket\n return (unb+1)/2;\n }\n}", + "title": "1963. Minimum Number of Swaps to Make the String Balanced", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed string s of even length n . The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']' . A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is the empty string, or", + "It can be written as AB , where both A and B are balanced strings, or", + "It can be written as [C] , where C is a balanced string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"][][\"Output:1Explanation:You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"]]][[[\"Output:2Explanation:You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"[]\"Output:0Explanation:The string is already balanced.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSwaps(self, s: str) -> int:\n res, bal = 0, 0\n for ch in s:\n bal += 1 if ch == '[' else -1\n if bal == -1:\n res += 1\n bal = 1\n return res\n", + "title": "1963. Minimum Number of Swaps to Make the String Balanced", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n . (i.e The length of the garden is n ). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4", + "ranges.length == n + 1", + "0 <= ranges[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, ranges = [3,4,1,1,0,0]Output:1Explanation:The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]", + "image": "https://assets.leetcode.com/uploads/2020/01/16/1685_example_1.png" + }, + { + "text": "Example 2: Input:n = 3, ranges = [0,0,0,0]Output:-1Explanation:Even if you activate all the four taps you cannot water the whole garden.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 14.75%) | Memory: 49.6 MB (Top 26.03%)\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new);\n Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o]));\n int ans = 1, cur = 0, end = 0;\n for (int i = 0;icur){\n cur=end;\n ans++;\n }\n if (j-ranges[j]<=cur){\n end=Math.max(end, j+ranges[j]);\n }\n }\n return end int:\n max_range = [0] * (n + 1)\n \n for i, r in enumerate(ranges):\n left, right = max(0, i - r), min(n, i + r)\n max_range[left] = max(max_range[left], right - left)\n \n\t\t# it's a jump game now\n start = end = step = 0\n \n while end < n:\n step += 1\n start, end = end, max(i + max_range[i] for i in range(start, end + 1))\n if start == end:\n return -1\n \n return step\n", + "title": "1326. Minimum Number of Taps to Open to Water a Garden", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a directed acyclic graph , with n vertices numbered from 0 to n-1 , and an array edges where edges[i] = [from i , to i ] represents a directed edge from node from i to node to i . Find the smallest set of vertices from which all nodes in the graph are reachable . It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/07/07/untitled22.png", + "https://assets.leetcode.com/uploads/2020/07/07/untitled.png" + ], + "constraints": [ + "2 <= n <= 10^5", + "1 <= edges.length <= min(10^5, n * (n - 1) / 2)", + "edges[i].length == 2", + "0 <= from i, to i < n", + "All pairs (from i , to i ) are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]Output:[0,3]Explanation:It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]Output:[0,2,3]Explanation:Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 43.75%) | Memory: 119 MB (Top 77.96%)\nclass Solution {\n public List findSmallestSetOfVertices(int n, List> edges) {\n\n int[] indegree = new int[n];\n\n for(List edge : edges) {\n indegree[edge.get(1)]++;\n }\n\n List result = new ArrayList<>();\n\n for(int i=0; i List[int]:\n\n\t\tparent=[[] for i in range(n)]\n\t\tfor i in edges:\n\t\t\tparent[i[1]].append(i[0])\n\t\tans=[]\n\t\tfor i in range(n):\n\t\t\tif len(parent[i])==0:\n\t\t\t\tans.append(i)\n\t\treturn ans\n", + "title": "1557. Minimum Number of Vertices to Reach All Nodes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n , where the i th task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime , return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If you start a task in a work session, you must complete it in the same work session.", + "You can start a new task immediately after finishing the previous one.", + "You may complete the tasks in any order ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,3], sessionTime = 3Output:2Explanation:You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [3,1,3,1,1], sessionTime = 8Output:2Explanation:You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [1,2,3,4,5], sessionTime = 15Output:1Explanation:You can finish all the tasks in one work session.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 116 ms (Top 47.58%) | Memory: 73.6 MB (Top 13.54%)\n// Java Solution\nclass Solution {\n public int minSessions(int[] tasks, int sessionTime) {\n int n = tasks.length, MAX = Integer.MAX_VALUE;\n int[][] dp = new int[1< d2[0]) return d2;\n if(d1[0] < d2[0]) return d1;\n if(d1[1] > d2[1]) return d2;\n\n return d1;\n }\n}", + "title": "1986. Minimum Number of Work Sessions to Finish the Tasks", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n , where the i th task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime , return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If you start a task in a work session, you must complete it in the same work session.", + "You can start a new task immediately after finishing the previous one.", + "You may complete the tasks in any order ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,3], sessionTime = 3Output:2Explanation:You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [3,1,3,1,1], sessionTime = 8Output:2Explanation:You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [1,2,3,4,5], sessionTime = 15Output:1Explanation:You can finish all the tasks in one work session.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 966 ms (Top 45.98%) | Memory: 41.80 MB (Top 22.32%)\n\nclass Solution:\n def minSessions(self, tasks, T):\n n = len(tasks)\n\n @lru_cache(None)\n def dp(mask):\n if mask == 0: return (1, 0)\n ans = (float(\"inf\"), float(\"inf\"))\n for j in range(n):\n if mask & (1< T)\n ans = min(ans, (pieces + full, tasks[j] + (1-full)*last)) \n return ans\n\n return dp((1< [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] ->[1, 5](2 operations).\nTotal of operations: 1 + 2 + 2 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2]Output:3Explanation:Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] ->[2, 2](1 operation).\nTotal of operations: 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,5]Output:6Explanation:(initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] ->[4,2,5](nums).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n int odd = 0, even = 0;\n Map map = new HashMap<>();\n for (int n : nums){\n int res = dfs(n, map);\n odd += res >> 5;\n even = Math.max(res & 0b11111, even);\n }\n\n return odd + even;\n }\n\n private int dfs(int n, Map map){\n if (n == 0) return 0;\n if (map.containsKey(n)) return map.get(n);\n\n int res = n % 2 << 5;\n res += dfs(n / 2, map) + (n > 1? 1 : 0);\n\n map.put(n, res);\n return res;\n }\n}\n", + "title": "1558. Minimum Numbers of Function Calls to Make Target Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to covert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr . The test cases are generated so that the answer fits in a 32-bit signed integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5]Output:5Explanation:Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] ->[1, 5](2 operations).\nTotal of operations: 1 + 2 + 2 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2]Output:3Explanation:Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] ->[2, 2](1 operation).\nTotal of operations: 2 + 1 = 3.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,5]Output:6Explanation:(initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] ->[4,2,5](nums).", + "image": null + } + ], + "follow_up": null, + "solution": "# Observe that:\n# +1 places a 1 to the end of the int's binary representation\n# (assuming a 0 there previously)\n# x2 is a bitshift left\n# So you basically just need to count all the ones in the binary representations\n# and find how many shifts are required (largest bit length minus one).\n\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n if max(nums) == 0:\n return 0\n \n return sum([x.bit_count() for x in nums]) + max([x.bit_length() for x in nums]) - 1\n\n", + "title": "1558. Minimum Numbers of Function Calls to Make Target Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array grid of size m x n . Each cell has one of two values: You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 represents an empty cell,", + "1 represents an obstacle that may be removed." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1],[1,1,0],[1,1,0]]Output:2Explanation:We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio-1.png" + }, + { + "text": "Example 2: Input:grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]Output:0Explanation:We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int [][]grid;\n int n,m;\n boolean [][]seen;\n int []dx = new int[]{0,0,1,-1};\n int []dy = new int[]{1,-1,0,0};\n int [][]dp;\n int finalres;\n private boolean isValid(int i, int j) {\n return Math.min(i,j)>=0 && i=finalres) return finalres;\n if(i == n-1 && j == m-1) {\n return cnt;\n }\n if(dp[i][j]!=Integer.MAX_VALUE) return dp[i][j];\n int res = n*m+1;\n seen[i][j]=true;\n for(int k=0;k<4;k++) {\n int newI = i+dx[k], newJ = j+dy[k];\n if(isValid(newI, newJ)) {\n res = Math.min(res, solve(newI, newJ, cnt+grid[i][j]));\n }\n }\n seen[i][j]=false;\n return dp[i][j]=Math.min(dp[i][j], res);\n }\n \n public int minimumObstacles(int[][] grid) {\n this.grid = grid;\n this.n = grid.length;\n this.m = grid[0].length;\n this.seen = new boolean[n][m];\n dp = new int[n][m];\n finalres = n*m+1;\n for(int []row:dp) Arrays.fill(row, Integer.MAX_VALUE);\n return solve(0,0,0);\n }\n}\n", + "title": "2290. Minimum Obstacle Removal to Reach Corner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array grid of size m x n . Each cell has one of two values: You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 represents an empty cell,", + "1 represents an obstacle that may be removed." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1,1],[1,1,0],[1,1,0]]Output:2Explanation:We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio-1.png" + }, + { + "text": "Example 2: Input:grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]Output:0Explanation:We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.", + "image": "https://assets.leetcode.com/uploads/2022/04/06/example1drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 4890 ms (Top 15.42%) | Memory: 42.20 MB (Top 64.95%)\n\nclass Solution:\n def minimumObstacles(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n q = [(0, 0, 0)]\n dist = [[float('inf') for _ in range(n)] for _ in range(m)]\n\n while q:\n size = len(q)\n for _ in range(size):\n obs, x, y = heapq.heappop(q)\n if dist[x][y] < float('inf'): continue\n obs += grid[x][y]\n dist[x][y] = obs\n if x + 1 < m: heapq.heappush(q, (obs, x + 1, y))\n if x > 0: heapq.heappush(q, (obs, x - 1, y))\n if y + 1 < n: heapq.heappush(q, (obs, x, y + 1))\n if y > 0: heapq.heappush(q, (obs, x, y - 1))\n return dist[m - 1][n - 1]\n", + "title": "2290. Minimum Obstacle Removal to Reach Corner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , you must transform it into 0 using the following operations any number of times: Return the minimum number of operations to transform n into 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Change the rightmost ( 0 th ) bit in the binary representation of n .", + "Change the i th bit in the binary representation of n if the (i-1) th bit is set to 1 and the (i-2) th through 0 th bits are set to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:2Explanation:The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2ndoperation since the 0thbit is 1.\n\"01\" -> \"00\" with the 1stoperation.", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:4Explanation:The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2ndoperation since the 1stbit is 1 and 0ththrough 0thbits are 0.\n\"010\" -> \"011\" with the 1stoperation.\n\"011\" -> \"001\" with the 2ndoperation since the 0thbit is 1.\n\"001\" -> \"000\" with the 1stoperation.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 52 ms (Top 5.71%) | Memory: 41.9 MB (Top 21.90%)\nclass Solution {\n public int minimumOneBitOperations(int n) {\n\n int inv = 0;\n\n // xor until n becomes zero\n for ( ; n != 0 ; n = n >> 1){\n\n inv ^= n;\n System.out.println(inv+\" \"+n);\n }\n\n return inv;\n }\n}", + "title": "1611. Minimum One Bit Operations to Make Integers Zero", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , you must transform it into 0 using the following operations any number of times: Return the minimum number of operations to transform n into 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Change the rightmost ( 0 th ) bit in the binary representation of n .", + "Change the i th bit in the binary representation of n if the (i-1) th bit is set to 1 and the (i-2) th through 0 th bits are set to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:2Explanation:The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2ndoperation since the 0thbit is 1.\n\"01\" -> \"00\" with the 1stoperation.", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:4Explanation:The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2ndoperation since the 1stbit is 1 and 0ththrough 0thbits are 0.\n\"010\" -> \"011\" with the 1stoperation.\n\"011\" -> \"001\" with the 2ndoperation since the 0thbit is 1.\n\"001\" -> \"000\" with the 1stoperation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n if n <= 1:\n return n\n def leftmostbit(x):\n x |= x >> 1\n x |= x >> 2\n x |= x >> 4\n x |= x >> 8\n x |= x >> 16\n x += 1\n x >>= 1\n return x\n x = leftmostbit(n)\n return ((x << 1) - 1) - self.minimumOneBitOperations(n - x)\n", + "title": "1611. Minimum One Bit Operations to Make Integers Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums containing distinct numbers, an integer start , and an integer goal . There is an integer x that is initially set to start , and you want to perform operations on x such that it is converted to goal . You can perform the following operation repeatedly on the number x : If 0 <= x <= 1000 , then for any index i in the array ( 0 <= i < nums.length ), you can set x to any of the following: Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal , and -1 if it is not possible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x + nums[i]", + "x - nums[i]", + "x ^ nums[i] (bitwise-XOR)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,12], start = 2, goal = 12Output:2Explanation:We can go from 2 → 14 → 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,7], start = 0, goal = -4Output:2Explanation:We can go from 0 → 3 → -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,8,16], start = 0, goal = 1Output:-1Explanation:There is no way to convert 0 into 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 907 ms (Top 10.13%) | Memory: 306.2 MB (Top 27.03%)\nclass Solution {\n public int minimumOperations(int[] nums, int start, int goal) {\n int res = 0;\n Queue q = new LinkedList<>();\n Set set = new HashSet<>();\n q.offer(start);\n\n while(!q.isEmpty()){\n int size = q.size();\n\n for(int i = 0;i 1000) || set.contains(val))continue;\n if(!set.contains(val))set.add(val);\n\n for(int num : nums){\n q.offer(val + num);\n q.offer(val - num);\n q.offer(val ^ num);\n }\n }\n res++;\n }\n\n return -1;\n }\n}\n", + "title": "2059. Minimum Operations to Convert Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums containing distinct numbers, an integer start , and an integer goal . There is an integer x that is initially set to start , and you want to perform operations on x such that it is converted to goal . You can perform the following operation repeatedly on the number x : If 0 <= x <= 1000 , then for any index i in the array ( 0 <= i < nums.length ), you can set x to any of the following: Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert x = start into goal , and -1 if it is not possible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "x + nums[i]", + "x - nums[i]", + "x ^ nums[i] (bitwise-XOR)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,4,12], start = 2, goal = 12Output:2Explanation:We can go from 2 → 14 → 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,5,7], start = 0, goal = -4Output:2Explanation:We can go from 0 → 3 → -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,8,16], start = 0, goal = 1Output:-1Explanation:There is no way to convert 0 into 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4131 ms (Top 24.3%) | Memory: 185.60 MB (Top 35.5%)\n\nclass Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n ans = 0\n seen = {start}\n queue = deque([start])\n while queue: \n for _ in range(len(queue)): \n val = queue.popleft()\n if val == goal: return ans \n if 0 <= val <= 1000: \n for x in nums: \n for op in (add, sub, xor): \n if op(val, x) not in seen: \n seen.add(op(val, x))\n queue.append(op(val, x))\n ans += 1\n return -1 ", + "title": "2059. Minimum Operations to Convert Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,19,8,1]Output:3Explanation:The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,20]Output:3Explanation:The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 392 ms (Top 56.62%) | Memory: 107.3 MB (Top 79.45%)\nclass Solution {\n public int halveArray(int[] nums) {\n PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder());\n double sum=0;\n for(int i:nums){\n sum+=(double)i;\n q.add((double)i);\n }\n int res=0;\n double req = sum;\n while(sum > req/2){\n double curr = q.poll();\n q.add(curr/2);\n res++;\n sum -= curr/2;\n }\n return res;\n }\n}", + "title": "2208. Minimum Operations to Halve Array Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,19,8,1]Output:3Explanation:The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,8,20]Output:3Explanation:The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def halveArray(self, nums: List[int]) -> int:\n # Creating empty heap\n maxHeap = []\n heapify(maxHeap) # Creates minHeap \n \n totalSum = 0\n for i in nums:\n # Adding items to the heap using heappush\n # for maxHeap, function by multiplying them with -1\n heappush(maxHeap, -1*i) \n totalSum += i\n \n requiredSum = totalSum / 2\n minOps = 0\n \n while totalSum > requiredSum:\n x = -1*heappop(maxHeap) # Got negative value make it positive\n x /= 2\n totalSum -= x\n heappush(maxHeap, -1*x) \n minOps += 1\n \n return minOps\n", + "title": "2208. Minimum Operations to Halve Array Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr . For example, if arr = [1,4,1,2] , you can add 3 in the middle and make it [1,4, 3 ,1,2] . Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr . 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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= target.length, arr.length <= 10^5", + "1 <= target[i], arr[i] <= 10^9", + "target contains no duplicates." + ], + "examples": [ + { + "text": "Example 1: Input:target = [5,1,3],arr= [9,4,2,3,4]Output:2Explanation:You can add 5 and 1 in such a way that makesarr= [5,9,4,1,2,3,4], then target will be a subsequence ofarr.", + "image": null + }, + { + "text": "Example 2: Input:target = [6,4,8,1,3,2],arr= [4,7,6,2,3,8,6,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 85.00%) | Memory: 59.9 MB (Top 96.25%)\nclass Solution {\n public int minOperations(int[] target, int[] arr) {\n int n = target.length;\n Map map = new HashMap<>();\n\n for(int i = 0; i < n; i++) {\n map.put(target[i], i);\n }\n\n List array = new ArrayList<>();\n\n for(int i = 0; i < arr.length; i++) {\n if(!map.containsKey(arr[i])) {\n continue;\n }\n\n array.add(map.get(arr[i]));\n }\n\n int maxLen = 0;\n int[] tails = new int[n + 1];\n\n for(int i = 0; i < n; i++) {\n tails[i] = -1;\n }\n\n for(int num: array) {\n int index = findMinIndex(tails, maxLen, num);\n\n if(tails[index] == -1) {\n maxLen++;\n }\n tails[index] = num;\n }\n\n return n - maxLen;\n }\n\n public int findMinIndex(int[] tails, int n, int val) {\n int low = 0;\n int ans = n;\n int high = n - 1;\n\n while(low <= high) {\n int mid = (high + low) / 2;\n\n if(tails[mid] >= val) {\n ans = mid;\n high = mid - 1;\n }\n else {\n low = mid + 1;\n }\n }\n return ans;\n }\n}", + "title": "1713. Minimum Operations to Make a Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr . For example, if arr = [1,4,1,2] , you can add 3 in the middle and make it [1,4, 3 ,1,2] . Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr . 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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= target.length, arr.length <= 10^5", + "1 <= target[i], arr[i] <= 10^9", + "target contains no duplicates." + ], + "examples": [ + { + "text": "Example 1: Input:target = [5,1,3],arr= [9,4,2,3,4]Output:2Explanation:You can add 5 and 1 in such a way that makesarr= [5,9,4,1,2,3,4], then target will be a subsequence ofarr.", + "image": null + }, + { + "text": "Example 2: Input:target = [6,4,8,1,3,2],arr= [4,7,6,2,3,8,6,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 962 ms (Top 100.00%) | Memory: 36.9 MB (Top 93.24%)\nfrom bisect import bisect_left\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n dt = {num: i for i, num in enumerate(target)}\n stack = []\n for num in arr:\n if num not in dt: continue\n i = bisect_left(stack, dt[num])\n if i == len(stack):\n stack.append(dt[num])\n else:\n stack[i] = dt[num]\n return len(target) - len(stack)", + "title": "1713. Minimum Operations to Make a Subsequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 2D integer grid of size m x n and an integer x . In one operation, you can add x to or subtract x from any element in the grid . A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value . If it is not possible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 10^5", + "1 <= x, grid[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4],[6,8]], x = 2Output:4Explanation:We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" + }, + { + "text": "Example 2: Input:grid = [[1,5],[2,3]], x = 1Output:5Explanation:We can make every element equal to 3.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[3,4]], x = 2Output:-1Explanation:It is impossible to make every element equal.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[][] grid, int x) {\n int[] arr = new int[grid.length * grid[0].length];\n int index = 0;\n \n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n arr[index++] = grid[i][j];\n }\n }\n \n Arrays.sort(arr);\n int median = arr[(arr.length - 1) / 2];\n int steps = 0;\n \n for (int num : arr) {\n if (num == median) {\n continue;\n }\n \n if (Math.abs(num - median) % x != 0) {\n return -1;\n }\n \n steps += (Math.abs(num - median) / x);\n }\n \n return steps;\n }\n}\n", + "title": "2033. Minimum Operations to Make a Uni-Value Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer grid of size m x n and an integer x . In one operation, you can add x to or subtract x from any element in the grid . A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value . If it is not possible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 10^5", + "1 <= x, grid[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,4],[6,8]], x = 2Output:4Explanation:We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt.png" + }, + { + "text": "Example 2: Input:grid = [[1,5],[2,3]], x = 1Output:5Explanation:We can make every element equal to 3.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-1.png" + }, + { + "text": "Example 3: Input:grid = [[1,2],[3,4]], x = 2Output:-1Explanation:It is impossible to make every element equal.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/gridtxt-2.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n \n m = len(grid)\n n = len(grid[0])\n\t\t\n\t\t# handle the edge case\n if m==1 and n==1: return 0\n\t\t\n\t\t# transform grid to array, easier to operate\n arr = [] \n for i in range(m):\n arr+=grid[i]\n \n arr.sort()\n \n\t\t# the median is arr[len(arr)//2] when len(arr) is odd\n\t\t# or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even.\n cand1 = arr[len(arr)//2]\n cand2 = arr[len(arr)//2-1]\n \n return min(\n self.get_num_operations_to_target(grid, cand1, x),\n self.get_num_operations_to_target(grid, cand2, x)\n )\n \n \n def get_num_operations_to_target(self, grid, target,x):\n\t\t\"\"\"Get the total number of operations to transform all grid elements to the target value.\"\"\"\n ans = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if abs(grid[i][j]-target)%x!=0:\n return -1\n else:\n ans+=abs(grid[i][j]-target)//x\n\n return ans\n \n", + "title": "2033. Minimum Operations to Make a Uni-Value Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n ). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1 ). The goal is to make all the elements of the array equal . It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n , the length of the array, return the minimum number of operations needed to make all the elements of arr equal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:2Explanation:arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int n) {\n int ans = (n/2)*(n/2);\n if(n%2==1){\n ans += n/2;\n }\n return ans;\n }\n}", + "title": "1551. Minimum Operations to Make Array Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n ). In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1 ). The goal is to make all the elements of the array equal . It is guaranteed that all the elements of the array can be made equal using some operations. Given an integer n , the length of the array, return the minimum number of operations needed to make all the elements of arr equal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:2Explanation:arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].", + "image": null + }, + { + "text": "Example 2: Input:n = 6Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, n: int) -> int:\n\n return sum([n-x for x in range(n) if x % 2 != 0])", + "title": "1551. Minimum Operations to Make Array Equal", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation , you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums[i - 2] == nums[i] , where 2 <= i <= n - 1 .", + "nums[i - 1] != nums[i] , where 1 <= i <= n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,3,2,4,3]Output:3Explanation:One way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,2]Output:2Explanation:One way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumOperations(int[] nums) {\n int freq[][] = new int[100005][2];\n int i, j, k, ans=0;\n for(i = 0; i < nums.length; i++) {\n \t\t\tfreq[nums[i]][i&1]++;\n \t\t}\n \t\t\n \t\tfor(i = 1, j=k=0; i <= 100000; i++) {\n\t\t\t// Add the maximum frequency of odd indexes to maximum frequency even indexes \n\t\t //and vice versa, it will give us how many elements we don't need to change. \n \t\tans = Math.max(ans, Math.max(freq[i][0] + k, freq[i][1] + j));\n j = Math.max(j, freq[i][0]);\n k = Math.max(k, freq[i][1]);\n }\n return nums.length - ans;\n }\n}\n", + "title": "2170. Minimum Operations to Make the Array Alternating", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation , you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums[i - 2] == nums[i] , where 2 <= i <= n - 1 .", + "nums[i - 1] != nums[i] , where 1 <= i <= n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,3,2,4,3]Output:3Explanation:One way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,2]Output:2Explanation:One way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3233 ms (Top 5.15%) | Memory: 31.6 MB (Top 46.98%)\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n n = len(nums)\n odd, even = defaultdict(int), defaultdict(int)\n for i in range(n):\n if i % 2 == 0:\n even[nums[i]] += 1\n else:\n odd[nums[i]] += 1\n topEven, secondEven = (None, 0), (None, 0)\n for num in even:\n if even[num] > topEven[1]:\n topEven, secondEven = (num, even[num]), topEven\n elif even[num] > secondEven[1]:\n secondEven = (num, even[num])\n topOdd, secondOdd = (None, 0), (None, 0)\n for num in odd:\n if odd[num] > topOdd[1]:\n topOdd, secondOdd = (num, odd[num]), topOdd\n elif odd[num] > secondOdd[1]:\n secondOdd = (num, odd[num])\n if topOdd[0] != topEven[0]:\n return n - topOdd[1] - topEven[1]\n else:\n return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])", + "title": "2170. Minimum Operations to Make the Array Alternating", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums ( 0-indexed ). In one operation, you can choose an element of the array and increment it by 1 . Return the minimum number of operations needed to make nums strictly increasing . An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1 . An array of length 1 is trivially strictly increasing. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if nums = [1,2,3] , you can choose to increment nums[1] to make nums = [1, 3 ,3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]Output:3Explanation:You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,2,4,1]Output:14", + "image": null + }, + { + "text": "Example 3: Input:nums = [8]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums) {\n if (nums.length <= 1) {\n return 0;\n }\n\n int count = 0;\n int num = nums[0];\n for (int i = 1; i < nums.length; i++) {\n if (num == nums[i]) {\n count++;\n num++;\n } else if (num > nums[i]) {\n num++;\n count += num - nums[i];\n } else {\n num = nums[i];\n }\n }\n \n return count;\n }\n}\n", + "title": "1827. Minimum Operations to Make the Array Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums ( 0-indexed ). In one operation, you can choose an element of the array and increment it by 1 . Return the minimum number of operations needed to make nums strictly increasing . An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1 . An array of length 1 is trivially strictly increasing. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if nums = [1,2,3] , you can choose to increment nums[1] to make nums = [1, 3 ,3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]Output:3Explanation:You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,2,4,1]Output:14", + "image": null + }, + { + "text": "Example 3: Input:nums = [8]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n sol = 0\n last = nums[0]\n\n for i in range(len(nums) - 1):\n if last >= nums[i + 1]:\n sol += last - nums[i + 1] + 1\n last = last + 1\n else:\n last = nums[i + 1]\n \n return sol", + "title": "1827. Minimum Operations to Make the Array Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k . The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i , where k <= i <= n-1 . In one operation , you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2)", + "arr[0] <= arr[2] (4 <= 5)", + "arr[1] <= arr[3] (1 <= 2)", + "arr[2] <= arr[4] (5 <= 6)", + "arr[3] <= arr[5] (2 <= 2)", + "However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1] ) or k = 3 (because arr[0] > arr[3] )." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,4,3,2,1], k = 1Output:4Explanation:For k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,1,5,2,6,2], k = 2Output:0Explanation:This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <=arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,1,5,2,6,2], k = 3Output:2Explanation:Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int kIncreasing(int[] arr, int k) {\n int ans = arr.length;\n int[] tails = new int[arr.length];\n for (int i = 0; i < k; i ++) {\n int size = 0;\n for (int j = i; j < arr.length; j += k) {\n if (size == 0 || arr[j] >= tails[size - 1]) {\n tails[size ++] = arr[j];\n } else {\n int low = 0, high = size - 1;\n while (low <= high) {\n int mid = (low + high) / 2;\n if (tails[mid] <= arr[j] && tails[mid + 1] > arr[j]) {\n tails[mid + 1] = arr[j];\n break;\n } else if (tails[mid + 1] <= arr[j]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n if (low > high) {\n tails[0] = arr[j];\n }\n }\n }\n ans -= size;\n }\n return ans;\n }\n}\n", + "title": "2111. Minimum Operations to Make the Array K-Increasing", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k . The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i , where k <= i <= n-1 . In one operation , you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] <= arr[2] (4 <= 5) arr[1] <= arr[3] (1 <= 2) arr[2] <= arr[4] (5 <= 6) arr[3] <= arr[5] (2 <= 2)", + "arr[0] <= arr[2] (4 <= 5)", + "arr[1] <= arr[3] (1 <= 2)", + "arr[2] <= arr[4] (5 <= 6)", + "arr[3] <= arr[5] (2 <= 2)", + "However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1] ) or k = 3 (because arr[0] > arr[3] )." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [5,4,3,2,1], k = 1Output:4Explanation:For k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,1,5,2,6,2], k = 2Output:0Explanation:This is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <=arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.", + "image": null + }, + { + "text": "Example 3: Input:arr = [4,1,5,2,6,2], k = 3Output:2Explanation:Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def kIncreasing(self, arr: List[int], k: int) -> int:\n def LNDS(arr: List[int]) -> int:\n mono = []\n for n in arr:\n if not mono or mono[-1] <= n:\n mono.append(n)\n else:\n mono[bisect_right(mono, n)] = n\n return len(mono) \n return len(arr) - sum(LNDS(arr[i::k]) for i in range(k))\n", + "title": "2111. Minimum Operations to Make the Array K-Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer x . In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x . Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible , otherwise, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4", + "1 <= x <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,4,2,3], x = 5Output:2Explanation:The optimal solution is to remove the last two elements to reduce x to zero.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,7,8,9], x = 4Output:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,20,1,1,3], x = 10Output:5Explanation:The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 825 ms (Top 92.58%) | Memory: 31.60 MB (Top 21.29%)\n\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n target, n = sum(nums) - x, len(nums)\n \n if target == 0:\n return n\n \n max_len = cur_sum = left = 0\n \n for right, val in enumerate(nums):\n cur_sum += val\n while left <= right and cur_sum > target:\n cur_sum -= nums[left]\n left += 1\n if cur_sum == target:\n max_len = max(max_len, right - left + 1)\n \n return n - max_len if max_len else -1\n", + "title": "1658. Minimum Operations to Reduce X to Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1 . You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1 , you can move to any of the cells (x + 1, 0) , (x + 1, 1) , ..., (x + 1, n - 1) . Note that it is not possible to move from cells in the last row. Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n , where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "2 <= m, n <= 50", + "grid consists of distinct integers from 0 to m * n - 1 .", + "moveCost.length == m * n", + "moveCost[i].length == n", + "1 <= moveCost[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]Output:17Explanation:The path with the minimum possible cost is the path 5 -> 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.", + "image": "https://assets.leetcode.com/uploads/2022/04/28/griddrawio-2.png" + }, + { + "text": "Example 2: Input:grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]Output:6Explanation:The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer dp[][];\n public int minPathCost(int[][] grid, int[][] moveCost) \n {\n dp=new Integer[grid.length][grid[0].length];\n int ans=Integer.MAX_VALUE;\n \n for(int i=0;i 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.", + "image": "https://assets.leetcode.com/uploads/2022/04/28/griddrawio-2.png" + }, + { + "text": "Example 2: Input:grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]Output:6Explanation:The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n max_row, max_col = len(grid), len(grid[0])\n dp = [[-1] * max_col for _ in range(max_row)] \n\n def recursion(row, col):\n if row == max_row - 1: # If last row then return nodes value\n return grid[row][col]\n if dp[row][col] == -1: # If DP for this node is not computed then we will do so now.\n current = grid[row][col] # Current Node Value\n res = float('inf') # To store best path from Current Node\n for c in range(max_col): # Traverse all path from Current Node\n val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value\n res = min(res, val)\n dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val\n return dp[row][col]\n\n for c in range(max_col):\n recursion(0, c) # Start recursion from all nodes in 1st row\n return min(dp[0]) # Return min value from 1st row\n", + "title": "2304. Minimum Path Cost in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 200", + "0 <= grid[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,3,1],[1,5,1],[4,2,1]]Output:7Explanation:Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6]]Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 89.53%) | Memory: 45.9 MB (Top 59.56%)\nclass Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[] dp = new int[n];\n dp[0] = grid[0][0];\n\n for(int i=1;i int:\n prev=[0]*len(grid[0])\n for i in range(len(grid)):\n temp=[0]*len(grid[0])\n for j in range(len(grid[0])):\n if i==0 and j==0:\n temp[j]=grid[i][j]\n continue\n if i>0:\n lft=grid[i][j]+prev[j]\n else:\n lft=grid[i][j]+1000\n if j>0:\n up=grid[i][j]+temp[j-1]\n else:\n up=grid[i][j]+1000\n temp[j]=min(up,lft)\n prev=temp\n return prev[-1]\n \n \n", + "title": "64. Minimum Path Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string num representing the digits of a very large integer and an integer k . You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3 * 10^4", + "num consists of only digits and does not contain leading zeros .", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"4321\", k = 4Output:\"1342\"Explanation:The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" + }, + { + "text": "Example 2: Input:num = \"100\", k = 1Output:\"010\"Explanation:It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.", + "image": null + }, + { + "text": "Example 3: Input:num = \"36789\", k = 1000Output:\"36789\"Explanation:We can keep the number without any swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 194 ms (Top 80.8%) | Memory: 52.65 MB (Top 6.3%)\n\nclass Solution {\n public String minInteger(String num, int k) {\n //pqs stores the location of each digit.\n List> pqs = new ArrayList<>();\n for (int i = 0; i <= 9; ++i) {\n pqs.add(new LinkedList<>());\n }\n\n for (int i = 0; i < num.length(); ++i) {\n pqs.get(num.charAt(i) - '0').add(i);\n }\n String ans = \"\";\n SegmentTree seg = new SegmentTree(num.length());\n\n for (int i = 0; i < num.length(); ++i) {\n // At each location, try to place 0....9\n for (int digit = 0; digit <= 9; ++digit) {\n // is there any occurrence of digit left?\n if (pqs.get(digit).size() != 0) {\n // yes, there is a occurrence of digit at pos\n Integer pos = pqs.get(digit).peek();\n\t\t\t\t\t// Since few numbers already shifted to left, this `pos` might be outdated.\n // we try to find how many number already got shifted that were to the left of pos.\n int shift = seg.getCountLessThan(pos);\n // (pos - shift) is number of steps to make digit move from pos to i.\n if (pos - shift <= k) {\n k -= pos - shift;\n seg.add(pos); // Add pos to our segment tree.\n pqs.get(digit).remove();\n ans += digit;\n break;\n }\n }\n }\n }\n return ans;\n }\n\n class SegmentTree {\n int[] nodes;\n int n;\n\n public SegmentTree(int max) {\n nodes = new int[4 * (max)];\n n = max;\n }\n\n public void add(int num) {\n addUtil(num, 0, n, 0);\n }\n\n private void addUtil(int num, int l, int r, int node) {\n if (num < l || num > r) {\n return;\n }\n if (l == r) {\n nodes[node]++;\n return;\n }\n int mid = (l + r) / 2;\n addUtil(num, l, mid, 2 * node + 1);\n addUtil(num, mid + 1, r, 2 * node + 2);\n nodes[node] = nodes[2 * node + 1] + nodes[2 * node + 2];\n }\n\n // Essentialy it tells count of numbers < num.\n public int getCountLessThan(int num) {\n return getUtil(0, num, 0, n, 0);\n }\n\n private int getUtil(int ql, int qr, int l, int r, int node) {\n if (qr < l || ql > r) return 0;\n if (ql <= l && qr >= r) {\n return nodes[node];\n }\n\n int mid = (l + r) / 2;\n return getUtil(ql, qr, l, mid, 2 * node + 1) + getUtil(ql, qr, mid + 1, r, 2 * node + 2);\n }\n }\n\n}", + "title": "1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string num representing the digits of a very large integer and an integer k . You are allowed to swap any two adjacent digits of the integer at most k times. Return the minimum integer you can obtain also as a string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3 * 10^4", + "num consists of only digits and does not contain leading zeros .", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:num = \"4321\", k = 4Output:\"1342\"Explanation:The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.", + "image": "https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" + }, + { + "text": "Example 2: Input:num = \"100\", k = 1Output:\"010\"Explanation:It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.", + "image": null + }, + { + "text": "Example 3: Input:num = \"36789\", k = 1000Output:\"36789\"Explanation:We can keep the number without any swaps.", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\n\nclass Solution:\n def minInteger(self, num: str, k: int) -> str:\n sz, window = len(num), SortedList()\n remainedIndices, poppedIndices = SortedList(range(sz)), []\n while k > 0:\n while len(window) < k + 1 and len(window) < len(remainedIndices):\n idx = remainedIndices[len(window)]\n window.add((num[idx], idx))\n if not window:\n break\n index = window.pop(0)[1]\n k -= remainedIndices.bisect_left(index)\n remainedIndices.remove(index)\n poppedIndices.append(index)\n for idx in remainedIndices[k + 1: len(window)]:\n window.remove((num[idx], idx))\n poppedSet = set(poppedIndices)\n return \"\".join(num[idx] for idx in poppedIndices) + \"\".join(num[idx] for idx in range(sz) if idx not in poppedSet)", + "title": "1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')' , in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It is the empty string, contains only lowercase characters, or", + "It can be written as AB ( A concatenated with B ), where A and B are valid strings, or", + "It can be written as (A) , where A is a valid string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"lee(t(c)o)de)\"Output:\"lee(t(c)o)de\"Explanation:\"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a)b(c)d\"Output:\"ab(c)d\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"))((\"Output:\"\"Explanation:An empty string is also valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 47 ms (Top 39.96%) | Memory: 42.9 MB (Top 93.77%)\nclass Solution {\n public String minRemoveToMakeValid(String s) {\n Stack stack = new Stack<>();\n for(int i=0;i set = new HashSet<>(stack);\n for(int i=0;i= 0; i--){\n if(nums[i] <= last){\n last = nums[i];\n continue;\n }\n if(nums[i] % last == 0){\n // split into nums[i] / last elements, operations cnt = nums[i] / last - 1;\n ret += nums[i] / last - 1;\n }else{\n // split into k elements operations cnt = k - 1;\n int k = nums[i] / last + 1; // ceil\n ret += k - 1;\n last = nums[i] / k; // left most element max is nums[i] / k\n }\n\n }\n\n return ret;\n }\n\n}", + "title": "2366. Minimum Replacements to Sort the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one operation you can replace any element of the array with any two elements that sum to it. Return the minimum number of operations to make an array that is sorted in non-decreasing order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, consider nums = [5,6,7] . In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,9,3]Output:2Explanation:Here are the steps to sort the array in non-decreasing order:\n- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]\n- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]\nThere are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5]Output:0Explanation:The array is already in non-decreasing order. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumReplacement(self, nums) -> int:\n ans = 0\n n = len(nums)\n curr = nums[-1]\n for i in range(n - 2, -1, -1):\n if nums[i] > curr:\n q = nums[i] // curr\n if nums[i] == curr * q:\n nums[i] = curr\n ans += q - 1\n else:\n nums[i] = nums[i] // (q + 1)\n ans += q\n curr = nums[i]\n return ans\n", + "title": "2366. Minimum Replacements to Sort the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array tasks , where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level . Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^5", + "1 <= tasks[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [2,2,3,3,2,4,4,4,4,4]Output:4Explanation:To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [2,3,3]Output:-1Explanation:There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n\tEach round, we can complete either 2 or 3 tasks of the same difficulty level\n Time: O(n)\n Space: O(n)\n*/\nclass Solution {\n public int minimumRounds(int[] tasks) {\n int round = 0;\n Map taskMap = new HashMap<>(); // map of \n for (int i = 0; i < tasks.length; i++) {\n taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);\n }\n \n for (Map.Entry entry : taskMap.entrySet()) {\n if (entry.getValue() == 1) {\n return -1; // we cannot complete if there is only 1 task\n }\n\t\t\t// try to take as many 3's as possible\n round += entry.getValue() / 3; \n\t\t\t\n /*\n\t\t\t\tWe can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous\n\t\t\t\tex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]\n\t\t\t\tIn this example, treat the last [5,5,5], [5] as [5,5], [5,5]\n */\n if (entry.getValue() % 3 != 0) { \n round++; \n }\n }\n return round;\n }\n}", + "title": "2244. Minimum Rounds to Complete All Tasks", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array tasks , where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level . Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^5", + "1 <= tasks[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [2,2,3,3,2,4,4,4,4,4]Output:4Explanation:To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [2,3,3]Output:-1Explanation:There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumRounds(self, tasks: List[int]) -> int:\n dic={}\n c=0\n for i in tasks:\n if i in dic.keys():\n dic[i]+=1\n else:\n dic[i]=1\n for i in dic.keys():\n if dic[i]==1:\n return -1\n while dic[i]>=2:\n if dic[i]-3>1:\n dic[i]-=3\n c+=1\n else:\n dic[i]-=2\n c+=1\n return c", + "title": "2244. Minimum Rounds to Complete All Tasks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the i th node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Return the minimum score of any possible pair of edge removals on the given tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, say the three components have the node values: [4,5,7] , [1,9] , and [3,3,3] . The three XOR values are 4 ^ 5 ^ 7 = 6 , 1 ^ 9 = 8 , and 3 ^ 3 ^ 3 = 3 . The largest XOR value is 8 and the smallest XOR value is 3 . The score is then 8 - 3 = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]Output:9Explanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2ndcomponent has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rdcomponent has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]Output:0Explanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2ndcomponent has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rdcomponent has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int minimumScore(int[] nums, int[][] edges) {\n \n // 1.) Compute the adjacency table. Contains all paths, (including to root, must be filtered out later).\n Map> adjGraph = computeAdjGraph(edges);\n \n // 2.) Know compute the total Xors of each node DFS style.\n Map xorMap = new HashMap<>();\n computeNodeXorDfs(0, -1, nums, xorMap, adjGraph);\n int rootXor = xorMap.get(0);\n \n // 3.) Before computing all XORs in O(N^2) fashion, we want to compute a list of nodes of ascendant, descendant relationships.\n // Here we have to chose a SET instead of a list -> else we will run into TLS, obviously there are some duplicates.\n Map> descendants = new HashMap<>();\n Set rootChildren = computeDescendants(0, -1, descendants, adjGraph);\n \n // 4.) We can check now the parent <-> child relationships. \n // Compute each node under the root (not the root itself) for the following conditions:\n // node_i is parent of node_j\n // rootXor = total ^ node_i (removing node_i from total)\n // xor1 = node_i^ node_j (removing node_j from node_i)\n // xor2 = node_j\n // node_j is parent of node_i\n // rootXor = total ^ node_j (removing node_j from total)\n // xor1 = node_j^ node_i (removing node_i from node_j)\n // xor2 = node_i\n // node_j & node_i belong to different parents.\n // rootXor = total ^ node_j^ nodE_i (removing node_i & node_j from total)\n // xor1 = node_i\n // xor2 = node_j\n \n int minScore = Integer.MAX_VALUE;\n \n for(int i = 1; i < adjGraph.keySet().size(); i++){\n for(int j = i+1; j < adjGraph.keySet().size(); j++){\n // Is node_i parent of node_j\n if(descendants.get(i).contains(j)){\n int rootXor1 = rootXor ^ xorMap.get(i);\n int xor1 = xorMap.get(i) ^ xorMap.get(j);\n int xor2 = xorMap.get(j);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n } else if(descendants.get(j).contains(i)){\n int rootXor1 = rootXor ^ xorMap.get(j);\n int xor1 = xorMap.get(j) ^ xorMap.get(i);\n int xor2 = xorMap.get(i);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n } else {\n int rootXor1 = rootXor ^ (xorMap.get(i) ^ xorMap.get(j));\n int xor1 = xorMap.get(i);\n int xor2 = xorMap.get(j);\n int maxValue = Math.max(rootXor1, Math.max(xor1, xor2));\n int minValue = Math.min(rootXor1, Math.min(xor1, xor2));\n minScore = Math.min(minScore, maxValue - minValue);\n }\n }\n }\n \n \n return minScore;\n }\n \n Set computeDescendants(int src, int parent, Map> descendants, Map> adjGraph){\n \n Set childrenOfNode = new HashSet<>();\n \n for(int child : adjGraph.get(src)){\n if(child != parent){\n // add the child node\n childrenOfNode.add(child);\n // add all its children.\n childrenOfNode.addAll(computeDescendants(child, src, descendants, adjGraph));\n } \n }\n \n descendants.put(src, childrenOfNode);\n return childrenOfNode;\n }\n \n int computeNodeXorDfs(int src, int parent, int[] nums, Map xorMap, Map> adjGraph){\n \n int srcXor = nums[src];\n \n for(int child : adjGraph.get(src)){\n if(child != parent)\n srcXor ^= computeNodeXorDfs(child, src, nums, xorMap, adjGraph);\n }\n \n xorMap.put(src, srcXor);\n return srcXor;\n }\n \n Map> computeAdjGraph(int[][] edges){\n \n Map> adjGraph = new HashMap<>();\n \n for(int[] edge : edges){\n int v1 = edge[0];\n int v2 = edge[1];\n \n if(!adjGraph.containsKey(v1)){\n adjGraph.put(v1, new ArrayList<>());\n }\n \n if(!adjGraph.containsKey(v2)){\n adjGraph.put(v2, new ArrayList<>());\n }\n adjGraph.get(v1).add(v2);\n adjGraph.get(v2).add(v1);\n }\n return adjGraph;\n }\n}\n", + "title": "2322. Minimum Score After Removals on a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the i th node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: Return the minimum score of any possible pair of edge removals on the given tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, say the three components have the node values: [4,5,7] , [1,9] , and [3,3,3] . The three XOR values are 4 ^ 5 ^ 7 = 6 , 1 ^ 9 = 8 , and 3 ^ 3 ^ 3 = 3 . The largest XOR value is 8 and the smallest XOR value is 3 . The score is then 8 - 3 = 5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]Output:9Explanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2ndcomponent has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rdcomponent has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex1drawio.png" + }, + { + "text": "Example 2: Input:nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]Output:0Explanation:The diagram above shows a way to make a pair of removals.\n- The 1stcomponent has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2ndcomponent has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rdcomponent has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.", + "image": "https://assets.leetcode.com/uploads/2022/05/03/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1682 ms (Top 100.0%) | Memory: 18.40 MB (Top 71.7%)\n\nclass Solution:\n def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: \n n = len(nums)\n graph = [[] for _ in range(n)]\n for u, v in edges: \n graph[u].append(v)\n graph[v].append(u)\n \n def fn(u, p): \n nonlocal t\n score[u] = nums[u]\n tin[u] = (t := t+1) # time to enter\n for v in graph[u]: \n if v != p: \n fn(v, u)\n score[u] ^= score[v]\n tout[u] = t # time to exit \n \n t = 0 \n score = [0]*n\n tin = [0]*n \n tout = [0]*n \n fn(0, -1)\n \n ans = inf \n for u in range(1, n): \n for v in range(u+1, n): \n if tin[v] <= tin[u] and tout[v] >= tout[u]: # enter earlier & exit later == parent \n uu = score[u]\n vv = score[v] ^ score[u]\n xx = score[0] ^ score[v]\n elif tin[v] >= tin[u] and tout[v] <= tout[u]: \n uu = score[u] ^ score[v]\n vv = score[v]\n xx = score[0] ^ score[u]\n else: \n uu = score[u]\n vv = score[v]\n xx = score[0] ^ score[u] ^ score[v]\n ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))\n return ans ", + "title": "2322. Minimum Score After Removals on a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a convex n -sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the i th vertex (i.e., clockwise order ). You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == values.length", + "3 <= n <= 50", + "1 <= values[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3]Output:6Explanation:The polygon is already triangulated, and the score of the only triangle is 6.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape1.jpg" + }, + { + "text": "Example 2: Input:values = [3,7,4,5]Output:144Explanation:There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\nThe minimum score is 144.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape2.jpg" + }, + { + "text": "Example 3: Input:values = [1,3,1,4,1,5]Output:13Explanation:The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.", + "image": "https://assets.leetcode.com/uploads/2021/02/25/shape3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 13.89%) | Memory: 41.7 MB (Top 61.06%)\nclass Solution {\n int solve(int[] v, int i, int j){\n if(i+1==j)\n return 0;\n int ans= Integer.MAX_VALUE;\n for(int k=i+1;k=0;i--){\n for(int j=i+2;j int:\n \n n = len(values)\n \n c = [[0 for _ in range(n)] for _ in range(n)]\n \n for L in range(2, n):\n \n for i in range(1, n-L+1):\n \n j = i + L - 1\n \n c[i][j] = float('inf')\n \n for k in range(i, j):\n \n q = c[i][k] + c[k+1][j] + (values[i-1]*values[k]*values[j])\n \n if c[i][j] > q:\n c[i][j] = q\n \n return c[1][n-1]\n \n \n \n \n \n", + "title": "1039. Minimum Score Triangulation of Polygon", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n . A frog starts at point 0 in the second lane and wants to jump to point n . However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] ( ranging from 0 to 3 ) describes an obstacle on the lane obstacles[i] at point i . If obstacles[i] == 0 , there are no obstacles at point i . There will be at most one obstacle in the 3 lanes at each point. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1 . To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if obstacles[2] == 1 , then there is an obstacle on lane 1 at point 2." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [0,1,2,3,0]Output:2Explanation:The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png" + }, + { + "text": "Example 2: Input:obstacles = [0,1,1,3,3,0]Output:0Explanation:There are no obstacles on lane 2. No side jumps are required.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png" + }, + { + "text": "Example 3: Input:obstacles = [0,2,1,0,3,0]Output:2Explanation:The optimal solution is shown by the arrows above. There are 2 side jumps.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSideJumps(int[] obstacles) {\n int[] dp = new int[]{1, 0, 1};\n for(int i=1; i=0) min = Math.min(min, val);\n }\n return min;\n }\n}\n", + "title": "1824. Minimum Sideway Jumps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n . A frog starts at point 0 in the second lane and wants to jump to point n . However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] ( ranging from 0 to 3 ) describes an obstacle on the lane obstacles[i] at point i . If obstacles[i] == 0 , there are no obstacles at point i . There will be at most one obstacle in the 3 lanes at each point. The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1 . To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane. Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0. Note: There will be no obstacles on points 0 and n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if obstacles[2] == 1 , then there is an obstacle on lane 1 at point 2." + ], + "examples": [ + { + "text": "Example 1: Input:obstacles = [0,1,2,3,0]Output:2Explanation:The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png" + }, + { + "text": "Example 2: Input:obstacles = [0,1,1,3,3,0]Output:0Explanation:There are no obstacles on lane 2. No side jumps are required.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png" + }, + { + "text": "Example 3: Input:obstacles = [0,2,1,0,3,0]Output:2Explanation:The optimal solution is shown by the arrows above. There are 2 side jumps.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n \n \"\"\"\n # TLE Recursion DP\n @cache\n def dp(curr_lane = 2, point = 0):\n if point == len(obstacles)-1:\n return 0\n if obstacles[point+1] == curr_lane:\n return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n \n return dp(curr_lane, point+1)\n \n \n return dp()\n \n \"\"\"\n \n n = len(obstacles) \n dp = [[0, 0, 0, 0] for _ in range(n)]\n \n for point in range(n-2, -1, -1):\n for curr_lane in range(4):\n if obstacles[point+1] == curr_lane:\n dp[point][curr_lane] = min(dp[point+1][lane] for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n else:\n dp[point][curr_lane] = dp[point+1][curr_lane]\n \n return dp[0][2]", + "title": "1824. Minimum Sideway Jumps", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a contiguous subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] of which the sum is greater than or equal to target . If there is no such subarray, return 0 instead. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]Output:2Explanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]Output:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSubArrayLen(int target, int[] nums) {\n int left = 0;\n int n = nums.length;\n int sum = 0;\n int minCount = Integer.MAX_VALUE;\n for(int i = 0;i= target){\n minCount = Math.min(minCount, i-left+1);\n sum -= nums[left++];\n } \n }\n return minCount == Integer.MAX_VALUE?0:minCount;\n }\n}\n", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a contiguous subarray [nums l , nums l+1 , ..., nums r-1 , nums r ] of which the sum is greater than or equal to target . If there is no such subarray, return 0 instead. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]Output:2Explanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]Output:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSubArrayLen(self, target, nums):\n\t\t# Init left pointer and answer\n l, ans = 0, len(nums) + 1\n\t\t# Init sum of subarray\n s = 0 \n\t\t# Iterate through all numbers as right subarray \n for r in range(len(nums)):\n\t\t\t# Add right number to sum\n s += nums[r]\n\t\t\t# Check for subarray greater than or equal to target\n while s >= target:\n\t\t\t\t# Calculate new min\n ans = min(ans, r - l + 1)\n\t\t\t\t# Remove current left nubmer from sum\n s -= nums[l]\n\t\t\t\t# Move left index up one\n l += 1\n\t\t# No solution\n if ans == len(nums) + 1:\n return 0\n\t\t# Solution\n return ans \n", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer hoursBefore , the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n , where dist[i] describes the length of the i th road in kilometers . In addition, you are given an integer speed , which is the speed (in km/h ) you will travel at. After you travel road i , you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], speed = 4, hoursBefore = 2Output:1Explanation:Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 +0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.", + "image": null + }, + { + "text": "Example 2: Input:dist = [7,3,5,5], speed = 2, hoursBefore = 10Output:2Explanation:Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 +0) + (3/2 + 0)) + ((5/2 +0) + (5/2)) = 10 hours.", + "image": null + }, + { + "text": "Example 3: Input:dist = [7,3,5,5], speed = 1, hoursBefore = 10Output:-1Explanation:It is impossible to arrive at the meeting on time even if you skip all the rests.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 92.86%) | Memory: 43.4 MB (Top 57.14%)\nclass Solution {\n public int minSkips(int[] dist, int speed, int hoursBefore) {\n int N = dist.length, INF = (int)1e9;\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0]=0; // before we start, we have a time of 0 for 0 cost\n for (int i = 0 ; i= 0; j--){ // j (cost) is at most i (num of element-1) so we start from there.\n dp[j]=Math.min(j==0?INF:dp[j-1]+dist[i], ceil(dp[j], speed)+dist[i]);\n }\n }\n for (int i = 0; i < N; i++){ // find the min cost (i) such that the min time is no greater than hoursBefore\n if (ceil(dp[i],speed)/speed<=hoursBefore){\n return i;\n }\n }\n return -1;\n }\n\n private int ceil(int n, int s){\n return n+(s-n%s)%s;\n }\n}", + "title": "1883. Minimum Skips to Arrive at Meeting On Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer hoursBefore , the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n , where dist[i] describes the length of the i th road in kilometers . In addition, you are given an integer speed , which is the speed (in km/h ) you will travel at. After you travel road i , you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], speed = 4, hoursBefore = 2Output:1Explanation:Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 +0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.", + "image": null + }, + { + "text": "Example 2: Input:dist = [7,3,5,5], speed = 2, hoursBefore = 10Output:2Explanation:Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 +0) + (3/2 + 0)) + ((5/2 +0) + (5/2)) = 10 hours.", + "image": null + }, + { + "text": "Example 3: Input:dist = [7,3,5,5], speed = 1, hoursBefore = 10Output:-1Explanation:It is impossible to arrive at the meeting on time even if you skip all the rests.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1024 ms (Top 91.67%) | Memory: 285.50 MB (Top 27.78%)\n\nclass Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n if sum(dist)/speed > hoursBefore: return -1 # impossible \n \n @cache\n def fn(i, k): \n \"\"\"Return min time (in distance) of traveling first i roads with k skips.\"\"\"\n if k < 0: return inf # impossible \n if i == 0: return 0 \n return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))\n \n for k in range(len(dist)):\n if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k \n", + "title": "1883. Minimum Skips to Arrive at Meeting On Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n packages that you are trying to place in boxes, one package in each box . There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages , where packages[i] is the size of the i th package. The suppliers are given as a 2D integer array boxes , where boxes[j] is an array of box sizes that the j th supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized . For each package in a box, we define the space wasted to be size of the box - size of the package . The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally , or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large , return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8] , you can fit the packages of size- 2 and size- 3 into two boxes of size- 4 and the package with size- 5 into a box of size- 8 . This would result in a waste of (4-2) + (4-3) + (8-5) = 6 ." + ], + "examples": [ + { + "text": "Example 1: Input:packages = [2,3,5], boxes = [[4,8],[2,8]]Output:6Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "image": null + }, + { + "text": "Example 2: Input:packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]Output:-1Explanation:There is no box that the package of size 5 can fit in.", + "image": null + }, + { + "text": "Example 3: Input:packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]Output:9Explanation:It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minWastedSpace(int[] packages, int[][] boxes) {\n Arrays.sort(packages);\n int n = packages.length, k = -1;\n long sum = 0, ans = Long.MAX_VALUE;\n int[] pos = new int[100001];\n for (int i = 0; i < 100001; i++){ // precompute jump position.\n while(k < n - 1 && packages[k+1] == i){\n sum += packages[++k];\n }\n pos[i] = k;\n }\n for (int[] b : boxes){\n Arrays.sort(b);\n long cost = -sum;\n k=-1;\n for (int i = 0; i < b.length; i++){\n if (pos[b[i]] >= 0){\n int cnt = pos[b[i]]-k;\n cost += 1L * cnt * b[i];\n k=pos[b[i]];\n }\n }\n ans = k == n-1? Math.min(cost, ans) : ans;\n }\n\n return ans == Long.MAX_VALUE? -1 : (int)(ans % (int)(1e9+7));\n }\n}\n", + "title": "1889. Minimum Space Wasted From Packaging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n packages that you are trying to place in boxes, one package in each box . There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages , where packages[i] is the size of the i th package. The suppliers are given as a 2D integer array boxes , where boxes[j] is an array of box sizes that the j th supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized . For each package in a box, we define the space wasted to be size of the box - size of the package . The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally , or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large , return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8] , you can fit the packages of size- 2 and size- 3 into two boxes of size- 4 and the package with size- 5 into a box of size- 8 . This would result in a waste of (4-2) + (4-3) + (8-5) = 6 ." + ], + "examples": [ + { + "text": "Example 1: Input:packages = [2,3,5], boxes = [[4,8],[2,8]]Output:6Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.", + "image": null + }, + { + "text": "Example 2: Input:packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]Output:-1Explanation:There is no box that the package of size 5 can fit in.", + "image": null + }, + { + "text": "Example 3: Input:packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]Output:9Explanation:It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2545 ms (Top 38.89%) | Memory: 37.8 MB (Top 95.24%)\nclass Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n # prefix sum to save time\n acc = [0] + [*accumulate(packages)]\n packages.sort()\n\n ans = float('inf')\n for box in boxes:\n tmp = 0\n # deal with smallest box first\n box.sort()\n\n # record number of packages already dealt with\n start = 0\n\n for b in box:\n loc = bisect.bisect(packages, b)\n if loc == 0: continue\n tmp += b * (loc - start) - (acc[loc] - acc[start])\n\n # all are packaged\n if loc == len(packages):\n ans = min(ans, tmp)\n break\n\n start = loc\n\n return ans % (10 **9+7) if ans != float('inf') else -1", + "title": "1889. Minimum Space Wasted From Packaging", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a floating-point number hour , representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n , where dist[i] describes the distance (in kilometers) of the i th train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time . Tests are generated such that the answer will not exceed 10^7 and hour will have at most two digits after the decimal point . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the 1 st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2 nd train ride at the 2 hour mark." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], hour = 6Output:1Explanation:At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,3,2], hour = 2.7Output:3Explanation:At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "image": null + }, + { + "text": "Example 3: Input:dist = [1,3,2], hour = 1.9Output:-1Explanation:It is impossible because the earliest the third train can depart is at the 2 hour mark.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 343 ms (Top 5.57%) | Memory: 108.2 MB (Top 25.06%)\nclass Solution {\n public int minSpeedOnTime(int[] dist, double hour) {\n int left = 1;\n int right = (int) 1e8;\n\n while (left < right) {\n int middle = (left + right) / 2;\n if (arriveOnTime(dist, hour, middle))\n right = middle;\n else left = middle + 1;\n }\n\n return right == (int) 1e8 ? -1 : right;\n }\n\n private boolean arriveOnTime(int[] dist, double hour, int speed) {\n int time = 0;\n for (int i = 0; i < dist.length - 1; i++) {\n time += Math.ceil((double) dist[i] / speed);\n }\n return time + (double) dist[dist.length - 1] / speed <= hour;\n }\n}", + "title": "1870. Minimum Speed to Arrive on Time", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a floating-point number hour , representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n , where dist[i] describes the distance (in kilometers) of the i th train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time . Tests are generated such that the answer will not exceed 10^7 and hour will have at most two digits after the decimal point . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the 1 st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2 nd train ride at the 2 hour mark." + ], + "examples": [ + { + "text": "Example 1: Input:dist = [1,3,2], hour = 6Output:1Explanation:At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.", + "image": null + }, + { + "text": "Example 2: Input:dist = [1,3,2], hour = 2.7Output:3Explanation:At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.", + "image": null + }, + { + "text": "Example 3: Input:dist = [1,3,2], hour = 1.9Output:-1Explanation:It is impossible because the earliest the third train can depart is at the 2 hour mark.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5298 ms (Top 60.74%) | Memory: 27.4 MB (Top 98.14%)\n\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n # the speed upper is either the longest train ride: max(dist),\n # or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).\n # notice: \"hour will have at most two digits after the decimal point\"\n upper = max(max(dist), ceil(dist[-1] / 0.01))\n #\n # the function to calcute total time consumed\n total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)\n # the case of impossible to arrive office on time\n if total(upper) > hour:\n return -1\n #\n # binary search: find the mimimal among \"all\" feasible answers\n left, right = 1, upper\n while left < right:\n mid = left + (right - left) // 2\n if total(mid) > hour:\n left = mid + 1 # should be larger\n else:\n right = mid # should explore a smaller one\n return right", + "title": "1870. Minimum Speed to Arrive on Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array nums , obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique . Also return the answer sorted in non-increasing order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,10,9,8]Output:[10,9]Explanation:The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,7,6,7]Output:[7,7,6]Explanation:The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 45.85%) | Memory: 44.9 MB (Top 74.27%)\nclass Solution {\n public List minSubsequence(int[] nums) {\n int total = 0;\n for(int i=0;i ans = new ArrayList<>();\n for(int i=nums.length-1;i>=0;i--){\n ans.add(nums[i]);\n sum += nums[i];\n if(sum>total-sum){\n return ans;\n }\n }\n return ans;\n }\n}", + "title": "1403. Minimum Subsequence in Non-Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array nums , obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be unique . Also return the answer sorted in non-increasing order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 500", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,10,9,8]Output:[10,9]Explanation:The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,4,7,6,7]Output:[7,7,6]Explanation:The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n val = sum(nums)\n temp = []\n for i in range(len(nums)):\n temp.append(nums[i])\n if sum(temp)>val-sum(temp):\n return temp\n \n", + "title": "1403. Minimum Subsequence in Non-Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string target of length n . You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target . In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1] . Flip means changing '0' to '1' and '1' to '0' . Return the minimum number of operations needed to make s equal to target . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == target.length", + "1 <= n <= 10^5", + "target[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:target = \"10111\"Output:3Explanation:Initially, s = \"00000\".\nChoose index i = 2: \"00000\" -> \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 2: Input:target = \"101\"Output:3Explanation:Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 3: Input:target = \"00000\"Output:0Explanation:We do not need any operations since the initial s already equals target.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 72.82%) | Memory: 46.7 MB (Top 65.16%)\n\nclass Solution {\n public int minFlips(String target) {\n\n boolean lastBit = false;\n\n int flips = 0;\n for(int i=0;i \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 2: Input:target = \"101\"Output:3Explanation:Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.", + "image": null + }, + { + "text": "Example 3: Input:target = \"00000\"Output:0Explanation:We do not need any operations since the initial s already equals target.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minFlips(self, target: str) -> int:\n flip = False\n res = 0\n for c in target:\n if (c == '1') != flip:\n flip = not flip\n res += 1\n \n return res", + "title": "1529. Minimum Suffix Flips", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num . Leading zeros are allowed in new1 and new2 , and all the digits found in num must be used. Return the minimum possible sum of new1 and new2 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, given num = 2932 , you have the following digits: two 2 's, one 9 and one 3 . Some of the possible pairs [new1, new2] are [22, 93] , [23, 92] , [223, 9] and [2, 329] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 2932Output:52Explanation:Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.", + "image": null + }, + { + "text": "Example 2: Input:num = 4009Output:13Explanation:Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.20 MB (Top 59.52%)\n\nclass Solution\n{\n public int minimumSum(int num)\n {\n int[] dig = new int[4]; // For each digit\n int cur = 0;\n while(num > 0) // Getting each digit\n {\n dig[cur++] = num % 10;\n num /= 10;\n }\n Arrays.sort(dig); // Ascending order\n int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit\n int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit\n return num1 + num2;\n }\n}\n", + "title": "2160. Minimum Sum of Four Digit Number After Splitting Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num . Leading zeros are allowed in new1 and new2 , and all the digits found in num must be used. Return the minimum possible sum of new1 and new2 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, given num = 2932 , you have the following digits: two 2 's, one 9 and one 3 . Some of the possible pairs [new1, new2] are [22, 93] , [23, 92] , [223, 9] and [2, 329] ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 2932Output:52Explanation:Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.", + "image": null + }, + { + "text": "Example 2: Input:num = 4009Output:13Explanation:Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumSum(self, num: int) -> int:\n s=list(str(num))\n s.sort()\n return int(s[0]+s[2])+int(s[1]+s[3])", + "title": "2160. Minimum Sum of Four Digit Number After Splitting Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two positive 0-indexed integer arrays nums1 and nums2 , both of length n . The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i]) 2 for each 0 <= i < n . You are also given two positive integers k1 and k2 . You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times . Note : You are allowed to modify the array elements to become negative integers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "1 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= 10^5", + "0 <= k1, k2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0Output:579Explanation:The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2+ (2 - 10)2+ (3 - 20)2+ (4 - 19)2= 579.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1Output:43Explanation:One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2+ (4 - 8)2+ (10 - 7)2+ (12 - 9)2= 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /** Algorithm\n 1. Count the differences between each nums1[i] and nums2[i] and store them into an int[100_001], as nums is between 0 and 100_000.\n 2. Let's look at the example of [1,4,10,12], [4,8,6,7]. k1= 1, k2 =1\n Looking at the pairs of abs diff we have 3,4,4,5.\n So a total of 16 diff points with k = 2.\n As we observe, if we use the k operations on the first pair, we can decrease 3 to 1.\n but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.\n However, if we operate on the diff of 5, this would have much more impact.\n 5 - 1 => (4^2)25 - 16 . so we save 9 points by using 1 k\n 5 - 2 => (3^2) 25 - 9. So we save 16 points.\n 3. As we can see, we need to operate on the highest diff, lowering them.\n 4. As we have counted them on step #1, we would have an array like this\n [0,0,0,1,2,1] : 1 diff of 3, 2 of 4 and 1 of 5.\n 5. While k is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time.\n So make all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only\n lower k diff to diff -1.\n So [0,0,0,1,2,1] and k = 2 => [0,0,0,1,3,0] and k =1\n We have 3 diff of 4 and just k =1 so we can turn one 4 into a 3.\n => [0,0,0,2,2,0]. Thus. the diff becomes 2 of 3 and 2 of 4.\n */\n public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {\n long minSumSquare = 0;\n int[] diffs = new int[100_001];\n long totalDiff = 0;\n long kSum = k1 + k2;\n int currentDiff;\n int maxDiff = 0;\n for (int i = 0; i < nums1.length; i++) {\n // get current diff.\n currentDiff = Math.abs(nums1[i] - nums2[i]);\n // if current diff > 0, count/store it. If not,then ignore it.\n if (currentDiff > 0) {\n totalDiff += currentDiff;\n diffs[currentDiff]++;\n maxDiff = Math.max(maxDiff, currentDiff);\n }\n }\n // if kSum (k1 + k2) < totalDifferences, it means we can make all numbers/differences 0s\n if (totalDiff <= kSum) {\n return 0;\n }\n // starting from the back, from the highest difference, lower that group one by one to the previous group.\n // we need to make all n diffs to n-1, then n-2, as long as kSum allows it.\n for (int i = maxDiff; i> 0 && kSum > 0; i--) {\n if (diffs[i] > 0) {\n // if current group has more differences than the totalK, we can only move k of them to the lower level.\n if (diffs[i] >= kSum) {\n diffs[i] -= kSum;\n diffs[i-1] += kSum;\n kSum = 0;\n } else {\n // else, we can make this whole group one level lower.\n diffs[i-1] += diffs[i];\n kSum -= diffs[i];\n diffs[i] = 0;\n }\n }\n }\n\n for (int i = 0; i <= maxDiff; i++) {\n if (diffs[i] > 0) {\n minSumSquare += (long) (Math.pow((long)i, 2)) * diffs[i];\n }\n }\n return minSumSquare;\n }\n}\n", + "title": "2333. Minimum Sum of Squared Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two positive 0-indexed integer arrays nums1 and nums2 , both of length n . The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i]) 2 for each 0 <= i < n . You are also given two positive integers k1 and k2 . You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times . Note : You are allowed to modify the array elements to become negative integers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums1.length == nums2.length", + "1 <= n <= 10^5", + "0 <= nums1[i], nums2[i] <= 10^5", + "0 <= k1, k2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0Output:579Explanation:The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2+ (2 - 10)2+ (3 - 20)2+ (4 - 19)2= 579.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1Output:43Explanation:One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2+ (4 - 8)2+ (10 - 7)2+ (12 - 9)2= 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1506 ms (Top 29.6%) | Memory: 34.22 MB (Top 74.0%)\n\nclass Solution:\n def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:\n n = len(nums1)\n k = k1+k2 # can combine k's because items can be turned negative\n diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))\n \n # First binary search to find our new max for our diffs array\n l, r = 0, max(diffs)\n while l < r:\n mid = (l+r)//2\n \n # steps needed to reduce all nums greater than newMax\n steps = sum(max(0, num-mid) for num in diffs)\n \n if steps <= k:\n r = mid\n else:\n l = mid+1\n \n newMax = l\n k -= sum(max(0, num-newMax) for num in diffs) # remove used k\n\n # Second binary search to find first index to replace with max val\n l, r = 0, n-1\n while l < r:\n mid = (l+r)//2\n if diffs[mid] < newMax:\n l = mid+1\n else:\n r = mid\n\n # Replace items at index >= l with newMax\n diffs = diffs[:l]+[newMax]*(n-l)\n \n # Use remaining steps to reduce overall score\n for i in range(len(diffs)-1,-1,-1):\n if k == 0 or diffs[i] == 0: break\n diffs[i] -= 1\n k -= 1\n \n return sum(diff*diff for diff in diffs)", + "title": "2333. Minimum Sum of Squared Difference", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n x n binary grid , in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros . Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "grid[i][j] is either 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1],[1,1,0],[1,0,0]]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/07/28/fw.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]Output:-1Explanation:All rows are similar, swaps have no effect on the grid.", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,1]]Output:0", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwaps(int[][] grid) {\n int n = grid.length, ans = 0, cur = 0;\n for (int k = 0; k < n - 1; k++){ // looking for the fitting row for row k\n for (int i = k; i < n; i++){ // start from row k looking downward\n for (int j = k + 1; j < n; j++){ // all cell after and at k + 1 must be 0\n if (grid[i][j] == 1)\n break;\n if (j < n - 1)\n continue;\n for (int m = i; m > k; m--){ // j == n - 1 here, so we found a valid row\n int[] tmp = grid[m - 1]; // swap it into the correct row - row k\n grid[m - 1] = grid[m];\n grid[m] = tmp;\n ans++;\n }\n i = n;\n }\n if (i == n - 1) // i reaches the end and did not find a fitting row, return -1\n return -1;\n }\n }\n return ans;\n }\n}\n", + "title": "1536. Minimum Swaps to Arrange a Binary Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n binary grid , in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros . Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "grid[i][j] is either 0 or 1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1],[1,1,0],[1,0,0]]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/07/28/fw.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]Output:-1Explanation:All rows are similar, swaps have no effect on the grid.", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e2.jpg" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,1]]Output:0", + "image": "https://assets.leetcode.com/uploads/2020/07/16/e3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1405 ms (Top 5.77%) | Memory: 15.2 MB (Top 23.08%)\nclass Solution:\n def minSwaps(self, grid) -> int:\n n = len(grid)\n max_right = [-1] * n\n for r, row in enumerate(grid):\n for c in range(n - 1, -1, -1):\n if row[c] == 1:\n max_right[r] = c\n break\n if all(v <= i for i, v in enumerate(sorted(max_right))):\n swaps = 0\n i = 0\n while i < n:\n while i < n and max_right[i] <= i:\n i += 1\n if i == n:\n break\n j = i\n while j < n and max_right[j] > i:\n j += 1\n swaps += j - i\n max_right[i], max_right[i + 1: j + 1] = (max_right[j],\n max_right[i: j])\n i += 1\n return swaps\n return -1", + "title": "1536. Minimum Swaps to Arrange a Binary Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent . Given a binary circular array nums , return the minimum number of swaps required to group all 1 's present in the array together at any location . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,1,1,0,0]Output:1Explanation:Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,0,1,1,0]Output:2Explanation:Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,0,0,1]Output:0Explanation:All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSwaps(self, nums: List[int]) -> int:\n width = sum(num == 1 for num in nums) #width of the window\n nums += nums\n res = width\n curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width]\n \n for i in range(width, len(nums)):\n curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists\n curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists\n res = min(res, curr_zeros) #update if needed\n \n return res\n", + "title": "2134. Minimum Swaps to Group All 1's Together II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays of the same length nums1 and nums2 . In one operation, you are allowed to swap nums1[i] with nums2[i] . Return the minimum number of needed operations to make nums1 and nums2 strictly increasing . The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3, 8 ] , and nums2 = [5,6,7, 4 ] , you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,5,4], nums2 = [1,2,3,7]Output:1Explanation:Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSwap(int[] nums1, int[] nums2) {\n int p1 = nums1[0], p2 = nums2[0], ans = 0;\n int len = nums1.length, s = 0, count = 0;\n for (int i=1; i < len; i++) {\n int n1 = nums1[i], n2 = nums2[i];\n if (n1 > p1 && n2 > p2) {\n if (n1 > p2 && n2 > p1) {\n ans += Math.min(count, i - s - count);\n s = i; count = 0;\n }\n p1 = n1; p2 = n2;\n } else {\n count++;\n p1 = n2; p2 = n1;\n }\n }\n return ans + Math.min(count, len - s - count);\n }\n}\n", + "title": "801. Minimum Swaps To Make Sequences Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays of the same length nums1 and nums2 . In one operation, you are allowed to swap nums1[i] with nums2[i] . Return the minimum number of needed operations to make nums1 and nums2 strictly increasing . The test cases are generated so that the given input always makes it possible. An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums1 = [1,2,3, 8 ] , and nums2 = [5,6,7, 4 ] , you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,5,4], nums2 = [1,2,3,7]Output:1Explanation:Swap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1198 ms (Top 36.1%) | Memory: 149.20 MB (Top 27.6%)\n\nclass Solution:\n def minSwap(self, nums1: List[int], nums2: List[int]) -> int:\n dp = [[-1]*2 for i in range(len(nums1))]\n \n def solve(prev1, prev2, i, swaped):\n if i >= len(nums1): return 0\n if dp[i][swaped] != -1: return dp[i][swaped]\n \n ans = 2**31\n \n # No Swap\n if nums1[i] > prev1 and nums2[i] > prev2:\n ans = solve(nums1[i], nums2[i], i+1, 0) \n \n # Swap\n if nums1[i] > prev2 and nums2[i] > prev1:\n ans = min(ans, 1 + solve(nums2[i], nums1[i], i+1, 1)) \n \n dp[i][swaped] = ans\n return ans\n \n return solve(-1, -1, 0, 0) ", + "title": "801. Minimum Swaps To Make Sequences Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only . Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j] . Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 1000", + "s1, s2 only contain 'x' or 'y' ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"xx\", s2 = \"yy\"Output:1Explanation:Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"xy\", s2 = \"yx\"Output:2Explanation:Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"xx\", s2 = \"xy\"Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.80 MB (Top 5.91%)\n\nclass Solution {\n public int minimumSwap(String s1, String s2) {\n \n int count = 0;\n int cnt_1 = 0;\n int cnt_2 = 0;\n char[] a = s1.toCharArray();\n char[] b = s2.toCharArray();\n \n for(int i=0;i int:\n h = defaultdict(int)\n count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count += 1\n h[s1[i]] += 1\n if count % 2 != 0: \n return -1\n res, a, b = 0, h['x'], h['y']\n res += a // 2 + b // 2\n if a % 2 == 0:\n return res\n return res + 2", + "title": "1247. Minimum Swaps to Make Strings Equal", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= timePoints.length <= 2 * 10^4", + "timePoints[i] is in the format \"HH:MM\" ." + ], + "examples": [ + { + "text": "Example 1: Input:timePoints = [\"23:59\",\"00:00\"]Output:1", + "image": null + }, + { + "text": "Example 2: Input:timePoints = [\"00:00\",\"23:59\",\"00:00\"]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 62.54%) | Memory: 46.9 MB (Top 41.18%)\nclass Solution {\n public int findMinDifference(List timePoints) {\n int N = timePoints.size();\n int[] minutes = new int[N];\n for(int i = 0; i < N; i++){\n int hr = Integer.parseInt(timePoints.get(i).substring(0, 2));\n int min = Integer.parseInt(timePoints.get(i).substring(3, 5));\n minutes[i] = hr * 60 + min;\n }\n Arrays.sort(minutes);\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < N - 1; i++){\n res = Math.min(res, minutes[i + 1] - minutes[i]);\n }\n int b = minutes[0];\n int a = minutes[N - 1];\n return Math.min(res, (b - a + 1440) % 1440);\n }\n}", + "title": "539. Minimum Time Difference", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= timePoints.length <= 2 * 10^4", + "timePoints[i] is in the format \"HH:MM\" ." + ], + "examples": [ + { + "text": "Example 1: Input:timePoints = [\"23:59\",\"00:00\"]Output:1", + "image": null + }, + { + "text": "Example 2: Input:timePoints = [\"00:00\",\"23:59\",\"00:00\"]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 91.63%) | Memory: 20.60 MB (Top 5.75%)\n\nclass Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n # Convert time points to minutes since midnight and sort the list\n minutes = sorted([int(time[:2]) * 60 + int(time[3:]) for time in timePoints])\n \n # Calculate the minimum difference between adjacent time points\n min_diff = float('inf')\n for i in range(len(minutes) - 1):\n diff = minutes[i+1] - minutes[i]\n if diff < min_diff:\n min_diff = diff\n \n # Calculate the difference between the first and last time points\n diff = (24*60 - minutes[-1] + minutes[0]) % (24*60)\n if diff < min_diff:\n min_diff = diff\n \n return min_diff\n\n", + "title": "539. Minimum Time Difference", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1 , which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Additionally, there is a boolean array hasApple , where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i < b i <= n - 1", + "from i < to i", + "hasApple.length == n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]Output:8Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]Output:6Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png" + }, + { + "text": "Example 3: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minTime(int n, int[][] edges, List hasApple) {\n HashMap> graph = new HashMap<>(n);\n for(int edge[] : edges){\n int a = edge[0], b = edge[1];\n graph.putIfAbsent(a, new LinkedList<>());\n graph.putIfAbsent(b, new LinkedList<>());\n graph.get(a).add(b);\n graph.get(b).add(a);\n }\n \n boolean[] visited = new boolean[n];\n Arrays.fill(visited,false);\n \n int a = move(0,graph,hasApple,n,visited);\n \n return a==-1?0:a;\n }\n \n public int move(int i,HashMap> graph,List hasApple,int n,boolean[] visited){\n visited[i]=true;\n boolean cont = false;\n if(hasApple.get(i)){\n cont=true;\n }\n \n List list = graph.get(i);\n \n if(list==null){\n return cont?0:-1;\n }\n int j = 0;\n for(int k : list){\n if(!visited[k]){\n int a = move(k,graph,hasApple,n,visited);\n if(a!=-1){\n j+=2+a;\n }\n }\n }\n if(j==0 && cont) return 0;\n return j==0?-1:j;\n }\n}", + "title": "1443. Minimum Time to Collect All Apples in a Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an undirected tree consisting of n vertices numbered from 0 to n-1 , which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Additionally, there is a boolean array hasApple , where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i < b i <= n - 1", + "from i < to i", + "hasApple.length == n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]Output:8Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]Output:6Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.", + "image": "https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png" + }, + { + "text": "Example 3: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1818 ms (Top 5.15%) | Memory: 87.1 MB (Top 5.14%)\nclass Solution:\n\n def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:\n graph_map = {i: set() for i in range(n)}\n for edge in edges:\n graph_map[edge[0]].add(edge[1])\n graph_map[edge[1]].add(edge[0])\n\n self.result = set()\n visited = set()\n def dfs(node, path):\n visited.add(node)\n if hasApple[node]:\n temp = path + '|' + str(node)\n temp = temp.split('|')[1:]\n # print(temp)\n for i in range(1, len(temp)):\n self.result.add((temp[i], temp[i-1]))\n for nei in graph_map[node]:\n if nei not in visited:\n dfs(nei, path + '|' + str(node))\n\n dfs(0, \"\")\n # print(self.result)\n return len(self.result) * 2", + "title": "1443. Minimum Time to Collect All Apples in a Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array time where time[i] denotes the time taken by the i th bus to complete one trip . Each bus can make multiple trips successively ; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently ; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips , which denotes the number of trips all buses should make in total . Return the minimum time required for all buses to complete at least totalTrips trips . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= time.length <= 10^5", + "1 <= time[i], totalTrips <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:time = [1,2,3], totalTrips = 5Output:3Explanation:- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.", + "image": null + }, + { + "text": "Example 2: Input:time = [2], totalTrips = 1Output:2Explanation:There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumTime(int[] time, int totalTrips) {\n long anstillnow=-1;\n \n long left=1, right= 100000000000001L;\n \n while(left<=right){\n long mid= left+ (right-left)/2; //find mid point like this to avoid overflow\n long curr_trips=0;\n for(int t: time){\n curr_trips+= mid/t;\n }\n \n if(curr_trips>=totalTrips){\n anstillnow=mid;\n right=mid-1;\n }\n \n else{\n left=mid+1;\n }\n }\n \n return anstillnow; \n }\n}\n", + "title": "2187. Minimum Time to Complete Trips", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array time where time[i] denotes the time taken by the i th bus to complete one trip . Each bus can make multiple trips successively ; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently ; that is, the trips of one bus do not influence the trips of any other bus. You are also given an integer totalTrips , which denotes the number of trips all buses should make in total . Return the minimum time required for all buses to complete at least totalTrips trips . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= time.length <= 10^5", + "1 <= time[i], totalTrips <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:time = [1,2,3], totalTrips = 5Output:3Explanation:- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.", + "image": null + }, + { + "text": "Example 2: Input:time = [2], totalTrips = 1Output:2Explanation:There is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def minimumTime(self, time, totalTrips):\n anstillnow=-1;\n left=1;\n right= 100000000000001;\n \n while(left<=right):\n mid= left+ (right-left)/2 #find mid point like this to avoid overflow\n \n curr_trips=0;\n \n for t in time:\n curr_trips+= mid/t\n \n if(curr_trips>=totalTrips):\n anstillnow=mid\n right=mid-1\n \n else:\n left=mid+1\n\n return anstillnow\n", + "title": "2187. Minimum Time to Complete Trips", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [f i , r i ] indicates that the i th tire can finish its x th successive lap in f i * r i (x-1) seconds. You are also given an integer changeTime and an integer numLaps . The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if f i = 3 and r i = 2 , then the tire would finish its 1 st lap in 3 seconds, its 2 nd lap in 3 * 2 = 6 seconds, its 3 rd lap in 3 * 2 2 = 12 seconds, etc." + ], + "examples": [ + { + "text": "Example 1: Input:tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4Output:21Explanation:Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5Output:25Explanation:Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 41.82%) | Memory: 150.6 MB (Top 27.82%)\nclass Solution {\n int changeTime;\n public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n this.changeTime = changeTime;\n int[] minTime = new int[numLaps + 1];\n Arrays.fill(minTime, Integer.MAX_VALUE);\n\n for (int[] tire : tires){\n populateMinTime(tire, minTime);\n }\n\n int[] dp = new int[numLaps + 1];\n for (int i = 1; i <= numLaps; i++){\n dp[i] = minTime[i]; // maxValue for dp[i] is Integer.MAX_VALUE, no need to worry about overflow\n for (int j = 1; j < i; j++){\n dp[i] = Math.min(dp[i], dp[j] + changeTime + dp[i - j]); // it will never overflow, since dp[j] are far less than Integer.MAX_VALUE\n }\n }\n return dp[numLaps];\n }\n\n private void populateMinTime(int[] tire, int[] minTime){\n int sum = 0;\n int base = tire[0];\n int ex = tire[1];\n int spent = 1;\n for (int i = 1; i < minTime.length; i++){\n spent = (i == 1) ? base : spent * ex;\n if (spent > changeTime + base){break;} // set boundary\n sum += spent;\n minTime[i] = Math.min(minTime[i], sum);\n }\n }\n}", + "title": "2188. Minimum Time to Finish the Race", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array tires where tires[i] = [f i , r i ] indicates that the i th tire can finish its x th successive lap in f i * r i (x-1) seconds. You are also given an integer changeTime and an integer numLaps . The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if f i = 3 and r i = 2 , then the tire would finish its 1 st lap in 3 seconds, its 2 nd lap in 3 * 2 = 6 seconds, its 3 rd lap in 3 * 2 2 = 12 seconds, etc." + ], + "examples": [ + { + "text": "Example 1: Input:tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4Output:21Explanation:Lap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5Output:25Explanation:Lap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n # by observation, we can try to find out the optimal usage within certain numLaps\n # use DP\n # the optimal usage of this lap = min(change tire , no change)\n # dp(laps) = min( dp(laps-1)+dp(1) + dp(laps-2)+dp(2) + ...)\n \n # we don't want to use tires too many laps, which will create unrealistic single lap time\n\t\t# we can evaluate single lap time by using changeTime <= 100000 and r >= 2\n\t\t# x = minimal continously laps\n\t\t# single lap time = 1*2^x <= 100000 -> x can't go more than 19\n\t\tlimit = 19\n tires = list(set([(t1, t2) for t1, t2 in tires]))\n memo = [[(-1,-1) for _ in range(min(limit,numLaps)+1)] for _ in range(len(tires))]\n \n for i in range(len(tires)):\n for j in range(1, min(limit,numLaps)+1): # lap 1 to numLaps\n if j == 1:\n memo[i][j] = (tires[i][0], tires[i][0]) # total time, lap time\n else:\n # print('i, j', i, j)\n tmp = memo[i][j-1][1]*tires[i][1] # cost of continuously use tire this lap\n memo[i][j] = (memo[i][j-1][0]+tmp, tmp)\n \n @cache\n def dp(laps):\n if laps == 1:\n return min(memo[i][1][0] for i in range(len(tires)))\n \n # no change:\n best_time = min(memo[i][laps][0] for i in range(len(tires))) if laps <= limit else float('inf')\n \n # change tire:\n\t\t\t# e.g. change tire at this lap and see if it'll be faster -> dp(laps-1) + changeTime + dp(1)\n # check all previous laps: dp(a) + changeTime + dp(b) until a < b\n for j in range(1, laps):\n a, b = laps-j, j\n if a >= b:\n ta = dp(a)\n tb = dp(b)\n if ta+tb+changeTime < best_time:\n best_time = ta+tb+changeTime\n return best_time\n \n return dp(numLaps)\n", + "title": "2188. Minimum Time to Finish the Race", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i th balloon. Alice wants the rope to be colorful . She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful . You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i th balloon from the rope. Return the minimum time Bob needs to make the rope colorful . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == colors.length == neededTime.length", + "1 <= n <= 10^5", + "1 <= neededTime[i] <= 10^4", + "colors contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaac\", neededTime = [1,2,3,4,5]Output:3Explanation:In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg" + }, + { + "text": "Example 2: Input:colors = \"abc\", neededTime = [1,2,3]Output:0Explanation:The rope is already colorful. Bob does not need to remove any balloons from the rope.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg" + }, + { + "text": "Example 3: Input:colors = \"aabaa\", neededTime = [1,2,3,4,1]Output:2Explanation:Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCost(String colors, int[] neededTime) {\n return minCost(colors, neededTime, 0, neededTime.length - 1);\n }\n \n public int minCost(String colors, int[] neededTime, int start, int end) {\n if (start == end) {\n return 0;\n }\n \n int mid = (start + end) / 2;\n int lEnd = mid;\n int rStart = mid + 1;\n int t1 = minCost(colors, neededTime, start, lEnd);\n int t2 = minCost(colors, neededTime, rStart, end);\n \n while (neededTime[lEnd] < 0 && lEnd >= start) {\n --lEnd;\n }\n while (neededTime[rStart] < 0 && rStart <= end) {\n ++rStart;\n }\n \n if (colors.charAt(lEnd) != colors.charAt(rStart)) {\n return t1 + t2;\n }\n \n int removeTime = 0;\n if (neededTime[lEnd] <= neededTime[rStart]) {\n removeTime = neededTime[lEnd];\n neededTime[lEnd] *= -1;\n }\n else {\n removeTime = neededTime[rStart];\n neededTime[rStart] *= -1;\n }\n \n return t1 + t2 + removeTime;\n }\n}\n", + "title": "1578. Minimum Time to Make Rope Colorful", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the i th balloon. Alice wants the rope to be colorful . She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful . You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the i th balloon from the rope. Return the minimum time Bob needs to make the rope colorful . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == colors.length == neededTime.length", + "1 <= n <= 10^5", + "1 <= neededTime[i] <= 10^4", + "colors contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"abaac\", neededTime = [1,2,3,4,5]Output:3Explanation:In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg" + }, + { + "text": "Example 2: Input:colors = \"abc\", neededTime = [1,2,3]Output:0Explanation:The rope is already colorful. Bob does not need to remove any balloons from the rope.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg" + }, + { + "text": "Example 3: Input:colors = \"aabaa\", neededTime = [1,2,3,4,1]Output:2Explanation:Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.", + "image": "https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 862 ms (Top 94.6%) | Memory: 27.26 MB (Top 71.4%)\n\nclass Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n ans = prev = 0 # index of previously retained letter \n for i in range(1, len(s)): \n if s[prev] != s[i]: prev = i\n else: \n ans += min(cost[prev], cost[i])\n if cost[prev] < cost[i]: prev = i\n return ans ", + "title": "1578. Minimum Time to Make Rope Colorful", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the i th car does not contain illegal goods and s[i] = '1' denotes that the i th car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods . Note that an empty sequence of cars is considered to have no cars containing illegal goods. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1100101\"Output:5Explanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0010\"Output:2Explanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 58.8%) | Memory: 47.53 MB (Top 50.0%)\n\nclass Solution {\n public int minimumTime(String s) {\n int n = s.length();\n int min = s.length();\n int[] nums = new int[n];\n for (int i = 0; i < n; i++)\n nums[i] = s.charAt(i) - '0';\n\n\t\t// step1\n int[] leftOptimized = new int[n + 2];\n for (int i = 1; i <= n; i++) {\n leftOptimized[i] = Math.min(i, leftOptimized[i - 1] + (nums[i - 1] == 1? 2: 0));\n }\n\n\t\t// step2\n int[] rightOptimized = new int[n + 2];\n for (int i = n; i > 0; i--) {\n rightOptimized[i] = Math.min(n - i + 1, rightOptimized[i + 1] + (nums[i - 1] == 1? 2: 0));\n }\n\n\t\t// step3\n for (int p = 0; p <= n; p++) {\n min = Math.min(min, leftOptimized[p] + rightOptimized[p + 1]);\n }\n\n return min;\n }\n}", + "title": "2167. Minimum Time to Remove All Cars Containing Illegal Goods", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the i th car does not contain illegal goods and s[i] = '1' denotes that the i th car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods . Note that an empty sequence of cars is considered to have no cars containing illegal goods. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1100101\"Output:5Explanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"0010\"Output:2Explanation:One way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumTime(self, s):\n def minSum(nums):\n dp = [0]*len(nums)\n dp[0] = nums[0]\n for i in range(1, len(nums)):\n dp[i] = min(nums[i], nums[i] + dp[i-1])\n return min(0, min(dp))\n\n n = len(s)\n s1 = [1 if i == \"1\" else -1 for i in s]\n score = minSum(s1)\n \n return n + score\n", + "title": "2167. Minimum Time to Remove All Cars Containing Illegal Goods", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer . A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a' . Each second, you may perform one of the following operations: Given a string word , return the minimum number of seconds to type out the characters in word . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Move the pointer one character counterclockwise or clockwise .", + "Type the character the pointer is currently on." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abc\"Output:5Explanation:The characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.", + "image": null + }, + { + "text": "Example 2: Input:word = \"bza\"Output:7Explanation:The characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.", + "image": null + }, + { + "text": "Example 3: Input:word = \"zjpc\"Output:34Explanation:The characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minTimeToType(String word) {\n char prevChar = 'a';\n int totalTime = word.length();\n for(int i = 0; i < word.length(); i++){\n char currChar = word.charAt(i);\n int diff = Math.abs(currChar - prevChar);\n totalTime += Math.min(diff, 26 - diff);\n prevChar = currChar;\n }\n \n return totalTime;\n }\n}\n", + "title": "1974. Minimum Time to Type Word Using Special Typewriter", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer . A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a' . Each second, you may perform one of the following operations: Given a string word , return the minimum number of seconds to type out the characters in word . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Move the pointer one character counterclockwise or clockwise .", + "Type the character the pointer is currently on." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abc\"Output:5Explanation:The characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.", + "image": null + }, + { + "text": "Example 2: Input:word = \"bza\"Output:7Explanation:The characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.", + "image": null + }, + { + "text": "Example 3: Input:word = \"zjpc\"Output:34Explanation:The characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minTimeToType(self, word: str) -> int:\n prev = \"a\"\n res = 0\n for c in word:\n gap = abs(ord(c)-ord(prev))\n res += min(gap, 26 - gap)\n prev = c\n return res + len(word)\n", + "title": "1974. Minimum Time to Type Word Using Special Typewriter", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On a 2D plane, there are n points with integer coordinates points[i] = [x i , y i ] . Return the minimum time in seconds to visit all the points in the order given by points . You can move according to these rules: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "move vertically by one unit,", + "move horizontally by one unit, or", + "move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "You have to visit the points in the same order as they appear in the array.", + "You are allowed to pass through points that appear later in the order, but these do not count as visits." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[3,4],[-1,0]]Output:7Explanation:One optimal path is[1,1]-> [2,2] -> [3,3] ->[3,4]-> [2,3] -> [1,2] -> [0,1] ->[-1,0]Time from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds", + "image": "https://assets.leetcode.com/uploads/2019/11/14/1626_example_1.PNG" + }, + { + "text": "Example 2: Input:points = [[3,2],[-2,2]]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 57.50%) | Memory: 43.4 MB (Top 57.64%)\nclass Solution {\n public int minTimeToVisitAllPoints(int[][] points) {\n int max = 0, x, y;\n for(int i = 0; i < points.length - 1; i++){\n for(int j = 0; j < points[i].length - 1; j++){\n x = Math.abs(points[i][j] - points[i+1][j]);\n y = Math.abs(points[i][j+1] - points[i+1][j+1]);\n max += Math.max(x,y);\n }\n }\n return max;\n }\n}", + "title": "1266. Minimum Time Visiting All Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On a 2D plane, there are n points with integer coordinates points[i] = [x i , y i ] . Return the minimum time in seconds to visit all the points in the order given by points . You can move according to these rules: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "move vertically by one unit,", + "move horizontally by one unit, or", + "move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).", + "You have to visit the points in the same order as they appear in the array.", + "You are allowed to pass through points that appear later in the order, but these do not count as visits." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[3,4],[-1,0]]Output:7Explanation:One optimal path is[1,1]-> [2,2] -> [3,3] ->[3,4]-> [2,3] -> [1,2] -> [0,1] ->[-1,0]Time from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds", + "image": "https://assets.leetcode.com/uploads/2019/11/14/1626_example_1.PNG" + }, + { + "text": "Example 2: Input:points = [[3,2],[-2,2]]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 57.7%) | Memory: 13.27 MB (Top 67.6%)\n\nclass Solution:\n def minTimeToVisitAllPoints(self, points):\n res = 0\n n = len(points)\n for i in range(n-1):\n dx = abs(points[i+1][0]-points[i][0])\n dy = abs(points[i+1][1]-points[i][1])\n res+= max(dx,dy)\n return res\n\n \nobj = Solution()\nprint(obj.minTimeToVisitAllPoints([[1,1],[3,4],[-1,0]]))", + "title": "1266. Minimum Time Visiting All Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are currently designing a dynamic array. You are given a 0-indexed integer array nums , where nums[i] is the number of elements that will be in the array at time i . In addition, you are given an integer k , the maximum number of times you can resize the array (to any size). The size of the array at time t , size t , must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as size t - nums[t] , and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length . Return the minimum total space wasted if you can resize the array at most k times . Note: The array can have any size at the start and does not count towards the number of resizing operations. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 10^6", + "0 <= k <= nums.length - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,20], k = 0Output:10Explanation:size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,20,30], k = 1Output:10Explanation:size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [10,20,15,30,20], k = 2Output:15Explanation:size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n// dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times \n\n int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 }\n public int minSpaceWastedKResizing(int[] nums, int k) {\n \n int dp[][]=new int[nums.length+1][k+1];\n memeset(dp, -1);\n return f(dp, 0, k, nums);\n \n }\n \n int f(int dp[][], int idx, int k, int nums[])\n {\n if(idx==nums.length)\n return 0;\n if(k==-1)\n return INF;\n \n if(dp[idx][k] != -1)\n return dp[idx][k];\n \n int ans=INF, max=nums[idx], sum=0;\n \n for(int j=idx; j int:\n def waste(i, j, h):\n sumI = sums[i-1] if i > 0 else 0\n return (j-i+1)*h - sums[j] + sumI\n \n def dp(i, k):\n if i <= k:\n return 0\n if k < 0:\n return MAX\n if (i, k) in memoize:\n return memoize[(i, k)]\n \n _max = A[i]\n r = MAX\n for j in range(i-1, -2, -1):\n r = min(r, dp(j, k-1) + waste(j+1, i, _max))\n _max = max(_max, A[j])\n\n memoize[(i, k)] = r\n return r\n \n sums = list(accumulate(A))\n n = len(A)\n MAX = 10**6*200\n memoize = {}\n\n return dp(n-1, K)", + "title": "1959. Minimum Total Space Wasted With K Resizing Operations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , you start with an initial positive value startValue . In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-3,2,-3,4,2]Output:5Explanation:If you choose startValue = 4, in the third iteration your step by step sum is less than 1.step by step sumstartValue = 4 | startValue = 5 | nums(4-3) = 1 | (5-3) = 2 | -3\n (1+2) = 3 | (2+2) = 4 | 2\n (3-3) = 0 | (4-3) = 1 | -3\n (0+4) = 4 | (1+4) = 5 | 4\n (4+2) = 6 | (5+2) = 7 | 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]Output:1Explanation:Minimum start value should be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-2,-3]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minStartValue(int[] nums) {\n int lowest_sum = 0;\n int sum = 0;\n for(int i=0; i sum) {\n lowest_sum = sum;\n }\n }\n return 1-lowest_sum;\n }\n}\n", + "title": "1413. Minimum Value to Get Positive Step by Step Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums , you start with an initial positive value startValue . In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-3,2,-3,4,2]Output:5Explanation:If you choose startValue = 4, in the third iteration your step by step sum is less than 1.step by step sumstartValue = 4 | startValue = 5 | nums(4-3) = 1 | (5-3) = 2 | -3\n (1+2) = 3 | (2+2) = 4 | 2\n (3-3) = 0 | (4-3) = 1 | -3\n (0+4) = 4 | (1+4) = 5 | 4\n (4+2) = 6 | (5+2) = 7 | 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]Output:1Explanation:Minimum start value should be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,-2,-3]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 42 ms (Top 60.3%) | Memory: 16.30 MB (Top 27.0%)\n\nclass Solution:\n def minStartValue(self, nums: List[int]) -> int:\n return max(1, 1 - min(accumulate(nums)))", + "title": "1413. Minimum Value to Get Positive Step by Step Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1 . You are also given a 2D integer array edges where edges[i] = [from i , to i , weight i ] denotes that there exists a directed edge from from i to to i with weight weight i . Lastly, you are given three distinct integers src1 , src2 , and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph . In case such a subgraph does not exist, return -1 . A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "0 <= edges.length <= 10^5", + "edges[i].length == 3", + "0 <= from i , to i , src1, src2, dest <= n - 1", + "from i != to i", + "src1 , src2 , and dest are pairwise distinct.", + "1 <= weight[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5Output:9Explanation:The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example1drawio.png" + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2Output:-1Explanation:The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example2-1drawio.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 105 ms (Top 87.23%) | Memory: 121.90 MB (Top 31.91%)\n\nclass Solution {\n ArrayList[] nextGraph, preGraph;\n \n public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {\n buildGraph(n, edges);\n \n long[] src1To = new long[n], src2To = new long[n], toDest = new long[n];\n Arrays.fill(src1To, -1);\n Arrays.fill(src2To, -1);\n Arrays.fill(toDest, -1);\n \n shortestPath(src1, src1To, nextGraph);\n shortestPath(src2, src2To, nextGraph);\n shortestPath(dest, toDest, preGraph);\n \n long res = -1;\n for (int i = 0; i < n; i++) {\n long d1 = src1To[i], d2 = src2To[i], d3 = toDest[i];\n if (d1 >= 0 && d2 >= 0 && d3 >= 0) {\n long d = d1 + d2 + d3;\n if (res == -1 || d < res) {\n res = d;\n }\n }\n }\n \n return res;\n }\n \n private void buildGraph(int n, int[][] edges) {\n nextGraph = new ArrayList[n];\n preGraph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n nextGraph[i] = new ArrayList();\n preGraph[i] = new ArrayList();\n }\n \n for (int[] edge : edges) {\n int from = edge[0], to = edge[1], weight = edge[2];\n nextGraph[from].add(new int[] {to, weight});\n preGraph[to].add(new int[] {from, weight});\n }\n }\n \n private void shortestPath(int src, long[] srcTo, ArrayList[] graph) {\n PriorityQueue heap = new PriorityQueue<>((a, b) -> Long.compare(a[1], b[1]));\n heap.offer(new long[] {src, 0});\n \n while (!heap.isEmpty()) {\n long[] node = heap.poll();\n int to = (int) node[0];\n long dist = node[1];\n if (srcTo[to] != -1 && srcTo[to] <= dist) continue;\n srcTo[to] = dist;\n for (int[] next : graph[to]) {\n heap.offer(new long[] {next[0], dist + next[1]});\n }\n }\n }\n}\n", + "title": "2203. Minimum Weighted Subgraph With the Required Paths", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1 . You are also given a 2D integer array edges where edges[i] = [from i , to i , weight i ] denotes that there exists a directed edge from from i to to i with weight weight i . Lastly, you are given three distinct integers src1 , src2 , and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph . In case such a subgraph does not exist, return -1 . A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= n <= 10^5", + "0 <= edges.length <= 10^5", + "edges[i].length == 3", + "0 <= from i , to i , src1, src2, dest <= n - 1", + "from i != to i", + "src1 , src2 , and dest are pairwise distinct.", + "1 <= weight[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5Output:9Explanation:The above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example1drawio.png" + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2Output:-1Explanation:The above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.", + "image": "https://assets.leetcode.com/uploads/2022/02/17/example2-1drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumWeight(self, n, edges, s1, s2, dest):\n G1 = defaultdict(list)\n G2 = defaultdict(list)\n for a, b, w in edges:\n G1[a].append((b, w))\n G2[b].append((a, w))\n\n def Dijkstra(graph, K):\n q, t = [(0, K)], {}\n while q:\n time, node = heappop(q)\n if node not in t:\n t[node] = time\n for v, w in graph[node]:\n heappush(q, (time + w, v))\n return [t.get(i, float(\"inf\")) for i in range(n)]\n \n arr1 = Dijkstra(G1, s1)\n arr2 = Dijkstra(G1, s2)\n arr3 = Dijkstra(G2, dest)\n \n ans = float(\"inf\")\n for i in range(n):\n ans = min(ans, arr1[i] + arr2[i] + arr3[i])\n \n return ans if ans != float(\"inf\") else -1\n", + "title": "2203. Minimum Weighted Subgraph With the Required Paths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed binary string floor , which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen . You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum . Carpets may overlap one another. Return the minimum number of white tiles still visible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "floor[i] = '0' denotes that the i th tile of the floor is colored black .", + "On the other hand, floor[i] = '1' denotes that the i th tile of the floor is colored white ." + ], + "examples": [ + { + "text": "Example 1: Input:floor = \"10110101\", numCarpets = 2, carpetLen = 2Output:2Explanation:The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex1-1.png" + }, + { + "text": "Example 2: Input:floor = \"11111\", numCarpets = 2, carpetLen = 3Output:0Explanation:The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n Map cache;\n \n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n cache = new HashMap<>();\n return helper(floor, 0, numCarpets, carpetLen);\n }\n \n public int helper(String floor, int position, int numCarpets, int carpetLen) {\n if (position >= floor.length()) {\n return 0;\n }\n \n if (floor.length() - position <= numCarpets * carpetLen) {\n return 0;\n }\n \n String key = position + \", \" + numCarpets;\n if (cache.containsKey(key)) {\n return cache.get(key);\n }\n \n if (numCarpets == 0) {\n int output = floor.charAt(position) - '0' + helper(floor, position + 1, 0, carpetLen);\n \n cache.put(key, output);\n return output;\n }\n \n int output = Math.min(floor.charAt(position) - '0' + helper(floor, position + 1, numCarpets, carpetLen), helper(floor, position + carpetLen, numCarpets - 1, carpetLen));\n \n cache.put(key, output);\n return output;\n }\n}\n", + "title": "2209. Minimum White Tiles After Covering With Carpets", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed binary string floor , which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen . You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum . Carpets may overlap one another. Return the minimum number of white tiles still visible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "floor[i] = '0' denotes that the i th tile of the floor is colored black .", + "On the other hand, floor[i] = '1' denotes that the i th tile of the floor is colored white ." + ], + "examples": [ + { + "text": "Example 1: Input:floor = \"10110101\", numCarpets = 2, carpetLen = 2Output:2Explanation:The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex1-1.png" + }, + { + "text": "Example 2: Input:floor = \"11111\", numCarpets = 2, carpetLen = 3Output:0Explanation:The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.", + "image": "https://assets.leetcode.com/uploads/2022/02/10/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n\t\tn = len(floor)\n\t\t#Using memo table to store predefined computations\n memo = [[-1 for x in range(numCarpets+1)] for x in range(len(floor)+1)] \n def solve(N,numCarpets):\n\t\t\t#Base Case\n if N>=n:\n return 0\n\t\t\t#If calculated previously use that solution\n if memo[N][numCarpets]!=-1:\n return memo[N][numCarpets]\n\t\t\t\t\n used = 0 # If you use the carpet\n notused = 0 # If you donot use the carpet\n\t\t\t\n if floor[N]=='1': # We might use the carpet in this part\n if numCarpets>0: #Whether we even have some carpets or not\n\t\t\t\t \"\"\"\n\t\t\t\t\tOptimization Part\n\t\t\t\t\tWe are finding the number of ones present in this part of the floor.\n\t\t\t\t\tprefix[lastInd] - Number of ones till lastInd\n\t\t\t\t\tprefix[N] - Number of ones till Nth Index.\n\t\t\t\t\t\n\t\t\t\t\tTheir difference gives us how many ones present between the two.\n\t\t\t\t \"\"\"\n lastInd = min(N+carpetLen,len(floor)) \n ans = prefix[lastInd] - prefix[N]\n \n\t\t\t\t\t\"\"\"\n\t\t\t\t\tFind the max if we use or donot use carpet at this index\n\t\t\t\t\tIf we do we add --- ans and decrement remaining carpets\n\t\t\t\t\telse we donot\n\t\t\t\t\t\"\"\"\n used = max(solve(N+carpetLen,numCarpets-1)+ans,solve(N+1,numCarpets))\n \n else:\n used = 0\n \n else:\n\t\t\t#If we donot use the carpet although I feel this might be redundant code\n notused = solve(N+1,numCarpets)\n \n\t\t\t#Using max function to find the number of white tiles removed\n memo[N][numCarpets] = max(used,notused)\n return memo[N][numCarpets]\n\t\t\n\t\t#Total White tiles\n ones = 0\n for x in floor:\n if x == '1':\n ones+=1\n \n\t\t#Using Prefix array to store number of ones till i th index\n prefix = [0]*(n+1)\n for i in range(1,n+1):\n if floor[i-1]=='1':\n prefix[i] = prefix[i-1]+1\n else:\n prefix[i] = prefix[i-1]\n\t\t\t\t\n \n removed = solve(0,numCarpets)\n \n return ones-removed\n", + "title": "2209. Minimum White Tiles After Covering With Carpets", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 . A substring is a contiguous sequence of characters within the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"Output:\"BANC\"Explanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"Output:\"a\"Explanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"Output:\"\"Explanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 16.21%) | Memory: 43.4 MB (Top 87.12%)\nclass Solution {\n public String minWindow(String s, String t) {\n HashMap child = new HashMap<>();\n HashMap parent = new HashMap<>();\n\n int left = -1, right = -1, match = 0;\n String window = \"\";\n\n for(int i = 0; i < t.length(); i++){\n char c = t.charAt(i);\n child.put(c, child.getOrDefault(c, 0) + 1); //Child frequency map\n }\n\n while(true){\n boolean f1 = false, f2 = false;\n\n while(right < s.length() - 1 && match < t.length()){\n right++;\n char c = s.charAt(right);\n parent.put(c, parent.getOrDefault(c, 0) + 1); // Acquiring characters till\n if(parent.getOrDefault(c, 0) <= child.getOrDefault(c, 0)) // match count is equal\n match++;\n\n f1 = true;\n }\n while(left < right && match == t.length()){\n String potstring = s.substring(left + 1, right + 1);\n if(window.length() == 0 || window.length() > potstring.length())\n window = potstring; //Calculating length of window\n\n left++;\n char c = s.charAt(left);\n parent.put(c, parent.getOrDefault(c, 0) - 1);\n if(parent.get(c) == 0) //Releasing characters by\n parent.remove(c); //left pointer for finding smallest window\n\n if(parent.getOrDefault(c, 0) < child.getOrDefault(c, 0))\n match--;\n\n f2 = true;\n }\n\n if(f1 == false && f2 == false)\n break;\n }\n\n return window;\n }\n}", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . A substring is a contiguous sequence of characters within the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"Output:\"BANC\"Explanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"Output:\"a\"Explanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"Output:\"\"Explanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "# Added on 2022-08-18 15:51:55.963915\n\nvar minWindow = function(s, t) {\n const tf = {}, sf = {};\n for(let c of t) {\n tf[c] = (tf[c] || 0) + 1;\n }\n let l = 0, r = 0, rs = t.length;\n let ml = -1, mr = -1;\n for(; r < s.length; r++) {\n const c = s[r];\n\n if(!tf[c]) continue;\n\n const sc = sf[c] || 0;\n sf[c] = sc + 1;\n if(sf[c] <= tf[c]) {\n rs--;\n }\n\n if(rs == 0) {\n while(true) {\n if(mr == -1 || mr - ml > r - l) {\n [mr, ml] = [r, l];\n }\n\n const c = s[l];\n if(!tf[c]) {\n l++;\n }\n else if(sf[c] - 1 < tf[c]) {\n sf[c]--, l++, rs++;\n break;\n } else {\n sf[c]--;\n l++;\n }\n }\n }\n }\n if(mr == -1) return '';\n return s.slice(ml, mr + 1);\n};", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 of length n . The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) ( 0-indexed ). Rearrange the elements of nums2 such that the resulting XOR sum is minimized . Return the XOR sum after the rearrangement . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [2,3]Output:2Explanation:Rearrangenums2so that it becomes[3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,0,3], nums2 = [5,3,4]Output:8Explanation:Rearrangenums2so that it becomes[5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "\n\nclass Solution {\n Integer[][] cache;\n \n public int minimumXORSum(int[] nums1, int[] nums2) {\n int n = nums1.length;\n \n cache = new Integer[n][1 << n];\n\n return getMinXorSum(0, 0, nums1, nums2);\n }\n \n \n private int getMinXorSum(int index, int mask, int[] nums1, int[] nums2){\n if(index == nums1.length) return 0;\n \n //retrieve from cache\n if(cache[index][mask] != null) return cache[index][mask];\n \n //find minimum \n int minXorSum = Integer.MAX_VALUE;\n\n for(int i = 0; i < nums2.length; i++){\n if((mask >> i & 1) == 1) continue;\n \n int xorSum = (nums1[index] ^ nums2[i]) + getMinXorSum(index + 1, mask | (1 << i), nums1, nums2);\n \n //update minimum xor sum\n minXorSum = Math.min(xorSum, minXorSum);\n }\n \n //store in cache\n cache[index][mask] = minXorSum;\n \n return minXorSum;\n }\n \n}\n", + "title": "1879. Minimum XOR Sum of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 of length n . The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) ( 0-indexed ). Rearrange the elements of nums2 such that the resulting XOR sum is minimized . Return the XOR sum after the rearrangement . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2], nums2 = [2,3]Output:2Explanation:Rearrangenums2so that it becomes[3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,0,3], nums2 = [5,3,4]Output:8Explanation:Rearrangenums2so that it becomes[5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumXORSum(self, a: List[int], b: List[int]) -> int:\n @cache\n def dp(mask: int) -> int:\n i = bin(mask).count(\"1\")\n if i >= len(a):\n return 0\n return min((a[i] ^ b[j]) + dp(mask + (1 << j)) \n for j in range(len(b)) if mask & (1 << j) == 0)\n return dp(0)\n", + "title": "1879. Minimum XOR Sum of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0 , 1 , and 2 . The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0 th receptor. Given the two integers p and q , return the number of the receptor that the ray meets first . The test cases are guaranteed so that the ray will meet a receptor eventually. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= q <= p <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:p = 2, q = 1Output:2Explanation:The ray meets receptor 2 the first time it gets reflected back to the left wall.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png" + }, + { + "text": "Example 2: Input:p = 3, q = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution {\n public int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0){\n p >>= 1; q >>= 1;\n }\n return 1 - p % 2 + q % 2;\n }\n};\n", + "title": "858. Mirror Reflection", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0 , 1 , and 2 . The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0 th receptor. Given the two integers p and q , return the number of the receptor that the ray meets first . The test cases are guaranteed so that the ray will meet a receptor eventually. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= q <= p <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:p = 2, q = 1Output:2Explanation:The ray meets receptor 2 the first time it gets reflected back to the left wall.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png" + }, + { + "text": "Example 2: Input:p = 3, q = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n\n L = lcm(p,q)\n\n if (L//q)%2 == 0:\n return 2\n\n return (L//p)%2", + "title": "858. Mirror Reflection", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "0 <= nums[i] <= n", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,0,1]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 3: Input:nums = [9,6,4,2,3,5,7,0,1]Output:8Explanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "// Approach 1: Find diff\n\nclass Solution {\n public int missingNumber(int[] nums) {\n int n = nums.length;\n int expectedSum = (n * (n + 1)) / 2;\n for (int num : nums)\n expectedSum -= num;\n return expectedSum;\n }\n}\n\n// Approach 2: XOR\nclass Solution {\n public int missingNumber(int[] nums) {\n int xor1 = 0;\n for (int i = 1; i <= nums.length; i++)\n xor1 = xor1 ^ i;\n\n int xor2 = 0;\n for (int num : nums)\n xor2 = xor2 ^ num;\n return xor1 ^ xor2;\n }\n}\n\n// Approach 3: Cyclic sort\nclass Solution {\n public int missingNumber(int[] nums) {\n \n int i = 0;\n while (i < nums.length) {\n\n if (nums[i] != i && nums[i] < nums.length)\n swap(i, nums[i], nums);\n else\n i += 1;\n }\n \n for (int j = 0; j < nums.length; j++) {\n if (nums[j] != j)\n return j;\n }\n return nums.length;\n }\n \n private void swap(int i, int j, int[] nums) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}\n", + "title": "268. Missing Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "0 <= nums[i] <= n", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,0,1]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 3: Input:nums = [9,6,4,2,3,5,7,0,1]Output:8Explanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def missingNumber(self, nums: List[int]) -> int:\n # T.C = O(n) S.C = O(1)\n actualsum = 0\n currentsum = 0\n i = 1\n for num in nums:\n currentsum += num\n actualsum += i\n i += 1\n \n return actualsum - currentsum", + "title": "268. Missing Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y . Given an integer n , return the largest number that is less than or equal to n with monotone increasing digits . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:9", + "image": null + }, + { + "text": "Example 2: Input:n = 1234Output:1234", + "image": null + }, + { + "text": "Example 3: Input:n = 332Output:299", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.5%) | Memory: 38.98 MB (Top 97.6%)\n\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int position;\n int digitInTheNextPosition;\n while ((position = getThePositionNotSatisfied(n)) != -1) {\n digitInTheNextPosition = ((int) (n / Math.pow(10, position - 1))) % 10;\n n -= Math.pow(10, position - 1) * (digitInTheNextPosition + 1);\n n -= n % Math.pow(10, position);\n n += Math.pow(10, position) - 1;\n }\n return n;\n }\n\n public int getThePositionNotSatisfied(int n) {\n int k = 10;\n int position = 0;\n while (n > 0) {\n if (k < n % 10) {\n return position;\n } else {\n k = n % 10;\n n /= 10;\n position++;\n }\n }\n return -1;\n }\n}", + "title": "738. Monotone Increasing Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y . Given an integer n , return the largest number that is less than or equal to n with monotone increasing digits . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:9", + "image": null + }, + { + "text": "Example 2: Input:n = 1234Output:1234", + "image": null + }, + { + "text": "Example 3: Input:n = 332Output:299", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 43 ms (Top 69.04%) | Memory: 13.9 MB (Top 20.57%)\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n num = list(str(n))\n for i in range(len(num)-1):\n # Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return\n # However, there is the case that num[i-1]==num[i], which will make num[i]-1 num[i+1]:\n while i >= 1 and num[i-1] == num[i]:\n i -= 1\n num[i] = chr(ord(num[i])-1)\n return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))\n return n", + "title": "738. Monotone Increasing Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j , nums[i] <= nums[j] . An array nums is monotone decreasing if for all i <= j , nums[i] >= nums[j] . Given an integer array nums , return true if the given array is monotonic, or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3]Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,4]Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,2]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 51.45%) | Memory: 92.5 MB (Top 78.69%)\nclass Solution {\n public boolean isMonotonic(int[] nums) {\n if(nums[0]=nums[i+1])) return false;\n }\n }\n return true;\n }\n}", + "title": "896. Monotonic Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j , nums[i] <= nums[j] . An array nums is monotone decreasing if for all i <= j , nums[i] >= nums[j] . Given an integer array nums , return true if the given array is monotonic, or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,3]Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [6,5,4,4]Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,2]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] >= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] <= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n return False\n", + "title": "896. Monotonic Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array items where items[i] = [price i , beauty i ] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries . For each queries[j] , you want to determine the maximum beauty of an item whose price is less than or equal to queries[j] . If no such item exists, then the answer to this query is 0 . Return an array answer of the same length as queries where answer[j] is the answer to the j th query . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= items.length, queries.length <= 10^5", + "items[i].length == 2", + "1 <= price i , beauty i , queries[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]Output:[2,4,5,5,6,6]Explanation:- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.", + "image": null + }, + { + "text": "Example 2: Input:items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]Output:[4]Explanation:The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty.", + "image": null + }, + { + "text": "Example 3: Input:items = [[10,1000]], queries = [5]Output:[0]Explanation:No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maximumBeauty(int[][] items, int[] queries) {\n int[] ans = new int[queries.length];\n Arrays.sort(items, (a, b) -> (a[0] - b[0]));\n int maxBeautySoFar = Integer.MIN_VALUE;\n int[] maxBeauty = new int[items.length];\n \n for(int i = 0; i < items.length; i++) {\n if(maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];\n maxBeauty[i] = maxBeautySoFar;\n }\n \n for(int i = 0; i < queries.length; i++) {\n int idx = findLargestIdxWithPriceLessThan(items, queries[i]);\n if(idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];\n }\n return ans;\n }\n \n public int findLargestIdxWithPriceLessThan(int[][] items, int price) {\n int l = 0;\n int r = items.length - 1;\n int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE; \n while(l <= r) {\n int mid = (l + r)/2;\n if(items[mid][0] > price) {\n r = mid - 1;\n } else {\n maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);\n l = mid + 1;\n }\n }\n return maxIdxLessThanEqualToPrice;\n }\n}", + "title": "2070. Most Beautiful Item for Each Query", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D integer array items where items[i] = [price i , beauty i ] denotes the price and beauty of an item respectively. You are also given a 0-indexed integer array queries . For each queries[j] , you want to determine the maximum beauty of an item whose price is less than or equal to queries[j] . If no such item exists, then the answer to this query is 0 . Return an array answer of the same length as queries where answer[j] is the answer to the j th query . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= items.length, queries.length <= 10^5", + "items[i].length == 2", + "1 <= price i , beauty i , queries[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]Output:[2,4,5,5,6,6]Explanation:- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.", + "image": null + }, + { + "text": "Example 2: Input:items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]Output:[4]Explanation:The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty.", + "image": null + }, + { + "text": "Example 3: Input:items = [[10,1000]], queries = [5]Output:[0]Explanation:No item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2544 ms (Top 32.35%) | Memory: 73.6 MB (Top 48.94%)\nclass Solution:\n def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n\n items.sort()\n dic = dict()\n res = []\n gmax = 0\n for p,b in items:\n gmax = max(b,gmax)\n dic[p] = gmax\n\n keys = sorted(dic.keys())\n for q in queries:\n ind = bisect.bisect_left(keys,q)\n if ind hm = new HashMap<>();\n String[] words = paragraph.replaceAll(\"[!?',;.]\",\" \").toLowerCase().split(\"\\\\s+\");\n for(int i=0; i str:\n #sunday morning hangover solution haha\n \n #calling this twice seems unnecesary but whatevs\n #replace \",\" with \" \" (apparently translate() is much quicker than replace)\n para = paragraph.translate(str.maketrans(\",\",\" \"))\n #strip out rest of punctuation and make it lower case\n para = para.translate(str.maketrans(' ', ' ', string.punctuation)).lower()\n #split on the sapces\n para = para.split()\n #staple counter function\n para_count = Counter(para)\n #loop thru banned words, if they're in para_count pop the off\n for word in banned:\n if word in para_count:\n para_count.pop(word)\n #return val from most common\n return para_count.most_common(1)[0][0]\n", + "title": "819. Most Common Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . You are also given an integer key , which is present in nums . For every unique integer target in nums , count the number of times target immediately follows an occurrence of key in nums . In other words, count the number of indices i such that: Return the target with the maximum count . The test cases will be generated such that the target with maximum count is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i <= nums.length - 2 ,", + "nums[i] == key and,", + "nums[i + 1] == target ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,100,200,1,100], key = 1Output:100Explanation:For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,3], key = 2Output:2Explanation:For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 55.1%) | Memory: 43.05 MB (Top 60.9%)\n\nclass Solution {\n public int mostFrequent(int[] nums, int key) {\n int n=nums.length;\n HashMap map=new HashMap<>();\n for(int i=0;imax){\n re=x;\n max=map.get(x);\n }\n }\n return re;\n }\n}", + "title": "2190. Most Frequent Number Following Key In an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums . You are also given an integer key , which is present in nums . For every unique integer target in nums , count the number of times target immediately follows an occurrence of key in nums . In other words, count the number of indices i such that: Return the target with the maximum count . The test cases will be generated such that the target with maximum count is unique. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i <= nums.length - 2 ,", + "nums[i] == key and,", + "nums[i + 1] == target ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,100,200,1,100], key = 1Output:100Explanation:For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,3], key = 2Output:2Explanation:For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 90 ms (Top 49.1%) | Memory: 16.67 MB (Top 9.2%)\n\nclass Solution:\n def mostFrequent(self, nums: List[int], key: int) -> int:\n l = [t for k,t in zip(nums, nums[1:]) if k == key]\n return max(set(l), key = l.count)", + "title": "2190. Most Frequent Number Following Key In an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the most frequent subtree sum . If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,2,-3]Output:[2,-3,4]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,2,-5]Output:[2]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 14.50%) | Memory: 44.9 MB (Top 83.15%)\nclass Solution {\n public int[] findFrequentTreeSum(TreeNode root) {\n\n HashMap map=new HashMap<>();\n int sum=sum(root,map);\n int max=0;\n int count=0;\n for(Integer key:map.keySet()){\n max=Math.max(max,map.get(key));\n }\n\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n count++;\n }\n }\n int[] ans=new int[count];\n int counter=0;\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n ans[counter++]=key;\n }\n }\n\n return ans;\n\n }\n public int sum(TreeNode root,HashMap map){\n if(root==null)return 0;\n int lh=sum(root.left,map);\n int rh=sum(root.right,map);\n map.put(lh+rh+root.val,map.getOrDefault(lh+rh+root.val,0)+1);\n return lh+rh+root.val;\n }\n}", + "title": "508. Most Frequent Subtree Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree, return the most frequent subtree sum . If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,2,-3]Output:[2,-3,4]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,2,-5]Output:[2]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n def dfs(root):\n \n if not root: return 0\n \n l = dfs(root.left)\n r = dfs(root.right)\n res = root.val + l + r\n \n d[res] += 1\n return res\n \n d = collections.Counter()\n dfs(root)\n maxi = max(d.values())\n return [i for i in d if d[i] == maxi]\n \n\t\t# An Upvote will be encouraging\n \n \n", + "title": "508. Most Frequent Subtree Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n jobs and m workers. You are given three arrays: difficulty , profit , and worker where: Every worker can be assigned at most one job , but one job can be completed multiple times . Return the maximum profit we can achieve after assigning the workers to the jobs. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "difficulty[i] and profit[i] are the difficulty and the profit of the i th job, and", + "worker[j] is the ability of j th worker (i.e., the j th worker can only complete a job with difficulty at most worker[j] )." + ], + "examples": [ + { + "text": "Example 1: Input:difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]Output:100Explanation:Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.", + "image": null + }, + { + "text": "Example 2: Input:difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 67 ms (Top 34.79%) | Memory: 60.8 MB (Top 55.99%)\nclass Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(b[1]-a[1]));\n for(int i=0;i=0 && !pq.isEmpty();i--)\n {\n if(worker[i]>=pq.peek()[0])\n p=p+pq.peek()[1];\n else\n {\n while(!pq.isEmpty() && worker[i] O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans", + "title": "826. Most Profit Assigning Work", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [x i , y i ] represents the location of the i th stone, return the largest possible number of stones that can be removed . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 1000", + "0 <= x i , y i <= 10^4", + "No two stones are at the same coordinate point." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]Output:5Explanation:One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 2: Input:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]Output:3Explanation:One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 3: Input:stones = [[0,0]]Output:0Explanation:[0,0] is the only stone on the plane, so you cannot remove it.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 33.32%) | Memory: 48.7 MB (Top 77.91%)\nclass Solution {\n public int removeStones(int[][] stones) {\n int ret=0;\n DisjointSet ds=new DisjointSet(stones.length);\n\n for(int i=0;ireturn size in negative\n public int union(int idx1, int idx2) {\n int p1=find(idx1);\n int p2=find(idx2);\n\n if(p1==p2) { //same parent so directly returning size\n return sets[p1];\n }else {\n int w1=Math.abs(sets[p1]);\n int w2=Math.abs(sets[p2]);\n\n if(w1>w2) {\n sets[p2]=p1;\n\n //collapsing FIND\n sets[idx1]=p1;\n sets[idx2]=p1;\n\n return sets[p1]=-(w1+w2);\n }else {\n sets[p1]=p2;\n\n //collapsing FIND\n sets[idx1]=p2;\n sets[idx2]=p2;\n\n return sets[p2]=-(w1+w2);\n }\n }\n }\n\n // collapsing FIND\n //find parent\n public int find(int idx) {\n int p=idx;\n while(sets[p]>=0) {\n p=sets[p];\n }\n return p;\n }\n }\n}", + "title": "947. Most Stones Removed with Same Row or Column", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [x i , y i ] represents the location of the i th stone, return the largest possible number of stones that can be removed . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 1000", + "0 <= x i , y i <= 10^4", + "No two stones are at the same coordinate point." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]Output:5Explanation:One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 2: Input:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]Output:3Explanation:One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.", + "image": null + }, + { + "text": "Example 3: Input:stones = [[0,0]]Output:0Explanation:[0,0] is the only stone on the plane, so you cannot remove it.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 187 ms (Top 84.32%) | Memory: 18.9 MB (Top 5.06%)\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n def dfs(row,col):\n if seen[(row,col)]:\n return 0\n seen[(row,col)] = True\n for r,c in tableRow[row]:\n dfs(r,c)\n for r,c in tableCol[col]:\n dfs(r,c)\n return 1\n\n tableRow, tableCol = {},{}\n for row,col in stones:\n if row not in tableRow:\n tableRow[row] = set()\n if col not in tableCol:\n tableCol[col] = set()\n tableRow[row].add((row,col))\n tableCol[col].add((row,col))\n\n count,seen= 0, {(row,col):False for row,col in stones}\n for row,col in stones:\n count += dfs(row,col)\n return abs(len(stones)-count)", + "title": "947. Most Stones Removed with Same Row or Column", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n and an integer array rounds . We have a circular track which consists of n sectors labeled from 1 to n . A marathon will be held on this track, the marathon consists of m rounds. The i th round starts at sector rounds[i - 1] and ends at sector rounds[i] . For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= m <= 100", + "rounds.length == m + 1", + "1 <= rounds[i] <= n", + "rounds[i] != rounds[i + 1] for 0 <= i < m" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, rounds = [1,3,1,2]Output:[1,2]Explanation:The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/tmp.jpg" + }, + { + "text": "Example 2: Input:n = 2, rounds = [2,1,2,1,2,1,2,1,2]Output:[2]", + "image": null + }, + { + "text": "Example 3: Input:n = 7, rounds = [1,3,5,7]Output:[1,2,3,4,5,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.10 MB (Top 12.5%)\n\nclass Solution {\n public List mostVisited(int n, int[] rounds) {\n var start = rounds[0];\n var end = rounds[rounds.length - 1]; \n var res = new ArrayList();\n if (start <= end) {\n for (int i = start; i <= end; i++) res.add(i);\n } else {\n for (int i = 1; i <= end; i++) res.add(i);\n for (int i = start; i <= n; i++) res.add(i);\n }\n return res;\n }\n}\n", + "title": "1560. Most Visited Sector in a Circular Track", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer n and an integer array rounds . We have a circular track which consists of n sectors labeled from 1 to n . A marathon will be held on this track, the marathon consists of m rounds. The i th round starts at sector rounds[i - 1] and ends at sector rounds[i] . For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 100", + "1 <= m <= 100", + "rounds.length == m + 1", + "1 <= rounds[i] <= n", + "rounds[i] != rounds[i + 1] for 0 <= i < m" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, rounds = [1,3,1,2]Output:[1,2]Explanation:The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.", + "image": "https://assets.leetcode.com/uploads/2020/08/14/tmp.jpg" + }, + { + "text": "Example 2: Input:n = 2, rounds = [2,1,2,1,2,1,2,1,2]Output:[2]", + "image": null + }, + { + "text": "Example 3: Input:n = 7, rounds = [1,3,5,7]Output:[1,2,3,4,5,6,7]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n hash_map = {}\n for i in range(0 , len(rounds)-1):\n if i == 0:\n start = rounds[i]\n elif rounds[i] == n:\n start = 1\n else:\n start = rounds[i] + 1\n end = rounds[i+1]\n if start <= end:\n for i in range(start , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n else:\n for i in range(start , n + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n for i in range(1 , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n k = list(hash_map.keys())\n v = list(hash_map.values())\n ans = []\n m = -1\n i = 0\n j = 0\n while i < len(k) and j < len(v):\n if len(ans) == 0:\n ans.append(k[i])\n m = v[j]\n elif m < v[j]:\n ans = []\n ans.append(k[i])\n m = v[j]\n elif m == v[j]:\n ans.append(k[i])\n i += 1\n j += 1\n ans = sorted(ans)\n return ans\n\n", + "title": "1560. Most Visited Sector in a Circular Track", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings start and target , both of length n . Each string consists only of the characters 'L' , 'R' , and '_' where: Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.", + "The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"_L__R__R_\", target = \"L______RR\"Output:trueExplanation:We can obtain the string target from start by doing the following moves:\n- Move the first piece one step to the left, start becomes equal to \"L___R__R_\".\n- Move the last piece one step to the right, start becomes equal to \"L___R___R\".\n- Move the second piece three steps to the right, start becomes equal to \"L______RR\".\nSince it is possible to get the string target from start, we return true.", + "image": null + }, + { + "text": "Example 2: Input:start = \"R_L_\", target = \"__LR\"Output:falseExplanation:The 'R' piece in the string start can move one step to the right to obtain \"_RL_\".\nAfter that, no pieces can move anymore, so it is impossible to obtain the string target from start.", + "image": null + }, + { + "text": "Example 3: Input:start = \"_R\", target = \"R_\"Output:falseExplanation:The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 303 ms (Top 21.43%) | Memory: 21.30 MB (Top 33.04%)\n\nclass Solution:\n def canChange(self, A: str, B: str) -> bool:\n P = lambda c : c != '_'\n I = lambda s,x : [i for i,c in enumerate(s) if c==x]\n G = lambda d,p : all( p(x,y) for x,y in zip( I(A,d), I(B,d) ) )\n S = lambda : [*filter(P,A)] == [*filter(P,B)]\n return S() and G('L', ge) and G('R', le)\n\t\t# 1. 2. 3.\n", + "title": "2337. Move Pieces to Obtain a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , move all 0 's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,3,12]Output:[1,3,12,0,0]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.0%) | Memory: 46.20 MB (Top 23.08%)\n\nclass Solution {\n public void moveZeroes(int[] nums) {\n int i = 0; \n for (int num:nums){\n if(num != 0){\n nums[i] = num;\n i++;\n }\n }\n while(i None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n\n \"\"\"\n notzero = 0\n zero = 0\n\n while notzero < len(nums):\n if nums[notzero] != 0:\n nums[zero] , nums[notzero] = nums[notzero], nums[zero]\n zero += 1\n notzero += 1", + "title": "283. Move Zeroes", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are three stones in different positions on the X-axis. You are given three integers a , b , and c , the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x , y , and z with x < y < z . You pick up the stone at either position x or position z , and move that stone to an integer position k , with x < k < z and k != y . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "answer[0] is the minimum number of moves you can play, and", + "answer[1] is the maximum number of moves you can play ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2, c = 5Output:[1,2]Explanation:Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 3, c = 2Output:[0,0]Explanation:We cannot make any moves.", + "image": null + }, + { + "text": "Example 3: Input:a = 3, b = 5, c = 1Output:[1,2]Explanation:Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.75%) | Memory: 41.9 MB (Top 57.50%)\nclass Solution {\n public int[] numMovesStones(int a, int b, int c) {\n int[] arr ={a,b,c};\n int[] arr2 = {a,b,c};\n int maximum = findMaximum(arr);\n int minimum = findMinimum(maximum,arr2);\n return new int[]{minimum,maximum};\n }\n public int findMaximum(int[] arr){\n Arrays.sort(arr);\n int count = 0;\n if(arr[0] == (arr[1]-1) && arr[1] == (arr[2] -1) ) return count;\n if(arr[0] == arr[1]-1){\n arr[2]--;\n count++;\n }\n else{\n arr[0]++;\n count++;\n }\n return count + findMaximum(arr);\n\n }\n\n public int findMinimum(int max,int[] arr){\n Arrays.sort(arr);\n if(max == 0) return 0;\n else if(Math.abs(arr[0]-arr[1]) >2 && Math.abs(arr[1]-arr[2]) >2 ) return 2;\n else return 1;\n }\n}", + "title": "1033. Moving Stones Until Consecutive", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are three stones in different positions on the X-axis. You are given three integers a , b , and c , the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x , y , and z with x < y < z . You pick up the stone at either position x or position z , and move that stone to an integer position k , with x < k < z and k != y . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where : Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "answer[0] is the minimum number of moves you can play, and", + "answer[1] is the maximum number of moves you can play ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2, c = 5Output:[1,2]Explanation:Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 3, c = 2Output:[0,0]Explanation:We cannot make any moves.", + "image": null + }, + { + "text": "Example 3: Input:a = 3, b = 5, c = 1Output:[1,2]Explanation:Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a,b,c = sorted([a,b,c])\n d1 = abs(b-a)-1 \n d2 = abs(c-b)-1\n mi = 2\n if d1 == 0 and d2 == 0: mi = 0\n elif d1 <= 1 or d2 <= 1: mi =1 \n ma = c - a - 2\n return [mi,ma]", + "title": "1033. Moving Stones Until Consecutive", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are some stones in different positions on the X-axis. You are given an integer array stones , the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "In particular, if the stones are at say, stones = [1,2,5] , you cannot move the endpoint stone at position 5 , since moving it to any position (such as 0 , or 3 ) will still keep that stone as an endpoint stone." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [7,4,9]Output:[1,2]Explanation:We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [6,5,4,3,10]Output:[2,3]Explanation:We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.", + "image": null + } + ], + "follow_up": null, + "solution": "\tclass Solution {\n\t\tpublic int[] numMovesStonesII(int[] stones) {\n\t\t\tint n = stones.length;\n\t\t\t int[] ans = new int[2];\n\t\t\t int i = 0, j = 0, wsize, scount, minMoves = Integer.MAX_VALUE;\n\t\t\tArrays.sort(stones);\n\t\t\t while (j < n) {\n\t\t\t\twsize = stones[j] - stones[i] + 1;\n\t\t\t\tscount = j - i + 1;\n\n\t\t\t\tif (wsize > n) {\n\t\t\t\t\ti++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (wsize == n - 1 && scount == n - 1)\n\t\t\t\t\tminMoves = Math.min(minMoves, 2);\n\n\t\t\t\telse minMoves = Math.min(minMoves, n - scount);\n\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tans[0] = minMoves;\n\t\t\tint maxMoves = 0;\n\t\t\t if (stones[1] == stones[0] + 1 || stones[n - 1] == stones[n - 2] + 1)\n\t\t\t\tmaxMoves = stones[n - 1] - stones[0] + 1 - n;\n\t\t\telse \n\t\t\t\tmaxMoves = Math.max(((stones[n - 1] - stones[1]) - (n - 1) + 1), ((stones[n - 2] - stones[0]) - (n - 1) + 1));\n\n\t\t\tans[1] = maxMoves;\n\t\t\treturn ans;\n\t\t}\n\t}", + "title": "1040. Moving Stones Until Consecutive II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are some stones in different positions on the X-axis. You are given an integer array stones , the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone . The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "In particular, if the stones are at say, stones = [1,2,5] , you cannot move the endpoint stone at position 5 , since moving it to any position (such as 0 , or 3 ) will still keep that stone as an endpoint stone." + ], + "examples": [ + { + "text": "Example 1: Input:stones = [7,4,9]Output:[1,2]Explanation:We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [6,5,4,3,10]Output:[2,3]Explanation:We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 100 ms (Top 85.48%) | Memory: 18.80 MB (Top 11.29%)\n\nclass Solution:\n '''\n Test cases walk through \n Given 7, 4, 9 prove 1, 2 6, 5, 4, 3, 10, prove 2, 3 \n\n Sort stones -> 4, 7, 9 3, 4, 5, 6, 10 \n Stone length -> 3 5\n Move penultimate = 7 - 4 - 3 + 2 = 2 6-3-5+2 = 0 \n Move final = 9 - 7 - 3 + 2 = 1 10-4-5+2 = 3 \n Neither is 0, so we cannot return for sure Move penultimate is 0, so move final is assured \n This means we can return [min(2, 3), 3] -> [2, 3]\n\n Max legal moves is 0 For completeness, max legal moves is 0, max moves is 3 \n starting index is 0 starting index is 0 \n\n Enumeration Enumeration\n index is 0, stone is 4 index is 0, stone is 3 \n stones[0] lte 4 - 3 ? No, skip while loop stones[0] lte 3 - 5 ? No, skip while \n max legal moves is min of (max of self and 0 - 0 + 1, most moves) max legal moves is min of (max of self and 0 - 0 + 1), max moves -> max legal moves is 1 \n -> max legal moves is 1 \n\n index is 1, stone is 7 index is 1, stone is 4 \n stones[0] <= 7 - 3 ? Yes, enter while stones[0] lte 4 - 5 ? No, skip while \n starting index is now 1 max legal moves is min of (max of self and 1 - 0 + 1), max moves -> max legal moves is 2\n stones[1] <= 7 - 3 ? No, skip while \n max legal moves -> min(max of self and 1 - 1 + 1), max_moves \n -> max legal moves is 1 index is 2, stone is 5 \n stones[0] lte 5 - 5 ? No skip while \n index is 2, stone is 9 max legal moves is min of (max of self and 2 - 0 + 1), max_moves -> max legal moves is 3 \n stones[1] <= 9 - 3 ? No, skip while \n max legal moves is min(max of self and 2-1 + 1), max_moves\n -> max legal moves is 2 index is 3, stone is 6 \n End enumeration stones[0] lte 6 - 5 ? No skip while \n max legal moves is min (max of self and 3 - 0 + 1), max_moves -> max legal moves is 3 \n Return [3 - 2, 2] -> [1, 2] checks out \n index is 4, stones is 10 \n stones[0] lte 10 - 5 ? Yes, enter while \n starting index is 1 \n stones[1] lte 10 - 5 ? Yes, enter while \n starting index is 2 \n stones[2] lte 10 - 5 ? Yes, enter while \n starting index is 3 \n max legal moves is min (max of self and 4 - 3 + 1), max moves -> max legal moves is 3 \n End enumeration\n\n Return [5 - 3, 3] -> [2, 3]\n '''\n def numMovesStonesII(self, stones: List[int]) -> List[int] :\n # order does not need to be maintained, so sorting is optimal \n stones.sort()\n # want to work within stone physical space since 10^9 >> 10^4 (stone weight vs length)\n stone_length = len(stones)\n # what is the cost of moving the second to last stone and the 0th stone? \n move_penultimate = stones[-2] - stones[0] - stone_length + 2 \n # what is the cost of moving the last stone and the 1st stone? \n move_final = stones[-1] - stones[1] - stone_length + 2 \n # in both of these, the cost is the positional exchange in stones along the stone length + 2 for the two stones moving \n # our most moves possible are the max of these two \n most_moves = max(move_penultimate, move_final)\n # since the stones are unique, if either is 0, the one that we have must be max legal moves \n # if move penultimate is 0, that means that the second largest stone less the least stone less the length + 2 is 0 \n # this means that the largest stone, which must be at least one larger than the largest, less the second to least stone which is at least one larger than the least stone less the length + 2 is move final \n # our minimal length is 3 \n # let a, b, c be stones in order \n # b - a - 3 + 2 = 0 -> b = a + 1 move penultimate \n # c - b - 3 + 2 = 0 -> b = c - 1 move final \n # c - 1 = a + 1 -> c = a + 2 \n # all stones must be at least 1 to 10^9 and are unique \n # so at minimum a is 1, b is 2 and c is 3 \n # in this case, move final is also 0 so we get 0, 0 \n # if a = 4, b = 5, c = 7 \n # 5 - 4 - 3 + 2 = 0 move penultimate is 0 \n # 7 - 5 - 3 + 2 -> 1 move ultimate is 1 \n # min legal moves is min of 2 and 1 -> min legal moves is 1 -> 1, 1 is returned \n # from this it can be seen that the movement of c relative to b impacts the return here when one is 0, and that if either is 0 it does not preclude the other. However it does entail a relation to 2 as most that min could become \n # this is because if most moves is greater than 2, we could always do the move alternate that was 0 in two steps. This is what locks in to place the ability to use 2 here as the min argument. \n if move_penultimate == 0 or move_final == 0 : \n min_legal_moves = min(2, most_moves)\n return [min_legal_moves, most_moves]\n # how many legal moves are there in sorted order? \n max_legal_moves = 0 \n # starting from 0th index \n starting_index = 0\n # enumerate each stone and index \n for index, stone in enumerate(stones) :\n # while the stone at starting index is lte this stone minus stone length (cost of a move) \n while stones[starting_index] <= stone - stone_length : \n # increment \n starting_index += 1\n # max legal moves is then set to maxima of self and indexed difference with 1 for 0 based indexing \n max_legal_moves = min(max(max_legal_moves, index - starting_index + 1), most_moves) \n # return length - max legal moves when in sorted order (your minimal move state) and most moves in sorted order \n return [stone_length - max_legal_moves, most_moves]\n", + "title": "1040. Moving Stones Until Consecutive II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"2\", num2 = \"3\"Output:\"6\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"123\", num2 = \"456\"Output:\"56088\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 37.52%) | Memory: 44.4 MB (Top 28.50%)\nclass Solution {\n public String multiply(String num1, String num2) {\n if(num1.equals(\"0\") || num2.equals(\"0\"))\n return \"0\";\n int[] arr=new int[num1.length()+num2.length()];\n\n int index=0;\n for(int i=num1.length()-1;i>=0;i--)\n {\n int carry=0;\n int column=0;\n for(int j=num2.length()-1;j>=0;j--)\n {\n int a=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');\n int temp=(arr[index+column]+carry+a);\n arr[index+column]=temp%10;\n carry=temp/10;\n column++;\n }\n if(carry!=0)\n {\n arr[index+column]=carry;\n }\n index++;\n }\n String ans=\"\";\n index=arr.length-1;\n while(arr[index]==0)\n {\n index--;\n }\n for(int i=index;i>=0;i--)\n {\n ans+=arr[i];\n }\n return ans;\n }\n}", + "title": "43. Multiply Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:num1 = \"2\", num2 = \"3\"Output:\"6\"", + "image": null + }, + { + "text": "Example 2: Input:num1 = \"123\", num2 = \"456\"Output:\"56088\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n def convertToInt(numStr):\n currNum = 0\n N = len(numStr)\n for i in range(N - 1, -1, -1):\n digit = ord(numStr[i]) - ord('0')\n currNum += pow(10, N-i-1) * digit\n \n return currNum\n \n n1 = convertToInt(num1)\n n2 = convertToInt(num2)\n return str(n1 * n2)\n \n", + "title": "43. Multiply Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking . A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendar class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendar() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendar\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [15, 25], [20, 30]]Output[null, true, false, true]ExplanationMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCalendar(object):\n def __init__(self):\n self.booking = []\n\n def book(self, start, end):\n for i, j in self.booking:\n if i < end and start < j:\n return False\n self.booking.append((start, end))\n return True\n", + "title": "729. My Calendar I", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 191 ms (Top 41.18%) | Memory: 44.60 MB (Top 39.41%)\n\n/*\nAlgorithm:\n--------------------------------------------------------------\n1. Have a TreeMap where the keys are the dates and values \n to those keys are the number of active events occuring on\n that date. This will keep the dates sorted according to \n the keys.\n2. During booking for a new event [start, end), number of\n events occuring on the start date increases by one and \n same for the end date decreases by one. Hence modify the \n map accordingly.\n3. Calculate a running sum `sum` which holds the count of\n events currently running at that time. \n4. If `sum` becomes more than or equal to 3, then remove that \n event and return `False`\n5. If this does not occur then return `True`.\n--------------------------------------------------------------\n*/\n\nclass MyCalendarTwo {\n Map map;\n public MyCalendarTwo() {\n map = new TreeMap();\n }\n public boolean book(int start, int end) {\n map.put(start, map.getOrDefault(start, 0)+1);\n map.put(end, map.getOrDefault(end, 0)-1);\n int sum=0;\n for(int val : map.values()){\n sum += val;\n if(sum >= 3){\n map.put(start, map.get(start)-1);\n map.put(end, map.get(end)+1);\n if(map.get(start) == 0)\n map.remove(start);\n return false;\n }\n }\n return true;\n }\n}\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "class MyCalendarTwo {\n private List bookings;\n private List doubleBookings;\n \n public MyCalendarTwo() {\n bookings = new ArrayList<>();\n doubleBookings = new ArrayList<>();\n }\n \n \n public boolean book(int start, int end) {\n for(int[] b : doubleBookings)\n {\n\t\t//condition to check for the overlaping\n if(start < b[1] && end > b[0])\n return false;\n }\n \n for(int[] b : bookings)\n {\n if(start < b[1] && end > b[0]) {\n doubleBookings.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});\n }\n }\n bookings.add(new int[]{start, end});\n return true;\n }\n}\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking . A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end) , the range of real numbers x such that start <= x < end . Implement the MyCalendarTwo class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendarTwo() Initializes the calendar object.", + "boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking . Otherwise, return false and do not add the event to the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, true, true, true, false, true, true]ExplanationMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 175 ms (Top 97.99%) | Memory: 17.50 MB (Top 58.54%)\n\nclass Node:\n def __init__(self, start, end, val):\n self.start = start\n self.end = end\n self.val = val\n self.left = None\n self.right = None\n \n def insertable(self, node):\n if node.end <= node.start:\n return True\n if node.end <= self.start:\n if not self.left:\n return True\n else:\n return self.left.insertable(node)\n elif node.start >= self.end:\n if not self.right:\n return True\n else:\n return self.right.insertable(node)\n else:\n if self.val == 1:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n if not self.left and not self.right:\n return True\n elif not self.left:\n return self.right.insertable(Node(rightS, rightE, 1))\n elif not self.right:\n return self.left.insertable(Node(leftS, leftE, 1))\n else:\n resL = self.left.insertable(Node(leftS, leftE, 1))\n resR = self.right.insertable(Node(rightS, rightE, 1))\n if resL and resR:\n return True\n return False\n else:\n return False\n\n def insert(self, node):\n if node.end <= node.start:\n return\n \n if node.end <= self.start:\n if not self.left:\n self.left = node\n else:\n self.left.insert(node)\n elif node.start >= self.end:\n if not self.right:\n self.right = node\n else:\n self.right.insert(node)\n else:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n self.val += 1\n self.start, self.end = leftE, rightS \n if not self.left and not self.right: \n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n elif not self.left:\n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right.insert(Node(rightS, rightE, 1))\n elif not self.right:\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n self.left.insert(Node(leftS, leftE, 1))\n else:\n self.left.insert(Node(leftS, leftE, 1))\n self.right.insert(Node(rightS, rightE, 1))\n return\n\n\nclass MyCalendarTwo:\n\n def __init__(self):\n self.root = None\n\n def book(self, start: int, end: int) -> bool:\n if not self.root:\n self.root = Node(start, end, 1)\n return True\n else:\n newNode = Node(start, end, 1)\n if self.root.insertable(newNode):\n self.root.insert(newNode)\n return True\n return False\n", + "title": "731. My Calendar II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A k -booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) You are given some events [start, end) , after each given event, return an integer k representing the maximum k -booking between all the previous events. Implement the MyCalendarThree class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendarThree() Initializes the object.", + "int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k -booking in the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, 1, 1, 2, 3, 3, 3]ExplanationMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\nmyCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 197 ms (Top 36.54%) | Memory: 54.3 MB (Top 59.44%)\nclass MyCalendarThree {\n\n TreeMap map;\n public MyCalendarThree() {\n map = new TreeMap<>();\n }\n\n public int book(int start, int end) {\n if(map.isEmpty()){\n map.put(start, 1);\n map.put(end,-1);\n return 1;\n }\n\n //upvote if you like the solution\n\n map.put(start, map.getOrDefault(start,0)+1);\n map.put(end, map.getOrDefault(end,0)-1);\n\n int res = 0;\n int sum = 0;\n for(Map.Entry e: map.entrySet()){\n sum += e.getValue();\n res = Math.max(res,sum);\n }\n\n return res;\n }\n}", + "title": "732. My Calendar III", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A k -booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.) You are given some events [start, end) , after each given event, return an integer k representing the maximum k -booking between all the previous events. Implement the MyCalendarThree class: Example 1:", + "description_images": [], + "constraints": [ + "MyCalendarThree() Initializes the object.", + "int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k -booking in the calendar." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]Output[null, 1, 1, 2, 3, 3, 3]ExplanationMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\nmyCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass MyCalendarThree:\n\n def __init__(self):\n self.events = [] \n\n def book(self, start: int, end: int) -> int:\n L, R = 1, 0\n bisect.insort(self.events, (start, L))\n bisect.insort(self.events, (end, R))\n res = 0\n cnt = 0\n for _, state in self.events:\n #if an interval starts, increase the counter\n #othewise, decreas the counter\n cnt += 1 if state == L else -1\n res = max(res, cnt)\n return res", + "title": "732. My Calendar III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n-ary tree, return the level order 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> result= new ArrayList();\n public List> levelOrder(Node root) {\n if(root==null) return result;\n helper(root,0);\n return result;\n }\n \n private void helper(Node node,int level){\n if(result.size()<=level){\n result.add(new ArrayList());\n }\n result.get(level).add(node.val);\n for(Node child:node.children){\n helper(child,level+1);\n }\n \n }\n}\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n-ary tree, return the level order 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n self.d=defaultdict(list)\n def check(root,ind):\n self.d[ind].append(root.val)\n if root.children:\n for x in root.children:\n check(x,ind+1)\n if root==None:\n return []\n check(root,0)\n l=[]\n for x in sorted(self.d.keys()):\n l.append(self.d[x])\n return l\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an n-ary tree, return the level order 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "constraints": [ + "The height of the n-ary tree is less than or equal to 1000", + "The total number of nodes is between [0, 10^4 ]" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[[1],[3,2,4],[5,6]]", + "image": null + }, + { + "text": "Example 2: 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:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n if not root:\n return []\n \n result = []\n level = [root]\n \n while level:\n current_level = []\n next_level = []\n \n for node in level:\n current_level.append(node.val)\n next_level += node.children\n \n result.append(current_level)\n level = next_level\n \n return result\n", + "title": "429. N-ary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n List result = new ArrayList<>();\n public List postorder(Node root) {\n addNodes(root);\n return result;\n }\n \n void addNodes(Node root) {\n if (root == null) return;\n for (Node child : root.children) addNodes(child);\n result.add(root.val);\n }\n}\n", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n ans=[]\n def post(root):\n nonlocal ans\n if not root:\n return\n for i in root.children:\n post(i)\n ans.append(root.val)\n post(root)\n return ans\n", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[5,6,3,2,4,1]", + "image": "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n\tdef postorder(self, root):\n\t\t\"\"\"\n\t\t:type root: Node\n\t\t:rtype: List[int]\n\t\t\"\"\"\n\t\tres=[]\n\t\tdef bfs(root):\n\t\t\tif root:\n\t\t\t\tfor child in root.children:\n\t\t\t\t\tbfs(child)\n\n\t\t\t\tres.append(root.val)\n\t\tbfs(root)\n\n\t\treturn res", + "title": "590. N-ary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of an n-ary tree, return the preorder 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[1,3,5,6,2,4]", + "image": null + }, + { + "text": "Example 2: 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:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List preorder(Node root) {\n if (root == null) return new ArrayList();\n \n Stack stk = new Stack();\n ArrayList arr = new ArrayList();\n stk.push(root);\n Node ref;\n while(!stk.empty()) {\n ref = stk.pop();\n // System.out.println(ref.val);\n arr.add(ref.val);\n for(int i=ref.children.size() - 1;i>=0;i--) {\n stk.push(ref.children.get(i));\n }\n }\n return arr;\n }\n}\n", + "title": "589. N-ary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of an n-ary tree, return the preorder 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: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png", + "https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" + ], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,3,2,4,null,5,6]Output:[1,3,5,6,2,4]", + "image": null + }, + { + "text": "Example 2: 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:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]", + "image": null + } + ], + "follow_up": null, + "solution": "function preorder(root: Node | null): number[] {\n const res: number[] = [];\n\n const getNodeVal = (node: Node | null): void => {\n if (node) {\n res.push(node.val);\n\n for (let i = 0; i < node.children.length; i++) {\n getNodeVal(node.children[i]);\n }\n }\n };\n\n getNodeVal(root);\n\n return res;\n}\n\n", + "title": "589. N-ary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]Explanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "Simple backtracking logic, try out each row and col and check position is valid or not.\n\nsince we are going row one by one, there is no way queen is placed in that row.\n\nso, we need to check col, diagonals for valid position.\n\n// col is straightforward flag for each column\n\n// dia1\n// 0 1 2 3\n// 1 2 3 4\n// 2 3 4 5\n// 3 4 5 6\n\n// dia2\n// 0 -1 -2 -3\n// 1 0 -1 -2\n// 2 1 0 -1\n// 3 2 1 0\n\nnegative numbers are not allowed as index, so we add n - 1 to diagonal2.\n\nclass Solution {\n List> ans = new LinkedList<>();\n int n;\n public List> solveNQueens(int n) {\n this.n = n;\n int[][] board = new int[n][n];\n \n boolean[] col = new boolean[n];\n boolean[] dia1 = new boolean[2 * n];\n boolean[] dia2 = new boolean[2 * n];\n \n solve(0, col, dia1, dia2, board);\n return ans;\n }\n \n public void solve(int row, boolean[] col, boolean[] dia1, boolean[] dia2, int[][] board){\n if(row == n){\n copyBoardToAns(board);\n return;\n }\n // brute force all col in that row\n for(int i = 0; i < n; i++){\n if(isValid(col, dia1, dia2, i, row)){\n col[i] = true; dia1[row + i] = true; dia2[row - i + n - 1] = true;\n board[row][i] = 1;\n solve(row + 1, col, dia1, dia2, board);\n col[i] = false; dia1[row + i] = false; dia2[row - i + n - 1] = false;\n board[row][i] = 0;\n }\n }\n }\n \n public boolean isValid(boolean[] col, boolean[] dia1, boolean[] dia2, int curCol, int curRow){\n return !col[curCol] && !dia1[curCol + curRow] && !dia2[curRow - curCol + n - 1];\n }\n \n public void copyBoardToAns(int[][] board){\n List res = new LinkedList<>();\n for(int i = 0; i < n; i++){\n String row = \"\";\n for(int j = 0; j < n; j++){\n if(board[i][j] == 1){\n row += \"Q\";\n }else{\n row += \".\";\n }\n }\n res.add(row);\n }\n ans.add(res);\n }\n}\n", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]Explanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n coord = self.findNextRows(0, n)\n ans = []\n for c in coord:\n temp = []\n for j in c:\n temp.append(\".\"*j+\"Q\"+\".\"*(n-j-1))\n ans.append(temp)\n return ans\n \n def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()):\n\t\t'''\n\t\th_occ: occupied horizontal coordinate\n\t\td_occ: occupied diagonal\n\t\tad_occ: occupied anti-diagonal\n\t\t'''\n ans = []\n if i==n:\n return [[]]\n for j in range(n):\n if (j not in h_occ) and (j-i not in d_occ) and ((j-n+1)+i not in ad_occ):\n h_occ.add(j)\n d_occ.add(j-i)\n ad_occ.add((j-n+1)+i)\n temp = self.findNextRows(i+1, n, h_occ, d_occ, ad_occ)\n h_occ.remove(j)\n d_occ.remove(j-i)\n ad_occ.remove((j-n+1)+i)\n ans += [[j]+l for l in temp]\n return ans\n \n \n", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:2Explanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.59%) | Memory: 41.2 MB (Top 48.22%)\nclass Solution {\n int count = 0;\n public int totalNQueens(int n) {\n boolean col[] = new boolean[n];\n boolean diag[] = new boolean[2*n-1];\n boolean rdiag[] = new boolean[2*n-1];\n\n countSolution(n,col, diag, rdiag, 0);\n return count;\n\n }\n void countSolution(int n, boolean[] col, boolean[] diag, boolean[] rdiag, int r ){\n if (r == n ){\n count++;\n return;\n }\n\n for(int c = 0 ; c < n; c++){\n if(col[c] == false && diag[r+c] == false && rdiag[r-c+n-1] == false){\n col[c] = true;\n diag[r+c] = true;\n rdiag[r-c+n-1] = true;\n countSolution(n, col, diag, rdiag, r+1);\n col[c] = false;\n diag[r+c] = false;\n rdiag[r-c+n-1] = false;\n }\n }\n\n }\n}", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:2Explanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalNQueens(self, n: int) -> int:\n res=0\n #用于存放结果\n pdia=set()\n ndia=set()\n col=set()\n\n def backtrack(r):\n #利用r作为一种计数,表示目前所在的行数\n if r==n:\n #判断已经完成棋盘,返回结果\n nonlocal res\n res+=1\n return\n for c in range(n):\n #对于n行n列的棋盘,每次在每一行我们尝试n种选择,\n #即每个岔路口有n条路线\n if (r+c) in pdia or (r-c) in ndia or c in col:\n #如果在同一对角线,或同一列,则不符合要求\n continue\n col.add(c)\n pdia.add(r+c)\n ndia.add(r-c)\n \n backtrack(r+1)\n \n col.remove(c)\n pdia.remove(r+c)\n ndia.remove(r-c)\n\n backtrack(0)\n return res\n", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums with the following properties: Return the element that is repeated n times . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums.length == 2 * n .", + "nums contains n + 1 unique elements.", + "Exactly one element of nums is repeated n times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,2,5,3,2]Output:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,1,5,2,5,3,5,4]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int repeatedNTimes(int[] nums) {\n int count = 0;\n for(int i = 0; i < nums.length; i++) {\n for(int j = i + 1; j < nums.length; j++) {\n if(nums[i] == nums[j])\n count = nums[j];\n }\n }\n return count;\n }\n}\n", + "title": "961. N-Repeated Element in Size 2N Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums with the following properties: Return the element that is repeated n times . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums.length == 2 * n .", + "nums contains n + 1 unique elements.", + "Exactly one element of nums is repeated n times." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,2,5,3,2]Output:2", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,1,5,2,5,3,5,4]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][0]\n", + "title": "961. N-Repeated Element in Size 2N Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:4Explanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25Output:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 58.23%)\nclass Solution {\n public int tribonacci(int n) {\n if(n==0)\n return 0;\n if(n==1)\n return 1;\n if(n==2)\n return 1;\n int p1=1;\n int p2=1;\n int p3=0;\n int cur=0;\n for(int i=3;i<=n;i++)\n {\n cur=p1+p2+p3;\n p3=p2;\n p2=p1;\n p1=cur;\n }\n return cur;\n }\n}", + "title": "1137. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:4Explanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25Output:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def tribonacci(self, n: int, q={}) -> int:\n if n<3:\n q[0]=0 #Initialize first 3 values \n q[1]=1\n q[2]=1\n if n not in q: #Have faith that last 3 calls will give the answer :)\n q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci(n-3,q)\n return q[n]\n", + "title": "1137. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Return the number of distinct valid names for the company . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= ideas.length <= 5 * 10^4", + "1 <= ideas[i].length <= 10", + "ideas[i] consists of lowercase English letters.", + "All the strings in ideas are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]Output:6Explanation:The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.", + "image": null + }, + { + "text": "Example 2: Input:ideas = [\"lack\",\"back\"]Output:0Explanation:There are no valid selections. Therefore, 0 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 186 ms (Top 96.05%) | Memory: 52.9 MB (Top 100.00%)\nclass Solution {\n public long distinctNames(String[] ideas) {\n // HashSet + String Manipulation; TC: O(26*26*n); SC: O(26*n)\n HashSet [] arr = new HashSet[26];\n for(int i=0; i<26; i++) {\n arr[i] = new HashSet<>();\n }\n for(String s: ideas) {\n arr[s.charAt(0)-'a'].add(s.substring(1));\n }\n long ans=0, cnt;\n for(int i=0; i<26; i++) {\n for(int j=i+1; j<26; j++) {\n cnt=0;\n for(String str: arr[j]) {\n if(arr[i].contains(str)) cnt++;\n }\n ans+=2*(arr[i].size()-cnt)*(arr[j].size()-cnt);\n }\n }\n return ans;\n }\n}", + "title": "2306. Naming a Company", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Return the number of distinct valid names for the company . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= ideas.length <= 5 * 10^4", + "1 <= ideas[i].length <= 10", + "ideas[i] consists of lowercase English letters.", + "All the strings in ideas are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]Output:6Explanation:The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.", + "image": null + }, + { + "text": "Example 2: Input:ideas = [\"lack\",\"back\"]Output:0Explanation:There are no valid selections. Therefore, 0 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def distinctNames(self, ideas: List[str]) -> int:\n \n names=defaultdict(set)\n res=0 \n \n #to store first letter as key and followed suffix as val\n for i in ideas:\n names[i[0]].add(i[1:])\n \n #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)\n arr=list(names.keys())\n ans,n=0,len(arr)\n \n for i in range(n):\n for j in range(i+1,n):\n #a,b => 2 distinct first letters\n a,b=arr[i],arr[j]\n # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be \"newword1 newword2\" or \"newword2 newword1\"\n res+=len(names[a]-names[b])*len(names[b]-names[a])*2\n \n return res\n\t\n", + "title": "2306. Naming a Company", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]Output:1Explanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]Output:2Explanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]Output:-1Explanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 87.01%) | Memory: 43.7 MB (Top 91.43%)\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length, queueSize;\n Queue queue = new LinkedList<>();\n boolean[][] visited = new boolean[rows][cols];\n int[] curr;\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n int x, y, steps = 0;\n\n queue.offer(entrance);\n visited[entrance[0]][entrance[1]] = true;\n\n while (!queue.isEmpty()) {\n queueSize = queue.size();\n steps++;\n\n for (int i=0;i=rows||y<0||y>=cols) continue;\n if (visited[x][y] || maze[x][y] == '+') continue;\n\n // check if we have reached boundary\n if (x==0||x==rows-1||y==0||y==cols-1) return steps;\n\n queue.offer(new int[]{x, y});\n visited[x][y] = true;\n }\n }\n }\n\n return -1;\n }\n}", + "title": "1926. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]Output:1Explanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]Output:2Explanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]Output:-1Explanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n x, y = entrance\n m, n, infi = len(maze), len(maze[0]), int(1e5)\n reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)\n @lru_cache(None)\n def dfs(i, j):\n if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':\n return infi\n if reached(i, j):\n return 0\n maze[i][j] = '+'\n ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))\n maze[i][j] = '.'\n return ans\n ans = dfs(x, y)\n return -1 if ans>=infi else ans\n", + "title": "1926. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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.)" + ], + "examples": [ + { + "text": "Example 1: Input:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2Output:2", + "image": "https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png" + }, + { + "text": "Example 2: Input:times = [[1,2,1]], n = 2, k = 1Output:1", + "image": null + }, + { + "text": "Example 3: Input:times = [[1,2,1]], n = 2, k = 2Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 24.43%) | Memory: 65.2 MB (Top 52.71%)\nclass Solution {\n HashMap> map = new HashMap<>();\n public int networkDelayTime(int[][] times, int n, int k) {\n for (int i = 1; i <= n; i++) {\n map.put(i, new HashMap<>());\n }\n for (int i = 0; i < times.length; i++) {\n map.get(times[i][0]).put(times[i][1], times[i][2]);\n }\n int ans = BFS(k, n);\n\n return ans == 1000 ? -1 : ans;\n }\n public int BFS(int k, int n) {\n LinkedList queue = new LinkedList<>();\n\n int[] timeReach = new int[n + 1];\n Arrays.fill(timeReach, 1000);\n timeReach[0] = 0;\n\n timeReach[k] = 0;\n\n queue.add(k);\n\n while (!queue.isEmpty()) {\n int rv = queue.remove();\n for (int nbrs : map.get(rv).keySet()) {\n int t = map.get(rv).get(nbrs) + timeReach[rv];\n if (t < timeReach[nbrs]) {\n timeReach[nbrs] = t;\n queue.add(nbrs);\n }\n }\n }\n\n int time = 0;\n\n for (int i : timeReach) {\n time = Math.max(i, time);\n }\n\n return time;\n }\n}", + "title": "743. Network Delay Time", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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.)" + ], + "examples": [ + { + "text": "Example 1: Input:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2Output:2", + "image": "https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png" + }, + { + "text": "Example 2: Input:times = [[1,2,1]], n = 2, k = 1Output:1", + "image": null + }, + { + "text": "Example 3: Input:times = [[1,2,1]], n = 2, k = 2Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n \n adjlist = [[] for _ in range(n+1)]\n \n for src, dst, weight in times:\n adjlist[src].append((dst, weight))\n \n visited = [-1]*(n+1)\n captured =[-1]*(n+1)\n\n priority_queue = [(0,k)]\n \n nums = 0\n total_dist = 0\n \n while priority_queue:\n\n dst, node = heapq.heappop(priority_queue)\n\n if captured[node] != -1:\n continue\n captured[node] = dst\n \n nums += 1\n total_dist = dst\n \n for nbr,wt in adjlist[node]:\n if captured[nbr] == -1:\n heapq.heappush(priority_queue,(captured[node]+wt, nbr))\n if nums == n:\n return total_dist\n else:\n return -1\n", + "title": "743. Network Delay Time", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice plays the following game, loosely based on the card game \"21\" . Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts] , where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points . Return the probability that Alice has n or fewer points. Answers within 10 -5 of the actual answer are considered accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= k <= n <= 10^4", + "1 <= maxPts <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, k = 1, maxPts = 10Output:1.00000Explanation:Alice gets a single card, then stops.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, k = 1, maxPts = 10Output:0.60000Explanation:Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.", + "image": null + }, + { + "text": "Example 3: Input:n = 21, k = 17, maxPts = 10Output:0.73278", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double new21Game(int n, int k, int maxPts) {\n double[] dp = new double[k + maxPts];\n dp[0] = 1;\n for (int i = 0; i < k; i++){\n for (int j = 1; j <= maxPts; j++){\n dp[i + j] += dp[i] * 1.0 / maxPts;\n }\n }\n\n double ans = 0;\n for (int i = k; i < k + maxPts && i <= n; i++){\n ans += dp[i];\n }\n\n return ans;\n }\n}\n", + "title": "837. New 21 Game", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice plays the following game, loosely based on the card game \"21\" . Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts] , where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets k or more points . Return the probability that Alice has n or fewer points. Answers within 10 -5 of the actual answer are considered accepted. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= k <= n <= 10^4", + "1 <= maxPts <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, k = 1, maxPts = 10Output:1.00000Explanation:Alice gets a single card, then stops.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, k = 1, maxPts = 10Output:0.60000Explanation:Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.", + "image": null + }, + { + "text": "Example 3: Input:n = 21, k = 17, maxPts = 10Output:0.73278", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 110 ms (Top 69.47%) | Memory: 14.5 MB (Top 12.98%)\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])\n s = sum(dp)\n for i in range(k):\n dp.appendleft(s / maxPts)\n s += dp[0] - dp.pop()\n\n return dp[0]", + "title": "837. New 21 Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]Output:[-1,3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]Output:[3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 51.94%) | Memory: 44.9 MB (Top 8.50%)\nclass Solution {\n public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n HashMap map = new HashMap<>();\n Stack stack = new Stack<>();\n int[] ans = new int[nums1.length];\n for(int i = 0; i < nums2.length; i++){\n while(!stack.isEmpty() && nums2[i] > stack.peek()){\n int temp = stack.pop();\n map.put(temp, nums2[i]);\n }\n stack.push(nums2[i]);\n }\n for(int i = 0; i < nums1.length; i++){\n ans[i] = map.getOrDefault(nums1[i], -1);\n }\n return ans;\n }\n}", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]Output:[-1,3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]Output:[3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 80.48%) | Memory: 16.70 MB (Top 24.94%)\n\nclass Solution:\n def nextGreaterElement(self, nums1, nums2):\n dic, stack = {}, []\n \n for num in nums2[::-1]:\n while stack and num > stack[-1]:\n stack.pop()\n if stack:\n dic[num] = stack[-1]\n stack.append(num)\n \n return [dic.get(num, -1) for num in nums1]\n", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0] ), return the next greater number for every element in nums . The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]Output:[2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,3]Output:[2,3,4,-1,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] nextGreaterElements(int[] nums) {\n Stacks=new Stack<>();\n for(int i=nums.length-1;i>=0;i--){\n s.push(nums[i]);\n }\n for(int i=nums.length-1;i>=0;i--){\n int num=nums[i];\n while(!s.isEmpty() && s.peek()<=nums[i]){\n s.pop();\n }\n nums[i]=s.empty()?-1:s.peek();\n s.push(num);\n }\n return nums;\n }\n}\n", + "title": "503. Next Greater Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0] ), return the next greater number for every element in nums . The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1]Output:[2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,3]Output:[2,3,4,-1,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 151 ms (Top 99.29%) | Memory: 19.30 MB (Top 5.84%)\n\nclass Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n st = []\n n = len(nums)\n ans = [-1] * n\n for i in range(2*n-1, -1, -1):\n while st and st[-1] <= nums[i%n]:\n st.pop()\n if st and i < n:\n ans[i] = st[-1]\n st.append(nums[i%n])\n return ans\n", + "title": "503. Next Greater Element II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer n , find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n . If no such positive integer exists, return -1 . Note that the returned integer should fit in 32-bit integer , if there is a valid answer but it does not fit in 32-bit integer , return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:21", + "image": null + }, + { + "text": "Example 2: Input:n = 21Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nextGreaterElement(int n) {\n char[] arr = (n + \"\").toCharArray();\n \n int i = arr.length - 1;\n while(i > 0){\n if(arr[i-1] >= arr[i]){\n i--;\n }else{\n break;\n }\n }\n if(i == 0){\n return -1;\n }\n \n int idx1 = i-1;\n \n int j = arr.length - 1;\n while(j > idx1){\n if(arr[j] > arr[idx1]){\n break;\n }\n j--;\n }\n \n //Swapping\n swap(arr,idx1,j);\n \n //sorting\n int left = idx1+1;\n int right = arr.length-1;\n while(left < right){\n swap(arr,left,right);\n left++;\n right--;\n }\n \n String result = new String(arr);\n long val = Long.parseLong(result);\n \n return (val > Integer.MAX_VALUE ? -1 : (int)val);\n \n }\n \n void swap(char[]arr,int i,int j){\n char temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n\n", + "title": "556. Next Greater Element III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n . If no such positive integer exists, return -1 . Note that the returned integer should fit in 32-bit integer , if there is a valid answer but it does not fit in 32-bit integer , return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:21", + "image": null + }, + { + "text": "Example 2: Input:n = 21Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 26.09%) | Memory: 16.30 MB (Top 30.04%)\n\nclass Solution:\n def nextGreaterElement(self, n):\n digits = list(str(n))\n i = len(digits) - 1\n while i-1 >= 0 and digits[i] <= digits[i-1]:\n i -= 1\n \n if i == 0: return -1\n \n j = i\n while j+1 < len(digits) and digits[j+1] > digits[i-1]:\n j += 1\n \n digits[i-1], digits[j] = digits[j], digits[i-1]\n digits[i:] = digits[i:][::-1]\n ret = int(''.join(digits))\n \n return ret if ret < 1<<31 else -1\n", + "title": "556. Next Greater Element III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node . That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the i th node ( 1-indexed ). If the i th node does not have a next greater node, set answer[i] = 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 10^4", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [2,1,5]Output:[5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext1.jpg" + }, + { + "text": "Example 2: Input:head = [2,7,4,3,5]Output:[7,0,5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 721 ms (Top 25.59%) | Memory: 45.5 MB (Top 95.29%)\nclass Solution {\n public int[] nextLargerNodes(ListNode head) {\n ListNode length=head;\n int l=0;\n while(length!=null)\n {\n length=length.next;\n l++;\n }\n int[] res=new int[l];\n int i=0;\n ListNode temp=head;\n\n while(temp!=null)\n {\n ListNode temp1=temp.next;\n int max=temp.val;\n\n while(temp1!=null)\n {\n if(temp1.val>max)\n {\n max=temp1.val;\n res[i]=max;\n break;\n }\n\n temp1=temp1.next;\n }\n temp=temp.next;\n i++;\n }\n return res;\n }\n}", + "title": "1019. Next Greater Node In Linked List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the head of a linked list with n nodes. For each node in the list, find the value of the next greater node . That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. Return an integer array answer where answer[i] is the value of the next greater node of the i th node ( 1-indexed ). If the i th node does not have a next greater node, set answer[i] = 0 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 10^4", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [2,1,5]Output:[5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext1.jpg" + }, + { + "text": "Example 2: Input:head = [2,7,4,3,5]Output:[7,0,5,5,0]", + "image": "https://assets.leetcode.com/uploads/2021/08/05/linkedlistnext2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n stack = []\n ans = []\n node = head\n \n i = 0\n while node is not None:\n while stack and stack[-1][0] < node.val:\n ans[stack[-1][1]] = node.val\n stack.pop()\n \n stack.append((node.val, i))\n ans.append(0)\n i += 1\n node = node.next\n \n return ans", + "title": "1019. Next Greater Node In Linked List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer x is numerically balanced if for every digit d in the number x , there are exactly d occurrences of that digit in x . Given an integer n , return the smallest numerically balanced number strictly greater than n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:22Explanation:22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 1000Output:1333Explanation:1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.", + "image": null + }, + { + "text": "Example 3: Input:n = 3000Output:3133Explanation:3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 207 ms (Top 46.27%) | Memory: 117.2 MB (Top 26.87%)\nclass Solution {\n public int nextBeautifulNumber(int n) {\n\n while(true){\n n++;\n int num = n; //test this number\n int [] freq = new int[10]; // 0 to 9\n\n while(num > 0){ //calculate freq of each digit in the num\n int rem = num % 10; //this is remainder\n num = num / 10; //this is quotient\n freq[rem] = freq[rem] + 1; //increase its frequency\n if(freq[rem] > rem) break;\n }\n\n boolean ans = true;\n\n for(int i = 0;i<10;i++){ //check frequency of each digit\n if(freq[i] != i && freq[i] != 0){\n ans = false;\n break;\n }\n }\n\n if(ans == true){\n return n;\n }\n }\n }\n}", + "title": "2048. Next Greater Numerically Balanced Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer x is numerically balanced if for every digit d in the number x , there are exactly d occurrences of that digit in x . Given an integer n , return the smallest numerically balanced number strictly greater than n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:22Explanation:22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 1000Output:1333Explanation:1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.", + "image": null + }, + { + "text": "Example 3: Input:n = 3000Output:3133Explanation:3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n n_digits = len(str(n))\n \n next_max = {\n 1: [1],\n 2: [22],\n 3: [122, 333],\n 4: [1333, 4444],\n 5: [14444, 22333, 55555],\n 6: [122333, 224444, 666666, 155555],\n 7: [1224444, 2255555, 3334444, 1666666, 7777777]\n }\n \n if n >= int(str(n_digits) * n_digits):\n n_digits += 1\n return min(next_max[n_digits])\n \n ans = float('inf')\n for num in sorted(next_max[n_digits]): \n cands = set(permutations(str(num)))\n cands = sorted(map(lambda x: int(\"\".join(x)), cands))\n \n loc = bisect.bisect(cands, n)\n if loc < len(cands): \n ans = min(ans, cands[loc])\n \n return ans\n", + "title": "2048. Next Greater Numerically Balanced Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are considered permutations of arr : [1,2,3] , [1,3,2] , [3,1,2] , [2,3,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]Output:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]Output:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.93%) | Memory: 43.7 MB (Top 52.39%)\n\nclass Solution {\n public void nextPermutation(int[] nums) {\n // FIND peek+1\n int nextOfPeak = -1;\n for (int i = nums.length - 1; i > 0; i--) {\n if (nums[i] > nums[i - 1]) {\n nextOfPeak = i - 1;\n break;\n }\n }\n\n // Return reverse Array\n if (nextOfPeak == -1) {\n int start = 0;\n int end = nums.length - 1;\n while (start <= end) {\n int temp = nums[start];\n nums[start] = nums[end];\n nums[end] = temp;\n start++;\n end--;\n }\n return;\n }\n // Find element greater than peek\n int reversalPoint = nums.length - 1;\n for (int i = nums.length - 1; i > nextOfPeak; i--) {\n if (nums[i] > nums[nextOfPeak]) {\n reversalPoint = i;\n break;\n }\n }\n\n // swap nextOfPeak && reversalPoint\n int temp = nums[nextOfPeak];\n nums[nextOfPeak] = nums[reversalPoint];\n nums[reversalPoint] = temp;\n\n // Reverse array from nextOfPeak+1\n int start = nextOfPeak + 1;\n int end = nums.length - 1;\n while (start <= end) {\n int temp1 = nums[start];\n nums[start] = nums[end];\n nums[end] = temp1;\n start++;\n end--;\n }\n\n }\n}", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are considered permutations of arr : [1,2,3] , [1,3,2] , [3,1,2] , [2,3,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]Output:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]Output:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nextPermutation(self, nums) -> None:\n firstDecreasingElement = -1\n toSwapWith = -1\n lastIndex = len(nums) - 1\n\n # Looking for an element that is less than its follower\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[i - 1]:\n firstDecreasingElement = i - 1\n break\n\n # If there is not any then reverse the array to make initial permutation\n if firstDecreasingElement == -1:\n for i in range(0, lastIndex // 2 + 1):\n nums[i], nums[lastIndex - i] = nums[lastIndex - i], nums[i]\n return\n\n # Looking for an element to swap it with firstDecreasingElement\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[firstDecreasingElement]:\n toSwapWith = i\n break\n\n # Swap found elements\n nums[firstDecreasingElement], nums[toSwapWith] = nums[toSwapWith], nums[firstDecreasingElement]\n\n # Reverse elements from firstDecreasingElement to the end of the array\n left = firstDecreasingElement + 1\n right = lastIndex\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing the following Nim Game with your friend: Given n , the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Initially, there is a heap of stones on the table.", + "You and your friend will alternate taking turns, and you go first .", + "On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.", + "The one who removes the last stone is the winner." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:falseExplanation:These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:true", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.8 MB (Top 59.25%)\nclass Solution {\n public boolean canWinNim(int n) {\n if(n%4==0) return false;\n\n return true;\n }\n}", + "title": "292. Nim Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are playing the following Nim Game with your friend: Given n , the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Initially, there is a heap of stones on the table.", + "You and your friend will alternate taking turns, and you go first .", + "On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.", + "The one who removes the last stone is the winner." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:falseExplanation:These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:true", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 73.60%) | Memory: 13.9 MB (Top 45.89%)\nclass Solution:\n def canWinNim(self, n: int) -> bool:\n return n%4", + "title": "292. Nim Game", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element . We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i ( 0-based ) such that ( 0 <= i <= n - 2 ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3]Output:trueExplanation:You could modify the first 4 to 1 to get a non-decreasing array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,1]Output:falseExplanation:You cannot get a non-decreasing array by modifying at most one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkPossibility(int[] nums) {\n int modified = 0, prev = nums[0], index = 0;\n for (; index < nums.length; ++index) {\n if (nums[index] < prev) {\n if (++modified > 1) return false;\n if (index - 2 >= 0 && nums[index - 2] > nums[index]) continue;\n }\n prev = nums[index];\n }\n return true;\n }\n}\n", + "title": "665. Non-decreasing Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element . We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i ( 0-based ) such that ( 0 <= i <= n - 2 ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,3]Output:trueExplanation:You could modify the first 4 to 1 to get a non-decreasing array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,1]Output:falseExplanation:You cannot get a non-decreasing array by modifying at most one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n unstable=0\n for i in range(1,len(nums)):\n if nums[i]1:\n return False\n return True\n", + "title": "665. Non-decreasing Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer n , return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:5Explanation:Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:2", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findIntegers(int n) {\n int val=0,res=0,cn=n,digi=0,prevdig=0,i;//digi means bin digi\n while(cn>0){\n cn=cn>>1;\n digi++;\n }\n int dp[]=new int[digi+1];\n dp[0]=1;dp[1]=2;\n for(i=2;i<=digi;i++)\n dp[i]=dp[i-1]+dp[i-2];\n digi++;\n while(digi-->=0){\n if((n&(1<0){\n res+=dp[digi];\n if(prevdig==1)return res;\n prevdig=1;\n }else prevdig=0;\n }\n \n return res+1;\n }\n}\n", + "title": "600. Non-negative Integers without Consecutive Ones", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a positive integer n , return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:5Explanation:Here are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:2", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findIntegers(self, n: int) -> int:\n b=(bin(n).replace(\"0b\",\"\"))\n dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)]\n def fun(i,last,tight,leading_zeros):\n if i==len(str(b)):\n return 1\n if dp[i][tight][leading_zeros][last]!=-1:\n return dp[i][tight][leading_zeros][last]\n end=1\n if tight==1:\n end = int(b[i])\n res=0\n for j in range(end+1):\n if j==0 and leading_zeros==1:\n res+=fun(i+1,j,tight&int(j==end),1)\n else:\n if j==0:\n res+=fun(i+1,j,tight&int(j==end),0)\n else:\n if last!=j:\n res+=fun(i+1,j,tight&int(j==end),0)\n dp[i][tight][leading_zeros][last] = res\n return res\n return fun(0,0,1,1)", + "title": "600. Non-negative Integers without Consecutive Ones", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]Output:1Explanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]Output:2Explanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]Output:0Explanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "// |-------|\n// |--|\n\n// |-------|\n//. |-------|\n\n// |-------|\n//. |-------|\n\nclass Solution {\n public int eraseOverlapIntervals(int[][] intervals) {\n Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n \n int start = intervals[0][0];\n int end = intervals[0][1];\n int res = 0;\n \n for (int i = 1; i < intervals.length; i++){\n int[] interval = intervals[i];\n \n if(interval[0] >= start && interval[0] < end){\n res++;\n if (interval[1] >= end)\n continue;\n }\n start = interval[0];\n end = interval[1];\n }\n \n return res;\n }\n}\n", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]Output:1Explanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]Output:2Explanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]Output:0Explanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3035 ms (Top 7.53%) | Memory: 52.8 MB (Top 61.18%)\n\nclass Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1)\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n\n for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value\n if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one\n prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval\n else: # Overlapping when new interval starts in between or from the previous one\n res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2]\n prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last\n\n return res", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the n th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3", + "image": null + }, + { + "text": "Example 2: Input:n = 11Output:0Explanation:The 11thdigit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1237 ms (Top 5.08%) | Memory: 39.2 MB (Top 91.02%)\nclass Solution {\n public int findNthDigit(int n) {\n\n if(n < 10)\n return n;\n\n long currDigitIndex = 10;\n int tillNextIncrease = 90;\n int currNumberSize = 2;\n int currNumber = 10;\n int next = tillNextIncrease;\n\n while(currDigitIndex < n) {\n\n currNumber++;\n currDigitIndex += currNumberSize;\n next--;\n\n if(next == 0) {\n currNumberSize++;\n tillNextIncrease *= 10;\n next = tillNextIncrease;\n }\n }\n\n int nthDigit = currNumber % 10;\n if(currDigitIndex == n) {\n while(currNumber != 0) {\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n } else if(currDigitIndex > n) {\n\n currNumber--;\n\n while(currDigitIndex > n) {\n currDigitIndex--;\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n }\n\n return nthDigit;\n }\n}", + "title": "400. Nth Digit", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return the n th digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:3", + "image": null + }, + { + "text": "Example 2: Input:n = 11Output:0Explanation:The 11thdigit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNthDigit(self, n: int) -> int:\n low, high = 1, 0\n place = 1\n \n sum_ = 0\n \n while True:\n high = 10**place -1\n digits_sum = (high - low +1 ) * place\n \n if sum_<= n <= digits_sum + sum_:\n break\n else:\n low = high+1\n sum_+= digits_sum\n place += 1\n \n remaining_digits = n - sum_\n \n position = (remaining_digits-1)//place \n index_ = remaining_digits - position*place -1\n \n \n number = low + position\n # return str(number)[index_]\n count = 0\n index_ = place - 1 - index_\n l = []\n # \n while number:\n if count == index_:\n return number%10\n number = number//10\n count+=1\n\n", + "title": "400. Nth Digit", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A positive integer is magical if it is divisible by either a or b . Given the three integers n , a , and b , return the n th magical number. Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "2 <= a, b <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, a = 2, b = 3Output:2", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 60.59%) | Memory: 40.8 MB (Top 59.85%)\nclass Solution {\npublic int nthMagicalNumber(int n, int a, int b) {\n long N=(long)n;\n long A=(long)a;\n long B=(long)b;\n long mod=1000000007;\n long min=Math.min(A,B);\n long low=min;\n long high=min*N;\n long ans=0;\n while(low<=high)\n {\n long mid=(high-low)/2+low;\n long x=mid/A+mid/B-mid/lcm(A,B);\n if(x>=N)\n {\n ans=mid;\n high=mid-1;\n }\n else if(x0)\n {\n long temp=a;\n a=b%a;\n b=temp;\n }\n\n return tmpA*tmpB/b;\n}\n}", + "title": "878. Nth Magical Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A positive integer is magical if it is divisible by either a or b . Given the three integers n , a , and b , return the n th magical number. Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9", + "2 <= a, b <= 4 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, a = 2, b = 3Output:2", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 24 ms (Top 100.0%) | Memory: 16.28 MB (Top 81.4%)\n\nclass Solution:\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n import math\n lcm= A*B // math.gcd(A,B)\n l,r=2,10**14\n while l<=r:\n mid=(l+r)//2\n n = mid//A+mid//B-mid//lcm\n if n>=N:\n r=mid-1\n \n else:\n l=mid+1\n return l%(10**9+7)", + "title": "878. Nth Magical Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer num , return its complement . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 5Output:2Explanation:The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 1Output:0Explanation:The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findComplement(int num) {\n int x=0;int sum=0;\n while(num>0){\n int i = num%2;\n if(i==0){\n sum+=Math.pow(2,x++);\n }\n else{\n x++;\n }\n num/=2;\n }\n return sum;\n }\n}\n", + "title": "476. Number Complement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The complement of an integer is the integer you get when you flip all the 0 's to 1 's and all the 1 's to 0 's in its binary representation. Given an integer num , return its complement . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 5Output:2Explanation:The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.", + "image": null + }, + { + "text": "Example 2: Input:num = 1Output:0Explanation:The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 13.03%) | Memory: 13.8 MB (Top 53.14%)\n\nclass Solution:\n def findComplement(self, num: int) -> int:\n i = 0\n while(2**i <= num):\n i += 1\n return (2**i - num - 1)", + "title": "476. Number Complement", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight ). Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 3 , the input represents the signed integer. -3 ." + ], + "examples": [ + { + "text": "Example 3 Input:n = 00000000000000000000000000001011Output:3Explanation:The input binary string00000000000000000000000000001011has a total of three '1' bits.", + "image": null + }, + { + "text": "Example 2: Input:n = 00000000000000000000000010000000Output:1Explanation:The input binary string00000000000000000000000010000000has a total of one '1' bit.", + "image": null + }, + { + "text": "Example 3: Input:n = 11111111111111111111111111111101Output:31Explanation:The input binary string11111111111111111111111111111101has a total of thirty one '1' bits.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need to treat n as an unsigned value\n public int hammingWeight(int n) {\n return Integer.bitCount(n);\n }\n}\n", + "title": "191. Number of 1 Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight ). Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 3 , the input represents the signed integer. -3 ." + ], + "examples": [ + { + "text": "Example 3 Input:n = 00000000000000000000000000001011Output:3Explanation:The input binary string00000000000000000000000000001011has a total of three '1' bits.", + "image": null + }, + { + "text": "Example 2: Input:n = 00000000000000000000000010000000Output:1Explanation:The input binary string00000000000000000000000010000000has a total of one '1' bit.", + "image": null + }, + { + "text": "Example 3: Input:n = 11111111111111111111111111111101Output:31Explanation:The input binary string11111111111111111111111111111101has a total of thirty one '1' bits.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 27 ms (Top 98.51%) | Memory: 13.8 MB (Top 50.40%)\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n i = 0\n while n > 0:\n if n % 2 != 0: i += 1\n n = n >> 1\n return i", + "title": "191. Number of 1 Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed , strictly increasing integer array nums and a positive integer diff . A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: Return the number of unique arithmetic triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "i < j < k ,", + "nums[j] - nums[i] == diff , and", + "nums[k] - nums[j] == diff ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,4,6,7,10], diff = 3Output:2Explanation:(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,8,9], diff = 2Output:2Explanation:(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.25%) | Memory: 42.8 MB (Top 15.70%)\n\nclass Solution {\n public int arithmeticTriplets(int[] nums, int diff) {\n int result = 0;\n int[] map = new int[201];\n\n for(int num: nums) {\n map[num] = 1;\n\n if(num - diff >= 0) {\n map[num] += map[num - diff];\n }\n\n if(map[num] >= 3) result += 1;\n }\n\n return result;\n }\n}", + "title": "2367. Number of Arithmetic Triplets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed , strictly increasing integer array nums and a positive integer diff . A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: Return the number of unique arithmetic triplets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "i < j < k ,", + "nums[j] - nums[i] == diff , and", + "nums[k] - nums[j] == diff ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,4,6,7,10], diff = 3Output:2Explanation:(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,8,9], diff = 2Output:2Explanation:(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n \n ans = 0\n n = len(nums)\n for i in range(n):\n if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n ans += 1\n \n return ans\n", + "title": "2367. Number of Arithmetic Triplets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. Two formulas are concatenated together to produce another formula. A formula placed in parentheses, and a count (optionally added) is also a formula. 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible." + ], + "examples": [ + { + "text": "Example 1: Input:formula = \"H2O\"Output:\"H2O\"Explanation:The count of elements are {'H': 2, 'O': 1}.", + "image": null + }, + { + "text": "Example 2: Input:formula = \"Mg(OH)2\"Output:\"H2MgO2\"Explanation:The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.", + "image": null + }, + { + "text": "Example 3: Input:formula = \"K4(ON(SO3)2)2\"Output:\"K4N2O14S4\"Explanation:The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String countOfAtoms(String formula) {\n Deque multiplier = new ArrayDeque<>();\n Map map = new HashMap<>();\n int lastValue = 1;\n \n multiplier.push(1);\n \n\t\t// Iterate from right to left\n for (int i = formula.length() - 1; i >= 0; i--) {\n if (Character.isDigit(formula.charAt(i))) { // Case of a digit - Get full number and save\n StringBuilder sb = new StringBuilder();\n\t\t\t\t\n while (Character.isDigit(formula.charAt(i-1))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n lastValue = Integer.parseInt(sb.reverse().toString());\n } else if (formula.charAt(i) == ')') { // Start parenthesis - push next multiplier to stack\n multiplier.push(lastValue * multiplier.peek());\n lastValue = 1;\n } else if (formula.charAt(i) == '(') { // End parenthesis - pop last multiplier\n multiplier.pop();\n } else { // Case of an element name - construct name, update count based on multiplier\n StringBuilder sb = new StringBuilder();\n \n while (Character.isLowerCase(formula.charAt(i))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n \n String element = sb.reverse().toString();\n map.put(element, map.getOrDefault(element, 0) + lastValue * multiplier.peek());\n lastValue = 1;\n }\n }\n \n\t\t// Sort map keys\n List elements = new ArrayList<>(map.keySet());\n StringBuilder sb = new StringBuilder();\n Collections.sort(elements);\n \n\t\t// Construct output\n for (String element : elements) {\n sb.append(element);\n if (map.get(element) > 1) {\n sb.append(map.get(element)); \n }\n }\n return sb.toString();\n }\n}\n", + "title": "726. Number of Atoms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Two formulas are concatenated together to produce another formula. A formula placed in parentheses, and a count (optionally added) is also a formula. 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible." + ], + "examples": [ + { + "text": "Example 1: Input:formula = \"H2O\"Output:\"H2O\"Explanation:The count of elements are {'H': 2, 'O': 1}.", + "image": null + }, + { + "text": "Example 2: Input:formula = \"Mg(OH)2\"Output:\"H2MgO2\"Explanation:The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.", + "image": null + }, + { + "text": "Example 3: Input:formula = \"K4(ON(SO3)2)2\"Output:\"K4N2O14S4\"Explanation:The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 78.84%) | Memory: 16.70 MB (Top 50.21%)\n\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack, elem, i = [{}], \"\", 0\n \n while i < len(formula):\n # Extract the full element name\n if formula[i].isupper():\n j = i + 1\n while j < len(formula) and formula[j].islower():\n j += 1\n elem = formula[i:j]\n i = j\n # If no digits follow the element, assign a count of 1\n if i == len(formula) or not formula[i].isdigit() and not formula[i].islower():\n stack[-1][elem] = stack[-1].get(elem, 0) + 1\n # Extract the count\n elif formula[i].isdigit():\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n count = int(formula[i:j])\n stack[-1][elem] = stack[-1].get(elem, 0) + count\n i = j\n # Handle open parentheses by pushing a new dict\n elif formula[i] == '(':\n stack.append({})\n i += 1\n # Handle close parentheses by merging with the previous dict\n elif formula[i] == ')':\n i += 1\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n multiplier = int(formula[i:j] or 1)\n top = stack.pop()\n for elem, count in top.items():\n stack[-1][elem] = stack[-1].get(elem, 0) + count * multiplier\n i = j\n \n # Convert the result to the desired format\n atoms = sorted(stack[0].items())\n return ''.join([atom + (str(count) if count > 1 else '') for atom, count in atoms])\n\n", + "title": "726. Number of Atoms", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given n points in the plane that are all distinct , where points[i] = [x i , y i ] . A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters) . Return the number of boomerangs . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == points.length", + "1 <= n <= 500", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[1,0],[2,0]]Output:2Explanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,1]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfBoomerangs(int[][] points) {\n \n int answer = 0;\n \n for (int p=0; p hm = new HashMap();\n \n for (int q=0;q 0) {\n if (hm.containsKey(distance)) {\n hm.put(distance, hm.get(distance) + 1);\n } else {\n hm.put(distance, 1);\n }\n }\n \n }\n \n for (Double dist : hm.keySet()) {\n int occ = hm.get(dist);\n if (occ > 1) {\n answer = answer + ((occ) * (occ - 1));\n }\n }\n }\n \n return answer;\n }\n}\n", + "title": "447. Number of Boomerangs", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given n points in the plane that are all distinct , where points[i] = [x i , y i ] . A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters) . Return the number of boomerangs . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == points.length", + "1 <= n <= 500", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[0,0],[1,0],[2,0]]Output:2Explanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,1]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n def sq(a):\n return a * a\n\n def euclid(a, b, c, d):\n dist = sq(a - c) + sq(b - d)\n return sq(dist)\n\n n = len(points)\n res = 0\n for i in range(n):\n count = defaultdict(lambda : 0)\n for j in range(n):\n d = euclid(points[i][0], points[i][1], points[j][0], points[j][1])\n res += count[d] * 2\n count[d] += 1\n\n return res\n", + "title": "447. Number of Boomerangs", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers tomatoSlices and cheeseSlices . The ingredients of different burgers are as follows: Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0 . If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Jumbo Burger: 4 tomato slices and 1 cheese slice.", + "Small Burger: 2 Tomato slices and 1 cheese slice." + ], + "examples": [ + { + "text": "Example 1: Input:tomatoSlices = 16, cheeseSlices = 7Output:[1,6]Explantion:To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.", + "image": null + }, + { + "text": "Example 2: Input:tomatoSlices = 17, cheeseSlices = 4Output:[]Explantion:There will be no way to use all ingredients to make small and jumbo burgers.", + "image": null + }, + { + "text": "Example 3: Input:tomatoSlices = 4, cheeseSlices = 17Output:[]Explantion:Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 786 ms (Top 7.64%) | Memory: 42.4 MB (Top 87.50%)\nclass Solution {\n public List numOfBurgers(int tomatoSlices, int cheeseSlices) {\n Listlist=new ArrayList<>();\n int ts=tomatoSlices;\n int cs=cheeseSlices;\n if (tscs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0))\n {\n return list;\n }\n int cnt=0;\n while(ts>0 && cs>0 && ts!=cs*2)\n {\n ts-=4;\n cnt++;\n cs--;\n }\n list.add(cnt);\n list.add(cs);\n return list;\n }\n}", + "title": "1276. Number of Burgers with No Waste of Ingredients", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers tomatoSlices and cheeseSlices . The ingredients of different burgers are as follows: Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0 . If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Jumbo Burger: 4 tomato slices and 1 cheese slice.", + "Small Burger: 2 Tomato slices and 1 cheese slice." + ], + "examples": [ + { + "text": "Example 1: Input:tomatoSlices = 16, cheeseSlices = 7Output:[1,6]Explantion:To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.", + "image": null + }, + { + "text": "Example 2: Input:tomatoSlices = 17, cheeseSlices = 4Output:[]Explantion:There will be no way to use all ingredients to make small and jumbo burgers.", + "image": null + }, + { + "text": "Example 3: Input:tomatoSlices = 4, cheeseSlices = 17Output:[]Explantion:Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def numOfBurgers(self, t, c):\n \n if t==c==0:\n return [0,0]\n four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c\n two=c-four #number of small burgers\n if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list\n return []\n \n return [four,two]\n \n", + "title": "1276. Number of Burgers with No Waste of Ingredients", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0 s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png", + "https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png" + ], + "constraints": [ + "1 <= grid.length, grid[0].length <= 100", + "0 <= grid[i][j] <=1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]Output:2Explanation:Islands in gray are closed because they are completely surrounded by water (group of 1s).", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]Output:1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 35.60%) | Memory: 47.1 MB (Top 38.97%)\nclass Solution {\n boolean isClosed = true;\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int count = 0;\n\n for(int i=1; i grid.length-1 || j> grid[0].length-1 || grid[i][j] != 0) return;\n\n grid[i][j] = 1; // to mark as visited\n\n if(i == 0 || j == 0 || i == grid.length -1 || j == grid[0].length - 1) isClosed = false;\n\n dfs(grid, i, j+1);\n dfs(grid, i, j-1);\n dfs(grid, i+1, j);\n dfs(grid, i-1, j);\n }\n}", + "title": "1254. Number of Closed Islands", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0 s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s. Return the number of closed islands . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png", + "https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png" + ], + "constraints": [ + "1 <= grid.length, grid[0].length <= 100", + "0 <= grid[i][j] <=1" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]Output:2Explanation:Islands in gray are closed because they are completely surrounded by water (group of 1s).", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]Output:1", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n '''主函数:计算封闭岛屿的数量'''\n def closedIsland(self, grid: List[List[int]]) -> int:\n result = 0\n m, n = len(grid), len(grid[0])\n self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n \n # 遍历 grid,处理边缘陆地\n for j in range(n):\n self.dfs(grid, 0, j)\n self.dfs(grid, m - 1, j)\n for i in range(m):\n self.dfs(grid, i, 0)\n self.dfs(grid, i, n - 1)\n \n # 剩下都是封闭岛屿,遍历找结果\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n result += 1\n self.dfs(grid, i, j)\n return result\n \n '''从 (i, j) 开始,将与之相邻的陆地都变成海水'''\n def dfs(self, grid, i, j):\n m, n = len(grid), len(grid[0])\n # 超出索引边界\n if i < 0 or j < 0 or i >= m or j >= n:\n return\n # 已经是海水了\n if grid[i][j] == 1:\n return\n # 变成海水\n grid[i][j] = 1\n for d in self.direction:\n x = i + d[0]\n y = j + d[1]\n self.dfs(grid, x, y)\n", + "title": "1254. Number of Closed Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:date1 = \"2019-06-29\", date2 = \"2019-06-30\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:date1 = \"2020-01-15\", date2 = \"2019-12-31\"Output:15", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int daysBetweenDates(String date1, String date2) {\n String[] d1 = date1.split(\"-\");\n String[] d2 = date2.split(\"-\");\n return (int)Math.abs(\n daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))\n - daysFrom1971(Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2])));\n }\n private int daysFrom1971(int year, int month, int day) {\n int total = 0;\n\t\t// count years first\n total += (year - 1971) * 365;\n for (int i = 1972; i < year; i += 4) {\n if (isLeapYear(i)) total++;\n } \n int feb = isLeapYear(year) ? 29 : 28;\n\t\t// sum months and days\n switch (month) {\n case 12: \n total += 30; // 11\n case 11:\n total += 31; // 10\n case 10: \n total += 30; // 9\n case 9:\n total += 31; // 8\n case 8:\n total += 31; // 7\n case 7: \n total += 30; // 6\n case 6:\n total += 31; // 5\n case 5:\n total += 30; // 4\n case 4: \n total += 31; // 3\n case 3: \n total += feb; // 2\n case 2:\n total += 31;\n case 1:\n total += day; \n }\n return total;\n }\n private boolean isLeapYear(int i) {\n return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0);\n }\n}\n", + "title": "1360. Number of Days Between Two Dates", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The given dates are valid dates between the years 1971 and 2100 ." + ], + "examples": [ + { + "text": "Example 1: Input:date1 = \"2019-06-29\", date2 = \"2019-06-30\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:date1 = \"2020-01-15\", date2 = \"2019-12-31\"Output:15", + "image": null + } + ], + "follow_up": null, + "solution": "from datetime import date\n\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days)\n", + "title": "1360. Number of Days Between Two Dates", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have n dice and each die has k faces numbered from 1 to k . Given three integers n , k , and target , return the number of possible ways (out of the k n total ways) to roll the dice so the sum of the face-up numbers equals target . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n, k <= 30", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 6, target = 3Output:1Explanation:You throw one die with 6 faces.\nThere is only one way to get a sum of 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 6, target = 7Output:6Explanation:You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 30, target = 500Output:222616187Explanation:The answer must be returned modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 94.21%) | Memory: 40.8 MB (Top 96.38%)\nclass Solution {\n public int numRollsToTarget(int n, int k, int target) {\n if (target < n || target > n*k) return 0;\n if (n == 1) return 1;\n\n int[][] dp = new int[n+1][n*k+1];\n for (int i = 1; i<= k; i++) {\n dp[1][i] = 1;\n }\n int mod = 1000000007;\n for (int i = 2; i <= n; i++) {\n for (int j = i; j <= i*k && j <= target; j++) {\n for (int x = 1; x <= k; x++) {\n if (j-x >= 1) {\n dp[i][j] += dp[i-1][j-x];\n if (dp[i][j] >= mod) {\n dp[i][j] %= mod;\n }\n }\n }\n }\n }\n return dp[n][target]%mod;\n }\n}", + "title": "1155. Number of Dice Rolls With Target Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have n dice and each die has k faces numbered from 1 to k . Given three integers n , k , and target , return the number of possible ways (out of the k n total ways) to roll the dice so the sum of the face-up numbers equals target . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n, k <= 30", + "1 <= target <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 6, target = 3Output:1Explanation:You throw one die with 6 faces.\nThere is only one way to get a sum of 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 6, target = 7Output:6Explanation:You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 30, target = 500Output:222616187Explanation:The answer must be returned modulo 109+ 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 782 ms (Top 50.50%) | Memory: 18.9 MB (Top 42.22%)\n\nclass Solution(object):\n def numRollsToTarget(self, n, k, target):\n \"\"\"\n :type n: int\n :type k: int\n :type target: int\n :rtype: int\n \"\"\"\n\n mem = {}\n\n def dfs(i,currSum):\n\n if currSum > target:\n return 0\n\n if i == n:\n if currSum == target:\n return 1\n return 0\n\n if (i,currSum) in mem:\n return mem[(i,currSum)]\n\n ans = 0\n for dicenumber in range(1,k+1):\n ans += dfs(i+1,currSum+dicenumber)\n\n mem[(i,currSum)] = ans\n\n return mem[(i,currSum)]\n\n return dfs(0,0) % (10**9 + 7)\n", + "title": "1155. Number of Dice Rolls With Target Sum", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\" . Notice that you are left with some integers that are separated by at least one space: \"123\" , \"34\" , \"8\" , and \"34\" . Return the number of different integers after performing the replacement operations on word . Two integers are considered different if their decimal representations without any leading zeros are different. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 1000", + "word consists of digits and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"a123bc34d8ef34\"Output:3Explanation:The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:word = \"leet1234code234\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:word = \"a1b01c001\"Output:1Explanation:The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 16.67%) | Memory: 44.5 MB (Top 21.67%)\nclass Solution {\n public int numDifferentIntegers(String word) {\n String[] arr = word.replaceAll(\"[a-zA-Z]\", \" \").split(\"\\\\s+\");\n Set set = new HashSet();\n\n for (String str : arr) {\n if (!str.isEmpty())\n set.add(String.valueOf(str.replaceAll(\"^0*\",\"\")));\n }\n\n return set.size();\n }\n}", + "title": "1805. Number of Different Integers in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\" . Notice that you are left with some integers that are separated by at least one space: \"123\" , \"34\" , \"8\" , and \"34\" . Return the number of different integers after performing the replacement operations on word . Two integers are considered different if their decimal representations without any leading zeros are different. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 1000", + "word consists of digits and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"a123bc34d8ef34\"Output:3Explanation:The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.", + "image": null + }, + { + "text": "Example 2: Input:word = \"leet1234code234\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:word = \"a1b01c001\"Output:1Explanation:The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 85.83%) | Memory: 16.50 MB (Top 46.61%)\n\nclass Solution:\n def numDifferentIntegers(self, word: str) -> int:\n word = re.findall('(\\d+)', word)\n nums = [int(i) for i in word]\n \n return len(set(nums))\n", + "title": "1805. Number of Different Integers in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the GCD of the sequence [4,6,16] is 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,10,3]Output:5Explanation:The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.", + "image": "https://assets.leetcode.com/uploads/2021/03/17/image-1.png" + }, + { + "text": "Example 2: Input:nums = [5,15,40,5,6]Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1084 ms (Top 15.1%) | Memory: 56.26 MB (Top 90.9%)\n\nclass Solution {\n int max = 0;\n Set exist = new HashSet();\n public int countDifferentSubsequenceGCDs(int[] nums) {\n getMax(nums);\n for(int num : nums) exist.add(num);\n int count = 0;\n for (int i=1;i<=max;i++) if(findGCD(i)) count++; // <---- findGCD\n return count;\n }\n public void getMax(int[] nums){\n for(int i : nums) max = Math.max(max, i);\n }\n public int gcd(int a, int b){\n return (a == 0) ? b : gcd(b % a, a);\n }\n\tpublic boolean findGCD(int num){\n int val = 0;\n for(int i = num; i <= max; i+= num)\n if(exist.contains(i)) val = gcd(i, val); // <---- gcd between two number\n return (val == num);\n }\n}", + "title": "1819. Number of Different Subsequences GCDs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums that consists of positive integers. The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly. A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. Return the number of different GCDs among all non-empty subsequences of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the GCD of the sequence [4,6,16] is 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,10,3]Output:5Explanation:The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.", + "image": "https://assets.leetcode.com/uploads/2021/03/17/image-1.png" + }, + { + "text": "Example 2: Input:nums = [5,15,40,5,6]Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5748 ms (Top 75.00%) | Memory: 34.4 MB (Top 21.43%)\nimport math\n\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n max_n = max(nums) + 1\n seen = set(nums)\n\n ans = 0\n for k in range(1, max_n): # iterate candidate k\n gcd = 0\n for multiple in range(k, max_n, k): # compute gcd of all array multiples of k\n if multiple in seen:\n gcd = math.gcd(gcd, multiple)\n if gcd == k: # check the candidate\n ans += 1\n return ans", + "title": "1819. Number of Different Subsequences GCDs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , count the total number of digit 1 appearing in all non-negative integers less than or equal to n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:6", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": " class Solution {\n\tint max(int a, int b){\n\t\tif(a>b)\n\t\t\treturn a;\n\t\telse\n\t\t\treturn b;\n\t}\n\n\tint min(int a, int b){\n\t\tif(a>b)\n\t\t\treturn b;\n\t\telse\n\t\t\treturn a;\n\t}\n\n\tpublic int countDigitOne(int n) {\n\t\tint c = 0;\n\t\tfor(int i=1; i<=n; i*=10){\n\t\t\tint divider = i*10;\n\t\t\tc += (n/divider)*i + min(max((n%divider -i + 1), 0),i);\n\t\t}\n\t\treturn c;\n\t}\n}\n\n// T.C. - O(log n)\n", + "title": "233. Number of Digit One", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , count the total number of digit 1 appearing in all non-negative integers less than or equal to n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 13Output:6", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 7.05%) | Memory: 13.8 MB (Top 68.36%)\nclass Solution:\n def countDigitOne(self, n: int) -> int:\n num = str(n)[::-1]\n count = 0\n for i in range(len(num)-1, -1, -1):\n pv = 10**i # placevalue\n # mulitplicity of current digit (how many times it will be repeated)\n mul = n//(pv*10)\n rem = n % pv # remainder of current place value\n count += mul * pv # count for number of times 1 occurs in this place when the current digit is considered to be less than 1\n # if the current digit is greater than 1 then additional number of 1's are added to the count (equivalent to the place value)\n if num[i] > '1':\n count += pv\n # if the current digit is equal to 1 then additional number of 1's are added to the count (equivalent to the number modded by the current place value)\n if num[i] == '1':\n count += rem + 1\n return count\n", + "title": "233. Number of Digit One", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n . You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: Return the total number of distinct sequences possible . Since the answer may be very large, return it modulo 10^9 + 7 . Two sequences are considered distinct if at least one element is different. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:184Explanation:Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\nSome invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).\n(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).\n(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.\nThere are a total of 184 distinct sequences possible, so we return 184.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:22Explanation:Some of the possible sequences are (1, 2), (2, 1), (3, 2).\nSome invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\nThere are a total of 22 distinct sequences possible, so we return 22.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 361 ms (Top 36.73%) | Memory: 68 MB (Top 53.88%)\nclass Solution {\n static long[][] dp;\n public int distinctSequences(int n) {\n if(n==1) return 6;\n int mod = 1_000_000_007;\n dp =new long[][]\n {\n {0,1,1,1,1,1},\n {1,0,1,0,1,0},\n {1,1,0,1,1,0},\n {1,0,1,0,1,0},\n {1,1,1,1,0,1},\n {1,0,0,0,1,0}\n };\n for(int i=2;i int:\n return func(n,-1,-1)\n", + "title": "2318. Number of Distinct Roll Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary matrix grid , where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent ( 4-directionally ) land cell or walking off the boundary of the grid . Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]Output:3Explanation:There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]Output:0Explanation:All 1s are either on the boundary or can reach the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 84.26%) | Memory: 54.7 MB (Top 92.39%)\n\n class Solution {\n public int numEnclaves(int[][] grid) {\n int maxcount = 0;\n // if(grid.length==10)\n // {\n // return 3;\n // }\n for(int i = 0;i=grid.length||coldash>=grid[0].length||\n grid[rowdash][coldash]==0)\n {\n continue;\n }\n\n if(grid[rowdash][coldash]==1)\n {\n dfs(grid,rowdash,coldash);\n }\n\n }\n\n }\n}", + "title": "1020. Number of Enclaves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n binary matrix grid , where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent ( 4-directionally ) land cell or walking off the boundary of the grid . Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 500", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]Output:3Explanation:There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]Output:0Explanation:All 1s are either on the boundary or can reach the boundary.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def recursion(self, grid, row, col, m, n):\n if 0<=row int:\n m, n = len(grid), len(grid[0])\n if not m or not n:\n return 0\n # mark all boundary lands and neighbors with 0\n for row in range(m):\n self.recursion(grid, row, 0, m, n)\n self.recursion(grid, row, n-1, m, n)\n \n for col in range(n):\n self.recursion(grid, 0, col, m, m)\n self.recursion(grid, m-1, col, m, n)\n \n result = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n result += 1\n \n \n return result\n", + "title": "1020. Number of Enclaves", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of dominoes , dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either ( a == c and b == d ), or ( a == d and b == c ) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length , and dominoes[i] is equivalent to dominoes[j] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= dominoes.length <= 4 * 10^4", + "dominoes[i].length == 2", + "1 <= dominoes[i][j] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = [[1,2],[2,1],[3,4],[5,6]]Output:1", + "image": null + }, + { + "text": "Example 2: Input:dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n /** Algorithm\n 1. Brute force cannot be used because of the set size.\n 2. Traverse the dominos and group & count them by min-max value.\n As pieces can be from 1 to 9, means their groups will be from 11 to 99.\n eg: [1,2] will be the same as [2,1]. Their value is 10 * (min(1,2)) + max(1,2)\n => 10 * 1 + 2 = 12.\n so pieces[12]++;\n 3. After finishing traversing, iterate over the counted pieces and if the count is\n > 1, calculate the combinations of X by 2.\n 4. The formula is n!/ (k! * (n-k)!)\n As n! can be very large, use the short version of it; (n * (n-1)) / 2. EG n= 40\n Eg: 40! simplify this(divide by 38!) 39 * 40\n -------- --------- \n 2! * (38!) 2\n 5. Return the total result \n */\n public int numEquivDominoPairs(int[][] dominoes) {\n int[] pieces = new int[100];\n for (int[] domino : dominoes) {\n pieces[10 * Math.min(domino[0], domino[1]) + Math.max(domino[0], domino[1])]++;\n }\n int pairs = 0;\n for (int i = 11; i <= 99; i++) {\n if (pieces[i] > 1) {\n pairs += getCombinations(pieces[i]);\n }\n }\n \n return pairs; \n }\n \n private int getCombinations(int n) {\n return (n * (n-1)) / 2;\n }\n}\n", + "title": "1128. Number of Equivalent Domino Pairs", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list of dominoes , dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either ( a == c and b == d ), or ( a == d and b == c ) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length , and dominoes[i] is equivalent to dominoes[j] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= dominoes.length <= 4 * 10^4", + "dominoes[i].length == 2", + "1 <= dominoes[i][j] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = [[1,2],[2,1],[3,4],[5,6]]Output:1", + "image": null + }, + { + "text": "Example 2: Input:dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "import math\nclass Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n d=dict()\n for i in dominoes:\n i.sort() #Just to make everything equal and comparable\n if(tuple(i) in d.keys()): #In python, lists are unhashable so converted the list into tuples\n d[tuple(i)]+=1\n else:\n d[tuple(i)]=1\n count=0\n for x,y in d.items():\n if(y>1):\n\t\t\t\tcount+=y*(y-1)//2 #To check the number of pairs, if 2 elements pairs is 1,if 3 pair is 3 and so on.....formula is n*n-1/2\n return count\n \n\n\n", + "title": "1128. Number of Equivalent Domino Pairs", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed positive integer array nums and a positive integer k . A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Return the number of distinct excellent pairs . Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d . For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Both the numbers num1 and num2 exist in the array nums .", + "The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k , where OR is the bitwise OR operation and AND is the bitwise AND operation." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3Output:5Explanation:The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1], k = 10Output:0Explanation:There are no excellent pairs for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 785 ms (Top 5.01%) | Memory: 176.5 MB (Top 5.07%)\nclass Solution {\n public long countExcellentPairs(int[] nums, int k) {\n HashMap> map = new HashMap<>();\n for(int i : nums){\n int x = Integer.bitCount(i);\n map.putIfAbsent(x,new HashSet<>());\n map.get(x).add(i);\n }\n long ans = 0;\n HashSet vis = new HashSet<>();\n for(int i : nums){\n if(vis.contains(i)) continue;\n int need = Math.max(0,k-Integer.bitCount(i));\n for(int key : map.keySet()) // runs at max 30 times\n if(key >= need) ans += (long) map.get(key).size();\n vis.add(i);\n }\n return ans;\n }\n}", + "title": "2354. Number of Excellent Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed positive integer array nums and a positive integer k . A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Return the number of distinct excellent pairs . Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d . For example, (1, 2) and (2, 1) are distinct. Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Both the numbers num1 and num2 exist in the array nums .", + "The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k , where OR is the bitwise OR operation and AND is the bitwise AND operation." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3Output:5Explanation:The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1], k = 10Output:0Explanation:There are no excellent pairs for this array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2052 ms (Top 44.44%) | Memory: 32.2 MB (Top 22.19%)\n\nclass Solution:\n def countExcellentPairs(self, nums: List[int], k: int) -> int:\n hamming = sorted([self.hammingWeight(num) for num in set(nums)])\n ans = 0\n for h in hamming:\n ans += len(hamming) - bisect.bisect_left(hamming, k - h)\n return ans\n\n def hammingWeight(self, n):\n ans = 0\n while n:\n n &= (n - 1)\n ans += 1\n return ans", + "title": "2354. Number of Excellent Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array flowers , where flowers[i] = [start i , end i ] means the i th flower will be in full bloom from start i to end i ( inclusive ). You are also given a 0-indexed integer array persons of size n , where persons[i] is the time that the i th person will arrive to see the flowers. Return an integer array answer of size n , where answer[i] is the number of flowers that are in full bloom when the i th person arrives. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= flowers.length <= 5 * 10^4", + "flowers[i].length == 2", + "1 <= start i <= end i <= 10^9", + "1 <= persons.length <= 5 * 10^4", + "1 <= persons[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]Output:[1,2,2,2]Explanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg" + }, + { + "text": "Example 2: Input:flowers = [[1,10],[3,3]], persons = [3,3,2]Output:[2,2,1]Explanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 204 ms (Top 31.03%) | Memory: 131.5 MB (Top 7.83%)\nclass Solution {\npublic int[] fullBloomFlowers(int[][] flowers, int[] persons) {\n int n = persons.length;\n int[] result = new int[n];\n\n TreeMap treeMap = new TreeMap<>();\n // See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clean-Code\n for (int[] flower : flowers) {\n treeMap.put(flower[0], treeMap.getOrDefault(flower[0], 0) + 1);\n // use end + 1 instead of end\n treeMap.put(flower[1] + 1, treeMap.getOrDefault(flower[1] + 1, 0) - 1);\n }\n\n TreeMap sum = new TreeMap<>();\n int prev = 0;\n for (Map.Entry entry : treeMap.entrySet()) {\n prev += entry.getValue();\n sum.put(entry.getKey(), prev);\n }\n\n for (int i = 0; i < n; i++) {\n Map.Entry entry = sum.floorEntry(persons[i]);\n // if entry is null then result[i] = 0\n if (entry != null) result[i] = entry.getValue();\n }\n return result;\n }\n}", + "title": "2251. Number of Flowers in Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed 2D integer array flowers , where flowers[i] = [start i , end i ] means the i th flower will be in full bloom from start i to end i ( inclusive ). You are also given a 0-indexed integer array persons of size n , where persons[i] is the time that the i th person will arrive to see the flowers. Return an integer array answer of size n , where answer[i] is the number of flowers that are in full bloom when the i th person arrives. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= flowers.length <= 5 * 10^4", + "flowers[i].length == 2", + "1 <= start i <= end i <= 10^9", + "1 <= persons.length <= 5 * 10^4", + "1 <= persons[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]Output:[1,2,2,2]Explanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg" + }, + { + "text": "Example 2: Input:flowers = [[1,10],[3,3]], persons = [3,3,2]Output:[2,2,1]Explanation:The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.", + "image": "https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 931 ms (Top 66.6%) | Memory: 45.16 MB (Top 22.2%)\n\nclass Solution:\n def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n #we ADD flowers in the order in which they start, but we remove them in the order they \n #end. For this reason, we sort the flowers by starting time but put them in a heap, \n #in which we remove them by ending time\n starts = sorted(flowers) #keep flowers untouched in case array should be constant\n blooming = [] #heap of active flowers\n answer = [-1] * len(people) #output array\n hours = [(people[i], i) for i in range(len(people))] #the people, ordered and indexed by their time\n hours.sort()\n\n i = 0 #going through starts\n for hour, person in hours:\n #add all flowers that have started\n while i < len(starts) and starts[i][0] <= hour:\n heappush(blooming, (starts[i][1], starts[i][0]))\n i += 1\n #now remove all flowers that have ended. Note that we only care about the absolute smallest, \n #and in python minheaps, that is always the first element - even if no other element's order \n #is guaranteed\n while blooming and blooming[0][0] < hour: #as long as the soonest to end blooming flower hasn't already stopped\n heappop(blooming)\n answer[person] = len(blooming)\n \n return answer", + "title": "2251. Number of Flowers in Full Bloom", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree and an integer distance . A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance . Return the number of good leaf node pairs in the tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 10 ].", + "1 <= Node.val <= 100", + "1 <= distance <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,4], distance = 3Output:1Explanation:The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7], distance = 3Output:2Explanation:The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e2.jpg" + }, + { + "text": "Example 3: Input:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3Output:1Explanation:The only good pair is [2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 86 ms (Top 15.89%) | Memory: 53.6 MB (Top 51.73%)\nclass Solution {\n static int res;\n public int countPairs(TreeNode root, int distance) {\n res=0;\n rec(root,distance);\n return res;\n }\n static List rec(TreeNode root,int dist){\n if(root==null){\n return new LinkedList();\n }\n List left=rec(root.left,dist);\n List right=rec(root.right,dist);\n if(left.size()==0&&right.size()==0){\n List temp=new LinkedList<>();\n temp.add(1);\n return temp;\n }\n for(int i:left){\n for(int j:right){\n if(i+j<=dist){\n res++;\n }\n }\n }\n List temp=new LinkedList<>();\n for(int i:left){\n temp.add(i+1);\n }\n for(int i:right){\n temp.add(i+1);\n }\n return temp;\n }\n}", + "title": "1530. Number of Good Leaf Nodes Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree and an integer distance . A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance . Return the number of good leaf node pairs in the tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 10 ].", + "1 <= Node.val <= 100", + "1 <= distance <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,4], distance = 3Output:1Explanation:The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7], distance = 3Output:2Explanation:The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/e2.jpg" + }, + { + "text": "Example 3: Input:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3Output:1Explanation:The only good pair is [2,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n adjList=defaultdict(list)\n leaves=[]\n ct=0\n \n [#undirected graph two way using parent and node in postorder style]\n def dfs(node, parent):\n if node:\n if not node.left and not node.right:\n leaves.append(node)\n adjList[node].append(parent)\n adjList[parent].append(node)\n dfs(node.left,node)\n dfs(node.right,node)\n \n [#construct graph and get all the leaves]\n dfs(root, None)\n \n #bfs from each leaf till we find another leaf\n for leaf in leaves:\n q=deque([(leaf,0)] )\n seen=set()\n while q:\n curr,dist = q.popleft()\n seen.add(curr)\n if dist>distance:\n break \n for nbr in adjList[curr]:\n if nbr and nbr not in seen:\n if nbr in leaves and dist+1<=distance:\n ct+=1\n q.append((nbr,dist+1))\n \n return ct//2", + "title": "1530. Number of Good Leaf Nodes Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , return the number of good pairs . A pair (i, j) is called good if nums[i] == nums[j] and i < j . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1,1,3]Output:4Explanation:There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1]Output:6Explanation:Each pair in the array aregood.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 85.5%) | Memory: 40.27 MB (Top 18.8%)\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int len =nums.length;\n int counter=0;\n for (int i =0;i int:\n res = 0\n\t\tnums_set = set(nums)\n nums_coppy = nums\n for number in nums_set:\n number_found = []\n deleted = 0\n while True:\n try:\n found = nums_coppy.index(number)\n nums_coppy.remove(number)\n if deleted > 0:\n number_found.append(found + deleted)\n else:\n number_found.append(found + deleted)\n deleted += 1\n except:\n comb = list(combinations(number_found, 2))\n res += len(comb)\n break\n return res\n", + "title": "1512. Number of Good Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s . A split is called good if you can split s into two non-empty strings s left and s right where their concatenation is equal to s (i.e., s left + s right = s ) and the number of distinct letters in s left and s right is the same. Return the number of good splits you can make in s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacaba\"Output:2Explanation:There are 5 ways to split\"aacaba\"and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"Output:1Explanation:Split the string as follows (\"ab\", \"cd\").", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSplits(String s) {\n int a[] = new int[26];\n int b[] = new int[26];\n int ds1=0,ds2=0;\n int count=0;\n for(int i=0;i int:\n one = set()\n two = set()\n dic = {}\n \n for i in s:\n dic[i] = dic.get(i, 0) + 1\n two.add(i)\n tot = 0\n \n for i in s:\n one.add(i)\n dic[i] -= 1\n if dic[i] == 0:\n two.remove(i)\n \n if len(one) == len(two):\n tot += 1\n return tot\n", + "title": "1525. Number of Good Ways to Split a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer matrix grid , where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7 . Two paths are considered different if they do not have exactly the same sequence of visited cells. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[3,4]]Output:8Explanation:The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.", + "image": "https://assets.leetcode.com/uploads/2022/05/10/griddrawio-4.png" + }, + { + "text": "Example 2: Input:grid = [[1],[2]]Output:3Explanation:The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n long[][] dp;\n int mod = 1_000_000_007;\n public int countPaths(int[][] grid) {\n dp = new long[grid.length][grid[0].length];\n long sum=0L;\n for(int i=0;i=grid.length||j>=grid[0].length) return 0;\n if(grid[i][j]<=pre) return 0;\n if(dp[i][j]>0) return dp[i][j];\n long a = dfs(grid,i+1,j,grid[i][j]);\n long b = dfs(grid,i,j+1,grid[i][j]);\n long c = dfs(grid,i-1,j,grid[i][j]);\n long d = dfs(grid,i,j-1,grid[i][j]);\n dp[i][j] = (1+a+b+c+d)%mod;\n return dp[i][j];\n }\n}\n", + "title": "2328. Number of Increasing Paths in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid , where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7 . Two paths are considered different if they do not have exactly the same sequence of visited cells. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1],[3,4]]Output:8Explanation:The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.", + "image": "https://assets.leetcode.com/uploads/2022/05/10/griddrawio-4.png" + }, + { + "text": "Example 2: Input:grid = [[1],[2]]Output:3Explanation:The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2506 ms (Top 21.4%) | Memory: 118.67 MB (Top 7.1%)\n\nclass Solution:\n def __init__(self):\n self.dp = None\n self.di = [0, 0, -1, 1]\n self.dj = [-1, 1, 0, 0]\n self.mod = 1000000007\n \n def countPaths(self, grid):\n n = len(grid)\n m = len(grid[0])\n self.dp = [[0] * m for _ in range(n)]\n ans = 0\n for i in range(n):\n for j in range(m):\n ans = (ans + self.dfs(grid, i, j, -1)) % self.mod\n return ans\n \n def dfs(self, grid, i, j, prev):\n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= prev:\n return 0\n if self.dp[i][j] != 0:\n return self.dp[i][j]\n self.dp[i][j] = 1\n for k in range(4):\n self.dp[i][j] += self.dfs(grid, i + self.di[k], j + self.dj[k], grid[i][j])\n self.dp[i][j] %= self.mod\n return self.dp[i][j] % self.mod\n", + "title": "2328. Number of Increasing Paths in a Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]Output:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 97.42%) | Memory: 50.7 MB (Top 93.44%)\nclass Solution {\n public int numIslands(char[][] grid) {\n int count = 0;\n int r = grid.length;\n int c = grid[0].length;\n for(int i=0;i=grid.length || j>=grid[0].length || grid[i][j]=='0'){\n return;\n }\n grid[i][j] = '0';\n dfs(grid,i,j+1);\n dfs(grid,i,j-1);\n dfs(grid,i+1,j);\n dfs(grid,i-1,j);\n }\n}", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]Output:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 353 ms (Top 84.15%) | Memory: 28.7 MB (Top 5.01%)\n\nseen=set()\ndef dfs(i,j,m,n,grid):\n global seen\n if (i<0 or i>=m or j<0 or j>=n):return\n if (i,j) in seen:return\n seen.add((i,j))\n if grid[i][j]==\"1\":\n dfs(i,j+1,m,n,grid)\n dfs(i,j-1,m,n,grid)\n dfs(i+1,j,m,n,grid)\n dfs(i-1,j,m,n,grid)\n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n global seen\n m=len(grid) #no of rows\n n=len(grid[0]) #no of columns\n count=0\n for i in range(m):\n for j in range(n):\n if (i,j) not in seen and grid[i][j]==\"1\":\n dfs(i,j,m,n,grid)\n count+=1\n seen.clear()\n return count", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the i th row, consisting of '0' s and '1' s. '0' means the cell is empty, while '1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The two devices are located on two different rows : r 1 and r 2 , where r 1 < r 2 .", + "For each row i where r 1 < i < r 2 , there are no security devices in the i th row." + ], + "examples": [ + { + "text": "Example 1: Input:bank = [\"011001\",\"000000\",\"010100\",\"001000\"]Output:8Explanation:Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0throw with any on the 3rdrow.\nThis is because the 2ndrow contains security devices, which breaks the second condition.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg" + }, + { + "text": "Example 2: Input:bank = [\"000\",\"111\",\"000\"]Output:0Explanation:There does not exist two devices located on two different rows.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 22.34%) | Memory: 54.9 MB (Top 32.26%)\nclass Solution {\n public int numberOfBeams(String[] bank) {\n int ans = 0, pre = 0;\n for (int i = 0;i < bank.length; i ++) {\n int n = 0;\n for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++;\n if (n == 0) continue;\n ans += pre * n;;\n pre = n;\n }\n return ans;\n }\n}", + "title": "2125. Number of Laser Beams in a Bank", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the i th row, consisting of '0' s and '1' s. '0' means the cell is empty, while '1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The two devices are located on two different rows : r 1 and r 2 , where r 1 < r 2 .", + "For each row i where r 1 < i < r 2 , there are no security devices in the i th row." + ], + "examples": [ + { + "text": "Example 1: Input:bank = [\"011001\",\"000000\",\"010100\",\"001000\"]Output:8Explanation:Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0throw with any on the 3rdrow.\nThis is because the 2ndrow contains security devices, which breaks the second condition.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg" + }, + { + "text": "Example 2: Input:bank = [\"000\",\"111\",\"000\"]Output:0Explanation:There does not exist two devices located on two different rows.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def numberOfBeams(self, bank):\n ans, pre = 0, 0\n for s in bank:\n n = s.count('1')\n if n == 0: continue\n ans += pre * n\n pre = n\n return ans\n", + "title": "2125. Number of Laser Beams in a Bank", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a' , widths[1] is the width of 'b' , and so on. You are trying to write s across several lines, where each line is no longer than 100 pixels . Starting at the beginning of s , write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s , continue writing as many letters as you can on the second line. Continue this process until you have written all of s . Return an array result of length 2 where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "result[0] is the total number of lines.", + "result[1] is the width of the last line in pixels." + ], + "examples": [ + { + "text": "Example 1: Input:widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"Output:[3,60]Explanation:You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.", + "image": null + }, + { + "text": "Example 2: Input:widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"Output:[2,4]Explanation:You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 73.53%) | Memory: 41.8 MB (Top 76.89%)\nclass Solution {\n public int[] numberOfLines(int[] widths, String s) {\n int sum=0,count=0;\n for(int j=0;j100)\n {\n j--;\n count++;\n sum=0;\n continue;\n }\n }\n int[] arr = new int[2];\n arr[0]=count+1;\n arr[1]=sum;\n return arr;\n }\n}", + "title": "806. Number of Lines To Write String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a' , widths[1] is the width of 'b' , and so on. You are trying to write s across several lines, where each line is no longer than 100 pixels . Starting at the beginning of s , write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s , continue writing as many letters as you can on the second line. Continue this process until you have written all of s . Return an array result of length 2 where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "result[0] is the total number of lines.", + "result[1] is the width of the last line in pixels." + ], + "examples": [ + { + "text": "Example 1: Input:widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"Output:[3,60]Explanation:You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.", + "image": null + }, + { + "text": "Example 2: Input:widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"Output:[2,4]Explanation:You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfLines(self, w: List[int], s: str) -> List[int]:\n r=[0]*2\n px=0\n l=1\n for i in range(len(s)):\n px+=w[ord(s[i])-97]\n if px>100:\n l+=1\n px=w[ord(s[i])-97]\n \n print(ord(s[i]))\n r[0]=l\n r[1]=px\n return r\n ", + "title": "806. Number of Lines To Write String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2000", + "-10^6 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,4,7]Output:2Explanation:The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2]Output:5Explanation:The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 72.27%) | Memory: 44.7 MB (Top 20.08%)\nclass Solution {\n public int findNumberOfLIS(int[] nums) {\n int N = nums.length;\n int []dp =new int[N];\n int []count = new int[N];\n Arrays.fill(dp,1);Arrays.fill(count,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j]+1;\n //inherit a new one\n count[i]=count[j];\n maxi = Math.max(dp[i],maxi);\n }else if(nums[j] < nums[i] && dp[j]+1 == dp[i]){\n //got one as same len, increase count\n count[i]+=count[j];\n }\n }\n }//for ends\n int maxlis=0;\n for(int i=0;i int:\n \n if not nums or len(nums) == 0:\n return 0\n \n def find_pos(sub, val):\n left, right = 0, len(sub) - 1\n while left < right:\n mid = (left + right) >> 1\n if sub[mid] >= val: \n right = mid\n else:\n left = mid + 1\n return left \n \n \n sub_list = []\n \n for val in nums:\n if len(sub_list) == 0 or val > sub_list[-1][-1][0]:\n # should append a new element at the end\n cur_count = sum([x[1] for x in sub_list[-1] if val > x[0]]) if len(sub_list) != 0 else 1\n sub_list.append([(val, cur_count)])\n else:\n # get the last number to turn it back to a LIS problem\n cur_sub = [array[-1][0] for array in sub_list]\n pos = find_pos(cur_sub, val)\n # if pos == 0, means it is smallest, no need to look the previous level and set it to be 1\n cur_count = sum([x[1] for x in sub_list[pos - 1] if val > x[0]]) if pos > 0 else 1\n sub_list[pos].append((val, cur_count))\n \n return sum([x[1] for x in sub_list[-1]])", + "title": "673. Number of Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s and an array of strings words , return the number of words[i] that is a subsequence of s . 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. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]Output:3Explanation:There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numMatchingSubseq(String s, String[] words) {\n int count = 0;\n Map map = new HashMap<>();\n for(String word : words){\n if(!map.containsKey(word)){\n map.put(word, 1);\n }\n else{\n map.put(word, map.get(word)+1);\n }\n }\n for(String word : map.keySet()){\n if(isSeq(word, s)){\n count += map.get(word);\n }\n }\n return count;\n }\n public boolean isSeq(String s1, String s2){\n int s1ind = 0;\n int s2ind = 0;\n int counter = 0;\n if(s1.length() > s2.length()){\n return false;\n }\n while(s1ind < s1.length() && s2ind < s2.length()){\n if(s1.charAt(s1ind) == s2.charAt(s2ind)){\n counter++;\n s1ind++;\n s2ind++;\n }\n else{\n s2ind++;\n }\n }\n return counter == s1.length();\n }\n}\n", + "title": "792. Number of Matching Subsequences", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s and an array of strings words , return the number of words[i] that is a subsequence of s . 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. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]Output:3Explanation:There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 851 ms (Top 55.45%) | Memory: 16.4 MB (Top 32.26%)\nclass Solution:\n def numMatchingSubseq(self, s: str, words: List[str]) -> int:\n word_dict = defaultdict(list)\n numMatch = 0\n # add words into bucket with key as order of the first letter\n for w in words:\n word_dict[ord(w[0])-ord('a')].append(w)\n # loop through the characters in s\n for c in s:\n qualified = word_dict[ord(c)-ord('a')]\n word_dict[ord(c)-ord('a')] = []\n for q in qualified:\n # if the word starts with the specified letter. i.e this is the last letter of the word\n if len(q) == 1:\n numMatch += 1\n else:\n word_dict[ord(q[1])-ord('a')].append(q[1:])\n return numMatch\n", + "title": "792. Number of Matching Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: Given n , goal , and k , return the number of possible playlists that you can create . Since the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Every song is played at least once .", + "A song can only be played again only if k other songs have been played." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, goal = 3, k = 1Output:6Explanation:There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].", + "image": null + }, + { + "text": "Example 2: Input:n = 2, goal = 3, k = 0Output:6Explanation:There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].", + "image": null + }, + { + "text": "Example 3: Input:n = 2, goal = 3, k = 1Output:2Explanation:There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 77.87%) | Memory: 13.9 MB (Top 86.89%)\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n prev_p, cur_p = [0] * (n+1), [0] * (n+1)\n\n for i in range(k+1, goal+1):\n if i == k+1:\n prev_p[i] = math.factorial(n) // math.factorial(n-i)\n else:\n for j in range(k+1, min(i, n)+1):\n cur_p[j] = prev_p[j-1] * (n - j + 1) + prev_p[j] * (j-k)\n prev_p, cur_p = cur_p, [0] * (n+1)\n return prev_p[n] % (10**9 + 7)", + "title": "920. Number of Music Playlists", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges . The root of the tree is the node 0 , and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i] ). The edges array is given on the form edges[i] = [a i , b i ] , which means there is an edge between nodes a i and b i in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the i th node which have the same label as node i . A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "labels.length == n", + "labels is consisting of only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"Output:[2,1,1,1,1,1,1]Explanation:Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"Output:[4,2,1,1]Explanation:The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" + }, + { + "text": "Example 3: Input:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"Output:[3,2,1,1,1]", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] res;\n\n public int[] countSubTrees(int n, int[][] edges, String labels) {\n res = new int[n];\n Map> adjList = new HashMap<>();\n for (int i = 0; i < n; i++) {\n adjList.put(i, new ArrayList<>());\n }\n for (int[] edge : edges) {\n adjList.get(edge[0]).add(edge[1]);\n adjList.get(edge[1]).add(edge[0]);\n }\n postOrderDfs(adjList, labels, 0, -1);\n return res;\n }\n\n int[] postOrderDfs(Map> adjList, String labels, int n, int parent) {\n int[] chars = new int[26];\n chars[labels.charAt(n) - 'a']++;\n for (int next : adjList.get(n)) {\n if (next != parent) mergeArrCounts(chars, postOrderDfs(adjList, labels, next, n));\n }\n res[n] = chars[labels.charAt(n) - 'a'];\n return chars;\n }\n\n // Merge from B to A\n void mergeArrCounts(int[] A, int[] B) {\n for (int i = 0; i < 26; i++) {\n A[i] += B[i];\n }\n }\n}\n", + "title": "1519. Number of Nodes in the Sub-Tree With the Same Label", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges . The root of the tree is the node 0 , and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i] ). The edges array is given on the form edges[i] = [a i , b i ] , which means there is an edge between nodes a i and b i in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the i th node which have the same label as node i . A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "labels.length == n", + "labels is consisting of only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"Output:[2,1,1,1,1,1,1]Explanation:Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" + }, + { + "text": "Example 2: Input:n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"Output:[4,2,1,1]Explanation:The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" + }, + { + "text": "Example 3: Input:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"Output:[3,2,1,1,1]", + "image": "https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n we can solve this using dfs based approach\n identify the root of the tree and start a dfs from there \n \"\"\"\n def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:\n graph_map = {i: set() for i in range(n)}\n for edge in edges:\n graph_map[edge[0]].add(edge[1])\n graph_map[edge[1]].add(edge[0])\n \n result = [None for _ in range(n)]\n \n visited = set()\n def dfs(index):\n visited.add(index)\n temp = [0 for _ in range(26)]\n temp[ord(labels[index])-97]+=1\n for idx in graph_map[index]:\n if idx not in visited:\n x = dfs(idx)\n temp = [a + b for a, b in zip(temp, x)]\n result[index] = temp[ord(labels[index])-97]\n return temp\n \n dfs(0)\n return result\n", + "title": "1519. Number of Nodes in the Sub-Tree With the Same Label", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a i , b i ] represents a connection between computers a i and b i . Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections . You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected . If it is not possible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= connections.length <= min(n * (n - 1) / 2, 10^5 )", + "connections[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated connections.", + "No two computers are connected by more than one cable." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[0,2],[1,2]]Output:1Explanation:Remove cable between computer 1 and 2 and place between computers 1 and 3.", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png" + }, + { + "text": "Example 2: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png" + }, + { + "text": "Example 3: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]Output:-1Explanation:There are not enough cables.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int makeConnected(int n, int[][] connections) {\n int m = connections.length;\n if(m < n - 1) return -1;\n UnionFind uf = new UnionFind(n);\n \n for(int[] connection: connections){\n uf.union(connection[0], connection[1]);\n }\n return uf.getIsolated();\n }\n}\nclass UnionFind{\n int[] root;\n int[] rank;\n int isolated;\n public UnionFind(int n){\n root = new int[n];\n rank = new int[n];\n for(int i = 0; i < n; i++){\n root[i] = i;\n rank[i] = 1;\n }\n isolated = 0;\n }\n public int find(int x){\n if(root[x] != x) root[x] = find(root[x]);\n return root[x];\n }\n public void union(int x, int y){\n int rootx = find(x);\n int rooty = find(y);\n if(rootx == rooty) return;\n if(rank[rootx] > rank[rooty]){\n root[rooty] = rootx;\n }else if(rank[rootx] < rank[rooty]){\n root[rootx] = rooty;\n }else{\n root[rootx] = rooty;\n rank[rooty] += 1;\n }\n }\n public int getIsolated(){\n for(int i = 0; i < root.length; i ++){\n if(root[i] == i) isolated++;\n }\n return isolated - 1;\n }\n}\n", + "title": "1319. Number of Operations to Make Network Connected", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a i , b i ] represents a connection between computers a i and b i . Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections . You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected . If it is not possible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= connections.length <= min(n * (n - 1) / 2, 10^5 )", + "connections[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "There are no repeated connections.", + "No two computers are connected by more than one cable." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, connections = [[0,1],[0,2],[1,2]]Output:1Explanation:Remove cable between computer 1 and 2 and place between computers 1 and 3.", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png" + }, + { + "text": "Example 2: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png" + }, + { + "text": "Example 3: Input:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]Output:-1Explanation:There are not enough cables.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 772 ms (Top 55.10%) | Memory: 34.3 MB (Top 72.08%)\nclass Solution(object):\n def __init__(self):\n self.parents = []\n self.count = []\n\n def makeConnected(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n if len(connections) < n-1:\n return -1\n self.parents = [i for i in range(n)]\n self.count = [1 for _ in range(n)]\n for connection in connections:\n a, b = connection[0], connection[1]\n self.union(a, b)\n return len({self.find(i) for i in range(n)}) - 1\n\n def find(self, node):\n \"\"\"\n :type node: int\n :rtype: int\n \"\"\"\n while(node != self.parents[node]):\n node = self.parents[node];\n return node\n\n def union(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: None\n \"\"\"\n a_parent, b_parent = self.find(a), self.find(b)\n a_size, b_size = self.count[a_parent], self.count[b_parent]\n\n if a_parent != b_parent:\n if a_size < b_size:\n self.parents[a_parent] = b_parent\n self.count[b_parent] += a_size\n else:\n self.parents[b_parent] = a_parent\n self.count[a_parent] += b_size", + "title": "1319. Number of Operations to Make Network Connected", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D integer array orders , where each orders[i] = [price i , amount i , orderType i ] denotes that amount i orders have been placed of type orderType i at the price price i . The orderType i is: Note that orders[i] represents a batch of amount i independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i . There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input . Since this number can be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 if it is a batch of buy orders, or", + "1 if it is a batch of sell orders." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]Output:6Explanation:Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rdorder is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4thorder is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex1.png" + }, + { + "text": "Example 2: Input:orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]Output:999999984Explanation:Here is what happens with the orders:\n- 109orders of type sell with price 7 are placed. There are no buy orders, so the 109orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109+ 7).", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n PriorityQueue buyBackLog;\n PriorityQueue sellBackLog;\n \n static int MOD = 1_000_000_007;\n \n \n public int getNumberOfBacklogOrders(int[][] orders) {\n \n //max heap, heapify on price\n buyBackLog = new PriorityQueue((a, b) -> (b.price - a.price));\n //min heap, heapify on price\n sellBackLog = new PriorityQueue((a, b) -> (a.price - b.price));\n \n \n //handle all order\n for(int[] order : orders){\n int price = order[0];\n int quantity = order[1];\n int orderType = order[2];\n \n if(orderType == 0){\n //buy order \n handleBuyOrder(new Order(price, quantity));\n \n }else if(orderType == 1){ \n //sell order\n handleSellOrder(new Order(price, quantity));\n }\n }\n \n long counts = 0L;\n \n //count buy backlog\n while(!buyBackLog.isEmpty()){\n counts += buyBackLog.remove().quantity; \n counts %= MOD;\n }\n \n //count sell backlog\n while(!sellBackLog.isEmpty()){\n counts += sellBackLog.remove().quantity; \n counts %= MOD;\n }\n \n \n return (int) (counts % MOD);\n }\n \n \n \n \n private void handleBuyOrder(Order buyOrder){\n //just add buyorder, if there is no sell back log\n if(sellBackLog.isEmpty()){\n buyBackLog.add(buyOrder);\n return;\n }\n \n \n while(!sellBackLog.isEmpty() && buyOrder.price >= sellBackLog.peek().price && buyOrder.quantity > 0){\n //selloder with minumum price\n Order sellOrder = sellBackLog.remove();\n \n if(buyOrder.quantity >= sellOrder.quantity){\n buyOrder.quantity -= sellOrder.quantity;\n sellOrder.quantity = 0;\n } else {\n //decrement sell order, add remaining sellorder\n sellOrder.quantity -= buyOrder.quantity;\n sellBackLog.add(sellOrder);\n \n buyOrder.quantity = 0;\n }\n }\n \n //add reaming buyorder\n if(buyOrder.quantity > 0){\n buyBackLog.add(buyOrder);\n }\n }\n \n \n private void handleSellOrder(Order sellOrder){\n //just add sell order, if there is no buy backlog\n if(buyBackLog.isEmpty()){\n sellBackLog.add(sellOrder);\n return;\n }\n \n \n while(!buyBackLog.isEmpty() && buyBackLog.peek().price >= sellOrder.price && sellOrder.quantity > 0){\n //buy order with maximum price\n Order buyOrder = buyBackLog.remove();\n \n if(sellOrder.quantity >= buyOrder.quantity){\n sellOrder.quantity -= buyOrder.quantity;\n buyOrder.quantity = 0;\n \n }else{\n //decrement buy order quantity, add remaining buyorder\n buyOrder.quantity -= sellOrder.quantity;\n buyBackLog.add(buyOrder);\n \n sellOrder.quantity = 0;\n }\n }\n \n //add remaining sell order\n if(sellOrder.quantity > 0){\n sellBackLog.add(sellOrder);\n }\n }\n}\n\nclass Order{\n int price;\n int quantity;\n \n public Order(int price, int quantity){\n this.price = price;\n this.quantity = quantity;\n }\n}\n", + "title": "1801. Number of Orders in the Backlog", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 2D integer array orders , where each orders[i] = [price i , amount i , orderType i ] denotes that amount i orders have been placed of type orderType i at the price price i . The orderType i is: Note that orders[i] represents a batch of amount i independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i . There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input . Since this number can be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 if it is a batch of buy orders, or", + "1 if it is a batch of sell orders." + ], + "examples": [ + { + "text": "Example 1: Input:orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]Output:6Explanation:Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rdorder is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4thorder is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex1.png" + }, + { + "text": "Example 2: Input:orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]Output:999999984Explanation:Here is what happens with the orders:\n- 109orders of type sell with price 7 are placed. There are no buy orders, so the 109orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109+ 7).", + "image": "https://assets.leetcode.com/uploads/2021/03/11/ex2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 689 ms (Top 70.7%) | Memory: 55.89 MB (Top 32.0%)\n\nclass Solution:\n def getNumberOfBacklogOrders(self, orders):\n b, s = [], []\n heapq.heapify(b)\n heapq.heapify(s)\n \n for p,a,o in orders:\n if o == 0:\n heapq.heappush(b, [-p, a])\n \n elif o == 1:\n heapq.heappush(s, [p, a])\n \n # Check \"good\" condition\n while s and b and s[0][0] <= -b[0][0]:\n a1, a2 = b[0][1], s[0][1]\n \n if a1 > a2:\n b[0][1] -= a2\n heapq.heappop(s)\n elif a1 < a2:\n s[0][1] -= a1\n heapq.heappop(b)\n else:\n heapq.heappop(b)\n heapq.heappop(s)\n \n count = sum([a for p,a in b]) + sum([a for p,a in s])\n return count % (10**9 + 7)", + "title": "1801. Number of Orders in the Backlog", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles , where rectangles[i] = [width i , height i ] denotes the width and height of the i th rectangle. Two rectangles i and j ( i < j ) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if width i /height i == width j /height j (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == rectangles.length", + "1 <= n <= 10^5", + "rectangles[i].length == 2", + "1 <= width i , height i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[4,8],[3,6],[10,20],[15,30]]Output:6Explanation:The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[4,5],[7,8]]Output:0Explanation:There are no interchangeable pairs of rectangles.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 81.13%) | Memory: 99.50 MB (Top 16.9%)\n\nclass Solution {\n \n public long interchangeableRectangles(int[][] rectangles) {\n Map hash = new HashMap<>();\n \n for (int i = 0; i < rectangles.length; i++) {\n Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]);\n \n hash.put(tmp, hash.getOrDefault(tmp, 0L) + 1);\n }\n \n long ans = 0;\n for (Map.Entry entry : hash.entrySet()) {\n if (entry.getValue() > 1) {\n Long n = entry.getValue();\n ans += (n * (n - 1)) / 2;\n }\n }\n \n return ans;\n }\n}\n", + "title": "2001. Number of Pairs of Interchangeable Rectangles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles , where rectangles[i] = [width i , height i ] denotes the width and height of the i th rectangle. Two rectangles i and j ( i < j ) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if width i /height i == width j /height j (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == rectangles.length", + "1 <= n <= 10^5", + "rectangles[i].length == 2", + "1 <= width i , height i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[4,8],[3,6],[10,20],[15,30]]Output:6Explanation:The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[4,5],[7,8]]Output:0Explanation:There are no interchangeable pairs of rectangles.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n ratios = defaultdict(int)\n for x, y in rectangles:\n ratios[x/y] += 1\n res = 0\n for val in ratios.values():\n res += (val*(val-1)//2)\n return res\n", + "title": "2001. Number of Pairs of Interchangeable Rectangles", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digit strings nums and a digit string target , return the number of pairs of indices (i, j) (where i != j ) such that the concatenation of nums[i] + nums[j] equals target . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 100", + "1 <= nums[i].length <= 100", + "2 <= target.length <= 100", + "nums[i] and target consist of digits.", + "nums[i] and target do not have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"Output:4Explanation:Valid pairs are:\n- (0, 1): \"777\" + \"7\"\n- (1, 0): \"7\" + \"777\"\n- (2, 3): \"77\" + \"77\"\n- (3, 2): \"77\" + \"77\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"Output:2Explanation:Valid pairs are:\n- (0, 1): \"123\" + \"4\"\n- (2, 3): \"12\" + \"34\"", + "image": null + }, + { + "text": "Example 3: Input:nums = [\"1\",\"1\",\"1\"], target = \"11\"Output:6Explanation:Valid pairs are:\n- (0, 1): \"1\" + \"1\"\n- (1, 0): \"1\" + \"1\"\n- (0, 2): \"1\" + \"1\"\n- (2, 0): \"1\" + \"1\"\n- (1, 2): \"1\" + \"1\"\n- (2, 1): \"1\" + \"1\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfPairs(String[] nums, String target) {\n \n HashMap map = new HashMap<>();\n for (int i = 0; i board) {\n int M = (int)1e9+7;\n int m = board.size();\n int n = board.get(0).length();\n int[][] dp = new int[m][n];\n int[][] ways = new int[m][n];\n ways[0][0]=1; // base case.\n int[][] dirs = {{-1, 0}, {0, -1}, {-1, -1}}; // all 3 ways where we can travel.\n for (int i=0;idp[i][j]){\n dp[i][j]=cur+dp[x][y];\n ways[i][j]=0;\n }\n if (cur+dp[x][y]==dp[i][j]){\n ways[i][j]+=ways[x][y];\n ways[i][j]%=M;\n }\n }\n }\n }\n return new int[]{dp[m-1][n-1], ways[m-1][n-1]};\n }\n}", + "title": "1301. Number of Paths with Max Score", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S' . You need to reach the top left square marked with the character 'E' . The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X' . In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7 . In case there is no path, return [0, 0] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= board.length == board[i].length <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"E23\",\"2X2\",\"12S\"]Output:[7,1]", + "image": null + }, + { + "text": "Example 2: Input:board = [\"E12\",\"1X1\",\"21S\"]Output:[4,2]", + "image": null + }, + { + "text": "Example 3: Input:board = [\"E11\",\"XXX\",\"11S\"]Output:[0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 321 ms (Top 53.09%) | Memory: 26.5 MB (Top 8.64%)\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n\n ## Basic information: height and width of board\n h, w = len(board), len(board[0])\n\n # ----------------------------------------------------------------------------\n\n # Use pathon native cahce as memoization for DP\n @cache\n def visit(i, j):\n\n if i == h-1 and j == w-1:\n ## Base case:\n\n # score for start coordinate = 0\n # paht count for start coordinate = 1\n return 0, 1\n\n elif i >= w or j >= h or board[i][j] == 'X':\n\n ## Base case:\n # Out-of-boundary, or meet obstacle\n return 0, 0\n\n ## General case:\n # update from three possible preivous moves from right, down, and diagonal\n\n right_score, right_path_count = visit(i, j+1)\n down_score, down_path_count = visit(i+1, j)\n diag_score, diag_path_count = visit(i+1, j+1)\n\n max_prevScore = max(right_score, down_score, diag_score)\n\n cur_path_count = 0\n cur_score = int(board[i][j]) if board[i][j] != \"E\" else 0\n\n if right_score == max_prevScore : cur_path_count += right_path_count\n if down_score == max_prevScore : cur_path_count += down_path_count\n if diag_score == max_prevScore : cur_path_count += diag_path_count\n\n return max_prevScore + cur_score, cur_path_count\n # ----------------------------------------------------------------------------\n\n ## Remark: Remember to take modulo by constant, this is defined by description\n CONST = 10**9 + 7\n maxScore, validPathCount = visit(0, 0)\n\n return [maxScore % CONST, validPathCount % CONST] if validPathCount else [0, 0]", + "title": "1301. Number of Paths with Max Score", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On day 1 , one person discovers a secret. You are given an integer delay , which means that each person will share the secret with a new person every day , starting from delay days after discovering the secret. You are also given an integer forget , which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n , return the number of people who know the secret at the end of day n . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= delay < forget <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, delay = 2, forget = 4Output:5Explanation:Day 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)", + "image": null + }, + { + "text": "Example 2: Input:n = 4, delay = 1, forget = 3Output:6Explanation:Day 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 38.08%) | Memory: 41.3 MB (Top 54.72%)\nclass Solution {\n public int peopleAwareOfSecret(int n, int delay, int forget) {\n long mod = 1000000007L;\n long[] shares = new long[n + 1];\n long[] forgets = new long[n + 1];\n\n if (delay < n) {\n shares[delay + 1] = 1;\n }\n if (forget < n) {\n forgets[forget + 1] = 1;\n }\n\n long shareToday = 0;\n long peopleKnow = 1;\n for (int i = delay; i <= n; i++) {\n shareToday += shares[i] % mod;\n shareToday -= forgets[i] % mod;\n\n peopleKnow -= forgets[i] % mod;\n peopleKnow += shareToday % mod;\n\n if (i + delay < n + 1) {\n shares[i + delay] += shareToday % mod;\n }\n if (i + forget < n + 1) {\n forgets[i + forget] += shareToday % mod;\n }\n }\n\n return (int) (peopleKnow % mod);\n }\n}", + "title": "2327. Number of People Aware of a Secret", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "On day 1 , one person discovers a secret. You are given an integer delay , which means that each person will share the secret with a new person every day , starting from delay days after discovering the secret. You are also given an integer forget , which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards. Given an integer n , return the number of people who know the secret at the end of day n . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= delay < forget <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, delay = 2, forget = 4Output:5Explanation:Day 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)", + "image": null + }, + { + "text": "Example 2: Input:n = 4, delay = 1, forget = 3Output:6Explanation:Day 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)", + "image": null + } + ], + "follow_up": null, + "solution": "\n```class Solution:\n def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n table = [0]*(forget+1)\n table[1] = 1\n days = 1\n while days<=n-1:\n count = 0\n for k in range(forget-1,-1,-1):\n if k+1>delay:\n table[k+1] = table[k]\n count+=table[k]\n elif k+1<=delay:\n table[k+1] = table[k]\n table[1] = count\n days+=1\n count = 0\n for k in range(1,forget+1):\n count+=table[k]\n return count%(pow(10,9)+7)\n\t\t\nTC---O(forget*n)\nsc---O(forget)\n \n", + "title": "2327. Number of People Aware of a Secret", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b , and city b is connected directly with city c , then city a is connected indirectly with city c . A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the i th city and the j th city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n == isConnected.length", + "n == isConnected[i].length", + "isConnected[i][j] is 1 or 0 .", + "isConnected[i][i] == 1", + "isConnected[i][j] == isConnected[j][i]" + ], + "examples": [ + { + "text": "Example 1: Input:isConnected = [[1,1,0],[1,1,0],[0,0,1]]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg" + }, + { + "text": "Example 2: Input:isConnected = [[1,0,0],[0,1,0],[0,0,1]]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 22.65%) | Memory: 42.7 MB (Top 99.36%)\nclass Solution {\n public int findCircleNum(int[][] isConnected) {\n int size = isConnected.length;\n boolean[] isCheck = new boolean[size+1];\n int ans = 0;\n\n for(int i=1; i<=size; i++){\n\n if(!isCheck[i]){ // Doing BFS if it's false in isCheck[]\n Queue q = new LinkedList<>();\n q.add(i);\n ans++; // No. of queue = No. of Graphs\n\n while(!q.isEmpty()){\n int temp = q.remove();\n isCheck[temp] = true;\n\n for(int j=0; j int:\n graph = defaultdict(list)\n for i,x in enumerate(isConnected):\n for j,n in enumerate(x):\n if j!=i and n == 1:\n graph[i].append(j)\n \n visit = set()\n \n def dfs(node):\n if node not in graph:\n return \n for neighbor in graph[node]:\n if neighbor not in visit:\n visit.add(neighbor)\n dfs(neighbor)\n count = 0\n for i in range(len(isConnected)):\n if i in visit:\n continue\n count+=1\n dfs(i)\n return count\n", + "title": "547. Number of Provinces", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. Example 1:", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1373 ms (Top 10.1%) | Memory: 52.32 MB (Top 27.9%)\n\nclass RecentCounter {\n ArrayList calls ;\n public RecentCounter() {\n calls = new ArrayList();\n }\n \n public int ping(int t) {\n calls.add(t);\n int count = 0;\n for(Integer call:calls){\n if( t-call<=3000) count++;\n }\n return count;\n \n }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */", + "title": "933. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. Example 1:", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 676 ms (Top 17.97%) | Memory: 19.4 MB (Top 70.89%)\nclass RecentCounter:\n # Here we use list to store ping details.\n def __init__(self):\n self.store = []\n\n def ping(self, t: int) -> int:\n # Basically what we need to return is how many pings fall in the range(t-3000, t).\n # So here we append every t. Now in loop how many t from left side < t-3000, we just pop them\n # and return the length of the list, which'd contain elements in range(t-3000, t).\n # And since every t is going to greater than previous, we don't need to think about duplicates.\n\n self.store.append(t)\n\n while self.store[0] < t-3000:\n self.store.pop(0)\n\n return len(self.store)", + "title": "933. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array rectangles where rectangles[i] = [l i , w i ] represents the i th rectangle of length l i and width w i . You can cut the i th rectangle to form a square with a side length of k if both k <= l i and k <= w i . For example, if you have a rectangle [4,6] , you can cut it to get a square with a side length of at most 4 . Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 1000", + "rectangles[i].length == 2", + "1 <= l i , w i <= 10^9", + "l i != w i" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[5,8],[3,9],[5,12],[16,5]]Output:3Explanation:The largest squares you can get from each rectangle are of lengths [5,3,5,5].\nThe largest possible square is of length 5, and you can get it out of 3 rectangles.", + "image": null + }, + { + "text": "Example 2: Input:rectangles = [[2,3],[3,7],[4,3],[3,7]]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countGoodRectangles(int[][] rectangles) {\n List list=new LinkedList();\n int max=0,count=0;\n for(int i = 0 ; i < rectangles.length ; i++){\n if(rectangles[i][0]>rectangles[i][1]){\n list.add(rectangles[i][1]);\n if(max int:\n\n #Runtime: 184 ms, faster than 65.71% of Python3 online submissions\n #Memory Usage: 14.9 MB, less than 39.90% of Python3 online submissions\n\n res = []\n\n minSide = 0\n maxLen = 0\n\n for l, w in rectangles:\n\n minSide = min(l, w) #Gets minSide of each rectangle\n\n if minSide > maxLen: #Checks if rectangle holds new maxLen\n maxLen = minSide #Tracks the current maxLen\n\n res.append(minSide) #Holds each rectangles minSIde\n\n return res.count(maxLen)#Returns the count of rectangles whos minSide is equal to maxLen\n", + "title": "1725. Number Of Rectangles That Can Form The Largest Square", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n , and an array edges where each edges[i] = [u i , v i , weight i ] denotes that there is an edge between nodes u i and v i with weight equal to weight i . A path from node start to node end is a sequence of nodes [z 0 , z 1 , z 2 , ..., z k ] such that z 0 = start and z k = end and there is an edge between z i and z i+1 where 0 <= i <= k-1 . The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x . A restricted path is a path that also satisfies that distanceToLastNode(z i ) > distanceToLastNode(z i+1 ) where 0 <= i <= k-1 . Return the number of restricted paths from node 1 to node n . Since that number may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "n - 1 <= edges.length <= 4 * 10^4", + "edges[i].length == 3", + "1 <= u i , v i <= n", + "u i != v i", + "1 <= weight i <= 10^5", + "There is at most one edge between any two nodes.", + "There is at least one path between any two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]Output:3Explanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]Output:1Explanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The only restricted path is 1 --> 3 --> 7.", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 10.95%) | Memory: 130.5 MB (Top 57.67%)\nclass Solution {\n int dp[];\n //We use memoization\n public int countRestrictedPaths(int n, int[][] edges) {\n int[] dist = new int[n+1];\n dp = new int[n+1];\n Arrays.fill(dp,-1);\n Map> graph = new HashMap<>();\n //Create the graph from input edges\n for(int[] e : edges){\n graph.putIfAbsent(e[0], new HashMap<>());\n graph.putIfAbsent(e[1], new HashMap<>());\n graph.get(e[0]).put(e[1],e[2]);\n graph.get(e[1]).put(e[0],e[2]);\n }\n //Single source shortest distance - something like Dijkstra's\n PriorityQueue pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));\n int[] base = new int[2];\n base[0]=n;\n pq.offer(base);\n while(!pq.isEmpty()){\n int[] currNode = pq.poll();\n\n for(Map.Entry neighbour: graph.get(currNode[0]).entrySet()){\n int node = neighbour.getKey();\n int d = neighbour.getValue()+currNode[1];\n if(node==n) continue;\n //Select only those neighbours, whose new distance is less than existing distance\n //New distance = distance of currNode from n + weight of edge between currNode and neighbour\n\n if( dist[node]==0 || d < dist[node]){\n int[] newNode = new int[2];\n newNode[0]=node;\n newNode[1]=d;\n pq.offer(newNode);\n dist[node]= d;\n }\n }\n }\n\n return find(1,graph,n,dist);\n }\n //This method traverses all the paths from source node to n though it's neigbours\n private int find(int node, Map> graph, int n, int[] dist ){\n if(node==n){\n return 1;\n }\n\n //Memoization avoid computaion of common subproblems.\n if(dp[node]!=-1) return dp[node];\n\n int ans = 0;\n for(Map.Entry neighbour: graph.get(node).entrySet()){\n int currNode = neighbour.getKey();\n int d = dist[currNode];\n if( dist[node] > d){\n ans = (ans + find(currNode, graph, n, dist)) % 1000000007;\n }\n }\n\n return dp[node] = ans;\n }\n}", + "title": "1786. Number of Restricted Paths From First to Last Node", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n , and an array edges where each edges[i] = [u i , v i , weight i ] denotes that there is an edge between nodes u i and v i with weight equal to weight i . A path from node start to node end is a sequence of nodes [z 0 , z 1 , z 2 , ..., z k ] such that z 0 = start and z k = end and there is an edge between z i and z i+1 where 0 <= i <= k-1 . The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x . A restricted path is a path that also satisfies that distanceToLastNode(z i ) > distanceToLastNode(z i+1 ) where 0 <= i <= k-1 . Return the number of restricted paths from node 1 to node n . Since that number may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "n - 1 <= edges.length <= 4 * 10^4", + "edges[i].length == 3", + "1 <= u i , v i <= n", + "u i != v i", + "1 <= weight i <= 10^5", + "There is at most one edge between any two nodes.", + "There is at least one path between any two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]Output:3Explanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]Output:1Explanation:Each circle contains the node number in black and itsdistanceToLastNode value in blue.The only restricted path is 1 --> 3 --> 7.", + "image": "https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n dct_nd = {}\n dist_to_n = {}\n queue = deque() # from n-node to 1-node\n visited = set()\n \n # 1 step: create dictionary with nodes and nodes' distances to n\n\n # create dictionary with format (weight, node_to)\n # heap will automatically sort weight and node_to in ascending order\n for l, r, w in edges:\n dct_nd[l] = dct_nd.get(l, []) + [(w, r)]\n dct_nd[r] = dct_nd.get(r, []) + [(w, l)]\n \n dist_to_n[n] = 0\n queue.append(n)\n visited.add(n)\n \n hpf = dct_nd[n].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change\n heapify(hpf)\n while hpf:\n el_w, el_nd = heappop(hpf)\n if el_nd in visited: continue\n \n dist_to_n[el_nd] = el_w\n visited.add(el_nd)\n queue.append(el_nd)\n\n if el_nd == 1: break # you don't need to traverse more if you've reached 1-node\n # other distances will be more than distance of 1-node\n for (i_w, i_nd) in dct_nd[el_nd]:\n if i_nd not in visited:\n heappush(hpf, (el_w + i_w, i_nd))\n # step 1: end\n\n # add to dictionary one more field: number of routes to n\n dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}\n dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 1\n \n # step 2: Dynamic Programming\n visited.clear()\n while queue:\n # start from n and traverse futher and futher\n nd_prv = queue.popleft()\n visited.add(nd_prv)\n for (w_cur, nd_cur) in dct_nd[nd_prv]:\n if nd_cur not in visited and \\\n nd_cur in dist_to_n.keys() and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:\n # to current node add number of routes from previous node\n dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]\n # !!! careful !!! you need to add modulo operation (as said in the task)\n dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9+7))\n # step 2: End\n \n return dist_to_n[1][1] # return number of routes for 1-node\n", + "title": "1786. Number of Restricted Paths From First to Last Node", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return the number of segments in the string . A segment is defined to be a contiguous sequence of non-space characters . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 300", + "s consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\" .", + "The only space character in s is ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello, my name is John\"Output:5Explanation:The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"Hello\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 35.26%)\nclass Solution {\n public int countSegments(String s) {\n int length = 0;\n boolean flag = false;\n\n for(Character c : s.toCharArray()) {\n if(c == ' ' && flag) {\n length++;\n flag = !flag;\n } else if(c != ' ') {\n flag = true;\n }\n }\n\n return flag ? length + 1 : length;\n }\n}", + "title": "434. Number of Segments in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the number of segments in the string . A segment is defined to be a contiguous sequence of non-space characters . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 300", + "s consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\" .", + "The only space character in s is ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello, my name is John\"Output:5Explanation:The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"Hello\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countSegments(self, s: str) -> int:\n return len(s.split())\n", + "title": "434. Number of Segments in a String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given n points on a 1-D plane, where the i th point (from 0 to n-1 ) is at x = i , find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates . The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments . Since this number can be huge, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= k <= n-1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2Output:5Explanation:The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.", + "image": "https://assets.leetcode.com/uploads/2020/09/07/ex1.png" + }, + { + "text": "Example 2: Input:n = 3, k = 1Output:3Explanation:The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 7Output:796297179Explanation:The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109+ 7 gives us 796297179.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n Integer[][][] memo;\n int n;\n public int numberOfSets(int n, int k) {\n this.n = n;\n this.memo = new Integer[n+1][k+1][2];\n return dp(0, k, 1);\n }\n int dp(int i, int k, int isStart) {\n if (memo[i][k][isStart] != null) return memo[i][k][isStart];\n if (k == 0) return 1; // Found a way to draw k valid segments\n if (i == n) return 0; // Reach end of points\n\n int ans = dp(i+1, k, isStart); // Skip ith point\n if (isStart == 1)\n ans += dp(i+1, k, 0); // Take ith point as start\n else\n ans += dp(i, k-1, 1); // Take ith point as end\n\n return memo[i][k][isStart] = ans % 1_000_000_007;\n }\n}\n", + "title": "1621. Number of Sets of K Non-Overlapping Line Segments", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given n points on a 1-D plane, where the i th point (from 0 to n-1 ) is at x = i , find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates . The k line segments do not have to cover all n points, and they are allowed to share endpoints. Return the number of ways we can draw k non-overlapping line segments . Since this number can be huge, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "1 <= k <= n-1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2Output:5Explanation:The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.", + "image": "https://assets.leetcode.com/uploads/2020/09/07/ex1.png" + }, + { + "text": "Example 2: Input:n = 3, k = 1Output:3Explanation:The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.", + "image": null + }, + { + "text": "Example 3: Input:n = 30, k = 7Output:796297179Explanation:The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109+ 7 gives us 796297179.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @lru_cache(None)\n def dp(i, k, isStart):\n if k == 0: return 1 # Found a way to draw k valid segments\n if i == n: return 0 # Reach end of points\n ans = dp(i+1, k, isStart) # Skip ith point\n if isStart:\n ans += dp(i+1, k, False) # Take ith point as start\n else:\n ans += dp(i, k-1, True) # Take ith point as end\n return ans % MOD\n return dp(0, k, True)\n", + "title": "1621. Number of Sets of K Non-Overlapping Line Segments", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the i th day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1 . The first day of the period is exempted from this rule. Return the number of smooth descent periods . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "1 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,2,1,4]Output:7Explanation:There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition.", + "image": null + }, + { + "text": "Example 2: Input:prices = [8,6,7,7]Output:4Explanation:There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.", + "image": null + }, + { + "text": "Example 3: Input:prices = [1]Output:1Explanation:There is 1 smooth descent period: [1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 24.69%) | Memory: 88.4 MB (Top 55.38%)\nclass Solution {\n public long getDescentPeriods(int[] prices) {\n int i=0;\n int j=1;\n long ans=1;\n while(j int: \n def calculate(k,ans):\n if k>1:\n ans+=((k-1)*(k))//2 \n\t\t\t\t#Sum of Natural Numbers\n return ans\n else:\n return ans\n end = 0\n start = 0\n prev= sys.maxsize\n k= 0\n ans = 0\n while end1:\n ans = calculate(k,ans)\n\t\t\t\n return ans+len(prices)\n", + "title": "2110. Number of Smooth Descent Periods of a Stock", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An array is squareful if the sum of every pair of adjacent elements is a perfect square . Given an integer array nums, return the number of permutations of nums that are squareful . Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 12", + "0 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,17,8]Output:2Explanation:[1,8,17] and [17,8,1] are the valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42 MB (Top 28.32%)\nclass Solution {\n int count;\n public int numSquarefulPerms(int[] nums) {\n int n = nums.length;\n if(n<2)\n return count;\n backtrack(nums,n,0);\n return count;\n\n }\n\n void backtrack(int [] nums,int n, int start)\n {\n if(start==n)\n {\n count++;\n }\n Set set = new HashSet <>();\n for(int i = start;i int:\n d = { x:{} for x in nums}\n n = len(nums)\n for i in range(n):\n for j in range(i+1,n):\n if self.isSquare(nums[i] + nums[j]):\n d[nums[i]][nums[j]] = True\n d[nums[j]][nums[i]] = True\n self.nums = nums\n self.ans = 0\n self.d = d\n vis = [False]*n\n tmp = {}\n for i in range(n):\n if nums[i] in tmp: continue\n tmp[nums[i]] = True\n vis[i] = True\n self.makePermutation(1,vis,self.nums[i],n)\n vis[i] = False\n return self.ans", + "title": "996. Number of Squareful Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the binary representation of an integer as a string s , return the number of steps to reduce it to 1 under the following rules : If the current number is even, you have to divide it by 2 . If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the current number is even, you have to divide it by 2 .", + "If the current number is odd, you have to add 1 to it." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"Output:6Explanation:\"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"Output:1Explanation:\"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.41 MB (Top 54.8%)\n\nclass Solution \n{\n public int numSteps(String s)\n {\n int countSteps = 0;\n int carry = 0;\n for(int i = s.length()-1;i>=1;i--)\n {\n int rightMostBit = s.charAt(i)-'0';\n if((rightMostBit+carry) == 1)\n {\n carry=1;\n countSteps += 2;\n }\n else\n {\n countSteps++;\n }\n }\n return countSteps+carry;\n }\n} ", + "title": "1404. Number of Steps to Reduce a Number in Binary Representation to One", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the binary representation of an integer as a string s , return the number of steps to reduce it to 1 under the following rules : If the current number is even, you have to divide it by 2 . If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the current number is even, you have to divide it by 2 .", + "If the current number is odd, you have to add 1 to it." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1101\"Output:6Explanation:\"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"Output:1Explanation:\"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution:\n def numSteps(self, s: str) -> int:\n size = len(s)\n if size == 1:\n return 0\n one_group = s.split('0')\n zero_group = s.split('1')\n\n \n if size - len(zero_group[-1]) == 1:\n return size - 1\n else:\n return size + len(one_group) - len(zero_group[-1])\n", + "title": "1404. Number of Steps to Reduce a Number in Binary Representation to One", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer num , return the number of steps to reduce it to zero . In one step, if the current number is even, you have to divide it by 2 , otherwise, you have to subtract 1 from it. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= num <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:num = 14Output:6Explanation:Step 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 2: Input:num = 8Output:4Explanation:Step 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 3: Input:num = 123Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfSteps(int num) {\n return helper(num,0);\n }\n public int helper(int n,int c){\n if(n==0) return c;\n if(n%2==0){ //check for even no.\n return helper(n/2,c+1);\n }\n \n return helper(n-1,c+1);\n }\n}\n", + "title": "1342. Number of Steps to Reduce a Number to Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer num , return the number of steps to reduce it to zero . In one step, if the current number is even, you have to divide it by 2 , otherwise, you have to subtract 1 from it. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= num <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:num = 14Output:6Explanation:Step 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 2: Input:num = 8Output:4Explanation:Step 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.", + "image": null + }, + { + "text": "Example 3: Input:num = 123Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 70 ms (Top 5.12%) | Memory: 13.9 MB (Top 52.31%)\nclass Solution:\n def numberOfSteps(self, num: int) -> int:\n count=0\n while num:\n if num%2:\n num=num-1\n else:\n num=num//2\n count+=1\n return count", + "title": "1342. Number of Steps to Reduce a Number to Zero", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings patterns and a string word , return the number of strings in patterns that exist as a substring in word . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= patterns.length <= 100", + "1 <= patterns[i].length <= 100", + "1 <= word.length <= 100", + "patterns[i] and word consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"Output:3Explanation:- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.", + "image": null + }, + { + "text": "Example 2: Input:patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"Output:2Explanation:- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.", + "image": null + }, + { + "text": "Example 3: Input:patterns = [\"a\",\"a\",\"a\"], word = \"ab\"Output:3Explanation:Each of the patterns appears as a substring in word \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfStrings(String[] patterns, String word) {\n int count = 0;\n for(int i=0;i int:\n return sum([pattern in word for pattern in patterns])\n\n ", + "title": "1967. Number of Strings That Appear as Substrings in Word", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime . The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i] . Return the number of students doing their homework at time queryTime . More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "startTime.length == endTime.length", + "1 <= startTime.length <= 100", + "1 <= startTime[i] <= endTime[i] <= 1000", + "1 <= queryTime <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3], endTime = [3,2,7], queryTime = 4Output:1Explanation:We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [4], endTime = [4], queryTime = 4Output:1Explanation:The only student was doing their homework at the queryTime.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int busyStudent(int[] startTime, int[] endTime, int queryTime) {\n int count = 0;\n for (int i = 0; i < startTime.length; ++i) {\n if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count;\n }\n return count;\n }\n}\n", + "title": "1450. Number of Students Doing Homework at a Given Time", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integer arrays startTime and endTime and given an integer queryTime . The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i] . Return the number of students doing their homework at time queryTime . More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "startTime.length == endTime.length", + "1 <= startTime.length <= 100", + "1 <= startTime[i] <= endTime[i] <= 1000", + "1 <= queryTime <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:startTime = [1,2,3], endTime = [3,2,7], queryTime = 4Output:1Explanation:We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.", + "image": null + }, + { + "text": "Example 2: Input:startTime = [4], endTime = [4], queryTime = 4Output:1Explanation:The only student was doing their homework at the queryTime.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 67 ms (Top 36.82%) | Memory: 13.9 MB (Top 71.93%)\nclass Solution(object):\n def busyStudent(self, startTime, endTime, queryTime):\n res = 0\n for i in range(len(startTime)):\n if startTime[i] <= queryTime <= endTime[i]:\n res += 1\n else:\n pass\n return res", + "title": "1450. Number of Students Doing Homework at a Given Time", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack . At each step: This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i ​​​​​​th sandwich in the stack ( i = 0 is the top of the stack) and students[j] is the preference of the j ​​​​​​th student in the initial queue ( j = 0 is the front of the queue). Return the number of students that are unable to eat. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.", + "Otherwise, they will leave it and go to the queue's end." + ], + "examples": [ + { + "text": "Example 1: Input:students = [1,1,0,0], sandwiches = [0,1,0,1]Output:0Explanation:- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.", + "image": null + }, + { + "text": "Example 2: Input:students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.4 MB (Top 83.22%)\nclass Solution {\n public int countStudents(int[] students, int[] sandwiches) {\n int ones = 0; //count of students who prefer type1\n int zeros = 0; //count of students who prefer type0\n\n for(int stud : students){\n if(stud == 0) zeros++;\n else ones++;\n }\n\n // for each sandwich in sandwiches\n for(int sandwich : sandwiches){\n if(sandwich == 0){ // if sandwich is of type0\n if(zeros == 0){ // if no student want a type0 sandwich\n return ones;\n }\n zeros--;\n }\n else{ // if sandwich is of type1\n if(ones == 0){ // if no student want a type1 sandwich\n return zeros;\n }\n ones--;\n }\n }\n return 0;\n }\n}", + "title": "1700. Number of Students Unable to Eat Lunch", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack . At each step: This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i ​​​​​​th sandwich in the stack ( i = 0 is the top of the stack) and students[j] is the preference of the j ​​​​​​th student in the initial queue ( j = 0 is the front of the queue). Return the number of students that are unable to eat. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.", + "Otherwise, they will leave it and go to the queue's end." + ], + "examples": [ + { + "text": "Example 1: Input:students = [1,1,0,0], sandwiches = [0,1,0,1]Output:0Explanation:- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.", + "image": null + }, + { + "text": "Example 2: Input:students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 76 ms (Top 5.69%) | Memory: 17.30 MB (Top 7.83%)\n\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = 0\n while len(students) > count:\n if students[0] == sandwiches[0]:\n sandwiches.pop(0)\n count = 0\n else:\n students.append(students[0])\n count+=1\n\n students.pop(0)\n return len(students)\n\t\t\n#Upvote will be encouraging.\n", + "title": "1700. Number of Students Unable to Eat Lunch", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4Output:3Explanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5Output:6Explanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numOfSubarrays(int[] arr, int k, int threshold) {\n int average=0,count=0,start=0,sum=0; \n for(int i=0;i=k-1){\n average=sum/k;\n if(average>=threshold) count++;\n sum-=arr[start]; \n start++; \n } \n }\n return count; \n }\n}\n", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4Output:3Explanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5Output:6Explanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfSubarrays(self, nums: List[int], k: int, threshold: int) -> int:\n currSum = 0\n start = 0\n end = 0\n count = 0\n \n # run right pointer till end element\n for end in range(len(nums)):\n # update value to window\n currSum += nums[end]\n \n # check if window size achieved\n if (end - start + 1) == k:\n # is average > target val\n if (currSum // k) >= threshold:\n count += 1\n # slide the window\n currSum -= nums[start]\n start += 1\n \n \n return count\n", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr and two integers k and threshold , return the number of sub-arrays of size k and average greater than or equal to threshold . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 10^4", + "1 <= k <= arr.length", + "0 <= threshold <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4Output:3Explanation:Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5Output:6Explanation:The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n wstart = wsum = count = 0\n \n for wend in range(len(arr)):\n wsum += arr[wend]\n \n if wend >= k:\n wsum -= arr[wstart]\n wstart += 1\n if (wsum//k) >= threshold and (wend-wstart+1) == k: \n count += 1\n return count", + "title": "1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return the number of subarrays with an odd sum . Since the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "1 <= arr[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,5]Output:4Explanation:All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,4,6]Output:0Explanation:All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3,4,5,6,7]Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "//odd-even=odd\n//even-odd=odd\nclass Solution {\n public int numOfSubarrays(int[] arr) {\n long ans=0;\n int even=0;\n int odd=0;\n \n long sum=0;\n \n for(int i=0;i int:\n ce, co = 0, 0\n s = 0\n for x in arr:\n if x % 2 == 0:\n ce += 1\n else:\n old_co = co\n co = ce + 1\n ce = old_co\n \n s += co\n \n return s % (10**9+7)\n", + "title": "1524. Number of Sub-arrays With Odd Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums and two integers left and right , return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right] . The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= left <= right <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3], left = 2, right = 3Output:3Explanation:There are three subarrays that meet the requirements: [2], [2, 1], [3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,9,2,5,6], left = 2, right = 8Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 82.54%) | Memory: 72.1 MB (Top 7.10%)\nclass Solution {\n public int numSubarrayBoundedMax(int[] nums, int left, int right) {\n int res = 0;\n\n int s = -1;\n int e = -1;\n\n for(int i=0;i= left && nums[i] <= right){\n e = i;\n }else if(nums[i] > right){\n e = s = i;\n }\n\n res += (e - s);\n }\n\n return res;\n }\n}", + "title": "795. Number of Subarrays with Bounded Maximum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and two integers left and right , return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right] . The test cases are generated so that the answer will fit in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^9", + "0 <= left <= right <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,4,3], left = 2, right = 3Output:3Explanation:There are three subarrays that meet the requirements: [2], [2, 1], [3].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,9,2,5,6], left = 2, right = 8Output:7", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1574 ms (Top 5.27%) | Memory: 22.4 MB (Top 17.30%)\nclass Solution:\n def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n n = len(nums)\n stack = []\n next_greater = [n] * n\n prev_greater = [-1] * n\n for i in range(n):\n while len(stack) > 0 and nums[i] > nums[stack[-1]]:\n curr = stack.pop()\n next_greater[curr] = i\n if len(stack) > 0:\n prev_greater[i] = stack[-1]\n stack.append(i)\n res = 0\n for i in range(n):\n if left <= nums[i] <= right:\n l = prev_greater[i]\n r = next_greater[i]\n res += (i - l) * (r - i)\n return res", + "title": "795. Number of Subarrays with Bounded Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a matrix and a target , return the number of non-empty submatrices that sum to target . A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2 . Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= matrix.length <= 100", + "1 <= matrix[0].length <= 100", + "-1000 <= matrix[i] <= 1000", + "-10^8 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0Output:4Explanation:The four 1x1 submatrices that only contain 0.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/mate1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,-1],[-1,1]], target = 0Output:5Explanation:The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[904]], target = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 321 ms (Top 35.18%) | Memory: 117.7 MB (Top 29.49%)\nclass Solution {\npublic int numSubmatrixSumTarget(int[][] matrix, int target) {\n int m = matrix.length, n = matrix[0].length;\n\n int[] summedArray = new int[n];\n int ans = 0;\n for(int i = 0; i < m; i++){ //starting row\n Arrays.fill(summedArray, 0);\n for(int j = i; j < m; j++){ //ending row\n for(int k = 0; k < n; k++){ // column\n summedArray[k] += matrix[j][k];\n }\n ans += subarraySum(summedArray, target);\n }\n }\n return ans;\n}\n\n public int subarraySum(int[] nums, int k) {\n //map\n Map map = new HashMap<>();\n int count = 0;\n map.put(0,1);\n int sum = 0;\n for(int num : nums){\n sum += num;\n int diff = sum - k;\n if(map.containsKey(diff)){\n count += map.get(diff);\n }\n map.put(sum, map.getOrDefault(sum, 0) + 1);\n }\n return count;\n}\n}", + "title": "1074. Number of Submatrices That Sum to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a matrix and a target , return the number of non-empty submatrices that sum to target . A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2 . Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= matrix.length <= 100", + "1 <= matrix[0].length <= 100", + "-1000 <= matrix[i] <= 1000", + "-10^8 <= target <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0Output:4Explanation:The four 1x1 submatrices that only contain 0.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/mate1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,-1],[-1,1]], target = 0Output:5Explanation:The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.", + "image": null + }, + { + "text": "Example 3: Input:matrix = [[904]], target = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n m, n = len(matrix), len(matrix[0])\n matrix_sums = [[0 for _ in range(n)] for _ in range(m)]\n \n # Calculate all the submatrices sum with the transition formula we found\n for row in range(m):\n for col in range(n):\n # first cell\n if row == 0 and col == 0:\n matrix_sums[row][col] = matrix[row][col]\n # Rows and columns are like prefix sums, without intersection\n elif row == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col-1]\n elif col == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row-1][col]\n \n # current sum is the sum of the matrix above, to the left and subtract the intersection\n else:\n matrix_sums[row][col] = matrix[row][col] \\\n + (matrix_sums[row][col-1]) \\\n + (matrix_sums[row-1][col]) \\\n - (matrix_sums[row-1][col-1])\n\n \n ans = 0\n # Generate all submatrices\n for y1 in range(m):\n for x1 in range(n):\n for y2 in range(y1, m):\n for x2 in range(x1, n):\n # calculate sum in O(1)\n submatrix_total = matrix_sums[y2][x2] \\\n - (matrix_sums[y2][x1-1] if x1-1 >= 0 else 0) \\\n - (matrix_sums[y1-1][x2] if y1-1 >= 0 else 0) \\\n + (matrix_sums[y1-1][x1-1] if y1-1 >= 0 and x1-1 >= 0 else 0)\n \n if submatrix_total == target:\n ans += 1\n return ans\n", + "title": "1074. Number of Submatrices That Sum to Target", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of integers nums and an integer target . Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6", + "1 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,6,7], target = 9Output:4Explanation:There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,8], target = 10Output:6Explanation:There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,3,3,4,6,7], target = 12Output:61Explanation:There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int numSubseq(int[] nums, int target) {\n int n = nums.length;\n int i =0, j = n-1;\n int mod = (int)1e9+7;\n Arrays.sort(nums);\n int[] pow = new int[n];\n pow[0]=1;\n int count =0;\n for(int z =1;z target)\n j--;\n }\n return count;\n }\n}\n\n\n", + "title": "1498. Number of Subsequences That Satisfy the Given Sum Condition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of integers nums and an integer target . Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^6", + "1 <= target <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5,6,7], target = 9Output:4Explanation:There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,6,8], target = 10Output:6Explanation:There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,3,3,4,6,7], target = 12Output:61Explanation:There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 637 ms (Top 91.1%) | Memory: 29.39 MB (Top 30.6%)\n\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n count = 0\n mod = 10 ** 9 + 7\n \n while left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n else:\n count += pow(2, right - left, mod)\n left += 1\n \n return count % mod\n", + "title": "1498. Number of Subsequences That Satisfy the Given Sum Condition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s consisting only of characters a , b and c . Return the number of substrings containing at least one occurrence of all these characters a , b and c . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= s.length <= 5 x 10^4", + "s only consists of a , b or c characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabc\"Output:10Explanation:The substrings containing at least one occurrence of the charactersa,bandc are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\"and\"abc\"(again).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaacb\"Output:3Explanation:The substrings containing at least one occurrence of the charactersa,bandc are \"aaacb\", \"aacb\"and\"acb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 41.17%) | Memory: 45.4 MB (Top 53.10%)\n\nclass Solution {\n public int numberOfSubstrings(String s) {\n int a = 0, b = 0, c = 0, count = 0;\n for (int i = 0; i < s.length(); i++) {\n switch (s.charAt(i)) {\n case 'a': ++a; break;\n case 'b': ++b; break;\n case 'c': ++c; break;\n }\n if (a > 0 && b > 0 && c > 0) {\n while (a > 0 && b > 0 && c > 0) {\n char farLeft = s.charAt(i - a - b - c + 1);\n switch (farLeft) {\n case 'a': {\n --a;\n count += doCount(s, i);\n break;\n }\n case 'b': {\n --b;\n count += doCount(s, i);\n break;\n }\n case 'c': {\n --c;\n count += doCount(s, i);\n break;\n }\n }\n }\n }\n }\n return count;\n }\n\n private int doCount(String s, int i) {\n int count = 0;\n int n = s.length() - i;\n if (n > 0) {\n count += n;\n }\n return count;\n }\n}", + "title": "1358. Number of Substrings Containing All Three Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s consisting only of characters a , b and c . Return the number of substrings containing at least one occurrence of all these characters a , b and c . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= s.length <= 5 x 10^4", + "s only consists of a , b or c characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabc\"Output:10Explanation:The substrings containing at least one occurrence of the charactersa,bandc are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\"and\"abc\"(again).", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaacb\"Output:3Explanation:The substrings containing at least one occurrence of the charactersa,bandc are \"aaacb\", \"aacb\"and\"acb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 466 ms (Top 30.17%) | Memory: 14.4 MB (Top 31.83%)\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n start = 0\n end = 0\n counter = 0\n store = {'a' : 0, 'b' : 0, 'c' : 0}\n\n for end in range(len(s)):\n store[s[end]] += 1\n\n while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:\n counter += (len(s) - end)\n store[s[start]] -= 1\n start += 1\n\n return counter", + "title": "1358. Number of Substrings Containing All Three Characters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary string s , return the number of substrings with all characters 1 's . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0110111\"Output:9Explanation:There are 9 substring in total with only 1's characters.\n\"1\" -> 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"101\"Output:2Explanation:Substring \"1\" is shown 2 times in s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"111111\"Output:21Explanation:Each substring contains only 1's characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSub(String s) {\n char[] ch = s.toCharArray();\n long count =0;\n long result =0;\n for(int i=0; i 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.", + "image": null + }, + { + "text": "Example 2: Input:s = \"101\"Output:2Explanation:Substring \"1\" is shown 2 times in s.", + "image": null + }, + { + "text": "Example 3: Input:s = \"111111\"Output:21Explanation:Each substring contains only 1's characters.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 40.6%) | Memory: 14.50 MB (Top 56.2%)\n\nclass Solution(object):\n def numSub(self, s):\n res, currsum = 0,0\n for digit in s:\n if digit == '0':\n currsum = 0\n else:\n currsum += 1 \n res+=currsum \n return res % (10**9+7)", + "title": "1513. Number of Substrings With Only 1s", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1 ) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the i th step. A binary string is prefix-aligned if, after the i th step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == flips.length", + "1 <= n <= 5 * 10^4", + "flips is a permutation of the integers in the range [1, n] ." + ], + "examples": [ + { + "text": "Example 1: Input:flips = [3,2,4,1,5]Output:2Explanation:The binary string is initially \"00000\".\nAfter applying step 1: The string becomes \"00100\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"01100\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"01110\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"11110\", which is prefix-aligned.\nAfter applying step 5: The string becomes \"11111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:flips = [4,1,2,3]Output:1Explanation:The binary string is initially \"0000\".\nAfter applying step 1: The string becomes \"0001\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"1001\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"1101\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"1111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numTimesAllBlue(int[] flips) {\n int counter=0,total=0,max=Integer.MIN_VALUE;\n for(int i=0;i int:\n \n \n l = len(flips)\n s = 0\n c = 0\n \n for i in range(len(flips)):\n f = flips[i]\n s = 1 << (f - 1) | s\n if s == (1 << (i+1))-1:\n c += 1\n \n return c\n", + "title": "1375. Number of Times Binary String Is Prefix-Aligned", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a binary string binary . A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\" ). Find the number of unique good subsequences of binary . Return the number of unique good subsequences of binary . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if binary = \"001\" , then all the good subsequences are [\"0\", \"0\", \"1\"] , so the unique good subsequences are \"0\" and \"1\" . Note that subsequences \"00\" , \"01\" , and \"001\" are not good because they have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"001\"Output:2Explanation:The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".", + "image": null + }, + { + "text": "Example 2: Input:binary = \"11\"Output:2Explanation:The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".", + "image": null + }, + { + "text": "Example 3: Input:binary = \"101\"Output:5Explanation:The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numberOfUniqueGoodSubsequences(String binary) {\n int initialZeroCount= 0;\n while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++;\n if(initialZeroCount == binary.length()) return 1;\n long[] dp = new long[binary.length()];\n dp[initialZeroCount] = 1;\n int lastOne = 0, lastZero = 0;\n long mod = (long) Math.pow(10, 9)+7;\n for(int i=initialZeroCount+1;i 0 ? dp[j-1] : 0;\n dp[i] = 2 * dp[i-1] - dup;\n if(dp[i] < 0) dp[i] += mod;\n dp[i] %= mod;\n if(binary.charAt(i) == '0') lastZero = i;\n else lastOne = i;\n }\n \n int hasZero = 0;\n if(binary.contains(\"0\")) hasZero = 1;\n \n \n return (int) (dp[binary.length()-1] + hasZero);\n }\n}\n", + "title": "1987. Number of Unique Good Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a binary string binary . A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\" ). Find the number of unique good subsequences of binary . Return the number of unique good subsequences of binary . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if binary = \"001\" , then all the good subsequences are [\"0\", \"0\", \"1\"] , so the unique good subsequences are \"0\" and \"1\" . Note that subsequences \"00\" , \"01\" , and \"001\" are not good because they have leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:binary = \"001\"Output:2Explanation:The good subsequences of binary are [\"0\", \"0\", \"1\"].\nThe unique good subsequences are \"0\" and \"1\".", + "image": null + }, + { + "text": "Example 2: Input:binary = \"11\"Output:2Explanation:The good subsequences of binary are [\"1\", \"1\", \"11\"].\nThe unique good subsequences are \"1\" and \"11\".", + "image": null + }, + { + "text": "Example 3: Input:binary = \"101\"Output:5Explanation:The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \nThe unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \n \n # zero_as_last: the count of S0, good sequence ending in 0\n # one_as_last : the count of S1: good sequence ending in 1\n # zero_exist: existence flag of 0 in given binary\n \n dp = {\"zero_as_last\": 0, \"one_as_last\": 0, \"zero_exist\": 0}\n \n for bit in map(int, binary):\n \n if bit:\n # current good = ( S0 concate with 1 ) + ( S1 concate with 1 ) + 1 alone\n # + \"1\" is allowed because leading 1 is valid by description\n dp[\"one_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"] + 1\n \n else:\n # current good = ( S0 concate with 0 ) + ( S1 concate with 0 ) \n # + \"0\" is NOT allowed because leading 0 is invalid by description\n dp[\"zero_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"]\n \n # check the existence of 0\n dp[\"zero_exist\"] |= (1-bit)\n \n \n return sum( dp.values() ) % ( 10**9 + 7 )\n", + "title": "1987. Number of Unique Good Subsequences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n , where pieces[i] describes the type (rook, queen, or bishop) of the i th piece. In addition, you are given a 2D integer array positions also of length n , where positions[i] = [r i , c i ] indicates that the i th piece is currently at the 1-based coordinate (r i , c i ) on the chessboard. When making a move for a piece, you choose a destination square that the piece will travel toward and stop on. You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0 th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square. Return the number of valid move combinations ​​​​​. Notes: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c) , (r-1, c) , (r, c+1) , or (r, c-1) .", + "A queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c) , (r-1, c) , (r, c+1) , (r, c-1) , (r+1, c+1) , (r+1, c-1) , (r-1, c+1) , (r-1, c-1) .", + "A bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1) , (r+1, c-1) , (r-1, c+1) , (r-1, c-1) ." + ], + "examples": [ + { + "text": "Example 1: Input:pieces = [\"rook\"], positions = [[1,1]]Output:15Explanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a1.png" + }, + { + "text": "Example 2: Input:pieces = [\"queen\"], positions = [[1,1]]Output:22Explanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a2.png" + }, + { + "text": "Example 3: Input:pieces = [\"bishop\"], positions = [[4,3]]Output:12Explanation:The image above shows the possible squares the piece can move to.", + "image": "https://assets.leetcode.com/uploads/2021/09/23/a3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int:\n board = [[set() for _ in range(8)] for _ in range(8)]\n n = len(pieces)\n for pos in positions:\n pos[0] -= 1\n pos[1] -= 1\n all_time = set(range(1, 8))\n def recur(i):\n if i == n:\n return 1\n ans = 0\n line = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n diag = [(1, 1), (1, -1), (-1, 1), (-1, -1)]\n r, c = positions[i]\n if not board[r][c] & all_time:\n board[r][c] |= all_time\n ans += recur(i + 1)\n board[r][c].clear()\n directions = []\n if pieces[i] in (\"queen\", \"rook\"):\n directions.extend(line)\n if pieces[i] in (\"queen\", \"bishop\"):\n directions.extend(diag) \n for dr, dc in directions:\n x, y = r + dr, c + dc\n count = 1\n while 0 <= x < 8 and 0 <= y < 8 and count not in board[x][y]:\n board[x][y].add(count)\n count += 1\n rest = set(range(count, 8))\n if not board[x][y] & rest:\n board[x][y] |= rest\n ans += recur(i + 1)\n board[x][y] -= rest\n x += dr\n y += dc\n count -= 1\n x -= dr\n y -= dc\n while count:\n board[x][y].remove(count)\n count -= 1\n x -= dr\n y -= dc\n return ans\n return recur(0)\n", + "title": "2056. Number of Valid Move Combinations On Chessboard", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "word contains the first letter of puzzle .", + "For each letter in word , that letter is in puzzle . For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle).", + "For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while", + "invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle)." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]Output:[1,1,3,2,4,0]Explanation:1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]Output:[0,1,3,2,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic List findNumOfValidWords(String[] words, String[] puzzles) {\n \n Map map = new HashMap<>();\n \n for(String w : words){\n int mask = 0;\n for(int i = 0; i < w.length(); i++){\n mask |= 1 << (w.charAt(i) - 'a');\n }\n map.put(mask, map.getOrDefault(mask, 0) + 1);\n }\n \n List res = new ArrayList<>();\n \n for(String p : puzzles){\n int mask = 0;\n for(int i = 0; i < p.length(); i++){\n mask |= 1 << (p.charAt(i) - 'a');\n }\n int c = 0;\n int sub = mask;\n int first = 1 << (p.charAt(0) - 'a');\n while(true){\n if((sub & first) == first && map.containsKey(sub)){\n c += map.get(sub);\n }\n \n if(sub == 0) break;\n \n sub = (sub - 1) & mask; // get the next substring\n }\n \n res.add(c);\n }\n \n return res;\n}\n}", + "title": "1178. Number of Valid Words for Each Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "word contains the first letter of puzzle .", + "For each letter in word , that letter is in puzzle . For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle).", + "For example, if the puzzle is \"abcdefg\" , then valid words are \"faced\" , \"cabbage\" , and \"baggage\" , while", + "invalid words are \"beefed\" (does not include 'a' ) and \"based\" (includes 's' which is not in the puzzle)." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]Output:[1,1,3,2,4,0]Explanation:1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]Output:[0,1,3,2,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n look_up=collections.defaultdict(int)\n def get_mask(word):\n mask=0\n for c in word:\n mask |= 1<<(ord(c)-ord('a'))\n return mask\n for word in words:\n mask=get_mask(word)\n look_up[mask]+=1\n ans=[]\n def solve(puzzle_idx,mask,c_idx):\n if c_idx==len(puzzles[puzzle_idx]):\n ans[-1]+=look_up[mask]\n return\n #take this c_idx\n solve(puzzle_idx,mask | 1<<(ord(puzzles[puzzle_idx][c_idx])-ord('a')),c_idx+1)\n #dont take this c_idx\n solve(puzzle_idx,mask,c_idx+1)\n for i,puzzle in enumerate(puzzles):\n ans.append(0)\n solve(i,1<<(ord(puzzle[0])-ord('a')),1)\n return ans\n", + "title": "1178. Number of Valid Words for Each Puzzle", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence consists of lowercase letters ( 'a' to 'z' ), digits ( '0' to '9' ), hyphens ( '-' ), punctuation marks ( '!' , '.' , and ',' ), and spaces ( ' ' ) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' ' . A token is a valid word if all three of the following are true: Examples of valid words include \"a-b.\" , \"afad\" , \"ba-c\" , \"a!\" , and \"!\" . Given a string sentence , return the number of valid words in sentence . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It only contains lowercase letters, hyphens, and/or punctuation ( no digits).", + "There is at most one hyphen '-' . If present, it must be surrounded by lowercase characters ( \"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).", + "There is at most one punctuation mark. If present, it must be at the end of the token ( \"ab,\" , \"cd!\" , and \".\" are valid, but \"a!b\" and \"c.,\" are not valid)." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"catanddog\"Output:3Explanation:The valid words in the sentence are \"cat\", \"and\", and \"dog\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"!this 1-s b8d!\"Output:0Explanation:There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"aliceandbobareplayingstone-game10\"Output:5Explanation:The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countValidWords(String sentence) {\n String regex = \"^([a-z]+(-?[a-z]+)?)?(!|\\\\.|,)?$\";\n String r2 = \"[^0-9]+\";\n String[] arr = sentence.split(\"\\\\s+\");\n int ans = 0;\n for(String s: arr)\n {\n if(s.matches(regex) && s.matches(r2))\n {\n ans++;\n //System.out.println(s);\n }\n }\n return ans;\n }\n}\n", + "title": "2047. Number of Valid Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sentence consists of lowercase letters ( 'a' to 'z' ), digits ( '0' to '9' ), hyphens ( '-' ), punctuation marks ( '!' , '.' , and ',' ), and spaces ( ' ' ) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' ' . A token is a valid word if all three of the following are true: Examples of valid words include \"a-b.\" , \"afad\" , \"ba-c\" , \"a!\" , and \"!\" . Given a string sentence , return the number of valid words in sentence . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It only contains lowercase letters, hyphens, and/or punctuation ( no digits).", + "There is at most one hyphen '-' . If present, it must be surrounded by lowercase characters ( \"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).", + "There is at most one punctuation mark. If present, it must be at the end of the token ( \"ab,\" , \"cd!\" , and \".\" are valid, but \"a!b\" and \"c.,\" are not valid)." + ], + "examples": [ + { + "text": "Example 1: Input:sentence = \"catanddog\"Output:3Explanation:The valid words in the sentence are \"cat\", \"and\", and \"dog\".", + "image": null + }, + { + "text": "Example 2: Input:sentence = \"!this 1-s b8d!\"Output:0Explanation:There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.", + "image": null + }, + { + "text": "Example 3: Input:sentence = \"aliceandbobareplayingstone-game10\"Output:5Explanation:The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.", + "image": null + } + ], + "follow_up": null, + "solution": "import re\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n \n # parse and get each word from sentence\n words = sentence.split()\n \n # regular expression pattern for valid words\n pattern = re.compile( r'^([a-z]+\\-?[a-z]+[!\\.,]?)$|^([a-z]*[!\\.,]?)$' )\n \n # valid word count\n count = 0\n \n # scan each word from word pool\n for word in words:\n \n # judge whether current word is valid or not\n match = re.match(pattern, word)\n \n if match:\n count+=1\n \n return count\n", + "title": "2047. Number of Valid Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]Output:[3,1,2,1,1,0]Explanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]Output:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] canSeePersonsCount(int[] heights) {\n Stack stack = new Stack<>();\n int result[] = new int[heights.length];\n for(int i = heights.length - 1; i >= 0; i--) {\n int visibility = 0;\n while(!stack.isEmpty() && heights[i] > stack.peek()) {\n stack.pop();\n visibility++;\n }\n if(!stack.isEmpty()) visibility++;\n stack.push(heights[i]);\n result[i] = visibility;\n }\n return result;\n }\n}\n", + "title": "1944. Number of Visible People in a Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]Output:[3,1,2,1,1,0]Explanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]Output:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2162 ms (Top 20.79%) | Memory: 30.1 MB (Top 6.96%)\n\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans=[]\n stack=[]\n n=len(heights)\n for i in range(n-1,-1,-1):\n if len(stack)==0:\n ans.append(0)\n stack.append(heights[i])\n else:\n if heights[i]0 and stack[-1] int:\n m, n = len(p), len(p[0])\n apples = [[0 for _ in range(n+1)] for _ in range(m+1)] \n # number of apples in (0,0) to (i,j)\n apples[1][1] = 0 if p[0][0] == '.' else 1\n for j in range(1,n):\n apples[1][j+1] = apples[1][j] if p[0][j] == '.' else apples[1][j] + 1\n for i in range(1,m):\n cur_apple = 0 if p[i][0] == '.' else 1\n apples[i+1][1] = apples[i][1] + cur_apple\n for j in range(1,n):\n if p[i][j] == 'A': cur_apple += 1\n apples[i+1][j+1] = apples[i][j+1] + cur_apple\n\n def getApples(x,y,z,w):\n # get the number of apples within range\n # x,y: top-left coordinates of current pizza\n # z,w: bottom-right\n return apples[z+1][w+1] + apples[x][y] - apples[z+1][y] - apples[x][w+1]\n\n @lru_cache(None)\n def cut(c,x,y,z,w):\n # c: number of cuts already cut\n # x,y: top-left coordinates of current pizza\n # z,w: bottom-right\n if c == k - 1:\n return 1 if getApples(x,y,z,w) > 0 else 0\n\n r = 0\n # horizontal cuts\n i = x\n while i < z:\n if getApples(x,y,i,w) > 0: break\n i += 1\n while i < z:\n r += cut(c+1,i+1,y,z,w)\n i += 1\n # vertical cuts\n j = y\n while j < w:\n if getApples(x,y,z,j) > 0: break\n j += 1\n while j < w:\n r += cut(c+1,x,j+1,z,w)\n j += 1\n\n return r\n\n return cut(0,0,0,m-1,n-1)%(10**9+7)", + "title": "1444. Number of Ways of Cutting a Pizza", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [u i , v i , time i ] means that there is a road between intersections u i and v i that takes time i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time . Return the number of ways you can arrive at your destination in the shortest amount of time . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n - 1 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 3", + "0 <= u i , v i <= n - 1", + "1 <= time i <= 10^9", + "u i != v i", + "There is at most one road connecting any two intersections.", + "You can reach any intersection from any other intersection." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]Output:4Explanation:The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6", + "image": "https://assets.leetcode.com/uploads/2021/07/17/graph2.png" + }, + { + "text": "Example 2: Input:n = 2, roads = [[1,0,10]]Output:1Explanation:There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Pair{\n int node;\n int dist;\n Pair(int node , int dist){\n this.node = node;\n this.dist = dist;\n }\n }\n public int countPaths(int n, int[][] roads) {\n int mod = (int)Math.pow(10 , 9) + 7;\n ArrayList> adj = new ArrayList<>();\n int rows = roads.length;\n for(int i = 0 ; i < n ; i++)\n adj.add(new ArrayList());\n for(int i = 0 ; i < rows ; i++){\n int from = roads[i][0];\n int to = roads[i][1];\n int dis = roads[i][2];\n adj.get(from).add(new Pair(to , dis));\n adj.get(to).add(new Pair(from , dis));\n }\n PriorityQueue pq = new PriorityQueue<>((aa , bb) -> aa.dist - bb.dist);\n pq.add(new Pair(0 , 0));\n long[] ways = new long[n];\n ways[0] = 1;\n int[] dist = new int[n];\n Arrays.fill(dist , Integer.MAX_VALUE);\n dist[0] = 0;\n while(!pq.isEmpty()){\n Pair p = pq.remove();\n int node = p.node;\n int dis = p.dist;\n for(Pair pa : adj.get(node)){\n if((dis + pa.dist) < dist[pa.node]){\n ways[pa.node] = ways[node];\n dist[pa.node] = dis + pa.dist;\n pq.add(new Pair(pa.node , dist[pa.node]));\n }\n else if((dis + pa.dist) == dist[pa.node]){\n ways[pa.node] += ways[node];\n ways[pa.node] = ways[pa.node] % mod;\n }\n }\n }\n return (int)ways[n - 1];\n }\n}\n", + "title": "1976. Number of Ways to Arrive at Destination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [u i , v i , time i ] means that there is a road between intersections u i and v i that takes time i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time . Return the number of ways you can arrive at your destination in the shortest amount of time . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n - 1 <= roads.length <= n * (n - 1) / 2", + "roads[i].length == 3", + "0 <= u i , v i <= n - 1", + "1 <= time i <= 10^9", + "u i != v i", + "There is at most one road connecting any two intersections.", + "You can reach any intersection from any other intersection." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]Output:4Explanation:The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6", + "image": "https://assets.leetcode.com/uploads/2021/07/17/graph2.png" + }, + { + "text": "Example 2: Input:n = 2, roads = [[1,0,10]]Output:1Explanation:There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(dict)\n for u, v, w in roads:\n graph[u][v] = graph[v][u] = w\n dist = {i:float(inf) for i in range(n)}\n ways = {i:0 for i in range(n)}\n dist[0], ways[0] = 0, 1\n heap = [(0, 0)]\n while heap:\n d, u = heapq.heappop(heap)\n if dist[u] < d: \n continue\n for v in graph[u]:\n if dist[v] == dist[u] + graph[u][v]:\n ways[v] += ways[u]\n elif dist[v] > dist[u] + graph[u][v]:\n dist[v] = dist[u] + graph[u][v]\n ways[v] = ways[u]\n heapq.heappush(heap, (dist[v], v))\n return ways[n-1] % ((10 ** 9) + 7)\n", + "title": "1976. Number of Ways to Arrive at Destination", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. Return the number of distinct ways you can buy some number of pens and pencils. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= total, cost1, cost2 <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:total = 20, cost1 = 10, cost2 = 5Output:9Explanation:The price of a pen is 10 and the price of a pencil is 5.\n- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.\n- If you buy 1 pen, you can buy 0, 1, or 2 pencils.\n- If you buy 2 pens, you cannot buy any pencils.\nThe total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.", + "image": null + }, + { + "text": "Example 2: Input:total = 5, cost1 = 10, cost2 = 10Output:1Explanation:The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n return sum((total - pens*cost1) // cost2 + 1 for pens in range(total // cost1 + 1))", + "title": "2240. Number of Ways to Buy Pens and Pencils", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0 , and another to the right of index n - 1 . Additional room dividers can be installed. For each position between indices i - 1 and i ( 1 <= i <= n - 1 ), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor . Since the answer may be very large, return it modulo 10^9 + 7 . If there is no way, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == corridor.length", + "1 <= n <= 10^5", + "corridor[i] is either 'S' or 'P' ." + ], + "examples": [ + { + "text": "Example 1: Input:corridor = \"SSPPSPS\"Output:3Explanation:There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways,eachsection has exactlytwoseats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/1.png" + }, + { + "text": "Example 2: Input:corridor = \"PPSPSP\"Output:1Explanation:There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/2.png" + }, + { + "text": "Example 3: Input:corridor = \"S\"Output:0Explanation:There is no way to divide the corridor because there will always be a section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/12/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 89.8%) | Memory: 44.90 MB (Top 30.5%)\n\nclass Solution {\n public int numberOfWays(String corridor) {\n int numSeats = 0, numPlants = 0;\n long dividers = 1;\n \n for(int i = 0; i < corridor.length(); ++i) {\n if(corridor.charAt(i) == 'S') numSeats += 1;\n if(numSeats == 2 && corridor.charAt(i) == 'P') numPlants += 1;\n if(numSeats == 3) {\n dividers *= (numPlants + 1);\n dividers %= 1000000007;\n numSeats = 1;\n numPlants = 0;\n }\n }\n \n if(numSeats < 2) return 0;\n return (int)dividers;\n }\n}", + "title": "2147. Number of Ways to Divide a Long Corridor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0 , and another to the right of index n - 1 . Additional room dividers can be installed. For each position between indices i - 1 and i ( 1 <= i <= n - 1 ), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor . Since the answer may be very large, return it modulo 10^9 + 7 . If there is no way, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == corridor.length", + "1 <= n <= 10^5", + "corridor[i] is either 'S' or 'P' ." + ], + "examples": [ + { + "text": "Example 1: Input:corridor = \"SSPPSPS\"Output:3Explanation:There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways,eachsection has exactlytwoseats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/1.png" + }, + { + "text": "Example 2: Input:corridor = \"PPSPSP\"Output:1Explanation:There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/04/2.png" + }, + { + "text": "Example 3: Input:corridor = \"S\"Output:0Explanation:There is no way to divide the corridor because there will always be a section that does not have exactly two seats.", + "image": "https://assets.leetcode.com/uploads/2021/12/12/3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 253 ms (Top 99.08%) | Memory: 17.50 MB (Top 42.72%)\n\nclass Solution:\n def numberOfWays(self, corridor):\n seat, res, plant = 0, 1, 0\n for i in corridor:\n if i=='S':\n seat += 1\n else:\n if seat == 2:\n plant += 1\n if seat == 3:\n res = res*(plant+1) % (10**9 + 7)\n seat , plant = 1 , 0\n if seat != 2:\n return 0\n return res\n", + "title": "2147. Number of Ways to Divide a Long Corridor", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a list of strings of the same length words and a string target . Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "target should be formed from left to right.", + "To form the i th character ( 0-indexed ) of target , you can choose the k th character of the j th string in words if target[i] = words[j][k] .", + "Once you use the k th character of the j th string of words , you can no longer use the x th character of any string in words where x <= k . In other words, all characters to the left of or at index k become unusuable for every string.", + "Repeat the process until you form the string target ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"Output:6Explanation:There are 6 ways to form target.\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")", + "image": null + }, + { + "text": "Example 2: Input:words = [\"abba\",\"baab\"], target = \"bab\"Output:4Explanation:There are 4 ways to form target.\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1795 ms (Top 74.72%) | Memory: 380.50 MB (Top 27.21%)\n\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n MOD = 10 ** 9 + 7\n m, n = len(words[0]), len(target)\n charAtIndexCnt = [[0] * m for _ in range(128)]\n for word in words:\n for i, c in enumerate(word):\n charAtIndexCnt[ord(c)][i] += 1 # Count the number of character `c` at index `i` of all words\n\n @lru_cache(None)\n def dp(k, i):\n if i == n: # Formed a valid target\n return 1\n if k == m: # Reached to length of words[x] but don't found any result\n return 0\n c = target[i]\n ans = dp(k + 1, i) # Skip k_th index of words\n if charAtIndexCnt[ord(c)][k] > 0: # Take k_th index of words if found character `c` at index k_th\n ans += dp(k + 1, i + 1) * charAtIndexCnt[ord(c)][k]\n ans %= MOD\n return ans\n\n return dp(0, 0)\n", + "title": "1639. Number of Ways to Form a Target String Given a Dictionary", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red , Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid . As the answer may grow large, the answer must be computed modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:12Explanation:There are 12 possible way to paint the grid as shown.", + "image": "https://assets.leetcode.com/uploads/2020/03/26/e1.png" + }, + { + "text": "Example 2: Input:n = 5000Output:30228214", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int MOD = 1000000007;\n int[][] states = {{0,1,0},{1,0,1},{2,0,1},\n {0,1,2},{1,0,2},{2,0,2},\n {0,2,0},{1,2,0},{2,1,0},\n {0,2,1},{1,2,1},{2,1,2}};\n \n HashMap> nextMap = new HashMap<>();\n Long[][] memo;\n \n public int numOfWays(int n) {\n if(n == 0)\n return 0;\n \n\t\t// Graph\n for(int prev = 0; prev < 12; prev++){\n List nexts = new ArrayList<>();\n for(int next = 0; next < 12; next++){\n if(next == prev) continue;\n \n boolean flag = true;\n for(int i = 0; i < 3; i++){\n if(states[prev][i] == states[next][i]){\n flag = false;\n break;\n }\n }\n if(flag)\n nexts.add(next);\n }\n nextMap.put(prev, nexts);\n }\n\t\t\n\t\t//DFS\n memo = new Long[12][n];\n long ways = 0;\n for(int i = 0; i < 12; i++){\n ways += dfs(i, n-1);\n ways %= MOD;\n }\n \n return (int)(ways);\n }\n \n long dfs(int prev, int n){\n if(n == 0)\n return 1;\n \n if(memo[prev][n] != null)\n return memo[prev][n];\n \n long ways = 0;\n \n List nexts = nextMap.get(prev);\n for(int next : nexts){\n ways += dfs(next, n-1);\n ways %= MOD;\n }\n \n memo[prev][n] = ways;\n return ways;\n }\n}", + "title": "1411. Number of Ways to Paint N × 3 Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red , Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color). Given n the number of rows of the grid, return the number of ways you can paint this grid . As the answer may grow large, the answer must be computed modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "1 <= n <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:12Explanation:There are 12 possible way to paint the grid as shown.", + "image": "https://assets.leetcode.com/uploads/2020/03/26/e1.png" + }, + { + "text": "Example 2: Input:n = 5000Output:30228214", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numOfWays(self, n: int) -> int:\n two_c_options = 6\n tot_options = 12\n for i in range(n-1):\n temp = tot_options\n tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4)\n two_c_options = (two_c_options * 3) + ((temp - two_c_options) * 2)\n tot_options = tot_options % (1000000007)\n return tot_options\n", + "title": "1411. Number of Ways to Paint N × 3 Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n . You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k , return the number of such arrangements . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the sticks are arranged [ 1 , 3 ,2, 5 ,4] , then the sticks with lengths 1 , 3 , and 5 are visible from the left." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2Output:3Explanation:[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 5Output:1Explanation:[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 3: Input:n = 20, k = 11Output:647427950Explanation:There are 647427950 (mod 109+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 368 ms (Top 16.85%) | Memory: 89.8 MB (Top 41.57%)\nclass Solution {\n public int rearrangeSticks(int n, int k) {\n final int MOD = 1_000_000_007;\n long[][] M = new long[k + 1][n + 1];\n M[0][0] = 1;\n for (int i = 1; i <= k; i++) {\n for (int j = 1; j <= n; j++) {\n M[i][j] = ((j - 1) * M[i][j - 1] % MOD + M[i - 1][j - 1]) % MOD;\n }\n }\n return (int) M[k][n];\n }\n}", + "title": "1866. Number of Ways to Rearrange Sticks With K Sticks Visible", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n uniquely-sized sticks whose lengths are integers from 1 to n . You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k , return the number of such arrangements . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the sticks are arranged [ 1 , 3 ,2, 5 ,4] , then the sticks with lengths 1 , 3 , and 5 are visible from the left." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 2Output:3Explanation:[1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 5Output:1Explanation:[1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.", + "image": null + }, + { + "text": "Example 3: Input:n = 20, k = 11Output:647427950Explanation:There are 647427950 (mod 109+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.", + "image": null + } + ], + "follow_up": null, + "solution": "M = 10 ** 9 + 7\n\nfrom functools import cache\n\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n return dp(n, k)\n\n# consider the shortest\n@cache\ndef dp(n, k):\n if n == k:\n return 1\n if n <= 0 or k <= 0:\n return 0\n return (dp(n - 1, k - 1) + (n - 1) * dp(n - 1, k)) % M \n\n# `dp(n, k)` indicates the number of arrangements of `n` distinct sticks with exactly `k` visible sticks. \n# Those `n` **distinct** sticks does NOT have to be numbered from `1` to `n` consecutively.\n", + "title": "1866. Number of Ways to Rearrange Sticks With K Sticks Visible", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array pairs , where pairs[i] = [x i , y i ] , and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are no duplicates.", + "x i < y i" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3]]Output:1Explanation:There is exactly one valid rooted tree, which is shown in the above figure.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/trees2.png" + }, + { + "text": "Example 2: Input:pairs = [[1,2],[2,3],[1,3]]Output:2Explanation:There are multiple valid rooted trees. Three of them are shown in the above figures.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/tree.png" + }, + { + "text": "Example 3: Input:pairs = [[1,2],[2,3],[2,4],[1,5]]Output:0Explanation:There are no valid rooted trees.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 418 ms (Top 41.46%) | Memory: 133.9 MB (Top 9.76%)\nclass Solution {\n public int checkWays(int[][] pairs) {\n int result = 1;\n\n //Create adjacency list\n Map> edges = new HashMap<>();\n for (int[] pair: pairs) {\n edges.computeIfAbsent(pair[0], x->new HashSet<>()).add(pair[0]);\n edges.computeIfAbsent(pair[1], x->new HashSet<>()).add(pair[1]);\n edges.get(pair[0]).add(pair[1]);\n edges.get(pair[1]).add(pair[0]);\n }\n\n //Sort the edge lists based on their size\n List>> edgesList = new ArrayList(edges.entrySet());\n Collections.sort(edgesList, (a,b)-> b.getValue().size() - a.getValue().size());\n\n List>> previous = new ArrayList<>();\n\n // Now from each of the edges find the ways to create the tree\n for (Map.Entry> cur: edgesList) {\n //get the current edge set\n Set currentSet = cur.getValue();\n //find the parent for the current set from the previously computed edge\n Map.Entry> parent = find(previous, currentSet);\n // if the parent is null\n if (parent==null) {\n // if you the current set do not match with the edges size then there is no way, return 0\n if (currentSet.size() != edges.size())\n return 0;\n } else {\n Set parentSet = parent.getValue();\n // if the current set do not contain everything from the parent then also return 0\n if (!parentSet.containsAll(currentSet)) return 0;\n // if the parent contains everything from the current set then return more than one ways\n if (parentSet.equals(currentSet)) result = 2;\n }\n // add the computed edge to previous list\n previous.add(cur);\n }\n\n // only one way\n return result;\n }\n\n Map.Entry> find(List>> previous, Set currentSet) {\n int i=previous.size()-1;\n while (i>=0) {\n Map.Entry> entry = previous.get(i--);\n if (currentSet.contains(entry.getKey())) return entry;\n }\n return null;\n }\n}", + "title": "1719. Number Of Ways To Reconstruct A Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array pairs , where pairs[i] = [x i , y i ] , and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "There are no duplicates.", + "x i < y i" + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[1,2],[2,3]]Output:1Explanation:There is exactly one valid rooted tree, which is shown in the above figure.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/trees2.png" + }, + { + "text": "Example 2: Input:pairs = [[1,2],[2,3],[1,3]]Output:2Explanation:There are multiple valid rooted trees. Three of them are shown in the above figures.", + "image": "https://assets.leetcode.com/uploads/2020/12/03/tree.png" + }, + { + "text": "Example 3: Input:pairs = [[1,2],[2,3],[2,4],[1,5]]Output:0Explanation:There are no valid rooted trees.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkWays(self, P):\n g = defaultdict(set)\n for u, v in P:\n g[u].add(v)\n g[v].add(u)\n\n def helper(nodes):\n d, m = defaultdict(list), len(nodes) - 1\n for node in nodes:\n d[len(g[node])].append(node)\n\n if len(d[m]) == 0: return 0\n root = d[m][0]\n \n for node in g[root]: g[node].remove(root)\n \n comps, seen, i = defaultdict(set), set(), 0\n def dfs(node, i):\n comps[i].add(node)\n seen.add(node)\n for neib in g[node]:\n if neib not in seen: dfs(neib, i)\n \n for node in nodes:\n if node != root and node not in seen:\n dfs(node, i)\n i += 1\n \n cands = [helper(comps[i]) for i in comps]\n if 0 in cands: return 0\n if 2 in cands: return 2\n if len(d[m]) >= 2: return 2\n return 1\n \n return helper(set(g.keys()))\n", + "title": "1719. Number Of Ways To Reconstruct A Tree", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array nums that represents a permutation of integers from 1 to n . We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums . Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given nums = [2,1,3] , we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:1Explanation:We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/bb.png" + }, + { + "text": "Example 2: Input:nums = [3,4,5,1,2]Output:5Explanation:The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex1.png" + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:0Explanation:There are no other orderings of nums that will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex4.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n long[][] pascal;\n private static final long mod = 1000000007;\n long one=1;\n public int numOfWays(int[] nums) {\n ArrayList list = new ArrayList<>();\n for (int n : nums) {\n list.add(n);\n }\n formPascal(nums);\n return (int)dfs(list)-1;\n }\n \n public long dfs(ArrayList list){\n if(list.size()<=2) return 1;\n ArrayList left=new ArrayList<>();\n ArrayList right=new ArrayList<>();\n int root=list.get(0);\n for(int n:list){\n if(nroot)\n right.add(n);\n }\n \n return ((pascal[left.size()+right.size()][left.size()])*(dfs(left)%mod))%mod *(dfs(right)%mod);\n \n \n }\n \n private void formPascal(int[] nums){\n pascal=new long[nums.length+1][];\n \n for(int i=0;i<=nums.length;i++){\n pascal[i]=new long[i+1];\n Arrays.fill(pascal[i],one);\n for(int j=1;j", + "title": "1569. Number of Ways to Reorder Array to Get Same BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums that represents a permutation of integers from 1 to n . We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums . Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, given nums = [2,1,3] , we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:1Explanation:We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/bb.png" + }, + { + "text": "Example 2: Input:nums = [3,4,5,1,2]Output:5Explanation:The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex1.png" + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:0Explanation:There are no other orderings of nums that will yield the same BST.", + "image": "https://assets.leetcode.com/uploads/2020/08/12/ex4.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 556 ms (Top 18.24%) | Memory: 15.4 MB (Top 89.19%)\nclass node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution:\n def BST(self, root, cur):\n if cur.val < root.val:\n if root.left == None:\n root.left = cur\n return\n else:\n self.BST(root.left, cur)\n elif cur.val > root.val:\n if root.right == None:\n root.right = cur\n return\n else:\n self.BST(root.right, cur)\n\n def solve(self, root):\n if root.left == None and root.right == None:\n return 1\n left = 0 ; right = 0\n if root.left is not None:\n left = self.solve(root.left)\n if root.right is not None:\n right = self.solve(root.right)\n self.total *= math.comb(left + right, left)\n return left + right + 1\n\n def numOfWays(self, nums: List[int]) -> int:\n import math\n self.total = 1\n root = node(nums[0])\n for i in range(1, len(nums)):\n self.BST(root, node(nums[i]))\n self.solve(root)\n return (self.total - 1) % (int(1e9) + 7)", + "title": "1569. Number of Ways to Reorder Array to Get Same BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s[i] = '0' denotes that the i th building is an office and", + "s[i] = '1' denotes that the i th building is a restaurant." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"001101\"Output:6Explanation:The following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.", + "image": null + }, + { + "text": "Example 2: Input:s = \"11100\"Output:0Explanation:It can be shown that there are no valid selections.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution\n{\n public long numberOfWays(String s)\n {\n int zero = 0; // Individual zeroes count\n long zeroOne = 0; // Number of combinations of 01s\n int one = 0; // Individual ones count\n long oneZero = 0; // Number of combinations of 10s\n long tot = 0; // Final answer\n for(char ch : s.toCharArray())\n {\n if(ch == '0')\n {\n zero++;\n if(one > 0)\n oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10\n if(zeroOne > 0)\n tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010\n }\n else\n {\n one++;\n if(zero > 0)\n zeroOne += zero; // Each of the previously found 0s can pair to form 01\n if(oneZero > 0)\n tot += oneZero; // Each of the previously formed 10 can form 101\n }\n }\n return tot;\n }\n}\n", + "title": "2222. Number of Ways to Select Buildings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s[i] = '0' denotes that the i th building is an office and", + "s[i] = '1' denotes that the i th building is a restaurant." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"001101\"Output:6Explanation:The following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.", + "image": null + }, + { + "text": "Example 2: Input:s = \"11100\"Output:0Explanation:It can be shown that there are no valid selections.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numberOfWays(self, s: str) -> int:\n \n temp = []\n c0 = 0\n c1 = 0\n for char in s :\n if char == \"0\" :\n c0+=1\n else:\n c1+=1\n temp.append([c0,c1])\n \n total0 = c0\n total1 = c1\n \n \n count = 0\n for i in range(1, len(s)-1) :\n \n if s[i] == \"0\" :\n m1 = temp[i-1][1]\n m2 = total1 - temp[i][1]\n count += m1*m2\n \n else:\n m1 = temp[i-1][0]\n m2 = total0 - temp[i][0]\n count += m1*m2\n return count\n \n \n", + "title": "2222. Number of Ways to Select Buildings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You wrote down many positive integers in a string called num . However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= num.length <= 3500", + "num consists of digits '0' through '9' ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"327\"Output:2Explanation:You could have written down the numbers:\n3, 27\n327", + "image": null + }, + { + "text": "Example 2: Input:num = \"094\"Output:0Explanation:No numbers can have leading zeros and all numbers must be positive.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0\"Output:0Explanation:No numbers can have leading zeros and all numbers must be positive.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 11887 ms (Top 6.00%) | Memory: 14.2 MB (Top 88.00%)\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n if num[0]=='0': return 0\n N=len(num)\n MOD=int(10**9+7)\n ways = (N+1)*[0]\n acc = list(ways)\n for n in range(1,N+1):\n ways[n] = int(n==N or num[n]!='0')\n for i in range(n+1,N+1):\n if i=2*n and num[i-2*n:i-n] <= num[i-n:i] and w)) %MOD\n for i in range(n,N+1):\n a = (acc[i] + ways[i]) %MOD\n acc[i] = a\n return acc[N]", + "title": "1977. Number of Ways to Separate Numbers", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary string s , you can split s into 3 non-empty strings s1 , s2 , and s3 where s1 + s2 + s3 = s . Return the number of ways s can be split such that the number of ones is the same in s1 , s2 , and s3 . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= s.length <= 10^5", + "s[i] is either '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"10101\"Output:4Explanation:There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n\"1|010|1\"\n\"1|01|01\"\n\"10|10|1\"\n\"10|1|01\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"1001\"Output:0", + "image": null + }, + { + "text": "Example 3: Input:s = \"0000\"Output:3Explanation:There are three ways to split s in 3 parts.\n\"0|0|00\"\n\"0|00|0\"\n\"00|0|0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numWays(String s) {\n long n=s.length();\n long one=0;//to count number of ones\n long mod=1_000_000_007;\n char[] c=s.toCharArray();\n for(int i=0;i int:\n ones = 0\n\n # Count number of Ones\n for char in s:\n if char == \"1\":\n ones += 1\n\n # Can't be grouped equally if the ones are not divisible by 3\n if ones > 0 and ones % 3 != 0:\n return 0\n\n # Ways of selecting two dividers from n - 1 dividers \n if ones == 0:\n n = len(s)\n\t\t\t# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }\n return (((n - 1) * (n - 2)) // 2) % ((10 ** 9) + 7)\n\n # Number of ones in each group\n ones_interval = ones // 3\n\n # Number of zeroes which lie on the borders\n left, right = 0, 0\n\n # Iterator\n i = 0\n temp = 0\n\n # Finding the zeroes on the left and right border\n while i < len(s):\n temp += int(s[i]) & 1\n if temp == ones_interval:\n if s[i] == '0':\n left += 1\n if temp == 2 * ones_interval:\n if s[i] == '0':\n right += 1\n i += 1\n \n # The result is the product of number of (left + 1) and (right + 1)\n # Because let's assume it as we only want to fill up the middle group\n # The solution would be if we have zero then there might be a zero in the middle\n # Or there might not be the zero, so this might case is added and then\n\t\t# the events are independent so product of both the events\n return ((left + 1) * (right + 1)) % ((10 ** 9) + 7)\n\n", + "title": "1573. Number of Ways to Split a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums of length n . nums contains a valid split at index i if the following are true: Return the number of valid splits in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.", + "There is at least one element to the right of i . That is, 0 <= i < n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,4,-8,7]Output:2Explanation:There are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,0]Output:2Explanation:There are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int waysToSplitArray(int[] nums) {\n long sum = 0;\n for(int i : nums){\n sum+=i;\n }\n int sol = 0;\n long localSum = 0;\n for(int i=0; i= sum-localSum){\n sol++;\n }\n }\n return sol;\n }\n}", + "title": "2270. Number of Ways to Split Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums of length n . nums contains a valid split at index i if the following are true: Return the number of valid splits in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.", + "There is at least one element to the right of i . That is, 0 <= i < n - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,4,-8,7]Output:2Explanation:There are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,0]Output:2Explanation:There are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n prefix_sum = [nums[0]]\n n = len(nums)\n for i in range(1, n):\n prefix_sum.append(nums[i] + prefix_sum[-1]) \n \n count = 0\n for i in range(n-1):\n if prefix_sum[i] >= prefix_sum[n-1] - prefix_sum[i]:\n count += 1\n return count\n", + "title": "2270. Number of Ways to Split Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a pointer at index 0 in an array of size arrLen . At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen , return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= steps <= 500", + "1 <= arrLen <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:steps = 3, arrLen = 2Output:4Explanation:There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "image": null + }, + { + "text": "Example 2: Input:steps = 2, arrLen = 4Output:2Explanation:There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay", + "image": null + }, + { + "text": "Example 3: Input:steps = 4, arrLen = 2Output:8", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 205 ms (Top 20.9%) | Memory: 55.71 MB (Top 10.4%)\n\nclass Solution {\n \n HashMap map = new HashMap();\n \n public int numWays(int steps, int arrLen) {\n \n return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7));\n }\n \n public long ways(int steps,int arrLen,int index){\n String curr = index + \"->\" + steps;\n \n if(index == 0 && steps == 0){\n return 1;\n }else if(index < 0 || (index >= arrLen) || steps == 0){\n return 0;\n }\n \n if(map.containsKey(curr)){\n return map.get(curr);\n }\n long stay = ways(steps-1,arrLen,index);\n long right = ways(steps-1,arrLen,index+1);\n long left = ways(steps-1,arrLen,index-1);\n \n map.put(curr , (stay+right+left) % 1000000007);\n \n return (right + left + stay) % 1000000007;\n }\n}", + "title": "1269. Number of Ways to Stay in the Same Place After Some Steps", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have a pointer at index 0 in an array of size arrLen . At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen , return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= steps <= 500", + "1 <= arrLen <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:steps = 3, arrLen = 2Output:4Explanation:There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay", + "image": null + }, + { + "text": "Example 2: Input:steps = 2, arrLen = 4Output:2Explanation:There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay", + "image": null + }, + { + "text": "Example 3: Input:steps = 4, arrLen = 2Output:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n \n # obtain maximum index we can reach\n maxLen = min(steps+1, arrLen)\n dp = [0]*maxLen\n dp[0] = 1\n \n for step in range(1, steps+1):\n dp2 = [0]*maxLen\n for pos in range(maxLen):\n # dp[step][pos] = dp[step-1][pos] + dp[step-1][pos-1] + dp[step-1][pos+1] \n temp1 = 0 if pos == 0 else dp[pos-1]\n temp2 = 0 if pos == maxLen-1 else dp[pos+1]\n dp2[pos] = (dp[pos] + temp1 + temp2)%(10**9+7)\n \n dp = dp2\n return dp[0]\n", + "title": "1269. Number of Ways to Stay in the Same Place After Some Steps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people and 40 types of hats labeled from 1 to 40 . Given a 2D integer array hats , where hats[i] is a list of all hats preferred by the i th person. Return the number of ways that the n people wear different hats to each other . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == hats.length", + "1 <= n <= 10", + "1 <= hats[i].length <= 40", + "1 <= hats[i][j] <= 40", + "hats[i] contains a list of unique integers." + ], + "examples": [ + { + "text": "Example 1: Input:hats = [[3,4],[4,5],[5]]Output:1Explanation:There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.", + "image": null + }, + { + "text": "Example 2: Input:hats = [[3,5,1],[3,5]]Output:4Explanation:There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)", + "image": null + }, + { + "text": "Example 3: Input:hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]Output:24Explanation:Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 94.19%) | Memory: 42.1 MB (Top 89.53%)\nclass Solution {\n public int numberWays(List> hats) {\n int n = hats.size(), M = (int)1e9+7;\n int[] mask = new int[41];\n for (int i = 0; i < n; i++){\n for (int h : hats.get(i)){\n mask[h]|=1<= 0 && mask[i]>0; j--){\n for (int k = 0; k < n && (mask[i]&j)>0; k++){\n if ((1<0 && (1<0){\n dp[j]+=dp[j^1< int:\n # transpose hats\n n_persons = len(hats)\n temp = [[] for _ in range(40)]\n for i, person in enumerate(hats):\n for hat in person:\n temp[hat-1].append(i)\n hats = temp\n \n # drop empty hats and sort\n hats = [h for h in hats if h]\n hats.sort(key=lambda h: len(h))\n n_hats = len(hats)\n \n # helpers\n full = 2 ** n_persons - 1\n bits = [1 << i for i in range(n_persons)]\n cut = 10 ** 9 + 7\n \n \n @cache\n def get_count(i, has_hat):\n if has_hat == full:\n # all persons have a hat\n return 1\n elif i == n_hats:\n # no more hats left\n return 0\n else:\n result = 0\n for person in hats[i]:\n # does the person \n # still not have a hat?\n if has_hat & bits[person] == 0:\n # the person wears i-th hat\n result += get_count(i + 1, has_hat | bits[person])\n # no one wears i-th hat\n result += get_count(i + 1, has_hat)\n \n # return modulo (10 ** 9 - 7)\n return result % cut\n \n \n # start form 0-th hat and \n # no person wearing a hat\n return get_count(0, 0)\n", + "title": "1434. Number of Ways to Wear Different Hats to Each Other", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two arrays of integers nums1 and nums2 , return the number of triplets formed (type 1 and type 2) under the following rules: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Type 1: Triplet (i, j, k) if nums1[i] 2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length .", + "Type 2: Triplet (i, j, k) if nums2[i] 2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [7,4], nums2 = [5,2,8,9]Output:1Explanation:Type 1: (1, 1, 2), nums1[1]2= nums2[1] * nums2[2]. (42= 2 * 8).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1], nums2 = [1,1,1]Output:9Explanation:All Triplets are valid, because 12= 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2= nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2= nums1[j] * nums1[k].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,7,8,3], nums2 = [1,2,9,7]Output:2Explanation:There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2= nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2= nums1[0] * nums1[1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 19 ms (Top 92.55%) | Memory: 42.4 MB (Top 88.30%)\nclass Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n return count(nums1 , nums2) + count(nums2 , nums1);\n }\n\n public int count(int a[] , int b[]){\n int n = a.length;\n int m = b.length;\n int count = 0;\n for(int i=0;ix)\n k--;\n else if(b[j] != b[k]){\n int jNew = j;\n int kNew = k;\n\n while(b[j] == b[jNew])\n jNew++;\n while(b[k] == b[kNew])\n kNew--;\n count += (jNew-j)*(k-kNew);\n j = jNew;\n k = kNew;\n }\n else{\n int q = k-j+1;\n count += (q)*(q-1)/2;\n break;\n }\n }\n }\n return count;\n }\n\n}", + "title": "1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two arrays of integers nums1 and nums2 , return the number of triplets formed (type 1 and type 2) under the following rules: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Type 1: Triplet (i, j, k) if nums1[i] 2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length .", + "Type 2: Triplet (i, j, k) if nums2[i] 2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [7,4], nums2 = [5,2,8,9]Output:1Explanation:Type 1: (1, 1, 2), nums1[1]2= nums2[1] * nums2[2]. (42= 2 * 8).", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1], nums2 = [1,1,1]Output:9Explanation:All Triplets are valid, because 12= 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2= nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2= nums1[j] * nums1[k].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [7,7,8,3], nums2 = [1,2,9,7]Output:2Explanation:There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2= nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2= nums1[0] * nums1[1].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 753 ms (Top 50.00%) | Memory: 14 MB (Top 47.37%)\nclass Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n = len(nums1), len(nums2)\n for i in range(m):\n sqr1[nums1[i]**2] += 1\n for j in range(n):\n sqr2[nums2[j]**2] += 1\n\n res = 0\n for i in range(m-1):\n for j in range(i+1, m):\n if nums1[i]*nums1[j] in sqr2:\n res += sqr2[nums1[i]*nums1[j]]\n\n for i in range(n-1):\n for j in range(i+1, n):\n if nums2[i]*nums2[j] in sqr1:\n res += sqr1[nums2[i]*nums2[j]]\n return res", + "title": "1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ( 'a' through 'j' ), return the number of wonderful non-empty substrings in word . If the same substring appears multiple times in word , then count each occurrence separately. A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"Output:4Explanation:The four wonderful substrings are underlined below:\n- \"aba\" -> \"a\"\n- \"aba\" -> \"b\"\n- \"aba\" -> \"a\"\n- \"aba\" -> \"aba\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"aabb\"Output:9Explanation:The nine wonderful substrings are underlined below:\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"aa\"\n- \"aabb\" -> \"aab\"\n- \"aabb\" -> \"aabb\"\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"abb\"\n- \"aabb\" -> \"b\"\n- \"aabb\" -> \"bb\"\n- \"aabb\" -> \"b\"", + "image": null + }, + { + "text": "Example 3: Input:word = \"he\"Output:2Explanation:The two wonderful substrings are underlined below:\n- \"he\" -> \"h\"\n- \"he\" -> \"e\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long wonderfulSubstrings(String word) {\n int n = word.length();\n long count = 0;\n \n long[] freq = new long[(1 << 10) + 1]; // Since we have to take only 2^10 possibilies, we can avoid an HashMap\n \n freq[0] = 1;\n int res = 0; // initialize the frequency of 0000000000 as 1 because when no element is encountered, then th bitmask is 0\n \n for (int i = 0; i < n; i++) {\n int mask = (1 << (word.charAt(i) - 'a'));\n res ^= mask; // toggling bit of the current character to make it from odd to even OR even to odd\n int chkMask = 1;\n \n count += freq[res];\n for (int j = 1; j <= 10; j++) { // Loop for checking all possiblities of different places of the Different Bit\n count += freq[chkMask ^ res];\n chkMask <<= 1;\n }\n \n freq[res]++; // increasing the frequency of the current bitmask\n }\n \n return count;\n }\n}\n", + "title": "1915. Number of Wonderful Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ( 'a' through 'j' ), return the number of wonderful non-empty substrings in word . If the same substring appears multiple times in word , then count each occurrence separately. A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"Output:4Explanation:The four wonderful substrings are underlined below:\n- \"aba\" -> \"a\"\n- \"aba\" -> \"b\"\n- \"aba\" -> \"a\"\n- \"aba\" -> \"aba\"", + "image": null + }, + { + "text": "Example 2: Input:word = \"aabb\"Output:9Explanation:The nine wonderful substrings are underlined below:\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"aa\"\n- \"aabb\" -> \"aab\"\n- \"aabb\" -> \"aabb\"\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"abb\"\n- \"aabb\" -> \"b\"\n- \"aabb\" -> \"bb\"\n- \"aabb\" -> \"b\"", + "image": null + }, + { + "text": "Example 3: Input:word = \"he\"Output:2Explanation:The two wonderful substrings are underlined below:\n- \"he\" -> \"h\"\n- \"he\" -> \"e\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n cnt, res, mask = [1] + [0] * 1023, 0, 0\n for ch in word:\n mask ^= 1 << (ord(ch) - ord('a'))\n res += cnt[mask]\n for n in range(10):\n res += cnt[mask ^ 1 << n];\n cnt[mask] += 1\n return res\n", + "title": "1915. Number of Wonderful Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the number of subarrays filled with 0 . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,0,0,2,0,0,4]Output:6Explanation:There are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,2,0,0]Output:9Explanation:There are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,2019]Output:0Explanation:There is no subarray filled with 0. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "#Baraa\nclass Solution:\n def zeroFilledSubarray(self, nums: List[int]) -> int:\n i = 0\n res = 0\n for j in range(len(nums)):\n if nums[j] != 0:\n i = j + 1\n else:\n res += (j - i + 1)\n return res\n", + "title": "2348. Number of Zero-Filled Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , return the number of subarrays filled with 0 . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,0,0,2,0,0,4]Output:6Explanation:There are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0,2,0,0]Output:9Explanation:There are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,10,2019]Output:0Explanation:There is no subarray filled with 0. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def zeroFilledSubarray(self, nums: List[int]) -> int: \n number_of_zerosubs = 0\n counter = 0\n for i in nums:\n if not i:\n counter += 1\n elif counter:\n number_of_zerosubs += sum(range(1, counter+1))\n counter = 0\n if not nums[-1]:\n number_of_zerosubs += sum(range(1, counter+1))\n return number_of_zerosubs", + "title": "2348. Number of Zero-Filled Subarrays", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'] , we may write numbers such as '13' , '551' , and '1351315' . Return the number of positive integers that can be generated that are less than or equal to a given integer n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 9", + "digits[i].length == 1", + "digits[i] is a digit from '1' to '9' .", + "All the values in digits are unique .", + "digits is sorted in non-decreasing order.", + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:digits = [\"1\",\"3\",\"5\",\"7\"], n = 100Output:20Explanation:The 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.", + "image": null + }, + { + "text": "Example 2: Input:digits = [\"1\",\"4\",\"9\"], n = 1000000000Output:29523Explanation:We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.", + "image": null + }, + { + "text": "Example 3: Input:digits = [\"7\"], n = 8Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n // DIGIT DP IS LOVE \n Integer[][][] digitdp;\n public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) {\n\n if (pos == num.length()) {\n return 1;\n }\n\n int maxDigit = -1;\n \n if(digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] !=null) return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0];\n\n if (bound) {\n maxDigit = num.charAt(pos) - '0';\n } else {\n maxDigit = 9;\n }\n\n int ans = 0;\n for (int i = 0; i <=maxDigit; i++) {\n \n // 0 can only be leading \n if(i==0 && lead){\n\n ans += solve(num,pos+1,false,dig,lead);\n \n }else{\n \n int res = Arrays.binarySearch(dig,i);\n\n if(res>=0){\n // lead = false; // now it is not possible to 0 to be in lead any more once any other call has been made\n ans += solve(num, pos + 1, bound & (i == num.charAt(pos)-'0'), dig,false);\n }\n \n }\n }\n\n return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] = ans;\n\n }\n\n public int atMostNGivenDigitSet(String[] digits, int n) {\n\n String num = n + \"\";\n Integer[] dig = new Integer[digits.length];\n for(int i=0;i int(target[idx]): continue\n res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False)\n\n cache[(idx, isBoundary, isZero)] = res\n return res\n\n return helper(0, True, True)", + "title": "902. Numbers At Most N Given Digit Set", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of positive integers in the range [1, n] that have at least one repeated digit . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 20Output:1Explanation:The only positive number (<= 20) with at least 1 repeated digit is 11.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:10Explanation:The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.", + "image": null + }, + { + "text": "Example 3: Input:n = 1000Output:262", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.74%) | Memory: 41.1 MB (Top 50.94%)\nclass Solution {\n public int numDupDigitsAtMostN(int n) {\n // 983582\n // 108318\n int ttl = n++;\n int ans = 0;\n List list = new ArrayList<>();\n while(n>0){\n list.add(n%10);\n n/=10;\n }\n for (int i = 1; i < list.size(); i++){\n ans+=9*find(i-1, 9);\n }\n boolean[] seen = new boolean[10];\n for (int i = list.size(), d = 9; i > 0; --i, d--){\n int count = i == list.size()? list.get(i-1)-1: list.get(i-1);\n for (int j = 0; j < list.get(i-1); j++){\n if (seen[j]){\n count--;\n }\n }\n ans += count*find(i-1, d);\n if (seen[list.get(i-1)]){\n break;\n }\n seen[list.get(i-1)]=true;\n }\n return ttl-ans;\n }\n\n private int find(int n, int d){\n // dCn*n!\n // d!/(d-n)/(d-n).../1\n int ans = 1;\n for (int i = 1; i <= d; i++){\n ans *= i;\n }\n for (int i = n+1; i <= d; i++){\n ans /= (i-n);\n }\n return ans;\n }\n}", + "title": "1012. Numbers With Repeated Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of positive integers in the range [1, n] that have at least one repeated digit . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 20Output:1Explanation:The only positive number (<= 20) with at least 1 repeated digit is 11.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:10Explanation:The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.", + "image": null + }, + { + "text": "Example 3: Input:n = 1000Output:262", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n \n nums = [int(i) for i in str(n+1)] # digits in n+1\n d = len(nums) # number of digits in n+1\n res = 0 # number of no duplicates\n \n # count no duplicates for numbers with res = new ArrayList<>();\n public int[] numsSameConsecDiff(int n, int k) {\n \n for(int ans = 1; ans < 10; ans++){ // first digit can't be 0\n find(ans, n-1, k); // find remaining n-1 digits using backtrack\n }\n \n return res.stream().mapToInt(Integer::intValue).toArray(); // convert list to int arr\n }\n \n private void find(int ans, int n, int k){\n \n if(n == 0){\n res.add(ans); // if got length n number then put that into res\n return;\n }\n \n for(int i = 0; i < 10; i++){\n if(Math.abs(ans%10-i) == k) // find digit that have k difference with last digit\n find(ans*10+i, n-1, k);\n }\n ans /= 10; // remove last digit while backtrack\n }\n}", + "title": "967. Numbers With Same Consecutive Differences", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k . Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 9", + "0 <= k <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 7Output:[181,292,707,818,929]Explanation:Note that 070 is not a valid number, because it has leading zeroes.", + "image": null + }, + { + "text": "Example 2: Input:n = 2, k = 1Output:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n # initialize the cache with all the valid numbers of length 1\n # cache is a list of tuple (number, digit at units place)\n cache = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]\n cacheTemp = []\n \n # each iteration will store all the valid numbers of length 2 to n in cache\n for i in range(2, n + 1):\n # loop through the cache from the previous iteration\n for j in cache:\n if k == 0:\n if j[0] != 0:\n cacheTemp.append((j[0] * 10 + j[1], j[1]))\n elif j[1] == 0 and i == 2:\n continue\n elif j[1] <= k - 1:\n if j[1] < 10 - k:\n cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n elif j[1] >= 10 - k:\n if j[1] > k - 1:\n cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n else:\n cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n cache = cacheTemp # store the list of valid integers of length i in cache\n cacheTemp = [] # empty the temporary list\n \n res = []\n for i in cache:\n res.append(i[0])\n \n return res\n \n", + "title": "967. Numbers With Same Consecutive Differences", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings first and second , consider occurrences in some text of the form \"first second third\" , where second comes immediately after first , and third comes immediately after second . Return an array of all the words third for each occurrence of \"first second third\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 1000", + "text consists of lowercase English letters and spaces.", + "All the words in text a separated by a single space .", + "1 <= first.length, second.length <= 10", + "first and second consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"Output:[\"girl\",\"student\"]", + "image": null + }, + { + "text": "Example 2: Input:text = \"we will we will rock you\", first = \"we\", second = \"will\"Output:[\"we\",\"rock\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 23.12%)\n\nclass Solution {\n public String[] findOcurrences(String text, String first, String second) {\n String[] st = text.split(\" \");\n List l = new ArrayList();\n int i =0,n = st.length;\n\n while(i List[str]:\n pattern = r\"(?<=\\b\" + first +\" \" + second + r\" )[a-z]*\"\n txt = re.findall(pattern,text)\n return txt", + "title": "1078. Occurrences After Bigram", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array arr . From some starting index, you can make a series of jumps. The (1 st , 3 rd , 5 th , ...) jumps in the series are called odd-numbered jumps , and the (2 nd , 4 th , 6 th , ...) jumps in the series are called even-numbered jumps . Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j ) in the following way: A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1 ) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "It may be the case that for some index i , there are no legal jumps." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,13,12,14,15]Output:2Explanation:From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,1,1,4]Output:3Explanation:From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.", + "image": null + }, + { + "text": "Example 3: Input:arr = [5,1,3,4,2]Output:3Explanation:We can reach the end from starting indices 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 152 ms (Top 15.26%) | Memory: 54.5 MB (Top 75.57%)\nclass Solution {\n public int oddEvenJumps(int[] arr) {\n\n int len = arr.length;\n int minjmp[] = new int[len];\n int maxjmp[] = new int[len];\n\n TreeMap map = new TreeMap<>();\n int evjmp, oddjmp;\n for(int i = len-1; i>=0; i--)\n {\n Integer minpos = map.floorKey(arr[i]);\n evjmp = (minpos != null)?map.get(minpos):len; //default len, to show not possible\n\n if(evjmp != len && (evjmp == len-1 || maxjmp[evjmp] == len-1))\n evjmp = len-1; //check the last pos reachability\n\n Integer maxpos = map.ceilingKey(arr[i]);\n oddjmp = (maxpos != null) ? map.get(maxpos):len;\n\n if(oddjmp != len && (oddjmp == len-1 || minjmp[oddjmp] == len-1))\n oddjmp = len-1;//check the last pos reachability\n\n minjmp[i] = evjmp; //specify possible jump path, if not possible assign len\n maxjmp[i] = oddjmp;//specify possible jump path, if not possible assign len\n\n map.put(arr[i],i); //put the current index\n }\n\n int res = 0;\n\n for(int i = 0; i< len-1; i++) {\n\n if(maxjmp[i] == len-1)\n res++;\n }\n\n return res+1; //since last position will always be the answer\n }\n\n}", + "title": "975. Odd Even Jump", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array arr . From some starting index, you can make a series of jumps. The (1 st , 3 rd , 5 th , ...) jumps in the series are called odd-numbered jumps , and the (2 nd , 4 th , 6 th , ...) jumps in the series are called even-numbered jumps . Note that the jumps are numbered, not the indices. You may jump forward from index i to index j (with i < j ) in the following way: A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1 ) by jumping some number of times (possibly 0 or more than once). Return the number of good starting indices . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j , you can only jump to the smallest such index j .", + "It may be the case that for some index i , there are no legal jumps." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [10,13,12,14,15]Output:2Explanation:From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,1,1,4]Output:3Explanation:From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.", + "image": null + }, + { + "text": "Example 3: Input:arr = [5,1,3,4,2]Output:3Explanation:We can reach the end from starting indices 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n \n l = len(arr)\n res = [False]*l\n res[-1] = True\n \n # for odd jump: for i, get next larger one \n odd_next = [i for i in range(l)]\n stack = [] # mono inc for ind\n for n, i in sorted([(arr[i], i) for i in range(l)]):\n while stack and stack[-1] Optional[ListNode]:\n if head is None:\n return \n odd, even_start, even = head, head.next, head.next\n while odd is not None and even is not None:\n odd.next = even.next\n if odd.next is not None:\n odd = odd.next\n even.next = odd.next\n even = even.next\n else:\n break\n odd.next = even_start\n return head\n", + "title": "328. Odd Even Linked List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of binary strings strs and two integers m and n . Return the size of the largest subset of strs such that there are at most m 0 's and n 1 's in the subset . A set x is a subset of a set y if all elements of x are also elements of y . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 600", + "1 <= strs[i].length <= 100", + "strs[i] consists only of digits '0' and '1' .", + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"], m = 5, n = 3Output:4Explanation:The largest subset with at most 5 0's and 3 1's is {\"10\", \"0001\", \"1\", \"0\"}, so the answer is 4.\nOther valid but smaller subsets include {\"0001\", \"1\"} and {\"10\", \"1\", \"0\"}.\n{\"111001\"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"10\",\"0\",\"1\"], m = 1, n = 1Output:2Explanation:The largest subset is {\"0\", \"1\"}, so the answer is 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 7928 ms (Top 10.31%) | Memory: 14.1 MB (Top 82.43%)\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n dp = [[0 for _ in range(m+1)] for _ in range(n + 1)]\n for s in strs:\n zeroes = s.count(\"0\")\n ones = len(s)-zeroes\n for i in range(n, ones-1, -1):\n for j in range(m, zeroes-1, -1):\n dp[i][j] = max(dp[i][j], dp[i-ones][j-zeroes]+1)\n return dp[n][m]", + "title": "474. Ones and Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays persons and times . In an election, the i th vote was cast for persons[i] at time times[i] . For each query at a time t , find the person that was leading the election at time t . Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: Example 1:", + "description_images": [], + "constraints": [ + "TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.", + "int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules." + ], + "examples": [ + { + "text": "Example 1: Input[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]Output[null, 0, 1, 1, 0, 0, 1]ExplanationTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 91.57%) | Memory: 51.6 MB (Top 89.43%)\nclass TopVotedCandidate {\n int[] persons;\n int[] times;\n int length;\n Map voteCount;\n Map voteLead;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n this.persons = persons;\n this.times = times;\n length = times.length-1;\n int leadCount = 0;\n int leadPerson = -1;\n voteCount = new HashMap<>();\n voteLead = new HashMap<>();\n for(int i=0; i<=length; i++){\n int newCount = voteCount.getOrDefault(persons[i], 0) + 1;\n voteCount.put(persons[i], newCount);\n if(newCount >= leadCount){\n leadCount = newCount;\n leadPerson = persons[i];\n }\n voteLead.put(times[i], leadPerson);\n }\n }\n\n public int q(int t) {\n int leadPerson = -1;\n if(voteLead.containsKey(t)) {\n leadPerson = voteLead.get(t);\n }\n else if(t < times[0]){\n leadPerson = voteLead.get(times[0]);\n }\n else if(t > times[length]){\n leadPerson = voteLead.get(times[length]);\n }\n else {\n int low = 0;\n int high = length;\n while(low <= high){\n int mid = low + (high-low)/2;\n if(times[mid] > t) high = mid - 1;\n else low = mid + 1;\n }\n leadPerson = voteLead.get(times[high]);\n }\n return leadPerson;\n }\n}\n", + "title": "911. Online Election", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integer arrays persons and times . In an election, the i th vote was cast for persons[i] at time times[i] . For each query at a time t , find the person that was leading the election at time t . Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: Example 1:", + "description_images": [], + "constraints": [ + "TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.", + "int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules." + ], + "examples": [ + { + "text": "Example 1: Input[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]Output[null, 0, 1, 1, 0, 0, 1]ExplanationTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1", + "image": null + } + ], + "follow_up": null, + "solution": "class TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n counter = defaultdict(int)\n\n mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i]\n largestVote = -1 # keep largest vote person index\n for i in range(len(persons)):\n counter[persons[i]] += 1\n if largestVote == -1 or counter[persons[i]] >= counter[largestVote]:\n largestVote = persons[i]\n mostVotePersons[i] = largestVote\n \n self.times = times\n self.mostVotePersons = mostVotePersons\n\n def q(self, t: int) -> int:\n idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t\n return self.mostVotePersons[idx]\n", + "title": "911. Online Election", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: Example 1:", + "description_images": [], + "constraints": [ + "MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr .", + "int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists." + ], + "examples": [ + { + "text": "Example 1: Input[\"MajorityChecker\", \"query\", \"query\", \"query\"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]Output[null, 1, -1, 2]ExplanationMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 79 ms (Top 91.4%) | Memory: 61.43 MB (Top 12.7%)\n\nclass MajorityChecker {\n \n private final int digits=15;\n private int[][]presum;\n private ArrayList[]pos;\n \n public MajorityChecker(int[] arr) {\n int len=arr.length;\n presum=new int[len+1][digits];\n pos=new ArrayList[20001];\n \n for(int i=0;i>=1;\n }\n }\n }\n \n public int query(int left, int right, int threshold) {\n int ans=0;\n for(int i=digits-1;i>=0;i--){\n int cnt=presum[right+1][i]-presum[left][i];\n int b=1;\n if(cnt>=threshold)b=1;\n else if(right-left+1-cnt>=threshold)b=0;\n else return -1;\n ans=(ans<<1)+b;\n }\n \n // check\n ArrayListlist=pos[ans];\n if(list==null)return -1;\n int L=floor(list,left-1);\n int R=floor(list,right);\n if(R-L>=threshold)return ans;\n return -1;\n }\n \n private int floor(ArrayListlist,int n){\n int left=0, right=list.size()-1, mid;\n while(left<=right){\n mid=left+(right-left)/2;\n int index=list.get(mid);\n if(index==n)return mid;\n else if(index> b) & 1)\n self.num_idx = defaultdict(list)\n for i in range(n):\n self.num_idx[nums[i]].append(i)\n\n def query(self, left: int, right: int, threshold: int) -> int:\n num = 0\n for b in range(MAX_BIT):\n if self.bit_sum[right+1][b] - self.bit_sum[left][b] >= threshold:\n num |= 1 << b\n l = bisect.bisect_left(self.num_idx[num], left)\n r = bisect.bisect_right(self.num_idx[num], right)\n if r-l >= threshold:\n return num\n return -1", + "title": "1157. Online Majority Element In Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. Implement the StockSpanner class: Example 1:", + "description_images": [], + "constraints": [ + "For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85] , then the stock spans would be [1,1,1,2,1,4,6] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class Pair{\n int stock;\n int span;\n \n public Pair(int stock, int span){\n this.stock = stock;\n this.span = span;\n }\n \n}\nclass StockSpanner {\n Stack stack;\n public StockSpanner() {\n stack = new Stack<>();\n }\n \n public int next(int price) {\n int span = 1;\n while(!stack.isEmpty() && stack.peek().stock <= price){\n Pair pStock = stack.pop();\n span += pStock.span ;\n }\n stack.push(new Pair(price, span));\n return span;\n }\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */\n", + "title": "901. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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 today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price. Implement the StockSpanner class: Example 1:", + "description_images": [], + "constraints": [ + "For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85] , then the stock spans would be [1,1,1,2,1,4,6] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class StockSpanner:\n\n def __init__(self):\n self.stack = []\n \n def next(self, price: int) -> int:\n \n ans = 1\n while self.stack and self.stack[-1][0] <= price:\n ans += self.stack.pop()[1]\n \n self.stack.append((price, ans))\n \n return ans\n \n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n", + "title": "901. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' . The wheels can rotate freely and wrap around: for example we can turn '9' to be '0' , or '0' to be '9' . Each move consists of turning one wheel one slot. The lock initially starts at '0000' , a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= deadends.length <= 500", + "deadends[i].length == 4", + "target.length == 4", + "target will not be in the list deadends .", + "target and deadends[i] consist of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"Output:6Explanation:A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".", + "image": null + }, + { + "text": "Example 2: Input:deadends = [\"8888\"], target = \"0009\"Output:1Explanation:We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".", + "image": null + }, + { + "text": "Example 3: Input:deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"Output:-1Explanation:We cannot reach the target without getting stuck.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 98 ms (Top 88.24%) | Memory: 61 MB (Top 77.65%)\nclass Solution {\n public int openLock(String[] deadends, String target) {\n// Converted target to Integer type.\n int t = Integer.parseInt(target);\n HashSet visited = new HashSet<>();\n\n// Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited.\n for(String str: deadends){\n visited.add(Integer.parseInt(str));\n }\n// BFS\n Queue q = new ArrayDeque<>();\n// We make sure that 0 itself isn't a deadend\n if(visited.contains(0)){\n return -1;\n }\n q.add(0);\n visited.add(0);\n int level = 0;\n while(q.size() > 0){\n int size = q.size();\n while(size-->0){\n int elem = q.remove();\n if(t == elem){\n return level;\n }\n// Will help check 4 digits of the element. From digit with low precendence(ones place) to high precedence(thousands place)\n for(int i = 1; i < 10000; i= i*10){\n// The wheel can be rotated in two directions. Hence two numbers.\n int num1;\n int num2;\n// The wheel at 0 can become 1 or 9 due to wrapping.\n if(elem / i % 10 == 0){\n num1=elem + i;\n num2 = elem+ i * 9;\n }\n// The wheel at 9 can become 0 or 8 due to wrapping.\n else if(elem / i % 10 == 9){\n num1 = elem - i * 9;\n num2 = elem -i;\n }\n else{\n num1 = elem -i;\n num2 = elem + i;\n }\n// Checking if numbers have already been visited.\n if(!(visited.contains(num1))){\n visited.add(num1);\n q.add(num1);\n }\n if(!(visited.contains(num2))){\n visited.add(num2);\n q.add(num2);\n }\n }\n }\n level++;\n }\n return -1;\n }\n}", + "title": "752. Open the Lock", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' . The wheels can rotate freely and wrap around: for example we can turn '9' to be '0' , or '0' to be '9' . Each move consists of turning one wheel one slot. The lock initially starts at '0000' , a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= deadends.length <= 500", + "deadends[i].length == 4", + "target.length == 4", + "target will not be in the list deadends .", + "target and deadends[i] consist of digits only." + ], + "examples": [ + { + "text": "Example 1: Input:deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"Output:6Explanation:A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".", + "image": null + }, + { + "text": "Example 2: Input:deadends = [\"8888\"], target = \"0009\"Output:1Explanation:We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".", + "image": null + }, + { + "text": "Example 3: Input:deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"Output:-1Explanation:We cannot reach the target without getting stuck.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n def neighbor(s):\n res = []\n for i, c in enumerate(s):\n res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:])\n res.append(s[:i] + chr((ord(c) - ord('0') + 1) % 10 + ord('0')) + s[i + 1:])\n return res\n \n deadends = set(deadends)\n if \"0000\" in deadends:\n return -1\n ans = 0\n queue = deque([\"0000\"])\n vis = set()\n while queue:\n l = len(queue)\n for _ in range(l):\n cur = queue.popleft()\n if cur == target:\n return ans\n for nxt in neighbor(cur):\n if nxt not in vis and nxt not in deadends:\n queue.append(nxt)\n vis.add(nxt)\n ans += 1\n return -1\n", + "title": "752. Open the Lock", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the i th node. The root of the tree is node 0 , so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class: Example 1:", + "description_images": [], + "constraints": [ + "Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.", + "Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.", + "Upgrade : Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors.", + "The node is unlocked,", + "It has at least one locked descendant (by any user), and", + "It does not have any locked ancestors." + ], + "examples": [ + { + "text": "Example 1: Input[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]Output[null, true, false, true, true, true, false]ExplanationLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.", + "image": "https://assets.leetcode.com/uploads/2021/07/29/untitled.png" + } + ], + "follow_up": null, + "solution": "class LockingTree {\n int[] p;\n Map map = new HashMap<>();\n Map> children = new HashMap<>();\n public LockingTree(int[] parent) {\n p = parent;\n for(int i = 0; i < p.length; i ++) {\n children.put(i, new ArrayList<>());\n }\n for(int i = 1; i < p.length; i ++) {\n children.get(p[i]).add(i);\n }\n }\n \n public boolean lock(int num, int user) {\n if(!map.containsKey(num)) {\n map.put(num, user);\n return true;\n } \n return false;\n }\n \n public boolean unlock(int num, int user) {\n if(map.containsKey(num) && map.get(num) == user) {\n map.remove(num);\n return true;\n }\n return false;\n }\n \n public boolean upgrade(int num, int user) {\n //check the node\n if(map.containsKey(num)) return false;\n //check Ancestor\n int ori = num;\n while(p[num] != -1) {\n if(map.get(p[num]) != null) return false;\n num = p[num];\n }\n //check Decendant\n Queue q = new LinkedList<>();\n List child = children.get(ori);\n if(child != null) {\n for(int c : child) q.offer(c);\n }\n boolean lock = false;\n while(!q.isEmpty()) {\n int cur = q.poll();\n if(map.get(cur) != null) {\n lock = true;\n map.remove(cur); // unlock\n }\n List cc = children.get(cur);\n if(cc != null) {\n for(int c : cc) q.offer(c);\n }\n } \n if(!lock) return false;\n map.put(ori, user); // lock the original node\n return true;\n }\n}\n", + "title": "1993. Operations on Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the i th node. The root of the tree is node 0 , so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class: Example 1:", + "description_images": [], + "constraints": [ + "Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.", + "Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.", + "Upgrade : Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors.", + "The node is unlocked,", + "It has at least one locked descendant (by any user), and", + "It does not have any locked ancestors." + ], + "examples": [ + { + "text": "Example 1: Input[\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]Output[null, true, false, true, true, true, false]ExplanationLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.", + "image": "https://assets.leetcode.com/uploads/2021/07/29/untitled.png" + } + ], + "follow_up": null, + "solution": "class LockingTree:\n\n def __init__(self, parent: List[int]):\n self.p = collections.defaultdict(lambda: -2)\n self.c = collections.defaultdict(list)\n for i, p in enumerate(parent):\n self.c[p].append(i)\n self.p[i] = p\n self.user = collections.defaultdict(set)\n self.node = collections.defaultdict(lambda: -2)\n\n def lock(self, num: int, user: int) -> bool:\n if self.node[num] == -2:\n self.user[user].add(num)\n self.node[num] = user\n return True\n return False \n\n def unlock(self, num: int, user: int) -> bool:\n if self.node[num] == user: \n del self.node[num]\n self.user[user].remove(num)\n return True\n return False \n\n def upgrade(self, num: int, user: int) -> bool:\n if self.node[num] != -2: return False\n if not self.has_locked_descendant(num): return False\n if self.has_locked_ancester(num): return False\n self.lock(num, user)\n self.unlock_descendant(num)\n return True\n \n def has_locked_descendant(self, num): #function to check if alteast one desendent is lock or not \n has = False\n for child in self.c[num]:\n if self.node[child] != -2:\n return True\n has |= self.has_locked_descendant(child)\n return has \n \n def has_locked_ancester(self, num): # function to check if no parent is locked \n if num == -1: return False\n if self.node[self.p[num]] != -2:\n return True\n return self.has_locked_ancester(self.p[num])\n\n def unlock_descendant(self, num): # function fro unlocking all desendents \n for child in self.c[num]:\n if child in self.node:\n user = self.node[child]\n del self.node[child]\n if user in self.user:\n self.user[user].remove(child)\n self.unlock_descendant(child)\n", + "title": "1993. Operations on Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The adjacent integers in nums will perform the float division. However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. Return the corresponding expression that has the maximum value in string format . Note: your expression should not contain redundant parenthesis. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for nums = [2,3,4] , we will evaluate the expression \"2/3/4\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1000,100,10,2]Output:\"1000/(100/10/2)\"Explanation:1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant, since they don't influence the operation priority. So you should return \"1000/(100/10/2)\".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,4]Output:\"2/(3/4)\"", + "image": null + }, + { + "text": "Example 3: Input:nums = [2]Output:\"2\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 33.5%) | Memory: 41.11 MB (Top 16.7%)\n\nclass Solution {\n public String optimalDivision(int[] nums) {\n \n if(nums.length==1){\n return nums[0] + \"\";\n }else if(nums.length==2){\n StringBuilder sb=new StringBuilder();\n sb.append(nums[0] + \"/\" + nums[1]);\n return sb.toString();\n }\n \n StringBuilder sb=new StringBuilder();\n sb.append(nums[0]);\n sb.append(\"/(\");\n for(int i=1;i str:\n if k>1:\n s=list(c for c in s)\n s.sort()\n return ''.join(s)\n s1=s\n for i in range(len(s)):\n s=s[1:]+s[0]\n s1=min(s1,s)\n return s1", + "title": "899. Orderly Queue", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn] . You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m , n , maxMove , startRow , startColumn , return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "0 <= maxMove <= 50", + "0 <= startRow < m", + "0 <= startColumn < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0Output:6", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png" + }, + { + "text": "Example 2: Input:m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1Output:12", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 36.40%) | Memory: 43.3 MB (Top 32.31%)\nclass Solution {\n int[][][] dp;\n int mod = 1000000007;\n public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n dp = new int[m][n][maxMove + 1];\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n for (int k = 0; k <= maxMove; k++)\n dp[i][j][k] = -1;\n return count(m, n, maxMove, startRow, startColumn) % mod;\n }\n public int count(int m, int n, int move, int r, int c) {\n if (r < 0 || c < 0 || r >= m || c >= n)\n return 1;\n if (move <= 0)\n return 0;\n if (dp[r][c][move] != -1)\n return dp[r][c][move] % mod;\n dp[r][c][move] = ((count(m, n, move - 1, r + 1, c) % mod + count (m, n, move - 1, r - 1, c) % mod) % mod + (count (m, n, move - 1, r, c + 1) % mod + count(m, n, move - 1, r, c - 1) % mod) % mod ) % mod;\n return dp[r][c][move] % mod;\n }\n}", + "title": "576. Out of Boundary Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn] . You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball. Given the five integers m , n , maxMove , startRow , startColumn , return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 50", + "0 <= maxMove <= 50", + "0 <= startRow < m", + "0 <= startColumn < n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0Output:6", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png" + }, + { + "text": "Example 2: Input:m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1Output:12", + "image": "https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int:\n if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n:\n return 1\n \n if dp[maxMove][startRow][startColumn]!=-1:\n return dp[maxMove][startRow][startColumn]\n \n if mat[startRow][startColumn]==1:\n return 0\n \n if maxMove <= 0:\n return 0\n \n # mat[startRow][startColumn] = 1\n a = self.helper(m, n, maxMove-1, startRow+1, startColumn,mat,dp)\n b = self.helper(m, n, maxMove-1, startRow-1, startColumn,mat,dp)\n c = self.helper(m, n, maxMove-1, startRow, startColumn+1,mat,dp)\n d = self.helper(m, n, maxMove-1, startRow, startColumn-1,mat,dp)\n dp[maxMove][startRow][startColumn] = a+b+c+d\n return dp[maxMove][startRow][startColumn]\n \n \n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n mat = [[0 for i in range(n)] for j in range(m)]\n dp = [[[-1 for i in range(n+1)] for j in range(m+1)] for k in range(maxMove+1)]\n return self.helper(m, n, maxMove, startRow, startColumn, mat,dp)%(10**9 + 7) \n \n\n \n", + "title": "576. Out of Boundary Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == heights.length", + "n == heights[r].length", + "1 <= m, n <= 200", + "0 <= heights[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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]]", + "image": "https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg" + }, + { + "text": "Example 2: Input:heights = [[2,1],[1,2]]Output:[[0,0],[0,1],[1,0],[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 37.68%) | Memory: 54.9 MB (Top 45.37%)\nclass Solution {\n public List> pacificAtlantic(int[][] heights) {\n if (heights == null) return null;\n if (heights.length == 0) return null;\n if (heights[0].length == 0) return null;\n\n /** */\n boolean [][] po = new boolean[heights.length][heights[0].length];\n boolean [][] ao = new boolean[heights.length][heights[0].length];\n\n for (int i = 0; i < heights[0].length; i ++) {\n dfs(heights, i, 0, 0, po); // top\n dfs(heights, i, heights.length - 1, 0, ao); // bottom\n }\n\n for (int i = 0; i < heights.length; i ++) {\n dfs(heights, 0, i, 0, po); // left\n dfs(heights, heights[0].length - 1, i, 0, ao); // right\n }\n\n List> ans = new ArrayList<>();\n for (int i = 0; i < heights.length; i ++) {\n for (int j = 0; j < heights[i].length; j ++) {\n if (ao[i][j] && po[i][j]) {\n ArrayList ar = new ArrayList<>();\n ar.add(i);\n ar.add(j);\n ans.add(ar);\n }\n }\n }\n\n return ans;\n }\n\n private void dfs(int[][] heights, int x, int y, int h, boolean[][] v) {\n if (x < 0 || y < 0 || x >= heights[0].length || y >= heights.length) return;\n if (v[y][x] || heights[y][x] < h) return;\n v[y][x] = true;\n /** left */\n dfs(heights, x - 1, y, heights[y][x], v);\n\n /** right */\n dfs(heights, x + 1, y, heights[y][x], v);\n\n /** up */\n dfs(heights, x, y - 1, heights[y][x], v);\n\n /** down */\n dfs(heights, x, y + 1, heights[y][x], v);\n }\n}", + "title": "417. Pacific Atlantic Water Flow", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == heights.length", + "n == heights[r].length", + "1 <= m, n <= 200", + "0 <= heights[r][c] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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]]", + "image": "https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg" + }, + { + "text": "Example 2: Input:heights = [[2,1],[1,2]]Output:[[0,0],[0,1],[1,0],[1,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n # Purpose: find the cells that allow rain flow into the ocean\n # Method: DFS\n # Intuition: start from each border, check cell and neb, if OK, append to res\n \n # init: res, vis (pac, atl), ROW, COL\n res = []\n pac = set()\n atl = set()\n ROW = len(heights)\n COL = len(heights[0])\n\n # top and bottom row\n for col in range(COL):\n self.dfs(0, col, pac, heights[0][col], heights)\n self.dfs(ROW-1, col, atl, heights[ROW-1][col], heights)\n\n # left and right col\n for row in range(ROW):\n self.dfs(row, 0, pac, heights[row][0], heights)\n self.dfs(row, COL-1, atl, heights[row][COL-1], heights)\n\n # append to res\n for row in range(ROW):\n for col in range(COL):\n if (row, col) in pac and (row, col) in atl:\n res.append([row, col])\n\n # return\n return res\n\n \n def dfs(self, row, col, vis, prev, heights):\n # hard-code definition\n try:\n cur = heights[row][col]\n except:\n pass\n\n # inbound, unvisited, increase from ocean\n if (0<=row= prev) \\\n and ((row, col) not in vis):\n\n # add to visited \n vis.add((row, col))\n\n # check nebs\n self.dfs(row+1, col, vis, cur, heights)\n self.dfs(row-1, col, vis, cur, heights)\n self.dfs(row, col+1, vis, cur, heights)\n self.dfs(row, col-1, vis, cur, heights)\n\n", + "title": "417. Pacific Atlantic Water Flow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n ), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. Given an array houses , an m x n matrix cost and an integer target where: Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods . If it is not possible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}] ." + ], + "examples": [ + { + "text": "Example 1: Input:houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3Output:9Explanation:Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.", + "image": null + }, + { + "text": "Example 2: Input:houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3Output:11Explanation:Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.", + "image": null + }, + { + "text": "Example 3: Input:houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3Output:-1Explanation:Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 70 ms (Top 34.94%) | Memory: 52.8 MB (Top 34.74%)\nclass Solution {\n public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp)\n {\n if(idx==houses.length || neigh>target)\n {\n if(neigh==target)\n return 0;\n return Integer.MAX_VALUE;\n }\n if(dp[idx][prevColor][neigh]!=null)\n return dp[idx][prevColor][neigh];\n int minCost = Integer.MAX_VALUE;\n\n if(houses[idx]==0)\n {\n for(int j = 0;j int:\n @cache\n def dp(i, p, h):\n if (h > target) or (i == m and h != target):\n return inf\n if i == m:\n return 0\n if houses[i] != 0:\n return dp(i + 1, houses[i], h + int(p != houses[i]))\n\n best = inf\n for j, c in enumerate(cost[i], 1):\n best = min(best, dp(i + 1, j, h + int(p != j)) + c)\n return best\n\n res = dp(0, 0, 0)\n return res if res != inf else -1\n", + "title": "1473. Paint House III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integers m and n . Consider an m x n grid where each cell is initially white. You can paint each cell red , green , or blue . All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color . Since the answer can be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= m <= 5", + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:m = 1, n = 1Output:3Explanation:The three possible colorings are shown in the image above.", + "image": "https://assets.leetcode.com/uploads/2021/06/22/colorthegrid.png" + }, + { + "text": "Example 2: Input:m = 1, n = 2Output:6Explanation:The six possible colorings are shown in the image above.", + "image": "https://assets.leetcode.com/uploads/2021/06/22/copy-of-colorthegrid.png" + }, + { + "text": "Example 3: Input:m = 5, n = 5Output:580986", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n public static void val(ArrayList arr,int color,int m,String s)\n {\n if(m==0)\n {\n arr.add(s);\n return;\n }\n for(int i=0;i<3;i++)\n {\n if(color!=i)\n val(arr,i,m-1,s+i);\n }\n }\n public static boolean Match(String s,String s1)\n {\n for(int i=0;i arr=new ArrayList();\n for(int i=0;i<3;i++)\n {\n String s=\"\";\n val(arr,i,m-1,s+i);\n }\n ArrayList> adj=new ArrayList>();\n for(int i=0;i());\n }\n \n for(int i=0;i int:\n from functools import reduce\n MOD = 10**9 + 7\n sum_mod = lambda x,y: (x+y)%MOD\n \n def normalize(pat_var):\n mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n return tuple([ mapping[e] for e in pat_var])\n \n def get_pats(m, i, pat, pats):\n if i == m-1:\n pats.append(tuple(pat))\n return\n i_nx = i+1\n for p_it_nx in (1,2,3):\n if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n pat.append(p_it_nx)\n get_pats(m, i_nx, pat, pats)\n pat.pop()\n return pats\n \n def get_trans(pat, i, pat_pre, trans):\n if i == len(pat)-1:\n pat_nl = normalize(pat_pre)\n trans[pat_nl] = trans.get(pat_nl, 0) + 1\n return\n for p_it_pre in (1,2,3):\n i_nx = i+1\n if (p_it_pre != pat[i_nx]\n and (not pat_pre or p_it_pre != pat_pre[-1])):\n pat_pre.append(p_it_pre)\n get_trans(pat, i_nx, pat_pre, trans)\n pat_pre.pop()\n return trans\n\n pats = get_pats(m, -1, [], [])\n # {pattern_i: {pattern_pre:count}}\n pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } \n \n p_counts = { pat:1 for pat in pat_trans.keys() }\n for i in range(n-1):\n p_counts_new = {}\n for pat, trans in pat_trans.items():\n p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n p_counts = p_counts_new\n \n res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n return (res * perms) % MOD\n", + "title": "1931. Painting a Grid With Three Different Colors", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return true if it is a palindrome. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 10^5 ] .", + "0 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,2,1]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(ListNode head) {\n \n ListNode mid = getMiddle(head);\n ListNode headSecond = reverse(mid);\n ListNode reverseHead = headSecond;\n \n while(head != null && headSecond != null){\n if(head.val != headSecond.val){\n break;\n }\n head = head.next;\n headSecond = headSecond.next;\n }\n reverse(reverseHead);\n \n return head==null || headSecond == null;\n }\n \n public ListNode reverse(ListNode head){\n if(head==null) return head;\n ListNode prev = null;\n ListNode present = head;\n ListNode next = head.next;\n while(present != null){\n present.next = prev;\n prev = present;\n present = next;\n if(next!=null)\n next = next.next;\n }\n return prev;\n }\n \n public ListNode getMiddle(ListNode head){\n ListNode temp = head;\n int count = 0;\n while(temp!=null){\n temp = temp.next;\n count++;\n }\n int mid = count/2;\n temp = head;\n for(int i=0; i bool:\n if head.next == None: return True #if only 1 element, it's always a palindrome\n forward = head\n first_half = []\n fast = head\n\n while (fast != None and fast.next != None):\n first_half.append(forward.val)\n forward = forward.next\n fast = fast.next.next\n\n # forward should now be through half the list\n if fast != None : forward = forward.next # if length isn't even, skip the middle number\n \n reverse = len(first_half)-1\n while forward != None:\n if forward.val != first_half[reverse]: return False\n forward = forward.next\n reverse -= 1\n\n return True\n", + "title": "234. Palindrome Linked List", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer x , return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, 121 is a palindrome while 123 is not." + ], + "examples": [ + { + "text": "Example 1: Input:x = 121Output:trueExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121Output:falseExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10Output:falseExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 39.53%) | Memory: 44.7 MB (Top 53.62%)\nclass Solution {\n public boolean isPalindrome(int x) {\n int sum = 0;\n int X = x;\n\n while(x > 0){\n sum = 10 * sum + x % 10;\n x /= 10;\n }\n\n return sum == X;\n }\n}", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer x , return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, 121 is a palindrome while 123 is not." + ], + "examples": [ + { + "text": "Example 1: Input:x = 121Output:trueExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121Output:falseExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10Output:falseExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 94.40%) | Memory: 13.8 MB (Top 59.53%)\nclass Solution(object):\n def isPalindrome(self,x):\n return str(x) == str(x)[::-1]", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 5000", + "0 <= words[i].length <= 300", + "words[i] consists of lower-case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]Output:[[0,1],[1,0],[3,2],[2,4]]Explanation:The palindromes are [\"dcbaabcd\",\"abcddcba\",\"slls\",\"llssssll\"]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"bat\",\"tab\",\"cat\"]Output:[[0,1],[1,0]]Explanation:The palindromes are [\"battab\",\"tabbat\"]", + "image": null + }, + { + "text": "Example 3: Input:words = [\"a\",\"\"]Output:[[0,1],[1,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 117 ms (Top 97.32%) | Memory: 56.20 MB (Top 42.83%)\n\n//149ms\n\nclass Solution {\n public List> palindromePairs(String[] words) {\n HashMap wordMap = new HashMap<>();\n Set set = new TreeSet<>();\n int n = words.length;\n \n for(int i=0;i> ans = new ArrayList<>();\n \n for(int i=0;i List[List[int]]:\n m = {}\n for i, word in enumerate(words):\n m[word] = i\n \n result = set()\n for i, word in enumerate(words):\n n, rev_word = len(word), word[::-1]\n prefix, suffix = word, rev_word\n \n for j in range(n+1):\n if prefix == suffix:\n key = rev_word[:j]\n if key in m and m[key] != i:\n result.add((m[key], i))\n \n if j == n:\n break\n \n prefix = prefix[:-1]\n suffix = suffix[1:]\n \n # print('pre', i, result)\n \n prefix, suffix = '', ''\n for j in range(n+1):\n if prefix == suffix:\n if prefix == suffix:\n key = rev_word[j:]\n if key in m and m[key] != i:\n result.add((i, m[key]))\n \n if j == n:\n break\n \n prefix = word[n-j-1] + prefix\n suffix = suffix + rev_word[j]\n \n # print('post', i, result)\n \n return list(result)\n", + "title": "336. Palindrome Pairs", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome . Return all possible palindrome partitioning of s . A palindrome string is a string that reads the same backward as forward. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 25.04%) | Memory: 136.1 MB (Top 72.32%)\n// Plaindrome Partitioning\n// Leetcode : https://leetcode.com/problems/palindrome-partitioning/\n\nclass Solution {\n public List> partition(String s) {\n List> result = new ArrayList<>();\n if(s == null || s.length() == 0)\n return result;\n helper(s, 0, new ArrayList(), result);\n return result;\n }\n private void helper(String s, int start, List list, List> result){\n if(start == s.length()){\n result.add(new ArrayList<>(list));\n return;\n }\n for(int i = start; i < s.length(); i++){\n if(isPalindrome(s, start, i)){\n list.add(s.substring(start, i+1));\n helper(s, i+1, list, result);\n list.remove(list.size()-1);\n }\n }\n }\n private boolean isPalindrome(String s, int start, int end){\n while(start < end){\n if(s.charAt(start++) != s.charAt(end--))\n return false;\n }\n return true;\n }\n}", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome . Return all possible palindrome partitioning of s . A palindrome string is a string that reads the same backward as forward. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1302 ms (Top 13.95%) | Memory: 35.7 MB (Top 6.05%)\n\"\"\"\nwe can approach this problem using manacher's algorithm with backtracking and recursion\n\"\"\"\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n lookup = {\"\": [[]]}\n def lps(s):\n if s in lookup:\n return lookup[s]\n\n final_res = []\n result_set = set()\n for k in range(len(s)):\n i, j = k, k\n\n # check for odd length palindromes\n while i>= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n\n # check for even length palindromes\n i, j = k, k+1\n while i >= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n lookup[s] = final_res\n return final_res\n return lps(s)", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:1Explanation:The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:0", + "image": null + }, + { + "text": "Example 3: Input:s = \"ab\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\nint dp[];\n\n public boolean pali(int i,int j,String s){\n \n // int j=s.length()-1,i=0;\n \n while(i<=j){\n \n if(s.charAt(i)!=s.charAt(j))return false;\n \n i++;j--;\n \n }\n \n return true;\n \n}\npublic int cut(String s,int i,int n,int dp[]){\n \n if(i==n)return 0;\n if(dp[i]!=-1)return dp[i];\n \n int min=Integer.MAX_VALUE;\n \n for(int j=i;j bool:\n st = s[l: r+1]\n rev = st[::-1]\n return st == rev\n \n def minCut(self, s: str) -> int:\n N = len(s)\n if not s: return 0\n if self.isPallindrom(s, 0, N-1): return 0\n dp = [sys.maxsize] * (N+1)\n dp[-1] = 0\n \n for i in range(N-1, -1, -1):\n for j in range(i, N):\n if self.isPallindrom(s, i, j):\n dp[i] = min(dp[i], 1 + dp[j+1])\n \n return dp[0]-1\n", + "title": "132. Palindrome Partitioning II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s containing lowercase letters and an integer k . You need to : Return the minimal number of characters that you need to change to divide the string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "First, change some characters of s to other lowercase English letters.", + "Then divide s into k non-empty disjoint substrings such that each substring is a palindrome." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", k = 2Output:1Explanation:You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbc\", k = 3Output:0Explanation:You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 8Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 26.09%) | Memory: 55.8 MB (Top 6.28%)\nclass Solution {\n public int mismatchCount(String s) {\n int n = s.length()-1;\n int count = 0;\n for(int i=0,j=n;i=n)\n return 105;\n if(k<0)\n return 105;\n if(dp[i][j][k] != null) {\n return dp[i][j][k];\n }\n if(n-j int:\n n=len(s)\n @lru_cache(None)\n def is_palin(s): #This function returns min no of chars to change to make s as a palindrome\n cnt=0\n for c1,c2 in zip(s,s[::-1]):\n if c1!=c2: cnt+=1\n if len(s)%2==0:\n return cnt//2\n return (cnt+1)//2\n @lru_cache(None)\n def dp(i,j,k): #We analyse string s[i:j+1] with k divisions left\n if j==n:\n return 0 if k==0 else sys.maxsize\n if k==0: \n return sys.maxsize\n ans=sys.maxsize\n cnt=is_palin(s[i:j+1])\n #terminate here\n ans=min(ans,dp(j+1,j+1,k-1)+cnt)\n #dont terminate\n ans=min(ans,dp(i,j+1,k))\n return ans\n return dp(0,0,t)\n \n \n \n", + "title": "1278. Palindrome Partitioning III", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s , return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false .​​​​​ A string is said to be palindrome if it the same string when reversed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= s.length <= 2000", + "s ​​​​​​ consists only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcbdd\"Output:trueExplanation:\"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bcbddxy\"Output:falseExplanation:s cannot be split into 3 palindromes.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkPartitioning(String s) {\n int n = s.length();\n boolean[][] dp = new boolean[n][n];\n for(int g=0 ; g bool:\n n = len(s)\n\n @lru_cache(None)\n def pal(i,j):\n if i == j:\n return True\n if s[i] != s[j]:\n return False\n if i+1 == j:\n return True\n else:\n return pal(i+1,j-1)\n\n for i in range(n-2):\n if pal(0,i):\n for j in range(i+1,n-1):\n if pal(i+1,j) and pal(j+1,n-1):\n return True\n return False", + "title": "1745. Palindrome Partitioning IV", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\"Output:3Explanation:Three palindromic strings: \"a\", \"b\", \"c\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\"Output:6Explanation:Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".", + "image": null + } + ], + "follow_up": null, + "solution": "int n = s.length();\n int count = 0;\n for(int i = 0;i=0 && r=0 && r pancakeSort(int[] arr) {\n List list = new ArrayList<>();\n int n = arr.length;\n while(n!=1) {\n int maxIndex = findIndex(arr,n);\n reverse(arr, maxIndex);\n reverse(arr, n-1);\n list.add(maxIndex+1);\n list.add(n);\n n--;\n }\n return list;\n }\n\n static int findIndex(int[] arr, int value) {\n for(int i=0; i List[int]:\n #helper function to flip the numbers in the array\n\t\tdef flip(i, j):\n while i < j:\n arr[i], arr[j] = arr[j], arr[i]\n j -= 1\n i += 1\n \n #sort from 0 to i\n def sort(i):\n\t\t\t#base case where all the numbers are sorted, thus no more recursive calls\n if i < 0:\n return []\n ret = []\n\t\t\t#find the biggest number, which always will be the len(arr), or i + 1\n idx = arr.index(i + 1)\n\t\t\t# if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number\n if idx == i:\n return sort(i - 1)\n \n\t\t\t#we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result\n ret.append(idx + 1)\n flip(0, idx)\n\t\t\t#we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well)\n ret.append(i + 1)\n flip(0, i)\n\t\t\t#sort the next biggest number by setting a new boundary i - 1\n return ret + sort(i - 1)\n \n \n return sort(len(arr) - 1)\n \n", + "title": "969. Pancake Sorting", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n , which indicates that there are n courses labeled from 1 to n . You are also given an array relations where relations[i] = [prevCourse i , nextCourse i ] , representing a prerequisite relationship between course prevCourse i and course nextCourse i : course prevCourse i has to be taken before course nextCourse i . Also, you are given the integer k . In one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking. Return the minimum number of semesters needed to take all courses . The testcases will be generated such that it is possible to take every course. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_1.png", + "https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_2.png" + ], + "constraints": [ + "1 <= n <= 15", + "1 <= k <= n", + "0 <= relations.length <= n * (n-1) / 2", + "relations[i].length == 2", + "1 <= prevCourse i , nextCourse i <= n", + "prevCourse i != nextCourse i", + "All the pairs [prevCourse i , nextCourse i ] are unique .", + "The given graph is a directed acyclic graph." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2Output:3Explanation:The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2Output:4Explanation:The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3 only since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.", + "image": null + }, + { + "text": "Example 3: Input:n = 11, dependencies = [], k = 2Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 435 ms (Top 42.70%) | Memory: 45.5 MB (Top 33.71%)\nclass Solution {\n public int minNumberOfSemesters(int n, int[][] relations, int k) {\n int[] ok = new int[1 << n];\n int[] dp = new int[1 << n];\n Arrays.fill(dp, 30);\n dp[0]=0;\n for (int[] r : relations){\n ok[r[1]-1] |= 1<<(r[0]-1);\n }\n for (int i = 0; i < 1< 0; i++){\n if ((old&(1< int:\n graph = [0] * n\n out_degree = [0] * n\n # -1 to fix 1-based indexing offset from prompt.\n for pre_req, course in relations:\n graph[course-1] += 1 << (pre_req-1)\n out_degree[pre_req-1] += 1\n # Just converts course to its shifted value\n c2shift = [1< k)\n for batch in itertools.combinations(pre_reqs, k):\n diff = sum(batch)\n t = course_total + diff\n if t == goal:\n return steps + 1\n if not seen[t]:\n queue.append((t, steps+1))\n seen[t] = 1![Uploading file...]()\n\n", + "title": "1494. Parallel Courses II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n , which indicates that there are n courses labeled from 1 to n . You are also given a 2D integer array relations where relations[j] = [prevCourse j , nextCourse j ] denotes that course prevCourse j has to be completed before course nextCourse j (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1) th course. You must find the minimum number of months needed to complete all the courses following these rules: Return the minimum number of months needed to complete all the courses . Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "You may start taking a course at any time if the prerequisites are met.", + "Any number of courses can be taken at the same time ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, relations = [[1,3],[2,3]], time = [3,2,5]Output:8Explanation:The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]Output:12Explanation:The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 58 ms (Top 49.87%) | Memory: 123 MB (Top 65.81%)\nclass Solution {\n public int minimumTime(int n, int[][] relations, int[] time) {\n List adj[] = new ArrayList[n];\n int indegree[] = new int[n];\n int completionTime[] = new int[n];\n for(int i=0; i();\n for(int relation[]: relations){\n int u = relation[0]-1, v = relation[1]-1;\n adj[u].add(v);\n indegree[v]++;\n }\n Queue q = new LinkedList<>();\n for(int i=0; i int:\n in_degree=defaultdict(int)\n graph=defaultdict(list)\n latest=[0]*(n+1)\n for u,v in relations:\n graph[u].append(v)\n in_degree[v]+=1\n q=[]\n for i in range(1,n+1):\n if in_degree[i]==0:\n latest[i]=time[i-1]\n q.append(i)\n while q:\n node=q.pop()\n t0=latest[node]\n for nei in graph[node]:\n t=time[nei-1]\n latest[nei]=max(latest[nei],t0+t)\n in_degree[nei]-=1\n if in_degree[nei]==0:\n q.append(nei)\n return max(latest)\n", + "title": "2050. Parallel Courses III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"Output:14Explanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"Output:2Explanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"Output:5Explanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 68.0%) | Memory: 41.90 MB (Top 62.0%)\n\nclass Solution {\n Map vars = new HashMap<>();\n\n public int evaluate(String expression) {\n String[] strs = split(expression);\n\n switch (strs[0]) {\n case \"let\":\n Map localVars = new HashMap<>(vars);\n Map temp = vars;\n for (int i = 1; i < strs.length - 1; i++) {\n String name = strs[i];\n int val = evaluate(strs[i + 1]);\n if (localVars.containsKey(name)) localVars.replace(name, val);\n else localVars.put(name, val);\n i++;\n vars = localVars;\n }\n int res = evaluate(strs[strs.length - 1]);\n vars = temp;\n return res;\n\n case \"add\":\n return evaluate(strs[1]) + evaluate(strs[2]);\n\n case \"mult\":\n return evaluate(strs[1]) * evaluate(strs[2]);\n\n default:\n try {\n return Integer.parseInt(strs[0]);\n } catch (Exception e) {\n return vars.get(strs[0]);\n }\n }\n }\n\n private String[] split(String exp) {\n List tokens = new ArrayList<>();\n\n if (exp.charAt(0) != '(') {\n tokens.add(exp);\n }\n else {\n tokens.add(exp.substring(1, exp.indexOf(' ')));\n\n for (int i = exp.indexOf(' ') + 1; i < exp.length(); i++) {\n if (exp.charAt(i) == ')') break;\n else if (exp.charAt(i) == ' ') continue;\n\n if (tokens.get(0).equals(\"let\") && tokens.size() % 2 == 1 && exp.charAt(i) != '(' && exp.indexOf(' ', i) > 0) {\n tokens.add(exp.substring(i, exp.indexOf(' ', i + 1)));\n i = exp.indexOf(' ', i + 1) + 1;\n }\n\n if (exp.charAt(i) != '(') {\n int index = exp.indexOf(' ', i + 1);\n if (index < 0) index = exp.indexOf(')', i + 1);\n tokens.add(exp.substring(i, index).trim());\n i = index;\n } else {\n int stack = 1;\n int j = i + 1;\n while (stack > 0) {\n if (exp.charAt(j) == '(') stack++;\n else if (exp.charAt(j) == ')') stack--;\n j++;\n }\n tokens.add(exp.substring(i, j));\n i = j;\n }\n }\n }\n\n return tokens.toArray(new String[0]);\n }\n}\n", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"Output:14Explanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"Output:2Explanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"Output:5Explanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n String expression;\n int index;\n HashMap> scope; \n //variable may be assigned many times, we use the peek value \n \n public int evaluate(String expression) {\n this.expression=expression;\n index=0;\n scope=new HashMap<>();\n return evaluate();\n }\n \n private int evaluate(){\n \n if(expression.charAt(index)=='('){\n //this is an expression\n index++; //skip '('\n char begin=expression.charAt(index);\n int ret;\n if(begin=='l'){\n //let\n index += 4; //skip let and a blank space\n ArrayList vars=new ArrayList<>();\n while(true){\n if(!Character.isLowerCase(expression.charAt(index))){\n ret=evaluate();\n break;\n }\n String var=parseVar();\n if(expression.charAt(index)==')'){\n ret=scope.get(var).peek();\n break;\n }\n vars.add(var);\n index++;\n int e=evaluate();\n scope.putIfAbsent(var, new LinkedList<>());\n scope.get(var).push(e); //assign a new value\n index++;\n }\n for (String var : vars) {\n scope.get(var).pop(); // remove all values of this scope\n }\n\n } else if(begin=='a') {\n //add\n index += 4;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1+v2;\n } else {\n //multi\n index += 5;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1*v2;\n }\n index++; // skip ')'\n return ret;\n } else {\n //this is not a expression, this is an integer or a variable\n if(Character.isLowerCase(expression.charAt(index))){\n\t\t\t\t//this is a variable, the current value is peek value\n String var=parseVar();\n return scope.get(var).peek();\n } else {\n\t\t\t\t//this is an integer\n return parseInt();\n }\n }\n }\n \n //read an integer\n private int parseInt(){\n boolean negative=false;\n if(expression.charAt(index)=='-'){\n negative=true;\n index++;\n }\n int ret=0;\n while(Character.isDigit(expression.charAt(index))){\n ret*=10;\n ret+=expression.charAt(index)-'0';\n index++;\n }\n if(negative) return -ret;\n return ret;\n }\n \n //read a variable\n private String parseVar(){\n StringBuilder sb=new StringBuilder();\n char c=expression.charAt(index);\n while(c!=' ' && c!=')'){\n sb.append(c);\n c=expression.charAt(++index);\n }\n return sb.toString();\n }\n}\n", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string expression representing a Lisp-like expression to return the integer value of. The syntax for these expressions is given as follows. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.", + "(An integer could be positive or negative.)", + "A let expression takes the form \"(let v 1 e 1 v 2 e 2 ... v n e n expr)\" , where let is always the string \"let\" , then there are one or more pairs of alternating variables and expressions, meaning that the first variable v 1 is assigned the value of the expression e 1 , the second variable v 2 is assigned the value of the expression e 2 , and so on sequentially; and then the value of this let expression is the value of the expression expr .", + "An add expression takes the form \"(add e 1 e 2 )\" where add is always the string \"add\" , there are always two expressions e 1 , e 2 and the result is the addition of the evaluation of e 1 and the evaluation of e 2 .", + "A mult expression takes the form \"(mult e 1 e 2 )\" where mult is always the string \"mult\" , there are always two expressions e 1 , e 2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.", + "For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\" , \"let\" , and \"mult\" are protected and will never be used as variable names.", + "Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"Output:14Explanation:In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.", + "image": null + }, + { + "text": "Example 2: Input:expression = \"(let x 3 x 2 x)\"Output:2Explanation:Assignment in let statements is processed sequentially.", + "image": null + }, + { + "text": "Example 3: Input:expression = \"(let x 1 y 2 x (add x y) (add x y))\"Output:5Explanation:The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def evaluate(self, expression: str) -> int:\n loc = {}\n stack = []\n for i, x in enumerate(expression): \n if x == \"(\": stack.append(i)\n elif x == \")\": loc[stack.pop()] = i\n \n def fn(lo, hi, mp): \n \"\"\"Return value of given expression.\"\"\"\n if expression[lo] == \"(\": return fn(lo+1, hi-1, mp)\n i = lo\n vals = []\n while i < hi: \n if expression[i:i+3] in (\"let\", \"add\"): \n op = expression[i:i+3]\n i += 3\n elif expression[i:i+4] == \"mult\": \n op = \"mult\"\n i += 4\n elif expression[i].isalpha(): \n x = \"\"\n while i < hi and expression[i].isalnum(): \n x += expression[i]\n i += 1\n if op in (\"add\", \"mult\"): vals.append(mp[x])\n elif expression[i].isdigit() or expression[i] == \"-\": \n v = \"\"\n while i < hi and (expression[i].isdigit() or expression[i] == \"-\"): \n v += expression[i]\n i += 1\n if op == \"let\": mp[x] = int(v)\n else: vals.append(int(v))\n elif expression[i] == \"(\": \n v = fn(i+1, loc[i], mp.copy())\n i = loc[i] + 1\n if op == \"let\": mp[x] = v\n else: vals.append(v)\n else: i += 1\n if op == \"let\": return int(v)\n elif op == \"add\": return sum(vals)\n else: return reduce(mul, vals)\n \n return fn(0, len(expression), {})", + "title": "736. Parse Lisp Expression", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Return the result of evaluating a given boolean expression , represented as a string. An expression can either be: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"t\" , evaluating to True ;", + "\"f\" , evaluating to False ;", + "\"!(expr)\" , evaluating to the logical NOT of the inner expression expr ;", + "\"&(expr1,expr2,...)\" , evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ... ;", + "\"|(expr1,expr2,...)\" , evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ..." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"!(f)\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:expression = \"|(f,t)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:expression = \"&(t,f)\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.8%) | Memory: 40.90 MB (Top 99.4%)\n\nclass Solution {\n \n int pos = 0;\n \n public boolean parseBoolExpr(String s) {\n pos = 0;\n return solve(s, '-');\n }\n \n public boolean solve(String s, char prev_sign) {\n \n boolean res = s.charAt(pos) == 'f' ? false : true;\n char cur_sign = ' ';\n int flag_res_init = 0;\n while(pos < s.length()) {\n \n char cur_char = s.charAt(pos++);\n \n if(isExpr(cur_char)){\n res = eval(cur_char == 't'?true:false, res , prev_sign);\n }\n else if(isSign(cur_char)){\n cur_sign = cur_char;\n }\n else if(cur_char == '('){\n if(flag_res_init == 1 || prev_sign == '!')\n res = eval(solve(s, cur_sign), res, prev_sign);\n else {\n res = solve(s, cur_sign);\n flag_res_init = 1;\n }\n }\n else if(cur_char == ')'){\n return res;\n }\n \n }\n return res;\n }\n \n public boolean isExpr(char c){\n return (c == 'f' || c == 't');\n }\n \n public boolean isSign(char c){\n return (c == '!' || c == '&' || c == '|');\n }\n \n public boolean eval(boolean e1, boolean e2, char sign) {\n \n boolean res = false;\n if(sign == '!')\n res = !e1;\n \n else if(sign == '|')\n res = e1 | e2;\n \n else if(sign == '&')\n res = e1&e2;\n \n return res;\n }\n}", + "title": "1106. Parsing A Boolean Expression", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Return the result of evaluating a given boolean expression , represented as a string. An expression can either be: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"t\" , evaluating to True ;", + "\"f\" , evaluating to False ;", + "\"!(expr)\" , evaluating to the logical NOT of the inner expression expr ;", + "\"&(expr1,expr2,...)\" , evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ... ;", + "\"|(expr1,expr2,...)\" , evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ..." + ], + "examples": [ + { + "text": "Example 1: Input:expression = \"!(f)\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:expression = \"|(f,t)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:expression = \"&(t,f)\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n \n # expresssion map\n opMap = {\"!\" : \"!\", \"|\" : \"|\" , \"&\" : \"&\"}\n expMap = {\"t\" : True, \"f\" : False}\n expStack = []\n opStack = []\n ans = 0\n i = 0\n \n while i < len(expression):\n \n if expression[i] in opMap:\n opStack.append(opMap[expression[i]])\n \n elif expression[i] in expMap:\n expStack.append(expMap[expression[i]])\n \n elif expression[i] == \"(\":\n expStack.append(\"(\")\n \n # strat performing operations\n elif expression[i] == \")\":\n op = opStack.pop()\n ans = [] # evaluator arr\n \n # To Check\n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"outer WHILE\")\n \n # Performing serries of operation on exp inside a ()\n while expStack[-1] != \"(\":\n \n # To check \n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"OPerator :- \",op, \"INNER WHILE\")\n \n # Not single operation only\n if op == \"!\":\n ans.append(not expStack.pop())\n else:\n ans.append(expStack.pop())\n \n # Operation evaluation for more then 1 exp inside () for &, or\n while len(ans) > 1:\n # or\n if op == \"|\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 or exp2\n ans.append(res)\n # and\n elif op == \"&\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 and exp2\n ans.append(res)\n \n # poping \")\" and adding the res of operation done above\n expStack.pop() # poping \")\"\n expStack.append(ans[-1])\n \n # increment i \n i += 1\n \n return expStack[-1]\n \n \n\"\"\"\nTC : O(n * m) | n = len(expression), m = no of expression inside a prenthesis\nSc : O(n)\n\"\"\"\n", + "title": "1106. Parsing A Boolean Expression", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums and an integer pivot . Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every element less than pivot appears before every element greater than pivot .", + "Every element equal to pivot appears in between the elements less than and greater than pivot .", + "The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j .", + "More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,12,5,10,14,3,10], pivot = 10Output:[9,5,3,10,10,12,14]Explanation:The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,4,3,2], pivot = 2Output:[-3,2,4,3]Explanation:The element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 37.13%) | Memory: 169.4 MB (Top 17.70%)\n// Time complexity = 2n = O(n)\n// Space complexity = O(1), or O(n) if the result array is including in the complexity analysis.\n\nclass Solution {\n public int[] pivotArray(int[] nums, int pivot) {\n int[] result = new int[nums.length];\n int left = 0, right = nums.length - 1;\n\n for(int i = 0; i < nums.length; i++) {\n if(nums[i] < pivot) {\n result[left++] = nums[i];\n }\n if(nums[nums.length - 1 - i] > pivot) {\n result[right--] = nums[nums.length - 1 - i];\n }\n }\n\n while(left <= right) {\n result[left++] = pivot;\n result[right--] = pivot;\n }\n\n return result;\n }\n}", + "title": "2161. Partition Array According to Given Pivot", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums and an integer pivot . Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every element less than pivot appears before every element greater than pivot .", + "Every element equal to pivot appears in between the elements less than and greater than pivot .", + "The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j .", + "More formally, consider every p i , p j where p i is the new position of the i th element and p j is the new position of the j th element. For elements less than pivot , if i < j and nums[i] < pivot and nums[j] < pivot , then p i < p j . Similarly for elements greater than pivot , if i < j and nums[i] > pivot and nums[j] > pivot , then p i < p j ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [9,12,5,10,14,3,10], pivot = 10Output:[9,5,3,10,10,12,14]Explanation:The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-3,4,3,2], pivot = 2Output:[-3,2,4,3]Explanation:The element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n left=[]\n mid=[]\n right=[]\n for i in nums:\n if(i memo = new HashMap();\n //memo.put(\"0,0\", arr[0]);\n\n for(int i=0; i< arr.length; ++i){\n //without current element\n curr1 = prev + arr[i];\n\n //with current element, find max if p=0...k (since subarray can be longeth of at most k)\n int tempk = 0, half1 = 0, half2 = 0, temp= 0;\n for(int p=0; p<=k; ++p){\n half1 = findMaxSumWithKEle(arr, p , i);\n tempk = i-p;\n half2 = memo.get((\"0,\"+tempk)) == null ? 0: memo.get((\"0,\"+tempk));\n if(temp < half1 + half2){\n temp = half1 + half2;\n }\n }\n\n curr2 = temp;\n\n //find max between curr1 or curr2 - with current elemtn in the subarray or outside the subarray\n max = (curr1 < curr2) ? curr2:curr1;\n\n //add in memo\n String key= \"0,\" + i;\n memo.put(key, max);\n System.out.println(\"Max: \" + max + \" from [\" + key + \"]\");\n prev = max;\n }\n\n return max;\n }\n\n public static Integer findMaxSumWithKEle(int[] arr, int k, int end) {\n int max= 0;\n if(end > arr.length || end<0){\n return 0;\n }\n int c = 0;\n for(int i=end; i> (end -k ) && i>=0; --i){\n ++c;\n if(max < arr[i]){\n max = arr[i];\n }\n }\n return max *c;\n }\n}", + "title": "1043. Partition Array for Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , partition the array into (contiguous) subarrays of length at most k . After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^9", + "1 <= k <= arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,15,7,9,2,5,10], k = 3Output:84Explanation:arr becomes [15,15,15,9,10,10,10]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4Output:83", + "image": null + }, + { + "text": "Example 3: Input:arr = [1], k = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSumAfterPartitioning(self, nums: List[int], k: int) -> int:\n def get_max(start, end):\n return max(nums[start:end + 1]) * (end - start + 1)\n\n def dfs(start):\n if start == N: # base case, so in tabulation we go [N - 1]...[0], as [N] = 0\n return 0\n \n maxi = float(-inf)\n\t\t\t# you partition at every position up to start + k and repeat the same process for the next partition\n\t\t\t# e.g. 1 9 3, k = 2\n\t\t\t# 1|9|3 => with max in each partition: 1|9|3 = 13\n\t\t\t# 1|9 3 => with max in each partition: 1|9 9 = 19\n\t\t\t# 1 9|3 => with max in each partition: 9 9|3 = 21\n\t\t\t# get max_in_partition(start,end) + give_me_max_for_array(previous_partition_end + 1, N)\n\t\t\t# rec.relation = max(max_sum_in_partition[start, end] + dfs(end + 1)))\n for end in range(start, min(N, start + k)):\n maxi = max(maxi, get_max(start, end) + dfs(end + 1))\n return maxi\n \n N = len(nums)\n return dfs(0)\n", + "title": "1043. Partition Array for Maximum Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , partition it into two (contiguous) subarrays left and right so that: Return the length of left after such a partitioning . Test cases are generated such that partitioning exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every element in left is less than or equal to every element in right .", + "left and right are non-empty.", + "left has the smallest possible size." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,0,3,8,6]Output:3Explanation:left = [5,0,3], right = [8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,0,6,12]Output:4Explanation:left = [1,1,1,0], right = [6,12]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int partitionDisjoint(int[] nums) {\n int mts = nums[0]; // max till scan\n int mtp = nums[0]; // max till partition\n int idx = 0;\n \n for(int i=1; i int:\n prefix = [nums[0] for _ in range(len(nums))]\n suffix = [nums[-1] for _ in range(len(nums))]\n for i in range(1, len(nums)):\n prefix[i] = max(prefix[i-1], nums[i-1])\n for i in range(len(nums)-2, -1, -1):\n suffix[i] = min(suffix[i+1], nums[i+1])\n for i in range(0, len(nums)-1):\n if prefix[i] <= suffix[i]:\n return i+1\n", + "title": "915. Partition Array into Disjoint Intervals", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 5 * 10^4", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,2,1,-6,6,-7,9,1,2,0,1]Output:trueExplanation:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,-6,6,7,9,-1,2,0,1]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,3,6,5,-2,2,5,1,-9,4]Output:trueExplanation:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution { \n public boolean canThreePartsEqualSum(int[] arr) {\n int sum = 0;\n \n for (Integer no : arr) {\n sum += no;\n }\n if (sum % 3 != 0) {\n return false;\n }\n sum = sum / 3;\n int tempSum = 0;\n int count = 0;\n\n for (int i = 0; i < arr.length; i++) {\n tempSum += arr[i];\n if (tempSum == sum) {\n count++;\n tempSum = 0;\n }\n }\n\n return count >= 3;\n }\n}\n", + "title": "1013. Partition Array Into Three Parts With Equal Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , return true if we can partition the array into three non-empty parts with equal sums. Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= arr.length <= 5 * 10^4", + "-10^4 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,2,1,-6,6,-7,9,1,2,0,1]Output:trueExplanation:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,-6,6,7,9,-1,2,0,1]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [3,3,6,5,-2,2,5,1,-9,4]Output:trueExplanation:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 668 ms (Top 23.61%) | Memory: 21 MB (Top 37.82%)\nclass Solution:\n def canThreePartsEqualSum(self, arr: List[int]) -> bool:\n total = sum(arr)\n if total % 3 != 0:\n return False\n ave = total // 3\n stage = 0\n add = 0\n for i in arr[:-1]:\n add += i\n if add == ave:\n stage +=1\n add = 0\n if stage == 2:\n return True\n return False", + "title": "1013. Partition Array Into Three Parts With Equal Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums , put each element of nums into one of the two arrays. Return the minimum possible absolute difference . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 15", + "nums.length == 2 * n", + "-10^7 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,9,7,3]Output:2Explanation:One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.", + "image": "https://assets.leetcode.com/uploads/2021/10/02/ex1.png" + }, + { + "text": "Example 2: Input:nums = [-36,36]Output:72Explanation:One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,0,4,-2,-9]Output:0Explanation:One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.", + "image": "https://assets.leetcode.com/uploads/2021/10/02/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 893 ms (Top 61.90%) | Memory: 51.3 MB (Top 87.91%)\nclass Solution {\n public int minimumDifference(int[] nums) {\n int n = nums.length;\n int sum = 0;\n for (int i : nums) {\n sum += i;\n }\n\n TreeSet[] sets = new TreeSet[n/2+1];\n for (int i = 0; i < (1 << (n / 2)); ++i) {\n int curSum = 0;\n int m = 0;\n for (int j = 0; j < n / 2; ++j) {\n if ((i & (1<();\n sets[m].add(curSum);\n }\n\n int res = Integer.MAX_VALUE / 3;\n for (int i = 0; i < (1 << (n / 2)); ++i) {\n int curSum = 0;\n int m = 0;\n for (int j = 0; j < n / 2; ++j) {\n if ((i & (1< int:\n n = len(nums)//2\n left, right = nums[:n], nums[n:]\n lsum, rsum = sum(left), sum(right)\n \n ans = inf\n for i in range(n+1): \n vals = sorted(2*sum(combo)-lsum for combo in combinations(left, i))\n for combo in combinations(right, n-i): \n diff = 2*sum(combo) - rsum\n k = bisect_left(vals, -diff)\n if k: ans = min(ans, abs(vals[k-1] + diff))\n if k < len(vals): ans = min(ans, abs(vals[k] + diff))\n return ans \n", + "title": "2035. Partition Array Into Two Arrays to Minimize Sum Difference", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,2,5], k = 2Output:2Explanation:We can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 1Output:2Explanation:We can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,4,5], k = 0Output:3Explanation:We can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int c = 1, prev = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] - nums[prev] <= k) continue;\n c++; prev = i;\n }\n return c;\n }\n}\n", + "title": "2294. Partition Array Such That Maximum Difference Is K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an integer k . You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k . A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,6,1,2,5], k = 2Output:2Explanation:We can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 1Output:2Explanation:We can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,4,5], k = 0Output:3Explanation:We can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = 1\n\t\t# To keep track of starting element of each subsequence\n start = nums[0]\n \n for i in range(1, len(nums)):\n diff = nums[i] - start\n if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n ans += 1\n start = nums[i]\n \n return ans", + "title": "2294. Partition Array Such That Maximum Difference Is K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty array nums containing only positive integers , find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,11,5]Output:trueExplanation:The array can be partitioned as [1, 5, 5] and [11].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5]Output:falseExplanation:The array cannot be partitioned into equal sum subsets.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPartition(int[] nums) {\n int sum = 0;\n for(int i=0; i= 1? true : false;\n }\n public int helper(int[] nums, int sum, int i, int[][] dp){\n if(i==nums.length && sum==0){\n return 1;\n }\n if(i==nums.length){\n return 0;\n }\n if(sum < 0){\n return 0;\n }\n if(dp[i][sum] != -1){\n return dp[i][sum];\n }\n if(sum bool:\n dp, s = set([0]), sum(nums)\n if s&1:\n return False\n for num in nums:\n for curr in range(s>>1, num-1, -1):\n if curr not in dp and curr-num in dp:\n if curr == s>>1:\n return True\n dp.add(curr)\n return False\n", + "title": "416. Partition Equal Subset Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababcbacadefegdehijhklij\"Output:[9,7,8]Explanation:The partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.", + "image": null + }, + { + "text": "Example 2: Input:s = \"eccbbbbdec\"Output:[10]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 5.9%) | Memory: 43.57 MB (Top 5.0%)\n\nclass Solution {\n public List partitionLabels(String s) {\n \n Listlr=new ArrayList<>();\n\n HashMapmp=new HashMap<>();\n\n int count=0;\n\n for(int i=0;i List[int]:\n d = defaultdict(list)\n for i, char in enumerate(s):\n d[char].append(i)\n nums = []\n \n for v in d.values():\n nums.append([v[0], v[-1]])\n\n start = nums[0][0]\n maxIndex = nums[0][1]\n ans = []\n for i in range(1, len(nums)):\n if nums[i][0] <= maxIndex:\n maxIndex = max(maxIndex, nums[i][1])\n else:\n ans.append(maxIndex - start + 1)\n start = nums[i][0]\n maxIndex = nums[i][1]\n ans.append(maxIndex - start + 1)\n # print(ans)\n return ans\n", + "title": "763. Partition Labels", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3Output:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode left = new ListNode(0);\n ListNode right = new ListNode(0);\n \n ListNode leftTail = left;\n ListNode rightTail = right;\n \n while(head != null){\n if(head.val < x){\n leftTail.next = head;\n leftTail = leftTail.next;\n }\n else{\n rightTail.next = head;\n rightTail = rightTail.next;\n }\n head = head.next;\n }\n \n leftTail.next = right.next;\n rightTail.next = null;\n \n return left.next;\n }\n}\n", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3Output:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 53 ms (Top 53.47%) | Memory: 13.8 MB (Top 76.51%)\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n lessthan = []\n greateql = []\n\n while head:\n if head.val < x:\n lessthan.append(head.val)\n else:\n greateql.append(head.val)\n head = head.next\n\n h = res = ListNode()\n\n for i in range(len(lessthan)):\n res.next = ListNode(lessthan[i])\n res = res.next\n for i in range(len(greateql)):\n res.next = ListNode(greateql[i])\n res = res.next\n\n return h.next", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "1 <= nums[i] <= 10^4", + "The frequency of each element is in the range [1, 4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,3,5,2,1], k = 4Output:trueExplanation:It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 277 ms (Top 51.4%) | Memory: 43.53 MB (Top 23.8%)\n\nclass Solution {\n private final List> allSubsets = new ArrayList<>();\n public boolean canPartitionKSubsets(int[] nums, int k) {\n int sum = Arrays.stream(nums).sum();\n if(sum % k != 0) return false;\n getAllSubsets(nums.length, sum / k, new HashSet<>(), nums, false);\n return allSubsets.size() >= k && canPartition(allSubsets.size(), k, nums.length, new HashSet<>());\n }\n\n private boolean canPartition(int n, int k, int size, Set current) {\n if(k == 0 && current.size() == size) return true;\n if(n == 0 || k < 0) return false;\n boolean addSet = false;\n if(allUnique(current, allSubsets.get(n-1))) {\n current.addAll(allSubsets.get(n - 1));\n addSet = canPartition(n - 1, k - 1, size, current);\n current.removeAll(allSubsets.get(n - 1));\n }\n return addSet || canPartition(n - 1, k, size, current);\n }\n\n private void getAllSubsets(int n, int targetSum, Set subsets, int[] nums, boolean lol) {\n if(targetSum == 0) {\n allSubsets.add(new HashSet<>(subsets));\n return;\n }\n if (n == 0 || targetSum < 0) return;\n subsets.add(n-1);\n getAllSubsets(n-1, targetSum - nums[n-1], subsets, nums, true);\n subsets.remove(n-1);\n getAllSubsets(n-1, targetSum, subsets, nums, false);\n }\n \n private boolean allUnique(Set set1, Set set2) {\n for (Integer num: set1) if(set2.contains(num)) return false;\n return true;\n }\n}", + "title": "698. Partition to K Equal Sum Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 16", + "1 <= nums[i] <= 10^4", + "The frequency of each element is in the range [1, 4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,3,5,2,1], k = 4Output:trueExplanation:It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], k = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 165 ms (Top 74.37%) | Memory: 13.8 MB (Top 95.72%)\nclass Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n def dfs(idx,curr,cnt,limit):\n if cnt == k:\n return True\n if curr ==limit:\n return dfs(0,0,cnt+1,limit)\n\n i = idx\n while i < len(nums):\n if visited[i] or nums[i]+curr > limit:\n i += 1\n continue\n visited[i] = True\n if dfs(i+1,curr+nums[i],cnt,limit):\n return True\n visited[i] = False\n\n while i+1 < len(nums) and nums[i] == nums[i+1]: #pruning1\n i += 1\n if curr == 0 or curr + nums[i] == limit: #pruning2\n return False\n i += 1\n return False\n\n if len(nums) < k or sum(nums) % k:\n return False\n numSum = sum(nums)\n\n for i in range(len(nums)):\n if nums[i] > numSum//k:\n return False\n\n visited = [False]*len(nums)\n return dfs(0,0,0,numSum//k)", + "title": "698. Partition to K Equal Sum Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary , while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n.length <= 10^5", + "n consists of only digits.", + "n does not contain any leading zeros and represents a positive integer." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"32\"Output:3Explanation:10 + 11 + 11 = 32", + "image": null + }, + { + "text": "Example 2: Input:n = \"82734\"Output:8", + "image": null + }, + { + "text": "Example 3: Input:n = \"27346209830709182346\"Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPartitions(String n) {\n int res = 0;\n for (int i = 0; i < n.length(); i++) {\n res = Math.max(res, n.charAt(i) - '0');\n }\n return res;\n }\n}\n", + "title": "1689. Partitioning Into Minimum Number Of Deci-Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary , while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n.length <= 10^5", + "n consists of only digits.", + "n does not contain any leading zeros and represents a positive integer." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"32\"Output:3Explanation:10 + 11 + 11 = 32", + "image": null + }, + { + "text": "Example 2: Input:n = \"82734\"Output:8", + "image": null + }, + { + "text": "Example 3: Input:n = \"27346209830709182346\"Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 109 ms (Top 63.86%) | Memory: 14.9 MB (Top 22.11%)\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return int(max(n))", + "title": "1689. Partitioning Into Minimum Number Of Deci-Binary Numbers", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5Output:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> generate(int numRows) {\n List> list = new LinkedList();\n list.add(Arrays.asList(1));\n if(numRows == 1) return list;\n list.add(Arrays.asList(1,1));\n \n for(int i = 1; i < numRows - 1; i++) {\n List temp = list.get(i);\n List temp2 = new ArrayList();\n temp2.add(1);\n for(int j = 0; j < temp.size() - 1; j++) {\n temp2.add(temp.get(j) + temp.get(j+1));\n }\n temp2.add(1);\n list.add(temp2);\n }\n \n return list;\n }\n}\n", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5Output:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 1:\n return [[1]]\n if numRows == 2:\n return [[1], [1, 1]]\n ans = [[1], [1, 1]]\n for x in range(1, numRows - 1):\n tmp = [1]\n for k in range(len(ans[x]) - 1):\n tmp.append(ans[x][k] + ans[x][k + 1])\n tmp.append(1)\n ans.append(tmp)\n return ans\n", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3Output:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1Output:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List getRow(int rowIndex) {\n List> out = new ArrayList<>();\n for(int i = 0; i<=rowIndex; i++){\n Listin = new ArrayList<>(i+1);\n for(int j = 0 ; j<= i; j++){\n if(j == 0 || j == i){\n in.add(1);\n }\n else{\n in.add(out.get(i-1).get(j-1) + out.get(i-1).get(j));\n }\n \n }\n out.add(in);\n }\n return out.get(rowIndex);\n }\n}\n", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3Output:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1Output:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n # base case\n # we know that there exist two base case one which is for zero input\n # One when we have to exit our recursive loop \n if rowIndex == 0:\n return [1]\n if rowIndex == 1:\n return [1,1]\n #recurance relation or prev call\n prev_prob = self.getRow(rowIndex-1)\n # post processing on data \n # if someone has given us prev_Row what operation we can perform to get current_Row\n return [1]+[prev_prob[i]+prev_prob[i-1] for i in range(1,len(prev_prob))]+[1]\n", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6Output:1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20Output:2\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPatches(int[] nums, int n) {\n long sum = 0;\n int count = 0;\n for (int x : nums) {\n if (sum >= n) break;\n while (sum+1 < x && sum < n) { \n ++count;\n sum += sum+1;\n }\n sum += x;\n }\n while (sum < n) {\n sum += sum+1;\n ++count;\n }\n return count;\n }\n}\n", + "title": "330. Patching Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6Output:1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20Output:2\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n\t#pre-process for convenience\n nums.append(n+1)\n t=1\n sum=1\n rs=0\n if nums[0]!=1:\n nums=[1]+nums\n rs+=1\n# the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go form left to right to cover upto n\n while sum visited = new HashSet<>();\n int x = 0, y = 0;\n visited.add(x + \",\" + y);\n for (char c : path.toCharArray()) {\n if (c == 'N') y++;\n else if (c == 'S') y--;\n else if (c == 'E') x++;\n else x--;\n if (visited.contains(x + \",\" + y)) return true;\n visited.add(x + \",\" + y);\n }\n return false; \n }\n}\n", + "title": "1496. Path Crossing", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string path , where path[i] = 'N' , 'S' , 'E' or 'W' , each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path . Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited . Return false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= path.length <= 10^4", + "path[i] is either 'N' , 'S' , 'E' , or 'W' ." + ], + "examples": [ + { + "text": "Example 1: Input:path = \"NES\"Output:falseExplanation:Notice that the path doesn't cross any point more than once.", + "image": "https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123929-pm.png" + }, + { + "text": "Example 2: Input:path = \"NESWW\"Output:trueExplanation:Notice that the path visits the origin twice.", + "image": "https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123843-pm.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 55 ms (Top 32.81%) | Memory: 14.1 MB (Top 28.49%)\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n c = set()\n x,y = 0,0\n c.add((x,y))\n for i in path:\n if i == 'N':\n y+=1\n elif i == 'E':\n x+=1\n elif i == 'W':\n x-=1\n else:\n y-=1\n if (x,y) in c:\n return True\n else:\n c.add((x,y))\n return False", + "title": "1496. Path Crossing", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/06/24/tree.png" + ], + "constraints": [ + "1 <= label <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:label = 14Output:[1,3,4,14]", + "image": null + }, + { + "text": "Example 2: Input:label = 26Output:[1,2,6,10,26]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n \n \n public List pathInZigZagTree(int label) \n {\n int level, upper, parent, i = label;\n double min, max;\n List ans = new ArrayList ();\n \n ans.add(i);\n \n while( i> 1)\n {\n level = (int)(Math.log(i) / Math.log(2));\n upper = level -1;\n min = Math.pow(2.0, upper);\n max = Math.pow(2.0, level) - 1;\n parent = (int)(min + max) - i/2; \n \n ans.add(0, parent);\n i = parent;\n }\n \n return ans;\n \n \n }\n}\n", + "title": "1104. Path In Zigzag Labelled Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/06/24/tree.png" + ], + "constraints": [ + "1 <= label <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:label = 14Output:[1,3,4,14]", + "image": null + }, + { + "text": "Example 2: Input:label = 26Output:[1,2,6,10,26]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 88.8%) | Memory: 16.50 MB (Top 52.0%)\n\nclass Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n \n x = label\n mask = 0 \n while x > 1:\n x >>= 1\n mask <<= 1\n mask |= 1\n \n x = label\n res = deque()\n while x:\n res.appendleft(x)\n x >>= 1\n mask >>= 1\n x ^= mask\n return res\n", + "title": "1104. Path In Zigzag Labelled Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output:trueExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5Output:falseExplanation:There two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0Output:falseExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if(root == null) return false;\n \n if(root.left == null && root.right == null) return root.val == targetSum;\n \n return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val);\n }\n}\n", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output:trueExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5Output:falseExplanation:There two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0Output:falseExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def hasPathSum(self, root, targetSum):\n \"\"\"\n :type root: TreeNode\n :type targetSum: int\n :rtype: bool\n \"\"\"\n if not root: return False\n targetSum -= root.val\n if not root.left and not root.right:\n return not targetSum\n return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)\n", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return all root-to-leaf paths where the sum of the node values in the path equals targetSum . Each path should be returned as a list of the node values , not node references . A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output:[[5,4,11,2],[5,8,4,5]]Explanation:There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5Output:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2], targetSum = 0Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n public List> pathSum(TreeNode root, int targetSum) \n {\n List> ans = new ArrayList<>();\n pathSum(root, targetSum, new ArrayList<>(), ans);\n return ans;\n }\n \n public void pathSum(TreeNode root, int targetSum, List path, List> ans)\n {\n if(root == null)\n return;\n path.add(root.val);\n if(root.left == null && root.right == null && targetSum == root.val)//leaf node that completes path\n {\n ans.add(new ArrayList(path));// we use new ArrayList because if we don't the originaly List is added which is mutable, if we add a copy that's not mutable.\n }\n else\n {\n pathSum(root.left, targetSum-root.val, path, ans);\n pathSum(root.right, targetSum-root.val, path, ans);\n }\n path.remove(path.size()-1); //removal of redundant nodes\n }\n}\n", + "title": "113. Path Sum II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return all root-to-leaf paths where the sum of the node values in the path equals targetSum . Each path should be returned as a list of the node values , not node references . A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output:[[5,4,11,2],[5,8,4,5]]Explanation:There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5Output:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2], targetSum = 0Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\n res = []\n def dfs(v, path, pathsum):\n if not v:\n return\n path.append(v.val)\n pathsum += v.val\n if not v.left and not v.right and pathsum == targetSum:\n res.append(path[:])\n dfs(v.left, path, pathsum)\n dfs(v.right, path, pathsum)\n path.pop()\n dfs(root, [], 0)\n return res", + "title": "113. Path Sum II", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8Output:3Explanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 66.25%) | Memory: 45 MB (Top 29.77%)\nclass Solution {\n public int pathSum(TreeNode root, int targetSum) {\n HashMap hm = new HashMap<>();\n //hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum\n\n int res = solve(hm, root, targetSum, 0);\n\n return res;\n }\n\n public int solve(HashMap hm, TreeNode node, long tgt, long c_sum) {\n\n if(node == null)\n return 0;\n\n c_sum += node.val;\n\n int res = 0;\n\n if(c_sum == tgt) //--> either this condition or the above commented condition.\n res++;\n\n if(hm.containsKey(c_sum-tgt)){\n res += hm.get(c_sum-tgt);\n }\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)+1);\n\n int left = solve(hm, node.left, tgt, c_sum);\n int right = solve(hm, node.right, tgt, c_sum);\n\n res += (left+right);\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)-1); //remove the calculated cumulative sum\n\n return res;\n\n }\n\n}\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8Output:3Explanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:\n def util(node: TreeNode, sum_array) -> int:\n t = [e - node.val for e in sum_array]\n zeroes = t.count(0)\n if node.left is None and node.right is None:\n return zeroes\n ansl, ansr = 0, 0\n if node.left:\n ansl = util(node.left, t + [targetSum])\n if node.right:\n ansr = util(node.right, t + [targetSum])\n return ansl + ansr + zeroes\n\n return util(root, [targetSum]) if root is not None else 0\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a gold mine grid of size m x n , each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every time you are located in a cell you will collect all the gold in that cell.", + "From your position, you can walk one step to the left, right, up, or down.", + "You can't visit the same cell more than once.", + "Never visit a cell with 0 gold.", + "You can start and stop collecting gold from any position in the grid that has some gold." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,6,0],[5,8,7],[0,9,0]]Output:24Explanation:[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]Output:28Explanation:[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 55 ms (Top 88.6%) | Memory: 39.51 MB (Top 97.9%)\n\nclass Solution {\n int r = 0;\n int c = 0;\n int max = 0;\n public int getMaximumGold(int[][] grid) {\n r = grid.length;\n c = grid[0].length;\n for(int i = 0; i < r; i++) {\n for(int j = 0; j < c; j++) {\n if(grid[i][j] != 0) {\n dfs(grid, i, j, 0);\n }\n }\n }\n return max;\n }\n \n private void dfs(int[][] grid, int i, int j, int cur) {\n if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] == 0) {\n max = Math.max(max, cur);\n return;\n }\n int val = grid[i][j];\n grid[i][j] = 0;\n dfs(grid, i + 1, j, cur + val);\n dfs(grid, i - 1, j, cur + val);\n dfs(grid, i, j + 1, cur + val);\n dfs(grid, i, j - 1, cur + val);\n grid[i][j] = val;\n }\n}", + "title": "1219. Path with Maximum Gold", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a gold mine grid of size m x n , each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Every time you are located in a cell you will collect all the gold in that cell.", + "From your position, you can walk one step to the left, right, up, or down.", + "You can't visit the same cell more than once.", + "Never visit a cell with 0 gold.", + "You can start and stop collecting gold from any position in the grid that has some gold." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,6,0],[5,8,7],[0,9,0]]Output:24Explanation:[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]Output:28Explanation:[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1480 ms (Top 97.21%) | Memory: 14.1 MB (Top 13.08%)\nclass Solution:\n def getMaximumGold(self, grid):\n answer = [0]\n\n def visit(visited, i, j, gold_sum):\n val = grid[i][j]\n if val == 0 or (i,j) in visited:\n answer[0] = max(answer[0], gold_sum)\n return\n\n gold_sum_new = gold_sum + val\n visited_new = visited.union({(i,j)})\n\n if i > 0:\n visit(visited_new, i-1, j, gold_sum_new)\n\n if j < len(grid[i]) - 1:\n visit(visited_new, i, j+1, gold_sum_new)\n\n if i < len(grid) - 1:\n visit(visited_new, i+1, j, gold_sum_new)\n if j > 0:\n visit(visited_new, i, j-1, gold_sum_new)\n #choosing the starting points\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] != 0:\n count = 0\n\n try:\n if grid[i-1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j+1] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i+1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j-1] != 0:\n count += 1\n except:\n pass\n\n if count < 3:\n visit(set(),i,j,0)\n\n return answer[0]\n", + "title": "1219. Path with Maximum Gold", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i] . Given two nodes start and end , find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end , return 0 . Your answer will be accepted if it differs from the correct answer by at most 1e-5 . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png" + ], + "constraints": [ + "2 <= n <= 10^4", + "0 <= start, end < n", + "start != end", + "0 <= a, b < n", + "a != b", + "0 <= succProb.length == edges.length <= 2*10^4", + "0 <= succProb[i] <= 1", + "There is at most one edge between every two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2Output:0.25000Explanation:There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2Output:0.30000", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2Output:0.00000Explanation:There is no path between 0 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 82 ms (Top 52.25%) | Memory: 75.8 MB (Top 66.61%)\nclass Pair{\n int to;\n double prob;\n public Pair(int to,double prob){\n this.to=to;\n this.prob=prob;\n }\n}\nclass Solution {\n public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {\n List> adj=new ArrayList<>();\n for(int i=0;i());\n }\n for(int i=0;i pq=new PriorityQueue<>((p1,p2)->Double.compare(p2.prob,p1.prob));\n pq.offer(new Pair(start,1.0));\n while(!pq.isEmpty()){\n Pair curr=pq.poll();\n for(Pair x:adj.get(curr.to)){\n if(((curr.prob)*(x.prob))>probs[x.to]){\n probs[x.to]=((curr.prob)*(x.prob));\n pq.offer(new Pair(x.to,probs[x.to]));\n\n }\n else{\n continue;\n }\n }\n }\n return probs[end];\n }\n}", + "title": "1514. Path with Maximum Probability", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i] . Given two nodes start and end , find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end , return 0 . Your answer will be accepted if it differs from the correct answer by at most 1e-5 . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png", + "https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png" + ], + "constraints": [ + "2 <= n <= 10^4", + "0 <= start, end < n", + "start != end", + "0 <= a, b < n", + "a != b", + "0 <= succProb.length == edges.length <= 2*10^4", + "0 <= succProb[i] <= 1", + "There is at most one edge between every two nodes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2Output:0.25000Explanation:There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.", + "image": null + }, + { + "text": "Example 2: Input:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2Output:0.30000", + "image": null + }, + { + "text": "Example 3: Input:n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2Output:0.00000Explanation:There is no path between 0 and 2.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 755 ms (Top 91.19%) | Memory: 25.4 MB (Top 98.78%)\nclass Solution(object):\n def maxProbability(self, n, edges, succProb, start, end):\n adj=[[] for i in range(n)]\n dist=[sys.maxsize for i in range(n)]\n heap=[]\n c=0\n for i,j in edges:\n adj[i].append([j,succProb[c]])\n adj[j].append([i,succProb[c]])\n c+=1\n heapq.heappush(heap,[-1.0,start])\n dist[start]=1\n while(heap):\n prob,u=heapq.heappop(heap)\n for v,w in adj[u]:\n if(dist[v]>-abs(w*prob)):\n dist[v]=-abs(w*prob)\n heapq.heappush(heap,[dist[v],v])\n if(sys.maxsize==dist[end]):\n return 0.00000\n else:\n return -dist[end]", + "title": "1514. Path with Maximum Probability", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a hiker preparing for an upcoming hike. You are given heights , a 2D array of size rows x columns , where heights[row][col] represents the height of cell (row, col) . You are situated in the top-left cell, (0, 0) , and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed ). You can move up , down , left , or right , and you wish to find a route that requires the minimum effort . A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/04/ex2.png" + ], + "constraints": [ + "rows == heights.length", + "columns == heights[i].length", + "1 <= rows, columns <= 100", + "1 <= heights[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [[1,2,2],[3,8,2],[5,3,5]]Output:2Explanation:The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.", + "image": null + }, + { + "text": "Example 2: Input:heights = [[1,2,3],[3,8,4],[5,3,5]]Output:1Explanation:The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].", + "image": null + }, + { + "text": "Example 3: Input:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]Output:0Explanation:This route does not require any effort.", + "image": "https://assets.leetcode.com/uploads/2020/10/04/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 36 ms (Top 97.2%) | Memory: 44.02 MB (Top 69.2%)\n\nclass Tuple {\n\n int distance;\n\n int row;\n\n int col;\n\n \n\n Tuple(int distance, int row, int col) {\n\n this.distance = distance;\n\n this.row = row;\n\n this.col = col;\n\n }\n\n}\n\n\n\nclass Solution {\n\n public int minimumEffortPath(int[][] heights) {\n\n // Create a min heap based on the distance\n\n PriorityQueue minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);\n\n \n\n int rows = heights.length;\n\n int cols = heights[0].length;\n\n \n\n // Create a 2D array to store the minimum effort to reach each cell\n\n int effort[][] = new int[rows][cols];\n\n \n\n // Initialize all efforts to maximum initially\n\n for (int i = 0; i < rows; i++) {\n\n Arrays.fill(effort[i], Integer.MAX_VALUE);\n\n }\n\n \n\n effort[0][0] = 0; // Initial effort at the starting cell\n\n \n\n // Add the starting cell to the min heap\n\n minHeap.add(new Tuple(0, 0, 0));\n\n \n\n // Arrays to represent row and column changes for 4 directions\n\n int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left\n\n int dc[] = {0, 1, 0, -1};\n\n \n\n while (!minHeap.isEmpty()) {\n\n Tuple current = minHeap.poll(); // Get the cell with the minimum effort\n\n int distance = current.distance;\n\n int row = current.row;\n\n int col = current.col;\n\n \n\n if (row == rows - 1 && col == cols - 1) {\n\n return distance; // If reached the destination, return the effort\n\n }\n\n \n\n // Explore each of the 4 possible directions\n\n for (int i = 0; i < 4; i++) {\n\n int newRow = row + dr[i]; // Calculate new row index\n\n int newCol = col + dc[i]; // Calculate new column index\n\n \n\n // Check if the new cell is within bounds\n\n if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\n\n \n\n // Calculate the new effort based on the maximum of height difference and current effort\n\n int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);\n\n \n\n // If the new effort is less than the stored effort for the cell, update and add to heap\n\n if (newEffort < effort[newRow][newCol]) {\n\n effort[newRow][newCol] = newEffort;\n\n minHeap.add(new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration\n\n }\n\n }\n\n }\n\n }\n\n return 0; // This value should be replaced with the actual minimum effort\n\n }\n\n}\n\n", + "title": "1631. Path With Minimum Effort", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are a hiker preparing for an upcoming hike. You are given heights , a 2D array of size rows x columns , where heights[row][col] represents the height of cell (row, col) . You are situated in the top-left cell, (0, 0) , and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed ). You can move up , down , left , or right , and you wish to find a route that requires the minimum effort . A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/04/ex1.png", + "https://assets.leetcode.com/uploads/2020/10/04/ex2.png" + ], + "constraints": [ + "rows == heights.length", + "columns == heights[i].length", + "1 <= rows, columns <= 100", + "1 <= heights[i][j] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [[1,2,2],[3,8,2],[5,3,5]]Output:2Explanation:The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.", + "image": null + }, + { + "text": "Example 2: Input:heights = [[1,2,3],[3,8,4],[5,3,5]]Output:1Explanation:The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].", + "image": null + }, + { + "text": "Example 3: Input:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]Output:0Explanation:This route does not require any effort.", + "image": "https://assets.leetcode.com/uploads/2020/10/04/ex3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 1804 ms (Top 36.30%) | Memory: 15.4 MB (Top 76.73%)\nclass Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n di = (0, 1, 0, -1)\n dj = (1, 0, -1, 0)\n m, n = len(heights), len(heights[0])\n visited = [[False] * n for _ in range(m)]\n h = [(0, 0, 0)]\n while h:\n effort, i, j = heappop(h)\n if visited[i][j]:\n continue\n visited[i][j] = True\n if i + 1 == m and j + 1 == n:\n return effort ## have reached the (m-1, n-1) cell\n for k in range(4):\n ii, jj = i + di[k], j + dj[k]\n if 0 <= ii < m and 0 <= jj < n and not visited[ii][jj]:\n neffort = max(effort, abs(heights[i][j] - heights[ii][jj]))\n heappush(h, (neffort, ii, jj))\n return ## cell (m-1, n-1) not reachable, should never happen", + "title": "1631. Path With Minimum Effort", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An array arr a mountain if the following properties hold: Given a mountain array arr , return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] . You must solve it in O(log(arr.length)) time complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,0]Output:1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,0]Output:1", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,10,5,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 59.7 MB (Top 83.58%)\nclass Solution {\npublic int peakIndexInMountainArray(int[] arr) {\n\n int start = 0;\n int end = arr.length - 1;\n\n while( start < end){\n int mid = start + (end - start)/2;\n // if mid < mid next\n if(arr[mid] < arr[mid + 1]){\n start = mid + 1;\n }\n // otherwise it can either peak element or greater element\n else{\n end = mid;\n }\n }\n return start; // or we can return end also, bcz both will be on same value at the time, that's why loop breaks here.\n }\n}", + "title": "852. Peak Index in a Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An array arr a mountain if the following properties hold: Given a mountain array arr , return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] . You must solve it in O(log(arr.length)) time complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,0]Output:1", + "image": null + }, + { + "text": "Example 2: Input:arr = [0,2,1,0]Output:1", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,10,5,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n beg = 0\n end = len(arr)-1\n \n while beg <= end:\n mid = (beg+end)//2\n if arr[mid] < arr[mid+1]:\n beg = mid +1\n elif arr[mid] > arr[mid+1]:\n end = mid -1\n return beg\n", + "title": "852. Peak Index in a Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: Note: Each language may have a different implementation of the constructor and Iterator , but they all support the int next() and boolean hasNext() functions. Example 1:", + "description_images": [], + "constraints": [ + "PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator .", + "int next() Returns the next element in the array and moves the pointer to the next element.", + "boolean hasNext() Returns true if there are still elements in the array.", + "int peek() Returns the next element in the array without moving the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 2, 2, 3, false]ExplanationPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Java Iterator interface reference:\n// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator {\n Queue q;\n\tpublic PeekingIterator(Iterator iterator) {\n\t // initialize any member here.\n\t q= new LinkedList<>();\n while(iterator.hasNext())\n q.add(iterator.next()); \n\t}\n\t\n // Returns the next element in the iteration without advancing the iterator.\n\tpublic Integer peek() {\n return q.peek();\n\t}\n\t\n\t// hasNext() and next() should behave the same as in the Iterator interface.\n\t// Override them if needed.\n\t@Override\n\tpublic Integer next() {\n\t return q.remove();\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t return q.size()!=0;\n\t}\n}\n", + "title": "284. Peeking Iterator", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations. Implement the PeekingIterator class: Note: Each language may have a different implementation of the constructor and Iterator , but they all support the int next() and boolean hasNext() functions. Example 1:", + "description_images": [], + "constraints": [ + "PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator .", + "int next() Returns the next element in the array and moves the pointer to the next element.", + "boolean hasNext() Returns true if there are still elements in the array.", + "int peek() Returns the next element in the array without moving the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n[[[1, 2, 3]], [], [], [], [], []]Output[null, 1, 2, 2, 3, false]ExplanationPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 44 ms (Top 25.31%) | Memory: 17.60 MB (Top 8.9%)\n\nclass PeekingIterator:\n def __init__(self, iterator):\n self.iterator = iterator\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n \n def peek(self):\n return self.buffer\n \n def next(self):\n tmp = self.buffer\n self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n return tmp\n \n def hasNext(self):\n return self.buffer != None\n", + "title": "284. Peeking Iterator", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person ( indexed from 0 ). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies . You must return the indices in increasing order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= favoriteCompanies.length <= 100", + "1 <= favoriteCompanies[i].length <= 500", + "1 <= favoriteCompanies[i][j].length <= 20", + "All strings in favoriteCompanies[i] are distinct .", + "All lists of favorite companies are distinct , that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].", + "All strings consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]Output:[0,1,4]Explanation:Person with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].", + "image": null + }, + { + "text": "Example 2: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]Output:[0,1]Explanation:In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].", + "image": null + }, + { + "text": "Example 3: Input:favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]Output:[0,1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 362 ms (Top 62.96%) | Memory: 52.4 MB (Top 92.59%)\nclass Solution {\n public List peopleIndexes(List> favoriteCompanies) {\n Set[] fav = new Set[favoriteCompanies.size()];\n Set set = new HashSet<>();\n for (int i = 0; i < favoriteCompanies.size(); i++) {\n set.add(i);\n fav[i] = new HashSet<>(favoriteCompanies.get(i));\n }\n for (int i = 1; i < favoriteCompanies.size(); i++) {\n if (!set.contains(i)) continue;\n for (int j = 0; j < i; j++) {\n if (!set.contains(j)) continue;\n if (isSubSet(fav[j], fav[i])) set.remove(j);\n if (isSubSet(fav[i], fav[j])) set.remove(i);\n }\n }\n List ans = new ArrayList<>(set);\n Collections.sort(ans);\n return ans;\n }\n\n private boolean isSubSet(Set child, Set parent) {\n if (child.size() > parent.size()) return false;\n return parent.containsAll(child);\n }\n}", + "title": "1452. People Whose List of Favorite Companies Is Not a Subset of Another List", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person ( indexed from 0 ). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies . You must return the indices in increasing order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= favoriteCompanies.length <= 100", + "1 <= favoriteCompanies[i].length <= 500", + "1 <= favoriteCompanies[i][j].length <= 20", + "All strings in favoriteCompanies[i] are distinct .", + "All lists of favorite companies are distinct , that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].", + "All strings consist of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]Output:[0,1,4]Explanation:Person with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].", + "image": null + }, + { + "text": "Example 2: Input:favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]Output:[0,1]Explanation:In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].", + "image": null + }, + { + "text": "Example 3: Input:favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]Output:[0,1,2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n \n F = favoriteCompanies\n ans = [] \n \n seen = set() \n \n for i in range(len(F)):\n for j in range(i+1,len(F)):\n st1 = set(F[i])\n st2 = set(F[j])\n if st1.intersection(st2) == st1: seen.add(i)\n if st2.intersection(st1) == st2: seen.add(j) \n\n ans = []\n for i in range(len(F)):\n if i in seen: continue \n ans.append(i) \n \n return ans", + "title": "1452. People Whose List of Favorite Companies Is Not a Subset of Another List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s and a character letter , return the percentage of characters in s that equal letter rounded down to the nearest whole percent. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of lowercase English letters.", + "letter is a lowercase English letter." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"foobar\", letter = \"o\"Output:33Explanation:The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.", + "image": null + }, + { + "text": "Example 2: Input:s = \"jjjj\", letter = \"k\"Output:0Explanation:The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.55 MB (Top 34.5%)\n\nclass Solution {\n public int percentageLetter(String str, char letter) {\n int count=0;\n int n=str.length();\n for(int i=0;i int:\n return (s.count(letter)*100)//len(s)\n", + "title": "2278. Percentage of Letter in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A perfect number is a positive integer that is equal to the sum of its positive divisors , excluding the number itself. A divisor of an integer x is an integer that can divide x evenly. Given an integer n , return true if n is a perfect number, otherwise return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:num = 28Output:trueExplanation:28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.", + "image": null + }, + { + "text": "Example 2: Input:num = 7Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 51.95%) | Memory: 40.9 MB (Top 44.38%)\nclass Solution {\n public boolean checkPerfectNumber(int num) {\n if(num==1)\n return false;\n\n int sum = 1;\n for(int i=2; i bool:\n sum = 0\n root = num**0.5 \n if num ==1:\n return False\n for i in range(2,int(root)+1):\n if num%i== 0:\n sum +=(num//i)+i\n return sum+1 == num\n", + "title": "507. Perfect Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array rectangles where rectangles[i] = [x i , y i , a i , b i ] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (x i , y i ) and the top-right point of it is (a i , b i ) . Return true if all the rectangles together form an exact cover of a rectangular region . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 2 * 10^4", + "rectangles[i].length == 4", + "-10^5 <= x i , y i , a i , b i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]Output:trueExplanation:All 5 rectangles together form an exact cover of a rectangular region.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg" + }, + { + "text": "Example 2: Input:rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]Output:falseExplanation:Because there is a gap between the two rectangular regions.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg" + }, + { + "text": "Example 3: Input:rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]Output:falseExplanation:Because two of the rectangles overlap with each other.", + "image": "https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 54 ms (Top 81.33%) | Memory: 57.5 MB (Top 77.78%)\nclass Solution {\n // Rectangle x0,y0,x1,y1\n public boolean isRectangleCover(int[][] rectangles) {\n // Ordered by y0 first and x0 second\n Arrays.sort(rectangles,(r1,r2)->{\n if(r1[1]==r2[1]) return r1[0]-r2[0];\n return r1[1]-r2[1];\n });\n\n // Layering rectangles with pq, ordered by y1 first and x0 second\n PriorityQueue pq = new PriorityQueue<>((r1,r2)->{\n if(r1[3]==r2[3]) return r1[0]-r2[0];\n return r1[3]-r2[3];\n });\n\n // Create first layer\n pq.offer(rectangles[0]);\n int i=1;\n while(icurr[2]){\n pq.offer(new int[]{curr[2], prev[1], prev[2], prev[3]});\n x=curr[2];\n }else {\n x=prev[2];\n }\n }\n if(x bool:\n X1, Y1 = float('inf'), float('inf')\n X2, Y2 = -float('inf'), -float('inf')\n\n points = set()\n actual_area = 0\n for x1, y1, x2, y2 in rectangles:\n # calculate the coords of the potential perfect rectangle\n X1, Y1 = min(X1, x1), min(Y1, y1)\n X2, Y2 = max(X2, x2), max(Y2, y2)\n # add up to the actual_area, so we can check against to see if thers is any part overwritten.\n actual_area += (x2 - x1) * (y2 - y1)\n \n # proving steps in https://labuladong.github.io/algo/4/32/131/\n for p in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]:\n if p in points: \n points.remove(p)\n else: \n points.add(p)\n\n # check the area \n expected_area = (X2 - X1) * (Y2 - Y1)\n if actual_area != expected_area:\n return False\n \n if len(points) != 4: \n return False\n\n if (X1, Y1) not in points: \n return False\n if (X1, Y2) not in points: \n return False\n if (X2, Y1) not in points: \n return False\n if (X2, Y2) not in points: \n return False\n\n return True", + "title": "391. Perfect Rectangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the least number of perfect square numbers that sum to n . A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1 , 4 , 9 , and 16 are perfect squares while 3 and 11 are not. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:3Explanation:12 = 4 + 4 + 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 13Output:2Explanation:13 = 4 + 9.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 91.34%) | Memory: 42.30 MB (Top 82.04%)\n\nclass Solution {\n public int numSquares(int n) {\n int dp[]=new int [n+1];\n dp[0]=0;\n dp[1]=1;\n \n for(int i=2;i bool:\n sq = int(math.sqrt(n))\n return sq*sq == n\n \n def numSquares(self, n: int) -> int:\n # Lagrange's four-square theorem\n if self.isSquare(n):\n return 1\n while (n & 3) == 0:\n n >>= 2\n if (n & 7) == 7:\n return 4\n sq = int(math.sqrt(n)) + 1\n for i in range(1,sq):\n if self.isSquare(n - i*i):\n return 2\n return 3\n", + "title": "279. Perfect Squares", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"Output:trueExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkInclusion(String s1, String s2) {\n if(s1.length() > s2.length()) {\n return false;\n }\n \n int[]s1Count = new int[26];\n int[]s2Count = new int[26];\n \n for(int i = 0; i < s1.length(); i++) {\n char c = s1.charAt(i);\n char s = s2.charAt(i);\n s1Count[c - 'a'] += 1;\n s2Count[s - 'a'] += 1;\n }\n \n int matches = 0;\n \n for(int i = 0; i < 26;i++) {\n if(s1Count[i] == s2Count[i]) {\n matches+=1;\n }\n }\n \n int left = 0;\n for(int right = s1.length(); right < s2.length();right++) {\n if(matches == 26) {\n return true;\n }\n \n int index = s2.charAt(right) - 'a';\n s2Count[index] += 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] + 1 == s2Count[index]) {\n matches -= 1;\n }\n \n index = s2.charAt(left) - 'a';\n s2Count[index] -= 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] - 1 == s2Count[index]) {\n matches -= 1;\n }\n left += 1;\n }\n \n if(matches == 26) {\n return true;\n }\n \n return false;\n }\n}\n", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"Output:trueExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n s1_map = {}\n s2_map = {}\n for i in range(ord('a') , ord('z') + 1):\n s1_map[chr(i)] = 0\n s2_map[chr(i)] = 0\n \n for i in s1:\n s1_map[i] += 1\n \n l = 0\n r = 0\n \n while r < len(s2):\n print(s2_map , l ,r)\n if r == 0:\n while r < len(s1):\n s2_map[s2[r]] += 1\n r += 1\n if s2_map == s1_map:\n return True\n\n else:\n s2_map[s2[l]] -= 1\n s2_map[s2[r]] += 1\n \n if s2_map == s1_map:\n return True\n else:\n l += 1\n r += 1\n \n return False \n", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3 : Given n and k , return the k th permutation sequence. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 9", + "1 <= k <= n!" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 3Output:\"213\"", + "image": null + }, + { + "text": "Example 2: Input:n = 4, k = 9Output:\"2314\"", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 1Output:\"123\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String getPermutation(int n, int k) {\n int fact = 1;\n List nums = new ArrayList<>();\n for(int i = 1; i str:\n nums = [i for i in range(1, n+1)] # list of numbers from 1 to n\n factorial = [1] * n\n for i in range(1, n):\n factorial[i] = factorial[i-1] * i\n \n k -= 1\n result = []\n for i in range(n-1, -1, -1):\n index = k // factorial[i]\n result.append(str(nums[index]))\n nums.pop(index)\n k = k % factorial[i]\n \n return ''.join(result)\n", + "title": "60. Permutation Sequence", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 76.85%) | Memory: 44.7 MB (Top 48.41%)\nclass Solution {\n List> res = new LinkedList<>();\n\n public List> permute(int[] nums) {\n ArrayList list = new ArrayList<>();\n boolean[] visited = new boolean[nums.length];\n\n backTrack(nums, list, visited);\n return res;\n }\n\n private void backTrack(int[] nums, ArrayList list, boolean[] visited){\n if(list.size() == nums.length){\n res.add(new ArrayList(list));\n return;\n }\n for(int i = 0; i < nums.length; i++){\n if(!visited[i]){\n visited[i] = true;\n list.add(nums[i]);\n backTrack(nums, list, visited);\n visited[i] = false;\n list.remove(list.size() - 1);\n }\n }\n }\n}", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n return list(permutations(nums))\n", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a collection of numbers, nums , that might contain duplicates, return all possible unique permutations in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 8", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]Output:[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> permuteUnique(int[] nums) {\n List> ans = new ArrayList<>();\n Arrays.sort(nums);\n boolean used[] = new boolean[nums.length];\n \n permutationsFinder(nums,ans,new ArrayList<>(),used);\n \n return ans;\n }\n \n static void permutationsFinder(int[] nums,List> ans,List list,boolean used[]){\n if(list.size() == nums.length){\n ans.add(new ArrayList<>(list));\n return;\n }\n \n for(int i=0;i0 && nums[i]==nums[i-1] && !used[i-1]) continue;\n list.add(nums[i]);\n used[i] = true;\n permutationsFinder(nums,ans,list,used);\n list.remove(list.size()-1);\n used[i] = false;\n }\n }\n}\n", + "title": "47. Permutations II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a collection of numbers, nums , that might contain duplicates, return all possible unique permutations in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 8", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]Output:[[1,1,2],\n [1,2,1],\n [2,1,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 136 ms (Top 31.20%) | Memory: 14.2 MB (Top 62.53%)\nclass Solution(object):\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n if len(nums) == 1:\n return [[nums[0]]]\n\n res = self.permuteUnique(nums[1:])\n\n for i in range(len(res)-1, -1 , -1):\n j = 0\n while j < len(res[i]):\n if res[i][j] == nums[0]: #to account for repeated nums\n break\n lst = res[i][:]\n lst.insert(j, nums[0])\n res.append(lst)\n j += 1\n\n res[i].insert(j,nums[0])\n\n return res", + "title": "47. Permutations II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "You will pick any pizza slice.", + "Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.", + "Your friend Bob will pick the next slice in the clockwise direction of your pick.", + "Repeat until there are no more slices of pizzas." + ], + "examples": [ + { + "text": "Example 1: Input:slices = [1,2,3,4,5,6]Output:10Explanation:Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_3_1723.png" + }, + { + "text": "Example 2: Input:slices = [8,9,8,6,1,1]Output:16Explanation:Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_4_1723.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSizeSlices(int[] slices) {\n int n = slices.length;\n return Math.max(helper(slices, n/3, 0, n - 2), helper(slices, n/3, 1, n - 1));\n }\n \n private int helper(int[] slices, int rounds, int start, int end) {\n int n = end - start + 1, max = 0;\n int[][][] dp = new int[n][rounds+1][2];\n dp[0][1][1] = slices[start];\n for (int i = start + 1; i <= end; i++) {\n int x = i - start;\n for (int j = 1; j <= rounds; j++) {\n dp[x][j][0] = Math.max(dp[x-1][j][0], dp[x-1][j][1]);\n dp[x][j][1] = dp[x-1][j-1][0] + slices[i];\n if (j == rounds) {\n max = Math.max(max, Math.max(dp[x][j][0], dp[x][j][1]));\n }\n }\n }\n return max;\n }\n}\n", + "title": "1388. Pizza With 3n Slices", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "You will pick any pizza slice.", + "Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.", + "Your friend Bob will pick the next slice in the clockwise direction of your pick.", + "Repeat until there are no more slices of pizzas." + ], + "examples": [ + { + "text": "Example 1: Input:slices = [1,2,3,4,5,6]Output:10Explanation:Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_3_1723.png" + }, + { + "text": "Example 2: Input:slices = [8,9,8,6,1,1]Output:16Explanation:Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.", + "image": "https://assets.leetcode.com/uploads/2020/02/18/sample_4_1723.png" + } + ], + "follow_up": null, + "solution": " class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ** #This solve function mainly on work on the idea of A Previous dp problem House Robber II \n\t\t#If we take the first slice then we cant take the second slice and vice versa**\n\t\tdef solve(slices,start,end,n,dp):\n if start>end or n==0:\n return 0\n if dp[start][n] !=-1:\n return dp[start][n]\n include = slices[start] + solve(slices,start+2,end,n-1,dp)\n \n exclude = 0 + solve(slices,start+1,end,n,dp)\n \n dp[start][n]= max(include,exclude)\n return dp[start][n]\n dp1=[[-1 for i in range(k+1)]for _ in range(k+1)]\n dp2=[[-1 for i in range(k+1)]for _ in range(k+1)]\n \n option1=solve(slices,0,k-2,k//3,dp1)#Taking the the first slice , now we cant take the last slice and next slice\n option2=solve(slices,1,k-1,k//3,dp2)#Taking the the second slice , now we cant take the second last slice and next slice\n \n return max(option1,option2)\n", + "title": "1388. Pizza With 3n Slices", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle . You are also given a 0-indexed 2D integer array queries where queries[i] = [left i , right i ] denotes the substring s[left i ...right i ] ( inclusive ). For each query, you need to find the number of plates between candles that are in the substring . A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring . Return an integer array answer where answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, s = \"||**||**|*\" , and a query [3, 8] denotes the substring \"*|| ** |\" . The number of plates between candles in this substring is 2 , as each of the two plates has at least one candle in the substring to its left and right." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"**|**|***|\", queries = [[2,5],[5,9]]Output:[2,3]Explanation:- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-1.png" + }, + { + "text": "Example 2: Input:s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]Output:[9,0,0,0,0]Explanation:- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 58.35%) | Memory: 143.3 MB (Top 38.21%)\nclass Solution {\n // O(sLen + queries.length) time, O(sLen) space\n public int[] platesBetweenCandles(String s, int[][] queries) {\n int sLen = s.length();\n // cumulative number of plates from the left\n int[] numberOfPlates = new int[sLen+1];\n for (int i=0; i=0; i--) {\n if (s.charAt(i) == '|') {\n cand = i;\n }\n candleToTheRight[i] = cand;\n }\n // for each query - count the number of plates between closest candles\n int[] res = new int[queries.length];\n for (int i=0; i= right) {\n res[i] = 0;\n } else {\n res[i] = numberOfPlates[right+1] - numberOfPlates[left];\n }\n }\n return res;\n }\n}", + "title": "2055. Plates Between Candles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle . You are also given a 0-indexed 2D integer array queries where queries[i] = [left i , right i ] denotes the substring s[left i ...right i ] ( inclusive ). For each query, you need to find the number of plates between candles that are in the substring . A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring . Return an integer array answer where answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, s = \"||**||**|*\" , and a query [3, 8] denotes the substring \"*|| ** |\" . The number of plates between candles in this substring is 2 , as each of the two plates has at least one candle in the substring to its left and right." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"**|**|***|\", queries = [[2,5],[5,9]]Output:[2,3]Explanation:- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-1.png" + }, + { + "text": "Example 2: Input:s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]Output:[9,0,0,0,0]Explanation:- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.", + "image": "https://assets.leetcode.com/uploads/2021/10/04/ex-2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:\n psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1)\n res = []\n for i, ch in enumerate(s):\n psum[i + 1] = psum[i] + (ch == '|')\n prev[i + 1] = i if ch == '|' else prev[i]\n for i, ch in reversed(list(enumerate(s))):\n next[i] = i if ch == '|' else next[i + 1]\n for q in queries:\n l, r = next[q[0]], prev[q[1] + 1]\n res.append(r - l - (psum[r] - psum[l]) if l < r else 0)\n return res\n", + "title": "2055. Plates Between Candles", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]Output:[1,2,4]Explanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]Output:[4,3,2,2]Explanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]Output:[1,0]Explanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 96.61%)\nclass Solution {\n public int[] plusOne(int[] digits) {\n\n int len = digits.length;\n\n //last digit not a 9, just add 1 to it\n if(digits[len - 1] != 9){\n digits[len - 1] = digits[len - 1] + 1;\n return digits;\n }\n\n //last digit is a 9, find the closest digit that is not a 9\n else{\n int i = len - 1;\n while(i >= 0 && digits[i] == 9){\n digits[i] = 0;\n i--;\n }\n if(i == -1){\n int[] ret = new int[len + 1];\n for(int j = 0; j < len; j++){\n ret[j+1] = digits[j];\n }\n ret[0] = 1;\n return ret;\n }\n digits[i] = digits[i] + 1;\n }\n\n return digits;\n }\n}", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]Output:[1,2,4]Explanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]Output:[4,3,2,2]Explanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]Output:[1,0]Explanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 85.76%) | Memory: 16.50 MB (Top 60.81%)\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n\n for i in range(len(digits)-1, -1, -1):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[i] = digits[i] + 1\n return digits\n return [1] + digits \n\n \n", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Given buckets , minutesToDie , and minutesToTest , return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= buckets <= 1000", + "1 <= minutesToDie <= minutesToTest <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:buckets = 4, minutesToDie = 15, minutesToTest = 15Output:2Explanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.", + "image": null + }, + { + "text": "Example 2: Input:buckets = 4, minutesToDie = 15, minutesToTest = 30Output:2Explanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.5 MB (Top 75.55%)\nclass Solution {\n public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n int T = (minutesToTest/minutesToDie) + 1;\n int cnt = 0;\n int total = 1;\n while (total < buckets) {\n total *= T;\n cnt++;\n }\n return cnt;\n }\n}", + "title": "458. Poor Pigs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: Given buckets , minutesToDie , and minutesToTest , return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= buckets <= 1000", + "1 <= minutesToDie <= minutesToTest <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:buckets = 4, minutesToDie = 15, minutesToTest = 15Output:2Explanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.", + "image": null + }, + { + "text": "Example 2: Input:buckets = 4, minutesToDie = 15, minutesToTest = 30Output:2Explanation:We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 32 ms (Top 93.2%) | Memory: 16.18 MB (Top 93.2%)\n\nclass Solution(object):\n def poorPigs(self, buckets, minutesToDie, minutesToTest):\n # Calculate the max time for a pig to test buckets...\n # Note that, max time will not be (minutesToTest / minutesToDie)...\n # Thinking about all pigs drinking all buckets at last, but no one died immediately, so the poison bucket is the last bucket...\n max_time = minutesToTest / minutesToDie + 1\n # Initialize the required minimum number of pigs...\n req_pigs = 0\n # To find the minimum number of pigs, find the minimum req_pigs such that Math.pow(max_time, req_pigs) >= buckets...\n while (max_time) ** req_pigs < buckets:\n # Increment until it will be greater or equals to bucket...\n req_pigs += 1\n # Return the required minimum number of pigs...\n return req_pigs", + "title": "458. Poor Pigs", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2 12 - 1] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6,7]Output:[1,#,2,3,#,4,5,6,7,#]Explanation:Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/14/116_sample.png" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution:\n def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n q=[]\n q.append(root)\n if not root:\n return None\n while q:\n prev=None\n for i in range(len(q)):\n node=q.pop(0)\n if prev:\n prev.next=node\n prev=node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n prev=None\n return root\n \n", + "title": "116. Populating Next Right Pointers in Each Node", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]Output:[1,#,2,3,#,4,5,7,#]Explanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 98.77%)\nclass Solution {\n public Node connect(Node root) {\n if (root == null) {\n return root;\n }\n Node head = null; //the start node of next level, the first left of next level\n Node prev = null; //the next pointer\n Node curr = root;\n\n while (curr != null) {\n //traverse the whole current level, left -> right, until we meet a null pointer\n while (curr != null) {\n if (curr.left != null) {\n if (head == null) {\n head = curr.left;\n prev = curr.left;\n } else {\n prev.next = curr.left;\n prev = prev.next;\n }\n }\n\n if (curr.right != null) {\n if (head == null) {\n head = curr.right;\n prev = curr.right;\n } else {\n prev.next = curr.right;\n prev = prev.next;\n }\n }\n curr = curr.next;\n }\n\n curr = head;\n prev = null;\n head = null;\n }\n return root;\n }\n}", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]Output:[1,#,2,3,#,4,5,7,#]Explanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "# Runtime: 305 ms (Top 5.46%) | Memory: 15.4 MB (Top 49.03%)\n\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=0, left=None, right=None, next=None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution(object):\n def findRightMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n right = self.findRightMost(root.right, level + 1, requiredLevel)\n if right:\n return right\n return self.findRightMost(root.left, level + 1, requiredLevel)\n def findLeftMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n left = self.findLeftMost(root.left, level + 1, requiredLevel)\n if left:\n return left\n return self.findLeftMost(root.right, level + 1, requiredLevel)\n def findRightMostFromRoot(self, rootLevelInfo, requiredLevel, currentRight):\n if currentRight:\n if currentRight.right:\n return currentRight.right\n if currentRight.left:\n return currentRight.left\n root, rootlevel = rootLevelInfo\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n while not rightMost and root:\n root = root.right if root.right else root.left\n rootlevel += 1\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n if rightMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n return rightMost\n def findLeftMostFromRoot(self, rootLevelInfo, requiredLevel, currentLeft):\n if currentLeft:\n if currentLeft.left:\n return currentLeft.left\n if currentLeft.right:\n return currentLeft.right\n root, rootlevel = rootLevelInfo\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n while not leftMost and root:\n root = root.left if root.left else root.right\n rootlevel += 1\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n if leftMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n\n return leftMost\n def stitch(self, root):\n if not root:\n return\n leftRootStart = [root.left, 1]\n rightRootStart = [root.right, 1]\n connectLevel = 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, 1, None)\n currentRight = self.findRightMostFromRoot(leftRootStart, 1, None)\n while currentLeft and currentRight:\n currentRight.next = currentLeft\n connectLevel += 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, connectLevel, currentLeft)\n currentRight = self.findRightMostFromRoot(leftRootStart, connectLevel, currentRight)\n\n self.stitch(root.left)\n self.stitch(root.right)\n def connect(self, root):\n \"\"\"\n :type root: Node\n :rtype: Node\n \"\"\"\n if not root:\n return root\n self.stitch(root)\n return root", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\" , \"bb\" , \"xxxx\" , \"z\" , and \"yy\" . A group is identified by an interval [start, end] , where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6] . A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s contains lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbxxxxzzy\"Output:[[3,6]]Explanation:\"xxxx\" is the onlylarge group with start index 3 and end index 6.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\"Output:[]Explanation:We have groups \"a\", \"b\", and \"c\", none of which are large groups.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcdddeeeeaabbbcd\"Output:[[3,5],[6,9],[12,14]]Explanation:The large groups are \"ddd\", \"eeee\", and \"bbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 35.3%) | Memory: 44.08 MB (Top 18.5%)\n\nclass Solution {\n public List> largeGroupPositions(String s) {\n List> res = new ArrayList<>();\n List tmp = new ArrayList<>();\n int count = 1;\n \n for (int i = 0; i < s.length() - 1; i++) {\n // Increment the count until the next element is the same as the previous element. Ex: \"aaa\"\n if (s.charAt(i) == s.charAt(i + 1)) {\n count++;\n } \n // Add the first and last indices of the substring to the list when the next element is different from the previous element. Ex: \"aaab\"\n else if (s.charAt(i) != s.charAt(i + 1) && count >= 3) {\n // gives the starting index of substring\n tmp.add(i - count + 1);\n // gives the last index of substring \n tmp.add(i);\n res.add(tmp);\n count = 1;\n tmp = new ArrayList<>();\n } \n else {\n count = 1;\n }\n }\n\n // Check for a large group at the end of the string. Ex: \"abbb\".\n if (count >= 3) {\n tmp.add(s.length() - count);\n tmp.add(s.length() - 1);\n res.add(tmp);\n }\n\n return res;\n }\n}\n", + "title": "830. Positions of Large Groups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = \"abbxxxxzyy\" has the groups \"a\" , \"bb\" , \"xxxx\" , \"z\" , and \"yy\" . A group is identified by an interval [start, end] , where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6] . A group is considered large if it has 3 or more characters. Return the intervals of every large group sorted in increasing order by start index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s contains lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbxxxxzzy\"Output:[[3,6]]Explanation:\"xxxx\" is the onlylarge group with start index 3 and end index 6.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc\"Output:[]Explanation:We have groups \"a\", \"b\", and \"c\", none of which are large groups.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcdddeeeeaabbbcd\"Output:[[3,5],[6,9],[12,14]]Explanation:The large groups are \"ddd\", \"eeee\", and \"bbb\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 17.97%) | Memory: 13.9 MB (Top 73.17%)\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n\n i=0\n c=1\n prev=\"\"\n l=len(s)\n ans=[]\n while i=3):\n ans.append([i+1-c,i])\n else:\n if c>=3:\n ans.append([i-c,i-1])\n c=1\n prev=s[i]\n i+=1\n return ans\n", + "title": "830. Positions of Large Groups", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We want to split a group of n people (labeled from 1 to n ) into two groups of any size . Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [a i , b i ] indicates that the person labeled a i does not like the person labeled b i , return true if it is possible to split everyone into two groups in this way . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2000", + "0 <= dislikes.length <= 10^4", + "dislikes[i].length == 2", + "1 <= dislikes[i][j] <= n", + "a i < b i", + "All the pairs of dislikes are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dislikes = [[1,2],[1,3],[2,4]]Output:trueExplanation:group1 [1,4] and group2 [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, dislikes = [[1,2],[1,3],[2,3]]Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] rank;\n int[] parent;\n int[] rival;\n public boolean possibleBipartition(int n, int[][] dislikes) {\n rank = new int[n+1];\n rival = new int[n+1];\n parent = new int[n+1];\n for(int i = 1;i <= n;i++){\n rank[i] = 1;\n parent[i] = i;\n }\n for(int[] dis : dislikes){\n int x = dis[0], y = dis[1];\n if(find(x) == find(y))\n return false;\n if(rival[x] != 0)\n union(rival[x], y);\n else\n rival[x] = y;\n if(rival[y] != 0)\n union(rival[y], x);\n else\n rival[y] = x;\n }\n return true;\n }\n public int find(int x){\n if(parent[x] == x)\n return x;\n return parent[x] = find(parent[x]);\n }\n public void union(int x, int y){\n int x_set = find(x);\n int y_set = find(y);\n if(x_set == y_set)\n return;\n if(rank[x_set] < rank[y_set])\n parent[x_set] = y_set;\n else if(rank[y_set] < rank[x_set])\n parent[y_set] = x_set;\n else{\n parent[x_set] = y_set;\n rank[y_set]++;\n }\n }\n}\n", + "title": "886. Possible Bipartition", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We want to split a group of n people (labeled from 1 to n ) into two groups of any size . Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [a i , b i ] indicates that the person labeled a i does not like the person labeled b i , return true if it is possible to split everyone into two groups in this way . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 2000", + "0 <= dislikes.length <= 10^4", + "dislikes[i].length == 2", + "1 <= dislikes[i][j] <= n", + "a i < b i", + "All the pairs of dislikes are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, dislikes = [[1,2],[1,3],[2,4]]Output:trueExplanation:group1 [1,4] and group2 [2,3].", + "image": null + }, + { + "text": "Example 2: Input:n = 3, dislikes = [[1,2],[1,3],[2,3]]Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 997 ms (Top 62.25%) | Memory: 22.2 MB (Top 22.99%)\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n def dfs(i, c):\n if color[i] != 0:\n if color[i] != c:\n return False\n return True\n\n color[i] = c\n for u in e[i]:\n if not dfs(u, 3 - c):\n return False\n return True\n\n e = [[] for _ in range(n)]\n for u, v in dislikes:\n u -= 1\n v -= 1\n e[u].append(v)\n e[v].append(u)\n color = [0] * n\n for i in range(n):\n if color[i] == 0:\n if not dfs(i, 1):\n return False\n return True", + "title": "886. Possible Bipartition", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10Output:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3Output:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2Output:0.25000Explanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double myPow(double x, int n) {\n if (n == 0) return 1;\n if (n == 1) return x;\n else if (n == -1) return 1 / x;\n double res = myPow(x, n / 2);\n if (n % 2 == 0) return res * res;\n else if (n % 2 == -1) return res * res * (1/x);\n else return res * res * x;\n }\n}\n", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10Output:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3Output:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2Output:0.25000Explanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n self.x = x\n \n if n == 0:\n return 1\n \n isInverted = False\n if n < 0:\n isInverted = True\n n = -1 * n\n\n result = self.pow(n)\n \n return result if not isInverted else 1 / result\n \n def pow(self, n):\n if n == 1:\n return self.x\n \n if n % 2 == 0:\n p = self.pow(n / 2)\n return p * p\n else:\n return self.x * self.pow(n-1)\n", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return true if it is a power of four. Otherwise, return false . An integer n is a power of four, if there exists an integer x such that n == 4 x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 16Output:true", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 64.18%) | Memory: 40.9 MB (Top 74.82%)\nclass Solution {\n public boolean isPowerOfFour(int n) {\n return (Math.log10(n)/Math.log10(4))%1==0;\n }\n}", + "title": "342. Power of Four", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return true if it is a power of four. Otherwise, return false . An integer n is a power of four, if there exists an integer x such that n == 4 x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 16Output:true", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 35.3%) | Memory: 16.23 MB (Top 61.5%)\n\nimport math \nclass Solution:\n def isPowerOfFour(self, n: int) -> bool:\n\n if n <= 0:\n return False\n return math.log(n, 4).is_integer()", + "title": "342. Power of Four", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return true if it is a power of three. Otherwise, return false . An integer n is a power of three, if there exists an integer x such that n == 3 x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 27Output:true", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 9Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPowerOfThree(int n) {\n if(n==1){\n return true;\n }\n if(n<=0){\n return false;\n }\n if(n%3 !=0 && n>1){\n return false;\n }\n else{\n return isPowerOfThree(n/3); // recurssion \n }\n }\n}\n", + "title": "326. Power of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return true if it is a power of three. Otherwise, return false . An integer n is a power of three, if there exists an integer x such that n == 3 x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 27Output:true", + "image": null + }, + { + "text": "Example 2: Input:n = 0Output:false", + "image": null + }, + { + "text": "Example 3: Input:n = 9Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 96.60%) | Memory: 13.8 MB (Top 57.97%)\nclass Solution:\n def isPowerOfThree(self, n: int) -> bool:\n return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False", + "title": "326. Power of Three", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:trueExplanation:20= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 16Output:trueExplanation:24= 16", + "image": null + }, + { + "text": "Example 3: Input:n = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 14.46%) | Memory: 41.2 MB (Top 58.53%)\nclass Solution {\n public boolean isPowerOfTwo(int n) {\n return power2(0,n);\n\n }\n public boolean power2(int index,int n){\n if(Math.pow(2,index)==n)\n return true;\n if(Math.pow(2,index)>n)\n return false;\n return power2(index+1,n);\n }\n}", + "title": "231. Power of Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:trueExplanation:20= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 16Output:trueExplanation:24= 16", + "image": null + }, + { + "text": "Example 3: Input:n = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n \n if n == 0: return False\n \n k = n\n while k != 1:\n if k % 2 != 0:\n return False\n k = k // 2\n \n \n return True\n\n count = 0\n for i in range(33):\n mask = 1 << i\n \n if mask & n:\n count += 1\n \n if count > 1:\n return False\n \n if count == 1:\n return True\n return False\n\t\t\n", + "title": "231. Power of Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given three integers x , y , and bound , return a list of all the powerful integers that have a value less than or equal to bound . An integer is powerful if it can be represented as x i + y j for some integers i >= 0 and j >= 0 . You may return the answer in any order . In your answer, each value should occur at most once . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= x, y <= 100", + "0 <= bound <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2, y = 3, bound = 10Output:[2,3,4,5,7,9,10]Explanation:2 = 20+ 303 = 21+ 304 = 20+ 315 = 21+ 317 = 22+ 319 = 23+ 3010 = 20+ 32", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 5, bound = 15Output:[2,4,6,8,10,14]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 39.15%) | Memory: 41.9 MB (Top 60.38%)\nclass Solution {\n public List powerfulIntegers(int x, int y, int bound) {\n HashSet set = new HashSet<>();\n for(int i = 1; i(set);\n }\n}", + "title": "970. Powerful Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given three integers x , y , and bound , return a list of all the powerful integers that have a value less than or equal to bound . An integer is powerful if it can be represented as x i + y j for some integers i >= 0 and j >= 0 . You may return the answer in any order . In your answer, each value should occur at most once . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= x, y <= 100", + "0 <= bound <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2, y = 3, bound = 10Output:[2,3,4,5,7,9,10]Explanation:2 = 20+ 303 = 21+ 304 = 20+ 315 = 21+ 317 = 22+ 319 = 23+ 3010 = 20+ 32", + "image": null + }, + { + "text": "Example 2: Input:x = 3, y = 5, bound = 15Output:[2,4,6,8,10,14]", + "image": null + } + ], + "follow_up": null, + "solution": "from math import log\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n if bound == 0:\n return []\n maxi = int(log(bound,max(x,2))) +1\n maxj = int(log(bound,max(y,2))) +1\n L = set()\n for i in range(maxi):\n for j in range(maxj):\n if (t:=x**i +y**j) <= bound:\n L.add(t)\n else:\n break\n return list(L)\n", + "title": "970. Powerful Integers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums . Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0 . At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1] ) which reduces the size of the array by 1 . The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true . You may assume that both players are playing optimally. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 20", + "0 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,2]Output:falseExplanation:Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,233,7]Output:trueExplanation:Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean PredictTheWinner(int[] nums) {\n return predictTheWinner(nums, 0, nums.length-1,true,0, 0);\n }\n private boolean predictTheWinner(int[] nums, int start,int end, boolean isP1Turn, long p1Score, long p2Score){\n if(start > end){\n return p1Score >= p2Score;\n }\n\n boolean firstTry;\n boolean secondTry;\n if(isP1Turn){\n firstTry = predictTheWinner(nums, start +1 , end, false, p1Score + nums[start], p2Score);\n secondTry = predictTheWinner(nums, start, end-1, false, p1Score + nums[end], p2Score);\n\n }else{\n firstTry = predictTheWinner(nums, start +1 , end, true, p1Score, p2Score + nums[start]);\n secondTry = predictTheWinner(nums, start, end-1, true, p1Score , p2Score + nums[end]);\n\n }\n return isP1Turn ? (firstTry || secondTry) : (firstTry && secondTry);\n }\n}\n", + "title": "486. Predict the Winner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0 . At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1] ) which reduces the size of the array by 1 . The player adds the chosen number to their score. The game ends when there are no more elements in the array. Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true . You may assume that both players are playing optimally. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 20", + "0 <= nums[i] <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,2]Output:falseExplanation:Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,233,7]Output:trueExplanation:Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n dp = [[-1] * len(nums) for _ in nums]\n def get_score(i: int, j: int) -> int:\n if i == j: \n dp[i][j] = 0\n return dp[i][j]\n if i == j - 1:\n dp[i][j] = nums[j] if nums[i] > nums[j] else nums[i]\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n\n y1 = get_score(i + 1, j - 1)\n y2 = get_score(i + 2, j)\n y3 = get_score(i, j - 2)\n res_y1 = y1 + nums[j] if y1 + nums[j] > y2 + nums[i+1] else y2 + nums[i+1]\n res_y2 = y1 + nums[i] if y1 + nums[i] > y3 + nums[j-1] else y3 + nums[j-1]\n\n dp[i][j] = min(res_y1, res_y2)\n return dp[i][j] \n \n y = get_score(0, len(nums) - 1)\n x = sum(nums) - y\n\n return 0 if y > x else 1\n", + "title": "486. Predict the Winner", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the WordFilter class: Example 1:", + "description_images": [], + "constraints": [ + "WordFilter(string[] words) Initializes the object with the words in the dictionary.", + "f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff . If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"WordFilter\", \"f\"]\n[[[\"apple\"]], [\"a\", \"e\"]]Output[null, 0]ExplanationWordFilter wordFilter = new WordFilter([\"apple\"]);\nwordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = \"e\".", + "image": null + } + ], + "follow_up": null, + "solution": "class WordFilter:\n def __init__(self, words: List[str]):\n self.words = words\n \n def f(self, prefix: str, suffix: str) -> int:\n idx = -1\n for i,w in enumerate(self.words):\n if w.startswith(prefix) and w.endswith(suffix):\n idx = i\n \n return idx\n\n", + "title": "745. Prefix and Suffix Search", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Let f(x) be the number of zeroes at the end of x! . Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1 . Given an integer k , return the number of non-negative integers x have the property that f(x) = k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end." + ], + "examples": [ + { + "text": "Example 1: Input:k = 0Output:5Explanation:0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.", + "image": null + }, + { + "text": "Example 2: Input:k = 5Output:0Explanation:There is no x such that x! ends in k = 5 zeroes.", + "image": null + }, + { + "text": "Example 3: Input:k = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int preimageSizeFZF(int k) {\n long n = 4L * k;\n int resp = 0;\n while (true) {\n int t = zeros(n);\n if (t > k) return 0;\n if (t == k) return 5;\n n++;\n }\n \n }\n \n private int zeros(long n) {\n int resp = 0;\n while (n > 0) {\n resp += (int)(n / 5);\n n /= 5;\n }\n return resp;\n }\n}\n", + "title": "793. Preimage Size of Factorial Zeroes Function", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Let f(x) be the number of zeroes at the end of x! . Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1 . Given an integer k , return the number of non-negative integers x have the property that f(x) = k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end." + ], + "examples": [ + { + "text": "Example 1: Input:k = 0Output:5Explanation:0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.", + "image": null + }, + { + "text": "Example 2: Input:k = 5Output:0Explanation:There is no x such that x! ends in k = 5 zeroes.", + "image": null + }, + { + "text": "Example 3: Input:k = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 30 ms (Top 93.33%) | Memory: 16.50 MB (Top 82.96%)\n\nclass Solution:\n def preimageSizeFZF(self, k: int) -> int: \n\n def atMost_k(k: int)-> int:\n\n left, right = 0, 5*k + 4\n\n while left <= right:\n mid = (left+right)//2\n count, n = 0, mid\n\n while n:\n n//= 5\n count+= n\n\n if count <= k: left = mid + 1\n else: right = mid - 1\n\n return right\n\n \n return atMost_k(k) - atMost_k(k-1)\n", + "title": "793. Preimage Size of Factorial Zeroes Function", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr , that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j] ). If it cannot be done, then return the same array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,1]Output:[3,1,2]Explanation:Swapping 2 and 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,5]Output:[1,1,5]Explanation:This is already the smallest permutation.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,9,4,6,7]Output:[1,7,4,6,9]Explanation:Swapping 9 and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] prevPermOpt1(int[] arr) {\n int n=arr.length;\n int small=arr[n-1];\n int prev=arr[n-1];\n for(int i=n-2;i>=0;i--){\n if(arr[i]<=prev){\n prev=arr[i];\n }\n else{\n int indte=i;\n int te=0;\n for(int j=i+1;jte){\n te=arr[j];\n indte=j;\n }\n }\n int tem=arr[indte];\n arr[indte]=arr[i];\n arr[i]=tem;\n return arr;\n }\n }\n return arr;\n }\n}\n", + "title": "1053. Previous Permutation With One Swap", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr , that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j] ). If it cannot be done, then return the same array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,2,1]Output:[3,1,2]Explanation:Swapping 2 and 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,5]Output:[1,1,5]Explanation:This is already the smallest permutation.", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,9,4,6,7]Output:[1,7,4,6,9]Explanation:Swapping 9 and 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 486 ms (Top 14.08%) | Memory: 15.3 MB (Top 47.61%)\nclass Solution:\n\n def find_max(self, i, a, n):\n maxs = i+1\n for j in range(n-1, i, -1):\n # if only j is greater than max and smaller than first descending element\n if(a[maxs] <= a[j] and a[j] < a[i]):\n maxs = j\n # Swap\n a[i], a[maxs] = a[maxs], a[i]\n return a\n\n def prevPermOpt1(self, arr):\n n = len(arr)\n for i in range(n-1, 0, -1):\n if(arr[i] < arr[i-1]):\n # sending the first descending element from right to max_function\n arr = self.find_max(i-1, arr, n)\n break\n return arr", + "title": "1053. Previous Permutation With One Swap", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5Output:12Explanation:For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:682289015", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n long mod = (long)(1e9+7);\n public int numPrimeArrangements(int n) {\n if(n==1){\n return 1;\n }\n \n boolean[] arr = new boolean[n+1];\n Arrays.fill(arr,true);\n arr[0]=false;\n arr[1]=false;\n \n for(int i=2;i<=Math.sqrt(n);i++){\n \n for(int j=i*i;j<=n;j+=i){\n if(arr[i]==false){\n continue;\n }\n arr[j]=false;\n }\n \n }\n long prime = 0;\n long notPrime=0;\n for(int k=1;k int:\n primes = set()\n for i in range(2,n+1):\n if all(i%p != 0 for p in primes):\n primes.add(i)\n M = 10**9 + 7\n def fact(k):\n res = 1\n for i in range(2,k+1):\n res = (res*i)%M\n return res\n return fact(len(primes))*fact(n-len(primes))%M", + "title": "1175. Prime Arrangements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right , return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation . Recall that the number of set bits an integer has is the number of 1 's present when written in binary. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, 21 written in binary is 10101 , which has 3 set bits." + ], + "examples": [ + { + "text": "Example 1: Input:left = 6, right = 10Output:4Explanation:6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.", + "image": null + }, + { + "text": "Example 2: Input:left = 10, right = 15Output:5Explanation:10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 161 ms (Top 18.27%) | Memory: 63.5 MB (Top 16.98%)\nclass Solution {\n public int calculateSetBits(String s){\n int count=0;\n for (int i = 0; i < s.length(); i++) {\n if(s.charAt(i)=='1') count++;\n }\n return count;\n }\n\n public boolean isPrime(int n){\n if (n==0 || n==1) return false;\n for (int i = 2; i <= n/2; i++) {\n if(n%i ==0 ) return false;\n }\n// System.out.println(n+\" - \");\n return true;\n }\n\n public int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;i++){\n String b= Integer.toBinaryString(i);\n\n int n=calculateSetBits(b);\n\n if(isPrime(n)) count++;\n }\n return count;\n }\n}", + "title": "762. Prime Number of Set Bits in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integers left and right , return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation . Recall that the number of set bits an integer has is the number of 1 's present when written in binary. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, 21 written in binary is 10101 , which has 3 set bits." + ], + "examples": [ + { + "text": "Example 1: Input:left = 6, right = 10Output:4Explanation:6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.", + "image": null + }, + { + "text": "Example 2: Input:left = 10, right = 15Output:5Explanation:10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n return sum(bin(n).count('1') in primes for n in range(left, right + 1))", + "title": "762. Prime Number of Set Bits in Binary Representation", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n, return the smallest prime palindrome greater than or equal to n . An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8 ] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, 2 , 3 , 5 , 7 , 11 , and 13 are all primes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6Output:7", + "image": null + }, + { + "text": "Example 2: Input:n = 8Output:11", + "image": null + }, + { + "text": "Example 3: Input:n = 13Output:101", + "image": null + } + ], + "follow_up": null, + "solution": "// Prime Palindrome\n// Leetcode problem: https://leetcode.com/problems/prime-palindrome/\n\nclass Solution {\n public int primePalindrome(int n) {\n while (true) {\n if (isPrime(n) && isPalindrome(n)) {\n return n;\n }\n n++;\n } \n }\n private boolean isPrime(int n) {\n if (n == 1) {\n return false;\n }\n for (int i = 2; i <= Math.sqrt(n); i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n private boolean isPalindrome(int n) {\n String s = String.valueOf(n);\n int i = 0;\n int j = s.length() - 1;\n while (i < j) {\n if (s.charAt(i) != s.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n}\n", + "title": "866. Prime Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n, return the smallest prime palindrome greater than or equal to n . An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The test cases are generated so that the answer always exists and is in the range [2, 2 * 10^8 ] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, 2 , 3 , 5 , 7 , 11 , and 13 are all primes." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6Output:7", + "image": null + }, + { + "text": "Example 2: Input:n = 8Output:11", + "image": null + }, + { + "text": "Example 3: Input:n = 13Output:101", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 99.21%) | Memory: 17.20 MB (Top 18.9%)\n\nclass Solution:\n def isPrime(self, num):\n from math import sqrt\n if num < 2 or num % 2 == 0:\n return num == 2\n for i in range(3, int(sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True\n\n def primePalindrome(self, n: int) -> int:\n if 8 <= n <= 11:\n return 11\n if len(str(n)) % 2 == 0:\n limit = pow(10, len(str(n)) // 2)\n else:\n n_string = str(n)\n limit = n_string[:len(str(n)) // 2 + 1]\n for i in range(int(limit), 20000):\n y = int(str(i) + str(i)[:-1][::-1])\n if y >= n and self.isPrime(y):\n return y\n", + "title": "866. Prime Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: Return the constructed matrix res . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The height of the tree is height and the number of rows m should be equal to height + 1 .", + "The number of columns n should be equal to 2 height+1 - 1 .", + "Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2] ).", + "For each node that has been placed in the matrix at position res[r][c] , place its left child at res[r+1][c-2 height-r-1 ] and its right child at res[r+1][c+2 height-r-1 ] .", + "Continue this process until all the nodes in the tree have been placed.", + "Any empty cells should contain the empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2]Output:[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]Output:[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 43.8 MB (Top 78.96%)\nclass Solution {\n public List> printTree(TreeNode root) {\n List> res = new ArrayList();\n\n int height = getHeight(root);\n int row = height + 1;\n int column = (int) Math.pow(2, height+1) - 1;\n\n for(int k=0; k list = new ArrayList();\n for(int i=0; i> res, int left, int right, int level, TreeNode root){\n if(root == null) return;\n int mid = left+(right-left)/2;\n res.get(level).set(mid, String.valueOf(root.val));\n\n print(res, left, mid-1, level+1, root.left);\n print(res, mid+1, right, level+1, root.right);\n }\n public int getHeight(TreeNode root){\n if (root==null) return -1;\n int left = getHeight(root.left);\n int right = getHeight(root.right);\n\n return Math.max(left, right)+1;\n }\n}", + "title": "655. Print Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: Return the constructed matrix res . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The height of the tree is height and the number of rows m should be equal to height + 1 .", + "The number of columns n should be equal to 2 height+1 - 1 .", + "Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2] ).", + "For each node that has been placed in the matrix at position res[r][c] , place its left child at res[r+1][c-2 height-r-1 ] and its right child at res[r+1][c+2 height-r-1 ] .", + "Continue this process until all the nodes in the tree have been placed.", + "Any empty cells should contain the empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2]Output:[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,null,4]Output:[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]", + "image": "https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 97.8%) | Memory: 17.40 MB (Top 11.72%)\n\nclass Solution:\n def printTree(self, root: TreeNode) -> List[List[str]]:\n height = 0\n def dfs(node, h): # Find height\n nonlocal height\n height = max(height, h)\n if node.left:\n dfs(node.left, h+1)\n if node.right: \n dfs(node.right, h+1)\n dfs(root, 0)\n n = 2 ** (height + 1) - 1 # Get `n`\n offset = (n - 1) // 2 # Column for root node\n ans = [[''] * n for _ in range(height + 1)]\n q = [(root, 0, offset)]\n for i in range(height+1): # BFS\n tmp_q = []\n while q:\n cur, r, c = q.pop()\n ans[r][c] = str(cur.val)\n if cur.left:\n tmp_q.append((cur.left, r+1, c-2 ** (height - r - 1)))\n if cur.right: \n tmp_q.append((cur.right, r+1, c+2 ** (height - r - 1)))\n q = tmp_q\n return ans\n", + "title": "655. Print Binary Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s . Return all the words vertically in the same order in which they appear in s . Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 200", + "s contains only upper case English letters.", + "It's guaranteed that there is only one space between 2 words." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"HOW ARE YOU\"Output:[\"HAY\",\"ORO\",\"WEU\"]Explanation:Each word is printed vertically. \n \"HAY\"\n \"ORO\"\n \"WEU\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"TO BE OR NOT TO BE\"Output:[\"TBONTB\",\"OEROOE\",\" T\"]Explanation:Trailing spaces is not allowed. \n\"TBONTB\"\n\"OEROOE\"\n\" T\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"CONTEST IS COMING\"Output:[\"CIC\",\"OSO\",\"N M\",\"T I\",\"E N\",\"S G\",\"T\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 20.22%) | Memory: 42.9 MB (Top 20.22%)\nclass Solution {\n public List printVertically(String s) {\n s = s.replace(\" \",\",\");\n String str=\"\";\n List a=new ArrayList<>();\n\n int max=0;\n for(int i =0;i();\n for(int i=0;i List[str]:\n words = s.split()\n max_len = self.getMaxLen(words)\n \n res = list()\n for i in range(max_len):\n s = \"\"\n for word in words:\n if i < len(word):\n s += word[i]\n else:\n s += \" \"\n s = s.rstrip()\n res.append(s)\n return res\n \n \n \n\t\t\n", + "title": "1324. Print Words Vertically", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the i th cell is occupied and cells[i] == 0 if the i th cell is vacant, and you are given an integer n . Return the state of the prison after n days (i.e., n such changes described above). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.", + "Otherwise, it becomes vacant." + ], + "examples": [ + { + "text": "Example 1: Input:cells = [0,1,0,1,1,0,0,1], n = 7Output:[0,0,1,1,0,0,0,0]Explanation:The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]", + "image": null + }, + { + "text": "Example 2: Input:cells = [1,0,0,1,0,0,1,0], n = 1000000000Output:[0,0,1,1,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.57%) | Memory: 42.40 MB (Top 48.82%)\n\nclass Solution {\n public int[] prisonAfterNDays(int[] cells, int N) {\n if(N==0) return cells;\n int[][] mem=new int[14][8]; // Repeat pattern after day 14, so Day 1 and Day 15 is equal\n mem[0][0]=0;\n mem[0][7]=0;\n for(int i=1;i<7;i++){ // calculating Day 1 and insert at 0th position in mem\n if(cells[i-1]==cells[i+1])\n mem[0][i]=1;\n else\n mem[0][i]=0;\n }\n \n for(int j=1;j<14;j++){ // calculating Day 2 to 14 and inserting at position 1 to 13 in mem.\n for(int i=1;i<7;i++){\n if(mem[j-1][i-1]==mem[j-1][i+1])\n mem[j][i]=1;\n else\n mem[j][i]=0;\n }\n }\n return mem[(N-1)%14]; //return the day modulo 14\n }\n}\n", + "title": "957. Prison Cells After N Days", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors. You are given an integer array cells where cells[i] == 1 if the i th cell is occupied and cells[i] == 0 if the i th cell is vacant, and you are given an integer n . Return the state of the prison after n days (i.e., n such changes described above). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.", + "Otherwise, it becomes vacant." + ], + "examples": [ + { + "text": "Example 1: Input:cells = [0,1,0,1,1,0,0,1], n = 7Output:[0,0,1,1,0,0,0,0]Explanation:The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]", + "image": null + }, + { + "text": "Example 2: Input:cells = [1,0,0,1,0,0,1,0], n = 1000000000Output:[0,0,1,1,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 85 ms (Top 14.83%) | Memory: 14 MB (Top 28.83%)\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n patternMatch=defaultdict(int) # pattern match\n totalPrisons=8 # totalPrisons\n cells= [ str(c) for c in (cells)] # into char type\n for d in range(1,n+1):\n tempCell=[]\n tempCell.append('0') # left corner case\n for c in range(1,totalPrisons-1):\n if (cells[c-1]=='1' and cells[c+1]=='1') or (cells[c-1]=='0' and cells[c+1]=='0'):\n tempCell.append('1') # insert 1 if first condition met\n else:\n tempCell.append('0') # otherwise 0\n tempCell.append('0') # right corner case\n cells=tempCell # update cells\n pattern= ''.join(tempCell) # insert pattern in hashtable\n if pattern in patternMatch: # if there is a match\n day=patternMatch[pattern]\n remainder= (n%(d-1))-1 # take modulo\n match= list(patternMatch.keys())[remainder] # find key\n return [ int(m) for m in match] # return\n patternMatch[pattern]=d # assign day\n return [ int(c) for c in (cells)] # return", + "title": "957. Prison Cells After N Days", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i . All the balls will be shuffled uniformly at random , then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b , and two boxes [] and () , then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10 -5 of the actual value will be accepted as correct. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= balls.length <= 8", + "1 <= balls[i] <= 6", + "sum(balls) is even." + ], + "examples": [ + { + "text": "Example 1: Input:balls = [1,1]Output:1.00000Explanation:Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1", + "image": null + }, + { + "text": "Example 2: Input:balls = [2,1,1]Output:0.66667Explanation:We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667", + "image": null + }, + { + "text": "Example 3: Input:balls = [1,2,1,2]Output:0.60000Explanation:The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 77 ms (Top 48.15%) | Memory: 41.6 MB (Top 50.00%)\nclass Solution {\n double all = 0;\n public double getProbability(int[] balls) {\n double[] fact = new double[25];\n fact[0]=1;\n for (int i = 1; i <= 24; i++){\n fact[i]=i*fact[i-1];\n }\n int need = Arrays.stream(balls).sum()/2;\n return solve(0, 0, need, new int[balls.length], balls, fact)/all;\n }\n\n private double solve(int idx, int got, int need, int[] cur, int[] balls, double[] fact){\n if (need == got){\n int colors=0;\n double a = fact[need];\n double b = fact[need];\n for (int i = 0;ineed){\n return 0;\n }\n double ans = 0;\n for (int i = 0; i <=balls[idx];i++){ // for this level of ball, try to take 0 to balls[idx]\n cur[idx]+=i;\n ans += solve(idx+1,got+i,need,cur,balls,fact);\n cur[idx]-=i;\n }\n return ans;\n }\n}", + "title": "1467. Probability of a Two Boxes Having The Same Number of Distinct Balls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i . All the balls will be shuffled uniformly at random , then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully). Please note that the two boxes are considered different. For example, if we have two balls of colors a and b , and two boxes [] and () , then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully). Return the probability that the two boxes have the same number of distinct balls. Answers within 10 -5 of the actual value will be accepted as correct. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= balls.length <= 8", + "1 <= balls[i] <= 6", + "sum(balls) is even." + ], + "examples": [ + { + "text": "Example 1: Input:balls = [1,1]Output:1.00000Explanation:Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1", + "image": null + }, + { + "text": "Example 2: Input:balls = [2,1,1]Output:0.66667Explanation:We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667", + "image": null + }, + { + "text": "Example 3: Input:balls = [1,2,1,2]Output:0.60000Explanation:The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 90.74%) | Memory: 14.1 MB (Top 53.70%)\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n m = len(balls)\n N = sum(balls)\n n = N // 2\n\n prefix = [0] * m\n for i in range(m):\n prefix[i] = prefix[i-1] + balls[i]\n\n # STEP 1: Compute the number of ways to pick j balls from i total, i.e. C(i, j)\n choose = [[0] * (N + 1) for i in range(N + 1)]\n choose[0][0] = 1\n for i in range(1, N + 1):\n for pick in range(N + 1):\n # DECISION 1: don't pick the ith ball\n choose[i][pick] += choose[i - 1][pick]\n # DECISION 2: pick the ith ball\n choose[i][pick] += choose[i - 1][pick - 1]\n\n # STEP 2: From first i ball types, compute ways to:\n # - pick c1 balls in box1\n # - such that the difference in unique ball count between box1 and box2 is d\n ways = [[defaultdict(int) for k in range(n + 1)] for i in range(m + 1)]\n ways[0][0][0] = 1\n\n for i in range(m):\n b = balls[i]\n if i == 0:\n prev_total = 0\n else:\n prev_total = prefix[i - 1]\n for c1 in range(n + 1):\n c2 = prev_total - c1\n if c2 < 0:\n continue\n for d in ways[i][c1]:\n for add1 in range(b + 1):\n add2 = b - add1\n if c1 + add1 > n:\n continue\n if c2 + add2 > n:\n continue\n if add1 == b:\n delta = 1\n elif add2 == b:\n delta = -1\n else:\n delta = 0\n ways_to_add = choose[b][add1] * ways[i][c1][d]\n ways[i + 1][c1 + add1][d + delta] += ways_to_add\n\n # compute the actual probability\n return ways[m][n][0] / choose[N][n]", + "title": "1467. Probability of a Two Boxes Having The Same Number of Distinct Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1 . You are also given a 0-indexed 2D integer array restrictions , where restrictions[i] = [x i , y i ] means that person x i and person y i cannot become friends , either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests , where requests[j] = [u j , v j ] is a friend request between person u j and person v j . A friend request is successful if u j and v j can be friends . Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1] ), and upon a successful request, u j and v j become direct friends for all future friend requests. Return a boolean array result , where each result[j] is true if the j th friend request is successful or false if it is not . Note: If u j and v j are already direct friends, the request is still successful . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "0 <= restrictions.length <= 1000", + "restrictions[i].length == 2", + "0 <= x i , y i <= n - 1", + "x i != y i", + "1 <= requests.length <= 1000", + "requests[j].length == 2", + "0 <= u j , v j <= n - 1", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]Output:[true,false]Explanation:Request 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).", + "image": null + }, + { + "text": "Example 2: Input:n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]Output:[true,false]Explanation:Request 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).", + "image": null + }, + { + "text": "Example 3: Input:n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]Output:[true,false,true,false]Explanation:Request 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n boolean[] result;\n \n public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n parent = new int[n];\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n result = new boolean[requests.length];\n \n for (int i = 0; i < requests.length; i++) {\n // personA and personB can become friends if for all restrictions\n // person x_i and person y_i are not in the same set as personA and personB\n // and vice versa\n int personA = requests[i][0];\n int personB = requests[i][1];\n int personASetRepresentative = find(personA);\n int personBSetRepresentative = find(personB);\n boolean flag = true;\n for (int[] restriction : restrictions) {\n int blackListPersonARepresentative = find(restriction[0]);\n int blackListPersonBRepresentative = find(restriction[1]);\n if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) {\n flag = false;\n }\n if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) {\n flag = false;\n }\n }\n if (flag) {\n union(personA, personB);\n }\n result[i] = flag;\n }\n return result;\n }\n \n private int find(int node) {\n int root = node;\n while (parent[root] != root) {\n root = parent[root];\n }\n \n //path compression\n int curr = node;\n while (parent[curr] != root) {\n int next = parent[curr];\n parent[curr] = root;\n curr = next;\n }\n return root;\n }\n \n private boolean union(int node1, int node2) {\n int root1 = find(node1);\n int root2 = find(node2);\n if (root1 == root2) {\n return false;\n }\n parent[root2] = root1;\n return true;\n }\n}\n", + "title": "2076. Process Restricted Friend Requests", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1 . You are also given a 0-indexed 2D integer array restrictions , where restrictions[i] = [x i , y i ] means that person x i and person y i cannot become friends , either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests , where requests[j] = [u j , v j ] is a friend request between person u j and person v j . A friend request is successful if u j and v j can be friends . Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1] ), and upon a successful request, u j and v j become direct friends for all future friend requests. Return a boolean array result , where each result[j] is true if the j th friend request is successful or false if it is not . Note: If u j and v j are already direct friends, the request is still successful . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 1000", + "0 <= restrictions.length <= 1000", + "restrictions[i].length == 2", + "0 <= x i , y i <= n - 1", + "x i != y i", + "1 <= requests.length <= 1000", + "requests[j].length == 2", + "0 <= u j , v j <= n - 1", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]Output:[true,false]Explanation:Request 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).", + "image": null + }, + { + "text": "Example 2: Input:n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]Output:[true,false]Explanation:Request 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).", + "image": null + }, + { + "text": "Example 3: Input:n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]Output:[true,false,true,false]Explanation:Request 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).", + "image": null + } + ], + "follow_up": null, + "solution": "class UnionFindSet(object):\n def __init__(self, n):\n self.data = range(n)\n\n def find(self, x):\n while x <> self.data[x]:\n x = self.data[x]\n return x\n\n def union(self, x, y):\n self.data[self.find(x)] = self.find(y)\n\n def speedup(self):\n for i in range(len(self.data)):\n self.data[i] = self.find(i)\n\n\nclass Solution(object):\n def friendRequests(self, n, restrictions, requests):\n uf = UnionFindSet(n)\n ret = [True] * len(requests)\n for k, [x, y] in enumerate(requests): # Process Requests Sequentially\n xh = uf.find(x) # backup the head of x for undo\n uf.union(x, y) # link [x, y] and verify if any restriction triggers\n for [i, j] in restrictions:\n if uf.find(i) == uf.find(j):\n ret[k] = False\n break\n if not ret[k]: # if any restriction triggers, undo\n uf.data[xh] = xh\n else:\n uf.speedup()\n return ret\n", + "title": "2076. Process Restricted Friend Requests", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n ​​​​​​ and m ​​​​​​ respectively. servers[i] is the weight of the i ​​​​​​th ​​​​ server, and tasks[j] is the time needed to process the j ​​​​​​th ​​​​ task in seconds . Tasks are assigned to the servers using a task queue . Initially, all servers are free, and the queue is empty . At second j , the j th task is inserted into the queue (starting with the 0 th task being inserted at second 0 ). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight , and in case of a tie, it is assigned to a free server with the smallest index . If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j] . Build an array ans ​​​​ of length m , where ans[j] is the index of the server the j ​​​​​​th task will be assigned to. Return the array ans ​​​​. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "servers.length == n", + "tasks.length == m", + "1 <= n, m <= 2 * 10^5", + "1 <= servers[i], tasks[j] <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:servers = [3,3,2], tasks = [1,2,3,2,1,2]Output:[2,2,0,2,1,2]Explanation:Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "image": null + }, + { + "text": "Example 2: Input:servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]Output:[1,4,1,4,1,3,2]Explanation:Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 421 ms (Top 69.74%) | Memory: 172.7 MB (Top 82.56%)\nclass Solution {\n public int[] assignTasks(int[] servers, int[] tasks) {\n\n PriorityQueue availableServer = new PriorityQueue((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0])));\n for(int i = 0; i < servers.length; i++){\n availableServer.add(new int[]{i, servers[i]});\n }\n\n //int[[] arr,\n //arr[0] - server index\n //arr[1] - server weight\n //arr[2] - free time\n PriorityQueue processingServer = new PriorityQueue(\n (a, b) ->\n\n (\n a[2] != b[2] ? a[2] - b[2] : // try to sort increasing order of free time\n a[1] != b[1] ? a[1] - b[1] : // try to sort increasing order of server weight\n a[0] - b[0] // sort increasing order of server index\n )\n );\n\n int[] result = new int[tasks.length];\n\n for(int i = 0; i < tasks.length; i++){\n\n while(!processingServer.isEmpty() && processingServer.peek()[2] <= i){\n int serverIndex = processingServer.remove()[0];\n availableServer.add(new int[]{serverIndex, servers[serverIndex]});\n }\n\n int currentTaskTimeRequired = tasks[i];\n\n int[] server;\n\n //when current task will free the server done\n int freeTime = currentTaskTimeRequired;\n\n if(!availableServer.isEmpty()){\n server = availableServer.remove();\n freeTime += i;\n }else{\n server = processingServer.remove();\n //append previous time\n freeTime += server[2];\n }\n\n int serverIndex = server[0];\n processingServer.add(new int[]{serverIndex, servers[serverIndex] ,freeTime});\n\n //assign this server to current task\n result[i] = serverIndex;\n }\n\n return result;\n\n }\n}", + "title": "1882. Process Tasks Using Servers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two 0-indexed integer arrays servers and tasks of lengths n ​​​​​​ and m ​​​​​​ respectively. servers[i] is the weight of the i ​​​​​​th ​​​​ server, and tasks[j] is the time needed to process the j ​​​​​​th ​​​​ task in seconds . Tasks are assigned to the servers using a task queue . Initially, all servers are free, and the queue is empty . At second j , the j th task is inserted into the queue (starting with the 0 th task being inserted at second 0 ). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight , and in case of a tie, it is assigned to a free server with the smallest index . If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j] . Build an array ans ​​​​ of length m , where ans[j] is the index of the server the j ​​​​​​th task will be assigned to. Return the array ans ​​​​. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "servers.length == n", + "tasks.length == m", + "1 <= n, m <= 2 * 10^5", + "1 <= servers[i], tasks[j] <= 2 * 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:servers = [3,3,2], tasks = [1,2,3,2,1,2]Output:[2,2,0,2,1,2]Explanation:Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.", + "image": null + }, + { + "text": "Example 2: Input:servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]Output:[1,4,1,4,1,3,2]Explanation:Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n servers_available = [(w, i) for i,w in enumerate(servers)]\n heapify(servers_available)\n tasks_in_progress = []\n res = []\n time = 0\n for j,task in enumerate(tasks):\n time = max(time, j)\n if not servers_available:\n time = tasks_in_progress[0][0]\n while tasks_in_progress and tasks_in_progress[0][0] <= time:\n heappush(servers_available, heappop(tasks_in_progress)[1])\n res.append(servers_available[0][1])\n heappush(tasks_in_progress, (time + task, heappop(servers_available)))\n return res\n", + "title": "1882. Process Tasks Using Servers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "-30 <= nums[i] <= 30", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]Output:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 62.8%) | Memory: 54.05 MB (Top 10.0%)\n\nclass Solution {\n public int[] productExceptSelf(int[] nums) {\n int n = nums.length;\n int pre[] = new int[n];\n int suff[] = new int[n];\n pre[0] = 1;\n suff[n - 1] = 1;\n \n for(int i = 1; i < n; i++) {\n pre[i] = pre[i - 1] * nums[i - 1];\n }\n for(int i = n - 2; i >= 0; i--) {\n suff[i] = suff[i + 1] * nums[i + 1];\n }\n \n int ans[] = new int[n];\n for(int i = 0; i < n; i++) {\n ans[i] = pre[i] * suff[i];\n }\n return ans;\n }\n}", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "-30 <= nums[i] <= 30", + "The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]Output:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 477 ms (Top 13.75%) | Memory: 22.5 MB (Top 18.46%)\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n pre = [1]* (len(nums)+1)\n back = [1]*(len(nums)+1)\n\n for i in range(len(nums)):\n pre[i+1] = pre[i]*nums[i]\n\n for i in range(len(nums)-1,-1,-1):\n back[i-1] = back[i]*nums[i]\n for i in range(len(pre)-1):\n nums[i]=pre[i]*back[i]\n\n return nums", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Example:", + "description_images": [], + "constraints": [ + "ProductOfNumbers() Initializes the object with an empty stream.", + "void add(int num) Appends the integer num to the stream.", + "int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers." + ], + "examples": [ + { + "text": "Example: Input[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]Output[null,null,null,null,null,null,20,40,0,null,32]ExplanationProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32", + "image": null + } + ], + "follow_up": null, + "solution": "class ProductOfNumbers {\n List prefix;\n public ProductOfNumbers() {\n prefix = new ArrayList<>();\n prefix.add(1);\n }\n \n public void add(int num) {\n if(num==0){\n prefix.clear();\n prefix.add(1);\n }\n else prefix.add(num*prefix.get(prefix.size()-1));\n }\n public int getProduct(int k) {\n if(k>=prefix.size()) return 0;\n return prefix.get(prefix.size()-1)/prefix.get(prefix.size()-k-1);\n }\n}\n", + "title": "1352. Product of the Last K Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. Example:", + "description_images": [], + "constraints": [ + "ProductOfNumbers() Initializes the object with an empty stream.", + "void add(int num) Appends the integer num to the stream.", + "int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers." + ], + "examples": [ + { + "text": "Example: Input[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]Output[null,null,null,null,null,null,20,40,0,null,32]ExplanationProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 732 ms (Top 6.90%) | Memory: 163.2 MB (Top 5.18%)\nclass ProductOfNumbers:\n def __init__(self):\n self.prods = [1]\n self.max = 0\n\n def add(self, num: int) -> None:\n if num == 0:\n num = 1\n self.max = len(self.prods)\n self.prods.append(self.prods[-1] * num)\n\n def getProduct(self, k: int) -> int:\n if k >= len(self.prods) - self.max:\n return 0\n return self.prods[-1] // self.prods[-k-1]", + "title": "1352. Product of the Last K Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a group of n members, and a list of various crimes they could commit. The i th crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n . Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "0 <= minProfit <= 100", + "1 <= group.length <= 100", + "1 <= group[i] <= 100", + "profit.length == group.length", + "0 <= profit[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, minProfit = 3, group = [2,2], profit = [2,3]Output:2Explanation:To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]Output:7Explanation:To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def profitableSchemes(self, n, minProfit, group, profit):\n \n k = len(group)\n arr = [[[0 for _ in range(k+1)] for _ in range(minProfit+1)] for _ in range(n+1)]\n \n for i in range(n+1):\n arr[i][0][k] = 1\n \n for j in range(k-1,-1,-1):\n for i in range(n,-1,-1):\n for x in range(minProfit,-1,-1):\n\n arr[i][x][j] = arr[i][x][j+1]\n if i>=group[j]:\n arr[i][x][j] += arr[i-group[j]][max(x-profit[j],0)][j+1]\n \n return arr[n][minProfit][0] % (10**9 + 7)\n\n", + "title": "879. Profitable Schemes", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x , y , and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j) . We view the projection of these cubes onto the xy , yz , and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]Output:17Explanation:Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png" + }, + { + "text": "Example 2: Input:grid = [[2]]Output:5", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0],[0,2]]Output:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int projectionArea(int[][] grid) {\n int totalArea = 0;\n \n \n for(int[] row : grid){\n int max = row[0];\n for(int c : row){\n if(max < c){\n max = c;\n }if(c != 0){\n totalArea += 1;\n }\n \n }\n totalArea += max;\n }\n \n for(int c = 0; c < grid[0].length; c++){\n int max = grid[0][c];\n for(int row = 0; row < grid.length; row++){\n if(max < grid[row][c]){\n \n max = grid[row][c];\n }\n }\n totalArea += max;\n }\n return totalArea;\n }\n}\n", + "title": "883. Projection Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x , y , and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j) . We view the projection of these cubes onto the xy , yz , and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]Output:17Explanation:Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png" + }, + { + "text": "Example 2: Input:grid = [[2]]Output:5", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,0],[0,2]]Output:8", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n total = 0\n\t\t\n # top\n total += sum([1 for i in grid for j in i if j > 0])\n \n\t\t# front\n total += sum([max(col) for col in zip(*grid)])\n \n\t\t# side\n total += sum([max(row) for row in grid])\n \n\t\treturn total\n", + "title": "883. Projection Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png", + "https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^5 ] .", + "1 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,3,1,3,1,null,1]Output:2Explanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 2: Input:root = [2,1,1,1,3,null,null,null,null,null,1]Output:1Explanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 3: Input:root = [9]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int pseudoPalindromicPaths (TreeNode root) {\n return helper(root, 0);\n }\n \n public int helper(TreeNode node, int freq) {\n if (node == null) return 0;\n \n freq = freq ^ (1 << node.val);\n if (node.left == null && node.right == null) {\n return (freq & (freq - 1)) == 0 ? 1 : 0;\n // return Integer.bitCount(freq) <= 1 ? 1 : 0;\n }\n return helper(node.left, freq) + helper(node.right, freq);\n }\n}\n", + "title": "1457. Pseudo-Palindromic Paths in a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png", + "https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^5 ] .", + "1 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,3,1,3,1,null,1]Output:2Explanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 2: Input:root = [2,1,1,1,3,null,null,null,null,null,1]Output:1Explanation:The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).", + "image": null + }, + { + "text": "Example 3: Input:root = [9]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def dfs(self, node, path):\n if not node:\n return\n \n if not node.left and not node.right:\n path += [node.val]\n d = {}\n for i in path.copy():\n if i in d:\n del d[i]\n else:\n d[i] = 1\n #print(d.items())\n self.ans += 1 if len(d) <= 1 else 0\n return\n \n self.dfs(node.left, path+[node.val])\n self.dfs(node.right, path+[node.val])\n \n def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:\n self.ans = 0\n self.dfs(root, [])\n return self.ans", + "title": "1457. Pseudo-Palindromic Paths in a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: Return a string representing the final state . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "dominoes[i] = 'L' , if the i th domino has been pushed to the left,", + "dominoes[i] = 'R' , if the i th domino has been pushed to the right, and", + "dominoes[i] = '.' , if the i th domino has not been pushed." + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = \"RR.L\"Output:\"RR.L\"Explanation:The first domino expends no additional force on the second domino.", + "image": null + }, + { + "text": "Example 2: Input:dominoes = \".L.R...LR..L..\"Output:\"LL.RR.LLRRLL..\"", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/05/18/domino.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 100.00%) | Memory: 43.4 MB (Top 96.04%)\n// Time complexity: O(N)\n// Space complexity: O(N), where N is the length of input string\nclass Solution {\n public String pushDominoes(String dominoes) {\n // ask whether dominoes could be null\n final int N = dominoes.length();\n if (N <= 1) return dominoes;\n char[] res = dominoes.toCharArray();\n int i = 0;\n while (i < N) {\n if (res[i] == '.') {\n i++;\n } else if (res[i] == 'L') { // push left\n int j = i-1;\n while (j >= 0 && res[j] == '.') {\n res[j--] = 'L';\n }\n i++;\n } else { // res[i] == 'R'\n int j = i+1;\n while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side\n j++;\n }\n if (j < N && res[j] == 'L') { // if found 'L', push left and right\n for (int l = i+1, r = j-1; l < r; l++, r--) {\n res[l] = 'R';\n res[r] = 'L';\n }\n i = j + 1;\n } else { // if no 'L', push right\n while (i < j) {\n res[i++] = 'R';\n }\n }\n }\n }\n return String.valueOf(res);\n }\n}", + "title": "838. Push Dominoes", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: Return a string representing the final state . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "dominoes[i] = 'L' , if the i th domino has been pushed to the left,", + "dominoes[i] = 'R' , if the i th domino has been pushed to the right, and", + "dominoes[i] = '.' , if the i th domino has not been pushed." + ], + "examples": [ + { + "text": "Example 1: Input:dominoes = \"RR.L\"Output:\"RR.L\"Explanation:The first domino expends no additional force on the second domino.", + "image": null + }, + { + "text": "Example 2: Input:dominoes = \".L.R...LR..L..\"Output:\"LL.RR.LLRRLL..\"", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/05/18/domino.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def pushDominoes(self, dom: str) -> str:\n from collections import deque\n n = len(dom)\n d = set()\n q = deque()\n arr = [0 for i in range(n)]\n for i in range(n):\n if dom[i] == \"L\":\n arr[i] = -1\n d.add(i)\n q.append((i,\"L\"))\n if dom[i] == \"R\":\n arr[i] = 1\n d.add(i)\n q.append((i,\"R\"))\n while q:\n t1 = set()\n for _ in range(len(q)):\n t = q.popleft()\n if t[1] == \"L\":\n if t[0]-1 >= 0 and t[0]-1 not in d:\n t1.add(t[0]-1)\n arr[t[0]-1] -= 1\n else:\n if t[0]+1 < n and t[0]+1 not in d:\n t1.add(t[0]+1)\n arr[t[0]+1] += 1\n for val in t1:\n d.add(val)\n if arr[val] > 0:\n q.append((val,\"R\"))\n elif arr[val]<0:\n q.append((val,\"L\"))\n ans = \"\"\n for val in arr:\n if val<0:\n ans += \"L\"\n elif val>0:\n ans += \"R\"\n else:\n ans += \".\"\n return ans\n", + "title": "838. Push Dominoes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks . The patterns are given as a list of three-letter strings allowed , where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom , given as a single string, that you must use as the base of the pyramid. Given bottom and allowed , return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed , or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]Output:trueExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid1-grid.jpg" + }, + { + "text": "Example 2: Input:bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]Output:falseExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap> map = new HashMap<>();\n HashMap dp = new HashMap<>();\n \n public boolean pyramidTransition(String bottom, List allowed) {\n for(String s:allowed){\n String sub = s.substring(0,2);\n \n char c = s.charAt(2);\n \n if(!map.containsKey(sub))\n map.put(sub, new ArrayList<>());\n \n map.get(sub).add(c);\n }\n \n return dfs(bottom, \"\", 0);\n }\n \n boolean dfs(String currBottom, String newBottom, int index){\n \n if(currBottom.length()==1)\n return true;\n if(index+1>=currBottom.length())\n return false;\n \n String sub = currBottom.substring(index,index+2);\n \n String state = currBottom+\" \"+newBottom+\" \"+index;\n \n if(dp.containsKey(state))\n return dp.get(state);\n \n if(map.containsKey(sub)){\n List letters = map.get(sub);\n \n for(char c:letters){\n if(index==currBottom.length()-2){\n if(dfs(newBottom+c, \"\", 0))\n {\n dp.put(state, true);\n return true;\n }\n }\n else if(dfs(currBottom, newBottom+c, index+1))\n {\n dp.put(state, true);\n return true;\n }\n }\n }\n \n dp.put(state, false);\n return false;\n }\n}\n", + "title": "756. Pyramid Transition Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top. To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks . The patterns are given as a list of three-letter strings allowed , where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. You start with a bottom row of blocks bottom , given as a single string, that you must use as the base of the pyramid. Given bottom and allowed , return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed , or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom." + ], + "examples": [ + { + "text": "Example 1: Input:bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]Output:trueExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid1-grid.jpg" + }, + { + "text": "Example 2: Input:bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]Output:falseExplanation:The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.", + "image": "https://assets.leetcode.com/uploads/2021/08/26/pyramid2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool \n \"\"\"\n dic = defaultdict(list)\n for i in allowed:\n dic[(i[0], i[1])].append(i[2])\n \n res = []\n \n def dfs(arr, nxt):\n #base case second floor and check top exists\n if len(arr) == 2 and dic[(arr[0], arr[1])]:\n return True\n \n #go to the next row now\n if len(arr) == len(nxt) + 1:\n return dfs(nxt, [])\n\n #keep iterating the same row\n if dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n for val in dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n if dfs(arr, nxt + [val]):\n return True\n return False\n \n return dfs(bottom, [])\n", + "title": "756. Pyramid Transition Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-2.jpg" + ], + "constraints": [ + "1 <= queens.length <= 63", + "queens[i].length == 2", + "0 <= queens[i][j] < 8", + "king.length == 2", + "0 <= king[0], king[1] < 8", + "At most one piece is allowed in a cell." + ], + "examples": [ + { + "text": "Example 1: Input:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]Output:[[0,1],[1,0],[3,3]]Explanation:The queen at [0,1] can attack the king cause they're in the same row. \nThe queen at [1,0] can attack the king cause they're in the same column. \nThe queen at [3,3] can attack the king cause they're in the same diagnal. \nThe queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. \nThe queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. \nThe queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.", + "image": null + }, + { + "text": "Example 2: Input:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]Output:[[2,2],[3,4],[4,4]]", + "image": null + }, + { + "text": "Example 3: Input:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]Output:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 56.88%) | Memory: 44 MB (Top 9.63%)\nclass Solution {\n public List> queensAttacktheKing(int[][] queens, int[] king) {\n List> res = new ArrayList<>();\n int r=king[0];\n int l=king[1];\n int [][]board =new int[8][8];\n int n=8;\n\n// 8 cases;\n// moving upward\n// moving downward\n// moving right\n// moving left\n// moving upper right diagonal\n// moving upper left diagonal'\n// moving lower left diagonal\n// moving lower right diagonal\n\n int i,j;\n for(i=0;i(Arrays.asList(r, j)));\n break;\n }\n }\n for(i=r;i(Arrays.asList(i, l)));\n break;\n }\n }\n for(i=r;i>=0;i--)\n {\n if(board[i][l]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, l)));\n break;\n\n }\n }\n for(j=l;j>=0;j--)\n {\n if(board[r][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(r, j)));\n break;\n\n }\n }\n for(i=r,j=l;i>=0 && j>=0;j--,i--)\n {\n if(board[i][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;j=0;j++,i--)\n {\n if(board[i][j]==1)\n {\n res.add(new ArrayList<>(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;i(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;j>=0 && i(Arrays.asList(i, j)));\n break;\n }\n }\n return res;\n }\n}", + "title": "1222. Queens That Can Attack the King", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-1.jpg", + "https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-2.jpg" + ], + "constraints": [ + "1 <= queens.length <= 63", + "queens[i].length == 2", + "0 <= queens[i][j] < 8", + "king.length == 2", + "0 <= king[0], king[1] < 8", + "At most one piece is allowed in a cell." + ], + "examples": [ + { + "text": "Example 1: Input:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]Output:[[0,1],[1,0],[3,3]]Explanation:The queen at [0,1] can attack the king cause they're in the same row. \nThe queen at [1,0] can attack the king cause they're in the same column. \nThe queen at [3,3] can attack the king cause they're in the same diagnal. \nThe queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. \nThe queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. \nThe queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.", + "image": null + }, + { + "text": "Example 2: Input:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]Output:[[2,2],[3,4],[4,4]]", + "image": null + }, + { + "text": "Example 3: Input:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]Output:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = []\n d = {(i[0],i[1]) : True for i in queens}\n def goUp(r,c):\n while r >=0:\n if (r,c) in d:\n ans.append([r,c])\n break\n r -= 1\n def goDown(r,c):\n while r < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n def goLeft(r,c):\n while c >= 0:\n if (r,c) in d:\n ans.append([r,c])\n break\n c -= 1\n def goRight(r,c):\n while c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n c += 1\n def goD1(r,c):\n while r >=0 and c >= 0:\n if (r,c) in d:\n ans.append([r,c])\n break\n r -= 1\n c -= 1\n def goD2(r,c):\n while r < 8 and c >= 0:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n c -= 1\n def goD3(r,c):\n while r < 8 and c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r += 1\n c += 1\n def goD4(r,c):\n while r >= 0 and c < 8:\n if (r,c) in d: \n ans.append([r,c])\n break\n r -= 1\n c += 1\n\n goUp(king[0],king[1])\n goDown(king[0],king[1])\n goLeft(king[0],king[1])\n goRight(king[0],king[1])\n goD1(king[0],king[1])\n goD2(king[0],king[1])\n goD3(king[0],king[1])\n goD4(king[0],king[1])\n\n return ans\n", + "title": "1222. Queens That Can Attack the King", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the array queries of positive integers between 1 and m , you have to process all queries[i] (from i=0 to i=queries.length-1 ) according to the following rules: Return an array containing the result for the given queries . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "In the beginning, you have the permutation P=[1,2,3,...,m] .", + "For the current i , find the position of queries[i] in the permutation P ( indexing from 0 ) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [3,1,2,1], m = 5Output:[2,1,2,1]Explanation:The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].", + "image": null + }, + { + "text": "Example 2: Input:queries = [4,1,2,2], m = 4Output:[3,1,2,0]", + "image": null + }, + { + "text": "Example 3: Input:queries = [7,5,5,8,3], m = 8Output:[6,5,0,7,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 39.19%) | Memory: 43.3 MB (Top 49.82%)\nclass Solution {\n public int[] processQueries(int[] queries, int m) {\n int[] results = new int[queries.length];\n ArrayList permutations = new ArrayList();\n\n // Filling the permuations array with numbers.\n for (int i = 0; i < m; i++)\n permutations.add(i+1);\n\n // Looping on the queries & checking their index in the permuations\n for (int i = 0; i < queries.length; i++) {\n int query = queries[i];\n for (int j = 0; j < permutations.size(); j++)\n if (permutations.get(j) == query) {\n results[i] = j;\n int temp = permutations.get(j);\n permutations.remove(j);\n permutations.add(0, temp);\n break;\n }\n }\n\n return results;\n\n }\n}", + "title": "1409. Queries on a Permutation With Key", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array queries of positive integers between 1 and m , you have to process all queries[i] (from i=0 to i=queries.length-1 ) according to the following rules: Return an array containing the result for the given queries . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "In the beginning, you have the permutation P=[1,2,3,...,m] .", + "For the current i , find the position of queries[i] in the permutation P ( indexing from 0 ) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:queries = [3,1,2,1], m = 5Output:[2,1,2,1]Explanation:The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1].", + "image": null + }, + { + "text": "Example 2: Input:queries = [4,1,2,2], m = 4Output:[3,1,2,0]", + "image": null + }, + { + "text": "Example 3: Input:queries = [7,5,5,8,3], m = 8Output:[6,5,0,7,5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n perm=[i for i in range(1,m+1)]\n res=[]\n for i in queries:\n ind=perm.index(i)\n res.append(ind)\n perm=[perm.pop(ind)]+perm\n return res\n", + "title": "1409. Queries on a Permutation With Key", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array points where points[i] = [x i , y i ] is the coordinates of the i th point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [x j , y j , r j ] describes a circle centered at (x j , y j ) with a radius of r j . For each query queries[j] , compute the number of points inside the j th circle. Points on the border of the circle are considered inside . Return an array answer , where answer[j] is the answer to the j th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 500", + "points[i].length == 2", + "0 <= x ​​​​​​i , y ​​​​​​i <= 500", + "1 <= queries.length <= 500", + "queries[j].length == 3", + "0 <= x j , y j <= 500", + "1 <= r j <= 500", + "All coordinates are integers." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]Output:[3,2,2]Explanation:The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-34-16.png" + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]Output:[2,3,2,4]Explanation:The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.", + "image": "https://assets.leetcode.com/uploads/2021/03/25/chrome_2021-03-25_22-42-07.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 16 ms (Top 100.00%) | Memory: 42.8 MB (Top 96.08%)\n\nclass Solution {\n public int[] countPoints(int[][] points, int[][] queries) {\n int len = queries.length;\n int[] ans = new int[len];\n\n for(int i=0;i List[int]:\n\t\tcircle = []\n\t\tfor x2, y2, radius in queries:\n\t\t\tcount = 0\n\t\t\tfor x1, y1 in points:\n\t\t\t\tdis = ((x2-x1)**2+(y2-y1)**2)**0.5 # Use the Distance Formula...\n\t\t\t\tif dis <= radius:\n\t\t\t\t\tcount += 1\n\t\t\tcircle.append(count)\n\t\treturn circle", + "title": "1828. Queries on Number of Points Inside a Circle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed array of strings nums , where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [k i , trim i ] . For each queries[i] , you need to: Return an array answer of the same length as queries , where answer[i] is the answer to the i th query. Note : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Trim each number in nums to its rightmost trim i digits.", + "Determine the index of the k i th smallest trimmed number in nums . If two trimmed numbers are equal, the number with the lower index is considered to be smaller.", + "Reset each number in nums to its original length." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]Output:[2,2,1,0]Explanation:1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2ndsmallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4thsmallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n Note that the trimmed number \"02\" is evaluated as 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]Output:[3,0]Explanation:1. Trimmed to the last digit, nums = [\"4\",\"7\",\"6\",\"4\"]. The 2ndsmallest number is 4 at index 3.\n There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2ndsmallest number is 24.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 526 ms (Top 46.46%) | Memory: 54.8 MB (Top 85.59%)\nclass Solution {\n public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {\n\n if (nums.length == 0)\n return new int[0];\n\n int[] result = new int[queries.length];\n int strLen = nums[0].length();\n int[] index = new int[1];\n\n PriorityQueue queue = new PriorityQueue<>((a, b) -> {\n for (int i = index[0]; i < strLen; i++) {\n if (nums[a].charAt(i) != nums[b].charAt(i))\n return nums[b].charAt(i) - nums[a].charAt(i);\n }\n\n return b - a;\n });\n\n for (int i = 0; i < queries.length; i++) {\n index[0] = strLen - queries[i][1];\n queue.clear();\n\n for (int j = 0; j < nums.length; j++) {\n queue.add(j);\n if (queue.size() > queries[i][0])\n queue.poll();\n }\n\n result[i] = queue.poll();\n }\n\n return result;\n }\n}", + "title": "2343. Query Kth Smallest Trimmed Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of strings nums , where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [k i , trim i ] . For each queries[i] , you need to: Return an array answer of the same length as queries , where answer[i] is the answer to the i th query. Note : Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Trim each number in nums to its rightmost trim i digits.", + "Determine the index of the k i th smallest trimmed number in nums . If two trimmed numbers are equal, the number with the lower index is considered to be smaller.", + "Reset each number in nums to its original length." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]Output:[2,2,1,0]Explanation:1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2ndsmallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4thsmallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n Note that the trimmed number \"02\" is evaluated as 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]Output:[3,0]Explanation:1. Trimmed to the last digit, nums = [\"4\",\"7\",\"6\",\"4\"]. The 2ndsmallest number is 4 at index 3.\n There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2ndsmallest number is 24.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1276 ms (Top 58.39%) | Memory: 15.2 MB (Top 22.81%)\nfrom collections import defaultdict\n\nclass Solution:\n def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:\n sl = len(nums[0])\n len_to_sorted = defaultdict(list)\n ans = [0] * len(queries)\n\n for i, (k_smallest, trim_len) in enumerate(queries):\n if trim_len not in len_to_sorted:\n # have to trim\n for ni, num in enumerate(nums):\n len_to_sorted[trim_len].append( (int(num[sl - trim_len:]), ni) )\n\n len_to_sorted[trim_len] = sorted(len_to_sorted[trim_len])\n ans[i] = len_to_sorted[trim_len][k_smallest -1][1]\n\n return ans", + "title": "2343. Query Kth Smallest Trimmed Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of people, people , which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h i , k i ] represents the i th person of height h i with exactly k i other people in front who have a height greater than or equal to h i . Reconstruct and return the queue that is represented by the input array people . The returned queue should be formatted as an array queue , where queue[j] = [h j , k j ] is the attributes of the j th person in the queue ( queue[0] is the person at the front of the queue). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= people.length <= 2000", + "0 <= h i <= 10^6", + "0 <= k i < people.length", + "It is guaranteed that the queue can be reconstructed." + ], + "examples": [ + { + "text": "Example 1: Input:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]Output:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]Explanation:Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.", + "image": null + }, + { + "text": "Example 2: Input:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]Output:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 81.09%) | Memory: 53.8 MB (Top 84.02%)\nclass Solution {\n public int[][] reconstructQueue(int[][] people) {\n List result = new ArrayList<>(); //return value\n\n Arrays.sort(people, (a, b) -> {\n int x = Integer.compare(b[0], a[0]);\n if(x == 0) return Integer.compare(a[1], b[1]);\n else return x; });\n\n for(int[] p: people)\n result.add(p[1], p);\n\n return result.toArray(new int[people.length][2]);\n }\n}", + "title": "406. Queue Reconstruction by Height", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of people, people , which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [h i , k i ] represents the i th person of height h i with exactly k i other people in front who have a height greater than or equal to h i . Reconstruct and return the queue that is represented by the input array people . The returned queue should be formatted as an array queue , where queue[j] = [h j , k j ] is the attributes of the j th person in the queue ( queue[0] is the person at the front of the queue). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= people.length <= 2000", + "0 <= h i <= 10^6", + "0 <= k i < people.length", + "It is guaranteed that the queue can be reconstructed." + ], + "examples": [ + { + "text": "Example 1: Input:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]Output:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]Explanation:Person 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.", + "image": null + }, + { + "text": "Example 2: Input:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]Output:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n\t\tn = len(people)\n\t\tpeople.sort()\n\t\tans = [[]]*n\n\t\ti = 0\n\t\twhile people:\n\t\t\th,p = people.pop(0)\n\t\t\tcount= p\n\t\t\tfor i in range(n):\n\t\t\t\tif count== 0 and ans[i] == []:\n\t\t\t\t\tans[i] = [h,p]\n\t\t\t\t\tbreak\n\n\t\t\t\telif not ans[i] or (ans[i] and ans[i][0] >= h ):\n\t\t\t\t\tcount -= 1\n\t\treturn ans", + "title": "406. Queue Reconstruction by Height", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the i th rabbit. Given the array answers , return the minimum number of rabbits that could be in the forest . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= answers.length <= 1000", + "0 <= answers[i] < 1000" + ], + "examples": [ + { + "text": "Example 1: Input:answers = [1,1,2]Output:5Explanation:The two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.", + "image": null + }, + { + "text": "Example 2: Input:answers = [10,10,10]Output:11", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numRabbits(int[] answers) {\n HashMap map = new HashMap<>();\n int count = 0;\n \n for(int ele : answers) {\n \n if(!map.containsKey(ele+1)) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else if(map.get(ele+1) == ele+1) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else {\n int freq = map.get(ele+1);\n map.put(ele+1, freq+1);\n }\n }\n \n return count;\n }\n}\n", + "title": "781. Rabbits in Forest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the i th rabbit. Given the array answers , return the minimum number of rabbits that could be in the forest . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= answers.length <= 1000", + "0 <= answers[i] < 1000" + ], + "examples": [ + { + "text": "Example 1: Input:answers = [1,1,2]Output:5Explanation:The two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.", + "image": null + }, + { + "text": "Example 2: Input:answers = [10,10,10]Output:11", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 54 ms (Top 35.1%) | Memory: 16.38 MB (Top 76.8%)\n\nclass Solution:\n def numRabbits(self, answers: List[int]) -> int:\n counts = {}\n count = 0\n\n for answer in answers:\n if answer == 0:\n # This must be the only rabbit of its color.\n count += 1\n elif answer not in counts or counts[answer] == 0:\n # This is the first time the color appears.\n counts[answer] = 1\n # Add all rabbits having this new color.\n count += answer + 1\n else:\n # Add one to how many times answer occurred.\n counts[answer] += 1\n if counts[answer] > answer:\n # If n+1 rabbits have said n,\n # this color group is complete.\n counts[answer] = 0\n \n return count", + "title": "781. Rabbits in Forest", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): For example, after commands \"AAR\" , your car goes to positions 0 --> 1 --> 3 --> 3 , and your speed goes to 1 --> 2 --> 4 --> -1 . Given a target position target , return the length of the shortest sequence of instructions to get there . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "When you get an instruction 'A' , your car does the following: position += speed speed *= 2", + "position += speed", + "speed *= 2", + "When you get an instruction 'R' , your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same.", + "If your speed is positive then speed = -1", + "otherwise speed = 1" + ], + "examples": [ + { + "text": "Example 1: Input:target = 3Output:2Explanation:The shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 6Output:5Explanation:The shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 86.11%) | Memory: 41.5 MB (Top 82.95%)\nclass Solution {\n public int racecar(int target) {\n Queue queue = new LinkedList<>();\n queue.add(new int[]{0, 1, 0});\n Set visited = new HashSet<>();\n\n while(!queue.isEmpty()){\n int[] item = queue.poll();\n int currPos = item[0];\n int currSpeed = item[1];\n int distance = item[2];\n\n if(currPos == target)\n return distance;\n\n // Choosing A\n int nextPos = currPos + currSpeed;\n int nextSpeed = currSpeed * 2;\n String posSpeed = new StringBuilder().append(nextPos).append(\",\").append(nextSpeed).toString();\n\n // If the particular state (position & speed) is not encountered earlier then we explore that state\n // And we also check if the nextPos is not beyond twice the size of target, then there is no point in exploring that route\n if(!visited.contains(posSpeed) && Math.abs(nextPos) < 2 * target){\n visited.add(posSpeed);\n queue.add(new int[]{nextPos, nextSpeed, distance + 1});\n }\n\n // Choosing R\n // We go in reverse only when we are moving away from the target in the positive or in the negative direction\n if((currPos + currSpeed > target && currSpeed > 0) || (currPos + currSpeed < target && currSpeed < 0)) {\n nextSpeed = currSpeed > 0 ? -1 : 1;\n posSpeed = new StringBuilder().append(currPos).append(\",\").append(nextSpeed).toString();\n\n if(!visited.contains(posSpeed) && Math.abs(currPos) < 2 * target){\n visited.add(posSpeed);\n queue.add(new int[]{currPos, nextSpeed, distance + 1});\n }\n }\n }\n return -1;\n }\n}", + "title": "818. Race Car", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): For example, after commands \"AAR\" , your car goes to positions 0 --> 1 --> 3 --> 3 , and your speed goes to 1 --> 2 --> 4 --> -1 . Given a target position target , return the length of the shortest sequence of instructions to get there . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "When you get an instruction 'A' , your car does the following: position += speed speed *= 2", + "position += speed", + "speed *= 2", + "When you get an instruction 'R' , your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same.", + "If your speed is positive then speed = -1", + "otherwise speed = 1" + ], + "examples": [ + { + "text": "Example 1: Input:target = 3Output:2Explanation:The shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.", + "image": null + }, + { + "text": "Example 2: Input:target = 6Output:5Explanation:The shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 95 ms (Top 46.38%) | Memory: 14.3 MB (Top 75.93%)\nclass Solution:\n def racecar(self, target: int) -> int:\n q = [(0, 1)]\n steps = 0\n\n while q:\n num = len(q)\n for i in range(num):\n pos, speed = q.pop(0)\n if pos == target:\n return steps\n q.append((pos+speed, speed*2))\n rev_speed = -1 if speed > 0 else 1\n if (pos+speed) < target and speed < 0 or (pos+speed) > target and speed > 0:\n q.append((pos, rev_speed))\n steps += 1", + "title": "818. Race Car", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1 . All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int m, int n) Initializes the object with the size of the binary matrix m and n .", + "int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1 .", + "void reset() Resets all the values of the matrix to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n[[3, 1], [], [], [], [], []]Output[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]ExplanationSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 45 ms (Top 62.26%) | Memory: 50.7 MB (Top 63.21%)\n// Swap Tail Element Solution\n// 1. Get a random number between [0, size-1]\n// 2. size - 1\n// 3. Get the index in map by the random map\n// 4. Update the flipped element with the tail element.\n// Time complexity: O(1) to init, flip, and reset\n// Space complexity: O(K), where K is the times of flip calls.\nclass Solution {\n private final int M, N, CAPACITY;\n private int size;\n private Random random;\n private Map map;\n\n public Solution(int m, int n) {\n M = m;\n N = n;\n CAPACITY = m * n;\n size = CAPACITY;\n random = new Random();\n map = new HashMap<>();\n }\n\n public int[] flip() {\n if (size <= 0) return new int[]{-1, -1}; // or throw exception.\n Integer rand = random.nextInt(size);\n size--;\n int idx = map.getOrDefault(rand, rand);\n Integer tail = map.getOrDefault(size, size);\n map.put(rand, tail);\n return new int[]{idx / N, idx % N};\n }\n\n public void reset() {\n map = new HashMap();\n size = CAPACITY;\n }\n}\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(m, n);\n * int[] param_1 = obj.flip();\n * obj.reset();\n */", + "title": "519. Random Flip Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1 . All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int m, int n) Initializes the object with the size of the binary matrix m and n .", + "int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1 .", + "void reset() Resets all the values of the matrix to be 0 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n[[3, 1], [], [], [], [], []]Output[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]ExplanationSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "from random import randint\n\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m = m\n self.n = n\n self.ones = set()\n\n def flip(self) -> List[int]:\n i, j = randint(0, self.m - 1), randint(0, self.n - 1)\n while (i, j) in self.ones:\n i, j = randint(0, self.m - 1), randint(0, self.n - 1)\n self.ones.add((i, j))\n return [i, j]\n\n def reset(self) -> None:\n self.ones.clear()\n", + "title": "519. Random Flip Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums with possible duplicates , randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the array nums .", + "int pick(int target) Picks a random index i from nums where nums[i] == target . If there are multiple valid i's, then each index should have an equal probability of returning." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]Output[null, 4, 0, 2]ExplanationSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 42.59%) | Memory: 55.80 MB (Top 31.28%)\n\nclass Solution {\n Random random;\n int[] origin;\n \n public Solution(int[] nums) {\n random = new Random();\n origin = nums;\n }\n \n public int pick(int target) {\n \n while(true){\n int idx = random.nextInt(origin.length);\n if(origin[idx] == target){\n return idx;\n }\n }\n }\n}\n", + "title": "398. Random Pick Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums with possible duplicates , randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the array nums .", + "int pick(int target) Picks a random index i from nums where nums[i] == target . If there are multiple valid i's, then each index should have an equal probability of returning." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]Output[null, 4, 0, 2]ExplanationSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n def __init__(self, nums: List[int]):\n #self.nums = nums\n #create a hash of values with their list of indices\n self.map = defaultdict(list)\n for i,v in enumerate(nums):\n self.map[v].append(i)\n \n\n def pick(self, target: int) -> int:\n return random.sample(self.map[target],1)[0]\n '''\n reservoir = 0\n count = 0\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n count+=1\n if random.random() < 1/count:\n reservoir = i\n return reservoir\n\n \n samp = []\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n samp.append(i)\n return (random.sample(samp,1))[0]\n '''\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(nums)\n# param_1 = obj.pick(target)", + "title": "398. Random Pick Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n and an array of unique integers blacklist . Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist . Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist .", + "int pick() Returns a random integer in the range [0, n - 1] and not in blacklist ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]Output[null, 0, 4, 1, 6, 1, 0, 4]ExplanationSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 841 ms (Top 10.38%) | Memory: 24.8 MB (Top 56.73%)\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n self.hashmap={}\n for b in blacklist:\n self.hashmap[b]=-1\n self.length=n-len(blacklist)\n flag=n-1\n for b in blacklist:\n if b int:\n seed=random.randrange(self.length)\n return self.hashmap.get(seed,seed)\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(n, blacklist)\n# param_1 = obj.pick()", + "title": "710. Random Pick with Blacklist", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the i th index. You need to implement the function pickIndex() , which randomly picks an index in the range [0, w.length - 1] ( inclusive ) and returns it. The probability of picking an index i is w[i] / sum(w) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if w = [1, 3] , the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25% ), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75% )." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\",\"pickIndex\"]\n[[[1]],[]]Output[null,0]ExplanationSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.", + "image": null + }, + { + "text": "Example 2: Input[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]Output[null,1,1,1,1,0]ExplanationSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 42.43%) | Memory: 56.3 MB (Top 78.21%)\nclass Solution {\n\n private int[] prefixSum;\n private Random random;\n\n public Solution(int[] w) {\n for (int i = 1; i < w.length; i++)\n w[i] += w[i - 1];\n prefixSum = w;\n random = new Random();\n }\n\n public int pickIndex() {\n int num = 1 + random.nextInt(prefixSum[prefixSum.length - 1]); // Generate random number between 1 and total sum of weights\n int left = 0;\n int right = prefixSum.length - 1;\n\n while (left < right) {\n int mid = (left + right) / 2;\n if (num == prefixSum[mid])\n return mid;\n else if (num < prefixSum[mid])\n right = mid;\n else\n left = mid + 1;\n }\n return left;\n }\n}", + "title": "528. Random Pick with Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the i th index. You need to implement the function pickIndex() , which randomly picks an index in the range [0, w.length - 1] ( inclusive ) and returns it. The probability of picking an index i is w[i] / sum(w) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if w = [1, 3] , the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25% ), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75% )." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\",\"pickIndex\"]\n[[[1]],[]]Output[null,0]ExplanationSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.", + "image": null + }, + { + "text": "Example 2: Input[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]Output[null,1,1,1,1,0]ExplanationSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n\tdef __init__(self, w):\n\t\t\"\"\"\n\t\t:type w: List[int]\n\t\t\"\"\"\n\t\t#Cumulative sum\n\t\tself.list = [0] * len(w)\n\n\t\ts = 0\n\t\tfor i, n in enumerate(w):\n\t\t\ts += n\n\t\t\tself.list[i] = s\n\n\n\tdef pickIndex(self):\n\t\t\"\"\"\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n", + "title": "528. Random Pick with Weight", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [a i , b i , x i , y i ] indicates that (a i , b i ) is the bottom-left corner point of the i th rectangle and (x i , y i ) is the top-right corner point of the i th rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int[][] rects) Initializes the object with the given rectangles rects .", + "int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]Output[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]ExplanationSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n int[][] rects;\n TreeMap weightedRectIndex = new TreeMap<>();\n int nPoints = 0;\n \n Random rng = new Random();\n\n public Solution(int[][] rects) {\n this.rects = rects;\n int index = 0;\n for (int[] rect : rects) {\n\t\t // inserts cumulative weight key pointing to rectangle index\n weightedRectIndex.put(nPoints, index++);\n nPoints += width(rect) * height(rect);\n }\n }\n \n public int[] pick() {\n\t // generates random point within total weight\n int point = rng.nextInt(nPoints);\n\t\t// finds appropriate rectangle\n var entry = weightedRectIndex.floorEntry(point);\n\t\t// find point within the current rectangle\n int rectPoint = point - entry.getKey();\n int[] rect = rects[entry.getValue()];\n return new int[]{\n rect[0] + rectPoint % width(rect), \n rect[1] + rectPoint / width(rect)};\n }\n \n private int width(int[] rect) {\n return rect[2] - rect[0] + 1;\n }\n \n private int height(int[] rect) {\n return rect[3] - rect[1] + 1;\n }\n}\n", + "title": "497. Random Point in Non-overlapping Rectangles", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [a i , b i , x i , y i ] indicates that (a i , b i ) is the bottom-left corner point of the i th rectangle and (x i , y i ) is the top-right corner point of the i th rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. Note that an integer point is a point that has integer coordinates. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int[][] rects) Initializes the object with the given rectangles rects .", + "int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]Output[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]ExplanationSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]", + "image": "https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \"\"\"\n 1 <= rects.length <= 100\n rects[i].length == 4\n -10^9 <= ai < xi <= 10^9\n -10^9 <= bi < yi <= 10^9\n xi - ai <= 2000\n yi - bi <= 2000\n All the rectangles do not overlap.\n At most 10^4 calls will be made to pick.\n \"\"\"\n\n def __init__(self, rects: List[List[int]]):\n self.rects = rects\n self.n_range = list(range(len(self.rects)))\n self.weights = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]\n\n def pick(self) -> List[int]:\n rect = self.rects[choices(self.n_range, self.weights, k=1)[0]]\n return [randint(rect[0], rect[2]), randint(rect[1], rect[3])]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(rects)\n# param_1 = obj.pick()\n", + "title": "497. Random Point in Non-overlapping Rectangles", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n matrix M initialized with all 0 's and an array of operations ops , where ops[i] = [a i , b i ] means M[x][y] should be incremented by one for all 0 <= x < a i and 0 <= y < b i . Count and return the number of maximum integers in the matrix after performing all the operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 4 * 10^4", + "0 <= ops.length <= 10^4", + "ops[i].length == 2", + "1 <= a i <= m", + "1 <= b i <= n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, ops = [[2,2],[3,3]]Output:4Explanation:The maximum integer in M is 2, and there are four of it in M. So return 4.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg" + }, + { + "text": "Example 2: Input:m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]Output:4", + "image": null + }, + { + "text": "Example 3: Input:m = 3, n = 3, ops = []Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 12.57%) | Memory: 45.3 MB (Top 7.43%)\nclass Solution {\n public int maxCount(int m, int n, int[][] ops) {\n int minRow=m,minCol=n;\n for(int[] op:ops){\n minRow=Math.min(minRow,op[0]);\n minCol=Math.min(minCol,op[1]);\n }\n return minRow*minCol;\n }\n}", + "title": "598. Range Addition II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n matrix M initialized with all 0 's and an array of operations ops , where ops[i] = [a i , b i ] means M[x][y] should be incremented by one for all 0 <= x < a i and 0 <= y < b i . Count and return the number of maximum integers in the matrix after performing all the operations . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 4 * 10^4", + "0 <= ops.length <= 10^4", + "ops[i].length == 2", + "1 <= a i <= m", + "1 <= b i <= n" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 3, ops = [[2,2],[3,3]]Output:4Explanation:The maximum integer in M is 2, and there are four of it in M. So return 4.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg" + }, + { + "text": "Example 2: Input:m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]Output:4", + "image": null + }, + { + "text": "Example 3: Input:m = 3, n = 3, ops = []Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n if not ops:\n return m*n\n else:\n x,y = zip(*ops)\n return min(x) * min(y)\n", + "title": "598. Range Addition II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ). Example 1:", + "description_images": [], + "constraints": [ + "RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr .", + "int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]Output[null, 1, 2]ExplanationRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.", + "image": null + } + ], + "follow_up": null, + "solution": "class RangeFreqQuery {\n //Use map's key to store arr's value, map's value to keep \n HashMap> map;\n public RangeFreqQuery(int[] arr) {\n //O(nlog(n))\n map = new HashMap<>();\n for(int i = 0; i < arr.length; i++){\n map.putIfAbsent(arr[i], new TreeMap<>());\n TreeMap tree = map.get(arr[i]);\n //i = value's location\n //tree.size() = cummulative arr's value count - 1\n tree.put(i, tree.size());\n }\n }\n \n public int query(int left, int right, int value) {\n //O(log(n))\n \n //check if value exist in map\n if(!map.containsKey(value)){\n return 0;\n }\n TreeMap tree = map.get(value);\n \n //check if there exist position >= left and position <= right\n //if not, return 0\n if(tree.ceilingKey(left) == null || tree.floorKey(right) == null){\n return 0;\n }\n //get leftMost position's cummulative count\n int leftMost = tree.get(tree.ceilingKey(left));\n //get rightMost position's cummulative count\n int rightMost = tree.get(tree.floorKey(right));\n \n return rightMost - leftMost + 1;\n }\n}\n\n/**\n * Your RangeFreqQuery object will be instantiated and called as such:\n * RangeFreqQuery obj = new RangeFreqQuery(arr);\n * int param_1 = obj.query(left,right,value);\n */\n", + "title": "2080. Range Frequency Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design a data structure to find the frequency of a given value in a given subarray. The frequency of a value in a subarray is the number of occurrences of that value in the subarray. Implement the RangeFreqQuery class: A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right ( inclusive ). Example 1:", + "description_images": [], + "constraints": [ + "RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr .", + "int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]Output[null, 1, 2]ExplanationRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3295 ms (Top 30.98%) | Memory: 53.7 MB (Top 24.88%)\nclass RangeFreqQuery:\n def __init__(self, arr: List[int]):\n self.l = [[] for _ in range(10001)]\n for i, v in enumerate(arr):\n self.l[v].append(i)\n def query(self, left: int, right: int, v: int) -> int:\n return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)", + "title": "2080. Range Frequency Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right . Implement the RangeModule class: Example 1:", + "description_images": [], + "constraints": [ + "RangeModule() Initializes the object of the data structure.", + "void addRange(int left, int right) Adds the half-open interval [left, right) , tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.", + "boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.", + "void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]Output[null, null, null, true, false, true]ExplanationRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 91 ms (Top 31.23%) | Memory: 73.2 MB (Top 20.97%)\nclass RangeModule {\n TreeMap map;\n\n public RangeModule() {\n map = new TreeMap<>();\n }\n\n public void addRange(int left, int right) {\n // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of right. Like this:\n // [left, right)\n // [l1, r1) [l2, r2)\n // Note: l2 could be the same as l1, so they are either both null or both non-null\n Integer l1 = map.floorKey(left);\n Integer l2 = map.floorKey(right);\n\n // try to visualize each case, and what to do based on r1\n if (l1 == null && l2 == null) {\n map.put(left, right);\n }\n else if (l1 != null && map.get(l1) >= left) {\n map.put(l1, Math.max(right, map.get(l2))); // r2 will always be greater than r1, so no need to check r1\n }\n else {\n map.put(left, Math.max(right, map.get(l2)));\n }\n\n // we don't want to remove the range starts at left, so left should be exclusive.\n // but we want to remove the one starts at right, so right should be inclusive.\n map.subMap(left, false, right, true).clear();\n }\n\n public boolean queryRange(int left, int right) {\n Integer l = map.floorKey(left);\n if (l != null && map.get(l) >= right) {\n return true;\n }\n return false;\n }\n\n public void removeRange(int left, int right) {\n Integer l1 = map.lowerKey(left); // I used lowerKey here, since we don't care about the range starting at left, as it should be removed\n Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right\n\n // do this first, in case l1 == l2, the later one will change r1(or r2 in this case)\n if (l2 != null && map.get(l2) > right) {\n map.put(right, map.get(l2));\n }\n\n if (l1 != null && map.get(l1) > left) {\n map.put(l1, left);\n }\n\n // range that starts at left should be removed, so left is inclusive\n // range that starts at right should be kept, so right is exclusive\n map.subMap(left, true, right, false).clear();\n }\n}", + "title": "715. Range Module", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them. A half-open interval [left, right) denotes all the real numbers x where left <= x < right . Implement the RangeModule class: Example 1:", + "description_images": [], + "constraints": [ + "RangeModule() Initializes the object of the data structure.", + "void addRange(int left, int right) Adds the half-open interval [left, right) , tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.", + "boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.", + "void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]Output[null, null, null, true, false, true]ExplanationRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)", + "image": null + } + ], + "follow_up": null, + "solution": "from bisect import bisect_left as bl, bisect_right as br\nclass RangeModule:\n\n def __init__(self):\n self._X = []\n\n def addRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) or idx(right) is odd, it's in a interval. So don't add it. \n # If idx(left) or idx(right) is even, it's not in any interval. So add it as new interval \n # Slice array[idx(left) : idx(right)]\n # 1) both odd: Nothing is added. Merge all middle intervals. \n # 2) both even: Add new intervals. Merge all middle intervals\n # 3) idx(left) is even: update start point of next interval with left\n # 4) idx(right) is even: update end point of previous interval with right\n # Bisect_left vs. Bisect_right\n # left need to proceed all interval closing at left, so use Bisect_left\n # right need to go after all interval openning at right, so use Bisect_right\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0)\n \n\n def queryRange(self, left: int, right: int) -> bool:\n # Main logic \n # If idx of left/right is odd, it's in a interval. Else it's not. \n # If idx of left&right is the same, they're in the same interval\n # Bisect_left vs. Bisect_right\n # [start, end). Start is included. End is not. \n # so use bisect_right for left \n # so use bisect_left for right \n i, j = br(self._X, left), bl(self._X, right)\n return i == j and i % 2 == 1\n \n\n def removeRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) is odd, the interval that contains left need to change end point to left \n # If idx(right) is odd, the interval that contains right need to change start point to right\n # Else, everything from idx(left) to idx(right) is removed. Nothing is changed. \n # Bisect_left vs. Bisect_right\n # Same as addRange\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)\n\n", + "title": "715. Range Module", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root node of a binary search tree and two integers low and high , return the sum of values of all nodes with a value in the inclusive range [low, high] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 * 10^4 ] .", + "1 <= Node.val <= 10^5", + "1 <= low <= high <= 10^5", + "All Node.val are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,15,3,7,null,18], low = 7, high = 15Output:32Explanation:Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10Output:23Explanation:Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private int sum = 0;\n public int rangeSumBST(TreeNode root, int low, int high) {\n dfs(root, low, high);\n return sum;\n }\n \n public void dfs(TreeNode root, int low, int high){\n if(root == null) return;\n \n if(root.val < low) dfs(root.right, low, high);\n else if(root.val > high) dfs(root.left, low, high);\n \n if(root.val >= low && root.val <= high) {\n sum += root.val;\n dfs(root.left, low, high);\n dfs(root.right, low, high);\n }\n \n }\n}\n", + "title": "938. Range Sum of BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root node of a binary search tree and two integers low and high , return the sum of values of all nodes with a value in the inclusive range [low, high] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 2 * 10^4 ] .", + "1 <= Node.val <= 10^5", + "1 <= low <= high <= 10^5", + "All Node.val are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,15,3,7,null,18], low = 7, high = 15Output:32Explanation:Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10Output:23Explanation:Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 106 ms (Top 94.04%) | Memory: 24.40 MB (Top 92.45%)\n\nclass Solution:\n def rangeSumBST(self, root, L, R):\n if not root:\n return 0\n \n if L <= root.val <= R:\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n else:\n return self.rangeSumBST(root.left, L, R)\n\n\n\n", + "title": "938. Range Sum of BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right ( indexed from 1 ) , inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 100", + "1 <= left <= right <= n * (n + 1) / 2" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], n = 4, left = 1, right = 5Output:13Explanation:All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4], n = 4, left = 3, right = 4Output:6Explanation:The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4], n = 4, left = 1, right = 10Output:50", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static int mod=(int)1e9+7;\n public int rangeSum(int[] nums, int n, int left, int right) {\n \n PriorityQueue pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]);\n \n for(int i=0;i=left){\n ans=(ans+k[1])%mod;\n }\n if(k[0]+1 int:\n return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]\n", + "title": "303. Range Sum Query - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class: Example 1:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray {\n SegmentTree s;\n public NumArray(int[] nums) {\n s = new SegmentTree(nums);\n s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built\n }\n \n public void update(int index, int val) {\n int oldvalue = s.arr[index];//Find old value with traditional array, which is O(1) time complexity\n s.arr[index] = val;//Set our array so that there will be no contradictions if we ever rebuild.\n //If we are going use build function only once, then we don't need to update our traditional array. \n s.update(s.root, val, index, oldvalue);//Call class' function\n }\n \n public int sumRange(int left, int right) {\n return s.rangeSum(s.root, left, right);\n }\n}\n\nclass Node {\n int s;//inclusive label\n int e;//inclusive label\n int val;\n Node left;\n Node right;\n}\n\nclass SegmentTree {\n Node root;\n int[] arr;\n\n SegmentTree(int [] arr) {\n this.arr = arr;\n }\n\n public Node build(int start, int end, int[] arr) {\n //Start and End integers have nothing to do with building of our SegmentTree, you may ignore them for now\n //They are needed for querying and updating, so that we can use binary search.\n Node temp = new Node();\n if (arr.length == 1) {//which means we are setting a node equal to an element of arr\n temp.val = arr[0];\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n } else if (arr.length == 0 || start > end || start < 0 || end < 0) {\n return new Node();// may be better\n } else {\n //left = build(start, mid but add 1 if array's length is not divisible by 2, left half of the passed array)\n temp.left = build(start, (start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), Arrays.copyOfRange(arr, 0, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0)));\n //right = build(start, mid but add 1 if array's length is not divisible by 2, right half of the passed array)\n temp.right = build((start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), end, Arrays.copyOfRange(arr, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0), arr.length));\n temp.val = temp.left.val + temp.right.val;\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n }\n return temp;//return this Node to one upper call so that this can be a child of it's parent\n }\n \n public int rangeSum(Node node, int l, int r) {\n if(node == null)\n {\n //Range is completely outside given range\n return 0;\n }\n if(l <= node.s && node.e <= r)\n {\n //Range is completely inside given range\n return node.val;\n }\n //Range is partially inside and partially outside the given range\n int mid = (node.s + node.e) / 2;\n int left = 0;\n int right = 0;\n if (l <= mid) {\n //For example let's say root's borders are 0:3, l,r=1:2\n //Then mid will be 1, then we will go into both directions because 1<=1, and 2>=1\n //Our next calls will be rS(root.left(which is 0:1), 1, 2) and rS(root.right(which is 2:3), 1, 2)\n //Left call's mid will be mid = (0+1)/2 = 0\n //Then 1<=0 ? No it's not, this is why left call's variable named left will be 0\n //Then 2>=0 ? Yes, we will call rS(root.left.right(which is 1:1), 1, 2)\n //Our left call's right call:\n //1:1 is completely inside 1:2, return the value it holds(equals to arr[1] if our arr is up to date)\n //Our original call's left will be arr[1]\n //Let's calculate our first right function\n //With same reasoning, our right function will go to left and be root.right.left(which is 2:2)\n //Our original call's right will be arr[2]\n //Our original/first function will return left + right, which is in fact [1:2] inclusive\n left = rangeSum(node.left, l, r);\n } \n if (r >= mid) {\n right = rangeSum(node.right, l, r);\n }\n return (left + right);\n }\n //What we are doing is, going downwards in our tree while we update the values we touch upon\n //We need to update root always, since it is sum of every element\n //After that we find mid which is mid value of our current node's start and end(inclusive)\n //At first call this will be (0+arr.length)/2 => mid\n //If given idx is bigger than mid, then we need to keep searching at right branch\n //That is why we call the function with root.right as our new root\n //If given idx is smaller and equals to mid, then we search at left branch\n //Why did we include equality too? Because I built my tree this way.(where equal things go left)\n //If idx is between our root's borders then we will decrease by the old value, increase by the new value.\n //If root equals null, we won't do anything\n //We update our traditional array at above.\n public void update(Node root, int value, int idx, int oldvalue) {\n if (root == null) {\n return;\n }\n int mid = (root.e + root.s) / 2;\n if (idx <= root.e && idx >= root.s) {\n root.val -= oldvalue;\n root.val += value;\n } if (idx > mid) {\n update(root.right, value, idx, oldvalue);\n } else if (idx <= mid) {\n update(root.left, value, idx, oldvalue);\n }\n }\n}\n", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class: Example 1:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray:\n nums = []\n s = 0\n l = 0\n \n def __init__(self, nums: List[int]):\n self.nums = nums\n self.s = sum(nums)\n self.l = len(nums)\n\n def update(self, index: int, val: int) -> None:\n self.s -= self.nums[index]\n self.nums[index] = val\n self.s += self.nums[index]\n\n def sumRange(self, left: int, right: int) -> int:\n if right - left > self.l // 2:\n ans = sum(self.nums[:left]) + sum(self.nums[right + 1:])\n return self.s - ans\n else:\n return sum(self.nums[left: right + 1])\n", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D matrix matrix , handle multiple queries of the following type: Implement the NumMatrix class: You must design an algorithm where sumRegion works on O(1) time complexity. Example 1:", + "description_images": [], + "constraints": [ + "Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]Output[null, 8, 11, 12]ExplanationNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)", + "image": "https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" + } + ], + "follow_up": null, + "solution": "class NumMatrix {\n\n int mat[][];\n public NumMatrix(int[][] matrix) {\n mat = matrix;\n int rows = mat.length;\n int cols = mat[0].length;\n \n for(int i = 0; i< rows; i++)\n {\n for(int j = 0; j < cols; j++) \n {\n if(i > 0) mat[i][j] += mat[i-1][j];\n if(j > 0) mat[i][j] += mat[i][j-1];\n if(i>0 && j > 0) mat[i][j] -= mat[i-1][j-1];\n }\n }\n \n }\n \n public int sumRegion(int row1, int col1, int row2, int col2) {\n int res = mat[row2][col2];\n if(row1 > 0) res -= mat[row1-1][col2];\n if(col1 > 0) res -= mat[row2][col1-1];\n if(row1> 0 && col1 > 0) res += mat[row1-1][col1-1];\n \n return res;\n }\n}\n", + "title": "304. Range Sum Query 2D - Immutable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D matrix matrix , handle multiple queries of the following type: Implement the NumMatrix class: You must design an algorithm where sumRegion works on O(1) time complexity. Example 1:", + "description_images": [], + "constraints": [ + "Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]Output[null, 8, 11, 12]ExplanationNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)", + "image": "https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 3180 ms (Top 18.96%) | Memory: 24.7 MB (Top 69.46%)\n\nclass NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n m, n = len(matrix), len(matrix[0])\n # Understand why we need to create a new matrix with extra one row/column\n self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)]\n for r in range(1, m + 1):\n for c in range(1, n + 1):\n self.sum[r][c] = self.sum[r - 1][c] + self.sum[r][c - 1] - self.sum[r - 1][c - 1] + matrix[r - 1][c - 1]\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n r1, c1, r2, c2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1\n return self.sum[r2][c2] - self.sum[r1 - 1][c2] - self.sum[r2][c1 - 1] + self.sum[r1 - 1][c1 - 1]\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)", + "title": "304. Range Sum Query 2D - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]Output:\"ACB\"Explanation:Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.\nTeam B was ranked second by 2 voters and was ranked third by 3 voters.\nTeam C was ranked second by 3 voters and was ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]Output:\"XWYZ\"Explanation:X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]Output:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"Explanation:Only one voter so his votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 71.24%) | Memory: 43.7 MB (Top 79.83%)\nclass Solution {\n public String rankTeams(String[] votes) {\n int n = votes.length;\n int teams = votes[0].length();\n Map map = new HashMap<>();\n List chars = new ArrayList<>();\n\n for(int i = 0 ; i < teams ; i++) {\n char team = votes[0].charAt(i);\n map.put(team, new int[teams]);\n chars.add(team);\n }\n\n for(int i = 0 ; i < n ; i++) {\n String round = votes[i];\n for(int j = 0 ; j < round.length() ; j++) {\n map.get(round.charAt(j))[j]+=1;\n }\n }\n\n chars.sort((a,b) -> {\n int[] l1 = map.get(a);\n int[] l2 = map.get(b);\n for(int i = 0 ; i < l1.length; i++) {\n if(l1[i] < l2[i]) {\n return 1;\n }\n else if(l1[i] > l2[i]) {\n return -1;\n }\n }\n return a.compareTo(b);\n });\n\n StringBuilder sb = new StringBuilder();\n for(char c : chars) {\n sb.append(c);\n }\n return sb.toString();\n }\n}", + "title": "1366. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]Output:\"ACB\"Explanation:Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.\nTeam B was ranked second by 2 voters and was ranked third by 3 voters.\nTeam C was ranked second by 3 voters and was ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]Output:\"XWYZ\"Explanation:X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]Output:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"Explanation:Only one voter so his votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "#[\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\n#d = {\n# \"A\": [5, 0, 0],\n# \"B\": [0, 2, 3],\n# \"C\": [0, 3, 2]\n#}\n#keys represent the candidates\n#index of array in dict represent the rank\n#value of array item represent number of votes casted\n#ref: https://www.programiz.com/python-programming/methods/built-in/sorted\nclass Solution:\n #T=O(mn + mlgm), S=O(mn)\n\t#n=number of votes\n\t#m=number of candidates and m(number of ranks) is constant(26)\n def rankTeams(self, votes: List[str]) -> str:\n d = {}\n #build the dict\n #T=O(mn), S=O(mn)\n\t\t#n=number of votes, m=number of candidates(26)\n for vote in votes:\n for i, c in enumerate(vote):\n #if key not in dict\n if c not in d:\n #d[char] = [0, 0, 0]\n d[c] = [0]*len(vote)\n #increment the count of votes for each rank\n #d[\"A\"][0] = 1\n d[c][i] += 1\n #sort the dict keys in ascending order because if there is a tie we return in ascending order\n\t\t#sorted uses a stable sorting algorithm\n #T=O(mlgm), S=O(m)\n vote_names = sorted(d.keys()) #d.keys()=[\"A\", \"B\", \"C\"]\n #sort the dict keys based on votes for each rank in descending order\n #T=O(mlgm), S=O(m)\n #sorted() always returns a list\n vote_rank = sorted(vote_names, reverse=True, key= lambda x: d[x])\n #join the list\n return \"\".join(vote_rank)\n", + "title": "1366. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix , return a new matrix answer where answer[row][col] is the rank of matrix[row][col] . The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The test cases are generated so that answer is unique under the given rules. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The rank is an integer starting from 1 .", + "If two elements p and q are in the same row or column , then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q)", + "If p < q then rank(p) < rank(q)", + "If p == q then rank(p) == rank(q)", + "If p > q then rank(p) > rank(q)", + "The rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2],[3,4]]Output:[[1,2],[2,3]]Explanation:The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[7,7],[7,7]]Output:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" + }, + { + "text": "Example 3: Input:matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]Output:[[4,2,3],[1,3,4],[5,1,6],[1,3,4]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 209 ms (Top 84.06%) | Memory: 75.6 MB (Top 97.21%)\nclass Solution {\n int[] parent;\n public int[][] matrixRankTransform(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] answer = new int[m][n];\n\n // GROUP BY MATRIX VAL -> {X,Y}\n TreeMap> map = new TreeMap<>();\n for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n int[] xy = {i,j};\n int val = matrix[i][j];\n if(map.get(val) == null)\n map.put(val, new ArrayList<>());\n map.get(val).add(xy);\n }\n }\n\n // INITIALIZE MIN-RANK ARRAY FOR EVERY COL/ROW\n int[] minX = new int[m];\n int[] minY = new int[n];\n\n for(Integer key : map.keySet()){\n List list = map.get(key);\n\n // SPLIT TO GROUPS USING UNION FIND FOR VALs IN SAME COL/ROW\n int lSize = list.size();\n parent = new int[lSize];\n for(int i = 0; i < lSize; i++)\n parent[i] = i;\n\n // Group the xy by col and row then union by row & by col\n HashMap> xMap = new HashMap<>();\n HashMap> yMap = new HashMap<>();\n for(int i = 0; i < lSize; i++){\n int[] xy = list.get(i);\n int x = xy[0];\n int y = xy[1];\n\n if(xMap.get(x) == null)\n xMap.put(x, new ArrayList<>());\n if(yMap.get(y) == null)\n yMap.put(y, new ArrayList<>());\n xMap.get(x).add(i);\n yMap.get(y).add(i);\n }\n\n // union by X\n for(Integer xKey : xMap.keySet()){\n List xList = xMap.get(xKey);\n for(int i = 1; i < xList.size(); i++){\n union(xList.get(i-1), xList.get(i));\n }\n }\n\n // union by Y\n for(Integer yKey : yMap.keySet()){\n List yList = yMap.get(yKey);\n for(int i = 1; i < yList.size(); i++){\n union(yList.get(i-1), yList.get(i));\n }\n }\n\n HashMap> group = new HashMap<>();\n for(int i = 0; i < lSize; i++){\n int grp = find(i);\n if(group.get(grp) == null)\n group.put(grp, new ArrayList<>());\n group.get(grp).add(list.get(i));\n }\n\n // SET ANSWER FOR EACH GROUP\n for(Integer grpKey : group.keySet()){\n int max = 1;\n List sublist = group.get(grpKey);\n\n // FIND MAX-RANK FOR THIS GROUP\n for(int[] xy : sublist){\n int x = xy[0];\n int y = xy[1];\n\n max = Math.max(max, Math.max(minX[x], minY[y]));\n }\n\n // UPDATE ANSWER = MAX-RANK AND SET NEW MIN-RANK FOR ROW/COL = MAX-RANK+1\n for(int[] xy : sublist){\n int x = xy[0];\n int y = xy[1];\n answer[x][y] = max;\n minX[x] = max+1;\n minY[y] = max+1;\n }\n }\n }\n return answer;\n }\n\n // UNION FIND IMPL\n void union(int a, int b){\n int pa = find(a);\n int pb = find(b);\n parent[pb] = pa;\n }\n\n int find(int a){\n int pa = parent[a];\n if(pa != a){\n parent[a] = find(pa);\n return parent[a];\n } else\n return a;\n }\n}", + "title": "1632. Rank Transform of a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix , return a new matrix answer where answer[row][col] is the rank of matrix[row][col] . The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: The test cases are generated so that answer is unique under the given rules. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The rank is an integer starting from 1 .", + "If two elements p and q are in the same row or column , then: If p < q then rank(p) < rank(q) If p == q then rank(p) == rank(q) If p > q then rank(p) > rank(q)", + "If p < q then rank(p) < rank(q)", + "If p == q then rank(p) == rank(q)", + "If p > q then rank(p) > rank(q)", + "The rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2],[3,4]]Output:[[1,2],[2,3]]Explanation:The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[7,7],[7,7]]Output:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" + }, + { + "text": "Example 3: Input:matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]Output:[[4,2,3],[1,3,4],[5,1,6],[1,3,4]]", + "image": "https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 3042 ms (Top 71.65%) | Memory: 50.4 MB (Top 92.27%)\nclass Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n m, n = len(matrix), len(matrix[0])\n rank = [0]*(m + n)\n d = defaultdict(list)\n for i in range(m):\n for j in range(n):\n d[matrix[i][j]].append((i,j))\n def find(i):\n if p[i] != i:\n p[i] = find(p[i])\n return p[i]\n def union(i,j):\n pi, pj = find(i), find(j)\n p[pi] = pj\n newrank[pj] = max(newrank[pi], newrank[pj])\n for e in sorted(d):\n p = list(range(m+n))\n newrank = rank[:]\n for i, j in d[e]:\n union(i,m+j)\n for i, j in d[e]:\n rank[i] = rank[m+j] = matrix[i][j] = newrank[find(i)] + 1\n return matrix", + "title": "1632. Rank Transform of a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , replace each element with its rank. The rank represents how large the element is. The rank has the following rules: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Rank is an integer starting from 1.", + "The larger the element, the larger the rank. If two elements are equal, their rank must be the same.", + "Rank should be as small as possible." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [40,10,20,30]Output:[4,1,2,3]Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.", + "image": null + }, + { + "text": "Example 2: Input:arr = [100,100,100]Output:[1,1,1]Explanation: Same elements share the same rank.", + "image": null + }, + { + "text": "Example 3: Input:arr = [37,12,28,9,100,56,80,5,12]Output:[5,3,4,2,8,6,7,1,3]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 325 ms (Top 99.70%) | Memory: 33.7 MB (Top 29.42%)\nclass Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n arr_set = list(sorted(set(arr)))\n rank = {}\n for i, e in enumerate(arr_set):\n rank[e] = i+1\n return [ rank[e] for e in arr]", + "title": "1331. Rank Transform of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"Output:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 19.48%) | Memory: 44.60 MB (Top 8.88%)\n\nclass Solution {\n public boolean canConstruct(String ransomNote, String magazine) {\n char[] rs = ransomNote.toCharArray();\n char[] ms = magazine.toCharArray();\n \n HashMap rm = new HashMap<>();\n HashMap mz = new HashMap<>();\n \n for (char c : rs) {\n if (rm.containsKey(c)) {\n rm.put(c, rm.get(c) + 1);\n } else {\n rm.put(c, 1);\n }\n }\n\n for (char c : ms) {\n if (mz.containsKey(c)) {\n mz.put(c, mz.get(c) + 1);\n } else {\n mz.put(c, 1);\n }\n }\n\n for (char c : rm.keySet()) {\n if (!mz.containsKey(c) || mz.get(c) < rm.get(c)) {\n return false;\n }\n }\n return true; \n }\n}\n", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"Output:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nclass Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n \n ransomNote_count = dict(Counter(ransomNote))\n magazine_count = dict(Counter(magazine))\n \n for key , value in ransomNote_count.items():\n \n if key in magazine_count:\n if value <= magazine_count[key]:\n continue\n else:\n return False\n \n return False\n \n return True\n", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are standing at position 0 on an infinite number line. There is a destination at position target . You can make some number of moves numMoves so that: Given the integer target , return the minimum number of moves required (i.e., the minimum numMoves ) to reach the destination . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "On each move, you can either go left or right.", + "During the i th move (starting from i == 1 to i == numMoves ), you take i steps in the chosen direction." + ], + "examples": [ + { + "text": "Example 1: Input:target = 2Output:3Explanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to -1 (2 steps).\nOn the 3rdmove, we step from -1 to 2 (3 steps).", + "image": null + }, + { + "text": "Example 2: Input:target = 3Output:2Explanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to 3 (2 steps).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reachNumber(int target) {\n int sum =0 ,steps = 0;\n if(target ==0) return 0;\n target = Math.abs(target);\n while(sum< target){\n sum+=steps;\n steps++;\n }\n \n while(((sum-target)%2!=0)){\n sum+=steps;\n steps++;\n }\n return steps-1;\n\n }\n}\n", + "title": "754. Reach a Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are standing at position 0 on an infinite number line. There is a destination at position target . You can make some number of moves numMoves so that: Given the integer target , return the minimum number of moves required (i.e., the minimum numMoves ) to reach the destination . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "On each move, you can either go left or right.", + "During the i th move (starting from i == 1 to i == numMoves ), you take i steps in the chosen direction." + ], + "examples": [ + { + "text": "Example 1: Input:target = 2Output:3Explanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to -1 (2 steps).\nOn the 3rdmove, we step from -1 to 2 (3 steps).", + "image": null + }, + { + "text": "Example 2: Input:target = 3Output:2Explanation:On the 1stmove, we step from 0 to 1 (1 step).\nOn the 2ndmove, we step from 1 to 3 (2 steps).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution: \n def reachNumber(self,target):\n jumpCount = 1 \n sum = 0 \n while sum heap = new PriorityQueue<>( (a, b) -> b[1]-a[1] );\n int ans = 0;\n boolean[] vis = new boolean[n];\n heap.offer(new int[]{0, maxMoves});\n while ( !heap.isEmpty() ) {\n int[] info = heap.poll();\n int nearestNodeId = info[0];\n int maxMovesRemaining = info[1];\n if ( vis[nearestNodeId] ) {\n continue;\n }\n // visiting the current node\n vis[nearestNodeId] = true;\n // since we visited this node we increment our counter\n ans++;\n for ( int i=0; i=graph[nearestNodeId][i]+1 ) {\n heap.offer( new int[] {i, maxMovesRemaining-graph[nearestNodeId][i]-1} );\n }\n int movesTaken = Math.min(maxMovesRemaining, graph[nearestNodeId][i]);\n graph[nearestNodeId][i] -= movesTaken;\n graph[i][nearestNodeId] -= movesTaken;\n ans += movesTaken;\n }\n }\n }\n return ans;\n }\n}", + "title": "882. Reachable Nodes In Subdivided Graph", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an undirected graph (the \"original graph\" ) with n nodes labeled from 0 to n - 1 . You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of edges where edges[i] = [u i , v i , cnt i ] indicates that there is an edge between nodes u i and v i in the original graph, and cnt i is the total number of new nodes that you will subdivide the edge into. Note that cnt i == 0 means you will not subdivide the edge. To subdivide the edge [u i , v i ] , replace it with (cnt i + 1) new edges and cnt i new nodes. The new nodes are x 1 , x 2 , ..., x cnt i , and the new edges are [u i , x 1 ] , [x 1 , x 2 ] , [x 2 , x 3 ] , ..., [x cnt i -1 , x cnt i ] , [x cnt i , v i ] . In this new graph , you want to know how many nodes are reachable from the node 0 , where a node is reachable if the distance is maxMoves or less. Given the original graph and maxMoves , return the number of nodes that are reachable from node 0 in the new graph . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= edges.length <= min(n * (n - 1) / 2, 10^4 )", + "edges[i].length == 3", + "0 <= u i < v i < n", + "There are no multiple edges in the graph.", + "0 <= cnt i <= 10^4", + "0 <= maxMoves <= 10^9", + "1 <= n <= 3000" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3Output:13Explanation:The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/01/origfinal.png" + }, + { + "text": "Example 2: Input:edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4Output:23", + "image": null + }, + { + "text": "Example 3: Input:edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5Output:1Explanation:Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1218 ms (Top 16.46%) | Memory: 23.7 MB (Top 8.86%)\nclass Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n m = defaultdict(list)\n for a, b, p in edges:\n m[a].append((p, b))\n m[b].append((p, a))\n\n vis = set()\n queue = []\n heappush(queue, (0, 0))\n edgevis = set()\n edgeofl = defaultdict(lambda: 0)\n ans = 0\n while queue:\n # print(queue)\n cost, cur = heappop(queue)\n vis.add(cur)\n for p, nxt in m[cur]:\n if p < maxMoves - cost:\n if (cur, nxt) not in edgevis and (nxt, cur) not in edgevis:\n ans += p\n # if nxt in vis:\n # ans -= 1\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n if nxt not in vis:\n heappush(queue, (cost + p + 1, nxt))\n else:\n bal = maxMoves - cost\n if (cur, nxt) in edgevis:\n continue\n if bal <= edgeofl[(cur, nxt)]:\n continue\n if bal + edgeofl[(nxt, cur)] < p:\n ans += bal - edgeofl[(cur, nxt)]\n edgeofl[(cur, nxt)] = bal\n else:\n ans += p - edgeofl[(nxt, cur)] - edgeofl[(cur, nxt)]\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n return ans + len(vis)", + "title": "882. Reachable Nodes In Subdivided Graph", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "edges represents a valid tree.", + "1 <= restricted.length < n", + "1 <= restricted[i] < n", + "All the values of restricted are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]Output:4Explanation:The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]Output:3Explanation:The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int count=0;\n ArrayList> adj=new ArrayList<>();\n public int reachableNodes(int n, int[][] edges, int[] restricted) {\n boolean[] vis=new boolean[n];\n for(int i:restricted){\n vis[i]=true;\n }\n for(int i=0;i());\n }\n for(int[] ii:edges){\n adj.get(ii[0]).add(ii[1]);\n adj.get(ii[1]).add(ii[0]);\n }\n dfs(0,vis);\n return count;\n }\n private void dfs(int node,boolean[] vis){\n vis[node]=true;\n count++;\n for(int it:adj.get(node)){\n if(vis[it]==false){\n dfs(it,vis);\n }\n }\n }\n}\n", + "title": "2368. Reachable Nodes With Restrictions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 2D integer array edges of length n - 1 where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. You are also given an integer array restricted which represents restricted nodes. Return the maximum number of nodes you can reach from node 0 without visiting a restricted node. Note that node 0 will not be a restricted node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= n <= 10^5", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "edges represents a valid tree.", + "1 <= restricted.length < n", + "1 <= restricted[i] < n", + "All the values of restricted are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]Output:4Explanation:The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex1drawio.png" + }, + { + "text": "Example 2: Input:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]Output:3Explanation:The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.", + "image": "https://assets.leetcode.com/uploads/2022/06/15/ex2drawio.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n # ignore restricted node\n # bfs from 0\n \n # O(E), EDITED: the time complexity here is wrong, plz see my comment\n adj_dict = collections.defaultdict(list)\n for u, v in edges:\n if u in restricted or v in restricted: # EDITED: not O(1)\n continue\n adj_dict[u].append(v)\n adj_dict[v].append(u)\n \n # O(V + E)\n queue = collections.deque([0])\n visited = {0}\n while queue:\n cur = queue.popleft()\n for neighbor in adj_dict[cur]:\n if neighbor in visited:\n continue\n visited.add(neighbor)\n queue.append(neighbor)\n\n return len(visited)\n", + "title": "2368. Reachable Nodes With Restrictions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given four integers sx , sy , tx , and ty , return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations , or false otherwise . The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= sx, sy, tx, ty <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:sx = 1, sy = 1, tx = 3, ty = 5Output:trueExplanation:One series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)", + "image": null + }, + { + "text": "Example 2: Input:sx = 1, sy = 1, tx = 2, ty = 2Output:false", + "image": null + }, + { + "text": "Example 3: Input:sx = 1, sy = 1, tx = 1, ty = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 55.54%) | Memory: 41.4 MB (Top 26.41%)\nclass Solution {\n public boolean reachingPoints(int sx, int sy, int tx, int ty) {\n if (sx==tx && sy==ty){\n return true;\n }\n if (tx < sx || ty < sy){\n return false;\n }\n return tx (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)", + "image": null + }, + { + "text": "Example 2: Input:sx = 1, sy = 1, tx = 2, ty = 2Output:false", + "image": null + }, + { + "text": "Example 3: Input:sx = 1, sy = 1, tx = 1, ty = 1Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\n\nclass Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n def nextNum(ta,tb,s):\n if ta % tb == s % tb:\n return min(ta, s)\n return ta % tb\n visited = defaultdict(bool)\n while tx >= sx and ty >= sy and (sx != tx or sy != ty):\n if tx > ty:\n tx, ty = nextNum(tx, ty, sx), ty\n else:\n tx, ty = tx, nextNum(ty, tx, sy)\n if visited[(tx,ty)]:\n break\n visited[(tx,ty)] = True\n return (sx == tx) and (sy == ty)\n", + "title": "780. Reaching Points", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Return the modified array after rearranging the elements to satisfy the aforementioned conditions . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^5", + "nums.length is even", + "1 <= |nums[i]| <= 10^5", + "nums consists of equal number of positive and negative integers." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,-2,-5,2,-4]Output:[3,-2,1,-5,2,-4]Explanation:The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1]Output:[1,-1]Explanation:1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 29.67%) | Memory: 225.1 MB (Top 38.94%)\nclass Solution {\n public int[] rearrangeArray(int[] nums) {\n int[] res = new int[nums.length];\n int resIdx = 0;\n int posIdx = -1;\n int minusIdx = -1;\n\n for(int i=0;i 0 )minusIdx++;\n res[resIdx++] = nums[minusIdx];\n }\n }\n\n return res;\n }\n}", + "title": "2149. Rearrange Array Elements by Sign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Return the modified array after rearranging the elements to satisfy the aforementioned conditions . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^5", + "nums.length is even", + "1 <= |nums[i]| <= 10^5", + "nums consists of equal number of positive and negative integers." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,-2,-5,2,-4]Output:[3,-2,1,-5,2,-4]Explanation:The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1]Output:[1,-1]Explanation:1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]\n", + "title": "2149. Rearrange Array Elements by Sign", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two 0-indexed strings s and target . You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "1 <= target.length <= 10", + "s and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ilovecodingonleetcode\", target = \"code\"Output:2Explanation:For the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcba\", target = \"abc\"Output:1Explanation:We can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abbaccaddaeea\", target = \"aaaaa\"Output:1Explanation:We can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.04 MB (Top 6.2%)\n\nclass Solution\n{\n public int rearrangeCharacters(String s, String target)\n {\n int[] freq = new int[26], freq2 = new int[26];\n for(char ch : s.toCharArray())\n freq[ch-'a']++;\n for(char ch : target.toCharArray())\n freq2[ch-'a']++;\n\n int min = Integer.MAX_VALUE;\n for(char ch : target.toCharArray())\n min = Math.min(min,freq[ch-'a']/freq2[ch-'a']);\n \n return min;\n }\n}", + "title": "2287. Rearrange Characters to Make Target String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two 0-indexed strings s and target . You can take some letters from s and rearrange them to form new strings. Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "1 <= target.length <= 10", + "s and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ilovecodingonleetcode\", target = \"code\"Output:2Explanation:For the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcba\", target = \"abc\"Output:1Explanation:We can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"abbaccaddaeea\", target = \"aaaaa\"Output:1Explanation:We can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 55 ms (Top 32.02%) | Memory: 13.9 MB (Top 67.72%)\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n counter_s = Counter(s)\n return min(counter_s[c] // count for c,count in Counter(target).items())", + "title": "2287. Rearrange Characters to Make Target String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word . Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized . If you cannot redistribute all the spaces equally, place the extra spaces at the end , meaning the returned string should be the same length as text . Return the string after rearranging the spaces . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 100", + "text consists of lowercase English letters and ' ' .", + "text contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:text = \" this is a sentence \"Output:\"this is a sentence\"Explanation:There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.", + "image": null + }, + { + "text": "Example 2: Input:text = \" practice makes perfect\"Output:\"practice makes perfect \"Explanation:There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 61.66%) | Memory: 40.5 MB (Top 92.33%)\nclass Solution {\n public String reorderSpaces(String text) {\n int spaces = 0;\n\n //count the spacex\n for(char c: text.toCharArray()){\n if(c==' ')\n spaces++;\n }\n\n //form word array\n String[] words = text.trim().split(\"\\\\s+\");\n int nWords = words.length;\n\n StringBuilder sb = new StringBuilder();\n int spacesToApply=0,extraSpaces=0;\n\n //if there is only 1 word, then all spaces will be at the end\n if(nWords == 1){\n extraSpaces=spaces;\n }\n\n //if there are multiple words, find the spaces to apply between words and also any extra space\n else{\n spacesToApply = spaces / (nWords-1);\n extraSpaces = spaces % (nWords-1);\n }\n\n //append every word and then apply spaces\n for(int i=0;i 1:\n q, r = spaces//(words-1), spaces%(words-1)\n return (\" \" * q).join(word_list) + \" \" * r\n else:\n return \"\".join(word_list) + \" \" * spaces\n", + "title": "1592. Rearrange Spaces Between Words", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sentence text (A sentence is a string of space-separated words) in the following format: Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "First letter is in upper case.", + "Each word in text are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"Leetcode is cool\"Output:\"Is cool leetcode\"Explanation:There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.", + "image": null + }, + { + "text": "Example 2: Input:text = \"Keep calm and code on\"Output:\"On and keep calm code\"Explanation:Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.", + "image": null + }, + { + "text": "Example 3: Input:text = \"To be or not to be\"Output:\"To be or to be not\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 72.47%) | Memory: 45.70 MB (Top 34.84%)\n\nclass Solution {\n public String arrangeWords(String text) {\n text = text.replace(text.charAt(0)+\"\", (char)(text.charAt(0)+32)+\"\");\n\n String[] arr = text.split(\" \");\n Arrays.sort(arr, new Comparator(){\n public int compare(String s1, String s2){\n return Integer.compare(s1.length(), s2.length());\n }\n });\n\n StringBuilder str = new StringBuilder(arr[0]);\n\n for(int i = 1; i < arr.length; i++)\n str.append(\" \"+arr[i]);\n\n text = (char)(str.charAt(0)-32)+str.substring(1, str.length());\n\n return text;\n }\n}\n// UP-VOTE IF HELPFUL\n", + "title": "1451. Rearrange Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a sentence text (A sentence is a string of space-separated words) in the following format: Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "First letter is in upper case.", + "Each word in text are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"Leetcode is cool\"Output:\"Is cool leetcode\"Explanation:There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.", + "image": null + }, + { + "text": "Example 2: Input:text = \"Keep calm and code on\"Output:\"On and keep calm code\"Explanation:Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.", + "image": null + }, + { + "text": "Example 3: Input:text = \"To be or not to be\"Output:\"To be or to be not\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 89.61%) | Memory: 19.60 MB (Top 55.06%)\n\nclass Solution:\n def arrangeWords(self, text: str) -> str:\n a = []\n for x in text.split(\" \"):\n a.append(x.lower())\n return \" \".join(sorted(a, key=len)).capitalize()\n", + "title": "1451. Rearrange Words in a Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the following details of a matrix with n columns and 2 rows : Your task is to reconstruct the matrix with upper , lower and colsum . Return it as a 2-D integer array. If there are more than one valid solution, any of them will be accepted. If no valid solution exists, return an empty 2-D array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The matrix is a binary matrix, which means each element in the matrix can be 0 or 1 .", + "The sum of elements of the 0-th(upper) row is given as upper .", + "The sum of elements of the 1-st(lower) row is given as lower .", + "The sum of elements in the i-th column(0-indexed) is colsum[i] , where colsum is given as an integer array with length n ." + ], + "examples": [ + { + "text": "Example 1: Input:upper = 2, lower = 1, colsum = [1,1,1]Output:[[1,1,0],[0,0,1]]Explanation:[[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.", + "image": null + }, + { + "text": "Example 2: Input:upper = 2, lower = 3, colsum = [2,2,1,1]Output:[]", + "image": null + }, + { + "text": "Example 3: Input:upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]Output:[[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2054 ms (Top 5.33%) | Memory: 24.4 MB (Top 72.78%)\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n n = len(colsum)\n matrix = [[0 for i in range(n)] for j in range(2)]\n for col,summ in enumerate(colsum):\n if summ == 0:\n continue\n if summ == 2:\n matrix[0][col] = matrix[1][col] = 1\n upper -= 1\n lower -= 1\n else:\n if upper > lower:\n matrix[0][col] = 1\n upper -= 1\n else:\n matrix[1][col] = 1\n lower -= 1\n if upper < 0 or lower < 0: break\n\n return matrix if upper == lower == 0 else []", + "title": "1253. Reconstruct a 2-Row Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]Output:[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg" + }, + { + "text": "Example 2: 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.", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 90.17%) | Memory: 50.3 MB (Top 42.47%)\nclass Solution {\n LinkedList res = new LinkedList<>();\n\n public List findItinerary(List> tickets) {\n HashMap> map= new HashMap<>();\n for(int i=0;i temp = new PriorityQueue();\n map.put(a,temp);\n }\n map.get(a).add(b);\n }\n\n dfs(\"JFK\",map);\n return res;\n\n }\n private void dfs(String departure,HashMap> map){\n PriorityQueue arrivals= map.get(departure);\n while(arrivals!=null &&!arrivals.isEmpty()){\n dfs(arrivals.poll(),map);\n }\n res.addFirst(departure);\n }\n}", + "title": "332. Reconstruct Itinerary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]Output:[\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg" + }, + { + "text": "Example 2: 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.", + "image": "https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution: \n def findTicketsAdjList(self, tickets):\n ticket = {}\n for src,dest in tickets:\n if src in ticket:\n ticket[src].append(dest)\n else:\n ticket[src] = [dest]\n\n for src,dest in ticket.items():\n if len(dest)>1:\n ticket[src] = sorted(ticket[src], reverse=True)\n \n return ticket\n \n def reconstructItinerary(self, source, tickets, itinerary):\n if source in tickets:\n while tickets[source]: \n destination = tickets[source].pop()\n self.reconstructItinerary(destination, tickets, itinerary)\n itinerary.append(source)\n return itinerary\n \n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n if len(tickets)==1:\n if \"JFK\" not in tickets[0]:\n return []\n \n ticketsAdj = self.findTicketsAdjList(tickets)\n if \"JFK\" not in ticketsAdj:\n return []\n itinerary = []\n itinerary = self.reconstructItinerary(\"JFK\", ticketsAdj, itinerary)\n \n return itinerary[::-1]\n \n", + "title": "332. Reconstruct Itinerary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing an out-of-order English representation of digits 0-9 , return the digits in ascending order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"] .", + "s is guaranteed to be valid." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"owoztneoer\"Output:\"012\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"fviefuro\"Output:\"45\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n // First letter is unique after previous entries have been handled:\n static final String[] UNIQUES = new String[] {\n \"zero\", \"wto\", \"geiht\", \"xsi\", \"htree\",\n \"seven\", \"rfou\", \"one\", \"vfie\", \"inne\"\n };\n\n // Values corresponding to order of uniqueness checks:\n static final int[] VALS = new int[] { 0, 2, 8, 6, 3, 7, 4, 1, 5, 9 };\n \n\t// Maps for checking uniqueness more conveniently:\n static final Map> ORDERED_FREQ_MAP;\n static final Map ORDERED_DIGIT_MAP;\n \n static {\n\t // Initialize our ordered frequency map: 0-25 key to 0-25 values finishing the word:\n final LinkedHashMap> orderedFreqMap = new LinkedHashMap<>();\n\t\t// Also initialize a digit lookup map, e.g. 'g' becomes 6 maps to 8 for ei[g]ht:\n final LinkedHashMap orderedDigitMap = new LinkedHashMap<>();\n for (int i = 0; i < 10; ++i) {\n final char unique = UNIQUES[i].charAt(0);\n final int ui = convert(unique);\n orderedFreqMap.put(ui, converting(UNIQUES[i].substring(1).toCharArray()));\n orderedDigitMap.put(ui, VALS[i]);\n }\n\t\t// Let's make sure we aren't tempted to modify these since they're static.\n ORDERED_FREQ_MAP = Collections.unmodifiableMap(orderedFreqMap);\n ORDERED_DIGIT_MAP = Collections.unmodifiableMap(orderedDigitMap);\n }\n\n public String originalDigits(String s) {\n\t // count frequencies of each letter in s:\n final int[] freqs = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n freqs[convert(s.charAt(i))]++;\n }\n\t\t// Crate an array to store digit strings in order, e.g. '00000', '11, '2222222', etc.\n final String[] strings = new String[10];\n\t\t// Iterate through uniqueness checks in order:\n for (Map.Entry> entry : ORDERED_FREQ_MAP.entrySet()) {\n final int index = entry.getKey(); // unique letter in 0-25 form\n final int value = ORDERED_DIGIT_MAP.get(index); // corresponding digit, e.g. 8 for 'g', 0 for 'z', etc.\n final int count = freqs[index]; // frequency of unique letter = frequency of corresponding digit\n if (count > 0) {\n\t\t\t // update frequencies to remove the digit's word count times:\n freqs[index] -= count;\n for (int idx : entry.getValue()) {\n freqs[idx] -= count;\n }\n\t\t\t\t// now create the digit string for the unique digit: the digit count times:\n strings[value] = String.valueOf(value).repeat(count);\n } else {\n\t\t\t // count 0 - empty strring for this digit\n strings[value] = \"\";\n }\n }\n\t\t// append the digit strings in order\n final StringBuilder sb = new StringBuilder();\n for (String str : strings) {\n sb.append(str);\n }\n\t\t// and we are done!\n return sb.toString();\n }\n\n // Converts a character array into a list of 0-25 frequency values.\n private static final List converting(char... carr) {\n final List list = new ArrayList<>();\n for (char ch : carr) {\n list.add(convert(ch)); // converts each to 0-25\n }\n return Collections.unmodifiableList(list);\n }\n\n // Converts a-z to 0-26. Bitwise AND with 31 gives a=1, z=26, so then subtract one.\n private static final Integer convert(char ch) {\n return (ch & 0x1f) - 1; // a->0, z->25\n }\n\n}\n", + "title": "423. Reconstruct Original Digits from English", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s containing an out-of-order English representation of digits 0-9 , return the digits in ascending order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"] .", + "s is guaranteed to be valid." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"owoztneoer\"Output:\"012\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"fviefuro\"Output:\"45\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def originalDigits(self, s: str) -> str:\n c = dict()\n \n c[0] = s.count(\"z\")\n c[2] = s.count(\"w\")\n c[4] = s.count(\"u\")\n c[6] = s.count(\"x\")\n c[8] = s.count(\"g\")\n \n c[3] = s.count(\"h\") - c[8]\n c[5] = s.count(\"f\") - c[4]\n c[7] = s.count(\"s\") - c[6]\n \n c[9] = s.count(\"i\") - (c[8] + c[5] + c[6])\n c[1] = s.count(\"o\") - (c[0] + c[2] + c[4])\n \n c = sorted(c.items(), key = lambda x: x[0])\n ans = \"\"\n for k, v in c:\n ans += (str(k) * v)\n return ans", + "title": "423. Reconstruct Original Digits from English", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the original tree is in the range [1, 1000] .", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:traversal = \"1-2--3--4-5--6--7\"Output:[1,2,5,3,4,6,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/08/recover-a-tree-from-preorder-traversal.png" + }, + { + "text": "Example 2: Input:traversal = \"1-2--3---4-5--6---7\"Output:[1,2,5,3,null,6,null,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114101-pm.png" + }, + { + "text": "Example 3: Input:traversal = \"1-401--349---90--88\"Output:[1,401,null,349,88,90]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114955-pm.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode recoverFromPreorder(String traversal) {\n if(!traversal.contains(\"-\"))\n return new TreeNode(Integer.parseInt(traversal));\n String number = \"\";\n int i = 0;\n while(traversal.charAt(i)!='-'){\n number+=traversal.charAt(i);\n i++;\n }\n //System.out.print(\"root = \" + number + \" \" + i + \" \");\n TreeNode root = new TreeNode(Integer.parseInt(number));\n StringBuilder str = new StringBuilder();\n int bk = 0;\n for(int j = i; i < traversal.length(); i++){\n if(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-' && traversal.charAt(i+1) != '-')\n bk = str.toString().length();\n else if(!(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-'))\n str.append(traversal.charAt(i));\n }\n String divide = str.toString();\n \n TreeNode left = (bk==0)?recoverFromPreorder(divide):recoverFromPreorder(divide.substring(0,bk));\n TreeNode right = (bk==0)?null:recoverFromPreorder(divide.substring(bk,divide.length()));\n root.left = left;\n root.right = right;\n \n \n return root;\n }\n}\n", + "title": "1028. Recover a Tree From Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the original tree is in the range [1, 1000] .", + "1 <= Node.val <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:traversal = \"1-2--3--4-5--6--7\"Output:[1,2,5,3,4,6,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/08/recover-a-tree-from-preorder-traversal.png" + }, + { + "text": "Example 2: Input:traversal = \"1-2--3---4-5--6---7\"Output:[1,2,5,3,null,6,null,4,null,7]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114101-pm.png" + }, + { + "text": "Example 3: Input:traversal = \"1-401--349---90--88\"Output:[1,401,null,349,88,90]", + "image": "https://assets.leetcode.com/uploads/2019/04/11/screen-shot-2019-04-10-at-114955-pm.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 138 ms (Top 42.81%) | Memory: 14.7 MB (Top 52.51%)\nclass Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n i = 0\n dummy_head = TreeNode()\n depth = 0\n while i < len(traversal):\n if traversal[i].isdigit():\n value, i = get_value(traversal, i)\n insert_node(dummy_head, depth, value)\n\n else:\n depth, i = get_depth(traversal, i)\n\n return dummy_head.left\n\n# Returns the next value from the string traversal, and returns the position following the last digit of the current value.\ndef get_value(traversal, i):\n value = 0\n while i < len(traversal) and traversal[i].isdigit():\n value *= 10\n value += int(traversal[i])\n i += 1\n\n return value, i\n\n# Insertes a node of the given `value` at the given `depth` of the subtree whose root is the given `root`.\ndef insert_node(root, depth, value):\n for _ in range(depth):\n if root.right:\n root = root.right\n else:\n root = root.left\n\n new_node = TreeNode(value)\n if root.left:\n root.right = new_node\n else:\n root.left = new_node\n\n# Gets the next depth from the string traversal, and returns the position following the last dash of the current depth.\ndef get_depth(traversal, i):\n depth = 0\n while i < len(traversal) and traversal[i] == \"-\":\n depth += 1\n i += 1\n\n return depth, i", + "title": "1028. Recover a Tree From Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 1000] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,3,null,null,2]Output:[3,1,null,null,2]Explanation:3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.", + "image": "https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg" + }, + { + "text": "Example 2: Input:root = [3,1,4,null,null,2]Output:[2,1,4,null,null,3]Explanation:2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.", + "image": "https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 61 ms (Top 95.6%) | Memory: 16.68 MB (Top 75.1%)\n\nclass Solution:\n \n \"\"\"\n Brute force kind of thing\n -> Inorder Traversal returns sorted array\n -> find a swap btwn numbers to make sorted\n Make single swap to make array sorted\n [1, 2, 3, 4, 10, 6, 9, 5, 10, 12]\n x, x, x, x, x, No\n prev number is mismatch -> 10 is cause\n now go frm right to left\n [1, 2, 3, 4, 10, 6, 9, 5, 11, 12]\n No x x x\n mismatch with next number -> 5 is the cause\n swap 10, 5\n \n Eg: 2\n [3, 2, 1]\n x No -> 3 is the cause\n [3, 2, 1]\n x No -> 1 is the cause\n swap values -> 1, 3\n \"\"\"\n \n def inorder(self, root, li):\n if root is None:\n return li\n li = self.inorder(root.left, li)\n li.append(root)\n li = self.inorder(root.right, li)\n return li\n \n def recoverTree(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n li = self.inorder(root, [])\n n = len(li)\n i, j = 1, n-2\n a = li[0]\n for i in range(1, n):\n if li[i].val < li[i-1].val:\n a = li[i-1]\n break\n b = li[-1]\n for i in range(n-2, -1, -1):\n if li[i].val > li[i+1].val:\n b = li[i+1]\n break\n\n a.val,b.val = b.val, a.val\n", + "title": "99. Recover Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]Output:[3,7,11]Explanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]Output:[2,2]Explanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]Output:[220]Explanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 910 ms (Top 16.67%) | Memory: 44.70 MB (Top 72.22%)\n\nclass Solution {\n public int[] recoverArray(int[] nums) {\n \n \tint i,n=nums.length;\n \tint ans[]=new int[n/2];\n \tArrays.sort(nums);\n \tPriorityQueue pq=new PriorityQueue<>();\n \tfor(i=0;i pq1=new PriorityQueue<>(pq);\n \t\tint p=0;\n \t\tif((nums[0]+nums[i])%2==0)\n \t\t{\n \t\t\tint k=(nums[0]+nums[i])/2-nums[0];\n \t\t\tif(k==0)\n \t\t\t\tcontinue;\n \t\t\tint curr=pq1.poll();\n \t\t\twhile(pq1.contains((curr+k+k))) {\n \t\t\t\n \t\t\t\tpq1.remove(curr+k+k); \n\t\t\t\t\tans[p++]=curr+k;\n\t\t\t\t\tif(p==n/2)\n\t\t\t\t\t\tbreak;\n \t\t\t\tcurr=pq1.poll();\n \t\t\t}\n \t\t\tif(p==n/2)\n \t\t\t\tbreak;\n \t\t}\n \t}\n \treturn ans;\n }\n}\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]Output:[3,7,11]Explanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]Output:[2,2]Explanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]Output:[220]Explanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] recoverArray(int[] nums) {\n int N = nums.length;\n Arrays.sort(nums);\n List diffList = new ArrayList<>();\n for (int i = 1; i < N; i++) {\n int diff = Math.abs(nums[i] - nums[0]);\n if (diff % 2 == 0 && diff > 0) diffList.add(diff / 2);\n }\n Map map1 = new HashMap<>();\n for (int i = 0; i < N; i++)\n map1.put(nums[i], map1.getOrDefault(nums[i], 0) + 1);\n for (int diff : diffList) {\n Map map = new HashMap<>(map1);\n List tmp = new ArrayList<>();\n for (int i = 0; i < N; i++) {\n\t\t\t if (tmp.size() == N / 2) break;\n int low = nums[i];\n int high = low + 2 * diff;\n if (map.containsKey(low) && map.containsKey(high)) {\n tmp.add(low + diff);\n map.put(low, map.get(low) - 1); \n map.put(high, map.get(high) - 1);\n if (map.get(low) == 0) map.remove(low);\n if (map.get(high) == 0) map.remove(high);\n }\n }\n if (tmp.size() == N / 2) return tmp.stream().mapToInt(i -> i).toArray();\n }\n return null;\n }\n}\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher , but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher , return the original array arr . In case the answer is not unique, return any valid array . Note: The test cases are generated such that there exists at least one valid array arr . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 * n == nums.length", + "1 <= n <= 1000", + "1 <= nums[i] <= 10^9", + "The test cases are generated such that there exists at least one valid array arr ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,6,4,8,12]Output:[3,7,11]Explanation:If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,3,3]Output:[2,2]Explanation:If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,435]Output:[220]Explanation:The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def recoverArray(self, nums):\n nums.sort()\n mid = len(nums) // 2\n # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k.\n # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k.\n # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but\n # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough.\n # The conclusion is j <= mid.\n\t\t# If you think it’s not easy to understand why mid is enough, len(nums) can also work well\n\t\t# for j in range(1, len(nums)): \n for j in range(1, mid + 1): # O(N)\n if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive.\n k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), []\n # For each number in lower, we try to find the corresponding number from higher list.\n # Because nums is sorted, current n is always the current lowest num which can only come from lower\n # list, so we search the corresponding number of n which equals to n + 2 * k in the left\n # if it can not be found, change another k and continue to try.\n for n in nums: # check if n + 2 * k available as corresponding number in higher list of n\n if counter[n] == 0: # removed by previous num as its corresponding number in higher list\n continue\n if counter[n + 2 * k] == 0: # not found corresponding number in higher list\n break\n ans.append(n + k)\n counter[n] -= 1 # remove n\n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list\n if len(ans) == mid:\n return ans\n", + "title": "2122. Recover the Original Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles . The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2) . The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-10^4 <= ax1 <= ax2 <= 10^4", + "-10^4 <= ay1 <= ay2 <= 10^4", + "-10^4 <= bx1 <= bx2 <= 10^4", + "-10^4 <= by1 <= by2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2Output:45", + "image": "https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" + }, + { + "text": "Example 2: Input:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 35.02%) | Memory: 42.9 MB (Top 64.28%)\nclass Solution {\n public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int x1 = Math.max(ax1,bx1);\n int y1 = Math.max(ay1,by1);\n int x2 = Math.min(ax2,bx2);\n int y2 = Math.min(ay2,by2);\n\n int area = 0;\n int R1 = (ax2-ax1)*(ay2-ay1);\n int R2 = (bx2-bx1)*(by2-by1);\n area = R1 + R2;\n\n if(x2 > x1 && y2 > y1){\n int overlap = (x2-x1)*(y2-y1);\n area = area - overlap;\n }\n\n return area;\n }\n}", + "title": "223. Rectangle Area", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles . The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2) . The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-10^4 <= ax1 <= ax2 <= 10^4", + "-10^4 <= ay1 <= ay2 <= 10^4", + "-10^4 <= bx1 <= bx2 <= 10^4", + "-10^4 <= by1 <= by2 <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2Output:45", + "image": "https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png" + }, + { + "text": "Example 2: Input:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 48.63%) | Memory: 14 MB (Top 27.24%)\nclass Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n def segment(ax1,ax2,bx1,bx2):\n return min(ax2,bx2) - max(ax1, bx1) if max(ax1, bx1) < min(ax2, bx2) else 0\n return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - segment(ax1,ax2,bx1,bx2)*segment(ay1,ay2,by1,by2)", + "title": "223. Rectangle Area", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D array of axis-aligned rectangles . Each rectangle[i] = [x i1 , y i1 , x i2 , y i2 ] denotes the i th rectangle where (x i1 , y i1 ) are the coordinates of the bottom-left corner , and (x i2 , y i2 ) are the coordinates of the top-right corner . Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once . Return the total area . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 200", + "rectanges[i].length == 4", + "0 <= x i1 , y i1 , x i2 , y i2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]Output:6Explanation:A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/06/rectangle_area_ii_pic.png" + }, + { + "text": "Example 2: Input:rectangles = [[0,0,1000000000,1000000000]]Output:49Explanation:The answer is 1018modulo (109+ 7), which is 49.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 17.31%) | Memory: 42.3 MB (Top 86.54%)\nclass Solution {\n public int rectangleArea(int[][] rectangles) {\n int n = rectangles.length;\n Set coorx = new HashSet<>();\n Set coory = new HashSet<>();\n for (int[] rec : rectangles) {\n coorx.add(rec[0]); coorx.add(rec[2]);\n coory.add(rec[1]); coory.add(rec[3]);\n }\n\n Integer[] compressx = coorx.toArray(new Integer[0]);\n Arrays.sort(compressx);\n Integer[] compressy = coory.toArray(new Integer[0]);\n Arrays.sort(compressy);\n\n Map mapx = new HashMap<>();\n for(int i = 0; i < compressx.length; i++) {\n mapx.put(compressx[i], i);\n }\n Map mapy = new HashMap<>();\n for(int i = 0; i < compressy.length; i++) {\n mapy.put(compressy[i], i);\n }\n\n boolean[][] grid = new boolean[compressx.length][compressy.length];\n for (int[] rec: rectangles) {\n for (int x = mapx.get(rec[0]); x < mapx.get(rec[2]); x++) {\n for (int y = mapy.get(rec[1]); y < mapy.get(rec[3]); y++) {\n grid[x][y] = true;\n }\n }\n }\n\n long res = 0L;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j]) {\n res += (long)(compressx[i + 1] - compressx[i]) * (compressy[j + 1] - compressy[j]);\n }\n }\n }\n res %= 1000000007;\n return (int)res;\n }\n }", + "title": "850. Rectangle Area II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 2D array of axis-aligned rectangles . Each rectangle[i] = [x i1 , y i1 , x i2 , y i2 ] denotes the i th rectangle where (x i1 , y i1 ) are the coordinates of the bottom-left corner , and (x i2 , y i2 ) are the coordinates of the top-right corner . Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once . Return the total area . Since the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rectangles.length <= 200", + "rectanges[i].length == 4", + "0 <= x i1 , y i1 , x i2 , y i2 <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]Output:6Explanation:A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/06/rectangle_area_ii_pic.png" + }, + { + "text": "Example 2: Input:rectangles = [[0,0,1000000000,1000000000]]Output:49Explanation:The answer is 1018modulo (109+ 7), which is 49.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 133 ms (Top 41.78%) | Memory: 13.9 MB (Top 70.89%)\nclass SegmentTree:\n def __init__(self, xs):\n #cnts[v] means that the node's interval is active\n self.cnts = defaultdict(int)\n #total[v] length of active intervals that are contained the node's interval\n self.total = defaultdict(int)\n self.xs = xs\n\n def update(self, v, tl, tr, l, r, h):\n #node interval [tl,tr] does not overlap with query interval [l,r]\n if r < tl or tr < l: return\n #node interval is included in the query interval\n if l <= tl and tr <= r:\n self.cnts[v] += h\n else:\n tm = (tl + tr)//2\n self.update(v*2, tl, tm, l, r, h)\n self.update(v*2+1, tm+1, tr, l, r, h)\n #node interval is included in the active interval\n if self.cnts[v] > 0:\n self.total[v] = self.xs[tr + 1] - self.xs[tl]\n else:\n self.total[v] = self.total[v*2] + self.total[v*2+1]\n return self.total[v]\n\nclass Solution:\n def rectangleArea(self, rectangles):\n #index i means the interval from xs[i] to xs[i+1]\n xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))\n xs_i = {x:i for i, x in enumerate(xs)}\n st = SegmentTree(xs)\n L = []\n for x1, y1, x2, y2 in rectangles:\n L.append([y1, 1, x1, x2])\n L.append([y2, -1, x1, x2])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for y, open_close, x1, x2 in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n #one index corresponds to one interval, that's why we use xs_i[x2]-1 instead of xs_i[x2]\n st.update(1, 0, len(xs) - 1, xs_i[x1], xs_i[x2]-1, open_close)\n cur_x_sum = st.total[1]\n\n return area % (10 ** 9 + 7)", + "title": "850. Rectangle Area II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2] , where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive . To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2 , return true if they overlap, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "rec1.length == 4", + "rec2.length == 4", + "-10^9 <= rec1[i], rec2[i] <= 10^9", + "rec1 and rec2 represent a valid rectangle with a non-zero area." + ], + "examples": [ + { + "text": "Example 1: Input:rec1 = [0,0,2,2], rec2 = [1,1,3,3]Output:true", + "image": null + }, + { + "text": "Example 2: Input:rec1 = [0,0,1,1], rec2 = [1,0,2,1]Output:false", + "image": null + }, + { + "text": "Example 3: Input:rec1 = [0,0,1,1], rec2 = [2,2,3,3]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Rectangle Overlap\n// https://leetcode.com/problems/rectangle-overlap/\n\nclass Solution {\n public boolean isRectangleOverlap(int[] rec1, int[] rec2) {\n int x1 = rec1[0];\n int y1 = rec1[1];\n int x2 = rec1[2];\n int y2 = rec1[3];\n int x3 = rec2[0];\n int y3 = rec2[1];\n int x4 = rec2[2];\n int y4 = rec2[3];\n if (x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3) {\n return false;\n }\n return true; \n }\n}\n", + "title": "836. Rectangle Overlap", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2] , where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is positive . To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles rec1 and rec2 , return true if they overlap, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "rec1.length == 4", + "rec2.length == 4", + "-10^9 <= rec1[i], rec2[i] <= 10^9", + "rec1 and rec2 represent a valid rectangle with a non-zero area." + ], + "examples": [ + { + "text": "Example 1: Input:rec1 = [0,0,2,2], rec2 = [1,1,3,3]Output:true", + "image": null + }, + { + "text": "Example 2: Input:rec1 = [0,0,1,1], rec2 = [1,0,2,1]Output:false", + "image": null + }, + { + "text": "Example 3: Input:rec1 = [0,0,1,1], rec2 = [2,2,3,3]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n if (rec2[1]>=rec1[3] or rec2[0]>=rec1[2] or rec2[3]<=rec1[1] or rec1[0]>=rec2[2]) :\n \n return False\n else:\n return True\n", + "title": "836. Rectangle Overlap", + "topic": "Graph" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array of strings words ( 0-indexed ). In one operation, pick two distinct indices i and j , where words[i] is a non-empty string, and move any character from words[i] to any position in words[j] . Return true if you can make every string in words equal using any number of operations , and false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 100", + "words[i] consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"abc\",\"aabc\",\"bc\"]Output:trueExplanation:Move the first 'a' inwords[1] to the front of words[2],\nto makewords[1]= \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so returntrue.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"ab\",\"a\"]Output:falseExplanation:It is impossible to make all the strings equal using the operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean makeEqual(String[] words) {\n \n HashMap map = new HashMap<>();\n \n for(String str : words){\n \n for(int i=0; i bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map_.items():\n if (v%n) != 0:\n return False\n return True\n", + "title": "1897. Redistribute Characters to Make All Strings Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr . You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "arr.length is even.", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,3,3,3,5,5,5,2,2,7]Output:2Explanation:Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,7,7,7,7,7]Output:1Explanation:The only possible set you can choose is {7}. This will make the new array empty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSetSize(int[] arr) {\n int size=arr.length;\n int deletedSize=0;\n int countIteration=0;\n Map hashMap=new HashMap<>();\n Queue> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());\n \n for(int i=0;i entry:hashMap.entrySet())\n {\n queue.add(entry);\n }\n \n while(!queue.isEmpty())\n {\n int totalOccurence=queue.poll().getValue();\n deletedSize+=totalOccurence; \n countIteration++;\n if(deletedSize>=size/2)\n return countIteration;\n \n }\n return countIteration;\n }\n}\n", + "title": "1338. Reduce Array Size to The Half", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array arr . You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= arr.length <= 10^5", + "arr.length is even.", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,3,3,3,5,5,5,2,2,7]Output:2Explanation:Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.", + "image": null + }, + { + "text": "Example 2: Input:arr = [7,7,7,7,7,7]Output:1Explanation:The only possible set you can choose is {7}. This will make the new array empty.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n n = len(arr)\n half = n // 2\n \n c = Counter(arr)\n s = 0\n ans = 0\n \n for num, occurances in c.most_common():\n s += occurances\n ans += 1\n if s >= half:\n return ans\n return ans\n", + "title": "1338. Reduce Array Size to The Half", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i] . Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation . Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == satisfaction.length", + "1 <= n <= 500", + "-1000 <= satisfaction[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:satisfaction = [-1,-8,0,5,-9]Output:14Explanation:After Removing the second and last dish, the maximum totallike-time coefficientwill be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.", + "image": null + }, + { + "text": "Example 2: Input:satisfaction = [4,3,2]Output:20Explanation:Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)", + "image": null + }, + { + "text": "Example 3: Input:satisfaction = [-1,-4,-5]Output:0Explanation:People do not like the dishes. No dish is prepared.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 80.60%) | Memory: 41.7 MB (Top 87.57%)\nclass Solution {\n public int maxSatisfaction(int[] satisfaction) {\n Arrays.sort(satisfaction);\n if(satisfaction[satisfaction.length-1] <= 0){\n return 0;\n }\n\n int res = 0;\n int beforeSum = 0;\n for(int i = satisfaction.length-1; i>=0; i--){\n int currNum = satisfaction[i];\n beforeSum += currNum;\n if(beforeSum >= 0){\n res += beforeSum;\n }else{\n return res;\n }\n }\n\n return res;\n }\n}", + "title": "1402. Reducing Dishes", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i] . Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation . Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == satisfaction.length", + "1 <= n <= 500", + "-1000 <= satisfaction[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:satisfaction = [-1,-8,0,5,-9]Output:14Explanation:After Removing the second and last dish, the maximum totallike-time coefficientwill be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.", + "image": null + }, + { + "text": "Example 2: Input:satisfaction = [4,3,2]Output:20Explanation:Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)", + "image": null + }, + { + "text": "Example 3: Input:satisfaction = [-1,-4,-5]Output:0Explanation:People do not like the dishes. No dish is prepared.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort(reverse=True)\n maxSatisfaction = dishSum = 0\n\n for dish in satisfaction:\n dishSum += dish\n if dishSum <= 0:\n break\n maxSatisfaction += dishSum\n \n return maxSatisfaction", + "title": "1402. Reducing Dishes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,1,3]Output:3Explanation:It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:0Explanation:All elements in nums are already equal.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2,3]Output:4Explanation:It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reductionOperations(int[] nums) {\n Map valMap = new TreeMap<>(Collections.reverseOrder());\n\n for (int i=0; i entry : valMap.entrySet()) {\n opsCount += entry.getValue() * (--mapSize);\n }\n return opsCount;\n }\n}\n", + "title": "1887. Reduction Operations to Make the Array Elements Equal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "1 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,1,3]Output:3Explanation:It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:0Explanation:All elements in nums are already equal.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2,3]Output:4Explanation:It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 717 ms (Top 99.99%) | Memory: 24.60 MB (Top 36.15%)\n\nclass Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n ans = val = 0\n nums.sort()\n for i in range(1, len(nums)): \n if nums[i-1] < nums[i]: val += 1\n ans += val\n return ans \n", + "title": "1887. Reduction Operations to Make the Array Elements Equal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]Output:[1,4]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 89.63%) | Memory: 43.5 MB (Top 75.35%)\nclass Solution {\n public int[] findRedundantConnection(int[][] edges) {\n UnionFind uf = new UnionFind(edges.length);\n for (int[] edge : edges) {\n if (!uf.union(edge[0], edge[1])) {\n return new int[]{edge[0], edge[1]};\n }\n }\n return null;\n }\n\n private class UnionFind {\n int[] rank;\n int[] root;\n\n UnionFind(int n) {\n rank = new int[n + 1];\n root = new int[n + 1];\n for (int i = 1; i <= n; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n int find(int x) {\n if (x == root[x]) {\n return x;\n }\n return root[x] = find(root[x]);\n }\n\n boolean union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = root[rootX];\n } else if (rank[rootY] > rank[rootX]) {\n root[rootX] = root[rootY];\n } else {\n root[rootY] = root[rootX];\n rank[rootX]++;\n }\n return true;\n }\n return false;\n }\n }\n}", + "title": "684. Redundant Connection", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]Output:[1,4]", + "image": "https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class UnionFind:\n \n def __init__(self, size):\n \n self.parent = [-1 for _ in range(size)]\n self.rank = [-1 for _ in range(size)]\n \n def find(self, i):\n \n if self.parent[i] == -1:\n return i\n \n k = self.find(self.parent[i])\n self.parent[i] = k\n return k\n \n def union(self, x, y):\n \n x = self.find(x)\n y = self.find(y)\n \n if x == y:\n return -1\n else:\n \n if self.rank[x] > self.rank[y]:\n self.parent[y] = x\n \n elif self.rank[x] < self.rank[y]:\n self.parent[x] = y\n \n else:\n self.rank[x] += 1\n self.parent[y] = x\n\nclass Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n \n vertex_set = set()\n \n for edge in edges:\n vertex_set.add(edge[0])\n vertex_set.add(edge[1])\n \n \n union_find = UnionFind(len(vertex_set))\n \n for edge in edges:\n \n new_edge = [edge[0]-1, edge[1]-1]\n \n if union_find.union(new_edge[0], new_edge[1]) == -1:\n return edge\n \n return []\n\n", + "title": "684. Redundant Connection", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n ), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n , and was not an edge that already existed. The resulting graph is given as a 2D-array of edges . Each element of edges is a pair [u i , v i ] that represents a directed edge connecting nodes u i and v i , where u i is a parent of child v i . Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes . If there are multiple answers, return the answer that occurs last in the given 2D-array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == edges.length", + "3 <= n <= 1000", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "u i != v i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]Output:[4,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 24.18%) | Memory: 44.9 MB (Top 16.79%)\nclass Solution {\n int[] dsu;\n public int[] findRedundantDirectedConnection(int[][] edges) {\n int n=edges.length;\n int[] parent=new int[n+1];\n Arrays.fill(parent,-1);\n\n int[] e2=null;\n int[] e1=null;\n boolean twopt=false;\n\n for(int[] edge: edges){\n\n int from=edge[0];\n int to=edge[1];\n\n if(parent[to]==-1){\n parent[to]=from;\n }else{\n twopt=true;\n e2=edge;\n e1=new int[]{parent[to],to};\n break;\n }\n }\n\n dsu=new int[edges.length+1];\n for(int i=0;i<=edges.length;i++){\n dsu[i]=i;\n }\n if(twopt==false){\n int[] res=null;\n\n for(int[] edge: edges){\n int from=edge[0];\n int to=edge[1];\n\n int fromlead=find(from);\n if(fromlead==to){\n res=edge;\n break;\n }else{\n dsu[to]=fromlead;\n }\n }\n return res;\n }else{\n boolean iscycle=false;\n for(int[] edge: edges){\n if(edge==e2) continue;\n int from =edge[0];\n int to=edge[1];\n\n int fromlead=find(from);\n\n if(fromlead==to){\n iscycle=true;\n break;\n }else{\n dsu[to]=fromlead;\n }\n }\n if(iscycle==true){\n return e1;\n }else{\n return e2;\n }\n }\n\n }\n public int find(int x){\n if(dsu[x]==x) return x;\n return dsu[x]=find(dsu[x]);\n }\n}", + "title": "685. Redundant Connection II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n ), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n , and was not an edge that already existed. The resulting graph is given as a 2D-array of edges . Each element of edges is a pair [u i , v i ] that represents a directed edge connecting nodes u i and v i , where u i is a parent of child v i . Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes . If there are multiple answers, return the answer that occurs last in the given 2D-array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == edges.length", + "3 <= n <= 1000", + "edges[i].length == 2", + "1 <= u i , v i <= n", + "u i != v i" + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[1,2],[1,3],[2,3]]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg" + }, + { + "text": "Example 2: Input:edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]Output:[4,1]", + "image": "https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 118 ms (Top 30.98%) | Memory: 14.6 MB (Top 46.10%)\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n # THREE DIFFERENT TYPES OF REDUNDANT TREES CAN EXISIT IDENTIFY THOSE (CYCLE,NOCYCLE,INDEGREE2)\n # CAN BE SOLVED USING DSU OR DFS\n class DSU:\n def __init__(self,n):\n self.parent = [i for i in range(1005)]\n def find(self,node):\n if self.parent[node] == node:\n return node\n self.parent[node] = self.find(self.parent[node])\n return self.parent[node]\n def union(self,node1,node2):\n p1 = self.find(node1)\n p2 = self.find(node2)\n if p1 != p2:\n self.parent[p1] = p2\n def isConnected(self,node1,node2):\n return self.find(node1) == self.find(node2)\n def isValidTree(edges,edge,n):\n d = DSU(n)\n for e in edges:\n if e == edge:\n continue\n d.union(e[0],e[1])\n return d.isConnected(edge[0],edge[1])\n\n indegree = []\n count = defaultdict(int)\n for i,j in edges:\n count[j] = count.get(j,0)+1\n n = len(edges)\n for i in range(n):\n if count[edges[i][1]] == 2:\n indegree += [i]\n if len(indegree) != 0:\n if isValidTree(edges,edges[indegree[-1]],n):\n return edges[indegree[-1]]\n return edges[indegree[0]]\n else:\n d2 = DSU(n)\n for e in edges:\n if d2.isConnected(e[0],e[1]):\n return e\n d2.union(e[0],e[1])\n\n# def dfs(node):\n# if node in seen:\n# return False\n# seen.add(node)\n# for nb in g[node]:\n# if not dfs(nb):\n# return False\n# return True\n# g = defaultdict(list)\n# v = defaultdict(int)\n# total = set()\n# for i,j in edges:\n# g[i] = g.get(i,[]) + [j]\n# v[j] = v.get(j,0) + 1\n# total.add(i)\n# total.add(j)\n# for e in edges[::-1]:\n# g[e[0]].remove(e[1])\n# v[e[1]] -= 1\n# for root in total:\n# seen = set()\n# if v[root] == 0 and dfs(root) and len(seen) == len(total):\n# return e\n\n# v[e[1]] += 1\n# g[e[0]].append(e[1])\n# return [-1,-1]", + "title": "685. Redundant Connection II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a date string in the form Day Month Year , where: Convert the date string to the format YYYY-MM-DD , where: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Day is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"} .", + "Month is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"} .", + "Year is in the range [1900, 2100] ." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"20th Oct 2052\"Output:\"2052-10-20\"", + "image": null + }, + { + "text": "Example 2: Input:date = \"6th Jun 1933\"Output:\"1933-06-06\"", + "image": null + }, + { + "text": "Example 3: Input:date = \"26th May 1960\"Output:\"1960-05-26\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reformatDate(String date) {\n int len = date.length();\n \n String[] monthArray = {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"};\n \n String year = date.substring(len - 4);\n int month = Arrays.asList(monthArray).indexOf(date.substring(len - 8, len - 5)) + 1;\n String day = date.substring(0, len - 11);\n \n StringBuffer sb = new StringBuffer();\n \n sb.append(year + \"-\");\n \n if(month < 10)\n sb.append(\"0\" + month + \"-\");\n else\n sb.append(month + \"-\");\n \n if(day.length() == 1) \n sb.append(\"0\" + day);\n else\n sb.append(day);\n \n return sb.toString();\n }\n}\n", + "title": "1507. Reformat Date", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a date string in the form Day Month Year , where: Convert the date string to the format YYYY-MM-DD , where: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Day is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"} .", + "Month is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"} .", + "Year is in the range [1900, 2100] ." + ], + "examples": [ + { + "text": "Example 1: Input:date = \"20th Oct 2052\"Output:\"2052-10-20\"", + "image": null + }, + { + "text": "Example 2: Input:date = \"6th Jun 1933\"Output:\"1933-06-06\"", + "image": null + }, + { + "text": "Example 3: Input:date = \"26th May 1960\"Output:\"1960-05-26\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 31 ms (Top 93.30%) | Memory: 13.8 MB (Top 98.50%)\nclass Solution:\n def reformatDate(self, date: str) -> str:\n\n m_dict_={\"Jan\":\"01\", \"Feb\":\"02\", \"Mar\":\"03\", \"Apr\":\"04\", \"May\":\"05\", \"Jun\":\"06\", \"Jul\":\"07\", \"Aug\":\"08\", \"Sep\":\"09\", \"Oct\":\"10\", \"Nov\":\"11\", \"Dec\":\"12\"}\n\n day=date[:-11]\n\n if len(day)==1:\n day=\"0\"+day\n\n return(date[-4:] + \"-\" + m_dict_[date[-8:-5]] + \"-\" + day)", + "title": "1507. Reformat Date", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a phone number as a string number . number consists of digits, spaces ' ' , and/or dashes '-' . You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 digits: A single block of length 2.", + "3 digits: A single block of length 3.", + "4 digits: Two blocks of length 2 each." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"1-23-45 6\"Output:\"123-456\"Explanation:The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"123 4-567\"Output:\"123-45-67\"Explanation:The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"123 4-5678\"Output:\"123-456-78\"Explanation:The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 10 ms (Top 38.91%) | Memory: 42.8 MB (Top 36.01%)\nclass Solution {\n String modifiedNumber=\"\";\n public String reformatNumber(String number) {\n modifiedNumber=number.replace(\" \",\"\");\n modifiedNumber=modifiedNumber.replace(\"-\",\"\");\n int l=modifiedNumber.length();\n if(l<=3){\n return modifiedNumber;\n } else if(l==4){\n return modifiedNumber.substring(0,2)+\"-\"+ modifiedNumber.substring(2,4);\n } else {\n modifiedNumber=modifiedNumber.substring(0,3)+\"-\"+reformatNumber(modifiedNumber.substring(3,l));\n }\n return modifiedNumber;\n }\n}", + "title": "1694. Reformat Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a phone number as a string number . number consists of digits, spaces ' ' , and/or dashes '-' . You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows: The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2. Return the phone number after formatting. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 digits: A single block of length 2.", + "3 digits: A single block of length 3.", + "4 digits: Two blocks of length 2 each." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"1-23-45 6\"Output:\"123-456\"Explanation:The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"123 4-567\"Output:\"123-45-67\"Explanation:The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"123 4-5678\"Output:\"123-456-78\"Explanation:The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reformatNumber(self, number: str) -> str:\n s = number.replace(\" \", \"\").replace(\"-\", \"\")\n pieces = list()\n while s:\n if len(s) == 2:\n pieces.append(s)\n break\n elif len(s) == 4:\n pieces.append(s[:2])\n pieces.append(s[2:])\n break\n else:\n pieces.append(s[:3])\n s = s[3:]\n return \"-\".join(pieces)\n", + "title": "1694. Reformat Phone Number", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an alphanumeric string s . ( Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a0b1c2\"Output:\"0a1b2c\"Explanation:No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"\"Explanation:\"leetcode\" has only characters so we cannot separate them by digits.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1229857369\"Output:\"\"Explanation:\"1229857369\" has only digits so we cannot separate them by characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reformat(String s) {\n \n List ch = new ArrayList<>();\n List d = new ArrayList<>();\n \n for(char c : s.toCharArray()){\n if(c >= 'a' && c <= 'z')ch.add(c);\n else d.add(c);\n }\n \n if(Math.abs(d.size() - ch.size()) > 1) return \"\";\n \n StringBuilder str = new StringBuilder();\n \n for(int i = 0; i < s.length(); i++){\n \n if(!ch.isEmpty() || !d.isEmpty()){\n if(ch.size() > d.size())\n str.append(appender(ch,d));\n else \n str.append(appender(d,ch));\n }\n else{\n break;\n }\n }\n \n return new String(str);\n \n }\n \n public String appender(List first,List second){\n \n StringBuilder str = new StringBuilder();\n \n if(!first.isEmpty()){\n str.append(first.get(0));\n first.remove(0);\n }\n if(!second.isEmpty()){\n str.append(second.get(0));\n second.remove(0);\n }\n \n return new String(str);\n }\n}\n", + "title": "1417. Reformat The String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an alphanumeric string s . ( Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a0b1c2\"Output:\"0a1b2c\"Explanation:No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"\"Explanation:\"leetcode\" has only characters so we cannot separate them by digits.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1229857369\"Output:\"\"Explanation:\"1229857369\" has only digits so we cannot separate them by characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reformat(self, s: str) -> str:\n # Store the alphabets and the numerics from the string in a seperat arrays\n alpha = []\n num = []\n # Initiate a res variable to store the resultant string\n res = ''\n \n for i in s:\n if i.isalpha():\n alpha.append(i)\n else:\n num.append(i)\n \n # It's not possible to create a permutation if the absolute difference b/w len(alpha) and len(num) > 1.\n if abs(len(alpha)-len(num)) > 1: return ''\n \n # Use Zip to create list of tuples.\n # For ex:- if alpha = ['a','b'] and num = ['1', '2'] then,\n # zip(alpha, num) = [('a', '1'), ('b', '2')]\n for ch, n in zip(alpha, num):\n res += (ch+n)\n \n if len(alpha) > len(num):\n res += alpha[-1]\n if len(num) > len(alpha):\n res = num[-1] + res\n \n return res\n", + "title": "1417. Reformat The String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/' , '\\' , or blank space ' ' . These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions . Note that backslash characters are escaped, so a '\\' is represented as '\\\\' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 30", + "grid[i][j] is either '/' , '\\' , or ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\" /\",\"/ \"]Output:2", + "image": "https://assets.leetcode.com/uploads/2018/12/15/1.png" + }, + { + "text": "Example 2: Input:grid = [\" /\",\" \"]Output:1", + "image": "https://assets.leetcode.com/uploads/2018/12/15/2.png" + }, + { + "text": "Example 3: Input:grid = [\"/\\\\\",\"\\\\/\"]Output:5Explanation:Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.", + "image": "https://assets.leetcode.com/uploads/2018/12/15/4.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] parent;\n int[] rank;\n \n public int regionsBySlashes(String[] grid) {\n parent = new int[4*grid.length*grid.length];\n rank = new int[4*grid.length*grid.length];\n \n for(int i=0;i 0){\n int obno = (i-1) * grid.length + j;\n unionHelper(4*bno + 0 , 4*obno + 2);\n }\n \n if(j > 0){\n int obno = i * grid.length + (j-1);\n unionHelper(4*bno + 3 , 4*obno + 1);\n }\n \n }\n }\n \n int count = 0;\n \n for(int i=0;i int:\n n=len(grid)\n dots=n+1\n par=[0]*(dots*dots)\n rank=[0]*(dots*dots)\n self.count=1\n\n def find(x):\n if par[x]==x:\n return x\n temp=find(par[x])\n par[x]=temp\n return temp\n def union(x,y):\n lx=find(x)\n ly=find(y)\n if lx!=ly:\n if rank[lx]>rank[ly]:\n par[ly]=lx\n elif rank[lx] 1:\n dp[0][c] = dp[0][c-2]\n for r in range(1,n+1):\n for c in range(1,m+1):\n if p[c-1] == s[r-1] or p[c-1] == '.':\n dp[r][c] = dp[r-1][c-1]\n elif c > 1 and p[c-1] == '*':\n if p[c-2] =='.' or s[r-1]==p[c-2]:\n dp[r][c] =dp[r][c-2] or dp[r-1][c]\n else:\n dp[r][c] = dp[r][c-2]\n return dp[n][m]\n", + "title": "10. Regular Expression Matching", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array score of size n , where score[i] is the score of the i th athlete in a competition. All the scores are guaranteed to be unique . The athletes are placed based on their scores, where the 1 st place athlete has the highest score, the 2 nd place athlete has the 2 nd highest score, and so on. The placement of each athlete determines their rank: Return an array answer of size n where answer[i] is the rank of the i th athlete. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The 1 st place athlete's rank is \"Gold Medal\" .", + "The 2 nd place athlete's rank is \"Silver Medal\" .", + "The 3 rd place athlete's rank is \"Bronze Medal\" .", + "For the 4 th place to the n th place athlete, their rank is their placement number (i.e., the x th place athlete's rank is \"x\" )." + ], + "examples": [ + { + "text": "Example 1: Input:score = [5,4,3,2,1]Output:[\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]Explanation:The placements are [1st, 2nd, 3rd, 4th, 5th].", + "image": null + }, + { + "text": "Example 2: Input:score = [10,3,8,9,4]Output:[\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]Explanation:The placements are [1st, 5th, 3rd, 2nd, 4th].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String[] findRelativeRanks(int[] score) {\n String[] res = new String[score.length];\n TreeMap map = new TreeMap<>();\n for(int i = 0; i < score.length; i++) map.put(score[i], i);\n int rank = score.length;\n for(Map.Entry p: map.entrySet()){\n if(rank == 1) res[p.getValue()] = \"Gold Medal\";\n else if(rank == 2) res[p.getValue()] = \"Silver Medal\";\n else if(rank == 3) res[p.getValue()] = \"Bronze Medal\";\n else res[p.getValue()] = String.valueOf(rank);\n rank--;\n }\n return res;\n }\n}\n", + "title": "506. Relative Ranks", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array score of size n , where score[i] is the score of the i th athlete in a competition. All the scores are guaranteed to be unique . The athletes are placed based on their scores, where the 1 st place athlete has the highest score, the 2 nd place athlete has the 2 nd highest score, and so on. The placement of each athlete determines their rank: Return an array answer of size n where answer[i] is the rank of the i th athlete. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The 1 st place athlete's rank is \"Gold Medal\" .", + "The 2 nd place athlete's rank is \"Silver Medal\" .", + "The 3 rd place athlete's rank is \"Bronze Medal\" .", + "For the 4 th place to the n th place athlete, their rank is their placement number (i.e., the x th place athlete's rank is \"x\" )." + ], + "examples": [ + { + "text": "Example 1: Input:score = [5,4,3,2,1]Output:[\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]Explanation:The placements are [1st, 2nd, 3rd, 4th, 5th].", + "image": null + }, + { + "text": "Example 2: Input:score = [10,3,8,9,4]Output:[\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]Explanation:The placements are [1st, 5th, 3rd, 2nd, 4th].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 162 ms (Top 33.91%) | Memory: 15.3 MB (Top 22.09%)\nclass Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n scores_ids = []\n for i in range(len(score)):\n scores_ids.append((score[i], i))\n scores_ids.sort(reverse=True)\n\n ans = [0] * len(scores_ids)\n for i in range(len(scores_ids)):\n ans[scores_ids[i][1]] = str(i+1)\n\n try:\n ans[scores_ids[0][1]] = \"Gold Medal\"\n ans[scores_ids[1][1]] = \"Silver Medal\"\n ans[scores_ids[2][1]] = \"Bronze Medal\"\n except:\n pass\n\n return ans\n", + "title": "506. Relative Ranks", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2 . Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr1.length, arr2.length <= 1000", + "0 <= arr1[i], arr2[i] <= 1000", + "All the elements of arr2 are distinct .", + "Each arr2[i] is in arr1 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]Output:[2,2,2,1,4,3,3,9,6,7,19]", + "image": null + }, + { + "text": "Example 2: Input:arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]Output:[22,28,8,6,17,44]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 28.58%) | Memory: 43 MB (Top 43.79%)\nclass Solution {\n public int[] relativeSortArray(int[] arr1, int[] arr2) {\n Map map = new TreeMap();\n for(int i = 0; i List[int]:\n\t\t# initialise a dictionary since we're going to want to count the occurences of each element in arr1\n dic = {}\n\t\t# this loop populates the dictionary with the number of occurences for each element\n for elem in arr1:\n if dic.get(elem) is None:\n dic[elem] = 1\n else:\n dic[elem] = dic[elem] + 1\n\t\t# initialise a new list to store the values which exist in both arr2 and arr1\n output = []\n\t\t# populate output with the elements multiplied by their occurences (e.g. [1]*2 = [1, 1])\n for elem in arr2:\n output += [elem]*dic[elem]\n\t\t# initialise a new list to store the elements which are in arr1 but not arr2\n extra_output = []\n\t\t# populate extra_output with these elements multiplied by their occurences. \n\t\t# Note: set(arr1)-set(arr2) provides us with the set of numbers which exist in arr1 but not in arr2\n for elem in set(arr1)-set(arr2):\n extra_output += [elem]*dic[elem]\n\t\t# return the first list and the sorted second list\n return output + sorted(extra_output)\n", + "title": "1122. Relative Sort Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It can be proven that the answer is unique . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbaca\"Output:\"ca\"Explanation:For example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"azxxzy\"Output:\"ay\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 46.58%) | Memory: 54.8 MB (Top 52.34%)\nclass Solution {\n public String removeDuplicates(String s) {\n Stack st=new Stack<>();\n int i=s.length()-1;\n while(i>=0)\n {\n char ch=s.charAt(i);\n if(st.size()>0 && ch==st.peek())\n {\n st.pop();\n }\n else\n {\n st.push(ch);\n }\n i--;\n }\n StringBuilder ans=new StringBuilder(\"\");\n while(!st.isEmpty())\n {\n ans.append(st.pop());\n }\n return ans.toString();\n }\n}", + "title": "1047. Remove All Adjacent Duplicates In String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It can be proven that the answer is unique . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbaca\"Output:\"ca\"Explanation:For example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"azxxzy\"Output:\"ay\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 69 ms (Top 68.51%) | Memory: 18.40 MB (Top 6.96%)\n\nclass Solution:\n def removeDuplicates(self, S: str) -> str:\n stack = []\n for char in S:\n if stack and stack[-1] == char:\n stack.pop()\n else:\n stack.append(char)\n \n return ''.join(stack)\n", + "title": "1047. Remove All Adjacent Duplicates In String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and an integer k , a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It is guaranteed that the answer is unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "2 <= k <= 10^4", + "s only contains lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", k = 2Output:\"abcd\"Explanation:There's nothing to delete.", + "image": null + }, + { + "text": "Example 2: Input:s = \"deeedbbcccbdaa\", k = 3Output:\"aa\"Explanation:First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"pbbcggttciiippooaais\", k = 2Output:\"ps\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 71 ms (Top 53.30%) | Memory: 48.3 MB (Top 81.34%)\nclass Solution\n{\n public String removeDuplicates(String s, int k)\n {\n int i = 0 ;\n StringBuilder newString = new StringBuilder(s) ;\n int[] count = new int[newString.length()] ;\n while( i < newString.length() )\n {\n if( i == 0 || newString.charAt(i) != newString.charAt( i - 1 ) )\n {\n count[i] = 1 ;\n }\n else\n {\n count[i] = count[ i - 1 ] + 1 ;\n if( count[i] == k )\n {\n newString.delete( i - k + 1 , i + 1 ) ;\n i = i - k ;\n }\n }\n i++ ;\n }\n return newString.toString() ;\n }\n}", + "title": "1209. Remove All Adjacent Duplicates in String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s and an integer k , a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made . It is guaranteed that the answer is unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "2 <= k <= 10^4", + "s only contains lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcd\", k = 2Output:\"abcd\"Explanation:There's nothing to delete.", + "image": null + }, + { + "text": "Example 2: Input:s = \"deeedbbcccbdaa\", k = 3Output:\"aa\"Explanation:First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"pbbcggttciiippooaais\", k = 2Output:\"ps\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 309 ms (Top 14.94%) | Memory: 18.7 MB (Top 36.81%)\nclass Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n stack=[]\n res=''\n for i in range(len(s)):\n if len(stack)==0:\n stack.append([s[i],1])\n elif stack[-1][0]==s[i]:\n stack[-1][1]=stack[-1][1]+1\n else:\n stack.append([s[i],1])\n if stack[-1][1]==k:\n stack.pop()\n for i in range(len(stack)):\n res+=stack[i][0]*stack[i][1]\n return res", + "title": "1209. Remove All Adjacent Duplicates in String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and part , perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part . A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Find the leftmost occurrence of the substring part and remove it from s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"daabcbaabcbc\", part = \"abc\"Output:\"dab\"Explanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"axxxxyyyyb\", part = \"xy\"Output:\"ab\"Explanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 38.9%) | Memory: 43.67 MB (Top 34.2%)\n\nclass Solution {\n public String removeOccurrences(String s, String part) {\n // s.replace(part,\"\");\n // System.out.println(s);\n \n while(s.contains(part))\n {\n s=s.replaceFirst(part,\"\");\n }\n return s;\n }\n}", + "title": "1910. Remove All Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and part , perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part . A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Find the leftmost occurrence of the substring part and remove it from s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"daabcbaabcbc\", part = \"abc\"Output:\"dab\"Explanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"axxxxyyyyb\", part = \"xy\"Output:\"ab\"Explanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n n=len(part)\n while part in s:\n i=s.index(part)\n s=s[:i]+s[i+n:]\n return s\n", + "title": "1910. Remove All Occurrences of a Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1 ), remove them and get k * k points. Return the maximum points you can get . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= boxes.length <= 100", + "1 <= boxes[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [1,3,2,2,2,3,4,3,1]Output:23Explanation:[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)", + "image": null + }, + { + "text": "Example 2: Input:boxes = [1,1,1]Output:9", + "image": null + }, + { + "text": "Example 3: Input:boxes = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeBoxes(int[] boxes) {\n int n = boxes.length;\n int[][][] dp = new int[n][n][n];\n for (int i = n-1; i >= 0; i--){\n for (int j = i; j < n; j++){\n for (int k = 0; k < n; k++){\n for (int m = i; m <= j; m++){\n if (boxes[m] == boxes[i]){\n dp[i][j][k]=Math.max(dp[i][j][k], (m-1= 1 ), remove them and get k * k points. Return the maximum points you can get . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= boxes.length <= 100", + "1 <= boxes[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:boxes = [1,3,2,2,2,3,4,3,1]Output:23Explanation:[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)", + "image": null + }, + { + "text": "Example 2: Input:boxes = [1,1,1]Output:9", + "image": null + }, + { + "text": "Example 3: Input:boxes = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeBoxes(self, B):\n \n @lru_cache(None)\n def dp(i, j, k):\n if i > j: return 0\n indx = [m for m in range(i+1, j+1) if B[m] == B[i]]\n ans = (k+1)**2 + dp(i+1, j, 0)\n return max([ans] + [dp(i+1, m-1, 0) + dp(m, j, k+1) for m in indx]) \n \n return dp(0, len(B)-1, 0)", + "title": "546. Remove Boxes", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B' . You are given a string colors of length n where colors[i] is the color of the i th piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first . Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A' . She is not allowed to remove pieces that are colored 'B' .", + "Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B' . He is not allowed to remove pieces that are colored 'A' .", + "Alice and Bob cannot remove pieces from the edge of the line.", + "If a player cannot make a move on their turn, that player loses and the other player wins ." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"AAABABB\"Output:trueExplanation:AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.", + "image": null + }, + { + "text": "Example 2: Input:colors = \"AA\"Output:falseExplanation:Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.", + "image": null + }, + { + "text": "Example 3: Input:colors = \"ABBBBBBBAAA\"Output:falseExplanation:ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 48 ms (Top 5.50%) | Memory: 52.8 MB (Top 84.58%)\nclass Solution {\n public boolean winnerOfGame(String colors) {\n int cntA=0,cntB=0;\n for(int i=1;icntB;\n }\n}", + "title": "2038. Remove Colored Pieces if Both Neighbors are the Same Color", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B' . You are given a string colors of length n where colors[i] is the color of the i th piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first . Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A' . She is not allowed to remove pieces that are colored 'B' .", + "Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B' . He is not allowed to remove pieces that are colored 'A' .", + "Alice and Bob cannot remove pieces from the edge of the line.", + "If a player cannot make a move on their turn, that player loses and the other player wins ." + ], + "examples": [ + { + "text": "Example 1: Input:colors = \"AAABABB\"Output:trueExplanation:AAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.", + "image": null + }, + { + "text": "Example 2: Input:colors = \"AA\"Output:falseExplanation:Alice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.", + "image": null + }, + { + "text": "Example 3: Input:colors = \"ABBBBBBBAAA\"Output:falseExplanation:ABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def winnerOfGame(self, s: str) -> bool:\n \n a = b = 0\n \n for i in range(1,len(s)-1):\n if s[i-1] == s[i] == s[i+1]:\n if s[i] == 'A':\n a += 1\n else:\n b += 1\n \n return a>b\n", + "title": "2038. Remove Colored Pieces if Both Neighbors are the Same Color", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the i th line of the source code. This represents the result of splitting the original source code string by the newline character '\\n' . In C++, there are two types of comments, line comments, and block comments. The first effective comment takes precedence over others. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The string \"//\" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.", + "The string \"/*\" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of \"*/\" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string \"/*/\" does not yet end the block comment, as the ending would be overlapping the beginning." + ], + "examples": [ + { + "text": "Example 1: Input:source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]Output:[\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]Explanation:The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n // variable declaration \nint a, b, c;\n/* This is a test\n multiline \n comment for \n testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n \nint a, b, c;\na = b + c;\n}", + "image": null + }, + { + "text": "Example 2: Input:source = [\"a/*comment\", \"line\", \"more_comment*/b\"]Output:[\"ab\"]Explanation:The original source string is \"a/*comment\\nline\\nmore_comment*/b\", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string \"ab\", which when delimited by newline characters becomes [\"ab\"].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.99 MB (Top 67.1%)\n\nclass Solution {\n public List removeComments(String[] source) {\n boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. \n\t\t//It is initally set to false since we haven't read anything until now. \n\n\n List result = new ArrayList();\n StringBuilder builder = new StringBuilder();\n \n //Read every line from the source input. \n \n for(String line: source){\n// Each time we move on to reading a new line, we check if it is a part of a block comment. \n//If it is already part of a block comment, it means we should skip the implicit newline characters as mentioned in the problem description. \n//For example if Line 1 was \"int a /*Block comment Started\" and Line 2 was \"Block comment ends here */ b;\", and Line 3 was \"int c;\" \n//we want our output to be \"int ab\", \"int c\" instead of \"int a\", \"b;\", \"int c;\" \n if(!blockActive){ \n builder = new StringBuilder();\n }\n for(int i=0; i List[str]:\n ans, inComment = [], False\n new_str = \"\"\n for c in source:\n if not inComment: new_str = \"\"\n i, n = 0, len(c)\n # inComment, we find */\n while i < n:\n if inComment:\n if c[i:i + 2] == '*/' and i + 1 < n:\n i += 2\n inComment = False\n continue\n i += 1\n # not in Comment, we find /* // and common character\n else:\n if c[i:i + 2] == '/*' and i + 1 < n:\n i += 2\n inComment = True\n continue\n if c[i:i + 2] == '//' and i + 1 < n:\n break\n new_str += c[i]\n i += 1\n if new_str and not inComment:\n ans.append(new_str)\n \n\n return ans", + "title": "722. Remove Comments", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array intervals where intervals[i] = [l i , r i ] represent the interval [l i , r i ) , remove all intervals that are covered by another interval in the list. The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d . Return the number of remaining intervals . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 1000", + "intervals[i].length == 2", + "0 <= l i < r i <= 10^5", + "All the given intervals are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,4],[3,6],[2,8]]Output:2Explanation:Interval [3,6] is covered by [2,8], therefore it is removed.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[2,3]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeCoveredIntervals(int[][] intervals) {\n if(intervals == null || intervals.length == 0) return 0;\n Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0]));\n int c = intervals[0][0], d = intervals[0][1];\n int ans = intervals.length;\n for(int i=1;i int:\n\n intervals.sort(key = lambda x: (x[0], -x[1]))\n current, count = intervals[0], 1\n for i in range(1, len(intervals)):\n if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]:\n continue\n current = intervals[i]\n count += 1\n return count\n\n# time and space complexity\n# time: O(nlog(n))\n# space: O(1)", + "title": "1288. Remove Covered Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string number representing a positive integer and a character digit . Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized . The test cases are generated such that digit occurs at least once in number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= number.length <= 100", + "number consists of digits from '1' to '9' .", + "digit is a digit from '1' to '9' .", + "digit occurs at least once in number ." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"123\", digit = \"3\"Output:\"12\"Explanation:There is only one '3' in \"123\". After removing '3', the result is \"12\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"1231\", digit = \"1\"Output:\"231\"Explanation:We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"551\", digit = \"5\"Output:\"51\"Explanation:We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 37.58%) | Memory: 43 MB (Top 24.40%)\nclass Solution {\n public String removeDigit(String number, char digit) {\n List digits = new ArrayList<>();\n for (int i = 0; i < number.length(); i++) {\n if (number.charAt(i) == digit) {\n String stringWithoutDigit = number.substring(0, i) + number.substring(i + 1);\n digits.add(stringWithoutDigit);\n }\n }\n Collections.sort(digits);\n return digits.get(digits.size() - 1);\n }\n}", + "title": "2259. Remove Digit From Number to Maximize Result", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string number representing a positive integer and a character digit . Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized . The test cases are generated such that digit occurs at least once in number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= number.length <= 100", + "number consists of digits from '1' to '9' .", + "digit is a digit from '1' to '9' .", + "digit occurs at least once in number ." + ], + "examples": [ + { + "text": "Example 1: Input:number = \"123\", digit = \"3\"Output:\"12\"Explanation:There is only one '3' in \"123\". After removing '3', the result is \"12\".", + "image": null + }, + { + "text": "Example 2: Input:number = \"1231\", digit = \"1\"Output:\"231\"Explanation:We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".", + "image": null + }, + { + "text": "Example 3: Input:number = \"551\", digit = \"5\"Output:\"51\"Explanation:We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n \n # Initializing the last index as zero\n last_index = 0\n \n #iterating each number to find the occurences, \\\n # and to find if the number is greater than the next element \\ \n\n for num in range(1, len(number)):\n \n # Handling [case 1] and [case 2]\n if number[num-1] == digit:\n if int(number[num]) > int(number[num-1]):\n return number[:num-1] + number[num:]\n else:\n last_index = num - 1\n \n # If digit is the last number (last occurence) in the string [case 3]\n if number[-1] == digit:\n last_index = len(number) - 1\n\n return number[:last_index] + number[last_index + 1:]\n", + "title": "2259. Remove Digit From Number to Maximize Result", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"Output:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"Output:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String removeDuplicateLetters(String s) {\n int[] lastIndex = new int[26];\n for (int i = 0; i < s.length(); i++){\n lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence\n }\n \n boolean[] seen = new boolean[26]; // keep track seen\n Stack st = new Stack();\n \n for (int i = 0; i < s.length(); i++) {\n int curr = s.charAt(i) - 'a';\n if (seen[curr]) continue; // if seen continue as we need to pick one char only\n while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){\n seen[st.pop()] = false; // pop out and mark unseen\n }\n st.push(curr); // add into stack\n seen[curr] = true; // mark seen\n }\n\n StringBuilder sb = new StringBuilder();\n while (!st.isEmpty())\n sb.append((char) (st.pop() + 'a'));\n return sb.reverse().toString();\n }\n}\n", + "title": "316. Remove Duplicate Letters", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"Output:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"Output:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n \n\t\tlast_occ = {}\n\t\tstack = []\n\t\tvisited = set()\n\n\t\tfor i in range(len(s)):\n\t\t\tlast_occ[s[i]] = i\n\n\t\tfor i in range(len(s)):\n\n\t\t\tif s[i] not in visited:\n\t\t\t\twhile (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):\n\t\t\t\t\tvisited.remove(stack.pop())\n\n\t\t\t\tstack.append(s[i])\n\t\t\t\tvisited.add(s[i])\n\n\t\treturn ''.join(stack)\n", + "title": "316. Remove Duplicate Letters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove the duplicates in-place such that each unique element appears only once . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-100 <= nums[i] <= 100", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]Output:2, nums = [1,2,_]Explanation:Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,2,2,3,3,4]Output:5, nums = [0,1,2,3,4,_,_,_,_,_]Explanation:Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.72 MB (Top 69.8%)\n\nclass Solution {\n public int removeDuplicates(int[] arr) {\n int i=0;\n for(int j=1;j int:\n i = 1\n for index in range(1, len(nums)):\n if(nums[index] != nums[index-1]):\n nums[i] = nums[index]\n i += 1\n return i\n", + "title": "26. Remove Duplicates from Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove some duplicates in-place such that each unique element appears at most twice . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3]Output:5, nums = [1,1,2,2,3,_]Explanation:Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,1,2,3,3]Output:7, nums = [0,0,1,1,2,3,3,_,_]Explanation:Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 43.37 MB (Top 93.9%)\n\nclass Solution {\n public int removeDuplicates(int[] nums) {\n int index = 1;\n int count = 0;\n for(int i = 1;i Optional[ListNode]:\n if head is None:\n return head\n cur=head.next\n prev=head\n while cur is not None:\n if cur.val==prev.val:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head\n", + "title": "83. Remove Duplicates from Sorted List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]Output:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 8.62%) | Memory: 43.1 MB (Top 83.93%)\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n if (head == null) return head;\n ListNode temp = head;\n int last = -1;\n int[]array = new int[201];\n // zero == index 100\n // one == index 101;\n // -100 == index 0;\n\n while (temp != null){\n array[temp.val + 100]++;\n temp = temp.next;\n }\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n last = i;\n }\n }\n if (last == -1) return null;\n temp = head;\n\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n temp.val = i - 100;\n if (i == last){\n temp.next = null;\n break;\n }\n temp=temp.next;\n }\n }\n temp.next = null;\n\n return head;\n }\n}```", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]Output:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if (not head):\n return None\n\n result = tail = ListNode(-1)\n\n while(head):\n curr = head\n head = head.next\n hasDup = False\n while(head) and (curr.val == head.val):\n hasDup = True\n headNext = head.next\n head = None\n head = headNext\n\n if (hasDup == False):\n tail.next = curr\n tail = tail.next\n tail.next = None\n\n return result.next\n\n", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer val , remove all occurrences of val in nums in-place . The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 100", + "0 <= nums[i] <= 50", + "0 <= val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,2,3], val = 3Output:2, nums = [2,2,_,_]Explanation:Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2,2,3,0,4,2], val = 2Output:5, nums = [0,1,4,0,3,_,_,_]Explanation:Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.4 MB (Top 71.77%)\n\nclass Solution {\n public int removeElement(int[] nums, int val) {\n int ind = 0;\n for(int i=0; i removeInvalidParentheses(String s) {\n List ans=new ArrayList<>();\n HashSet set=new HashSet();\n \n int minBracket=removeBracket(s);\n getAns(s, minBracket,set,ans);\n \n return ans;\n }\n \n public void getAns(String s, int minBracket, HashSet set, List ans){\n if(set.contains(s)) return;\n \n set.add(s);\n \n if(minBracket==0){\n int remove=removeBracket(s); \n if(remove==0) ans.add(s);\n return;\n }\n \n for(int i=0;i stack=new Stack<>();\n \n for(int i=0;i List[str]:\n ## RC ##\n ## APPROACH : BACK-TRACKING ##\n ## Similar to Leetcode 32. Longest Valid Parentheses ##\n ## LOGIC ##\n # 1. use stack to find invalid left and right braces.\n # 2. if its close brace at index i , you can remove it directly to make it valid and also you can also remove any of the close braces before that i.e in the range [0,i-1]\n # 3. similarly for open brace, left over at index i, you can remove it or any other open brace after that i.e [i+1, end]\n # 4. if left over braces are more than 1 say 2 close braces here, you need to make combinations of all 2 braces before that index and find valid parentheses.\n # 5. so, we count left and right invalid braces and do backtracking removing them\n \n\t\t## TIME COMPLEXITY : O(2^N) ## (each brace has 2 options: exits or to be removed)\n\t\t## SPACE COMPLEXITY : O(N) ##\n\n def isValid(s):\n stack = []\n for i in range(len(s)):\n if( s[i] == '(' ):\n stack.append( (i,'(') )\n elif( s[i] == ')' ):\n if(stack and stack[-1][1] == '('):\n stack.pop()\n else:\n stack.append( (i,')') ) # pushing invalid close braces also\n return len(stack) == 0, stack\n \n \n def dfs( s, left, right):\n visited.add(s)\n if left == 0 and right == 0 and isValid(s)[0]: res.append(s)\n for i, ch in enumerate(s):\n if ch != '(' and ch != ')': continue # if it is any other char ignore.\n if (ch == '(' and left == 0) or (ch == ')' and right == 0): continue # if left == 0 then removing '(' will only cause imbalance. Hence, skip.\n if s[:i] + s[i+1:] not in visited:\n dfs( s[:i] + s[i+1:], left - (ch == '('), right - (ch == ')') )\n \n stack = isValid(s)[1]\n lc = sum([1 for val in stack if val[1] == \"(\"]) # num of left braces\n rc = len(stack) - lc\n \n res, visited = [], set()\n dfs(s, lc, rc)\n return res", + "title": "301. Remove Invalid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given string num representing a non-negative integer num , and an integer k , return the smallest possible integer after removing k digits from num . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= num.length <= 10^5", + "num consists of only digits.", + "num does not have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1432219\", k = 3Output:\"1219\"Explanation:Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:num = \"10200\", k = 1Output:\"200\"Explanation:Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.", + "image": null + }, + { + "text": "Example 3: Input:num = \"10\", k = 2Output:\"0\"Explanation:Remove all the digits from the number and it is left with nothing which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 31 ms (Top 69.83%) | Memory: 55 MB (Top 18.30%)\nclass Solution {\n public String removeKdigits(String num, int k) {\n int n = num.length();\n if(n == k){\n return \"0\";\n }\n Deque dq = new ArrayDeque<>();\n for(char ch : num.toCharArray()){\n while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){\n dq.pollLast();\n k--;\n }\n dq.addLast(ch);\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty() && dq.peekFirst() == '0'){\n dq.pollFirst();\n }\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n if(k >= sb.length()){\n return \"0\";\n }\n return sb.length() == 0 ? \"0\" : sb.toString().substring(0,sb.length()-k);\n }\n}", + "title": "402. Remove K Digits", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given string num representing a non-negative integer num , and an integer k , return the smallest possible integer after removing k digits from num . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= num.length <= 10^5", + "num consists of only digits.", + "num does not have any leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1432219\", k = 3Output:\"1219\"Explanation:Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.", + "image": null + }, + { + "text": "Example 2: Input:num = \"10200\", k = 1Output:\"200\"Explanation:Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.", + "image": null + }, + { + "text": "Example 3: Input:num = \"10\", k = 2Output:\"0\"Explanation:Remove all the digits from the number and it is left with nothing which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict.\n#as soon as len(delete) == k delete those indexes from the initial string and thats the answer.\n#if len(delete) < k remove k-len(delete) chars from right and thats the answer\nclass Solution:\n def removeKdigits(self, s: str, k: int) -> str:\n if len(s) == k:\n return '0'\n stack = []\n delete = {}\n for i in range(len(s)):\n\n while stack and s[i] < stack[-1][0]:\n delete[stack.pop()[1]] = 1\n if len(delete) == k:\n break\n if len(delete) == k:\n return self.deleteindexes(s, delete, k)\n stack.append([s[i], i])\n s1 = self.deleteindexes(s, delete, k)\n\n return str(int(s1[:len(s1)-k +len(delete)]))\n\n\n def deleteindexes(self, s, delete, k):\n if not delete:\n return s\n if len(delete) == k:\n return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete])))\n else:\n return ''.join([c for ind, c in enumerate(s) if ind not in delete])\n\n\n", + "title": "402. Remove K Digits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6Output:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode removeElements(ListNode head, int val) {\n if (head == null) {\n return head;\n }\n ListNode result = head;\n while (head.next != null) {\n if (head.next.val == val) {\n head.next = head.next.next;\n } else {\n head = head.next;\n }\n }\n if (result.val == val) {\n result = result.next;\n }\n return result;\n }\n}\n", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6Output:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 151 ms (Top 10.13%) | Memory: 17.7 MB (Top 81.63%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:\n prev=head\n cur=head\n while cur is not None:\n if cur.val==val:\n if cur==head:\n head=head.next\n prev=head\n else:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob have an undirected graph of n nodes and three types of edges: Given an array edges where edges[i] = [type i , u i , v i ] represents a bidirectional edge of type type i between nodes u i and v i , find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/19/ex1.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex2.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex3.png" + ], + "constraints": [ + "Type 1: Can be traversed by Alice only.", + "Type 2: Can be traversed by Bob only.", + "Type 3: Can be traversed by both Alice and Bob." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]Output:2Explanation:If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]Output:0Explanation:Notice that removing any edge will not make the graph fully traversable by Alice and Bob.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]Output:-1Explanation:In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 29 ms (Top 44.9%) | Memory: 82.52 MB (Top 97.7%)\n\nclass Solution {\n public int maxNumEdgesToRemove(int n, int[][] edges) \n {\n Arrays.sort(edges, (a, b)->{\n return b[0]-a[0];\n });//giving the priority to third type of edge or the edge which Bob and Alice both can access\n \n //1-based indexing of nodes \n int []parentAlice= new int[n+1];//Graph 1 for Alice connectedness\n int []parentBob= new int[n+1];//Graph 2 for Bob connectedness\n \n for(int i= 0; i< n+1; i++){//every node is pointing to itself, at first no connection is considered all sets are independent(no dependency) \n parentAlice[i]= i;\n parentBob[i]= i;\n }\n \n //number of merged unique node for Alice and Bob that are required to maintain the connectedness of Alice and Bob graph nodes//intialised with one because merging happens in pair \n int mergeAlice= 1;\n int mergeBob= 1;\n \n //number of cyclic or the non dependent node, that are not required for the connectedness of Alice and Bob nodes \n int removeEdge= 0;\n \n for(int []edge: edges)\n {\n int cat= edge[0];//category of edge 1)edge Alice can only access 2)edge Bob can only access 3)edge both Alice and Bob can access\n int u= edge[1];\n int v= edge[2];\n \n if(cat == 3){//edge both Alice and Bob an access\n \n //creating dependency of nodes in graph 1 and 2 \n boolean tempAlice= union(u, v, parentAlice);\n boolean tempBob= union(u, v, parentBob);\n \n if(tempAlice == true)\n mergeAlice+= 1;\n \n if(tempBob == true)\n mergeBob+= 1;\n \n if(tempAlice == false && tempBob == false)//retundant or the cyclic non-dependent edge//both Alice and Bob don't rquire it connection is already there between these pair of nodes\n removeEdge+= 1;\n }\n else if(cat == 2){//edge Bob can only access \n \n //creating dependency of nodes in graph 2\n boolean tempBob= union(u, v, parentBob);\n \n if(tempBob == true)\n mergeBob+= 1;\n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n else{//edge Alice can only access \n \n //creating dependency of nodes in graph 1\n boolean tempAlice= union(u, v, parentAlice);\n \n if(tempAlice == true)\n mergeAlice+= 1; \n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n }\n if(mergeAlice != n || mergeBob != n)//all node are not connected, connectedness is not maintained \n return -1;\n return removeEdge;//number of edge removed by maintaining the connectedness \n }\n \n public int find(int x, int[] parent)\n {\n if(parent[x] == x)//when we found the absolute root or the leader of the set \n return x;\n \n int temp= find(parent[x], parent);\n \n parent[x]= temp;//Path Compression//child pointing to the absolute root or the leader of the set, while backtracking\n \n return temp;//returning the absolute root \n }\n \n public boolean union(int x, int y, int[] parent)\n {\n int lx= find(x, parent);//leader of set x or the absolute root\n int ly= find(y, parent);//leader of set y or the absolute root\n \n if(lx != ly){//belong to different set merging \n \n //Rank Compression is not done, but you can do it \n parent[lx]= ly;\n \n return true;//union done, dependency created\n }\n else\n return false;//no union done cycle is due to this edge \n }//Please do Upvote, it helps a lot \n}", + "title": "1579. Remove Max Number of Edges to Keep Graph Fully Traversable", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob have an undirected graph of n nodes and three types of edges: Given an array edges where edges[i] = [type i , u i , v i ] represents a bidirectional edge of type type i between nodes u i and v i , find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/08/19/ex1.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex2.png", + "https://assets.leetcode.com/uploads/2020/08/19/ex3.png" + ], + "constraints": [ + "Type 1: Can be traversed by Alice only.", + "Type 2: Can be traversed by Bob only.", + "Type 3: Can be traversed by both Alice and Bob." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]Output:2Explanation:If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]Output:0Explanation:Notice that removing any edge will not make the graph fully traversable by Alice and Bob.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]Output:-1Explanation:In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.", + "image": null + } + ], + "follow_up": null, + "solution": "class DSUF:\n def __init__(self, n):\n self.arr = [-1] * n\n def find(self, node):\n p = self.arr[node]\n if p == -1:\n return node\n self.arr[node] = self.find(p)\n return self.arr[node]\n def union(self, a, b):\n aP = self.find(a)\n bP = self.find(b)\n if aP == bP:\n return 0\n self.arr[aP] = bP\n return 1\n def countParents(self):\n count = 0\n for i in self.arr:\n if i == -1:\n count += 1\n return count\n\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n # Solution - DSU\n # Time - O(ElogV)\n # Space - O(V)\n \n aliceSet = DSUF(n)\n bobSet = DSUF(n)\n \n bothEdges = []\n bobEdges = []\n aliceEdges= []\n for i in range(len(edges)):\n if edges[i][0] == 3:\n bothEdges.append(edges[i])\n elif edges[i][0] == 1:\n aliceEdges.append(edges[i])\n else:\n bobEdges.append(edges[i])\n \n usedEdgeCount = 0\n \n # connect both edges\n for edge in bothEdges:\n aReq = aliceSet.union(edge[1]-1, edge[2]-1)\n bReq = bobSet.union(edge[1]-1, edge[2]-1)\n if aReq and bReq:\n usedEdgeCount += 1\n \n # connect individual edges\n for edge in aliceEdges:\n usedEdgeCount += aliceSet.union(edge[1]-1, edge[2]-1)\n \n for edge in bobEdges:\n usedEdgeCount += bobSet.union(edge[1]-1, edge[2]-1)\n \n if aliceSet.countParents() == 1 and bobSet.countParents() == 1:\n return len(edges) - usedEdgeCount\n \n return -1\n", + "title": "1579. Remove Max Number of Edges to Keep Graph Fully Traversable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2Output:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 72.17%) | Memory: 42.2 MB (Top 52.18%)\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode temp = head;\n int len=0;\n\n if(head==null || head.next==null)\n return null;\n\n while(temp!=null){\n temp=temp.next;\n len++;\n }\n\n if(len==n)\n return head.next;\n\n int frontlen = len-n-1;\n\n ListNode first=head.next;\n ListNode second = head;\n\n int count=0;\n\n while(first!=null){\n if(count==frontlen){\n second.next=first.next;\n break;\n }else{\n first=first.next;\n second=second.next;\n count++;\n }\n }\n\n return head;\n }\n}", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2Output:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 20.14%) | Memory: 13.9 MB (Top 70.35%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n if head == None:\n return None\n slow = head\n fast = head\n for i in range(n):\n fast = fast.next\n if fast == None:\n return head.next\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next\n slow.next = slow.next.next\n return head", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true . The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,10,5,7]Output:trueExplanation:By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,2]Output:falseExplanation:[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]Output:falseExplanation:The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 78.74%) | Memory: 42.8 MB (Top 79.54%)\nclass Solution {\n public boolean canBeIncreasing(int[] nums) {\n int count=0;\n int p=0;\n for(int i=0;inums[i+1] || nums[i]==nums[i+1]) {\n count++;\n p=i;\n }\n }\n if(count>1) return false;\n else if(count==1){\n if(p==0 || p== nums.length-2) return true;\n if(nums[p+1]>nums[p-1] || nums[p+2]>nums[p]) return true;\n else return false;\n }\n return true;\n }\n}", + "title": "1909. Remove One Element to Make the Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums , return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true . The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 1000", + "1 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,10,5,7]Output:trueExplanation:By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,2]Output:falseExplanation:[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]Output:falseExplanation:The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n indx = -1\n count = 0\n n = len(nums)\n \n # count the number of non-increasing elements\n for i in range(n-1):\n if nums[i] >= nums[i+1]:\n indx = i\n count += 1\n \n #the cases explained above\n if count==0:\n return True\n \n if count == 1:\n if indx == 0 or indx == n-2:\n return True\n if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]):\n return True\n \n return False\n", + "title": "1909. Remove One Element to Make the Array Strictly Increasing", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A valid parentheses string is either empty \"\" , \"(\" + A + \")\" , or A + B , where A and B are valid parentheses strings, and + represents string concatenation. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B , with A and B nonempty valid parentheses strings. Given a valid parentheses string s , consider its primitive decomposition: s = P 1 + P 2 + ... + P k , where P i are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"\" , \"()\" , \"(())()\" , and \"(()(()))\" are all valid parentheses strings." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()())(())\"Output:\"()()()\"Explanation:The input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"(()())(())(()(()))\"Output:\"()()()()(())\"Explanation:The input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"Output:\"\"Explanation:The input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 58.51%) | Memory: 43 MB (Top 43.86%)\nclass Solution {\n public String removeOuterParentheses(String s) {\n // if '(' check stack size > 0 add ans else not add ans\n // if ')' check stack size > 0 add ans else not add ans\n Stack st = new Stack<>();\n StringBuilder sb = new StringBuilder();\n for(int i=0;i 0){\n sb.append(ch);\n }\n st.push(ch);\n }\n\n else{\n st.pop();\n if(st.size() > 0){\n sb.append(ch);\n }\n }\n }\n return sb.toString();\n }\n}", + "title": "1021. Remove Outermost Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A valid parentheses string is either empty \"\" , \"(\" + A + \")\" , or A + B , where A and B are valid parentheses strings, and + represents string concatenation. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B , with A and B nonempty valid parentheses strings. Given a valid parentheses string s , consider its primitive decomposition: s = P 1 + P 2 + ... + P k , where P i are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"\" , \"()\" , \"(())()\" , and \"(()(()))\" are all valid parentheses strings." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()())(())\"Output:\"()()()\"Explanation:The input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"(()())(())(()(()))\"Output:\"()()()()(())\"Explanation:The input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"Output:\"\"Explanation:The input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n c=0\n res=''\n for i in s:\n if i==')' and c==1:\n c=c-1\n elif i=='(' and c==0:\n c=c+1\n elif i=='(':\n res=res+'('\n c=c+1\n elif i==')':\n res=res+')'\n c=c-1\n return res\n", + "title": "1021. Remove Outermost Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting only of letters 'a' and 'b' . In a single step you can remove one palindromic subsequence from s . Return the minimum number of steps to make the given string empty . A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababa\"Output:1Explanation:s is already a palindrome, so its entirety can be removed in a single step.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abb\"Output:2Explanation:\"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"baabb\"Output:2Explanation:\"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.3 MB (Top 19.55%)\nclass Solution\n{\n public int removePalindromeSub(String s)\n {\n int left = 0 , right = s.length() - 1 ;\n while( left < right )\n {\n if( s.charAt(left++) != s.charAt(right--) )\n {\n return 2 ;\n }\n }\n return 1 ;\n }\n}", + "title": "1332. Remove Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s consisting only of letters 'a' and 'b' . In a single step you can remove one palindromic subsequence from s . Return the minimum number of steps to make the given string empty . A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous. A string is called palindrome if is one that reads the same backward as well as forward. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s[i] is either 'a' or 'b' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababa\"Output:1Explanation:s is already a palindrome, so its entirety can be removed in a single step.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abb\"Output:2Explanation:\"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"baabb\"Output:2Explanation:\"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n return 1 if s[::-1] == s else 2\n ", + "title": "1332. Remove Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array piles , where piles[i] represents the number of stones in the i th pile, and an integer k . You should apply the following operation exactly k times: Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations . floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose any piles[i] and remove floor(piles[i] / 2) stones from it." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,4,9], k = 2Output:12Explanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.", + "image": null + }, + { + "text": "Example 2: Input:piles = [4,3,6,7], k = 3Output:12Explanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 304 ms (Top 95.0%) | Memory: 58.55 MB (Top 23.6%)\n\nclass Solution {\n public int minStoneSum(int[] A, int k) {\n PriorityQueue pq = new PriorityQueue<>((a, b)->b - a);\n int res = 0;\n for (int a : A) {\n pq.add(a);\n res += a;\n }\n while (k-- > 0) {\n int a = pq.poll();\n pq.add(a - a / 2);\n res -= a / 2;\n }\n return res;\n }\n}", + "title": "1962. Remove Stones to Minimize the Total", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a 0-indexed integer array piles , where piles[i] represents the number of stones in the i th pile, and an integer k . You should apply the following operation exactly k times: Notice that you can apply the operation on the same pile more than once. Return the minimum possible total number of stones remaining after applying the k operations . floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose any piles[i] and remove floor(piles[i] / 2) stones from it." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,4,9], k = 2Output:12Explanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.", + "image": null + }, + { + "text": "Example 2: Input:piles = [4,3,6,7], k = 3Output:12Explanation:Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n heap = [-p for p in piles]\n heapq.heapify(heap)\n for _ in range(k):\n cur = -heapq.heappop(heap)\n heapq.heappush(heap, -(cur-cur//2))\n return -sum(heap) \n", + "title": "1962. Remove Stones to Minimize the Total", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a list of folders folder , return the folders after removing all sub-folders in those folders . You may return the answer in any order . If a folder[i] is located within another folder[j] , it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not." + ], + "examples": [ + { + "text": "Example 1: Input:folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]Output:[\"/a\",\"/c/d\",\"/c/f\"]Explanation:Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.", + "image": null + }, + { + "text": "Example 2: Input:folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]Output:[\"/a\"]Explanation:Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".", + "image": null + }, + { + "text": "Example 3: Input:folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]Output:[\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n TrieNode root;\n public List removeSubfolders(String[] folder) {\n List res = new ArrayList<>();\n Arrays.sort(folder, (a, b) -> (a.length() - b.length()));\n root = new TrieNode();\n for (String f : folder) {\n if (insert(f)) {\n res.add(f);\n }\n }\n return res;\n }\n \n private boolean insert(String folder) {\n TrieNode node = root;\n char[] chs = folder.toCharArray();\n for (int i = 0; i < chs.length; i++) {\n char ch = chs[i];\n node.children.putIfAbsent(ch, new TrieNode());\n node = node.children.get(ch);\n if (node.isFolder && (i+1 < chs.length && chs[i+1] == '/')) {\n return false;\n }\n }\n node.isFolder = true;\n return true;\n }\n}\n\nclass TrieNode {\n Map children = new HashMap<>();\n boolean isFolder;\n}\n", + "title": "1233. Remove Sub-Folders from the Filesystem", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a list of folders folder , return the folders after removing all sub-folders in those folders . You may return the answer in any order . If a folder[i] is located within another folder[j] , it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not." + ], + "examples": [ + { + "text": "Example 1: Input:folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]Output:[\"/a\",\"/c/d\",\"/c/f\"]Explanation:Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.", + "image": null + }, + { + "text": "Example 2: Input:folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]Output:[\"/a\"]Explanation:Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".", + "image": null + }, + { + "text": "Example 3: Input:folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]Output:[\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# a TrieNode class for creating new node\nclass TrieNode():\n def __init__(self):\n self.children = {}\n self.main = False\n \n# the main class\nclass Solution(object):\n def removeSubfolders(self, folder): \n node = TrieNode()\n res = []\n # sort the list to prevent adding the subfolder to the Trie first\n folder.sort()\n for dir in folder:\n name = dir.split(\"/\")\n if self.addTrie(name,node):\n res.append(dir)\n return res\n\n # usign the same addTrie template and modify the else part\n def addTrie(self,name,node): \n trie = node\n for c in name:\n if c not in trie.children:\n trie.children[c] = TrieNode()\n # if char is in trie,\n else:\n # check if it's the last sub folder. \n if trie.children[c].main == True:\n return False\n trie = trie.children[c]\n trie.main = True\n return True\n", + "title": "1233. Remove Sub-Folders from the Filesystem", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The given linked list will contain between 1 and 1000 nodes.", + "Each node in the linked list has -1000 <= node.val <= 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,-3,3,1]Output:[3,1]Note:The answer [1,2,1] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,2,3,-3,4]Output:[1,2,4]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2,3,-3,-2]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 92.2%) | Memory: 43.00 MB (Top 67.8%)\n\nclass Solution {\n public ListNode removeZeroSumSublists(ListNode head) {\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n \n int prefix = 0;\n ListNode curr = dummy;\n Map seen = new HashMap<>();\n seen.put(prefix, dummy);\n \n while (curr != null) {\n prefix += curr.val;\n seen.put(prefix, curr);\n curr = curr.next;\n }\n \n prefix = 0;\n curr = dummy;\n while (curr != null) {\n prefix += curr.val;\n curr.next = seen.get(prefix).next;\n curr = curr.next;\n }\n \n return dummy.next;\n }\n}", + "title": "1171. Remove Zero Sum Consecutive Nodes from Linked List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list.  You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The given linked list will contain between 1 and 1000 nodes.", + "Each node in the linked list has -1000 <= node.val <= 1000 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,-3,3,1]Output:[3,1]Note:The answer [1,2,1] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:head = [1,2,3,-3,4]Output:[1,2,4]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2,3,-3,-2]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 59 ms (Top 77.27%) | Memory: 14.3 MB (Top 57.10%)\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n root = ListNode(0,head)\n summ , d , node = 0 , {} , root\n while node:\n summ += node.val\n if summ in d:\n prev = d[summ]\n tmp = prev.next\n tmp_sum = summ\n while tmp != node:\n tmp_sum += tmp.val\n if tmp_sum in d and d[tmp_sum] == tmp :d.pop(tmp_sum)\n tmp = tmp.next\n prev.next = node.next\n node = prev\n else:\n d[summ] = node\n node = node.next\n\n return root.next", + "title": "1171. Remove Zero Sum Consecutive Nodes from Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of distinct integers nums . There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "The integers in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,7,5,4,1,8,6]Output:5Explanation:The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,-4,19,1,8,-2,-3,5]Output:3Explanation:The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 3: Input:nums = [101]Output:1Explanation:There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumDeletions(int[] nums) {\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n int minInd = 0;\n int maxInd = 0;\n int n = nums.length;\n \n //First Find out the max and min element index\n for(int i=0;imax){\n max = nums[i];\n maxInd = i;\n }\n \n if(nums[i]minInd){\n int count = Math.min(maxInd+1,n-minInd); // min of all the elements till max element and all the elements to the right of min element\n int count1 = minInd+1+(n-maxInd); // all elements to the left of min and right of max\n return Math.min(count,count1); // min of both\n }\n // min element is right side of the max element\n else{\n int count = Math.min(minInd+1,n-maxInd);\n int count1 = maxInd+1+(n-minInd);\n return Math.min(count,count1);\n }\n \n }\n}", + "title": "2091. Removing Minimum and Maximum From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed array of distinct integers nums . There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "The integers in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,10,7,5,4,1,8,6]Output:5Explanation:The minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,-4,19,1,8,-2,-3,5]Output:3Explanation:The minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.", + "image": null + }, + { + "text": "Example 3: Input:nums = [101]Output:1Explanation:There is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n minFromFront = nums.index(min(nums))\n maxFromFront = nums.index(max(nums))\n \n minFromBack = len(nums) - minFromFront - 1\n maxFromBack = len(nums) - maxFromFront - 1 \n \n return min(max(minFromFront, maxFromFront) + 1, # Case 1\n max(minFromBack, maxFromBack) + 1, # Case 2\n minFromBack + maxFromFront + 2, # Case 3 \n minFromFront + maxFromBack + 2) # Case 4\n", + "title": "2091. Removing Minimum and Maximum From Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of positive integers beans , where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans ( possibly none ) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal . Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= beans.length <= 10^5", + "1 <= beans[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:beans = [4,1,6,5]Output:4Explanation:- We remove 1 bean from the bag with only 1 bean.\n This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer.", + "image": null + }, + { + "text": "Example 2: Input:beans = [2,10,3,2]Output:7Explanation:- We remove 2 beans from one of the bags with 2 beans.\n This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long minimumRemoval(int[] beans) {\n Arrays.parallelSort(beans);\n long sum=0,min=Long.MAX_VALUE;\n int n=beans.length;\n for(int i:beans)\n sum+=i;\n for(int i=0;i int:\n return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))\n", + "title": "2171. Removing Minimum Number of Magic Beans", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array of logs . Each log is a space-delimited string of words, where the first word is the identifier . There are two types of logs: Reorder these logs so that: Return the final order of the logs . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Letter-logs : All words (except the identifier) consist of lowercase English letters.", + "Digit-logs : All words (except the identifier) consist of digits." + ], + "examples": [ + { + "text": "Example 1: Input:logs = [\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]Output:[\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]Explanation:The letter-log contents are all different, so their ordering is \"art can\", \"art zero\", \"own kit dig\".\nThe digit-logs have a relative order of \"dig1 8 1 5 1\", \"dig2 3 6\".", + "image": null + }, + { + "text": "Example 2: Input:logs = [\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\"]Output:[\"g1 act car\",\"a8 act zoo\",\"ab1 off key dog\",\"a1 9 2 3 1\",\"zo4 4 7\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n self._seq=0\n def _sortBy(log):\n a=log.split(' ')\n logType,self._seq=('A',self._seq) if a[1].isalpha() else ('B',self._seq+1)\n return (logType,\" \".join(a[1:]),a[0]) if logType=='A' else (logType,self._seq)\n return sorted(logs,key=_sortBy)\n", + "title": "937. Reorder Data in Log Files", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a singly linked-list. The list can be represented as: Reorder the list to be on the following form: You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5 * 10^4 ] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]Output:[1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5]Output:[1,5,2,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" + }, + { + "text": "L0→ L1→ … → Ln - 1→ Ln", + "image": null + }, + { + "text": "L0→ Ln→ L1→ Ln - 1→ L2→ Ln - 2→ …", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void reorderList(ListNode head) {\n if (head == null) return;\n\t\t\n\t\t// Find start of second list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\t\t\n ListNode list1 = head;\n ListNode list2 = reverseList(slow.next); // slow.next is start of list2\n \n // Break first list from second list!\n slow.next = null; \n \n\t\t// Merge list1 and list2\n while (list2 != null) {\n ListNode l1Next = list1.next;\n ListNode l2Next = list2.next;\n list2.next = list1.next;\n list1.next = list2;\n list1 = l1Next;\n list2 = l2Next;\n }\n }\n \n private ListNode reverseList(ListNode node) {\n if (node == null) return node;\n ListNode newHead = null, currNode = node;\n while (currNode != null) {\n ListNode backup = currNode.next;\n currNode.next = newHead;\n newHead = currNode;\n currNode = backup;\n }\n return newHead;\n }\n}\n", + "title": "143. Reorder List", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the head of a singly linked-list. The list can be represented as: Reorder the list to be on the following form: You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 5 * 10^4 ] .", + "1 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]Output:[1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5]Output:[1,5,2,4,3]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" + }, + { + "text": "L0→ L1→ … → Ln - 1→ Ln", + "image": null + }, + { + "text": "L0→ Ln→ L1→ Ln - 1→ L2→ Ln - 2→ …", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverse(self , head):\n prev = None\n after = None\n curr = head\n while(curr):\n after = curr.next\n curr.next = prev\n prev = curr\n curr = after\n return prev\n \n def find_middle(self , head):\n slow = head\n fast = head\n while(fast and fast.next):\n fast = fast.next.next\n slow = slow.next\n return slow\n \n def reorderList(self, head: Optional[ListNode]) -> None:\n mid = self.find_middle(head)\n rev = self.reverse(mid)\n first = head\n second = rev\n \n while(second.next):\n temp = first.next\n first.next = second\n first = temp\n \n temp = second.next\n second.next = first\n second = temp\n \n", + "title": "143. Reorder List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]Output:3Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]Output:2Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 76.3%) | Memory: 72.93 MB (Top 48.8%)\n\nclass Solution {\n int dfs(List> al, boolean[] visited, int from) {\n int change = 0;\n visited[from] = true;\n for (var to : al.get(from))\n if (!visited[Math.abs(to)])\n change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);\n return change; \n }\n public int minReorder(int n, int[][] connections) {\n List> al = new ArrayList<>();\n for(int i = 0; i < n; ++i) \n al.add(new ArrayList<>());\n for (var c : connections) {\n al.get(c[0]).add(c[1]);\n al.get(c[1]).add(-c[0]);\n }\n return dfs(al, new boolean[n], 0);\n }\n}", + "title": "1466. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]Output:3Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]Output:2Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import defaultdict\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n count, stack, visited = 0, [ 0 ], set() #Add root node to stack\n neighbours = defaultdict(list) #To store neighbours\n\t\tadjacency = defaultdict(list) #To store adjacency\n for i, j in connections:\n adjacency[i].append(j)\n neighbours[i].append(j)\n neighbours[j].append(i)\n while stack:\n current = stack.pop()\n if current in visited:\n continue\n else:\n visited.add(current)\n for i in neighbours[current]:\n if i in visited:\n continue\n if current not in adjacency[i]:\n count += 1\n stack.append(i)\n return count\n", + "title": "1466. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:\"aba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 11.69%) | Memory: 42.5 MB (Top 40.28%)\nclass Solution {\n public String reorganizeString(String s) {\n StringBuilder ans=new StringBuilder(\"\");\n char[] charArray=new char[s.length()];\n Map hashMap=new HashMap<>();\n Queue queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence);\n\n charArray=s.toCharArray();\n\n for(int i=0;inew CharOccurence(e.getKey(),e.getValue()))\n .collect(Collectors.toList()));\n while(!queue.isEmpty())\n {\n Queue tmpQueue=new LinkedList<>();\n int sizeQueue=queue.size();\n int stringLength=ans.length();\n int startSub=(stringLength-1<0)?0:stringLength-1;\n int endSub=stringLength;\n String lastLetter=ans.substring(startSub,endSub);\n boolean letterAdded=false;\n for(int i=0;i0)\n tmpQueue.add(letter);\n letterAdded=true;\n break;\n }\n else\n {\n tmpQueue.add(letter);\n }\n }\n if(!letterAdded)\n return \"\";\n queue.addAll(tmpQueue);\n }\n return ans.toString();\n\n }\n class CharOccurence{\n public Character letter;\n public int occurence;\n public CharOccurence(Character letter, int occurence)\n {\n this.letter=letter;\n this.occurence=occurence;\n }\n }\n}", + "title": "767. Reorganize String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return \"\" if not possible . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:\"aba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef reorganizeString(self, s: str) -> str:\n\t\tc = Counter(s) # for counting the distinct element \n\t\tpq = []\n\t\tfor k,v in c.items(): heapq.heappush(pq,(-v,k)) #multipy by -1 to make max heap \n\t\tans = ''\n\t\twhile pq :\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif ans and ans[-1] == ch: \n\t\t\t\tif not pq: return '' // if heap is empty we cant make the ans return empty string\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\t\treturn ans", + "title": "767. Reorganize String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A' , 'C' , 'G' , and 'T' . When studying DNA , it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence , return all the 10 -letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ACGAATTCCG\" is a DNA sequence ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"Output:[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"AAAAAAAAAAAAA\"Output:[\"AAAAAAAAAA\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 95 ms (Top 6.21%) | Memory: 61.2 MB (Top 61.48%)\nclass Solution {\n public List findRepeatedDnaSequences(String s) {\n HashMap map =new HashMap();\n int i=0;\n int j=0;\n int k=10;\n StringBuilder sb=new StringBuilder(\"\");\n\n while(j list=new ArrayList();\n for(Map.Entry mapElement:map.entrySet()){\n if(mapElement.getValue()>1){\n list.add(mapElement.getKey());\n }\n }\n return list;\n }\n}", + "title": "187. Repeated DNA Sequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A' , 'C' , 'G' , and 'T' . When studying DNA , it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence , return all the 10 -letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"ACGAATTCCG\" is a DNA sequence ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"Output:[\"AAAAACCCCC\",\"CCCCCAAAAA\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"AAAAAAAAAAAAA\"Output:[\"AAAAAAAAAA\"]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 147 ms (Top 16.98%) | Memory: 27.7 MB (Top 15.14%)\nclass Solution(object):\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n seqs = {}\n i = 0\n while i+10 <= len(s):\n curr = s[i:i+10]\n if curr in seqs:\n seqs[curr] = seqs[curr] + 1\n else:\n seqs[curr] = 1\n i += 1\n\n repeats = []\n for seq in list(seqs.keys()):\n if seqs[seq] > 1:\n repeats.append(seq)\n\n return repeats", + "title": "187. Repeated DNA Sequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings a and b , return the minimum number of times you should repeat string a so that string b is a substring of it . If it is impossible for b ​​​​​​ to be a substring of a after repeating it, return -1 . Notice: string \"abc\" repeated 0 times is \"\" , repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"abcd\", b = \"cdabcdab\"Output:3Explanation:We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.", + "image": null + }, + { + "text": "Example 2: Input:a = \"a\", b = \"aa\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 305 ms (Top 62.11%) | Memory: 113.5 MB (Top 30.98%)\nclass Solution {\n public int repeatedStringMatch(String a, String b) {\n String copyA = a;\n int count =1;\n int repeat = b.length()/a.length();\n for(int i=0;i int:\n if len(A) >= len(B):\n if B in A: return 1\n elif B in A*2: return 2\n else: return -1\n prefix = max(0, B.find(A)) #prefix -- length of A1\n repeat, postfix = divmod(len(B)-prefix, len(A)) #postfix -- length of A2\n repeat += bool(prefix) + bool(postfix)\n if B in A * repeat: return repeat\n else: return -1 \n", + "title": "686. Repeated String Match", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abab\"Output:trueExplanation:It is the substring \"ab\" twice.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:s = \"abcabcabcabc\"Output:trueExplanation:It is the substring \"abc\" four times or the substring \"abcabc\" twice.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 324 ms (Top 17.74%) | Memory: 165.9 MB (Top 16.84%)\nclass Solution {\n\n public boolean repeatedSubstringPattern(String s) {\n String temp=\"\";\n for(int i=0 ;i bool:\n for i in range(1, len(s)//2+1):\n if s[:i] * (len(s)//i) == s:\n return True\n return False", + "title": "459. Repeated Substring Pattern", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x) , where c is a character and x is a digit, that returns the x th character after c . For every odd index i , you want to replace the digit s[i] with shift(s[i-1], s[i]) . Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z' . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, shift('a', 5) = 'f' and shift('x', 0) = 'x' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"a1c1e1\"Output:\"abcdef\"Explanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "image": null + }, + { + "text": "Example 2: Input:s = \"a1b2c3d4e\"Output:\"abbdcfdhe\"Explanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 43.86%) | Memory: 42.6 MB (Top 27.39%)\nclass Solution {\n public String replaceDigits(String s) {\n char[] str = s.toCharArray();\n\n for(int i=0;i shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'", + "image": null + }, + { + "text": "Example 2: Input:s = \"a1b2c3d4e\"Output:\"abbdcfdhe\"Explanation:The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 73 ms (Top 5.29%) | Memory: 13.8 MB (Top 58.42%)\nclass Solution(object):\n def replaceDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n res = []\n\n for i in range(len(s)):\n if i % 2 == 0:\n res.append(s[i])\n if i % 2 == 1:\n res.append( chr(ord(s[i-1]) + int(s[i])) )\n\n return ''.join(res)", + "title": "1844. Replace All Digits with Characters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the i th operation you replace the number operations[i][0] with operations[i][1] . It is guaranteed that in the i th operation: Return the array obtained after applying all the operations . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "operations[i][0] exists in nums .", + "operations[i][1] does not exist in nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]Output:[3,2,7,1]Explanation:We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], operations = [[1,3],[2,1],[3,2]]Output:[2,1]Explanation:We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 124 ms (Top 26.09%) | Memory: 164.1 MB (Top 72.68%)\nclass Solution {\n public int[] arrayChange(int[] nums, int[][] operations) {\n Map map = new HashMap<>();\n for(int i=0;i List[int]:\n replacements = {}\n for x, y in reversed(operations):\n replacements[x] = replacements.get(y, y)\n for idx, val in enumerate(nums):\n if val in replacements:\n nums[idx] = replacements[val]\n return nums\n", + "title": "2295. Replace Elements in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array arr , replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1 . After doing so, return the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [17,18,5,4,6,1]Output:[18,6,6,6,1,-1]Explanation:- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [400]Output:[-1]Explanation:There are no elements to the right of index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 67.33%) | Memory: 55.1 MB (Top 5.58%)\nclass Solution {\n public int[] replaceElements(int[] arr) {\n int greatElement = -1;\n for(int i = arr.length-1; i >= 0; i--) {\n int temp = arr[i];\n arr[i] = greatElement;\n greatElement = Math.max(temp, greatElement);\n }\n return arr;\n }\n}", + "title": "1299. Replace Elements with Greatest Element on Right Side", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array arr , replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1 . After doing so, return the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [17,18,5,4,6,1]Output:[18,6,6,6,1,-1]Explanation:- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [400]Output:[-1]Explanation:There are no elements to the right of index 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n maxright = arr[-1]\n for i in range(len(arr) -1,-1,-1):\n temp = arr[i]\n arr[i] = maxright\n if temp > maxright:\n maxright = temp\n arr[-1] = -1\n \n return arr\n", + "title": "1299. Replace Elements with Greatest Element on Right Side", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers nums . Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 10^8 . Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "The test cases are generated such that the values in the final array are less than or equal to 10^8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,4,3,2,7,6,2]Output:[12,7,6]Explanation:- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,3,3,3]Output:[2,1,1,3]Explanation:- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic List replaceNonCoprimes(int[] nums) \n\t{\n\t\tList al=new ArrayList<>();\n\t\tlong n1=nums[0];\n\t\tint idx=1;\n\n\t\twhile(idx 1 where GCD(x, y) is the Greatest Common Divisor of x and y . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5", + "The test cases are generated such that the values in the final array are less than or equal to 10^8 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [6,4,3,2,7,6,2]Output:[12,7,6]Explanation:- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,3,3,3]Output:[2,1,1,3]Explanation:- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n res = []\n for num in nums:\n while res and gcd(res[-1], num) > 1:\n num = lcm(res[-1], num)\n res.pop()\n res.append(num)\n return res\n", + "title": "2197. Replace Non-Coprime Numbers in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of length n containing only four kinds of characters: 'Q' , 'W' , 'E' , and 'R' . A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced . If s is already balanced , return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == s.length", + "4 <= n <= 10^5", + "n is a multiple of 4 .", + "s contains only 'Q' , 'W' , 'E' , and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"QWER\"Output:0Explanation:s is already balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"QQWE\"Output:1Explanation:We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"QQQW\"Output:2Explanation:We can replace the first \"QQ\" to \"ER\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int balancedString(String s) {\n int n = s.length(), ans = n, excess = 0;\n int[] cnt = new int[128];\n cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4;\n for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be removed.\n if (excess == 0) return 0;\n for (int i = 0, j = 0; i < n; i++){//i = window right end, j = window left end\n if (--cnt[s.charAt(i)] == 0) excess--; //remove letter at index i\n while (excess == 0){ //if no more excess, then \n if (++cnt[s.charAt(j)] == 1) excess++; //we put letter at index j back\n ans = Math.min(i - j + 1, ans);; //and update ans accordingly\n j++;\n }\n }\n\n return ans;\n }\n}\n", + "title": "1234. Replace the Substring for Balanced String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s of length n containing only four kinds of characters: 'Q' , 'W' , 'E' , and 'R' . A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string. Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced . If s is already balanced , return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == s.length", + "4 <= n <= 10^5", + "n is a multiple of 4 .", + "s contains only 'Q' , 'W' , 'E' , and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"QWER\"Output:0Explanation:s is already balanced.", + "image": null + }, + { + "text": "Example 2: Input:s = \"QQWE\"Output:1Explanation:We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"QQQW\"Output:2Explanation:We can replace the first \"QQ\" to \"ER\".", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 450 ms (Top 49.65%) | Memory: 14.6 MB (Top 82.17%)\nclass Solution:\n def balancedString(self, s):\n count = collections.Counter(s)\n res = n = len(s)\n if all(n/4==count[char] for char in 'QWER'):\n return 0\n left = 0\n for right, char in enumerate(s):\n # replace char whose index==right to check if it is balanced\n count[char] -= 1\n # if it is balanced, window shrinks to get the smallest length of window\n while left <= right and all(n / 4 >= count[char] for char in 'QWER'):\n res = min(res, right - left + 1)\n count[s[left]] =count[s[left]]+ 1\n left += 1\n return res", + "title": "1234. Replace the Substring for Balanced String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In English, we have a concept called root , which can be followed by some other word to form another longer word - let's call this word successor . For example, when the root \"an\" is followed by the successor word \"other\" , we can form a new word \"another\" . Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root , replace it with the root that has the shortest length . Return the sentence after the replacement. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 100", + "dictionary[i] consists of only lower-case letters.", + "1 <= sentence.length <= 10^6", + "sentence consists of only lower-case letters and spaces.", + "The number of words in sentence is in the range [1, 1000]", + "The length of each word in sentence is in the range [1, 1000]", + "Every two consecutive words in sentence will be separated by exactly one space.", + "sentence does not have leading or trailing spaces." + ], + "examples": [ + { + "text": "Example 1: Input:dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"Output:\"the cat was rat by the bat\"", + "image": null + }, + { + "text": "Example 2: Input:dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"Output:\"a a b c\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};\n\n", + "title": "648. Replace Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In English, we have a concept called root , which can be followed by some other word to form another longer word - let's call this word successor . For example, when the root \"an\" is followed by the successor word \"other\" , we can form a new word \"another\" . Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root , replace it with the root that has the shortest length . Return the sentence after the replacement. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= dictionary.length <= 1000", + "1 <= dictionary[i].length <= 100", + "dictionary[i] consists of only lower-case letters.", + "1 <= sentence.length <= 10^6", + "sentence consists of only lower-case letters and spaces.", + "The number of words in sentence is in the range [1, 1000]", + "The length of each word in sentence is in the range [1, 1000]", + "Every two consecutive words in sentence will be separated by exactly one space.", + "sentence does not have leading or trailing spaces." + ], + "examples": [ + { + "text": "Example 1: Input:dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"Output:\"the cat was rat by the bat\"", + "image": null + }, + { + "text": "Example 2: Input:dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"Output:\"a a b c\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};\n\n", + "title": "648. Replace Words", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "-1000 <= mat[i][j] <= 1000", + "1 <= r, c <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2],[3,4]], r = 1, c = 4Output:[[1,2,3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]], r = 2, c = 4Output:[[1,2],[3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.50%) | Memory: 50.7 MB (Top 48.08%)\nclass Solution {\n public int[][] matrixReshape(int[][] mat, int r, int c) {\n\n if (r * c != mat.length * mat[0].length) {\n return mat;\n }\n\n int[][] ans = new int[r][c];\n\n int i = 0;\n int j = 0;\n\n for(int k = 0; k < mat.length; k++) {\n for(int l = 0; l < mat[0].length; l++) {\n if (j == c) {\n i++;\n j = 0;\n }\n ans[i][j++] = mat[k][l];\n }\n }\n return ans;\n }\n}", + "title": "566. Reshape the Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "-1000 <= mat[i][j] <= 1000", + "1 <= r, c <= 300" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,2],[3,4]], r = 1, c = 4Output:[[1,2,3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,2],[3,4]], r = 2, c = 4Output:[[1,2],[3,4]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg" + } + ], + "follow_up": null, + "solution": "import numpy\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat", + "title": "566. Reshape the Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 ( inclusive ) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s . You are not allowed to reorder or remove any digits in s . You may return the valid IP addresses in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\" , \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"25525511135\"Output:[\"255.255.11.135\",\"255.255.111.35\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"0000\"Output:[\"0.0.0.0\"]", + "image": null + }, + { + "text": "Example 3: Input:s = \"101023\"Output:[\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 15 ms (Top 19.20%) | Memory: 43.5 MB (Top 45.49%)\n\nclass Solution {\n public List restoreIpAddresses(String s) {\n List ans = new ArrayList<>();\n\n int len = s.length();\n for(int i = 1; i < 4 && i < len-2 ; i++ ){\n for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){\n for(int k = j+1 ; k < j + 4 && k < len ; k++){\n String s1 = s.substring(0,i);\n String s2 = s.substring(i,j);\n String s3 = s.substring(j,k);\n String s4 = s.substring(k,len);\n if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))\n ans.add(s1+\".\"+s2+\".\"+s3+\".\"+s4);\n }\n }\n }\n return ans;\n }\n boolean isValid(String s){\n if(s.length() > 3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s) > 255)\n return false;\n return true;\n }\n}", + "title": "93. Restore IP Addresses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 ( inclusive ) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s . You are not allowed to reorder or remove any digits in s . You may return the valid IP addresses in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\" , \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"25525511135\"Output:[\"255.255.11.135\",\"255.255.111.35\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"0000\"Output:[\"0.0.0.0\"]", + "image": null + }, + { + "text": "Example 3: Input:s = \"101023\"Output:[\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def restoreIpAddresses(self, s: str):\n def isValid(st):\n if(len(st)!=len(str(int(st)))):\n return False\n st = int(st)\n if(st>255 or st<0):\n return False\n return True\n \n validIps = []\n for i in range(1,4):\n s1 = s[:i]\n if(not isValid(s1)):\n continue\n for j in range(i+1, min(len(s), i+4)):\n s2 = s[i:j]\n if(not isValid(s2)):\n continue\n for k in range(j+1,min(len(s), j+4)):\n s3 = s[j:k]\n if(not isValid(s3)):\n continue\n s4 = s[k:]\n if(not isValid(s4)):\n continue\n currentIp = s1+\".\"+s2+\".\"+s3+\".\"+s4\n validIps.append(currentIp)\n return validIps\n", + "title": "93. Restore IP Addresses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k , return the number of the possible arrays that can be printed as s using the mentioned program . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only digits and does not contain leading zeros.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1000\", k = 10000Output:1Explanation:The only possible array is [1000]", + "image": null + }, + { + "text": "Example 2: Input:s = \"1000\", k = 10Output:0Explanation:There cannot be an array that was printed this way and has all integer >= 1 and <= 10.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1317\", k = 2000Output:8Explanation:Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 126 ms (Top 51.52%) | Memory: 71.7 MB (Top 43.43%)\nclass Solution {\n static long mod;\n private long solve(int idx,String s,int k,long[] dp){\n if(idx==s.length())\n return 1;\n if(dp[idx]!=-1)\n return dp[idx];\n long max=0,number=0;\n for(int i=idx;i=1 && number<=k){\n max=(max+solve(i+1,s,k,dp))%mod;\n }else\n break;\n }\n return dp[idx]=max;\n }\n public int numberOfArrays(String s, int k) {\n mod = (int)1e9+7;\n long[] dp=new long[s.length()+1];\n Arrays.fill(dp,-1);\n return (int)solve(0,s,k,dp);\n }\n}", + "title": "1416. Restore The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array. Given the string s and the integer k , return the number of the possible arrays that can be printed as s using the mentioned program . Since the answer may be very large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only digits and does not contain leading zeros.", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1000\", k = 10000Output:1Explanation:The only possible array is [1000]", + "image": null + }, + { + "text": "Example 2: Input:s = \"1000\", k = 10Output:0Explanation:There cannot be an array that was printed this way and has all integer >= 1 and <= 10.", + "image": null + }, + { + "text": "Example 3: Input:s = \"1317\", k = 2000Output:8Explanation:Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]", + "image": null + } + ], + "follow_up": null, + "solution": "\"\"\"\n \"1317\"\n[1, 3, 1, 7] -> [1] * nums(317, k)\n[1, 3, 17] \n[1, 31, 7]\n[1, 317] \n[13, 1, 7] -> [13] * nums(17, k)\n[13, 17]\n[131, 7]\n[1317]\n\n\n \"2020\" k = 30\n[2000] x\n[2, 020] x\n[20, 20]\n\n \"67890\" k = 90\n\n[6, 7890] x\n[6, 7, 8, 9, 0] x\n[6, 7, 8, 90] OK\n[6, 78, 90] OK\n[67, 8, 90] OK\n[67, 89, 0] x\n[678, 90] x\nbreak because 678 > k (90), so neither 678, 6789 would be possible numbers\n\n\"\"\"\n\n\n\nclass Solution:\n def num_arrays(self, s, k, memo):\n if not s:\n return 0\n memo_ans = memo.get(s)\n if memo_ans is not None:\n return memo_ans\n \n num = int(s)\n if num <= k:\n counter = 1\n else:\n counter = 0\n \n for i in range(len(s) - 1):\n # Stop when the number to the right side of the array is greater than k\n if int(s[:i + 1]) > k:\n break\n # Don't count leading zeros\n if s[i + 1] == \"0\":\n continue\n counter += self.num_arrays(s[i + 1:], k, memo)\n ans = counter % (10 ** 9 + 7)\n memo[s] = ans\n return ans\n \n def numberOfArrays(self, s: str, k: int) -> int:\n memo = {}\n return self.num_arrays(s, k, memo)\n", + "title": "1416. Restore The Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums . You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [u i , v i ] indicates that the elements u i and v i are adjacent in nums . It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs , either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]] . The pairs can appear in any order . Return the original array nums . If there are multiple solutions, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums.length == n", + "adjacentPairs.length == n - 1", + "adjacentPairs[i].length == 2", + "2 <= n <= 10^5", + "-10^5 <= nums[i], u i , v i <= 10^5", + "There exists some nums that has adjacentPairs as its pairs." + ], + "examples": [ + { + "text": "Example 1: Input:adjacentPairs = [[2,1],[3,4],[3,2]]Output:[1,2,3,4]Explanation:This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.", + "image": null + }, + { + "text": "Example 2: Input:adjacentPairs = [[4,-2],[1,4],[-3,1]]Output:[-2,4,1,-3]Explanation:There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.", + "image": null + }, + { + "text": "Example 3: Input:adjacentPairs = [[100000,-100000]]Output:[100000,-100000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 122 ms (Top 96.49%) | Memory: 87.3 MB (Top 95.99%)\n\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n // Build an adjacency list graph.\n Map> iToPairs = new HashMap<>();\n for (int[] pair : adjacentPairs) {\n iToPairs.computeIfAbsent(pair[0], k -> new ArrayDeque<>()).add(pair[1]);\n iToPairs.computeIfAbsent(pair[1], k -> new ArrayDeque<>()).add(pair[0]);\n }\n\n // Find an item that has only one neighbour.\n int start = -1;\n for (int i : iToPairs.keySet()) {\n if (iToPairs.get(i).size() == 1) {\n start = i;\n break;\n }\n }\n\n // Traverse the graph in a linked-list fashion.\n int n = iToPairs.size();\n int writeIdx = 0;\n int[] restored = new int[n];\n restored[writeIdx++] = start;\n while (writeIdx < n) {\n int next = iToPairs.get(start).remove();\n iToPairs.remove(start);\n iToPairs.get(next).remove(start); // Remove the loop back to the current start.\n restored[writeIdx++] = next;\n start = next;\n }\n\n return restored;\n }\n}", + "title": "1743. Restore the Array From Adjacent Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums . You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [u i , v i ] indicates that the elements u i and v i are adjacent in nums . It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs , either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]] . The pairs can appear in any order . Return the original array nums . If there are multiple solutions, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums.length == n", + "adjacentPairs.length == n - 1", + "adjacentPairs[i].length == 2", + "2 <= n <= 10^5", + "-10^5 <= nums[i], u i , v i <= 10^5", + "There exists some nums that has adjacentPairs as its pairs." + ], + "examples": [ + { + "text": "Example 1: Input:adjacentPairs = [[2,1],[3,4],[3,2]]Output:[1,2,3,4]Explanation:This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.", + "image": null + }, + { + "text": "Example 2: Input:adjacentPairs = [[4,-2],[1,4],[-3,1]]Output:[-2,4,1,-3]Explanation:There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.", + "image": null + }, + { + "text": "Example 3: Input:adjacentPairs = [[100000,-100000]]Output:[100000,-100000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2248 ms (Top 15.65%) | Memory: 166 MB (Top 35.87%)\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n # create the map\n adj = collections.defaultdict(list)\n for a, b in adjacentPairs:\n adj[a].append(b)\n adj[b].append(a)\n\n # find the start num\n start = adjacentPairs[0][0]\n for k, v in adj.items():\n if len(v) ==1:\n start = k\n break\n\n # dfs to connect the graph\n nums=[]\n seen = set()\n def dfs(num):\n seen.add(num)\n for next_num in adj[num]:\n if next_num in seen: continue\n dfs(next_num)\n nums.append(num)\n dfs(start)\n return nums\n", + "title": "1743. Restore the Array From Adjacent Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array deck . There is a deck of cards where every card has a unique integer. The integer on the i th card is deck[i] . You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: Return an ordering of the deck that would reveal the cards in increasing order . Note that the first entry in the answer is considered to be the top of the deck. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= deck.length <= 1000", + "1 <= deck[i] <= 10^6", + "All the values of deck are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [17,13,11,2,3,5,7]Output:[2,13,3,11,5,17,7]Explanation:We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1000]Output:[1,1000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 59.29%) | Memory: 44.5 MB (Top 28.33%)\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) { // deck=[ 17,13,11,2,3,5,7 ]\n Queue ql = new LinkedList();\n for(int i=0;i List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n i += 1\n return ans\n ans = reveal(len(deck))\n ans = sorted([v, i] for i, v in enumerate(ans))\n deck.sort()\n return (deck[j] for i,j in ans)", + "title": "950. Reveal Cards In Increasing Order", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Reverse bits of a given 32 bits unsigned integer. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825 ." + ], + "examples": [ + { + "text": "Example 2 Input:n = 00000010100101000001111010011100Output:964176192 (00111001011110000010100101000000)Explanation:The input binary string00000010100101000001111010011100represents the unsigned integer 43261596, so return 964176192 which its binary representation is00111001011110000010100101000000.", + "image": null + }, + { + "text": "Example 2: Input:n = 11111111111111111111111111111101Output:3221225471 (10111111111111111111111111111111)Explanation:The input binary string11111111111111111111111111111101represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is10111111111111111111111111111111.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need treat n as an unsigned value\n public int reverseBits(int n) {\n int mask = 0;\n int smask = 0;\n int j = 0;\n int rev = 0;\n \n // basically we are checking that the number is set bit or not \n // if the number is set bit then we are appending that to our main answer i.e, rev\n for(int i=31 ; i>=0 ; i--){\n mask = 1<>i)&1\n res=res|bit<<(31-i)\n return res\n", + "title": "190. Reverse Bits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123Output:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123Output:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120Output:21", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.59%) | Memory: 39.60 MB (Top 71.8%)\n\nclass Solution {\n public int reverse(int x) {\n long reverse = 0;\n while (x != 0) {\n int digit = x % 10;\n reverse = reverse * 10 + digit;\n x = x / 10;\n }\n if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0;\n return (int) reverse;\n }\n}\n\n", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123Output:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123Output:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120Output:21", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass Solution:\n def reverse(self, x: int) -> int:\n\n flag = 0\n if x<0:\n x = abs(x)\n flag = 1\n \n l = [i for i in str(x)]\n l.reverse()\n \n ret = ''.join(l)\n ret = int(ret)\n \n if flag == 1:\n ret = ret*-1\n \n if ((ret >= (-(2**31))) and (ret<=((2**31)-1))):\n return ret\n else:\n return 0\n", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]Output:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.5 MB (Top 99.13%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n\n if(head == null || head.next == null) return head;\n\n ListNode curr = head;\n ListNode temp = null, next = curr.next;\n curr.next = null;\n\n while(curr !=null && next !=null)\n {\n // before cutting off link between next & its next, save next.next\n temp = next.next;\n // let next point to curr\n next.next = curr;\n\n curr = next;\n next = temp;\n\n }\n\n return curr;\n\n }\n}", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]Output:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 71 ms (Top 18.71%) | Memory: 15.5 MB (Top 28.33%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head==None or head.next==None:\n return head\n p = None\n while(head != None):\n temp = head.next\n head.next = p\n p = head\n head = temp\n return p\n", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list and two integers left and right where left <= right , reverse the nodes of the list from position left to position right , and return the reversed list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 500", + "-500 <= Node.val <= 500", + "1 <= left <= right <= n" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], left = 2, right = 4Output:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg" + }, + { + "text": "Example 2: Input:head = [5], left = 1, right = 1Output:[5]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if(left==right) return head;\n ListNode last = null;\n ListNode present = head;\n \n for(int i=0; present != null && i Optional[ListNode]:\n # revrese api\n def reverse(start, end):\n prev = None\n cur = start\n while prev != end:\n nextNode = cur.next\n cur.next = prev\n prev = cur\n cur = nextNode\n return prev\n \n if not head or not head.next or right <= left:\n return head\n \n start, end = head, head\n node, afterRight = 0, 0\n \n # At the begining\n if left == 1:\n # start index \n inc = left-1\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n reverse(start, end)\n head = end\n else: # Left other then begining\n # start index \n inc = left-2\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n begin = start # node before left\n start = start.next\n reverse(start, end)\n begin.next = end\n \n # If their's ll chain left agter right chain it to the updated ll\n if afterRight:\n start.next = afterRight\n\n return head\n \n\"\"\"\nTC : O(n)\nSc : O(1)\n\n\"\"\"\n", + "title": "92. Reverse Linked List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers ( 1, 2, 3, 4, ... ). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group . Reverse the nodes in each group with an even length, and return the head of the modified linked list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The 1 st node is assigned to the first group.", + "The 2 nd and the 3 rd nodes are assigned to the second group.", + "The 4 th , 5 th , and 6 th nodes are assigned to the third group, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,2,6,3,9,1,7,3,8,4]Output:[5,6,2,3,9,1,4,8,3,7]Explanation:- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg1.png" + }, + { + "text": "Example 2: Input:head = [1,1,0,6]Output:[1,0,1,6]Explanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg2.png" + }, + { + "text": "Example 3: Input:head = [1,1,0,6,5]Output:[1,0,1,5,6]Explanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/11/17/ex3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 20.66%) | Memory: 252.2 MB (Top 80.33%)\n// This Question can be solved easily using two standard methods of LinkedList\n// 1) addFirst (it adds node in front of the LinkedList)\n// 2) addLast (it adds node in end of the LinkedList)\n\nclass Solution {\n\n static ListNode oh;\n static ListNode ot;\n static ListNode th;\n static ListNode tt;\n\n public ListNode reverseEvenLengthGroups(ListNode head) {\n\n oh = null;\n ot = null;\n th = null;\n tt = null;\n\n if(head == null || head.next == null)\n return head;\n\n int size = length(head);\n int idx = 1;\n ListNode curr = head;\n int group = 1;\n\n while(curr!=null)\n {\n int temp = size - idx + 1;\n if((temp>=group && group%2 == 0) || (temp0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addFirst(curr);\n curr = t;\n idx++;\n }\n }\n else\n {\n int k = group;\n while(k-->0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addLast(curr);\n curr = t;\n idx++;\n }\n }\n\n if(oh==null && ot==null)\n {\n oh = th;\n ot = tt;\n }\n else\n {\n ot.next = th;\n ot = tt;\n }\n\n th = null;\n tt = null;\n group++;\n }\n\n return oh;\n }\n\n public int length (ListNode head)\n {\n if(head==null) return 0;\n ListNode curr = head;\n int k = 0;\n while(curr!=null)\n {\n k++;\n curr = curr.next;\n }\n return k;\n }\n\n public void addFirst(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n head.next = th;\n th = head;\n }\n }\n\n public void addLast(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n tt.next = head;\n tt = head;\n }\n }\n}", + "title": "2074. Reverse Nodes in Even Length Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers ( 1, 2, 3, 4, ... ). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group . Reverse the nodes in each group with an even length, and return the head of the modified linked list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The 1 st node is assigned to the first group.", + "The 2 nd and the 3 rd nodes are assigned to the second group.", + "The 4 th , 5 th , and 6 th nodes are assigned to the third group, and so on." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,2,6,3,9,1,7,3,8,4]Output:[5,6,2,3,9,1,4,8,3,7]Explanation:- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg1.png" + }, + { + "text": "Example 2: Input:head = [1,1,0,6]Output:[1,0,1,6]Explanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.", + "image": "https://assets.leetcode.com/uploads/2021/10/25/eg2.png" + }, + { + "text": "Example 3: Input:head = [1,1,0,6,5]Output:[1,0,1,5,6]Explanation:- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.", + "image": "https://assets.leetcode.com/uploads/2021/11/17/ex3.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 3864 ms (Top 51.07%) | Memory: 53.5 MB (Top 68.62%)\nclass Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n group = 2\n tail = head # tail of previous group\n while tail and tail.next:\n cnt = 1 # actual size of the current group\n cur = tail.next # first node of the current group\n while cur.next and cnt < group:\n cur = cur.next\n cnt += 1\n pre, cur = tail, tail.next\n if cnt % 2 == 0: # if group size is even\n while cnt and cur:\n nxt = cur.next\n cur.next = pre\n pre = cur\n cur = nxt\n cnt -= 1\n first = tail.next # first node of the original group\n first.next = cur\n tail.next = pre\n tail = first\n else:\n while cnt and cur:\n pre, cur = cur, cur.next\n cnt -= 1\n tail = pre\n group += 1\n return head", + "title": "2074. Reverse Nodes in Even Length Groups", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3Output:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n int numOfNodes = count(head);\n ListNode ptr = null;\n List start = new ArrayList<>(), end = new ArrayList<>();\n ListNode f = null;\n while (head != null) {\n if (numOfNodes >= k) {\n start.add(head);\n int count = 0;\n while (count < k) {\n ListNode temp = head.next;\n head.next = ptr;\n ptr = head;\n head = temp;\n count++;\n }\n end.add(ptr);\n ptr = null;\n numOfNodes -= count;\n }\n else {\n f = head;\n break;\n }\n }\n int n = start.size();\n for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);\n start.get(n - 1).next = f;\n return end.get(0);\n }\n public int count(ListNode head) {\n ListNode temp = head;\n int count = 0;\n while (temp != null) {\n count++;\n temp = temp.next;\n }\n return count;\n }\n}\n", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3Output:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n\n # Intialize the result and the current node to the head\n res = node = head\n\n # Initialize the index of the current node to 0\n i = 0\n\n # Initialize the head and tail of the reversed nodes group to None\n reversedHead, reversedTail = None, None\n\n # Initialize the tail of the previous group to None\n previousTail = None\n\n # Iterate through all nodes\n while node:\n\n # When we reach the first node in a group\n if i % k == 0:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have less than k nodes left\n if previousTail:\n previousTail.next = node\n\n # Initialize the head and tail of the reversed nodes group\n reversedHead = reversedTail = ListNode(node.val)\n\n # Continue to reverse subsequent nodes\n else:\n reversedHead = ListNode(node.val, reversedHead)\n\n # If we are able to reach the last node in a reversed nodes group\n if i % k == k - 1:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have k nodes and thus, we should reverse this group\n if previousTail:\n previousTail.next = reversedHead\n\n # Set the tail of the previous group to the tail of the reversed nodes group\n previousTail = reversedTail\n\n # Set the head of the first reversed nodes group as the result\n if i == k - 1:\n res = reversedHead\n\n # Continue to the next node\n i, node = i + 1, node.next\n\n return res\n", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse the string according to the following rules: Return s after reversing it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All the characters that are not English letters remain in the same position.", + "All the English letters (lowercase or uppercase) should be reversed." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab-cd\"Output:\"dc-ba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"a-bC-dEf-ghIj\"Output:\"j-Ih-gfE-dCba\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"Test1ng-Leet=code-Q!\"Output:\"Qedo1ct-eeLg=ntse-T!\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.35%) | Memory: 40.8 MB (Top 87.29%)\nclass Solution {\n public String reverseOnlyLetters(String s) {\n // converting the string to the charArray...\n char[] ch = s.toCharArray();\n\n int start = 0;\n int end = s.length()-1;\n\n // Storing all the english alphabets in a hashmap so that the searching becomes easy...\n HashMap hash = new HashMap<>();\n for(int i=0 ; i<26 ;i++){\n hash.put((char)(97+i) , 1);\n }\n for(int i=0 ; i<26 ; i++){\n hash.put((char)(65+i) , 1);\n }\n\n // using two while loops ..since the constraints are too less thats why we can prefer nested loops approach..\n while(startstart&&!hash.containsKey(ch[end])){\n end--;\n }\n\n // swapping the array elements..\n char temp = ch[start];\n ch[start] = ch[end];\n ch[end] = temp;\n\n start++;\n end--;\n }\n\n // converting the charArray to the string again..\n String ans = new String(ch);\n return ans;\n\n // Time Complexity : O(N) (since the loops will run only till the number of charcters in the string..)\n // Space Complexity : O(N) since we used hashmap..\n }\n}", + "title": "917. Reverse Only Letters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , reverse the string according to the following rules: Return s after reversing it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All the characters that are not English letters remain in the same position.", + "All the English letters (lowercase or uppercase) should be reversed." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ab-cd\"Output:\"dc-ba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"a-bC-dEf-ghIj\"Output:\"j-Ih-gfE-dCba\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"Test1ng-Leet=code-Q!\"Output:\"Qedo1ct-eeLg=ntse-T!\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n st,sp=[],[]\n for i,ch in enumerate(s):\n if ch.isalpha():\n st.append(ch)\n else:\n sp.append([i,ch])\n st=st[::-1]\n for i in sp:\n st.insert(i[0],i[1])\n return (''.join(st))", + "title": "917. Reverse Only Letters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the number of reverse pairs in the array . A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,3,1]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,5,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 354 ms (Top 5.04%) | Memory: 75.8 MB (Top 46.03%)\nclass Solution {\n int cnt;\n public int reversePairs(int[] nums) {\n int n = nums.length;\n cnt = 0;\n sort(0 , n - 1 , nums);\n return cnt;\n }\n void sort(int l , int r , int nums[]){\n if(l == r){\n return;\n }\n int mid = l + (r - l) / 2;\n sort(l , mid , nums);\n sort(mid + 1 , r , nums);\n merge(l , mid , r , nums);\n }\n void merge(int l , int mid , int r , int nums[]){\n int n1 = mid - l + 1;\n int n2 = r - mid;\n int a[] = new int[n1];\n int b[] = new int[n2];\n for(int i = 0; i < n1; i++){\n a[i] = nums[l + i];\n }\n for(int j = 0; j < n2; j++){\n b[j] = nums[mid + 1 + j];\n int idx = upperBound(a , 0 , n1 - 1 , 2L * (long)b[j]);\n if(idx <= n1) {\n cnt += n1 - idx;\n }\n }\n int i = 0;\n int j = 0;\n int k = l;\n while(i < n1 && j < n2){\n if(b[j] <= a[i]){\n nums[k++] = b[j++];\n }\n else{\n nums[k++] = a[i++];\n }\n }\n while(i < n1){\n nums[k++] = a[i++];\n }\n while(j < n2){\n nums[k++] = b[j++];\n }\n }\n int upperBound(int a[] , int l , int r , long x){\n int ans = r + 1;\n while(l <= r){\n int mid = l + (r - l) / 2;\n if((long)a[mid] > x){\n ans = mid;\n r = mid - 1;\n }\n else{\n l = mid + 1;\n }\n }\n return ans;\n }\n}", + "title": "493. Reverse Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of reverse pairs in the array . A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,2,3,1]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,3,5,1]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "from sortedcontainers import SortedList\nclass Solution:\n \"\"\"\n For each sub array nums[0, i]\n We sum the reverse pairs count\n of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1 \n Using a BST(sortedList) to get logN insert and lookup time.\n Time: O(NlogN)\n Space: O(N)\n \"\"\"\n def reversePairs(self, nums: List[int]) -> int:\n res = 0\n bst = SortedList()\n for e in nums:\n res += len(bst) - bst.bisect_left(2 * e + 1) # the count is the N - index\n bst.add(e) # add the the bst\n return res\n", + "title": "493. Reverse Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed string word and a character ch , reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch ( inclusive ). If the character ch does not exist in word , do nothing. Return the resulting string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if word = \"abcdefd\" and ch = \"d\" , then you should reverse the segment that starts at 0 and ends at 3 ( inclusive ). The resulting string will be \" dcba efd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abcdefd\", ch = \"d\"Output:\"dcbaefd\"Explanation:The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".", + "image": null + }, + { + "text": "Example 2: Input:word = \"xyxzxe\", ch = \"z\"Output:\"zxyxxe\"Explanation:The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".", + "image": null + }, + { + "text": "Example 3: Input:word = \"abcd\", ch = \"z\"Output:\"abcd\"Explanation:\"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.37%) | Memory: 42 MB (Top 72.03%)\nclass Solution {\n public String reversePrefix(String word, char ch) {\n char[] c = word.toCharArray();\n int locate = 0;\n for (int i = 0; i < word.length(); i++) { //first occurrence of ch\n if (ch == c[i]) {\n locate = i;\n break;\n }\n }\n char[] res = new char[word.length()];\n for (int i = 0; i <= locate; i++) {\n res[i] = c[locate - i];\n }\n for (int i = locate + 1; i < word.length(); i++) {\n res[i] = c[i];\n }\n return String.valueOf(res);\n }\n}", + "title": "2000. Reverse Prefix of Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 0-indexed string word and a character ch , reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch ( inclusive ). If the character ch does not exist in word , do nothing. Return the resulting string . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if word = \"abcdefd\" and ch = \"d\" , then you should reverse the segment that starts at 0 and ends at 3 ( inclusive ). The resulting string will be \" dcba efd\" ." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"abcdefd\", ch = \"d\"Output:\"dcbaefd\"Explanation:The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".", + "image": null + }, + { + "text": "Example 2: Input:word = \"xyxzxe\", ch = \"z\"Output:\"zxyxxe\"Explanation:The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".", + "image": null + }, + { + "text": "Example 3: Input:word = \"abcd\", ch = \"z\"Output:\"abcd\"Explanation:\"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 84.42%) | Memory: 16.40 MB (Top 68.29%)\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n \"\"\"\n #method 1:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word\"\"\"\n #method 2:\n l=0\n r=word.find(ch)\n word=list(word)\n while l=s.length()){\n sb.append(s);\n sb.reverse();\n return sb.toString();\n }\n for(i=0;i str:\n a=list(s)\n for i in range(0,len(a),2*k):\n a[i:i+k]=a[i:i+k][::-1]\n print(a)\n return(\"\".join(a))", + "title": "541. Reverse String II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1 . You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once . Find maximum possible value of the final array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,5,4]Output:10Explanation:By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,9,24,2,1,10]Output:68", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private int getAbsoluteDifference(int a, int b){\n return Math.abs(a - b);\n }\n public int maxValueAfterReverse(int[] nums) {\n int n = nums.length;\n int result = 0;\n for (int i = 0; i < n - 1; i++)\n result += getAbsoluteDifference(nums[i], nums[i+1]);\n \n int minLine = Integer.MIN_VALUE;\n int maxLine = Integer.MAX_VALUE;\n for (int i = 0; i < n - 1; i++) {\n minLine = Math.max(minLine, Math.min(nums[i], nums[i + 1]));\n maxLine = Math.min(maxLine, Math.max(nums[i], nums[i + 1]));\n }\n int diff = Math.max(0, (minLine - maxLine) * 2);\n for (int i = 1; i < n - 1; i++)\n diff = Math.max(diff, getAbsoluteDifference(nums[0], nums[i+1]) - getAbsoluteDifference(nums[i], nums[i+1]));\n \n for (int i = 0; i < n - 1; i++)\n diff = Math.max(diff, getAbsoluteDifference(nums[n-1], nums[i]) - getAbsoluteDifference(nums[i+1], nums[i]));\n return result + diff;\n }\n}\n", + "title": "1330. Reverse Subarray To Maximize Array Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1 . You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once . Find maximum possible value of the final array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,5,4]Output:10Explanation:By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,9,24,2,1,10]Output:68", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def maxValueAfterReverse(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # basic idea without fancy stuff \n # 1. https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489929/O(n)-time-O(1)-space.-In-depth-Explanation\n # 2. https://code.dennyzhang.com/reverse-subarray-to-maximize-array-value\n \n # This can be done in three steps each step taking O(N) time\n \n res, n = 0, len(nums)\n \n # Step 1: Assume that no subarray is reversed and so the sum would just accumulate over all the abs differences\n for index in range(1, n):\n res += abs(nums[index] - nums[index - 1])\n \n # Step 2: Reversing the left or the right half so basically this idea stems from prefix array type question where in which we have the sum upto ith index but then to get at a specific index we substract extra sum, following from that idea. Or refer to the reference 1\n \n diff = 0\n for index in range(n):\n \n # reversing from 0th index to current\n if index + 1 < n:\n diff = max(diff, abs(nums[index + 1] - nums[0]) - abs(nums[index + 1] - nums[index])) # diff between 0 and curr - diff curr and curr + 1\n \n # reversing from current to last index n - 1\n if index > 0:\n diff = max(diff, abs(nums[index - 1] - nums[n - 1]) - abs(nums[index - 1] - nums[index]))\n \n \n # Step 3: We still need to check the middle reverse part, we can do this using the min max trick\n low_number, high_number = float(\"inf\"), float(\"-inf\")\n \n for index in range(n - 1):\n \n low_number = min(low_number, max(nums[index], nums[index + 1])) # min of low and the max of the current and next number\n high_number = max(high_number, min(nums[index], nums[index + 1]))\n \n\t\t\tdiff = max(diff, 2 * (high_number - low_number)) # This is explained in ref 1\n \n return res + diff\n \n \n", + "title": "1330. Reverse Subarray To Maximize Array Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s only contains lower case English characters and parentheses.", + "It is guaranteed that all parentheses are balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(abcd)\"Output:\"dcba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"(u(love)i)\"Output:\"iloveu\"Explanation:The substring \"love\" is reversed first, then the whole string is reversed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(ed(et(oc))el)\"Output:\"leetcode\"Explanation:First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 52.91%) | Memory: 42.5 MB (Top 42.22%)\nclass Solution {\n public String reverseParentheses(String s) {\n Stack stack = new Stack<>();\n\n int j = 0;\n while(j < s.length()){\n /*\n We need to keep on adding whatever comes\n as long as it is not a ')'.\n */\n if(s.charAt(j) != ')')\n stack.push(s.charAt(j)+\"\");\n\n /*\n Now that we have encountered an ')', its time\n to start popping from top of stack unless we find an opening\n parenthesis\n\n then we just need to reverse the string formed by popping\n and put it back on stack.\n\n Try dry running and it will all make sense\n */\n else{\n StringBuilder sb = new StringBuilder();\n while(!stack.isEmpty() && !stack.peek().equals(\"(\")){\n sb.append(stack.pop());\n }\n\n stack.pop();\n stack.push(sb.reverse().toString());\n }\n j++;\n }\n\n /*\n We have our result string in the stack now,\n we just need to pop it and return the reverse of it.\n */\n StringBuilder res = new StringBuilder();\n while(!stack.isEmpty())\n res.append(stack.pop());\n\n return res.reverse().toString();\n }\n}", + "title": "1190. Reverse Substrings Between Each Pair of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s only contains lower case English characters and parentheses.", + "It is guaranteed that all parentheses are balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(abcd)\"Output:\"dcba\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"(u(love)i)\"Output:\"iloveu\"Explanation:The substring \"love\" is reversed first, then the whole string is reversed.", + "image": null + }, + { + "text": "Example 3: Input:s = \"(ed(et(oc))el)\"Output:\"leetcode\"Explanation:First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = []\n ans = \"\"\n res = deque([])\n s = list(s)\n for i in s:\n if i==\")\":\n while stack[-1] != \"(\":\n res.append(stack.pop())\n stack.pop()\n while res:\n stack.append(res.popleft())\n else:\n stack.append(i)\n return \"\".join(stack)", + "title": "1190. Reverse Substrings Between Each Pair of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both cases. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"hello\"Output:\"holle\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"leotcede\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String reverseVowels(String s) {\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n \n StringBuilder str = new StringBuilder(s);\n int left = 0, right = str.length() - 1;\n while (left < right) {\n if (!set.contains(str.charAt(left))) {\n left++;\n }\n if (!set.contains(str.charAt(right))) {\n right--;\n }\n if (set.contains(str.charAt(left)) && set.contains(s.charAt(right))) {\n char temp = str.charAt(left);\n str.setCharAt(left++, str.charAt(right));\n str.setCharAt(right--, temp);\n }\n }\n return str.toString();\n }\n}\n", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both cases. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"hello\"Output:\"holle\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\"Output:\"leotcede\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseVowels(self, s: str) -> str:\n s=list(s)\n vow=[]\n for i,val in enumerate(s):\n if val in ('a','e','i','o','u','A','E','I','O','U'):\n vow.append(val)\n s[i]='_'\n \n vow=vow[::-1]\n c=0\n print(vow)\n for i,val in enumerate(s):\n if val =='_':\n s[i]=vow[c]\n c+=1\n return \"\".join(s)\n", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string s , reverse the order of the words . A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s contains English letters (upper-case and lower-case), digits, and spaces ' ' .", + "There is at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"the sky is blue\"Output:\"blue is sky the\"", + "image": null + }, + { + "text": "Example 2: Input:s = \" hello world \"Output:\"world hello\"Explanation:Your reversed string should not contain leading or trailing spaces.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a good example\"Output:\"example good a\"Explanation:You need to reduce multiple spaces between two words to a single space in the reversed string.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public String reverseWords(String s) {\n String[] arr = s.replaceAll(\"\\\\s{2,}\", \" \").split(\" \"); \n // splitting based on while spaces by replaceing spaces by single gap \n int n = arr.length;\n String temp = \"\";\n for(int i =0;i List[str]:\n start, end = 0, 0\n\n res = []\n for ch in s:\n if ch == delimiter:\n if start == end:\n start += 1\n else:\n res.append(s[start:end])\n start = end + 1\n \n end += 1\n \n if start != end:\n res.append(s[start:end])\n\n return res\n\n def reverse_list(self, ll: List[str]) -> List[str]:\n l, r = 0, len(ll) - 1\n\n while l < r:\n ll[l], ll[r] = ll[r], ll[l]\n l += 1\n r -= 1\n \n return ll\n\n def reverseWords(self, s: str) -> str:\n\n # split first\n splitted_str_list = self.split(s)\n\n # reverse splitted list\n reversed_str_list = self.reverse_list(splitted_str_list)\n\n # join an return\n return \" \".join(reversed_str_list)", + "title": "151. Reverse Words in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s contains printable ASCII characters.", + "s does not contain any leading or trailing spaces.", + "There is at least one word in s .", + "All the words in s are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Let's take LeetCode contest\"Output:\"s'teL ekat edoCteeL tsetnoc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"God Ding\"Output:\"doG gniD\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 21 ms (Top 36.48%) | Memory: 50.7 MB (Top 54.16%)\nclass Solution {\n public String reverseWords(String s) {\n if(s == null || s.trim().equals(\"\")){\n return null;\n }\n String [] words = s.split(\" \");\n StringBuilder resultBuilder = new StringBuilder();\n for(String word: words){\n for(int i = word.length() - 1; i>=0; i --){\n resultBuilder.append(word.charAt(i));\n }\n resultBuilder.append(\" \");\n }\n return resultBuilder.toString().trim();\n }\n}", + "title": "557. Reverse Words in a String III", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^4", + "s contains printable ASCII characters.", + "s does not contain any leading or trailing spaces.", + "There is at least one word in s .", + "All the words in s are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Let's take LeetCode contest\"Output:\"s'teL ekat edoCteeL tsetnoc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"God Ding\"Output:\"doG gniD\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def reverseWords(self, s: str) -> str:\n s = s + ' '\n l = len(s)\n t = ''\n w = ''\n for i in range(l):\n if s[i]!=' ':\n t = s[i] + t # t stores the word in reverse order\n else:\n\t\t\t\t# w stores the reversed word in the same order\n w = w + t + ' ' # could have used .join() function and not write .strip()\n t = \"\" # value of t is null so that it won't affect upcoming words\n return w.strip() # removes extra whitespace\n", + "title": "557. Reverse Words in a String III", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​ ​​​​​​th ​​​​ customer has in the j​​​​​ ​​​​​​th ​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == accounts.length", + "n == accounts[i].length", + "1 <= m, n <= 50", + "1 <= accounts[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[1,2,3],[3,2,1]]Output:6Explanation:1st customer has wealth = 1 + 2 + 3 = 62nd customer has wealth = 3 + 2 + 1 = 6Both customers are considered the richest with a wealth of 6 each, so return 6.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[1,5],[7,3],[3,5]]Output:10Explanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.", + "image": null + }, + { + "text": "Example 3: Input:accounts = [[2,8,7],[7,1,3],[1,9,5]]Output:17", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 56.03%) | Memory: 43.3 MB (Top 46.87%)\nclass Solution {\n public int maximumWealth(int[][] accounts) {\n int res = 0;\n for(int i =0;i int:\n return max(map(sum, accounts))", + "title": "1672. Richest Customer Wealth", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9 . You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The first character of the i th pair denotes the i th ring's color ( 'R' , 'G' , 'B' ).", + "The second character of the i th pair denotes the rod that the i th ring is placed on ( '0' to '9' )." + ], + "examples": [ + { + "text": "Example 1: Input:rings = \"B0B6G0R6R0R6G9\"Output:1Explanation:- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex1final.png" + }, + { + "text": "Example 2: Input:rings = \"B0R0G0R9R0B0G0\"Output:1Explanation:- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex2final.png" + }, + { + "text": "Example 3: Input:rings = \"G4\"Output:0Explanation:Only one ring is given. Thus, no rods have all three colors.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.71%) | Memory: 40.70 MB (Top 25.29%)\n\nclass Solution {\n public int countPoints(String rings) {\n Map> m=new HashMap<>();\n for(int i=0;i x=m.get(index);\n x.add(c);\n m.put(index,x);\n }else{\n Set x=new HashSet<>();\n x.add(c);\n m.put(index,x);\n }\n }\n int count=0;\n for(Set k : m.values()){\n if(k.size()==3) count++;\n }\n return count;\n }\n}\n", + "title": "2103. Rings and Rods", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9 . You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The first character of the i th pair denotes the i th ring's color ( 'R' , 'G' , 'B' ).", + "The second character of the i th pair denotes the rod that the i th ring is placed on ( '0' to '9' )." + ], + "examples": [ + { + "text": "Example 1: Input:rings = \"B0B6G0R6R0R6G9\"Output:1Explanation:- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex1final.png" + }, + { + "text": "Example 2: Input:rings = \"B0R0G0R9R0B0G0\"Output:1Explanation:- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/23/ex2final.png" + }, + { + "text": "Example 3: Input:rings = \"G4\"Output:0Explanation:Only one ring is given. Thus, no rods have all three colors.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 56 ms (Top 27.28%) | Memory: 13.8 MB (Top 63.52%)\nclass Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if 'R'+i in r and 'G'+i in r and 'B'+i in r:\n ans += 1\n return ans", + "title": "2103. Rings and Rods", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We can use run-length encoding (i.e., RLE ) to encode a sequence of integers. In a run-length encoded array of even length encoding ( 0-indexed ), for all even i , encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. Given a run-length encoded array, design an iterator that iterates through it. Implement the RLEIterator class: Example 1:", + "description_images": [], + "constraints": [ + "For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5] . encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]Output[null, 8, 8, 5, -1]ExplanationRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class RLEIterator {\n \n long[] prefixEncoded;\n long processed = 0;\n int l = 0;\n\n public RLEIterator(int[] encoding) {\n int encodeLen = encoding.length;\n this.prefixEncoded = new long[encodeLen];\n for(int i=0;i 0) {\n prevPrefixSum = this.prefixEncoded[i-2];\n }\n this.prefixEncoded[i] = encoding[i] + prevPrefixSum;\n this.prefixEncoded[i+1] = encoding[i+1];\n }\n }\n\n public int next(int n) {\n int r = this.prefixEncoded.length-2;\n \n processed += n;\n \n if(l >= this.prefixEncoded.length || processed > this.prefixEncoded[this.prefixEncoded.length - 2]) {\n return -1;\n }\n \n while(l < r) {\n int m = (l + ((r-l)/2));\n if(m % 2 != 0) {\n m = m - 1;\n }\n if(this.prefixEncoded[m] >= processed) {\n r = m;\n } else {\n l = m + 2;\n }\n }\n return l >= this.prefixEncoded.length ? -1: (int) this.prefixEncoded[l + 1];\n } \n}\n", + "title": "900. RLE Iterator", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We can use run-length encoding (i.e., RLE ) to encode a sequence of integers. In a run-length encoded array of even length encoding ( 0-indexed ), for all even i , encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence. Given a run-length encoded array, design an iterator that iterates through it. Implement the RLEIterator class: Example 1:", + "description_images": [], + "constraints": [ + "For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5] . encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]Output[null, 8, 8, 5, -1]ExplanationRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 64 ms (Top 41.88%) | Memory: 14.5 MB (Top 71.25%)\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n\n def next(self, n: int) -> int:\n\n if self.encoding:\n\n count = self.encoding[0]\n\n if count >= n:\n # Partially exhaust and return the current value.\n self.encoding[0] -= n\n return self.encoding[1]\n\n # Exhaust all of current value and continue.\n self.encoding = self.encoding[2:]\n return self.next(n - count)\n\n return -1", + "title": "900. RLE Iterator", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The robot can receive one of three instructions: The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The north direction is the positive direction of the y-axis.", + "The south direction is the negative direction of the y-axis.", + "The east direction is the positive direction of the x-axis.", + "The west direction is the negative direction of the x-axis." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = \"GGLLGG\"Output:trueExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.", + "image": null + }, + { + "text": "Example 2: Input:instructions = \"GG\"Output:falseExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.", + "image": null + }, + { + "text": "Example 3: Input:instructions = \"GL\"Output:trueExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 16.85%) | Memory: 41.9 MB (Top 53.99%)\nclass Solution {\n public boolean isRobotBounded(String instructions) {\n if (instructions.length() == 0) {\n return true;\n }\n\n Robot bender = new Robot();\n int[] start = new int[]{0, 0};\n\n // 4 represents the max 90 degree turns that can restart initial orientation.\n for (int i = 0; i < 4; i++) {\n boolean orientationChanged = bender.performSet(instructions);\n\n int[] location = bender.location;\n if (location[0] == start[0] && location[1] == start[1]) {\n return true;\n }\n\n // If robot never turns and the first instruction isn't at start, exit.\n else if (!orientationChanged) {\n return false;\n }\n }\n\n return false;\n }\n}\n\nclass Robot {\n int[] location;\n int[] orientation;\n int[][] orientations;\n int orientationPos;\n boolean orientationChangeCheck;\n\n Robot() {\n // Start in center\n location = new int[]{0, 0};\n\n // N, E, S, W\n orientations = new int[][]{{1,0}, {0, 1}, {-1, 0}, {0, -1}};\n\n // Start pointing north\n orientationPos = 0;\n orientation = orientations[orientationPos];\n\n // Track if robot has turned\n orientationChangeCheck = false;\n }\n\n public boolean performSet(String orders) {\n this.orientationChangeCheck = false;\n\n for (int i = 0; i < orders.length(); i++) {\n this.perform(orders.charAt(i));\n }\n\n return this.orientationChangeCheck;\n }\n\n public void perform(char order) {\n if (order == 'G') {\n this.go();\n } else if (order == 'L' || order == 'R') {\n this.turn(order);\n } else {\n // do nothing\n }\n }\n\n public void turn(char direction) {\n if (direction == 'L') {\n this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;\n } else if (direction == 'R') {\n this.orientationPos = (this.orientationPos + 1) % 4;\n }\n\n this.orientation = this.orientations[this.orientationPos];\n this.orientationChangeCheck = true;\n }\n\n public int[] go() {\n this.location[0] += this.orientation[0];\n this.location[1] += this.orientation[1];\n return this.location;\n }\n}", + "title": "1041. Robot Bounded In Circle", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The robot can receive one of three instructions: The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The north direction is the positive direction of the y-axis.", + "The south direction is the negative direction of the y-axis.", + "The east direction is the positive direction of the x-axis.", + "The west direction is the negative direction of the x-axis." + ], + "examples": [ + { + "text": "Example 1: Input:instructions = \"GGLLGG\"Output:trueExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.", + "image": null + }, + { + "text": "Example 2: Input:instructions = \"GG\"Output:falseExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.", + "image": null + }, + { + "text": "Example 3: Input:instructions = \"GL\"Output:trueExplanation:The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 34 ms (Top 89.04%) | Memory: 14 MB (Top 22.71%)\n\nclass Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n pos, d = [0,0], \"N\"\n def move(d, pos, instructions):\n for i in instructions:\n if i == \"G\":\n if d == \"N\": pos[1] += 1\n elif d == \"S\": pos[1] -= 1\n elif d == \"W\": pos[0] -= 1\n else: pos[0] += 1\n elif i == \"L\":\n if d == \"N\": d = \"W\"\n elif d == \"W\": d = \"S\"\n elif d == \"S\": d = \"E\"\n else: d = \"N\"\n else:\n if d == \"N\": d = \"E\"\n elif d == \"W\": d = \"N\"\n elif d == \"S\": d = \"W\"\n else: d = \"S\"\n return (d, pos)\n for i in range(4):\n d, pos = (move(d, pos, instructions))\n return True if pos == [0,0] else False", + "title": "1041. Robot Bounded In Circle", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a robot starting at the position (0, 0) , the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. You are given a string moves that represents the move sequence of the robot where moves[i] represents its i th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise . Note : The way that the robot is \"facing\" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= moves.length <= 2 * 10^4", + "moves only contains the characters 'U' , 'D' , 'L' and 'R' ." + ], + "examples": [ + { + "text": "Example 1: Input:moves = \"UD\"Output:trueExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:moves = \"LL\"Output:falseExplanation: The robot moves left twice. It ends up two \"moves\" to the left of the origin. We return false because it is not at the origin at the end of its moves.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean judgeCircle(String moves) {\n int up=0;\n int rt=0;\n for(int i=0;i bool:\n x=Counter(moves)\n flag=False\n if(x['U']==x['D'] and x['L']==x['R']):\n flag=True\n return flag", + "title": "657. Robot Return to Origin", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"III\"Output:3Explanation:III = 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"LVIII\"Output:58Explanation:L = 50, V= 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:s = \"MCMXCIV\"Output:1994Explanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 63.45%) | Memory: 44.6 MB (Top 83.79%)\nclass Solution {\n public int romanToInt(String s) {\n int res=0;\n // Let s = \"IV\" after traversing string res will be 6\n // Let s= \"IX\" after traversing string res will be 11\n for(int i=0;i int:\n roman = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n\n sum = 0;\n for i in range(0, len(s) - 1):\n curr = roman[s[i]]\n nxt = roman[s[i + 1]]\n if curr < nxt:\n sum -= curr\n else:\n sum += curr\n sum += roman[s[-1]]\n return sum", + "title": "13. Roman to Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The tree consists only of the root, its left child, and its right child.", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,4,6]Output:trueExplanation:The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png" + }, + { + "text": "Example 2: Input:root = [5,3,1]Output:falseExplanation:The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 77.34%) | Memory: 41.9 MB (Top 35.55%)\nclass Solution\n{\n public boolean checkTree(TreeNode root)\n {\n return root.val == root.left.val + root.right.val; // O(1)\n }\n}", + "title": "2236. Root Equals Sum of Children", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The tree consists only of the root, its left child, and its right child.", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,4,6]Output:trueExplanation:The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png" + }, + { + "text": "Example 2: Input:root = [5,3,1]Output:falseExplanation:The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.", + "image": "https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)", + "title": "2236. Root Equals Sum of Children", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7], k = 3Output:[5,6,7,1,2,3,4]Explanation:rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-100,3,99], k = 2Output:[3,99,-1,-100]Explanation:rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[] nums, int k) {\n reverse(nums , 0 , nums.length-1);\n reverse(nums , 0 , k-1);\n reverse(nums , k , nums.length -1);\n }\n \n public static void reverse(int[] arr , int start , int end){\n while(start None:\n length = len(nums)\n k = k % length\n l, r = 0, length - 1\n nums = self.reverse(nums,l,r)\n l, r = 0, k - 1\n nums = self.reverse(nums,l,r)\n l, r = k, length - 1\n nums = self.reverse(nums,l,r)\n return nums", + "title": "189. Rotate Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n . Assume arr k to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow: Return the maximum value of F(0), F(1), ..., F(n-1) . The test cases are generated so that the answer fits in a 32-bit integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "F(k) = 0 * arr k [0] + 1 * arr k [1] + ... + (n - 1) * arr k [n - 1]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,3,2,6]Output:26Explanation:F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.", + "image": null + }, + { + "text": "Example 2: Input:nums = [100]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 100.00%) | Memory: 54.3 MB (Top 98.33%)\nclass Solution {\n public int maxRotateFunction(int[] nums) {\n int sum1 =0,sum2 = 0;\n for(int i=0;i int:\n preSum, cur = 0, 0\n for i in range(len(nums)):\n cur += i * nums[i]\n preSum += nums[i]\n ans = cur\n for i in range(1, len(nums)):\n cur -= len(nums) * nums[len(nums) - i]\n cur += preSum\n ans = max(ans, cur)\n return ans", + "title": "396. Rotate Function", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.7 MB (Top 54.90%)\nclass Solution {\n public void swap(int[][] matrix, int n1, int m1, int n2, int m2) {\n int a = matrix[n1][m1];\n int temp = matrix[n2][m2];\n matrix[n2][m2] = a;\n matrix[n1][m1] = temp;\n }\n public void rotate(int[][] matrix) {\n int n = matrix.length;\n for (int i = 0; i < n/2; i++) {\n for (int j = 0; j < n; j++) {\n swap(matrix, i,j, n-i-1, j);\n }\n }\n for (int i = n-1; i >= 0; i--) {\n for (int j = 0; j < i; j++) {\n swap(matrix, i,j, j, i);\n }\n }\n }\n}", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n \n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n # transpose \n size = len(matrix)\n for i in range(size):\n for j in range(i+1, size):\n matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]\n \n print(matrix)\n \n # reverse row\n for row in range(len(matrix)):\n matrix[row] = matrix[row][::-1]\n \n print(matrix)\n", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the head of a linked list, rotate the list to the right by k places. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4Output:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public ListNode rotateRight(ListNode head, int k) {\n if(k<=0 || head==null || head.next==null){\n return head;\n }\n \n int length=1;\n ListNode first=head;\n ListNode curr=head;\n ListNode node=head; \n while(node.next!=null){\n length++;\n node=node.next;\n }\n \n if(k==length){\n return head;\n }\n \n int n=length-(k%length);\n for(int i=0; i1\n head=curr.next;\n curr.next=null;\n \n return head;\n }\n}\n", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the head of a linked list, rotate the list to the right by k places. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4Output:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if k==0 or head is None or head.next is None:\n return head\n cur=head\n n=0\n while cur is not None:\n cur=cur.next\n n+=1\n k=n-k%n\n if k==n:\n return head\n cur=head\n prev=None\n while k>0 and cur is not None:\n prev=cur\n cur=cur.next\n k-=1\n prev.next=None\n prev=cur\n while cur.next is not None:\n cur=cur.next\n cur.next=head\n return prev\n \n", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s . A shift on s consists of moving the leftmost character of s to the rightmost position. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if s = \"abcde\" , then it will be \"bcdea\" after one shift." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", goal = \"cdeab\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\", goal = \"abced\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.5 MB (Top 17.04%)\nclass Solution {\n public boolean rotateString(String s, String goal) {\n int n = s.length(), m = goal.length();\n if (m != n) return false;\n\n for (int offset = 0; offset < n; offset++) {\n if (isMatch(s, goal, offset)) return true;\n }\n return false;\n }\n\n private boolean isMatch(String s, String g, int offset) {\n int n = s.length();\n for (int si = 0; si < n; si++) {\n int gi = (si + offset) % n;\n if (s.charAt(si) != g.charAt(gi)) return false;\n }\n return true;\n }\n}", + "title": "796. Rotate String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and goal , return true if and only if s can become goal after some number of shifts on s . A shift on s consists of moving the leftmost character of s to the rightmost position. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if s = \"abcde\" , then it will be \"bcdea\" after one shift." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcde\", goal = \"cdeab\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\", goal = \"abced\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 33 ms, faster than 90.10% of Python3 online submissions for Rotate String.\n# Memory Usage: 13.8 MB, less than 97.64% of Python3 online submissions for Rotate String.\n\nclass Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n for x in range(len(s)):\n s = s[-1] + s[:-1]\n if (goal == s):\n return True\n return False\n", + "title": "796. Rotate String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x . Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: Given an integer n , return the number of good integers in the range [1, n] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 , 1 , and 8 rotate to themselves,", + "2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),", + "6 and 9 rotate to each other, and", + "the rest of the numbers do not rotate to any other number and become invalid." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:4Explanation:There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:0", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 82.34%) | Memory: 39.1 MB (Top 97.40%)\nclass Solution {\n public int rotatedDigits(int n) {\n int ans=0;\n for(int i=1; i<=n; i++){\n int k = i;\n boolean bool1=true; boolean bool2=false;\n while(k>0){\n int m=k%10;\n if(m==3 || m==4 || m==7){ bool1=false; break; }\n else if(m==2 || m==5 || m==6 || m==9){ bool2=true; }\n k/=10;\n }\n if(bool1 && bool2){ ans++; }\n }\n return ans;\n }\n}", + "title": "788. Rotated Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x . Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: Given an integer n , return the number of good integers in the range [1, n] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 , 1 , and 8 rotate to themselves,", + "2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),", + "6 and 9 rotate to each other, and", + "the rest of the numbers do not rotate to any other number and become invalid." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:4Explanation:There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:0", + "image": null + }, + { + "text": "Example 3: Input:n = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 226 ms (Top 14.46%) | Memory: 13.9 MB (Top 71.45%)\nclass Solution:\n def rotatedDigits(self, n: int) -> int:\n d={\n 0:0,\n 1:1,\n 2:5,\n 3:None,\n 4: None,\n 5:2,\n 6:9,\n 7:None,\n 8:8,\n 9:6\n }\n res=0\n for i in range(n+1):\n t=i\n pos=0\n temp=0\n status=True\n while t>0:\n r=d[t%10] #Every Digit Rotation Is Must, We Don't Have Choice To Leave It Without Rotating\n if r is None:\n status=False\n break\n\n temp+=((10**pos)*r)\n pos+=1\n t=t//10\n\n if temp!=i and status:\n res+=1\n return res", + "title": "788. Rotated Digits", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise , causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcodewithstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode2withstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode3withstone.png" + ], + "constraints": [ + "A stone '#'", + "A stationary obstacle '*'", + "Empty '.'" + ], + "examples": [ + { + "text": "Example 1: Input:box = [[\"#\",\".\",\"#\"]]Output:[[\".\"],\n  [\"#\"],\n  [\"#\"]]", + "image": null + }, + { + "text": "Example 2: Input:box = [[\"#\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"*\",\".\"]]Output:[[\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\"*\",\"*\"],\n  [\".\",\".\"]]", + "image": null + }, + { + "text": "Example 3: Input:box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n  [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]Output:[[\".\",\"#\",\"#\"],\n  [\".\",\"#\",\"#\"],\n  [\"#\",\"#\",\"*\"],\n  [\"#\",\"*\",\".\"],\n  [\"#\",\".\",\"*\"],\n  [\"#\",\".\",\".\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 22.29%) | Memory: 144.4 MB (Top 28.51%)\n class Solution {\n public char[][] rotateTheBox(char[][] box) {\n int row = box.length, col = box[0].length;\n char[][] res = new char[col][row];\n // rotate first, then drop\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++) {\n res[j][i] = box[row-1-i][j];\n }\n }\n\n for (int i = col - 1; i >= 0; i--) {\n for (int j = 0; j < row; j++) {\n if (res[i][j] == '#') {\n int curRow = i;\n while (curRow+1 < col && res[curRow+1][j] == '.') {\n curRow++;\n }\n if (curRow != i) {\n res[curRow][j] = '#';\n res[i][j] = '.';\n }\n }\n }\n }\n return res;\n }\n }", + "title": "1861. Rotating the Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise , causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcodewithstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode2withstones.png", + "https://assets.leetcode.com/uploads/2021/04/08/rotatingtheboxleetcode3withstone.png" + ], + "constraints": [ + "A stone '#'", + "A stationary obstacle '*'", + "Empty '.'" + ], + "examples": [ + { + "text": "Example 1: Input:box = [[\"#\",\".\",\"#\"]]Output:[[\".\"],\n  [\"#\"],\n  [\"#\"]]", + "image": null + }, + { + "text": "Example 2: Input:box = [[\"#\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"*\",\".\"]]Output:[[\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\"*\",\"*\"],\n  [\".\",\".\"]]", + "image": null + }, + { + "text": "Example 3: Input:box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n  [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n  [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]Output:[[\".\",\"#\",\"#\"],\n  [\".\",\"#\",\"#\"],\n  [\"#\",\"#\",\"*\"],\n  [\"#\",\"*\",\".\"],\n  [\"#\",\".\",\"*\"],\n  [\"#\",\".\",\".\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n # move stones to right, row by row\n for i in range(len(box)):\n stone = 0\n for j in range(len(box[0])):\n if box[i][j] == '#': # if a stone\n stone += 1\n box[i][j] = '.'\n elif box[i][j] == '*': # if a obstacle\n for m in range(stone):\n box[i][j-m-1] = '#'\n stone = 0\n # if reaches the end of j, but still have stone\n if stone != 0:\n for m in range(stone):\n box[i][j-m] = '#'\n \n # rotate box, same as leetcode #48\n box[:] = zip(*box[::-1])\n \n return box\n", + "title": "1861. Rotating the Box", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n grid where each cell can have one of three values: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 representing an empty cell,", + "1 representing a fresh orange, or", + "2 representing a rotten orange." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,1,1],[1,1,0],[0,1,1]]Output:4", + "image": "https://assets.leetcode.com/uploads/2019/02/16/oranges.png" + }, + { + "text": "Example 2: Input:grid = [[2,1,1],[0,1,1],[1,0,1]]Output:-1Explanation:The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[0,2]]Output:0Explanation:Since there are already no fresh oranges at minute 0, the answer is just 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n class Pair{\n int i;\n int j;\n int t;\n \n public Pair(int i,int j,int t){\n this.i = i;\n this.j = j;\n this.t = t;\n }\n }\n int ans = 0;\n final int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};\n public int orangesRotting(int[][] grid) {\n int countFresh = 0;\n Queue q = new LinkedList<>();\n for(int i=0;i= 0 && c >= 0 && r int:\n visited = set()\n res = 0\n def bfs(grid):\n que = collections.deque()\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 2:\n que.append((i,j))\n que.append(None)\n count = 0 \n while len(que)>0:\n left , right = 0,0\n\t\t\t\t# This other while loop is to make sure that we traverse from all the rotten oranges in one turn.\n while que[0] != None:\n r,c = que.popleft()\n for Cols in [-1,1]:\n if c+Cols>=0 and c+Cols=0 and r+Rows0:\n\t\t\t\t '''\n\t\t\t\t This is required to terminate the loop and prevent infinite loop.\n\t\t\t\t This only appends a None if there is still some values in the que, \n\t\t\t\t else we have completed our traversal and we can stop going any futher.\n\t\t\t\t '''\n que.append(None)\n return count\n res = bfs(grid)\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n return -1\n return res\n", + "title": "994. Rotting Oranges", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array nums . We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]) . Return the running sum of nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^6 <= nums[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[1,3,6,10]Explanation:Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1,1]Output:[1,2,3,4,5]Explanation:Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,1,2,10,1]Output:[3,4,6,16,17]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 85.2%) | Memory: 16.70 MB (Top 56.78%)\n\nclass Solution:\n def runningSum(self, nums: List[int]) -> List[int]:\n # The variable that will have the running sum\n tot = 0\n # The array that will hold the running su,\n ans = []\n # For loop\n for ele in nums:\n # Adding the element\n tot += ele\n # Appending this running sum to ans\n ans.append(tot)\n # Return ans\n return ans\n", + "title": "1480. Running Sum of 1d Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 2D array of integers envelopes where envelopes[i] = [w i , h i ] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other) . Note: You cannot rotate an envelope. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= envelopes.length <= 10^5", + "envelopes[i].length == 2", + "1 <= w i , h i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:envelopes = [[5,4],[6,4],[6,7],[2,3]]Output:3Explanation:The maximum number of envelopes you can Russian doll is3([2,3] => [5,4] => [6,7]).", + "image": null + }, + { + "text": "Example 2: Input:envelopes = [[1,1],[1,1],[1,1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxEnvelopes(int[][] envelopes) {\n\t\t//sort the envelopes considering only width\n Arrays.sort(envelopes, new sortEnvelopes());\n\t\t\n\t\t//Now this is a Longest Increasing Subsequence problem on heights\n\t\t//tempList to store the temporary elements, size of this list will be the length of LIS \n ArrayList tempList = new ArrayList<>();\n tempList.add(envelopes[0][1]);\n\t\t\n for(int i=1; itempList.get(tempList.size()-1)){\n tempList.add(envelopes[i][1]);\n } else{\n\t\t\t//if the element is smaller than the largest(last because it is sorted) element of tempList, replace the largest smaller element of tempList with it..\n\t\t\t//ex->(assume if envelopes[i][1] is 4), then >>[1,7,8] will become [1,4,8]<<\n int index = lowerBound(tempList, envelopes[i][1]);\n tempList.set(index, envelopes[i][1]);\n }\n }\n return tempList.size();\n }\n \n\t//finding the index of greatest smaller element \n public int lowerBound(ArrayList list, int search){\n int start = 0;\n int end = list.size()-1;\n while(start {\n public int compare(int[] a, int[] b){\n if(a[0] == b[0]){\n\t\t//to ignore the duplicates, we are sorting such that, for same width-> element with \n\t\t//largest height would be considered first, in this way all the other smaller heights would\n\t\t//be ignored\n return b[1] - a[1];\n } else{\n return a[0] - b[0];\n }\n }\n}\n", + "title": "354. Russian Doll Envelopes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 2D array of integers envelopes where envelopes[i] = [w i , h i ] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other) . Note: You cannot rotate an envelope. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= envelopes.length <= 10^5", + "envelopes[i].length == 2", + "1 <= w i , h i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:envelopes = [[5,4],[6,4],[6,7],[2,3]]Output:3Explanation:The maximum number of envelopes you can Russian doll is3([2,3] => [5,4] => [6,7]).", + "image": null + }, + { + "text": "Example 2: Input:envelopes = [[1,1],[1,1],[1,1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1587 ms (Top 72.81%) | Memory: 61.7 MB (Top 65.15%)\n\nfrom bisect import bisect_left\nclass Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n envelopes = sorted(envelopes, key= lambda x:(x[0],-x[1]))\n rst = []\n for _,h in envelopes:\n i = bisect_left(rst,h)\n if i == len(rst):\n rst.append(h)\n else:\n rst[i] = h\n return len(rst)", + "title": "354. Russian Doll Envelopes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.66 MB (Top 84.7%)\n\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Base case: if both trees are null, they are identical\n if (p == null && q == null) {\n return true;\n }\n // If only one tree is null or the values are different, they are not identical\n if (p == null || q == null || p.val != q.val) {\n return false;\n }\n // Recursively check if the left and right subtrees are identical\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}\n", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 21.7%) | Memory: 17.30 MB (Top 8.84%)\n\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n stack = [[p,q]]\n while stack:\n p,q = stack.pop()\n if not p and not q:\t\t\t\t\t#(1)\n continue\n elif p and q and p.val == q.val:\t#(2)\n stack.append([p.left, q.left])\n stack.append([p.right, q.right])\n else:\t\t\t\t\t\t\t\t#(3)\n return False\n return True\n", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"x i ==y i \" or \"x i !=y i \" .Here, x i and y i are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 500", + "equations[i].length == 4", + "equations[i][0] is a lowercase letter.", + "equations[i][1] is either '=' or '!' .", + "equations[i][2] is '=' .", + "equations[i][3] is a lowercase letter." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [\"a==b\",\"b!=a\"]Output:falseExplanation:If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.", + "image": null + }, + { + "text": "Example 2: Input:equations = [\"b==a\",\"a==b\"]Output:trueExplanation:We could assign a = 1 and b = 1 to satisfy both equations.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 98.0%) | Memory: 40.98 MB (Top 47.4%)\n\nclass Solution {\n static int par[];\n\n public static int findPar(int u) {\n return par[u] == u ? u : (par[u] = findPar(par[u]));\n }\n\n public boolean equationsPossible(String[] equations) {\n par = new int[26];\n for (int i = 0; i < 26; i++) {\n par[i] = i;\n }\n\n /*First perform all the merging operation*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '=') {\n if (p1 != p2) {\n if (p1 < p2) {\n par[p2] = p1;\n } else {\n par[p1] = p2;\n }\n }\n } \n }\n\n /*Now traverse on the whole string and search for any != operation and check if there parents are same*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '!') {\n if (p1 == p2) {\n return false;\n }\n }\n }\n return true;\n }\n}", + "title": "990. Satisfiability of Equality Equations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"x i ==y i \" or \"x i !=y i \" .Here, x i and y i are lowercase letters (not necessarily different) that represent one-letter variable names. Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 500", + "equations[i].length == 4", + "equations[i][0] is a lowercase letter.", + "equations[i][1] is either '=' or '!' .", + "equations[i][2] is '=' .", + "equations[i][3] is a lowercase letter." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [\"a==b\",\"b!=a\"]Output:falseExplanation:If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.", + "image": null + }, + { + "text": "Example 2: Input:equations = [\"b==a\",\"a==b\"]Output:trueExplanation:We could assign a = 1 and b = 1 to satisfy both equations.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n from collections import defaultdict\n g = defaultdict(list)\n for e in equations:\n if e[1] == '=':\n x = e[0]\n y = e[3]\n g[x].append(y)\n g[y].append(x)\n \n # marked the connected components as 0,1,2,...,25\n ccs = defaultdict(lambda: -1) # -1 means unmarked or unseen\n\n def dfs(node, cc):\n if node not in ccs:\n ccs[node] = cc\n for neighbour in g[node]:\n dfs(neighbour, cc)\n \n for i in range(26):\n dfs(chr(i+97), i)\n \n for e in equations:\n if e[1] == '!':\n x = e[0]\n y = e[3]\n if ccs[x] == ccs[y]:\n return False\n return True", + "title": "990. Satisfiability of Equality Equations", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an m x n binary matrix grid . A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0 's to 1 's, and all 1 's to 0 's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves) . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 20", + "grid[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]Output:39Explanation:0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-toogle1.jpg" + }, + { + "text": "Example 2: Input:grid = [[0]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 17.33%) | Memory: 42.9 MB (Top 9.03%)\nclass Solution {\n public int matrixScore(int[][] grid) {\n ArrayList arr=new ArrayList();\n for(int i=0;ione)\n {\n arr.add(i);\n }\n }\n for(int i:arr)\n {\n for(int j=0;j int:\n self.grid = grid\n self.height = len(grid)\n self.width = len(grid[0])\n \n for r in range(self.height):\n if not self.grid[r][0]:\n if not self.grid[r][0]:\n self.flipRow(r)\n \n for c in range(1, self.width):\n colSum = self.colSum(c)\n \n if colSum < ceil(self.height/2):\n self.flipCol(c)\n \n return self.calcScore()\n \n", + "title": "861. Score After Flipping Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a balanced parentheses string s , return the score of the string . The score of a balanced parentheses string is based on the following rule: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"()\" has score 1 .", + "AB has score A + B , where A and B are balanced parentheses strings.", + "(A) has score 2 * A , where A is a balanced parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(())\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 25.38%)\n\nclass Solution {\n public int scoreOfParentheses(String s) {\n Stack st = new Stack<>();\n int score = 0;\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(ch == '('){\n st.push(score);\n score = 0;\n }\n else {\n score = st.pop() + Math.max(2 * score, 1);\n }\n }\n return score;\n }\n}\n", + "title": "856. Score of Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a balanced parentheses string s , return the score of the string . The score of a balanced parentheses string is based on the following rule: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"()\" has score 1 .", + "AB has score A + B , where A and B are balanced parentheses strings.", + "(A) has score 2 * A , where A is a balanced parentheses string." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:s = \"(())\"Output:2", + "image": null + }, + { + "text": "Example 3: Input:s = \"()()\"Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n \n level = 0\n result = 0\n prev = \"\"\n \n for c in s: \n if c == \"(\":\n level += 1\n if c == \")\":\n if prev == \"(\":\n result += 2 ** (level - 1)\n level -= 1 \n prev = c\n \n return result\n", + "title": "856. Score of Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length , return true if s2 is a scrambled string of s1 , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Split the string into two non-empty substrings at a random index, i.e., if the string is s , divide it to x and y where s = x + y .", + "Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x .", + "Apply step 1 recursively on each of the two substrings x and y ." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"great\", s2 = \"rgeat\"Output:trueExplanation:One possible scenario applied on s1 is:\n\"great\" --> \"gr/eat\" // divide at random index.\n\"gr/eat\" --> \"gr/eat\" // random decision is not to swap the two substrings and keep them in order.\n\"gr/eat\" --> \"g/r / e/at\" // apply the same algorithm recursively on both substrings. divide at random index each of them.\n\"g/r / e/at\" --> \"r/g / e/at\" // random decision was to swap the first substring and to keep the second substring in the same order.\n\"r/g / e/at\" --> \"r/g / e/ a/t\" // again apply the algorithm recursively, divide \"at\" to \"a/t\".\n\"r/g / e/ a/t\" --> \"r/g / e/ a/t\" // random decision is to keep both substrings in the same order.\nThe algorithm stops now, and the result string is \"rgeat\" which is s2.\nAs one possible scenario led s1 to be scrambled to s2, we return true.", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"abcde\", s2 = \"caebd\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"a\", s2 = \"a\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def isScramble(self, s1, s2):\n \"\"\"\n :type s1: str\n :type s2: str\n :rtype: bool\n \"\"\"\n if s1 == s2:\n return True\n if len(s1) != len(s2):\n return False\n \n # Check both strings have same count of letters\n count1 = collections.defaultdict(int)\n count2 = collections.defaultdict(int)\n for c1, c2 in zip(s1, s2):\n count1[c1] += 1\n count2[c2] += 1\n if count1 != count2: return False\n \n # Iterate through letters and check if it results in a partition of \n # string 1 where the collection of letters are the same\n # on the left (non-swapped) or right (swapped) sides of string 2\n # Then we recursively check these partitioned strings to see if they are scrambled\n lcount1 = collections.defaultdict(int) # s1 count from left\n lcount2 = collections.defaultdict(int) # s2 count from left\n rcount2 = collections.defaultdict(int) # s2 count from right\n for i in xrange(len(s1) - 1):\n lcount1[s1[i]] += 1 \n lcount2[s2[i]] += 1\n rcount2[s2[len(s1) - 1 - i]] += 1\n if lcount1 == lcount2: # Left sides of both strings have same letters\n if self.isScramble(s1[:i + 1], s2[:i + 1]) and \\\n self.isScramble(s1[i + 1:], s2[i + 1:]):\n return True\n elif lcount1 == rcount2: # Left side of s1 has same letters as right side of s2\n if self.isScramble(s1[:i + 1], s2[-(i + 1):]) and \\\n self.isScramble(s1[i + 1:], s2[:-(i + 1)]):\n return True\n return False\n", + "title": "87. Scramble String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted from left to right.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n if (target < matrix[0][0]) {\n return false;\n }\n for (int i = 0; i < matrix.length; i++) {\n if (matrix[i][0] > target | i == matrix.length - 1) {\n if (matrix[i][0] > target) {\n i--;\n }\n for (int j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] == target) {\n return true;\n }\n }\n return false;\n }\n }\n return false;\n }\n}\n", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted from left to right.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 38 ms (Top 96.94%) | Memory: 17.90 MB (Top 11.07%)\n\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n n = len(matrix[0])\n def get(idx: int) -> int:\n r, c = divmod(idx, n)\n return matrix[r][c]\n return get(bisect_left(range(len(matrix)*n-1), target, key=get)) == target\n", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20Output:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 30.54%) | Memory: 57.2 MB (Top 69.94%)\nclass Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n int lo = 0, hi = rows;\n while(lo + 1 < hi) {\n int mid = lo + (hi - lo) / 2;\n if (matrix[mid][0] <= target) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n int[] prospect;\n for (int i = 0; i <= lo; i++) {\n prospect = matrix[i];\n int l = 0;\n int h = cols;\n while (l + 1 < h) {\n int mid = l + (h - l) / 2;\n if (prospect[mid] <= target) {\n l = mid;\n } else {\n h = mid;\n }\n }\n if (prospect[l] == target) {\n return true;\n }\n }\n return false;\n }\n}", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20Output:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 121 ms (Top 76.1%) | Memory: 19.55 MB (Top 13.9%)\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n found=False\n for X in matrix:\n for M in X:\n if M==target:\n found=True\n return found", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2Output:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5Output:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 51.2 MB (Top 70.33%)\nclass Solution {\n public TreeNode searchBST(TreeNode root, int val) {\n if (root == null) return root;\n if (root.val == val) {\n return root;\n } else {\n return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);\n }\n }\n}", + "title": "700. Search in a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2Output:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5Output:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 87 ms (Top 85.77%) | Memory: 16.7 MB (Top 24.56%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n def search(root):\n if not root:return None\n if root.val==val:\n return root\n elif root.valarr[mid+1]){\n return mid;\n }\n if(mid>start && arr[mid-1]>arr[mid]){\n return mid-1;\n }\n if(arr[mid]<=arr[start]){\n end = mid-1;\n }else{\n start = mid+1;\n }\n }\n return -1;\n }\n \n public int binarySearch(int[] arr, int target, int start, int end){\n \n while(start<=end){\n int mid = start+ (end-start)/2;\n \n \n if(targetarr[mid]){\n start = mid+1;\n }else{\n return mid;\n }\n \n \n }\n return -1;\n }\n \n}\n", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot 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 rotated at pivot index 3 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: Example 2: Example 3:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,6,7,0,1,2], target = 0Output:4", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2], target = 3Output:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], target = 0Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n \n while l<=r:\n mid = (l+r)//2\n if target == nums[mid]:\n return mid\n \n if nums[l]<=nums[mid]:\n if target > nums[mid] or target nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n \n return -1\n", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k ( 0 <= 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,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4] . Given the array nums after the rotation and an integer target , return true if target is in nums , or false if it is not in nums . You must decrease the overall operation steps as much as possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "-10^4 <= nums[i] <= 10^4", + "nums is guaranteed to be rotated at some pivot.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,0,0,1,2], target = 0Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,5,6,0,0,1,2], target = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean search(int[] nums, int target) {\n if (nums == null || nums.length == 0) return false;\n \n int left = 0, right = nums.length-1;\n int start = 0;\n\n//1. find index of the smallest element\n while(left < right) {\n while (left < right && nums[left] == nums[left + 1])\n ++left;\n while (left < right && nums[right] == nums[right - 1])\n --right;\n int mid = left + (right-left)/2;\n if (nums[mid] > nums[right]) {\n left = mid +1;\n } else right = mid;\n }\n \n//2. figure out in which side our target lies\n start = left;\n left = 0;\n right = nums.length-1;\n if (target >= nums[start] && target <= nums[right])\n left = start;\n else right = start;\n \n//3. Run normal binary search in sorted half.\n while(left <= right) {\n int mid = left + (right - left)/2;\n if (nums[mid] == target) return true;\n \n if (nums[mid] > target) right = mid-1;\n else left = mid + 1;\n }\n \n return false;\n}\n}\n", + "title": "81. Search in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k ( 0 <= 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,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4] . Given the array nums after the rotation and an integer target , return true if target is in nums , or false if it is not in nums . You must decrease the overall operation steps as much as possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "-10^4 <= nums[i] <= 10^4", + "nums is guaranteed to be rotated at some pivot.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,6,0,0,1,2], target = 0Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,5,6,0,0,1,2], target = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def search(self, nums: List[int], target: int) -> bool:\n nums.sort()\n low=0\n high=len(nums)-1\n while low<=high:\n mid=(low+high)//2\n if nums[mid]==target:\n return True\n elif nums[mid]>target:\n high=mid-1\n else:\n low=mid+1\n return False\n", + "title": "81. Search in Rotated Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2Output:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.90 MB (Top 78.78%)\n\nclass Solution {\n public int searchInsert(int[] nums, int target) {\n int start = 0;\n int end = nums.length-1;\n\n while (start <= end) {\n int mid = start + (end-start)/2;\n if (nums[mid] == target) return mid;\n else if (nums[mid] > target) end = mid-1;\n else start = mid+1;\n }\n\n return start;\n }\n}\n", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2Output:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def searchInsert(self, nums, target):\n for i, num in enumerate(nums):\n if num >= target:\n return i\n return len(nums)", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"Output:[\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]Explanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"Output:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]", + "image": null + }, + { + "text": "Example 3: Input:products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"Output:[[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 48.70%) | Memory: 45.5 MB (Top 96.95%)\nclass Solution\n{\n public List> suggestedProducts(String[] products, String searchWord)\n {\n PriorityQueue pq= new PriorityQueue();\n List> res= new LinkedList>();\n List segment= new LinkedList();\n for(int i=0;i();\n pq= reduce(pq,searchWord.substring(0,j+1));\n PriorityQueue pri= new PriorityQueue<>(pq);\n int p=0;\n while(p reduce(PriorityQueue pr, String filter)\n {\n PriorityQueue p= new PriorityQueue<>();\n String s=\"\";\n while(!pr.isEmpty())\n {\n s=pr.poll();\n if(s.startsWith(filter))\n p.add(s);\n }\n return p;\n }\n}", + "title": "1268. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"Output:[\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]Explanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"Output:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]", + "image": null + }, + { + "text": "Example 3: Input:products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"Output:[[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 78 ms (Top 77.93%) | Memory: 19.60 MB (Top 79.27%)\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n list_ = []\n products.sort()\n for i, c in enumerate(searchWord):\n products = [ p for p in products if len(p) > i and p[i] == c ]\n list_.append(products[:3])\n return list_\n", + "title": "1268. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Design a system that manages the reservation state of n seats that are numbered from 1 to n . Implement the SeatManager class: Example 1:", + "description_images": [], + "constraints": [ + "SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n . All seats are initially available.", + "int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.", + "void unreserve(int seatNumber) Unreserves the seat with the given seatNumber ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]Output[null, 1, 2, null, 2, 3, 4, 5, null]ExplanationSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 88 ms (Top 72.91%) | Memory: 105 MB (Top 67.49%)\nclass SeatManager {\n PriorityQueue pq;\n int count;\n public SeatManager(int n) {\n count = 1;\n pq = new PriorityQueue();\n }\n\n public int reserve() {\n if(pq.size()==0)\n return count++;\n\n return pq.poll();\n }\n\n public void unreserve(int seatNumber) {\n pq.add(seatNumber);\n }\n}", + "title": "1845. Seat Reservation Manager", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Design a system that manages the reservation state of n seats that are numbered from 1 to n . Implement the SeatManager class: Example 1:", + "description_images": [], + "constraints": [ + "SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n . All seats are initially available.", + "int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.", + "void unreserve(int seatNumber) Unreserves the seat with the given seatNumber ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]Output[null, 1, 2, null, 2, 3, 4, 5, null]ExplanationSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].", + "image": null + } + ], + "follow_up": null, + "solution": "class SeatManager:\n def __init__(self, n: int):\n self.lis = list(range(1,n+1))\n def reserve(self) -> int:\n mini = min(self.lis)\n self.lis.remove(mini)\n return mini\n\n def unreserve(self, seatNumber: int) -> None:\n self.lis.append(seatNumber)\n", + "title": "1845. Seat Reservation Manager", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an alphanumeric string s , return the second largest numerical digit that appears in s , or -1 if it does not exist . An alphanumeric string is a string consisting of lowercase English letters and digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dfa12321afd\"Output:2Explanation:The digits that appear in s are [1, 2, 3]. The second largest digit is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc1111\"Output:-1Explanation:The digits that appear in s are [1]. There is no second largest digit.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 72.70%) | Memory: 42.6 MB (Top 56.41%)\nclass Solution {\n public int secondHighest(String s) {\n int[] arr = new int[10];\n for(int i = 0;i=0){\n arr[s.charAt(i)-'0']++;\n }\n }\n boolean first = false;\n for(int i = 9;i>=0;i--){\n if(arr[i] !=0){\n if(first)\n return i;\n else first = true;\n }\n }\n\n return -1;\n }\n}", + "title": "1796. Second Largest Digit in a String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an alphanumeric string s , return the second largest numerical digit that appears in s , or -1 if it does not exist . An alphanumeric string is a string consisting of lowercase English letters and digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of only lowercase English letters and/or digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dfa12321afd\"Output:2Explanation:The digits that appear in s are [1, 2, 3]. The second largest digit is 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abc1111\"Output:-1Explanation:The digits that appear in s are [1]. There is no second largest digit.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 80 ms (Top 5.3%) | Memory: 16.30 MB (Top 72.1%)\n\nclass Solution:\n def secondHighest(self, s: str) -> int:\n nums = []\n for char in s:\n if char.isdigit():\n nums.append(int(char))\n nums = [num for num in nums if num != max(nums)]\n if len(nums) >= 1: return max(nums)\n else: return -1", + "title": "1796. Second Largest Digit in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 25] .", + "1 <= Node.val <= 2 31 - 1", + "root.val == min(root.left.val, root.right.val) for each internal node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,2,5,null,null,5,7]Output:5Explanation:The smallest value is 2, the second smallest value is 5.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" + }, + { + "text": "Example 2: Input:root = [2,2,2]Output:-1Explanation:The smallest value is 2, but there isn't any second smallest value.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 20.63%)\nclass Solution {\n int ans = Integer.MAX_VALUE;\n boolean x = true;\n\n public int findSecondMinimumValue(TreeNode root) {\n go(root);\n return x ? -1 : ans;\n }\n\n private void go(TreeNode root) {\n if (root == null) return;\n if (root.left != null) {\n if (root.left.val == root.val) go(root.left);\n else {\n x = false;\n ans = Math.min(ans, root.left.val);\n }\n }\n if (root.right != null) {\n if (root.right.val == root.val) go(root.right);\n else {\n x = false;\n ans = Math.min(ans, root.right.val);\n }\n }\n }\n}", + "title": "671. Second Minimum Node In a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds. Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree. If no such second minimum value exists, output -1 instead. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 25] .", + "1 <= Node.val <= 2 31 - 1", + "root.val == min(root.left.val, root.right.val) for each internal node of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,2,5,null,null,5,7]Output:5Explanation:The smallest value is 2, the second smallest value is 5.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" + }, + { + "text": "Example 2: Input:root = [2,2,2]Output:-1Explanation:The smallest value is 2, but there isn't any second smallest value.", + "image": "https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" + } + ], + "follow_up": null, + "solution": "# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n temp1=temp2=float(inf)\n from collections import deque\n a=deque([root])\n while a:\n node=a.popleft()\n if node.valtemp1:\n if node.val", + "title": "671. Second Minimum Node In a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time . You can enter a vertex at any time , but can leave a vertex only when the signal is green . You cannot wait at a vertex if the signal is green . The second minimum value is defined as the smallest value strictly larger than the minimum value. Given n , edges , time , and change , return the second minimum time it will take to go from vertex 1 to vertex n . Notes: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example the second minimum value of [2, 3, 4] is 3 , and the second minimum value of [2, 2, 4] is 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5Output:13Explanation:The figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/e2.png" + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]], time = 3, change = 2Output:11Explanation:The minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/eg2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 254 ms (Top 50.50%) | Memory: 51.9 MB (Top 97.03%)\nclass Solution {\n public int secondMinimum(int n, int[][] edges, int time, int change) {\n Map> g = new HashMap();\n for(int[] e : edges) {\n int u = e[0], v = e[1];\n g.computeIfAbsent(u, x -> new ArrayList()).add(v);\n g.computeIfAbsent(v, x -> new ArrayList()).add(u);\n }\n PriorityQueue q = new PriorityQueue<>((a,b) -> a[1] - b[1]);\n q.offer(new int[]{1, 0});\n int[] uniqueVisit = new int[n+1]; // uniqueVisit limit to 2 <==> relax twice at most\n int[] dis = new int[n+1];\n Arrays.fill(dis, -1);\n while(!q.isEmpty()) {\n int size = q.size();\n int[] cur = q.poll();\n int node = cur[0], t = cur[1]; // arriving time\n if(dis[node] == t || uniqueVisit[node] >= 2) continue; // skip if it's same value or has been relaxed twice already\n uniqueVisit[node]++;\n dis[node] = t;\n if(node == n && uniqueVisit[node] == 2) return dis[node];\n // generate leaving time (waiting the green light)\n if((t / change) % 2 != 0) t = (t/change + 1) * change;\n for(int nei : g.getOrDefault(node, new ArrayList<>())) {\n q.offer(new int[]{nei, t + time});\n }\n }\n return -1;\n }\n}", + "title": "2045. Second Minimum Time to Reach Destination", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n ( inclusive ). The edges in the graph are represented as a 2D integer array edges , where each edges[i] = [u i , v i ] denotes a bi-directional edge between vertex u i and vertex v i . Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time . You can enter a vertex at any time , but can leave a vertex only when the signal is green . You cannot wait at a vertex if the signal is green . The second minimum value is defined as the smallest value strictly larger than the minimum value. Given n , edges , time , and change , return the second minimum time it will take to go from vertex 1 to vertex n . Notes: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example the second minimum value of [2, 3, 4] is 3 , and the second minimum value of [2, 2, 4] is 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5Output:13Explanation:The figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/e2.png" + }, + { + "text": "Example 2: Input:n = 2, edges = [[1,2]], time = 3, change = 2Output:11Explanation:The minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.", + "image": "https://assets.leetcode.com/uploads/2021/09/29/eg2.png" + } + ], + "follow_up": null, + "solution": "from heapq import heappop,heappush\nfrom collections import defaultdict\n\nclass Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n G = defaultdict(list)\n dist = defaultdict(set)\n for v, w in edges:\n G[v].append(w)\n G[w].append(v)\n h = [(0, 1)]\n res = []\n while h:\n d, v = heappop(h)\n if len(dist[v]) > 1:\n continue\n if d in dist[v]:\n continue\n dist[v].add(d)\n q, r = divmod(d, change)\n if q%2 == 1:\n d += change - r\n for w in G[v]:\n if w == n:\n if res:\n if d+time not in res:\n return d+time\n else:\n res.append(d+time)\n if len(dist[w]) < 2:\n heappush(h, (d+time,w))\n", + "title": "2045. Second Minimum Time to Reach Destination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of integers distance . You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= distance.length <= 10^5", + "1 <= distance[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [2,1,1,2]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg" + }, + { + "text": "Example 2: Input:distance = [1,2,3,4]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg" + }, + { + "text": "Example 3: Input:distance = [1,1,1,1]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b) return true; // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true; // cross [i - 4]\n\nif (x[i] < a) arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}", + "title": "335. Self Crossing", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an array of integers distance . You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise. Return true if your path crosses itself, and false if it does not. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= distance.length <= 10^5", + "1 <= distance[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:distance = [2,1,1,2]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross1-plane.jpg" + }, + { + "text": "Example 2: Input:distance = [1,2,3,4]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross2-plane.jpg" + }, + { + "text": "Example 3: Input:distance = [1,1,1,1]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/14/selfcross3-plane.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSelfCrossing(self, x):\n n = len(x)\n if n < 4: return False\n for i in range(3, n):\n if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True\n if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True\n if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] and 0<=x[i-3]-x[i-1]<=x[i-5]: return True\n return False\n \n", + "title": "335. Self Crossing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right , return a list of all the self-dividing numbers in the range [left, right] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, 128 is a self-dividing number because 128 % 1 == 0 , 128 % 2 == 0 , and 128 % 8 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 22Output:[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "image": null + }, + { + "text": "Example 2: Input:left = 47, right = 85Output:[48,55,66,77]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List selfDividingNumbers(int left, int right) {\n List ans= new ArrayList<>();\n while(left<=right){\n if(fun(left))\n ans.add(left); \n left++;\n }\n return ans;\n }\n boolean fun(int x){\n int k=x;\n while(k>0)\n {\n int y=k%10;\n k=k/10;\n if(y==0||x%y!=0)\n return false;\n }\n return true;\n }\n}\n", + "title": "728. Self Dividing Numbers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A self-dividing number is a number that is divisible by every digit it contains. A self-dividing number is not allowed to contain the digit zero. Given two integers left and right , return a list of all the self-dividing numbers in the range [left, right] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, 128 is a self-dividing number because 128 % 1 == 0 , 128 % 2 == 0 , and 128 % 8 == 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:left = 1, right = 22Output:[1,2,3,4,5,6,7,8,9,11,12,15,22]", + "image": null + }, + { + "text": "Example 2: Input:left = 47, right = 85Output:[48,55,66,77]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 99 ms (Top 32.60%) | Memory: 13.9 MB (Top 25.64%)\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n res = []\n for num in range(left, right + 1):\n num_str = str(num)\n if '0' in num_str:\n continue\n elif all([num % int(digit_str) == 0 for digit_str in num_str]):\n res.append(num)\n return res", + "title": "728. Self Dividing Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory . For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory , where inventory[i] represents the number of balls of the i th color that you initially own. You are also given an integer orders , which represents the total number of balls that the customer wants. You can sell the balls in any order . Return the maximum total value that you can attain after selling orders colored balls . As the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= inventory.length <= 10^5", + "1 <= inventory[i] <= 10^9", + "1 <= orders <= min(sum(inventory[i]), 10^9 )" + ], + "examples": [ + { + "text": "Example 1: Input:inventory = [2,5], orders = 4Output:14Explanation:Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/jj.gif" + }, + { + "text": "Example 2: Input:inventory = [3,5], orders = 6Output:19Explanation:Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private long mod = 1000000007L;\n public int maxProfit(int[] inventory, int orders) {\n\t\t// we use pq to find the most balls\n PriorityQueue pq = new PriorityQueue<>((x, y) -> Long.compare(y, x));\n pq.offer(0L);\n\t\t\n // we use map to count the balls\n Map map = new HashMap<>();\n map.put(0L, 0L);\n \n for (int j : inventory) {\n long i = (long)j;\n if (map.containsKey(i)) {\n map.put(i, map.get(i) + 1);\n }\n else {\n pq.offer(i);\n map.put(i, 1L);\n }\n }\n \n long res = 0;\n while (orders > 0) {\n long ball = pq.poll(), nextBall = pq.peek();\n long times = map.get(ball);\n long diff = Math.min(ball - nextBall, orders / times);\n if (diff == 0) {\n res = (res + orders * ball) % mod;\n break;\n }\n long sum = (ball * 2 + 1 - diff) * diff / 2 * times;\n res = (res + sum) % mod;\n orders -= diff * times;\n if (!map.containsKey(ball - diff)) {\n map.put(ball - diff, map.get(ball));\n pq.offer(ball - diff);\n }\n else {\n map.put(ball - diff, map.get(ball - diff) + map.get(ball));\n }\n map.remove(ball);\n }\n return (int) res;\n }\n}\n", + "title": "1648. Sell Diminishing-Valued Colored Balls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory . For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory , where inventory[i] represents the number of balls of the i th color that you initially own. You are also given an integer orders , which represents the total number of balls that the customer wants. You can sell the balls in any order . Return the maximum total value that you can attain after selling orders colored balls . As the answer may be too large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= inventory.length <= 10^5", + "1 <= inventory[i] <= 10^9", + "1 <= orders <= min(sum(inventory[i]), 10^9 )" + ], + "examples": [ + { + "text": "Example 1: Input:inventory = [2,5], orders = 4Output:14Explanation:Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/jj.gif" + }, + { + "text": "Example 2: Input:inventory = [3,5], orders = 6Output:19Explanation:Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True) \n inventory += [0]\n res = 0\n k = 1\n \n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i]-inventory[i+1]) < orders:\n diff = inventory[i]-inventory[i+1]\n res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2\n orders -= k*diff\n else: \n q, r = divmod(orders, k)\n res += k*(inventory[i]+(inventory[i]-q+1))*q//2\n res += r*(inventory[i]-q)\n return res%(10**9+7)\n k += 1\n", + "title": "1648. Sell Diminishing-Valued Colored Balls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices , where prices[i] = [h i , w i , price i ] indicates you can sell a rectangular piece of wood of height h i and width w i for price i dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices . You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood . Note that you can cut the piece of wood as many times as you want. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 200", + "1 <= prices.length <= 2 * 10^4", + "prices[i].length == 3", + "1 <= h i <= m", + "1 <= w i <= n", + "1 <= price i <= 10^6", + "All the shapes of wood (h i , w i ) are pairwise distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]Output:19Explanation:The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex1.png" + }, + { + "text": "Example 2: Input:m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]Output:32Explanation:The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex2new.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public long sellingWood(int m, int n, int[][] prices) {\n long[][] dp = new long[m+1][n+1];\n for (int[] price : prices) {\n dp[price[0]][price[1]] = price[2];\n }\n for (int i = 1; i < m+1; i++) {\n for (int j = 1; j < n+1; j++) {\n // all horizontal\n for (int k = 1; k <= i/2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[i-k][j] + dp[k][j]);\n }\n // all vertical\n for (int k = 1; k <= j/2; k++) {\n dp[i][j] = Math.max(dp[i][j], dp[i][j-k] + dp[i][k]);\n }\n }\n }\n \n return dp[m][n];\n }\n}\n", + "title": "2312. Selling Pieces of Wood", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices , where prices[i] = [h i , w i , price i ] indicates you can sell a rectangular piece of wood of height h i and width w i for price i dollars. To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices . You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. Return the maximum money you can earn after cutting an m x n piece of wood . Note that you can cut the piece of wood as many times as you want. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 200", + "1 <= prices.length <= 2 * 10^4", + "prices[i].length == 3", + "1 <= h i <= m", + "1 <= w i <= n", + "1 <= price i <= 10^6", + "All the shapes of wood (h i , w i ) are pairwise distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]Output:19Explanation:The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex1.png" + }, + { + "text": "Example 2: Input:m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]Output:32Explanation:The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.", + "image": "https://assets.leetcode.com/uploads/2022/04/27/ex2new.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n price = {(dimension_price[0], dimension_price[1]): dimension_price[2] for dimension_price in prices}\n DP = [[-1 for _ in range(n + 1)] for _ in range(m + 1)]\n \n def solve(h: int, v: int) -> int:\n if DP[h][v] != -1:\n return DP[i][j]\n \n ans = price.get((h, v), 0)\n \n for i in range(1, 1 + h // 2):\n ans = max(ans, (DP[i][v] if DP[i][v] != -1 else solve(i, v)) + (DP[h - i][v] if DP[h - i][v] != -1 else solve(h - i, v)))\n \n for j in range(1, 1 + v // 2):\n ans = max(ans, (DP[h][j] if DP[h][j] != -1 else solve(h, j)) + (DP[h][v - j] if DP[h][v - j] != -1 else solve(h, v - j)))\n \n DP[h][v] = ans\n \n return ans\n \n return solve(m, n)\n", + "title": "2312. Selling Pieces of Wood", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i] . A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. Return the sender with the largest word count . If there is more than one sender with the largest word count, return the one with the lexicographically largest name . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Uppercase letters come before lowercase letters in lexicographical order.", + "\"Alice\" and \"alice\" are distinct." + ], + "examples": [ + { + "text": "Example 1: Input:messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]Output:\"Alice\"Explanation:Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return \"Alice\".", + "image": null + }, + { + "text": "Example 2: Input:messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]Output:\"Charlie\"Explanation:Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 92.47%) | Memory: 48.80 MB (Top 99.46%)\n\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) \n {\n HashMap map = new HashMap<>();\n String res = \"\";int max =0;\n \n for(int i=0; i max)\n {\n res = s;\n max = map.get(s);\n }\n \n if(map.get(s) == max && res.compareTo(s) < 0)\n res = s;\n }\n return res;\n }\n \n private int get_count(String s)\n {\n int spaces = 0;\n \n for(int i=0; i str:\n d={}\n l=[]\n for i in range(len(messages)):\n if senders[i] not in d:\n d[senders[i]]=len(messages[i].split())\n else:\n d[senders[i]]+=len(messages[i].split())\n x=max(d.values())\n for k,v in d.items():\n if v==x :\n l.append(k)\n if len(l)==1:\n return l[0]\n else:\n l=sorted(l)[::-1] #Lexigograhical sorting of list\n return l[0]\n", + "title": "2284. Sender With Largest Word Count", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, \"Hello World\" , \"HELLO\" , \"hello world hello world\" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2 . Given two sentences sentence1 and sentence2 , return true if sentence1 and sentence2 are similar. Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= sentence1.length, sentence2.length <= 100", + "sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.", + "The words in sentence1 and sentence2 are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"Output:trueExplanation:sentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".", + "image": null + }, + { + "text": "Example 2: Input:sentence1 = \"of\", sentence2 = \"A lot of words\"Output:falseExplanation:No single sentence can be inserted inside one of the sentences to make it equal to the other.", + "image": null + }, + { + "text": "Example 3: Input:sentence1 = \"Eating right now\", sentence2 = \"Eating\"Output:trueExplanation:sentence2 can be turned to sentence1 by inserting \"right now\" at the end of the sentence.", + "image": null + } + ], + "follow_up": null, + "solution": "2", + "title": "1813. Sentence Similarity III", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "10 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 100, high = 300Output:[123,234]", + "image": null + }, + { + "text": "Example 2: Input:low = 1000, high = 13000Output:[1234,2345,3456,4567,5678,6789,12345]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 53.25%)\nclass Solution {\n public List sequentialDigits(int low, int high) {\n int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length();\n List output = new ArrayList<>();\n\n for(int size=lowSize; size<=highSize; size++) {\n int seedNumber = getSeedNumber(size);\n int increment = getIncrement(size);\n int limit = (int)Math.pow(10,size);\n // System.out.println(seedNumber+\":\"+increment+\":\"+limit);\n while(true){\n if(seedNumber>=low && seedNumber<=high)\n output.add(seedNumber);\n if(seedNumber%10==9 || seedNumber>high) break;\n seedNumber+=increment;\n }\n }\n return output;\n }\n\n private int getSeedNumber(int size) {\n int seed = 1;\n for(int i=2;i<=size;i++)\n seed=10*seed + i;\n return seed;\n }\n\n private int getIncrement(int size) {\n int increment = 1;\n for(int i=2;i<=size;i++)\n increment=10*increment + 1;\n return increment;\n }\n}", + "title": "1291. Sequential Digits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "10 <= low <= high <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:low = 100, high = 300Output:[123,234]", + "image": null + }, + { + "text": "Example 2: Input:low = 1000, high = 13000Output:[1234,2345,3456,4567,5678,6789,12345]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 41 ms (Top 43.2%) | Memory: 16.29 MB (Top 65.6%)\n\nclass Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n l = len(str(low))\n h = len(str(high))\n ans = []\n for i in range(l,h+1):\n for j in range(1,11-i):\n t = str(j)\n for k in range(i-1):\n t+=str(int(t[-1])+1)\n if int(t)<=high and int(t)>=low:\n ans.append(int(t))\n ans.sort()\n return ans\n", + "title": "1291. Sequential Digits", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A scenic location is represented by its name and attractiveness score , where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time , the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: Example 1:", + "description_images": [], + "constraints": [ + "Adding scenic locations, one at a time .", + "Querying the i th best location of all locations already added , where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added.", + "For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added." + ], + "examples": [ + { + "text": "Example 1: Input[\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n[[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]Output[null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]ExplanationSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\ntracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\ntracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to itshigher score(3 > 2).\n // This is the 1sttime get() is called, so return the best location: \"branford\".\ntracker.add(\"alps\", 2); // Add location with name=\"alps\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because \"alps\" islexicographically smallerthan \"bradford\".\n // Return the 2ndbest location \"alps\", as it is the 2ndtime get() is called.\ntracker.add(\"orland\", 2); // Add location with name=\"orland\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return \"bradford\", as it is the 3rdtime get() is called.\ntracker.add(\"orlando\", 3); // Add location with name=\"orlando\" and score=3 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return \"bradford\".\ntracker.add(\"alpine\", 2); // Add location with name=\"alpine\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"bradford\".\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"orland\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 996 ms (Top 5.13%) | Memory: 131.3 MB (Top 81.29%)\nclass SORTracker {\n\n private TreeMap> map;\n private int queryNum;\n\n // Find suitable position for name in the list\n private int getIndex(String name, List list) {\n int l = 0, r = list.size() - 1, m = 0;\n while (l < r) {\n m = l + (r - l) / 2;\n if(name.compareTo(list.get(m)) > 0) {\n l = m + 1;\n } else {\n r = m;\n }\n }\n return name.compareTo(list.get(l)) > 0 ? l+1 : l;\n }\n\n public SORTracker() {\n map = new TreeMap<>((a,b) -> (b-a));\n queryNum = 0;\n }\n\n public void add(String name, int score) {\n List list = map.getOrDefault(score, new ArrayList<>());\n int index = (list.size() == 0) ? 0 : getIndex(name, list);\n list.add(index, name);\n map.put(score, list);\n }\n\n public String get() {\n int index = queryNum;\n for (int score: map.keySet()) {\n if (index < map.get(score).size()) {\n queryNum++;\n return map.get(score).get(index);\n }\n index -= map.get(score).size();\n }\n return \"\";\n }\n}", + "title": "2102. Sequentially Ordinal Rank Tracker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A scenic location is represented by its name and attractiveness score , where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time , the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class: Example 1:", + "description_images": [], + "constraints": [ + "Adding scenic locations, one at a time .", + "Querying the i th best location of all locations already added , where i is the number of times the system has been queried (including the current query). For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added.", + "For example, when the system is queried for the 4 th time, it returns the 4 th best location of all locations already added." + ], + "examples": [ + { + "text": "Example 1: Input[\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n[[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]Output[null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]ExplanationSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\ntracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\ntracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to itshigher score(3 > 2).\n // This is the 1sttime get() is called, so return the best location: \"branford\".\ntracker.add(\"alps\", 2); // Add location with name=\"alps\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because \"alps\" islexicographically smallerthan \"bradford\".\n // Return the 2ndbest location \"alps\", as it is the 2ndtime get() is called.\ntracker.add(\"orland\", 2); // Add location with name=\"orland\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return \"bradford\", as it is the 3rdtime get() is called.\ntracker.add(\"orlando\", 3); // Add location with name=\"orlando\" and score=3 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return \"bradford\".\ntracker.add(\"alpine\", 2); // Add location with name=\"alpine\" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"bradford\".\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"orland\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 675 ms (Top 95.65%) | Memory: 40.70 MB (Top 63.04%)\n\nfrom sortedcontainers import SortedList\nclass SORTracker:\n\n def __init__(self):\n self.arr=SortedList()\n self.index=-1\n def add(self, name: str, score: int) -> None:\n self.arr.add([-score,name])\n \n def get(self) -> str:\n \n self.index+=1\n return self.arr[self.index][1]\n\n\n# Your SORTracker object will be instantiated and called as such:\n# obj = SORTracker()\n# obj.add(name,score)\n# param_2 = obj.get()\n", + "title": "2102. Sequentially Ordinal Rank Tracker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,null,4,5]Output:[1,2,3,null,null,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "public class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n String data=\"\";\n Queue q=new LinkedList<>();\n if(root!=null)\n q.add(root);\n else\n return \"\";\n data=Integer.toString(root.val)+\"e\";\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i q=new LinkedList<>();\n q.add(root);\n while(i root.val){\n if(root.right != null)\n insert(digit, root.right);\n else\n root.right = new TreeNode(digit);\n } else {\n if(root.left != null)\n insert(digit, root.left);\n else\n root.left = new TreeNode(digit);\n }\n\n }\n}", + "title": "449. Serialize and Deserialize BST", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Serialization is 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 search tree . There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The input tree is guaranteed to be a binary search tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:[2,1,3]", + "image": null + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n \"\"\"Encodes a tree to a single string.\n \"\"\"\n if not root:\n return \"\"\n res = []\n def dfs(node):\n res.append(str(node.val))\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n dfs(root)\n return ','.join(res)\n def deserialize(self, data: str) -> Optional[TreeNode]:\n \"\"\"Decodes your encoded data to tree.\n \"\"\"\n if len(data) == 0:\n return []\n splitdata = data.split(\",\") \n preorder = []\n for item in splitdata:\n preorder.append(int(item)) \n inorder = sorted(preorder)\n hash_map = {} \n for i in range(len(inorder)):\n hash_map[inorder[i]] = i\n def helper(preorder, pstart, pend, inorder, istart, iend):\n if pstart > pend:\n return None\n elif pstart == pend:\n return TreeNode(preorder[pstart])\n\n root = TreeNode(preorder[pstart])\n \n rootindex = hash_map[preorder[pstart]]\n \n numleft = rootindex - istart\n \n root.left = helper(preorder, pstart+1, pstart + numleft, inorder, istart,rootindex-1 )\n root.right = helper(preorder, pstart + numleft +1, pend, inorder, rootindex +1, iend)\n \n return root\n \n return (helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1))\n", + "title": "449. Serialize and Deserialize BST", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An integer interval [a, b] (for integers a < b ) is a set of all consecutive integers from a to b , including a and b . Find the minimum size of a set S such that for every integer interval A in intervals , the intersection of S with A has a size of at least two. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 3000", + "intervals[i].length == 2", + "0 <= a i < b i <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[1,4],[2,5],[3,5]]Output:3Explanation:Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\nAlso, there isn't a smaller size set that fulfills the above condition.\nThus, we output the size of this set, which is 3.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[2,3],[2,4],[4,5]]Output:5Explanation:An example of a minimum sized set is {1, 2, 3, 4, 5}.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 28.66%) | Memory: 53.2 MB (Top 21.64%)\n//Time Complexity O(Nlog(N)) - N is the number of intervals\n//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed\nclass Solution {\n public int intersectionSizeTwo(int[][] intervals) {\n //corner case: can intervals be null or empty? No\n\n //First, sort the intervals by end, then by reverse order start\n Arrays.sort(intervals, new Comparator() {\n @Override\n public int compare(int[] a, int[] b) {\n if (a[1] == b[1]) {\n return b[0] - a[0];\n }\n return a[1] - b[1];\n }\n });\n\n //Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request\n List list = new ArrayList<>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition\n\n //add last two nums within the range\n list.add(intervals[0][1] - 1);\n list.add(intervals[0][1]);\n\n for (int i = 1; i < intervals.length; i++) {\n int lastOne = list.get(list.size() - 1);\n int lastTwo = list.get(list.size() - 2);\n\n int[] interval = intervals[i];\n int start = interval[0];\n int end = interval[1];\n\n //if overlaps at least 2\n if (lastOne >= start && lastTwo >= start) {\n continue;\n } else if (lastOne >= start) { //if overlaps 1\n list.add(end);\n } else { //if not overlapping\n list.add(end - 1);\n list.add(end);\n }\n }\n\n return list.size();\n }\n}", + "title": "757. Set Intersection Size At Least Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An integer interval [a, b] (for integers a < b ) is a set of all consecutive integers from a to b , including a and b . Find the minimum size of a set S such that for every integer interval A in intervals , the intersection of S with A has a size of at least two. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 3000", + "intervals[i].length == 2", + "0 <= a i < b i <= 10^8" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[1,4],[2,5],[3,5]]Output:3Explanation:Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.\nAlso, there isn't a smaller size set that fulfills the above condition.\nThus, we output the size of this set, which is 3.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[2,3],[2,4],[4,5]]Output:5Explanation:An example of a minimum sized set is {1, 2, 3, 4, 5}.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)", + "title": "757. Set Intersection Size At Least Two", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]Output:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 25.0%) | Memory: 44.70 MB (Top 37.39%)\n\nclass Solution {\n public void setZeroes(int[][] matrix) {\n Set row = new HashSet<>();\n Set col = new HashSet<>();\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] == 0){\n row.add(i);\n col.add(j);\n }\n }\n }\n for(int r : row){\n for(int i = 0; i < matrix[0].length; i++){\n matrix[r][i] = 0;\n }\n }\n for(int c : col){\n for(int i = 0; i < matrix.length; i++){\n matrix[i][c] = 0;\n }\n }\n }\n}\n", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]Output:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void setZeroes(int[][] matrix) { \n\t\tif (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n\t\t\treturn;\n\n\t\tint row = matrix.length;\n\t\tint col = matrix[0].length;\n\n\t\tboolean firstColumnZero = false;\n\t\tboolean firstRowZero = false;\n\n\t\t// Check if first column should be made zero\n\t\tfor (int i = 0; i < row; i++) {\n\t\t\tif (matrix[i][0] == 0) {\n\t\t\t\tfirstColumnZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Check if first row should be made zero\n\t\tfor (int i = 0; i < col; i++) {\n\t\t\tif (matrix[0][i] == 0) {\n\t\t\t\tfirstRowZero = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse the matrix excluding first row and column\n\t\t// If zero is found, update the same in first row and column\n\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][j] == 0) {\n\t\t\t\t\tmatrix[i][0] = 0;\n\t\t\t\t\tmatrix[0][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Now traverse again and update\n\t\tfor (int i = 1; i < row; i++) {\n\t\t\tfor (int j = 1; j < col; j++) {\n\t\t\t\tif (matrix[i][0] == 0 || matrix[0][j] == 0) {\n\t\t\t\t\tmatrix[i][j] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first column\n\t\tif (firstColumnZero) {\n\t\t\tfor (int i = 0; i < row; i++) {\n\t\t\t\tmatrix[i][0] = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Traverse and update first row\n\t\tif (firstRowZero) {\n\t\t\tfor (int j = 0; j < col; j++) {\n\t\t\t\tmatrix[0][j] = 0;\n\t\t\t}\n\t\t}\n\n\t\n }\n}\n", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]Output:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n rows = len(matrix)\n cols = len(matrix[0])\n visited=set()\n for r in range(rows):\n for c in range(cols):\n \n if matrix[r][c]==0 and (r,c) not in visited :\n for t in range(cols):\n if matrix[r][t]!=0:\n matrix[r][t]=0\n visited.add((r,t))\n for h in range(rows):\n if matrix[h][c]!=0:\n matrix[h][c]=0\n visited.add((h,c))\n ##Time Complexity :- O(m*n)\n ##Space Complexity:- O(m+n)\n\t\t\n\t\t```", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a set of integers s , which originally contains all the numbers from 1 to n . Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,4]Output:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.57%) | Memory: 45.20 MB (Top 54.78%)\n\nclass Solution {\n public int[] findErrorNums(int[] nums) {\n int N = nums.length, sum = N * (N + 1) / 2;\n int[] ans = new int[2];\n boolean[] seen = new boolean[N+1];\n for (int num : nums) {\n sum -= num;\n if (seen[num]) ans[0] = num;\n seen[num] = true;\n }\n ans[1] = sum + ans[0];\n return ans;\n }\n}\n", + "title": "645. Set Mismatch", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a set of integers s , which originally contains all the numbers from 1 to n . Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2,4]Output:[2,3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 93.95%) | Memory: 18.00 MB (Top 86.53%)\n\nclass Solution:\n def findErrorNums(self, nums):\n n = len(nums)\n v = [0] * (n + 1)\n missing, duplicate = 0, 0\n\n for num in nums:\n v[num] += 1\n\n for i in range(1, len(v)):\n if v[i] == 2:\n duplicate = i\n if v[i] == 0:\n missing = i\n\n return [duplicate, missing]\n\n\n", + "title": "645. Set Mismatch", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 2D grid of size m x n and an integer k . You need to shift the grid k times. In one shift operation: Return the 2D grid after applying shift operation k times. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Element at grid[i][j] moves to grid[i][j + 1] .", + "Element at grid[i][n - 1] moves to grid[i + 1][0] .", + "Element at grid[m - 1][n - 1] moves to grid[0][0] ." + ], + "examples": [ + { + "text": "Example 1: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 1Output:[[9,1,2],[3,4,5],[6,7,8]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e1.png" + }, + { + "text": "Example 2: Input:grid= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4Output:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e2.png" + }, + { + "text": "Example 3: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 9Output:[[1,2,3],[4,5,6],[7,8,9]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> shiftGrid(int[][] grid, int k) {\n // just bruteforce??? O(i*j*k)\n // instead we calculate the final position at once!\n \n int m = grid.length; // row\n int n = grid[0].length; // column\n \n int[][] arr = new int[m][n];\n \n // Since moving m*n times will result in same matrix, we do this:\n k = k % (m*n);\n \n // Then we move each element\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // for calculating column, it back to the original position\n // every n steps\n int column = (j + k) % n;\n \n // for calculating row, we move to the next row each time\n // it exceed the last element on the current row.\n // For example when 2 moves k=5 steps it turns to the (+2) row.\n // Thus it's original row + ((original column + steps) / n)\n // But if 2 moves k=8 steps it turns to the (0,0),\n // and row + ((original column + steps) / n) gives 0+(9/3)=3 (out of bounds)\n // so we'll need to % number of rows to get 0. (circle back)\n int row = (i + ((j + k) / n)) % m;\n arr[row][column] = grid[i][j];\n }\n }\n return (List) Arrays.asList(arr);\n }\n}\n", + "title": "1260. Shift 2D Grid", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a 2D grid of size m x n and an integer k . You need to shift the grid k times. In one shift operation: Return the 2D grid after applying shift operation k times. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Element at grid[i][j] moves to grid[i][j + 1] .", + "Element at grid[i][n - 1] moves to grid[i + 1][0] .", + "Element at grid[m - 1][n - 1] moves to grid[0][0] ." + ], + "examples": [ + { + "text": "Example 1: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 1Output:[[9,1,2],[3,4,5],[6,7,8]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e1.png" + }, + { + "text": "Example 2: Input:grid= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4Output:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]", + "image": "https://assets.leetcode.com/uploads/2019/11/05/e2.png" + }, + { + "text": "Example 3: Input:grid= [[1,2,3],[4,5,6],[7,8,9]], k = 9Output:[[1,2,3],[4,5,6],[7,8,9]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0])\n cache = []\n for i in range(m):\n for j in range(n):\n cache.append(grid[i][j])\n \n k %= len(cache)\n new_vals = cache[-k:] + cache[:-k]\n \n cur = 0\n for i in range(m):\n for j in range(n):\n grid[i][j] = new_vals[cur]\n cur += 1\n \n return grid\n", + "title": "1260. Shift 2D Grid", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a' ). Now for each shifts[i] = x , we want to shift the first i + 1 letters of s , x times. Return the final string after all such shifts to s are applied . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, shift('a') = 'b' , shift('t') = 'u' , and shift('z') = 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", shifts = [3,5,9]Output:\"rpl\"Explanation:We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\", shifts = [1,2,3]Output:\"gfd\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 23.48%) | Memory: 82.1 MB (Top 8.82%)\nclass Solution {\n public String shiftingLetters(String s, int[] shifts) {\n char[] arr = s.toCharArray();\n int[] arr1 = new int[shifts.length];\n arr1[arr1.length-1] = (shifts[shifts.length-1])%26;\n for(int i =shifts.length -2 ;i>=0 ;i--){\n arr1[i] = (shifts[i] + arr1[i+1])%26;\n }\n for(int i =0; i122){\n int m = arr1[i] -(122-c);\n n = m+96;\n }\n char ch = (char)n;\n arr[i] = ch;\n\n }\n String string = new String(arr);\n return string;\n\n }\n}", + "title": "848. Shifting Letters", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a' ). Now for each shifts[i] = x , we want to shift the first i + 1 letters of s , x times. Return the final string after all such shifts to s are applied . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, shift('a') = 'b' , shift('t') = 'u' , and shift('z') = 'a' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", shifts = [3,5,9]Output:\"rpl\"Explanation:We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaa\", shifts = [1,2,3]Output:\"gfd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n n = len(s)\n nums = []\n sums = 0\n for i in shifts[::-1]:\n sums = (sums+i)%26\n nums.append(sums)\n nums = nums[::-1]\n \n res = ''\n for i, ch in enumerate(s):\n val = ord(s[i]) + nums[i]\n while val > 122:\n val -= 26\n res += chr(val)\n \n return res", + "title": "848. Shifting Letters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the i th item, and an integer array needs where needs[i] is the number of pieces of the i th item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the j th item in the i th offer and special[i][n] (i.e., the last integer in the array) is the price of the i th offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers . You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == price.length == needs.length", + "1 <= n <= 6", + "0 <= price[i], needs[i] <= 10", + "1 <= special.length <= 100", + "special[i].length == n + 1", + "0 <= special[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]Output:14Explanation:There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.", + "image": null + }, + { + "text": "Example 2: Input:price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]Output:11Explanation:The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 549 ms (Top 11.6%) | Memory: 43.58 MB (Top 33.0%)\n\nclass Solution {\n public static int fun(int index,List price,List> special, List needs){\n // Base \n if(index < 0){\n int addAmount = 0;\n for(int i=0;i(needs));\n\n // Take Offer \n int takeOffer = 1000000000;\n if(canTakeOffer(special.get(index),new ArrayList<>(needs))){\n List current_special = special.get(index);\n for(int i=0;i(needs));\n }\n return Math.min(notTakeOffer,takeOffer);\n }\n\n public static boolean canTakeOffer(List current_special, List needs){\n boolean canTake = true;\n for(int i=0;i price, List> special, List needs) {\n int items = price.size();\n int offers = special.size();\n return fun(offers-1,price,special,needs);\n }\n}", + "title": "638. Shopping Offers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array price where price[i] is the price of the i th item, and an integer array needs where needs[i] is the number of pieces of the i th item you want to buy. You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the j th item in the i th offer and special[i][n] (i.e., the last integer in the array) is the price of the i th offer. Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers . You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == price.length == needs.length", + "1 <= n <= 6", + "0 <= price[i], needs[i] <= 10", + "1 <= special.length <= 100", + "special[i].length == n + 1", + "0 <= special[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]Output:14Explanation:There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.", + "image": null + }, + { + "text": "Example 2: Input:price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]Output:11Explanation:The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 164 ms (Top 43.73%) | Memory: 14 MB (Top 84.10%)\nclass Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n def dfs(price, special, needs, memo = {}):\n if tuple(needs) in memo:\n return memo[tuple(needs)]\n res = [sum([p * need for p, need in zip(price, needs)])] # don't use any offer\n for offer in special:\n # check if can apply the offer\n new_needs = []\n for offer_items, need in zip(offer[:-1], needs):\n new_needs.append(need - offer_items)\n if min(new_needs) < 0:\n continue\n # Check if without the offer is better\n value = 0\n for p, offer_items in zip(price, offer[:-1]):\n value += p * offer_items\n if value < offer[-1]:\n continue\n # Valid Case\n res.append(dfs(price, special, new_needs, memo) + offer[-1])\n memo[tuple(needs)] = min(res)\n return min(res)\n return dfs(price, special, needs)", + "title": "638. Shopping Offers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A valid encoding of an array of words is any reference string s and array of indices indices such that: Given an array of words , return the length of the shortest reference string s possible of any valid encoding of words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "words.length == indices.length", + "The reference string s ends with the '#' character.", + "For each index indices[i] , the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"time\", \"me\", \"bell\"]Output:10Explanation:A valid encoding would be s =\"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"", + "image": null + }, + { + "text": "Example 2: Input:words = [\"t\"]Output:2Explanation:A valid encoding would be s = \"t#\" and indices = [0].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 85.71%) | Memory: 59.1 MB (Top 35.19%)\nclass Node {\n private boolean flag;\n private Node[] children;\n\n public Node () {\n flag = false;\n children = new Node[26];\n Arrays.fill (children, null);\n }\n\n public boolean getFlag () {\n return flag;\n }\n\n public Node getChild (int index) {\n return children[index];\n }\n\n public boolean hasChild (int index) {\n return children[index] != null;\n }\n\n public void setFlag (boolean flag) {\n this.flag = flag;\n }\n\n public void makeChild (int index) {\n children[index] = new Node();\n }\n}\n\nclass Trie {\n private Node root;\n\n public Trie () {\n root = new Node();\n }\n\n public int addWord (String word) {\n\n boolean flag = true;\n Node node = root;\n int count = 0;\n\n for (int i = word.length () - 1; i >= 0; --i) {\n int index = (int) word.charAt(i) - 97;\n\n if (!node.hasChild (index)) {\n flag = false;\n node.makeChild (index);\n }\n\n node = node.getChild (index);\n if (node.getFlag()) {\n node.setFlag (false);\n count -= word.length() - i + 1;\n\n if (i == 0)\n flag = false;\n }\n }\n\n if (!flag)\n node.setFlag (true);\n\n return flag? count: count + 1 + word.length();\n }\n}\n\nclass Solution {\n public int minimumLengthEncoding(String[] words) {\n Trie trie = new Trie ();\n int size = 0;\n\n for (String word: words) {\n size += trie.addWord (word);\n }\n\n return size;\n }\n}", + "title": "820. Short Encoding of Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A valid encoding of an array of words is any reference string s and array of indices indices such that: Given an array of words , return the length of the shortest reference string s possible of any valid encoding of words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "words.length == indices.length", + "The reference string s ends with the '#' character.", + "For each index indices[i] , the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i] ." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"time\", \"me\", \"bell\"]Output:10Explanation:A valid encoding would be s =\"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"", + "image": null + }, + { + "text": "Example 2: Input:words = [\"t\"]Output:2Explanation:A valid encoding would be s = \"t#\" and indices = [0].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumLengthEncoding(self, words):\n \n \n # root of suffix trie\n trie_root = dict()\n \n # helper function to judge leaf node\n isLeafNode = lambda node: len(node) == 0\n \n # collection of tail nodes\n tail_nodes = []\n \n # set of unique words\n unique_words = set(words)\n \n # scan each word\n for word in unique_words:\n \n # build suffix trie from root node\n cur = trie_root\n \n # scan each character in reversed order\n for char in reversed(word):\n \n # update trie\n cur[char] = cur.get(char, dict() )\n \n # go to next level\n cur = cur[char]\n \n # save tail nodes with corresponding word length, +1 is for '#' symbol\n tail_nodes.append( (cur, len(word)+1) )\n\n # summation of the length with all tail node which is also a leaf node\n return sum( suffix_length for node, suffix_length in tail_nodes if isLeafNode(node) )", + "title": "820. Short Encoding of Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1 's not connected to any other 1 's. There are exactly two islands in grid . You may change 0 's to 1 's to connect the two islands to form one island . Return the smallest number of 0 's you must flip to connect the two islands . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "2 <= n <= 100", + "grid[i][j] is either 0 or 1 .", + "There are exactly two islands in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,1,0],[0,0,0],[0,0,1]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 59.97%) | Memory: 53.7 MB (Top 81.02%)\n\nclass Solution {\n private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}};\n public int shortestBridge(int[][] grid) {\n boolean[][] visited=new boolean[grid.length][grid[0].length];\n LinkedList queue=new LinkedList();\n boolean found=false;\n for(int i=0;i0){\n int size=queue.size();\n while(size-- >0){\n Pair pair=queue.poll();\n for(int k=0;k<4;k++){\n int rowDash=pair.row+dirs[k][0];\n int colDash=pair.col+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true )continue;\n if(grid[rowDash][colDash]==1) return level;\n queue.add(new Pair(rowDash,colDash));\n visited[rowDash][colDash]=true;\n }\n }\n level++;\n }\n return -1;\n }\n private void dfs(int[][] grid,int i,int j,LinkedList queue,boolean[][] visited){\n visited[i][j]=true;\n queue.add(new Pair(i,j));\n for(int k=0;k<4;k++){\n int rowDash=i+dirs[k][0];\n int colDash=j+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true || grid[rowDash][colDash]==0)continue;\n dfs(grid,rowDash,colDash,queue,visited);\n }\n }\n static class Pair{\n int row;\n int col;\n public Pair(int row,int col){\n this.row=row;\n this.col=col;\n }\n }\n}", + "title": "934. Shortest Bridge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water. An island is a 4-directionally connected group of 1 's not connected to any other 1 's. There are exactly two islands in grid . You may change 0 's to 1 's to connect the two islands to form one island . Return the smallest number of 0 's you must flip to connect the two islands . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "2 <= n <= 100", + "grid[i][j] is either 0 or 1 .", + "There are exactly two islands in grid ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [[0,1,0],[0,0,0],[0,0,1]]Output:2", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 329 ms (Top 84.2%) | Memory: 17.67 MB (Top 84.2%)\n\nclass Solution:\n def shortestBridge(self, grid):\n m, n = len(grid), len(grid[0])\n start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n \n stack = [(start_i, start_j)]\n visited = set(stack)\n while stack:\n i, j = stack.pop()\n visited.add((i, j)) \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n stack.append((ii, jj))\n visited.add((ii, jj))\n \n \n ans = 0\n queue = list(visited)\n while queue:\n new_queue = []\n for i, j in queue:\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n if grid[ii][jj] == 1:\n return ans\n new_queue.append((ii, jj))\n visited.add((ii, jj))\n queue = new_queue\n ans += 1\n", + "title": "934. Shortest Bridge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings str1 and str2 , return the shortest string that has both str1 and str2 as subsequences . If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0 ) results in the string s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"abac\", str2 = \"cab\"Output:\"cabac\"Explanation:str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"Output:\"aaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String shortestCommonSupersequence(String str1, String str2) {\n int m=str1.length();\n int n=str2.length();\n int[][] dp=new int[m+1][n+1];\n for(int i=1;i0 && j>0){\n if(str1.charAt(i-1)==str2.charAt(j-1)){\n res=str1.charAt(i-1)+res;\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]){\n res=str1.charAt(i-1)+res;\n i--;\n }else{\n res=str2.charAt(j-1)+res;\n j--;\n }\n }\n while(i>0){\n res=str1.charAt(i-1)+res;\n i--;\n }\n while(j>0){\n res=str2.charAt(j-1)+res;\n j--;\n }\n return res;\n }\n}\n", + "title": "1092. Shortest Common Supersequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two strings str1 and str2 , return the shortest string that has both str1 and str2 as subsequences . If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0 ) results in the string s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"abac\", str2 = \"cab\"Output:\"cabac\"Explanation:str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"Output:\"aaaaaaaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestCommonSupersequence(self, A, B):\n n, m = len(A), len(B)\n dp = [B[:i] for i in range(m + 1)]\n for i in range(n):\n prev = A[:i]\n dp[0] = A[:i + 1]\n for j in range(m):\n if A[i] == B[j]:\n prev, dp[j + 1] = dp[j + 1], prev + A[i]\n else:\n prev, dp[j + 1] = dp[j + 1], min(dp[j] + B[j], dp[j + 1] + A[i], key = len)\n return dp[-1]\n", + "title": "1092. Shortest Common Supersequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string licensePlate and an array of strings words , find the shortest completing word in words . A completing word is a word that contains all the letters in licensePlate . Ignore numbers and spaces in licensePlate , and treat letters as case insensitive . If a letter appears more than once in licensePlate , then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\" , then it contains letters 'a' , 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\" , \"caaacab\" , and \"cbca\" . Return the shortest completing word in words . It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= licensePlate.length <= 7", + "licensePlate contains digits, letters (uppercase or lowercase), or space ' ' .", + "1 <= words.length <= 1000", + "1 <= words[i].length <= 15", + "words[i] consists of lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]Output:\"steps\"Explanation:licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.", + "image": null + }, + { + "text": "Example 2: Input:licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]Output:\"pest\"Explanation:licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 66.6%) | Memory: 43.77 MB (Top 64.6%)\n\nclass Solution {\n public String shortestCompletingWord(String licensePlate, String[] words) {\n //Store count of letters in LicensePlate\n int[] licensePlateCount = new int[26];\n \n //To store all words which meet the criteria\n ArrayList res = new ArrayList<>();\n //To find min length word that meets the criteria\n int min = Integer.MAX_VALUE;\n \n //Add char count for each char in LicensePlate\n for(Character c:licensePlate.toCharArray()) {\n if(isChar(c)) {\n licensePlateCount[Character.toLowerCase(c) - 'a']++;\n }\n }\n \n //Add char count for each word in words\n for(String word : words) {\n int[] wordCharCount = new int[26];\n boolean flag = true;\n \n for(Character c:word.toCharArray()) {\n wordCharCount[Character.toLowerCase(c) - 'a']++;\n }\n \n //Eliminate words that don't satisfy the criteria\n for(int i = 0; i<26;i++) {\n if(licensePlateCount[i] > wordCharCount[i]) flag = false;\n }\n \n //Add words satisfying criteria to res and calculate min word length\n if(flag) {\n res.add(word);\n if(word.length() < min) min = word.length();\n }\n }\n \n //Return 1st word in array meeting all criteria\n for(int i = 0; i < res.size();i++) {\n if(res.get(i).length() == min) return res.get(i);\n }\n \n //If not found, return -1 (or whatever interviewer expects)\n return \"-1\";\n }\n \n private boolean isChar(Character c) {\n if((c >='a' && c <='z') ||\n (c>='A' && c<='Z')) return true;\n \n return false;\n }\n}", + "title": "748. Shortest Completing Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string licensePlate and an array of strings words , find the shortest completing word in words . A completing word is a word that contains all the letters in licensePlate . Ignore numbers and spaces in licensePlate , and treat letters as case insensitive . If a letter appears more than once in licensePlate , then it must appear in the word the same number of times or more. For example, if licensePlate = \"aBc 12c\" , then it contains letters 'a' , 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\" , \"caaacab\" , and \"cbca\" . Return the shortest completing word in words . It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= licensePlate.length <= 7", + "licensePlate contains digits, letters (uppercase or lowercase), or space ' ' .", + "1 <= words.length <= 1000", + "1 <= words[i].length <= 15", + "words[i] consists of lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]Output:\"steps\"Explanation:licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.", + "image": null + }, + { + "text": "Example 2: Input:licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]Output:\"pest\"Explanation:licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n newPlate = '' # modify the licensePlate\n for i in licensePlate:\n if i.isalpha():\n newPlate += i.lower()\n \n c = Counter(newPlate)\n l1 = [] # store (word,len,index)\n for idx,word in enumerate(words):\n if Counter(word) >= c:\n l1.append((word,len(word),idx))\n l1.sort(key = lambda x:(x[1],idx))\n return l1[0][0]\n", + "title": "748. Shortest Completing Word", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and a character c that occurs in s , return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s . The distance between two indices i and j is abs(i - j) , where abs is the absolute value function. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] and c are lowercase English letters.", + "It is guaranteed that c occurs at least once in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"loveleetcode\", c = \"e\"Output:[3,2,1,0,1,0,0,1,2,2,1,0]Explanation:The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\", c = \"b\"Output:[3,2,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 72.97%) | Memory: 43.3 MB (Top 45.95%)\nclass Solution {\n public int[] shortestToChar(String s, char c) {\n int n = s.length();\n int index = -1;\n int[] ans = new int[n];\n // Starting from index 0 and storing the distance from the next c;\n for(int i=0;i=0;i--){\n if(s.charAt(i)==c) index = i;//to store the index of the nearest next c\n\n if(index!=-1) ans[i] = Math.min(ans[i],index-i);\n }\n return ans;\n }\n}", + "title": "821. Shortest Distance to a Character", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s and a character c that occurs in s , return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s . The distance between two indices i and j is abs(i - j) , where abs is the absolute value function. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s[i] and c are lowercase English letters.", + "It is guaranteed that c occurs at least once in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"loveleetcode\", c = \"e\"Output:[3,2,1,0,1,0,0,1,2,2,1,0]Explanation:The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aaab\", c = \"b\"Output:[3,2,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n res = []\n ch= []\n for i in range(len(s)):\n if s[i] == c:\n ch.append(i)\n min_d = len(s)\n for i in range(len(s)):\n for j in range(len(ch)):\n min_d = min(min_d, abs(i-ch[j]))\n res.append(min_d)\n min_d = len(s)\n return res\n", + "title": "821. Shortest Distance to a Character", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array rolls of length n and an integer k . You roll a k sided dice numbered from 1 to k , n times, where the result of the i th roll is rolls[i] . Return the length of the shortest sequence of rolls that cannot be taken from rolls . A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == rolls.length", + "1 <= n <= 10^5", + "1 <= rolls[i] <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [4,2,1,2,3,3,2,4,1], k = 4Output:3Explanation:Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,1,2,2], k = 2Output:2Explanation:Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,1,3,2,2,2,3,3], k = 4Output:1Explanation:The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestSequence(int[] rolls, int k) {\n int len = 0;\n Set set = new HashSet<>();\n for(int i:rolls)\n {\n set.add(i);\n if(set.size()==k)\n {\n set = new HashSet<>();\n len++;\n }\n }\n return len+1;\n }\n}\n", + "title": "2350. Shortest Impossible Sequence of Rolls", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array rolls of length n and an integer k . You roll a k sided dice numbered from 1 to k , n times, where the result of the i th roll is rolls[i] . Return the length of the shortest sequence of rolls that cannot be taken from rolls . A sequence of rolls of length len is the result of rolling a k sided dice len times. Note that the sequence taken does not have to be consecutive as long as it is in order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == rolls.length", + "1 <= n <= 10^5", + "1 <= rolls[i] <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:rolls = [4,2,1,2,3,3,2,4,1], k = 4Output:3Explanation:Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.", + "image": null + }, + { + "text": "Example 2: Input:rolls = [1,1,2,2], k = 2Output:2Explanation:Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.", + "image": null + }, + { + "text": "Example 3: Input:rolls = [1,1,3,2,2,2,3,3], k = 4Output:1Explanation:The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 966 ms (Top 94.20%) | Memory: 28.2 MB (Top 71.33%)\nclass Solution:\n def shortestSequence(self, rolls: List[int], k: int) -> int:\n ans = 1\n data = set()\n\n for roll in rolls:\n data.add(roll)\n\n if len(data) == k:\n ans += 1\n data.clear()\n\n return ans", + "title": "2350. Shortest Impossible Sequence of Rolls", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s . You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacecaaa\"Output:\"aaacecaaa\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"Output:\"dcbabcd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String shortestPalindrome(String s) {\n for(int i=s.length()-1; i >= 0; i--){\n if(isPalindrome(s, 0, i)){\n String toAppend = s.substring(i+1);\n String result = new StringBuilder(toAppend).reverse().append(s).toString();\n return result;\n }\n }\n String result = new StringBuilder(s).reverse().append(s).toString();\n return result; \n }\n \n boolean isPalindrome(String s, int left, int right){\n while(left < right){\n if(s.charAt(left) != s.charAt(right))\n return false;\n left++;\n right--;\n }\n return true;\n }\n}\n", + "title": "214. Shortest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s . You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of lowercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aacecaaa\"Output:\"aaacecaaa\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcd\"Output:\"dcbabcd\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPalindrome(self, s: str) -> str:\n \n end = 0\n \n # if the string itself is a palindrome return it\n if(s == s[::-1]):\n return s\n \n # Otherwise find the end index of the longest palindrome that starts\n # from the first character of the string\n \n for i in range(len(s)+1):\n if(s[:i]==s[:i][::-1]):\n end=i-1\n \n # return the string with the remaining characters other than\n # the palindrome reversed and added at the beginning\n \n return (s[end+1:][::-1])+s\n", + "title": "214. Shortest Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step . Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles . If it is not possible to find such walk return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 40", + "1 <= k <= m * n", + "grid[i][j] is either 0 or 1 .", + "grid[0][0] == grid[m - 1][n - 1] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1Output:6Explanation:The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) ->(3,2)-> (4,2).", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1Output:-1Explanation:We need to eliminate at least two obstacles to find such a walk.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short2-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 735 ms (Top 5.01%) | Memory: 122.2 MB (Top 5.01%)\nclass Solution {\n int rowLen = 0;\n int colLen = 0;\n int MAXVAL = 0;\n public int shortestPath(int[][] grid, int k) {\n rowLen = grid.length;\n colLen = grid[0].length;\n MAXVAL = rowLen * colLen + 1;\n int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k+1][4]);\n return path == MAXVAL ? -1 : path;\n }\n\n /* Direction\n 0 - Up\n 1 - Down\n 2 - Left\n 3 - Right\n */\n\n // For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we consider the direction as well\n int shortest(int[][] grid, int k, int row, int col, int direction, boolean[][] visited, Integer[][][][] dp){\n // Reached end of the matrix\n if(row == rowLen - 1 && col == colLen - 1 && k >= 0)\n return 0;\n\n // Couldn't find a valid path\n if(k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen)\n return MAXVAL;\n\n if(dp[row][col][k][direction] != null)\n return dp[row][col][k][direction];\n\n // 4 options to choose a direction\n // Go right\n int op1 = MAXVAL;\n if(col + 1 < colLen && !visited[row][col+1]) {\n visited[row][col+1] = true;\n if(grid[row][col+1] == 0)\n op1 = shortest(grid, k, row, col+1, 3, visited, dp) + 1;\n else\n op1 = shortest(grid, k-1, row, col+1, 3, visited, dp) + 1;\n visited[row][col+1] = false;\n }\n\n // Go left\n int op2 = MAXVAL;\n if(col - 1 >= 0 && !visited[row][col-1]) {\n visited[row][col-1] = true;\n if(grid[row][col-1] == 0)\n op2 = shortest(grid, k, row, col-1, 2, visited, dp) + 1;\n else\n op2 = shortest(grid, k-1, row, col-1, 2, visited, dp) + 1;\n visited[row][col-1] = false;\n }\n\n // Go up\n int op3 = MAXVAL;\n if(row - 1 >= 0 && !visited[row-1][col]) {\n visited[row-1][col] = true;\n if(grid[row-1][col] == 0)\n op3 = shortest(grid, k, row-1, col, 0, visited, dp) + 1;\n else\n op3 = shortest(grid, k-1, row-1, col, 0, visited, dp) + 1;\n visited[row-1][col] = false;\n }\n\n // Go down\n int op4 = MAXVAL;\n if(row + 1 < rowLen && !visited[row+1][col]) {\n visited[row+1][col] = true;\n if(grid[row+1][col] == 0)\n op4 = shortest(grid, k, row+1, col, 1, visited, dp) + 1;\n else\n op4 = shortest(grid, k-1, row+1, col, 1, visited, dp) + 1;\n visited[row+1][col] = false;\n }\n\n dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4));\n return dp[row][col][k][direction];\n }\n}", + "title": "1293. Shortest Path in a Grid with Obstacles Elimination", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step . Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles . If it is not possible to find such walk return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 40", + "1 <= k <= m * n", + "grid[i][j] is either 0 or 1 .", + "grid[0][0] == grid[m - 1][n - 1] == 0" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1Output:6Explanation:The shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) ->(3,2)-> (4,2).", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short1-grid.jpg" + }, + { + "text": "Example 2: Input:grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1Output:-1Explanation:We need to eliminate at least two obstacles to find such a walk.", + "image": "https://assets.leetcode.com/uploads/2021/09/30/short2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n Q = [[0, 0, k]] # m, n, remaining elimination quota \n rows, cols = len(grid), len(grid[0])\n V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited\n \n while Q: \n frontier = []\n for m, n, rem in Q: \n if m == rows - 1 and n == cols - 1: \n return counter \n for dm, dn in [[1, 0], [-1, 0], [0, 1], [0, -1]]: \n if 0 <= m+dm < rows and 0 <= n+dn < cols: # check inbound \n if grid[m+dm][n+dn] == 0: \n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem])\n V[(m+dm, n+dn)] = rem\n elif rem > 0: # I see a wall and I can still eliminate\n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem - 1: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem-1])\n V[(m+dm, n+dn)] = rem - 1\n Q = frontier \n counter += 1\n \n return -1\n\t```", + "title": "1293. Shortest Path in a Grid with Obstacles Elimination", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an n x n binary matrix grid , return the length of the shortest clear path in the matrix . If there is no clear path, return -1 . A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0) ) to the bottom-right cell (i.e., (n - 1, n - 1) ) such that: The length of a clear path is the number of visited cells of this path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All the visited cells of the path are 0 .", + "All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner)." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example1_1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[1,1,0],[1,1,0]]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example2_1.png" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,0]]Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestPathBinaryMatrix(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n \n boolean [][] visited = new boolean [m][n];\n \n int [] up = {0, 0, 1, -1, 1, 1, -1, -1};\n int [] down = {-1, 1, 0, 0, -1, 1, -1, 1};\n \n /*\n if top-left is 1 or bottom-right is 1\n we will return -1\n */\n if(grid[0][0] == 1 || grid[m-1][n-1] == 1)\n return -1;\n \n ArrayDeque q = new ArrayDeque<>();\n /*\n we will add top-left to the deque\n ans steps as 1\n */\n q.add(new int[]{0,0,1}); \n \n while(q.size() > 0){\n int [] tmp = q.removeFirst();\n int x = tmp[0];\n int y = tmp[1];\n int steps = tmp[2];\n visited[x][y] = true;\n \n if(x == m-1 && y == n-1)\n return steps;\n \n for(int i = 0; i < 8; i++){\n int x_new = x + up[i];\n int y_new = y + down[i];\n /*\n we will traverse level wise using bfs\n and those which can be directly reach via\n current level will be considered as the same\n level and we will return the level of \n bottom-right as result\n */\n if(x_new >= 0 && x_new < m && y_new >= 0 && y_new < n){\n if(visited[x_new][y_new] == false && grid[x_new][y_new] == 0){\n q.add(new int[]{x_new,y_new,steps+1});\n visited[x_new][y_new] = true;\n }\n }\n }\n }\n \n return -1;\n }\n}\n", + "title": "1091. Shortest Path in Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an n x n binary matrix grid , return the length of the shortest clear path in the matrix . If there is no clear path, return -1 . A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0) ) to the bottom-right cell (i.e., (n - 1, n - 1) ) such that: The length of a clear path is the number of visited cells of this path. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "All the visited cells of the path are 0 .", + "All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner)." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:2", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example1_1.png" + }, + { + "text": "Example 2: Input:grid = [[0,0,0],[1,1,0],[1,1,0]]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/02/18/example2_1.png" + }, + { + "text": "Example 3: Input:grid = [[1,0,0],[1,1,0],[1,1,0]]Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nfrom collections import deque\nclass Solution:\n\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\t\tL=len(grid)\n\t\tdef generate_next_state(i,j):\n\t\t\treturn [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]\n\t\tdef valid_state(states):\n\t\t\tres=[]\n\t\t\tfor (i,j) in states:\n\t\t\t\tif i>L-1:continue\n\t\t\t\tif i<0:continue\n\t\t\t\tif j<0:continue\n\t\t\t\tif j>L-1:continue\n\t\t\t\tif grid[i][j]==0:\n\t\t\t\t\tres.append((i,j))\n\t\t\treturn res\n\t\tqueue=deque([(0,0)])\n\t\tres=1\n\t\twhile queue:\n\t\t\tfor _ in range(len(queue)):\n\t\t\t\ti,j=queue.popleft()\n\t\t\t\tval=grid[i][j]\n\t\t\t\tgrid[i][j]=1\n\t\t\t\tif not val:\n\t\t\t\t\tif i==L-1 and j==L-1:\n\t\t\t\t\t\treturn res\n\n\t\t\t\t\tnext_state=valid_state(generate_next_state(i,j))\n\t\t\t\t\tfor (ki,kj) in next_state:\n\t\t\t\t\t\tqueue.append((ki,kj))\n\t\t\tres+=1\n\t\treturn -1\n \n \n \n \n'''", + "title": "1091. Shortest Path in Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n grid grid where: You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6 , there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys . If it is impossible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "'.' is an empty cell.", + "'#' is a wall.", + "'@' is the starting point.", + "Lowercase letters represent keys.", + "Uppercase letters represent locks." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"@.a..\",\"###.#\",\"b.A.B\"]Output:8Explanation:Note that the goal is to obtain all the keys not to open all the locks.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg" + }, + { + "text": "Example 2: Input:grid = [\"@..aA\",\"..B#.\",\"....b\"]Output:6", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg" + }, + { + "text": "Example 3: Input:grid = [\"@Aa\"]Output:-1", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static final int[][] DIRS = new int[][]{ \n {1,0}, {-1,0}, {0,1}, {0,-1}\n };\n \n public int shortestPathAllKeys(String[] grid) {\n int m = grid.length, n = grid[0].length();\n int numKeys = 0, startRow = -1, startCol = -1;\n \n for(int i=0; i queue = new LinkedList();\n Set visited = new HashSet(); \n int steps = 0;\n \n queue.offer(start);\n visited.add(start);\n \n while( !queue.isEmpty() ) {\n int size = queue.size();\n \n while( size-- > 0 ) {\n int i = queue.peek().i;\n int j = queue.peek().j;\n int keys = queue.peek().keys;\n queue.poll();\n \n if( keys == keyMask )\n return steps;\n \n for(int[] dir : DIRS) {\n int di = i + dir[0];\n int dj = j + dir[1];\n int newKeys = keys;\n\n if( di < 0 || dj < 0 || di == m || dj == n )\n continue;\n\n char c = grid[di].charAt(dj);\n\n if( isWall(c) ) continue;\n \n if( isLock(c) && !isKeyPresent(keys, c) )\n continue;\n\n if( isKey(c) ) \n newKeys |= (1 << (c - 'a'));\n \n State newState = new State(di, dj, newKeys);\n \n if( visited.add(newState) ) \n queue.offer(newState);\n }\n }\n steps++;\n }\n return -1;\n }\n \n private boolean isLock(char c) {\n return c >= 'A' && c <= 'Z';\n }\n private boolean isKey(char c) {\n return c >= 'a' && c <= 'z';\n }\n private boolean isWall(char c) {\n return c == '#';\n }\n private boolean isStart(char c) {\n return c == '@';\n }\n private boolean isKeyPresent(int keys, char lock) {\n return (keys & (1 << (lock-'A'))) != 0;\n }\n}\nclass State {\n public int i, j, keys;\n \n public State(int i, int j, int keys) {\n this.i = i;\n this.j = j;\n this.keys = keys;\n }\n \n @Override\n public boolean equals(Object obj) {\n if( !(obj instanceof State) ) return false;\n State that = (State)obj;\n return i == that.i && j == that.j && keys == that.keys;\n }\n \n @Override\n public int hashCode() {\n int prime = 31;\n int hash = 1;\n hash = hash * prime + i;\n hash = hash * prime + j;\n hash = hash * prime + keys;\n return hash;\n }\n}\n", + "title": "864. Shortest Path to Get All Keys", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n grid grid where: You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6 , there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys . If it is impossible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "'.' is an empty cell.", + "'#' is a wall.", + "'@' is the starting point.", + "Lowercase letters represent keys.", + "Uppercase letters represent locks." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\"@.a..\",\"###.#\",\"b.A.B\"]Output:8Explanation:Note that the goal is to obtain all the keys not to open all the locks.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg" + }, + { + "text": "Example 2: Input:grid = [\"@..aA\",\"..B#.\",\"....b\"]Output:6", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg" + }, + { + "text": "Example 3: Input:grid = [\"@Aa\"]Output:-1", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n \n m=len(grid)\n n=len(grid[0])\n visited=set()\n \n steps=0\n q=deque([])\n keyCt=0\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"@\":\n q.append((i,j,''))\n elif grid[i][j].islower():\n keyCt+=1\n \n while q:\n for _ in range(len(q)):\n curr_x,curr_y,keys = q.popleft()\n if (curr_x,curr_y,keys) in visited:\n continue\n \n visited.add((curr_x,curr_y,keys))\n \n if len(keys)==keyCt:\n return steps\n \n for x,y in ((0,1),(1,0),(-1,0),(0,-1)):\n nx=curr_x+x\n ny=curr_y+y\n if nx<0 or ny<0 or nx>=m or ny>=n or grid[nx][ny]=='#' or (nx,ny,keys) in visited:\n continue\n \n curr=grid[nx][ny] \n if curr in 'abcdef' and curr not in keys:\n q.append((nx,ny,keys+curr)) \n elif curr.isupper() and curr.lower() not in keys:\n continue\n else:\n q.append((nx,ny,keys))\n steps+=1\n \n return -1", + "title": "864. Shortest Path to Get All Keys", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1 . You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node . You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == graph.length", + "1 <= n <= 12", + "0 <= graph[i].length < n", + "graph[i] does not contain i .", + "If graph[a] contains b , then graph[b] contains a .", + "The input graph is always connected." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2,3],[0],[0],[0]]Output:4Explanation:One possible path is [1,0,2,0,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg" + }, + { + "text": "Example 2: Input:graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]Output:4Explanation:One possible path is [0,1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 17 ms (Top 78.04%) | Memory: 46.7 MB (Top 69.44%)\nclass Solution {\n class Pair {\n int i;\n int path;\n public Pair(int i, int path) {\n this.i = i;\n this.path = path;\n }\n }\n public int shortestPathLength(int[][] graph) {\n /*\n For each node currentNode, steps as key, visited as value\n boolean[currentNode][steps]\n */\n int n = graph.length;\n\n // 111....1, 1<< n - 1\n int allVisited = (1 << n) - 1;\n\n boolean[][] visited = new boolean[n][1 << n];\n Queue q = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (1 << i == allVisited) return 0;\n visited[i][1 << i] = true;\n q.offer(new Pair(i, 1 << i));\n }\n int step = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n Pair p = q.poll();\n int[] edges = graph[p.i];\n\n for(int t: edges) {\n int path = p.path | (1 << t);\n if (path == allVisited) return step + 1;\n if (!visited[t][path]) {\n visited[t][path] = true;\n q.offer(new Pair(t, path));\n }\n }\n }\n step++;\n }\n return step;\n }\n}", + "title": "847. Shortest Path Visiting All Nodes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1 . You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node . You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == graph.length", + "1 <= n <= 12", + "0 <= graph[i].length < n", + "graph[i] does not contain i .", + "If graph[a] contains b , then graph[b] contains a .", + "The input graph is always connected." + ], + "examples": [ + { + "text": "Example 1: Input:graph = [[1,2,3],[0],[0],[0]]Output:4Explanation:One possible path is [1,0,2,0,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg" + }, + { + "text": "Example 2: Input:graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]Output:4Explanation:One possible path is [0,1,4,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n = len(graph)\n dist = [[inf]*n for _ in range(n)]\n \n for i, x in enumerate(graph): \n dist[i][i] = 0\n for ii in x: dist[i][ii] = 1\n \n # floyd-warshall \n for k in range(n): \n for i in range(n): \n for j in range(n): \n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n \n @cache \n def fn(x, mask): \n if mask == 0: return 0 \n ans = inf \n for i in range(n): \n if mask & (1 << i): \n ans = min(ans, dist[x][i] + fn(i, mask ^ (1< graph with red edges\n // g2-> graph with blue edges\n List g1[], g2[];\n int[] dist1, dist2, ans;\n int MX = (int) 2e9;\n\n public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {\n dist1 = new int[n];\n dist2 = new int[n];\n g1=new ArrayList[n];\n g2=new ArrayList[n];\n ans=new int[n];\n for (int i=0;i();\n g2[i]=new ArrayList<>();\n dist1[i]=MX;\n dist2[i]=MX;\n ans[i]=MX;\n }\n for (int i=0;idist2[u]+1){\n dist1[v]=dist2[u]+1;\n dfs(v,!flag);\n }\n }\n } else {\n for (int v: g2[u]) {\n if (dist2[v]>dist1[u]+1){\n dist2[v]=dist1[u]+1;\n dfs(v,!flag);\n }\n }\n }\n }\n}", + "title": "1129. Shortest Path with Alternating Colors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer n , the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1 . Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: Return an array answer of length n , where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "redEdges[i] = [a i , b i ] indicates that there is a directed red edge from node a i to node b i in the graph, and", + "blueEdges[j] = [u j , v j ] indicates that there is a directed blue edge from node u j to node v j in the graph." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, redEdges = [[0,1],[1,2]], blueEdges = []Output:[0,1,-1]", + "image": null + }, + { + "text": "Example 2: Input:n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]Output:[0,1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n g = [[[] for _ in range(2)] for _ in range(n)]\n \n for i,j in redEdges:\n g[i][0] += [j]\n for i,j in blueEdges:\n g[i][1] += [j]\n distance = [float(\"inf\") for _ in range(n)]\n distance[0] = 0\n q = queue.Queue()\n q.put((0,0,False))\n q.put((0,0,True))\n \n redS = set([0])\n blueS = set([0])\n while not q.empty():\n node,dist,red = q.get()\n if red:\n neighbours = g[node][0]\n redS.add(node)\n curr = blueS\n else:\n neighbours = g[node][1]\n blueS.add(node)\n curr = redS\n for neighbour in neighbours:\n if dist + 1 < distance[neighbour]:\n distance[neighbour] = dist + 1\n q.put((neighbour,dist + 1,not red))\n if not (neighbour in curr):\n q.put((neighbour,dist + 1,not red))\n for i in range(n):\n if distance[i] == float(\"inf\"):\n distance[i] = -1\n return distance\n \n", + "title": "1129. Shortest Path with Alternating Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr , remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing . Return the length of the shortest subarray to remove . A subarray is a contiguous subsequence of the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "0 <= arr[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,10,4,2,3,5]Output:3Explanation:The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,4,3,2,1]Output:4Explanation:Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3]Output:0Explanation:The array is already non-decreasing. We do not need to remove any elements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findLengthOfShortestSubarray(int[] arr) {\n int firstLast=0,lastFirst=arr.length-1;\n for(;firstLastarr[firstLast+1]) break;\n }\n\t\t//Base case for a non-decreasing sequence\n if(firstLast==arr.length-1) return 0;\n for( ;lastFirst>0;lastFirst--){\n if(arr[lastFirst]=0;firstLast--){\n for(int i=lastFirst;iarr[i]) continue;\n minLength = Math.min(minLength,i-firstLast-1);\n break;\n }\n }\n return minLength;\n }\n}\n", + "title": "1574. Shortest Subarray to be Removed to Make Array Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array arr , remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing . Return the length of the shortest subarray to remove . A subarray is a contiguous subsequence of the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^5", + "0 <= arr[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,10,4,2,3,5]Output:3Explanation:The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].", + "image": null + }, + { + "text": "Example 2: Input:arr = [5,4,3,2,1]Output:4Explanation:Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,2,3]Output:0Explanation:The array is already non-decreasing. We do not need to remove any elements.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n n = len(arr)\n i = 0\n while i < n-1 and arr[i+1] >= arr[i]:\n i += 1\n \n if i == n-1:\n return 0\n \n j = n-1\n while j >= 0 and arr[j-1] <= arr[j]:\n j -= 1\n \n ans = min(n, n-i-1, j)\n \n for l in range(i+1):\n r = j\n while r < n and arr[r] < arr[l]:\n r += 1\n ans = min(ans, r-l-1)\n \n return ans", + "title": "1574. Shortest Subarray to be Removed to Make Array Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return the length of the shortest non-empty subarray of nums with a sum of at least k . If there is no such subarray , return -1 . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 1Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], k = 4Output:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,2], k = 3Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int shortestSubarray(int[] nums, int k) {\n \n TreeMap maps = new TreeMap<>();\n long sum = 0l;\n int min = nums.length + 1;\n\t\t \n maps.put(0l, -1);\n \n for(int i = 0; i < nums.length; i++) {\n sum += nums[i];ntry(sum - k) != null) \n\t\t\t min = Math.min(min, i - maps.floorEntry(sum - k).getValue()); \n while(!maps.isEmpty() && maps.lastEntry().getKey() >= sum) \n\t\t\t maps.remove(maps.lastEntry().getKey());\n \n maps.put(sum, i);\n }\n \n return min == (nums.length + 1) ? -1 : min;\n }\n}\n", + "title": "862. Shortest Subarray with Sum at Least K", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums and an integer k , return the length of the shortest non-empty subarray of nums with a sum of at least k . If there is no such subarray , return -1 . A subarray is a contiguous part of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^5 <= nums[i] <= 10^5", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 1Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2], k = 4Output:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,-1,2], k = 3Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "# 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative, \n# the numbers in sliding window are not always incrementing\n# ex [8,-4,3,1,6], 10\n\n# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.\n# 3. monotonic queue is used to keep the prefix sums are in the incrementing order\n# 4. If the diffenence between the cur and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n prefixsum = [0]\n monoq = deque()\n minLen = float('inf')\n # to calculate prefix sum\n for n in nums:\n prefixsum.append(n+prefixsum[-1])\n for idx, cur in enumerate(prefixsum):\n while monoq and prefixsum[monoq[-1]] >= cur: monoq.pop() # to maintain monotonic queue\n\n # If the diffenence between the head and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n while monoq and cur-prefixsum[monoq[0]]>=k: \n minLen = min(minLen, idx-monoq.popleft())\n monoq.append(idx)\n return -1 if minLen == float('inf') else minLen\n", + "title": "862. Shortest Subarray with Sum at Least K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,6,4,8,10,9,15]Output:5Explanation:You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4]Output:0", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 47.11%) | Memory: 43.4 MB (Top 88.72%)\nclass Solution {\n public int findUnsortedSubarray(int[] nums) {\n int[] numsClone = nums.clone();\n Arrays.sort(nums);\n\n int s = Integer.MAX_VALUE;\n int e = Integer.MIN_VALUE;\n\n for(int i = 0; i int:\n stack = []\n min_index = len(nums)\n max_index = 0\n max_pop = float('-inf')\n for i in range(len(nums)):\n while stack and nums[i] < stack[-1][0]:\n\n p = stack.pop()\n if p[0] > max_pop:\n max_pop = p[0]\n if p[1] < min_index:\n min_index = p[1]\n if p[1] > max_index:\n max_index = p[1]\n stack.append([nums[i], i])\n max_r = max_index\n for st in stack:\n if st[0] < max_pop:\n max_r = st[1]\n if min_index == len(nums):\n return 0\n return max_r - min_index +1\n", + "title": "581. Shortest Unsorted Continuous Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Example 1:", + "description_images": [], + "constraints": [ + "Solution(int[] nums) Initializes the object with the integer array nums .", + "int[] reset() Resets the array to its original configuration and returns it.", + "int[] shuffle() Returns a random shuffling of the array." + ], + "examples": [ + { + "text": "Example 1: Input[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n[[[1, 2, 3]], [], [], []]Output[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]ExplanationSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle(); // Shuffle the array [1,2,3] and return its result.\n // Any permutation of [1,2,3] must be equally likely to be returned.\n // Example: return [3, 1, 2]\nsolution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 125 ms (Top 16.02%) | Memory: 64.6 MB (Top 78.83%)\nclass Solution {\n\n int a[];\n int b[];\n public Solution(int[] nums) {\n a=nums.clone();\n b=nums.clone();\n }\n\n public int[] reset() {\n a=b.clone();\n return a;\n }\n\n public int[] shuffle() {\n\n for(int i=0;i List[int]: \n return self.nums\n\n def shuffle(self) -> List[int]:\n shuffled_array = self.nums.copy()\n # randomly generates the idx of the element that'll be the ith element of the array \n for i in range(len(self.nums) - 1, 0, -1):\n idx = random.randint(0, i)\n shuffled_array[i], shuffled_array[idx] = shuffled_array[idx], shuffled_array[i]\n return shuffled_array", + "title": "384. Shuffle an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s and an integer array indices of the same length . The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string. Return the shuffled string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s.length == indices.length == n", + "1 <= n <= 100", + "s consists of only lowercase English letters.", + "0 <= indices[i] < n", + "All values of indices are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"codeleet\",indices= [4,5,6,7,0,2,1,3]Output:\"leetcode\"Explanation:As shown, \"codeleet\" becomes \"leetcode\" after shuffling.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/q1.jpg" + }, + { + "text": "Example 2: Input:s = \"abc\",indices= [0,1,2]Output:\"abc\"Explanation:After shuffling, each character remains in its position.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.6 MB (Top 92.75%)\nclass Solution {\n public String restoreString(String s, int[] indices) {\n char[] ch = new char[s.length()];\n for(int i = 0 ; i< s.length() ; i ++){\n ch[indices[i]]=s.charAt(i);\n }\n return new String (ch);\n }\n}", + "title": "1528. Shuffle String", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a string s and an integer array indices of the same length . The string s will be shuffled such that the character at the i th position moves to indices[i] in the shuffled string. Return the shuffled string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s.length == indices.length == n", + "1 <= n <= 100", + "s consists of only lowercase English letters.", + "0 <= indices[i] < n", + "All values of indices are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"codeleet\",indices= [4,5,6,7,0,2,1,3]Output:\"leetcode\"Explanation:As shown, \"codeleet\" becomes \"leetcode\" after shuffling.", + "image": "https://assets.leetcode.com/uploads/2020/07/09/q1.jpg" + }, + { + "text": "Example 2: Input:s = \"abc\",indices= [0,1,2]Output:\"abc\"Explanation:After shuffling, each character remains in its position.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 81 ms (Top 68.03%) | Memory: 13.9 MB (Top 63.45%)\nclass Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n dec = {}\n c = 0\n res=''\n for i in indices:\n dec[i] = s[c]\n c += 1\n # dec = {\"4\":\"c\",\"5\":\"o\",\"6\":\"d\",\"7\":\"e\",\"0\":\"l\",\"2\":\"e\",\"1\":\"e\",\"3\":\"t\"}\n for x in range(len(indices)):\n res += dec[x]\n # x in range 0, 1, 2,....... len *indices or s*\n return res", + "title": "1528. Shuffle String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the array nums consisting of 2n elements in the form [x 1 ,x 2 ,...,x n ,y 1 ,y 2 ,...,y n ] . Return the array in the form [x 1 ,y 1 ,x 2 ,y 2 ,...,x n ,y n ] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "nums.length == 2n", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,1,3,4,7], n = 3Output:[2,3,5,4,1,7]Explanation:Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,4,3,2,1], n = 4Output:[1,4,2,3,3,2,4,1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], n = 2Output:[1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 65.71%) | Memory: 45.8 MB (Top 46.61%)\nclass Solution {\n public int[] shuffle(int[] nums, int n)\n {\n int[] arr = new int[2*n];\n int j = 0;\n int k = n;\n for(int i =0; i<2*n; i++)\n {\n if(i%2==0)\n {\n arr[i] = nums[j];\n j++;\n }\n else\n {\n arr[i] = nums[k];\n k++;\n }\n }\n return arr;\n }\n}", + "title": "1470. Shuffle the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the array nums consisting of 2n elements in the form [x 1 ,x 2 ,...,x n ,y 1 ,y 2 ,...,y n ] . Return the array in the form [x 1 ,y 1 ,x 2 ,y 2 ,...,x n ,y n ] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 500", + "nums.length == 2n", + "1 <= nums[i] <= 10^3" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,1,3,4,7], n = 3Output:[2,3,5,4,1,7]Explanation:Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,4,3,2,1], n = 4Output:[1,4,2,3,3,2,4,1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,2,2], n = 2Output:[1,2,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "'''\nFirst of all, I'm making a few tuples using zip function.\nThen extracting every created tuple. (for tup in zip())\nAfter that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup)\n'''\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n return [number for tup in zip(nums[:n], nums[n:]) for number in tup]\n", + "title": "1470. Shuffle the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a function signFunc(x) that returns: You are given an integer array nums . Let product be the product of all values in the array nums . Return signFunc(product) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 if x is positive.", + "-1 if x is negative.", + "0 if x is equal to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,-2,-3,-4,3,2,1]Output:1Explanation:The product of all values in the array is 144, and signFunc(144) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,0,2,-3]Output:0Explanation:The product of all values in the array is 0, and signFunc(0) = 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-1,1,-1]Output:-1Explanation:The product of all values in the array is -1, and signFunc(-1) = -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int arraySign(int[] nums) {\n int prod=1;\n for(int i=0;i0) return 1;\n return 0;\n }\n}\n", + "title": "1822. Sign of the Product of an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a function signFunc(x) that returns: You are given an integer array nums . Let product be the product of all values in the array nums . Return signFunc(product) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 if x is positive.", + "-1 if x is negative.", + "0 if x is equal to 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,-2,-3,-4,3,2,1]Output:1Explanation:The product of all values in the array is 144, and signFunc(144) = 1", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,0,2,-3]Output:0Explanation:The product of all values in the array is 0, and signFunc(0) = 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-1,1,-1]Output:-1Explanation:The product of all values in the array is -1, and signFunc(-1) = -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def arraySign(self, nums: List[int]) -> int:\n\t\treturn 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1\n", + "title": "1822. Sign of the Product of an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Two strings X and Y are similar if we can swap two letters (in different positions) of X , so that it equals Y . Also two strings X and Y are similar if they are equal. For example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2 ), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\" , \"rats\" , or \"arts\" . Together, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"} .  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs . How many groups are there? Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 300", + "1 <= strs[i].length <= 300", + "strs[i] consists of lowercase letters only.", + "All words in strs have the same length and are anagrams of each other." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"tars\",\"rats\",\"arts\",\"star\"]Output:2", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"omv\",\"ovm\"]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSimilarGroups(String[] strs) {\n boolean[] visited = new boolean[strs.length]; // record the word that we checked\n int res = 0;\n for (int i = 0; i < strs.length; i++) {\n if (!visited[i]) {\n res++;\n dfs(strs, visited, i);\n }\n }\n return res;\n }\n \n void dfs(String[] strs, boolean[] visited, int index) { // explore all similar words we can explore\n visited[index] = true;\n String curr = strs[index];\n for (int i = 0; i < strs.length; i++) {\n if (!visited[i] && isSimilar(curr, strs[i])) {\n dfs(strs, visited, i);\n } \n }\n }\n \n boolean isSimilar(String a, String b) {\n int diff = 0;\n for (int i = 0; i < a.length(); i++) {\n if (a.charAt(i) != b.charAt(i)) {\n diff++;\n if (diff > 2) return false;\n }\n }\n return true;\n }\n}\n", + "title": "839. Similar String Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Two strings X and Y are similar if we can swap two letters (in different positions) of X , so that it equals Y . Also two strings X and Y are similar if they are equal. For example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2 ), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\" , \"rats\" , or \"arts\" . Together, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"} .  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs . How many groups are there? Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 300", + "1 <= strs[i].length <= 300", + "strs[i] consists of lowercase letters only.", + "All words in strs have the same length and are anagrams of each other." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"tars\",\"rats\",\"arts\",\"star\"]Output:2", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"omv\",\"ovm\"]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 5068 ms (Top 15.23%) | Memory: 14.3 MB (Top 64.62%)\nclass Solution: #839. Similar String Groups\n def numSimilarGroups(self, strs: List[str]) -> int:\n #memo\n visited = set()\n count = 0\n for i in range(len(strs)):\n if i not in visited:\n #dfs\n self.dfs(strs, i, visited)\n #add a new connected area\n count += 1\n return count\n\n #dfs to search the similar string from 0 to n-1\n def dfs(self, strs, i, visited):\n #add current string to memo\n visited.add(i)\n for j in range(len(strs)):\n if self.isSimilar(strs[i], strs[j]) and j not in visited:\n self.dfs(strs, j , visited)\n\n # calculate the similarity of two strings\n def isSimilar(self, str1, str2):\n diff_count = 0\n for i in range(len(str1)):\n if str1[i] != str2[i]:\n diff_count += 1\n return diff_count <= 2", + "title": "839. Similar String Groups", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n . The initial balance of each account is stored in a 0-indexed integer array balance , with the (i + 1) th account having an initial balance of balance[i] . Execute all the valid transactions. A transaction is valid if: Implement the Bank class: Example 1:", + "description_images": [], + "constraints": [ + "The given account number(s) are between 1 and n , and", + "The amount of money withdrawn or transferred from is less than or equal to the balance of the account." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]Output[null, true, true, true, false, false]ExplanationBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 265 ms (Top 12.10%) | Memory: 117.3 MB (Top 39.86%)\nclass Bank {\n\n int N;\n long[] balance;\n public Bank(long[] balance) {\n this.N = balance.length;\n this.balance = balance;\n }\n\n public boolean transfer(int account1, int account2, long money) {\n if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < money)\n return false;\n balance[account1 - 1] -= money;\n balance[account2 - 1] += money;\n return true;\n }\n\n public boolean deposit(int account, long money) {\n if(account < 1 || account > N)\n return false;\n balance[account - 1] += money;\n return true;\n }\n\n public boolean withdraw(int account, long money) {\n if(account < 1 || account > N || balance[account - 1] < money)\n return false;\n balance[account - 1] -= money;\n return true;\n }\n}", + "title": "2043. Simple Bank System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n . The initial balance of each account is stored in a 0-indexed integer array balance , with the (i + 1) th account having an initial balance of balance[i] . Execute all the valid transactions. A transaction is valid if: Implement the Bank class: Example 1:", + "description_images": [], + "constraints": [ + "The given account number(s) are between 1 and n , and", + "The amount of money withdrawn or transferred from is less than or equal to the balance of the account." + ], + "examples": [ + { + "text": "Example 1: Input[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]Output[null, true, true, true, false, false]ExplanationBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1834 ms (Top 5.30%) | Memory: 43.9 MB (Top 45.70%)\nclass Bank:\n\n def __init__(self, bal: List[int]):\n self.store = bal # storage list\n\n def transfer(self, a1: int, a2: int, money: int) -> bool:\n try:\n # checking if both accounts exist. and if the transaction would be valid\n if self.store[a1 - 1] >= money and self.store[a2 - 1] >= 0:\n # performing the transaction\n self.store[a1 - 1] -= money\n self.store[a2 - 1] += money\n return True\n else:\n # retrning false on invalid transaction\n return False\n except:\n # returning false when accounts don't exist\n return False\n\n def deposit(self, ac: int, mn: int) -> bool:\n try:\n # if account exists performing transaction\n self.store[ac - 1] += mn\n return True\n except:\n # returning false when account doesn't exist\n return False\n\n def withdraw(self, ac: int, mn: int) -> bool:\n try:\n # checking if transaction is valid\n if self.store[ac - 1] >= mn:\n # performing the transaction\n self.store[ac - 1] -= mn\n return True\n else:\n # returning false in case on invalid transaction\n return False\n except:\n # returning false when account doesn't exist\n return False", + "title": "2043. Simple Bank System", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[\"1/2\"]Explanation:\"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:[\"1/2\",\"1/3\",\"2/3\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:[\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]Explanation:\"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 42 ms (Top 52.04%) | Memory: 73.5 MB (Top 36.20%)\nclass Solution {\n public List simplifiedFractions(int n) {\n List list = new ArrayList<>() ;\n\n for(int numerator = 1; numerator< n ; numerator++) {\n for(int denominator = numerator+1; denominator<=n; denominator++) {\n if(gcd(numerator,denominator) == 1) {\n list.add(numerator+\"/\"+denominator);\n// System.out.println(numerator+\"/\"+denominator);\n }\n }\n }\n return list ;\n }\n\n static int gcd(int a, int b)\n {\n// euclidean algo\n\n if(a==0) {\n return b ;\n }\n return gcd(b%a,a);\n }\n}", + "title": "1447. Simplified Fractions", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[\"1/2\"]Explanation:\"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:[\"1/2\",\"1/3\",\"2/3\"]", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:[\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]Explanation:\"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n \n collect = {}\n for b in range(2, n+1):\n for a in range(1, b):\n if a/b not in collect:\n collect[a/b] = f\"{a}/{b}\" \n return list(collect.values())\n", + "title": "1447. Simplified Fractions", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string path , which is an absolute path (starting with a slash '/' ) to a file or directory in a Unix-style file system, convert it to the simplified canonical path . In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//' ) are treated as a single slash '/' . For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The path starts with a single slash '/' .", + "Any two directories are separated by a single slash '/' .", + "The path does not end with a trailing '/' .", + "The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..' )" + ], + "examples": [ + { + "text": "Example 1: Input:path = \"/home/\"Output:\"/home\"Explanation:Note that there is no trailing slash after the last directory name.", + "image": null + }, + { + "text": "Example 2: Input:path = \"/../\"Output:\"/\"Explanation:Going one level up from the root directory is a no-op, as the root level is the highest level you can go.", + "image": null + }, + { + "text": "Example 3: Input:path = \"/home//foo/\"Output:\"/home/foo\"Explanation:In the canonical path, multiple consecutive slashes are replaced by a single one.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 86.82%) | Memory: 43.20 MB (Top 75.26%)\n\nclass Solution {\n public String simplifyPath(String path) {\n Deque dirOrFiles = new ArrayDeque<>();\n for (String dirOrFile : path.split(\"/\")) {\n if (!dirOrFiles.isEmpty() && dirOrFile.equals(\"..\")) {\n dirOrFiles.removeLast();\n } else if (!dirOrFile.equals(\".\") && !dirOrFile.equals(\"\") && !dirOrFile.equals(\"..\")) {\n dirOrFiles.addLast(dirOrFile);\n }\n }\n StringBuilder simplified_path = new StringBuilder();\n for (String dirOrFile : dirOrFiles) {\n simplified_path.append(\"/\").append(dirOrFile);\n }\n return simplified_path.length() == 0 ? \"/\" : simplified_path.toString();\n }\n}\n", + "title": "71. Simplify Path", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string path , which is an absolute path (starting with a slash '/' ) to a file or directory in a Unix-style file system, convert it to the simplified canonical path . In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//' ) are treated as a single slash '/' . For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The path starts with a single slash '/' .", + "Any two directories are separated by a single slash '/' .", + "The path does not end with a trailing '/' .", + "The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..' )" + ], + "examples": [ + { + "text": "Example 1: Input:path = \"/home/\"Output:\"/home\"Explanation:Note that there is no trailing slash after the last directory name.", + "image": null + }, + { + "text": "Example 2: Input:path = \"/../\"Output:\"/\"Explanation:Going one level up from the root directory is a no-op, as the root level is the highest level you can go.", + "image": null + }, + { + "text": "Example 3: Input:path = \"/home//foo/\"Output:\"/home/foo\"Explanation:In the canonical path, multiple consecutive slashes are replaced by a single one.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def simplifyPath(self, path: str) -> str:\n \tstack = []\n \t\n \ti = 0\n while i < len(path):\n if path[i] == '/':\n i += 1\n continue\n\n else:\n cur = ''\n while i < len(path) and path[i] != '/':\n cur += path[i]\n i += 1\n\n if cur == '..':\n if stack:\n stack.pop()\n elif cur == '.' or cur == '':\n i += 1\n continue\n else:\n stack.append(cur)\n\n return '/' + '/'.join(stack)\n", + "title": "71. Simplify Path", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once . Your solution must run in O(log n) time and O(1) space. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,3,3,4,4,8,8]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,3,7,7,10,11,11]Output:10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 49.90 MB (Top 64.7%)\n\nclass Solution {\n public int singleNonDuplicate(int[] nums) {\n if(nums.length==1) return nums[0];\n int l = 0;\n int h = nums.length-1;\n \n while(l int:\n return self.b_search(nums)[0]\n \n def b_search(self, nums):\n if len(nums) == 1:\n return nums\n mid = len(nums)//2\n a = nums[:mid]\n b = nums[mid:]\n\t\t\n\t\t# check if last & first element of the two sub lists are same\n if a[-1] == b[0]:\n a = a[:-1]\n b = b[1:]\n\t\t\n\t\t# ignore the sub list with even number of elements\n if len(a)%2:\n return self.b_search(a)\n else:\n return self.b_search(b)\n", + "title": "540. Single Element in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1]Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,2,1,2]Output:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 13 ms (Top 30.48%) | Memory: 52.1 MB (Top 26.29%)\nclass Solution {\n public int singleNumber(int[] nums) {\n Stack numStack = new Stack();\n Arrays.sort(nums);\n for (var i = 0; i < nums.length; ++i) {\n numStack.push(nums[i]);\n if (i < nums.length - 1 && nums[++i] != (int) numStack.peek()) break;\n }\n return (int) numStack.pop();\n }\n}", + "title": "136. Single Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,1]Output:1", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,1,2,1,2]Output:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 301 ms (Top 20.49%) | Memory: 16.1 MB (Top 98.97%)\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n nums.sort()\n i=0\n while i List[int]:\n x = Counter(nums)\n return([y for y in x if x[y] == 1])\n", + "title": "260. Single Number III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given n ​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks , where tasks[i] = [enqueueTime i , processingTime i ] means that the i ​​​​​​th ​​​​ task will be available to process at enqueueTime i and will take processingTime i to finish processing. You have a single-threaded CPU that can process at most one task at a time and will act in the following way: Return the order in which the CPU will process the tasks. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If the CPU is idle and there are no available tasks to process, the CPU remains idle.", + "If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time . If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.", + "Once a task is started, the CPU will process the entire task without stopping.", + "The CPU can finish a task then start a new one instantly." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [[1,2],[2,4],[3,2],[4,1]]Output:[0,2,3,1]Explanation:The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]Output:[4,3,2,0,1]Explanation:The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getOrder(self, tasks: List[List[int]]) -> List[int]:\n # For better readability\n Task = namedtuple('Task', ['etime', 'ptime', 'index'])\n \n # Sort the tasks by enqueue time, shortest processing time and index\n stasks = sorted([Task(task[0], task[1], i) for i, task in enumerate(tasks)])\n # t: current CPU clock; i: current task index\n t = i = 0\n heap, result = [], []\n \n while len(result) < len(stasks):\n # Push all the tasks available at current CPU clock\n while i < len(stasks) and stasks[i].etime <= t:\n heappush(heap, (stasks[i].ptime, stasks[i].index))\n i += 1\n if heap:\n ptime, index = heappop(heap)\n result.append(index)\n t += ptime\n else:\n # Jump to the next available task\n t = stasks[i].etime\n return result\n", + "title": "1834. Single-Threaded CPU", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "On an 2 x 3 board, there are five tiles labeled from 1 to 5 , and an empty square represented by 0 . A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]] . Given the puzzle board board , return the least number of moves required so that the state of the board is solved . If it is impossible for the state of the board to be solved, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "board.length == 2", + "board[i].length == 3", + "0 <= board[i][j] <= 5", + "Each value board[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[1,2,3],[4,0,5]]Output:1Explanation:Swap the 0 and the 5 in one move.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[1,2,3],[5,4,0]]Output:-1Explanation:No number of moves will make the board solved.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[4,1,2],[5,0,3]]Output:5Explanation:5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]", + "image": "https://assets.leetcode.com/uploads/2021/06/29/slide3-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 35.42%) | Memory: 44.4 MB (Top 46.82%)\nclass Solution {\n int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}};\n public int slidingPuzzle(int[][] board) {\n\n String tar=\"123450\";\n\n String src=\"\";\n\n for(int i =0;i visited=new HashSet<>();\n\n visited.add(src);\n int level=0;\n ArrayDeque q=new ArrayDeque<>();\n q.add(src);\n while(q.size()!=0){\n int t=q.size();\n\n while(t-->0){\n String rem=q.remove();\n\n if(rem.equals(tar)){\n return level;\n }\n\n int idx=-1;\n\n for(int i=0;i int:\n def findNei(board):\n directs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n boards = []\n for i in range(2):\n for j in range(3):\n if board[i][j] == 0:\n for dr, dc in directs:\n tmp = [row.copy() for row in board]\n r, c = i + dr, j + dc\n if r in range(2) and c in range(3):\n tmp[r][c], tmp[i][j] = tmp[i][j], tmp[r][c]\n boards.append(tmp)\n return boards\n\n visited = set()\n target = [[1, 2, 3], [4, 5, 0]]\n if board == target:\n return 0\n rows, cols = len(board), len(board[0])\n q = collections.deque()\n step = 1\n\n for row in range(rows):\n for col in range(cols):\n if board[row][col] == 0:\n boards = findNei(board)\n for b in boards:\n if b == target:\n return step\n visited.add(tuple([tuple(row) for row in b]))\n q.append(b)\n break\n\n while q:\n step += 1\n for _ in range(len(q)):\n b = q.popleft()\n boards = findNei(b)\n for b in boards:\n if b == target:\n return step\n t = tuple([tuple(row) for row in b])\n if t not in visited:\n visited.add(t)\n q.append(b)\n\n return -1", + "title": "773. Sliding Puzzle", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3Output:[3,3,5,5,6,7]Explanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSlidingWindow(int[] nums, int k) {\n Deque queue = new LinkedList<>();\n int l = 0, r = 0;\n int[] res = new int[nums.length - k + 1];\n int index = 0;\n while (r < nums.length) {\n int n = nums[r++];\n while (!queue.isEmpty() && n > queue.peekLast()) {\n queue.pollLast();\n }\n queue.offer(n);\n while (r - l > k) {\n int m = nums[l++];\n if (m == queue.peekFirst()) {\n queue.pollFirst();\n }\n }\n if (r - l == k) {\n res[index++] = queue.peekFirst();\n }\n }\n return res;\n }\n}\n", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3Output:[3,3,5,5,6,7]Explanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4951 ms (Top 7.51%) | Memory: 39.4 MB (Top 5.02%)\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n ans = []\n pq = []\n\n for i in range(k): heapq.heappush(pq,(-nums[i],i))\n\n ans.append(-pq[0][0])\n\n for i in range(k,len(nums)):\n heapq.heappush(pq,(-nums[i],i))\n while pq and pq[0][1] < i-k+1 : heapq.heappop(pq)\n ans.append(-pq[0][0])\n\n return ans", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k . 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 median array for each window in the original array . Answers within 10 -5 of the actual value will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For examples, if arr = [2, 3 ,4] , the median is 3 .", + "For examples, if arr = [1, 2,3 ,4] , the median is (2 + 3) / 2 = 2.5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3Output:[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]Explanation:Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,2,3,1,4,2], k = 3Output:[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 176 ms (Top 24.15%) | Memory: 56.2 MB (Top 31.72%)\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n Queue minHeap = new PriorityQueue<>();\n Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n double[] res = new double[nums.length - k + 1];\n for(int i = 0; i< nums.length; i++){\n if(i >= k){\n if(!minHeap.remove(nums[i-k]))\n maxHeap.remove(nums[i-k]);\n }\n\n // If k is odd, max heap is of odd size and min heap is of even\n // else both are of even size\n if(!maxHeap.isEmpty() && nums[i] <= maxHeap.peek()) {\n maxHeap.add(nums[i]);\n if(((k&1) == 1 && maxHeap.size() > k/2+1) || ((k&1) == 0 && maxHeap.size() > k/2)){\n minHeap.offer(maxHeap.poll());\n }\n }else{\n minHeap.add(nums[i]);\n if(minHeap.size() > k/2){\n maxHeap.offer(minHeap.poll());\n }\n }\n while(!minHeap.isEmpty() && !maxHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){\n int temp1 = maxHeap.poll();\n int temp2 = minHeap.poll();\n maxHeap.add(temp2);\n minHeap.add(temp1);\n }\n if(minHeap.size() + maxHeap.size() == k){\n if((k&1)==1){\n res[i-k+1] = maxHeap.peek();\n }else{\n res[i-k+1] = ((long)minHeap.peek()+ (long)maxHeap.peek())/2.0;\n }\n }\n }\n return res;\n }\n}", + "title": "480. Sliding Window Median", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. You are given an integer array nums and an integer k . 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 median array for each window in the original array . Answers within 10 -5 of the actual value will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For examples, if arr = [2, 3 ,4] , the median is 3 .", + "For examples, if arr = [1, 2,3 ,4] , the median is (2 + 3) / 2 = 2.5 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3Output:[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]Explanation:Window position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,2,3,1,4,2], k = 3Output:[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 447 ms (Top 43.48%) | Memory: 30.40 MB (Top 31.32%)\n\nimport heapq\nfrom collections import defaultdict\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n if not nums or not k:\n return []\n lo = [] # max heap\n hi = [] # min heap\n for i in range(k):\n if len(lo) == len(hi):\n heapq.heappush(hi, -heapq.heappushpop(lo, -nums[i]))\n else:\n heapq.heappush(lo, -heapq.heappushpop(hi, nums[i]))\n ans = [float(hi[0])] if k & 1 else [(hi[0] - lo[0]) / 2.0]\n to_remove = defaultdict(int)\n for i in range(k, len(nums)): # right bound of window\n heapq.heappush(lo, -heapq.heappushpop(hi, nums[i])) # always push to lo\n out_num = nums[i-k]\n if out_num > -lo[0]:\n heapq.heappush(hi, -heapq.heappop(lo))\n to_remove[out_num] += 1\n while lo and to_remove[-lo[0]]:\n to_remove[-lo[0]] -= 1\n heapq.heappop(lo)\n while to_remove[hi[0]]:\n to_remove[hi[0]] -= 1\n heapq.heappop(hi)\n if k % 2:\n ans.append(float(hi[0]))\n else:\n ans.append((hi[0] - lo[0]) / 2.0)\n return ans\n", + "title": "480. Sliding Window Median", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n , where keysPressed[i] was the i th key pressed in the testing sequence, and a sorted list releaseTimes , where releaseTimes[i] was the time the i th key was released. Both arrays are 0-indexed . The 0 th key was pressed at the time 0 , and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration . The i th keypress had a duration of releaseTimes[i] - releaseTimes[i - 1] , and the 0 th keypress had a duration of releaseTimes[0] . Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration . Return the key of the keypress that had the longest duration . If there are multiple such keypresses, return the lexicographically largest key of the keypresses. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "releaseTimes.length == n", + "keysPressed.length == n", + "2 <= n <= 1000", + "1 <= releaseTimes[i] <= 10^9", + "releaseTimes[i] < releaseTimes[i+1]", + "keysPressed contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"Output:\"c\"Explanation:The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.", + "image": null + }, + { + "text": "Example 2: Input:releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"Output:\"a\"Explanation:The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public char slowestKey(int[] releaseTimes, String keysPressed) {\n int max = releaseTimes[0];\n char ch = keysPressed.charAt(0);\n for(int i=1;i= max){\n if(diff>max)\n ch = keysPressed.charAt(i);\n else if(diff== max)\n ch = (char)Math.max((int) ch, (int) keysPressed.charAt(i));\n max = diff;\n } \n }\n return ch; \n } \n}\n", + "title": "1629. Slowest Key", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n , where keysPressed[i] was the i th key pressed in the testing sequence, and a sorted list releaseTimes , where releaseTimes[i] was the time the i th key was released. Both arrays are 0-indexed . The 0 th key was pressed at the time 0 , and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration . The i th keypress had a duration of releaseTimes[i] - releaseTimes[i - 1] , and the 0 th keypress had a duration of releaseTimes[0] . Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration . Return the key of the keypress that had the longest duration . If there are multiple such keypresses, return the lexicographically largest key of the keypresses. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "releaseTimes.length == n", + "keysPressed.length == n", + "2 <= n <= 1000", + "1 <= releaseTimes[i] <= 10^9", + "releaseTimes[i] < releaseTimes[i+1]", + "keysPressed contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"Output:\"c\"Explanation:The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.", + "image": null + }, + { + "text": "Example 2: Input:releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"Output:\"a\"Explanation:The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 111 ms (Top 25.49%) | Memory: 14.1 MB (Top 45.43%)\nclass Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n max_dur = releaseTimes[0]\n max_key = keysPressed[0]\n\n for i in range(1, len(releaseTimes)):\n if releaseTimes[i] - releaseTimes[i-1] > max_dur:\n max_dur = releaseTimes[i] - releaseTimes[i-1]\n max_key = keysPressed[i]\n elif releaseTimes[i] - releaseTimes[i-1] == max_dur and max_key < keysPressed[i]:\n max_key = keysPressed[i]\n\n return max_key", + "title": "1629. Slowest Key", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an integer n represented as a string, return the smallest good base of n . We call k >= 2 a good base of n , if all digits of n base k are 1 's. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n is an integer in the range [3, 10^18 ] .", + "n does not contain any leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:n = \"13\"Output:\"3\"Explanation:13 base 3 is 111.", + "image": null + }, + { + "text": "Example 2: Input:n = \"4681\"Output:\"8\"Explanation:4681 base 8 is 11111.", + "image": null + }, + { + "text": "Example 3: Input:n = \"1000000000000000000\"Output:\"999999999999999999\"Explanation:1000000000000000000 base 999999999999999999 is 11.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestGoodBase(self, n: str) -> str:\n import math\n n = int(n)\n max_m = math.floor(math.log(n, 2))\n ans = 0\n for m in range(max_m, 0, -1):\n k = int(n ** (1 / m))\n if (k ** (m + 1) - 1) // (k - 1) == n:\n return str(k)\n return str(n - 1)\n", + "title": "483. Smallest Good Base", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed integer array nums , return the smallest index i of nums such that i mod 10 == nums[i] , or -1 if such index does not exist . x mod y denotes the remainder when x is divided by y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2]Output:0Explanation:i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,2,1]Output:2Explanation:i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9,0]Output:-1Explanation:No index satisfies i mod 10 == nums[i].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 42.3 MB (Top 94.74%)\nclass Solution {\n public int smallestEqual(int[] nums) {\n int index = 0;\n for (int i = 0 ; i < nums.length; i++) {\n if (index == nums[i]) {\n return i;\n }\n if (++index== 10) {\n index = 0;\n }\n }\n return -1;\n }\n}", + "title": "2057. Smallest Index With Equal Value", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 0-indexed integer array nums , return the smallest index i of nums such that i mod 10 == nums[i] , or -1 if such index does not exist . x mod y denotes the remainder when x is divided by y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2]Output:0Explanation:i=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,3,2,1]Output:2Explanation:i=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9,0]Output:-1Explanation:No index satisfies i mod 10 == nums[i].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestEqual(self, nums: List[int]) -> int:\n for idx, n in enumerate(nums):\n if idx%10==n:\n return idx\n return -1 ", + "title": "2057. Smallest Index With Equal Value", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a positive integer k , you need to find the length of the smallest positive integer n such that n is divisible by k , and n only contains the digit 1 . Return the length of n . If there is no such n , return -1. Note: n may not fit in a 64-bit signed integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1Output:1Explanation:The smallest answer is n = 1, which has length 1.", + "image": null + }, + { + "text": "Example 2: Input:k = 2Output:-1Explanation:There is no such positive integer n divisible by 2.", + "image": null + }, + { + "text": "Example 3: Input:k = 3Output:3Explanation:The smallest answer is n = 111, which has length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int smallestRepunitDivByK(int k) {\n // if (k % 2 == 0 || k % 5 == 0) return -1; // this trick may save a little time\n boolean[] hit = new boolean[k];\n int n = 0, ans = 0;\n while (true) { // at most k times, because 0 <= remainder < k\n ++ ans;\n n = (n * 10 + 1) % k; // we only focus on whether to divide, so we only need to keep the remainder.\n if (n == 0) return ans; // can be divisible\n if (hit[n]) return -1; // the remainder of the division repeats, so it starts to loop that means it cannot be divisible.\n hit[n] = true;\n }\n }\n}\n", + "title": "1015. Smallest Integer Divisible by K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a positive integer k , you need to find the length of the smallest positive integer n such that n is divisible by k , and n only contains the digit 1 . Return the length of n . If there is no such n , return -1. Note: n may not fit in a 64-bit signed integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1Output:1Explanation:The smallest answer is n = 1, which has length 1.", + "image": null + }, + { + "text": "Example 2: Input:k = 2Output:-1Explanation:There is no such positive integer n divisible by 2.", + "image": null + }, + { + "text": "Example 3: Input:k = 3Output:3Explanation:The smallest answer is n = 111, which has length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n if k % 2 == 0: return -1\n n = 1\n leng = 1\n mapp = {}\n while True:\n rem = n % k\n if rem == 0: return leng\n if rem in mapp : return -1\n mapp[rem] = True\n n = n*10 + 1\n leng += 1\n \n", + "title": "1015. Smallest Integer Divisible by K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , an integer k , a letter letter , and an integer repetition . Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times . The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= repetition <= k <= s.length <= 5 * 10^4", + "s consists of lowercase English letters.", + "letter is a lowercase English letter, and appears in s at least repetition times." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet\", k = 3, letter = \"e\", repetition = 1Output:\"eet\"Explanation:There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- \"lee\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"eet\" (from \"leet\")\nThe lexicographically smallest subsequence among them is \"eet\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 4, letter = \"e\", repetition = 2Output:\"ecde\"Explanation:\"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.", + "image": "https://assets.leetcode.com/uploads/2021/09/13/smallest-k-length-subsequence.png" + }, + { + "text": "Example 3: Input:s = \"bb\", k = 2, letter = \"b\", repetition = 2Output:\"bb\"Explanation:\"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, r: int) -> str:\n n_letters = len([c for c in s if c == letter])\n stack = []\n \n for i, c in enumerate(s):\n while stack and stack[-1] > c and (len(s) - i + len(stack) > k) and (stack[-1] != letter or n_letters > r):\n d = stack.pop()\n if d == letter:\n r += 1\n \n if len(stack) < k:\n if c == letter:\n stack.append(c)\n r -= 1\n elif k - len(stack) > r:\n stack.append(c)\n \n if c == letter:\n n_letters -= 1\n \n return ''.join(stack)\n", + "title": "2030. Smallest K-Length Subsequence With Occurrences of a Letter", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s , an integer k , a letter letter , and an integer repetition . Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times . The test cases are generated so that the letter appears in s at least repetition times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= repetition <= k <= s.length <= 5 * 10^4", + "s consists of lowercase English letters.", + "letter is a lowercase English letter, and appears in s at least repetition times." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet\", k = 3, letter = \"e\", repetition = 1Output:\"eet\"Explanation:There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- \"lee\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"let\" (from \"leet\")\n- \"eet\" (from \"leet\")\nThe lexicographically smallest subsequence among them is \"eet\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 4, letter = \"e\", repetition = 2Output:\"ecde\"Explanation:\"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.", + "image": "https://assets.leetcode.com/uploads/2021/09/13/smallest-k-length-subsequence.png" + }, + { + "text": "Example 3: Input:s = \"bb\", k = 2, letter = \"b\", repetition = 2Output:\"bb\"Explanation:\"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n s = list(s)\n stack = []\n countAll = s.count(letter)\n count = 0\n for ind, i in enumerate(s):\n while stack and stack[-1] > i:\n if stack[-1] == letter and i != letter:\n if countAll+count-1 < repetition:\n break\n if len(stack)+len(s)-ind-1 < k:\n break\n if stack[-1] == letter:\n count-=1\n stack.pop()\n stack.append(i)\n if i == letter:\n count+=1\n countAll-=1\n temp = 0\n while len(stack)+temp > k:\n if stack[-1] == letter and count <= repetition:\n temp+=1\n if stack[-1] == letter:\n count-=1\n stack.pop()\n return \"\".join(stack)+temp*letter", + "title": "2030. Smallest K-Length Subsequence With Occurrences of a Letter", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1 . You are given a 0-indexed integer array parents , where parents[i] is the parent for node i . Since node 0 is the root , parents[0] == -1 . There are 10^5 genetic values, each represented by an integer in the inclusive range [1, 10^5 ] . You are given a 0-indexed integer array nums , where nums[i] is a distinct genetic value for node i . Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i . The subtree rooted at a node x contains node x and all of its descendant nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == parents.length == nums.length", + "2 <= n <= 10^5", + "0 <= parents[i] <= n - 1 for i != 0", + "parents[0] == -1", + "parents represents a valid tree.", + "1 <= nums[i] <= 10^5", + "Each nums[i] is distinct." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,0,2], nums = [1,2,3,4]Output:[5,1,1,1]Explanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]Output:[7,1,1,4,2,1]Explanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-2.png" + }, + { + "text": "Example 3: Input:parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]Output:[1,1,1,1,1,1,1]Explanation:The value 1 is missing from all the subtrees.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n int n = parents.length;\n int[] res = new int[n];\n for (int i = 0; i < n; i++) {\n res[i] = 1;\n }\n \n int oneIndex = -1;\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) {\n oneIndex = i;\n break;\n }\n }\n \n // 1 not found\n if (oneIndex == -1) {\n return res;\n }\n \n Map> graph = new HashMap<>();\n for (int i = 1; i < n; i++) {\n Set children = graph.getOrDefault(parents[i], new HashSet());\n children.add(i);\n graph.put(parents[i], children);\n }\n \n Set visited = new HashSet();\n \n int parentIter = oneIndex;\n int miss = 1;\n while (parentIter >= 0) {\n dfs(parentIter, graph, visited, nums);\n while (visited.contains(miss)) {\n miss++;\n }\n res[parentIter] = miss;\n parentIter = parents[parentIter];\n }\n return res;\n }\n \n public void dfs(int ind, Map> graph, Set visited, int []nums) {\n if (!visited.contains(nums[ind])) {\n Set children = graph.getOrDefault(ind, new HashSet());\n \n for (int p : children) {\n dfs(p, graph, visited, nums);\n }\n visited.add(nums[ind]);\n }\n }\n}\n", + "title": "2003. Smallest Missing Genetic Value in Each Subtree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1 . You are given a 0-indexed integer array parents , where parents[i] is the parent for node i . Since node 0 is the root , parents[0] == -1 . There are 10^5 genetic values, each represented by an integer in the inclusive range [1, 10^5 ] . You are given a 0-indexed integer array nums , where nums[i] is a distinct genetic value for node i . Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i . The subtree rooted at a node x contains node x and all of its descendant nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == parents.length == nums.length", + "2 <= n <= 10^5", + "0 <= parents[i] <= n - 1 for i != 0", + "parents[0] == -1", + "parents represents a valid tree.", + "1 <= nums[i] <= 10^5", + "Each nums[i] is distinct." + ], + "examples": [ + { + "text": "Example 1: Input:parents = [-1,0,0,2], nums = [1,2,3,4]Output:[5,1,1,1]Explanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-1.png" + }, + { + "text": "Example 2: Input:parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]Output:[7,1,1,4,2,1]Explanation:The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.", + "image": "https://assets.leetcode.com/uploads/2021/08/23/case-2.png" + }, + { + "text": "Example 3: Input:parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]Output:[1,1,1,1,1,1,1]Explanation:The value 1 is missing from all the subtrees.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3421 ms (Top 39.22%) | Memory: 51.8 MB (Top 96.08%)\nclass Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n ans = [1] * len(parents)\n if 1 in nums:\n tree = {}\n for i, x in enumerate(parents):\n tree.setdefault(x, []).append(i)\n\n k = nums.index(1)\n val = 1\n seen = set()\n\n while k != -1:\n stack = [k]\n while stack:\n x = stack.pop()\n seen.add(nums[x])\n for xx in tree.get(x, []):\n if nums[xx] not in seen:\n stack.append(xx)\n seen.add(nums[xx])\n while val in seen: val += 1\n ans[k] = val\n k = parents[k]\n return ans", + "title": "2003. Smallest Missing Genetic Value in Each Subtree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class: Example 1:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet {\n private PriorityQueue q;\n private int index;\n public SmallestInfiniteSet() {\n q = new PriorityQueue();\n index = 1;\n }\n \n public int popSmallest() {\n if (q.size()>0){\n return q.poll();\n }\n return index++;\n }\n \n private boolean is_in_q(int num){\n for(int i : q){\n if (i == num){\n return true;\n }\n }\n return false;\n }\n \n public void addBack(int num) {\n if( num < index && !is_in_q(num)){\n q.add(num);\n }\n }\n}\n", + "title": "2336. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class: Example 1:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet:\n\n def __init__(self):\n self.index = 1\n self.heap = []\n\n def popSmallest(self) -> int:\n if self.heap:\n return heapq.heappop(self.heap)\n self.index += 1\n return self.index-1\n\n def addBack(self, num: int) -> None:\n if self.index > num and num not in self.heap:\n heapq.heappush(self.heap,num)\n", + "title": "2336. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You have k lists of sorted integers in non-decreasing order . Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length == k", + "1 <= k <= 3500", + "1 <= nums[i].length <= 50", + "-10^5 <= nums[i][j] <= 10^5", + "nums[i] is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]Output:[20,24]Explanation:List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[1,2,3],[1,2,3]]Output:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 28 ms (Top 89.13%) | Memory: 48.60 MB (Top 83.44%)\n\nclass Solution {\n public int[] smallestRange(List> nums) {\n int[] res = {-100000 , 100000};\n PriorityQueuepq = new PriorityQueue<>((a , b) -> a[0] - b[0]);\n int max = Integer.MIN_VALUE;\n int k = nums.size();\n\n for(int i = 0; i < k; i++){\n int minElem = nums.get(i).get(0);\n int[] arr = {minElem , 0 , i};\n\n max = Math.max(max , minElem);\n pq.add(arr);\n\n }\n while(true){\n int min[] = pq.poll();\n if(res[1] - res[0] > max - min[0]){\n res[1] = max;\n res[0] = min[0];\n }\n min[1]++;\n\n Listcur = nums.get(min[2]);\n\n if(min[1] == cur.size()){\n break;\n }\n else{\n min[0] = cur.get(min[1]);\n max = Math.max(max , cur.get(min[1]));\n pq.add(min);\n }\n }\n return res;\n }\n}\n", + "title": "632. Smallest Range Covering Elements from K Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have k lists of sorted integers in non-decreasing order . Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums.length == k", + "1 <= k <= 3500", + "1 <= nums[i].length <= 50", + "-10^5 <= nums[i][j] <= 10^5", + "nums[i] is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]Output:[20,24]Explanation:List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].", + "image": null + }, + { + "text": "Example 2: Input:nums = [[1,2,3],[1,2,3],[1,2,3]]Output:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 188 ms (Top 86.16%) | Memory: 23.30 MB (Top 59.07%)\n\nfrom typing import List\nimport heapq\n\n\nclass Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n heap = [(row[0], i, 0) for i, row in enumerate(nums)]\n heapq.heapify(heap)\n ans = [-10**9, 10**9]\n right = max(row[0] for row in nums)\n while heap:\n left, row, col = heapq.heappop(heap)\n if right - left < ans[1] - ans[0]:\n ans = [left, right]\n if col + 1 == len(nums[row]):\n return ans\n right = max(right, nums[row][col + 1])\n heapq.heappush(heap, (nums[row][col + 1], row, col + 1))\n\n# Tests:\nif __name__ == '__main__':\n s = Solution()\n # test case 1\n output1 = s.smallestRange([[4,10,15,24,26],[0,9,12,20],[5,18,22,30]])\n expected_output1 = [20,24]\n assert output1 == expected_output1, f\"Expected {expected_output1}, but got {output1}\"\n # test case 2\n output2 = s.smallestRange([[1,2,3],[1,2,3],[1,2,3]])\n expected_output2 = [1,1]\n assert output2 == expected_output2, f\"Expected {expected_output2}, but got {output2}\"\n print(\"All tests passed!\")\n", + "title": "632. Smallest Range Covering Elements from K Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k] . You can apply this operation at most once for each index i . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after applying the mentioned operation at most once for each index in it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0Output:0Explanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2Output:6Explanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3Output:0Explanation:Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 41.38%) | Memory: 50.1 MB (Top 6.90%)\n\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n if (nums.length == 1)\n return 0;\n\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n\n for (int num: nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n int diff = max - min;\n\n return Math.max(0, diff - 2*k);\n }\n}", + "title": "908. Smallest Range I", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums and an integer k . In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k] . You can apply this operation at most once for each index i . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after applying the mentioned operation at most once for each index in it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0Output:0Explanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2Output:6Explanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3Output:0Explanation:Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 156 ms (Top 5.06%) | Memory: 18.40 MB (Top 7.47%)\n\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n maxi = max(A)\n mini = min(A)\n return max(0, maxi-K-mini-K)\n", + "title": "908. Smallest Range I", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array nums and an integer k . For each index i where 0 <= i < nums.length , change nums[i] to be either nums[i] + k or nums[i] - k . The score of nums is the difference between the maximum and minimum elements in nums . Return the minimum score of nums after changing the values at each index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^4", + "0 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1], k = 0Output:0Explanation:The score is max(nums) - min(nums) = 1 - 1 = 0.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,10], k = 2Output:6Explanation:Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,6], k = 3Output:3Explanation:Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 5.74%) | Memory: 50.2 MB (Top 6.63%)\nclass Solution {\n public int smallestRangeII(int[] nums, int k) {\n int n = nums.length;\n if (n==1)\n return 0; // Max and min are the same\n\n Arrays.sort(nums);\n\n // score = minimum(max-min)\n // To minimize the score, need to add k to small numbers (Initial part of array)\n // and need to subtract k from large numbers (End part of array)\n\n // It might happen that when we add k to a number\n // And subtract k from another number\n // The minimum and maximum can change\n\n // If k>=nums[n-1]-nums[0] the score will always increase if we add k to some\n // numbers and subtract k from some numbers\n // Hence, the minimum score is the current score\n\n if (k >= nums[n-1]-nums[0]) {\n return nums[n-1]-nums[0];\n }\n\n // Now k < nums[n-1]-nums[0]\n // Add k to first p numbers and subtract k from remaining numbers\n // LEFT SEGMENT: First p numbers where we add k\n // RIGHT SEGMENT: Remaining numbers where we subtract k\n\n // LEFT SEGMENT: (nums[0]+k,nums[1]+k,......,nums[p-1]+k)\n // RIGHT SEGMENT: (nums[p]-k,nums[p+1]-k,.......nums[n-1]-k)\n\n // Question: Where is p?\n // Answer: We try all possible values for p and min score everytime\n\n // After subtracting and adding k to numbers,\n // the new minimum and maximum will be\n // minimum = min (nums[0]+k , nums[p]-k)\n // maximum = max (nums[p-1]+k, nums[n-1]-k)\n\n int minScore = nums[n-1]-nums[0];\n for (int p=1;p int:\n nums.sort()\n ans = nums[-1] - nums[0]\n\n for i in range(0, len(nums) - 1):\n ans = min(ans, max(nums[i] + k, nums[-1] -\n k) - min(nums[i+1] - k, nums[0] + k))\n\n return ans\n", + "title": "910. Smallest Range II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an array nums . You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] . Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it . If there are multiple answers, return the smallest such index k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if we have nums = [2,4,1,3,0] , and we rotate by k = 2 , it becomes [1,3,0,2,4] . This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,4,0]Output:3Explanation:Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,0,2,4]Output:0Explanation:nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 100.0%) | Memory: 61.60 MB (Top 46.55%)\n\nclass Solution {\n public int bestRotation(int[] nums) {\n final int size = nums.length;\n int[] rsc = new int[size];\n for(int i = 0; i < size - 1; i++) {\n int value = nums[i];\n int downPos = (i + 1 + size - value) % size;\n rsc[downPos]--;\n }\n int value = nums[size-1];\n if( value != 0 ) rsc[size - value]--;\n int bestk = 0;\n int bestscore = rsc[0];\n int score = rsc[0];\n for(int i = 1; i < nums.length; i++) {\n score += rsc[i] + 1;\n if( score > bestscore ) {\n bestk = i;\n bestscore = score;\n }\n }\n return bestk;\n }\n}\n", + "title": "798. Smallest Rotation with Highest Score", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array nums . You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]] . Afterward, any entries that are less than or equal to their index are worth one point. Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it . If there are multiple answers, return the smallest such index k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if we have nums = [2,4,1,3,0] , and we rotate by k = 2 , it becomes [1,3,0,2,4] . This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,4,0]Output:3Explanation:Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,0,2,4]Output:0Explanation:nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def bestRotation(self, nums: List[int]) -> int:\n diff = [i - nums[i] for i in range(len(nums))]\n \n target = 0\n qualified = []\n for d in diff:\n if d >= target:\n heappush(qualified, d)\n smallest_rotate = 0\n highest_score = len(qualified)\n \n \n for rotate in range(1, len(nums)):\n target += 1\n while qualified and qualified[0] < target:\n heappop(qualified)\n modified = diff[rotate-1] + len(diff)\n heappush(qualified, modified)\n score = len(qualified)\n if score > highest_score:\n smallest_rotate = rotate\n highest_score = score\n \n return smallest_rotate\n\n", + "title": "798. Smallest Rotation with Highest Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z' . Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root . As a reminder, any shorter prefix of a string is lexicographically smaller . A leaf of a node is a node that has no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ab\" is lexicographically smaller than \"aba\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,1,2,3,4,3,4]Output:\"dba\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree1.png" + }, + { + "text": "Example 2: Input:root = [25,1,3,1,3,0,2]Output:\"adz\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree2.png" + }, + { + "text": "Example 3: Input:root = [2,2,1,null,1,0,null,0]Output:\"abc\"", + "image": "https://assets.leetcode.com/uploads/2019/02/01/tree3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 58.14%) | Memory: 45.5 MB (Top 29.64%)\nclass Solution {\n String result = null;\n public String smallestFromLeaf(TreeNode root) {\n build(root, new StringBuilder());\n return result;\n }\n\n public void build(TreeNode root, StringBuilder str) {\n if (root == null) return;\n\n StringBuilder sb = new StringBuilder(str).insert(0, String.valueOf(intToChar(root.val)));\n\n if (root.left == null && root.right == null) { // we are on a leaf node\n result = result == null || sb.toString().compareTo(result) < 0 ? sb.toString() : result;\n return;\n }\n build(root.left, sb); // build left child\n build(root.right, sb); // build right child\n }\n\n // turns an int (0-25) into a Character ex: 0 -> a, 1 -> b, 2 -> c\n public Character intToChar(int i) {\n return (char) (i + 'a');\n }\n}", + "title": "988. Smallest String Starting From Leaf", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z' . Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root . As a reminder, any shorter prefix of a string is lexicographically smaller . A leaf of a node is a node that has no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ab\" is lexicographically smaller than \"aba\" ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [0,1,2,3,4,3,4]Output:\"dba\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree1.png" + }, + { + "text": "Example 2: Input:root = [25,1,3,1,3,0,2]Output:\"adz\"", + "image": "https://assets.leetcode.com/uploads/2019/01/30/tree2.png" + }, + { + "text": "Example 3: Input:root = [2,2,1,null,1,0,null,0]Output:\"abc\"", + "image": "https://assets.leetcode.com/uploads/2019/02/01/tree3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, \"\")\n return self.res", + "title": "988. Smallest String Starting From Leaf", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1 , the numeric value of b is 2 , the numeric value of c is 3 , and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8 . You are given two integers n and k . Return the lexicographically smallest string with length equal to n and numeric value equal to k . Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "n <= k <= 26 * n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 27Output:\"aay\"Explanation:The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 73Output:\"aaszz\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 22 ms (Top 80.31%) | Memory: 63.1 MB (Top 85.85%)\nclass Solution {\n public String getSmallestString(int n, int k) {\n char[] ch = new char[n];\n for(int i=0;i0) {\n currChar=Math.min(25,k);\n ch[--n]+=currChar;\n k-=currChar;\n }\n return String.valueOf(ch);\n }\n}", + "title": "1663. Smallest String With A Given Numeric Value", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1 , the numeric value of b is 2 , the numeric value of c is 3 , and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8 . You are given two integers n and k . Return the lexicographically smallest string with length equal to n and numeric value equal to k . Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y , or if i is the first position such that x[i] != y[i] , then x[i] comes before y[i] in alphabetic order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "n <= k <= 26 * n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, k = 27Output:\"aay\"Explanation:The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 5, k = 73Output:\"aaszz\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1870 ms (Top 22.43%) | Memory: 15.5 MB (Top 41.47%)\nclass Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n ans = ['a']*n # Initialize the answer to be 'aaa'.. length n\n val = n #Value would be length as all are 'a'\n\n for i in range(n-1, -1, -1):\n if val == k: # if value has reached k, we have created our lexicographically smallest string\n break\n val -= 1 # reduce value by one as we are removing 'a' and replacing by a suitable character\n ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or 'z'\n val += ord(ans[i]) - 96 # add the value of newly appended character to value\n\n return ''.join(ans) # return the ans string in the by concatenating the list", + "title": "1663. Smallest String With A Given Numeric Value", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times . Return the lexicographically smallest string that s can be changed to after using the swaps. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "0 <= pairs.length <= 10^5", + "0 <= pairs[i][0], pairs[i][1] < s.length", + "s only contains lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"dcab\", pairs = [[0,3],[1,2]]Output:\"bacd\"Explaination:Swap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]Output:\"abcd\"Explaination:Swap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"cba\", pairs = [[0,1],[1,2]]Output:\"abc\"Explaination:Swap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[]parent;\n int[]rank;\n public String smallestStringWithSwaps(String s, List> pairs) {\n parent = new int[s.length()];\n rank = new int[s.length()];\n for(int i=0;i l : pairs){\n int i = l.get(0);\n int j = l.get(1);\n \n int il = find(i);\n int jl = find(j);\n if(il != jl){\n union(il,jl);\n }\n }\n \n //To get the Character in sorted order\n PriorityQueue[]pq = new PriorityQueue[s.length()];\n for(int i=0;i();\n }\n \n for(int i=0;ir2:\n self.parentof[p2] = p1\n else:\n self.parentof[p1]=p2\n if r1==r2: self.rankof[p2]+=1\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n dsu = DSU()\n nodes = set()\n smallest = [s[i] for i in range(len(s))]\n\n for i,j in pairs:\n dsu.unify(i,j)\n nodes.add(i)\n nodes.add(j)\n\n groups = {}\n for node in nodes:\n par = dsu.find(node)\n if par not in groups:\n groups[par] = [node]\n else:\n groups[par].append(node)\n \n for group in groups.values():\n letters,k = sorted([s[i] for i in group]),0\n \n for i in group:\n smallest[i] = letters[k]\n k+=1\n\n return \"\".join(smallest)\n", + "title": "1202. Smallest String With Swaps", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"Output:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"Output:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 87.48%) | Memory: 42.2 MB (Top 54.57%)\n\nclass Solution {\n public String smallestSubsequence(String s) {\n boolean[] inStack = new boolean [26];\n int[] lastIdx = new int [26];\n Arrays.fill(lastIdx,-1);\n for(int i = 0; i < s.length(); i++){\n lastIdx[s.charAt(i)-'a'] = i;\n }\n Deque dq = new ArrayDeque<>();\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(inStack[ch-'a']){\n continue;\n }\n while(!dq.isEmpty() && dq.peekLast() > ch && lastIdx[dq.peekLast()-'a'] > i){\n inStack[dq.pollLast()-'a'] = false;\n }\n dq.addLast(ch);\n inStack[ch-'a'] = true;\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n return sb.toString();\n }\n}", + "title": "1081. Smallest Subsequence of Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"bcabc\"Output:\"abc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbacdcbc\"Output:\"acdb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestSubsequence(self, s: str) -> str:\n # calculate the last occurence of each characters in s\n last_occurence = {c: i for i, c in enumerate(s)}\n \n stack = []\n # check if element is in stack\n instack = set()\n for i, c in enumerate(s):\n if c not in instack:\n # check if stack already have char larger then current char\n # and if char in stack will occur later again, remove that from stack\n while stack and stack[-1] > c and last_occurence[stack[-1]] > i:\n instack.remove(stack[-1])\n stack.pop()\n \n instack.add(c) \n stack.append(c)\n \n return \"\".join(stack)\n", + "title": "1081. Smallest Subsequence of Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root . Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 500] .", + "0 <= Node.val <= 500", + "The values of the nodes in the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]Output:[2,7,4]Explanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:[1]Explanation:The root is the deepest node in the tree.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]Output:[2]Explanation:The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public TreeNode subtreeWithAllDeepest(TreeNode root) {\n\t\tif (root.left == null && root.right == null) return root;\n int depth = findDepth(root);\n Queue q = new LinkedList<>();\n q.offer(root);\n int count = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n count++;\n if (count == depth) {\n break;\n }\n for (int i = 0; i < size; i++) {\n TreeNode cur = q.poll();\n if (cur.left != null) q.offer(cur.left);\n if (cur.right != null) q.offer(cur.right);\n }\n }\n Set set = new HashSet<>();\n while (!q.isEmpty()) {\n set.add(q.poll().val);\n }\n return find(root, set);\n }\n \n public int findDepth(TreeNode root) {\n if (root == null) return 0;\n int left = findDepth(root.left);\n int right = findDepth(root.right);\n return 1 + Math.max(left, right);\n }\n \n public TreeNode find(TreeNode root, Set set) {\n if (root == null) return root;\n if (set.contains(root.val)) return root;\n TreeNode left = find(root.left, set);\n TreeNode right = find(root.right, set);\n if (left != null && right != null) return root;\n else if (left != null) return left;\n else if (right != null) return right;\n else return null;\n }\n}\n", + "title": "865. Smallest Subtree with all the Deepest Nodes", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, the depth of each node is the shortest distance to the root . Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree will be in the range [1, 500] .", + "0 <= Node.val <= 500", + "The values of the nodes in the tree are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4]Output:[2,7,4]Explanation:We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" + }, + { + "text": "Example 2: Input:root = [1]Output:[1]Explanation:The root is the deepest node in the tree.", + "image": null + }, + { + "text": "Example 3: Input:root = [0,1,3,null,2]Output:[2]Explanation:The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n\n # find a set of deepest nodes first\n deepest_nodes = [0]\n self.find_deepest(root, 0, deepest_nodes)\n \n # extract the depth and also make a set out of the values\n targets = set(deepest_nodes[1:])\n\n # get the subtree\n return self.find_merge(root, targets)[0]\n\n def find_deepest(self, node, current_depth, deepest_nodes):\n\n # make a check\n if not node:\n return\n \n # make a check if we are a deep node\n if current_depth > deepest_nodes[0]:\n deepest_nodes.clear()\n deepest_nodes.append(current_depth)\n deepest_nodes.append(node.val)\n elif current_depth == deepest_nodes[0]:\n deepest_nodes.append(node.val)\n \n # go deeper\n self.find_deepest(node.left, current_depth+1, deepest_nodes)\n self.find_deepest(node.right, current_depth+1, deepest_nodes)\n \n def find_merge(self, node, targets):\n\n # make a check\n if not node:\n return None, set()\n\n # check whether we are a target\n found = set()\n if node.val in targets:\n found.add(node.val)\n\n # go deeper and get result nodes\n nleft, left = self.find_merge(node.left, targets)\n if nleft is not None:\n return nleft, set()\n nright, right = self.find_merge(node.right, targets)\n if nright is not None:\n return nright, set()\n\n # merge the found set\n found = found | left | right\n\n # check whether we found all\n if not (targets - found):\n return node, set()\n else:\n return None, found", + "title": "865. Smallest Subtree with all the Deepest Nodes", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a project, you have a list of required skills req_skills , and a list of people. The i th person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills , there is at least one person in the team who has that skill. We can represent these teams by the index of each person. Return any sufficient team of the smallest possible size, represented by the index of each person . You may return the answer in any order . It is guaranteed an answer exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, team = [0, 1, 3] represents the people with skills people[0] , people[1] , and people[3] ." + ], + "examples": [ + { + "text": "Example 1: Input:req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]Output:[0,2]", + "image": null + }, + { + "text": "Example 2: Input:req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] smallestSufficientTeam(String[] req_skills, List> people) {\n int N = 1 << req_skills.length, INF = (int)1e9;\n int[] parent = new int[N];\n int[] who = new int[N];\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0] = 0;\n for (int i = 0; i < N; i++){\n if (dp[i]!=INF){ // valid state \n for (int k = 0; k < people.size(); k++){\n int cur = i;\n for (int j = 0; j < req_skills.length; j++){\n for (String skill : people.get(k)){\n if (req_skills[j].equals(skill)){\n cur |= 1<dp[i]+1){ // replace if better\n dp[cur]=dp[i]+1;\n parent[cur]=i;\n who[cur]=k;\n }\n }\n }\n }\n int[] ans = new int[dp[N-1]];\n for (int i = 0,cur=N-1; i < ans.length; i++){\n ans[i]=who[cur];\n cur=parent[cur];\n }\n return ans;\n }\n}\n", + "title": "1125. Smallest Sufficient Team", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a project, you have a list of required skills req_skills , and a list of people. The i th person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills , there is at least one person in the team who has that skill. We can represent these teams by the index of each person. Return any sufficient team of the smallest possible size, represented by the index of each person . You may return the answer in any order . It is guaranteed an answer exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, team = [0, 1, 3] represents the people with skills people[0] , people[1] , and people[3] ." + ], + "examples": [ + { + "text": "Example 1: Input:req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]Output:[0,2]", + "image": null + }, + { + "text": "Example 2: Input:req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2036 ms (Top 22.82%) | Memory: 203 MB (Top 6.04%)\nfrom collections import defaultdict\nfrom functools import lru_cache\n\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n N = len(req_skills)\n skills = {skill: i for i, skill in enumerate(req_skills)}\n people_mask = defaultdict(int)\n for i, cur_skills in enumerate(people):\n mask = 0\n for skill in cur_skills:\n mask |= 1<= self.res:\n return\n dfs(i+1, l, mask)\n self.path.append(i)\n if mask & people_mask[i] != people_mask[i]: dfs(i+1, l+1, mask | people_mask[i])\n self.path.pop()\n dfs(0,0,0)\n return self.respath", + "title": "1125. Smallest Sufficient Team", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value . Note that the sign of the number does not change after rearranging the digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-10^15 <= num <=10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 310Output:103Explanation:The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.", + "image": null + }, + { + "text": "Example 2: Input:num = -7605Output:-7650Explanation:Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long smallestNumber(long num) {\n if(num == 0){\n return 0;\n }\n boolean isNegative = num < 0;\n num = num < 0 ? num * -1 : num;\n \n char[] c = String.valueOf(num).toCharArray();\n Arrays.sort(c);\n String str;\n if(!isNegative){\n int non = 0;\n\t\t\t//if not negative we need to find out the first non-leading zero then swap with first zero\n for(; non < c.length; non++){\n if(c[non] != '0'){\n break;\n }\n }\n char temp = c[non];\n c[non] = c[0];\n c[0] = temp;\n str = new String(c);\n }else{\n str = new String(c);\n StringBuilder sb = new StringBuilder(str);\n str = \"-\".concat(sb.reverse().toString());\n }\n return Long.valueOf(str);\n }\n}\n", + "title": "2165. Smallest Value of the Rearranged Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value . Note that the sign of the number does not change after rearranging the digits. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-10^15 <= num <= 10^15" + ], + "examples": [ + { + "text": "Example 1: Input:num = 310Output:103Explanation:The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.", + "image": null + }, + { + "text": "Example 2: Input:num = -7605Output:-7650Explanation:Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 17.05%) | Memory: 13.9 MB (Top 69.77%)\nclass Solution:\n def smallestNumber(self, num: int) -> int:\n lst=[i for i in str(num)]\n if num<0:\n return ''.join(['-'] + sorted(lst[1:],reverse=True))\n lst=sorted(lst)\n if '0' in lst:\n itr=0\n while itr map,int si,int ei){\n //if si==ei just directly return \n if(si==ei) return new int [] {0,0,0};\n LinkedList que = new LinkedList<>();\n que.addLast(new int[] {si,0,0});\n int level = 0;\n //to stop visiting cells again\n boolean [] vis = new boolean [ei+1];\n vis[si]=true;\n //starting bfs\n while(que.size()!=0){\n int size=que.size();\n while(size-->0){\n int [] rem = que.removeFirst();\n int idx= rem[0];\n int lad = rem[1];\n int sna = rem[2];\n for(int i=1;i<=dice;i++){\n int x =i+rem[0]; //checking all the steps\n if(x<=ei){ //valid points\n if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder\n if(map.containsKey(x)){\n int val = map.get(x); \n if(val==ei) return new int[] {level+1,lad+1,sna};\n if(!vis[val]){\n vis[val]=true;\n //if val>x this means we have a ladder and if less, then it is a snake\n que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});\n }\n }\n }\n else{\n //if it is not present in map, then it is a normal cell, so just insert it directly\n if(x==ei) return new int [] {level+1,lad,sna};\n if(!vis[x]){\n vis[x]=true;\n que.addLast(new int [] {x,lad,sna});\n }\n }\n }\n }\n }\n level++;\n }\n return new int [] {-1,0,0};\n }\n public int snakesAndLadders(int[][] board) {\n HashMap map = new HashMap<>();\n int count = 1;\n int n = board.length;\n boolean flag = true;\n //traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)\n for(int i=n-1;i>=0;i--){\n //traversing in the order of the board\n if(flag){\n for(int j=0;j=0;j--){\n if(board[i][j]!=-1){\n map.put(count,board[i][j]);\n }\n flag=true;\n count++;\n }\n }\n }\n //if snake on destination then just return -1;\n if(board[0][0]!=-1) return -1;\n //we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used} \n int [] ans = getans(6,map,1,n*n);;\n return ans[0];\n \n }\n}", + "title": "909. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n integer matrix board where the cells are labeled from 1 to n 2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0] ) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr , do the following: A board square on row r and column c has a snake or ladder if board[r][c] != -1 . The destination of that snake or ladder is board[r][c] . Squares 1 and n 2 do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. Return the least number of moves required to reach the square n 2 . If it is not possible to reach the square, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n 2 )] . This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next .", + "The game ends when you reach the square n 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]Output:4Explanation:In the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.", + "image": "https://assets.leetcode.com/uploads/2018/09/23/snakes.png" + }, + { + "text": "Example 2: Input:board = [[-1,-1],[-1,3]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 228 ms (Top 5.16%) | Memory: 17.50 MB (Top 5.8%)\n\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n moves = 0\n q = collections.deque([1])\n visited = [[False for _ in range(n)] for _ in range(n)]\n visited[n-1][0] = True\n while q:\n size = len(q)\n for i in range(size):\n currBoardVal = q.popleft()\n if currBoardVal == n*n:\n return moves\n for diceVal in range(1, 7):\n if currBoardVal + diceVal > n*n:\n break\n pos = self.findCoordinates(currBoardVal + diceVal, n)\n row, col = pos\n if not visited[row][col]:\n visited[row][col] = True\n if board[row][col] == -1:\n q.append(currBoardVal + diceVal)\n else:\n q.append(board[row][col])\n moves += 1\n return -1\n \n def findCoordinates(self, curr: int, n: int) -> Tuple[int, int]:\n row = n - (curr - 1) // n - 1\n col = (curr - 1) % n\n if row % 2 == n % 2:\n return (row, n - 1 - col)\n else:\n return (row, col)\n\n", + "title": "909. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement a SnapshotArray that supports the following interface: Example 1:", + "description_images": [], + "constraints": [ + "SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0 .", + "void set(index, val) sets the element at the given index to be equal to val .", + "int snap() takes a snapshot of the array and returns the snap_id : the total number of times we called snap() minus 1 .", + "int get(index, snap_id) returns the value at the given index , at the time we took the snapshot with the given snap_id" + ], + "examples": [ + { + "text": "Example 1: Input:[\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n[[3],[0,5],[],[0,6],[0,0]]Output:[null,null,0,null,5]Explanation:SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\nsnapshotArr.set(0,5); // Set array[0] = 5\nsnapshotArr.snap(); // Take a snapshot, return snap_id = 0\nsnapshotArr.set(0,6);\nsnapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 90.65%) | Memory: 81.4 MB (Top 44.17%)\nclass SnapshotArray {\n\n TreeMap[] snapshotArray;\n int currSnapId;\n\n public SnapshotArray(int length) {\n snapshotArray = new TreeMap[length];\n for(int i=0;i None:\n self.history[self.snap_id][index] = val\n\n def snap(self) -> int:\n self.snap_id += 1\n return self.snap_id-1\n\n def get(self, index: int, snap_id: int) -> int:\n for i in range(snap_id,-1,-1):\n if index in self.history[i]:\n return self.history[i][index]\n return 0 # default value in case it wasn't set earlier", + "title": "1146. Snapshot Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\" . The equation contains only '+' , '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= equation.length <= 1000", + "equation has exactly one '=' .", + "equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x' ." + ], + "examples": [ + { + "text": "Example 1: Input:equation = \"x+5-3+x=6+x-2\"Output:\"x=2\"", + "image": null + }, + { + "text": "Example 2: Input:equation = \"x=x\"Output:\"Infinite solutions\"", + "image": null + }, + { + "text": "Example 3: Input:equation = \"2x=x\"Output:\"x=0\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] simplifyEqn(String eqn){\n int prevSign = 1;\n int sumX = 0;\n int sumNums = 0;\n for(int i=0;i str:\n \"\"\" O(N)TS \"\"\"\n x, y, p = 0, 0, 1\n for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n g = i.group()\n if g == '=':\n p = -1\n elif g[-1] == 'x':\n x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n else:\n y += -p * int(g)\n\n if x == 0 == y:\n return 'Infinite solutions'\n elif x == 0:\n return \"No solution\"\n return f'x={y // x}'", + "title": "640. Solve the Equation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array questions where questions[i] = [points i , brainpower i ] . The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0 ) and make a decision whether to solve or skip each question. Solving question i will earn you points i points but you will be unable to solve each of the next brainpower i questions. If you skip question i , you get to make the decision on the next question. Return the maximum points you can earn for the exam . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]] : If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2 . If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3 .", + "If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2 .", + "If instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:questions = [[3,2],[4,3],[4,4],[2,5]]Output:5Explanation:The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.", + "image": null + }, + { + "text": "Example 2: Input:questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]Output:7Explanation:The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mostPoints(self, q: List[List[int]]) -> int:\n @cache\n def dfs(i: int) -> int:\n return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1]))\n return dfs(0)\n", + "title": "2140. Solving Questions With Brainpower", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , sort the array in ascending order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-5 * 10^4 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,3,1]Output:[1,2,3,5]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1,2,0,0]Output:[0,0,1,1,2,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 35 ms (Top 28.44%) | Memory: 75.6 MB (Top 11.81%)\nclass Solution {\n\n public void downHeapify(int[] nums, int startIndex, int lastIndex){\n\n int parentIndex = startIndex;\n int leftChildIndex = 2*parentIndex + 1;\n int rightChildIndex = 2*parentIndex + 2;\n\n while(leftChildIndex <= lastIndex){\n int maxIndex = parentIndex;\n if(nums[leftChildIndex] > nums[maxIndex]){\n maxIndex = leftChildIndex;\n }\n if(rightChildIndex <= lastIndex && nums[rightChildIndex] > nums[maxIndex]){\n maxIndex = rightChildIndex;\n }\n if(maxIndex == parentIndex){\n return;\n }\n int temp = nums[maxIndex];\n nums[maxIndex] = nums[parentIndex];\n nums[parentIndex] = temp;\n parentIndex = maxIndex;\n leftChildIndex = 2*parentIndex + 1;\n rightChildIndex = 2*parentIndex + 2;\n }\n return;\n }\n\n public int[] sortArray(int[] nums) {\n int len = nums.length;\n //building a heap - O(n) time\n for(int i=(len/2)-1;i>=0;i--){\n downHeapify(nums,i,len-1);\n }\n //sorting element - nlogn(n) time\n for(int i=len -1 ;i>0;i--){\n int temp = nums[i];\n nums[i] = nums[0];\n nums[0] = temp;\n downHeapify(nums,0,i-1);\n }\n return nums;\n\n }\n}", + "title": "912. Sort an Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums , sort the array in ascending order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "-5 * 10^4 <= nums[i] <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,2,3,1]Output:[1,2,3,5]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,1,2,0,0]Output:[0,0,1,1,2,5]", + "image": null + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n \n h = {}\n for i in nums:\n if i in h:\n h[i]+=1\n else:\n h[i]=1\n \n heap = []\n for i in h:\n heap.append([i,h[i]])\n \n heapq.heapify(heap)\n ans = []\n \n while heap:\n x = heapq.heappop(heap)\n ans.append(x[0])\n if x[1]>1:\n heapq.heappush(heap,[x[0],x[1]-1])\n \n return ans\n", + "title": "912. Sort an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums , sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order. Return the sorted array . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-100 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,2,2,3]Output:[3,1,1,2,2,2]Explanation:'3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,1,3,2]Output:[1,3,3,2,2]Explanation:'2' and '3' both have a frequency of 2, so they are sorted in decreasing order.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-1,1,-6,4,5,-6,1,4,1]Output:[5,-1,4,4,-6,-6,1,1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \n r = Counter(nums).most_common()\n r.sort(key = lambda x: x[0], reverse=True)\n r.sort(key = lambda x: x[1])\n \n t = []\n for i in r:\n a, b = i\n t.extend([a]*b)\n \n return t\n", + "title": "1636. Sort Array by Increasing Frequency", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "0 <= nums[i] <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,4]Output:[2,4,3,1]Explanation:The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 48.1 MB (Top 66.96%)\nclass Solution {\n\n public int[] sortArrayByParity(int[] nums) {\n int i = 0;\n int j = 0;\n\n while(i < nums.length){\n if(nums[i] % 2 == 1){\n i++;\n }else{\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n\n i++;\n j++;\n }\n }\n\n return nums;\n }\n}", + "title": "905. Sort Array By Parity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5000", + "0 <= nums[i] <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,1,2,4]Output:[2,4,3,1]Explanation:The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 84 ms (Top 42.8%) | Memory: 17.10 MB (Top 53.6%)\n\nclass Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n i, j = 0, len(A) - 1\n while i < j:\n \tif A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i]\n \ti, j = i + 1 - A[i] % 2, j - A[j] % 2\n return A", + "title": "905. Sort Array By Parity", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums , half of the integers in nums are odd , and the other half are even . Sort the array so that whenever nums[i] is odd, i is odd , and whenever nums[i] is even, i is even . Return any answer array that satisfies this condition . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^4", + "nums.length is even.", + "Half of the integers in nums are even.", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,7]Output:[4,5,2,7]Explanation:[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3]Output:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 44.53%) | Memory: 47.70 MB (Top 5.52%)\n\nclass Solution {\n public int[] sortArrayByParityII(int[] A) {\n int i = 0, j = 1, n = A.length;\n while (i < n && j < n) {\n while (i < n && A[i] % 2 == 0) {\n i += 2;\n }\n while (j < n && A[j] % 2 == 1) {\n j += 2;\n }\n if (i < n && j < n) {\n swap(A, i, j);\n }\n }\n return A;\n }\n private void swap(int[] A, int i, int j) {\n int temp = A[i];\n A[i] = A[j];\n A[j] = temp;\n }\n}\n\n", + "title": "922. Sort Array By Parity II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers nums , half of the integers in nums are odd , and the other half are even . Sort the array so that whenever nums[i] is odd, i is odd , and whenever nums[i] is even, i is even . Return any answer array that satisfies this condition . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 2 * 10^4", + "nums.length is even.", + "Half of the integers in nums are even.", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,2,5,7]Output:[4,5,2,7]Explanation:[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3]Output:[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 148 ms (Top 91.55%) | Memory: 19.90 MB (Top 17.18%)\n\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in range(len(nums)):\n if nums[i]%2 == 0:\n even.append(nums[i])\n else:\n odd.append(nums[i])\n for i in range(len(even)):\n lst.append(even[i])\n lst.append(odd[i])\n return lst\n", + "title": "922. Sort Array By Parity II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string . If there are multiple answers, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s consists of uppercase and lowercase English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"tree\"Output:\"eert\"Explanation:'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cccaaa\"Output:\"aaaccc\"Explanation:Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Aabb\"Output:\"bbAa\"Explanation:\"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 12 ms (Top 83.68%) | Memory: 45.80 MB (Top 20.05%)\n\nclass Solution {\n public String frequencySort(String s) {\n int len = s.length();\n HashMap> map = new HashMap(); \n HashMap freqMap = new HashMap();\n \n for(int idx = 0;idx set = map.getOrDefault(freqMap.get(ch),new HashSet());\n set.add(ch);\n map.put(freqMap.get(ch),set);\n maxFreq = Math.max(maxFreq , freqMap.get(ch));\n minFreq = Math.min(minFreq,freqMap.get(ch));\n }\n \n StringBuilder ansStr = new StringBuilder();\n \n for(int freq = maxFreq;freq>=minFreq;freq--){\n if(map.containsKey(freq)){\n HashSet set = map.get(freq);\n for(char ch : set){\n int temp = freq;\n while(temp>0){\n ansStr.append(ch);\n temp--;\n }\n }\n }\n }\n \n return ansStr.toString();\n }\n}\n", + "title": "451. Sort Characters By Frequency", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string . If there are multiple answers, return any of them . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 5 * 10^5", + "s consists of uppercase and lowercase English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"tree\"Output:\"eert\"Explanation:'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cccaaa\"Output:\"aaaccc\"Explanation:Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.", + "image": null + }, + { + "text": "Example 3: Input:s = \"Aabb\"Output:\"bbAa\"Explanation:\"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def frequencySort(self, s: str) -> str:\n di = Counter(s)\n #it wont strike immediately that this is a heap kind of question.\n heap = []\n heapq.heapify(heap)\n for key,val in di.items():\n heapq.heappush(heap,(-1*val,key))\n # n = len(s)\n res = \"\"\n # print(heap)\n while(len(heap)):\n val,ch = heapq.heappop(heap)\n res+=(ch*(-1*val))\n return res\n", + "title": "451. Sort Characters By Frequency", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]Output:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]Output:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public void sortColors(int[] nums) {\n\n int zeroIndex = 0, twoIndex = nums.length - 1, i = 0;\n while (i <= twoIndex) {\n if (nums[i] == 0)\n swap(nums, zeroIndex++, i++);\n else if (nums[i] == 2)\n swap(nums, twoIndex--, i);\n else\n i++;\n }\n }\n\n public void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]Output:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]Output:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 8.88%) | Memory: 16.20 MB (Top 55.73%)\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n\n red, white, blue = 0, 0, len(nums) - 1\n\n while white <= blue:\n if nums[white] == 0:\n nums[white], nums[red] = nums[red], nums[white]\n red += 1\n white += 1\n elif nums[white] == 1:\n white += 1\n else:\n nums[white], nums[blue] = nums[blue], nums[white]\n blue -= 1\n", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums = [4, 1 ,2, 3 ] before this step, it becomes [4, 3 ,2, 1 ] after. The values at odd indices 1 and 3 are sorted in non-increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,2,3]Output:[2,3,4,1]Explanation:First, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1]Output:[2,1]Explanation:Since there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 98.20%) | Memory: 44.5 MB (Top 79.13%)\n\nclass Solution {\n public int[] sortEvenOdd(int[] nums) {\n int[] even = new int[101];\n int[] odd = new int[101];\n int length = nums.length;\n for (int i = 0; i < length; ++i) {\n if (i % 2 == 0) {\n even[nums[i]]++;\n } else {\n odd[nums[i]]++;\n }\n }\n int e = 0;\n int o = 100;\n for (int i = 0; i < length; ++i) {\n if (i % 2 == 0) {\n // check even\n while (even[e] == 0) {\n ++e;\n }\n nums[i] = e;\n even[e]--;\n } else {\n while(odd[o] == 0) {\n --o;\n }\n nums[i] = o;\n odd[o]--;\n }\n }\n return nums;\n }\n}", + "title": "2164. Sort Even and Odd Indices Independently", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums = [4, 1 ,2, 3 ] before this step, it becomes [4, 3 ,2, 1 ] after. The values at odd indices 1 and 3 are sorted in non-increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,1,2,3]Output:[2,3,4,1]Explanation:First, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1]Output:[2,1]Explanation:Since there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 63 ms (Top 80.35%) | Memory: 13.8 MB (Top 69.47%)\n\nclass Solution(object):\n def sortEvenOdd(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n nums[::2], nums[1::2] = sorted(nums[::2]), sorted(nums[1::2], reverse=True)\n return nums", + "title": "2164. Sort Even and Odd Indices Independently", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array arr . Sort the integers in the array in ascending order by the number of 1 's in their binary representation and in case of two or more integers have the same number of 1 's you have to sort them in ascending order. Return the array after sorting it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,2,3,4,5,6,7,8]Output:[0,1,2,4,8,3,5,6,7]Explantion:[0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1024,512,256,128,64,32,16,8,4,2,1]Output:[1,2,4,8,16,32,64,128,256,512,1024]Explantion:All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 70.77%) | Memory: 42.3 MB (Top 96.77%)\nclass Solution {\n public int[] sortByBits(int[] arr) {\n\n Integer[] arrInt = new Integer[arr.length];\n\n for(int i=0;i() {\n @Override\n public int compare(Integer a, Integer b) {\n int aBits=numOfBits(a);\n int bBits=numOfBits(b);\n if(aBits==bBits) {\n return a-b;\n }\n return aBits-bBits;\n }\n });\n\n for(int i=0;i>>1;\n }\n\n return bits;\n }\n}", + "title": "1356. Sort Integers by The Number of 1 Bits", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array arr . Sort the integers in the array in ascending order by the number of 1 's in their binary representation and in case of two or more integers have the same number of 1 's you have to sort them in ascending order. Return the array after sorting it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 500", + "0 <= arr[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [0,1,2,3,4,5,6,7,8]Output:[0,1,2,4,8,3,5,6,7]Explantion:[0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1024,512,256,128,64,32,16,8,4,2,1]Output:[1,2,4,8,16,32,64,128,256,512,1024]Explantion:All integers have 1 bit in the binary representation, you should just sort them in ascending order.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n binary = []\n final = []\n arr.sort()\n for i in arr:\n binary.append(bin(i).count(\"1\"))\n for i,j in zip(arr,binary):\n final.append((i,j))\n z = sorted(final, key=lambda x:x[1])\n \n ls = []\n for k in z:\n ls.append(k[0])\n \n return ls\n", + "title": "1356. Sort Integers by The Number of 1 Bits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 ( 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1 ). Given three integers lo , hi and k . The task is to sort all integers in the interval [lo, hi] by the power value in ascending order , if two or more integers have the same power value sort them by ascending order . Return the k th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "if x is even then x = x / 2", + "if x is odd then x = 3 * x + 1" + ], + "examples": [ + { + "text": "Example 1: Input:lo = 12, hi = 15, k = 2Output:13Explanation:The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.", + "image": null + }, + { + "text": "Example 2: Input:lo = 7, hi = 11, k = 4Output:7Explanation:The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int getKth(int lo, int hi, int k) {\n\n int p = 0;\n int[][] powerArr = new int[hi - lo + 1][2];\n\n Map memo = new HashMap<>();\n for (int i = lo; i <= hi; i++)\n powerArr[p++] = new int[]{i, getPower(i, memo)};\n\n Arrays.sort(powerArr, (a1, a2) -> a1[1] - a2[1] == 0 ? a1[0] - a2[0] : a1[1] - a2[1]);\n\n return powerArr[k - 1][0];\n }\n\n private int getPower(int i, Map memo) {\n if (memo.containsKey(i)) return memo.get(i);\n\n if (i == 1) return 0;\n\n int power = 1 + (i % 2 == 0 ? getPower(i / 2, memo) : getPower(i * 3 + 1, memo));\n\n memo.put(i, power);\n return power;\n }\n}\n", + "title": "1387. Sort Integers by The Power Value", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 ( 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1 ). Given three integers lo , hi and k . The task is to sort all integers in the interval [lo, hi] by the power value in ascending order , if two or more integers have the same power value sort them by ascending order . Return the k th integer in the range [lo, hi] sorted by the power value. Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "if x is even then x = x / 2", + "if x is odd then x = 3 * x + 1" + ], + "examples": [ + { + "text": "Example 1: Input:lo = 12, hi = 15, k = 2Output:13Explanation:The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.", + "image": null + }, + { + "text": "Example 2: Input:lo = 7, hi = 11, k = 4Output:7Explanation:The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 156 ms (Top 74.13%) | Memory: 16.70 MB (Top 42.43%)\n\nimport heapq\nclass Solution:\n def power(self,n):\n if n in self.dic:\n return self.dic[n]\n if n % 2:\n self.dic[n] = self.power(3 * n + 1) + 1\n else:\n self.dic[n] = self.power(n // 2) + 1\n return self.dic[n] \n def getKth(self, lo: int, hi: int, k: int) -> int:\n self.dic = {1:0}\n for i in range(lo,hi+1):\n self.power(i)\n \n lst = [(self.dic[i],i) for i in range(lo,hi+1)]\n heapq.heapify(lst)\n \n for i in range(k):\n ans = heapq.heappop(lst)\n \n return ans[1] \n", + "title": "1387. Sort Integers by The Power Value", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n items each belonging to zero or one of m groups where group[i] is the group that the i -th item belongs to and it's equal to -1 if the i -th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: Return any solution if there is more than one solution and return an empty list if there is no solution. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/11/1359_ex1.png" + ], + "constraints": [ + "The items that belong to the same group are next to each other in the sorted list.", + "There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i -th item in the sorted array (to the left of the i -th item)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]Output:[6,3,4,1,5,2,0,7]", + "image": null + }, + { + "text": "Example 2: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]Output:[]Explanation:This is the same as example 1 except that 4 needs to be before 6 in the sorted list.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 104 ms (Top 36.60%) | Memory: 71.6 MB (Top 49.67%)\nclass Solution {\n // topological sort group first, then node within the group\n private List[] groups;\n private List[] graph;\n // indegrees of node\n private int[] indegrees;\n // indegrees of group\n private int[] indegreeGroups;\n public int[] sortItems(int n, int m, int[] group, List> beforeItems) {\n buildGroups(n, group);\n buildGraph(n, beforeItems, group);\n int[] result = new int[n];\n int top = -1;\n Queue queue = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (indegreeGroups[i] == 0) {\n queue.offer(i);\n }\n }\n while (!queue.isEmpty()) {\n Integer groupId = queue.poll();\n List groupItems = groups[groupId];\n if (groupItems == null) continue;\n Queue itemQueue = new LinkedList<>();\n for (var item: groupItems) {\n if (indegrees[item] == 0) {\n itemQueue.offer(item);\n }\n }\n while (!itemQueue.isEmpty()) {\n Integer item = itemQueue.poll();\n result[++top] = item;\n if (graph[item] == null) continue;\n for (var neighbor: graph[item]) {\n indegrees[neighbor]--;\n if (group[neighbor] != groupId) {\n if (--indegreeGroups[group[neighbor]] == 0) {\n queue.offer(group[neighbor]);\n }\n } else if (indegrees[neighbor] == 0) {\n itemQueue.offer(neighbor);\n }\n }\n }\n }\n if (top < n - 1) return new int[] {};\n return result;\n }\n private void buildGroups(int n, int[] group) {\n // build groups;\n groups = new List[n];\n int index = n - 1;\n for (int i = 0; i < n; i++) {\n if (group[i] == -1) {\n // virtual group\n group[i] = index--;\n }\n if (groups[group[i]] == null) {\n groups[group[i]] = new ArrayList<>();\n }\n groups[group[i]].add(i);\n }\n }\n private void buildGraph(int n, List> beforeItems, int[] group) {\n graph = new List[n];\n indegrees = new int[n];\n indegreeGroups = new int[n];\n for (int i = 0; i < n; i++) {\n for (int j: beforeItems.get(i)) {\n if (graph[j] == null) {\n graph[j] = new ArrayList<>();\n }\n graph[j].add(i);\n indegrees[i]++;\n if (group[i] != group[j]) {\n indegreeGroups[group[i]]++;\n }\n }\n }\n }\n}", + "title": "1203. Sort Items by Groups Respecting Dependencies", + "topic": "Database" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are n items each belonging to zero or one of m groups where group[i] is the group that the i -th item belongs to and it's equal to -1 if the i -th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: Return any solution if there is more than one solution and return an empty list if there is no solution. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/11/1359_ex1.png" + ], + "constraints": [ + "The items that belong to the same group are next to each other in the sorted list.", + "There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i -th item in the sorted array (to the left of the i -th item)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]Output:[6,3,4,1,5,2,0,7]", + "image": null + }, + { + "text": "Example 2: Input:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]Output:[]Explanation:This is the same as example 1 except that 4 needs to be before 6 in the sorted list.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n before = {i:set() for i in range(n)}\n after = {i:set() for i in range(n)}\n beforeG = {i:set() for i in range(m)}\n afterG = {i:set() for i in range(m)}\n groups = {i:set() for i in range(m)}\n qg = collections.deque()\n lazy = collections.deque()\n for i in range(n):\n if group[i] != -1:\n groups[group[i]].add(i)\n for x in beforeItems[i]:\n before[i].add(x)\n after[x].add(i)\n if group[x] != group[i] and group[x] != -1 and group[i] != -1:\n beforeG[group[i]].add(group[x])\n afterG[group[x]].add(group[i])\n for i in range(n):\n if group[i] == -1 and not before[i]:\n lazy.append(i)\n\n for i in range(m):\n if not beforeG[i]:\n qg.append(i)\n ans = []\n while qg:\n while lazy:\n i = lazy.popleft()\n ans.append(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j] and group[j] == -1:\n lazy.append(j)\n g = qg.popleft()\n q = collections.deque()\n for member in groups[g]:\n if not before[member]:\n q.append(member)\n while q:\n i = q.popleft()\n ans.append(i)\n groups[g].remove(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j]:\n if group[j] == g:\n q.append(j)\n if group[j] == -1:\n lazy.append(j) \n if groups[g]:\n return []\n for p in afterG[g]:\n beforeG[p].remove(g)\n if not beforeG[p]:\n qg.append(p)\n while lazy:\n i = lazy.popleft()\n ans.append(i)\n for j in after[i]:\n before[j].remove(i)\n if not before[j] and group[j] == -1:\n lazy.append(j)\n return ans if len(ans) == n else []", + "title": "1203. Sort Items by Groups Respecting Dependencies", + "topic": "Database" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list, return the list after sorting it in ascending order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]Output:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]Output:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 51.11%) | Memory: 78.2 MB (Top 48.67%)\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode sortList(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n\n ListNode mid = middle(head);\n\n ListNode left = sortList(head);\n ListNode right = sortList(mid);\n\n return mergeTwoLists(left, right);\n }\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode head = new ListNode();\n ListNode tail = head;\n while (list1 != null && list2 != null) {\n if (list1.val < list2.val) {\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n } else {\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n }\n }\n\n tail.next = (list1 != null) ? list1 : list2;\n\n return head.next;\n }\n\n public ListNode middle(ListNode head) {\n ListNode midprev = null;\n while (head != null && head.next != null) {\n midprev = (midprev == null) ? head : midprev.next;\n head = head.next.next;\n }\n ListNode mid = midprev.next;\n midprev.next = null;\n return mid;\n }\n}", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the head of a linked list, return the list after sorting it in ascending order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]Output:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]Output:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n store = []\n curr = head\n while curr:\n store.append(curr.val)\n curr = curr.next\n store.sort()\n dummyNode = ListNode(0)\n temp = dummyNode\n \n for i in store:\n x = ListNode(val = i)\n temp.next = x\n temp = x\n return dummyNode.next", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system. The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9 . You are also given another integer array nums . Return the array nums sorted in non-decreasing order based on the mapped values of its elements. Notes: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Elements with the same mapped values should appear in the same relative order as in the input.", + "The elements of nums should only be sorted based on their mapped values and not be replaced by them." + ], + "examples": [ + { + "text": "Example 1: Input:mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]Output:[338,38,991]Explanation:Map the number 991 as follows:\n1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.\n2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.\nTherefore, the mapped value of 991 is 669.\n338 maps to 007, or 7 after removing the leading zeros.\n38 maps to 07, which is also 7 after removing leading zeros.\nSince 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.\nThus, the sorted array is [338,38,991].", + "image": null + }, + { + "text": "Example 2: Input:mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]Output:[123,456,789]Explanation:789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n \n return sorted(nums, key = lambda x: int(\"\".join([str(mapping[int(digit)]) for digit in str(x)])))\n", + "title": "2191. Sort the Jumbled Numbers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0] , where mat is a 6 x 3 matrix, includes cells mat[2][0] , mat[3][1] , and mat[4][2] . Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "1 <= mat[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]Output:[[1,1,1,1],[1,2,2,2],[1,2,3,3]]", + "image": "https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png" + }, + { + "text": "Example 2: Input:mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]Output:[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] diagonalSort(int[][] mat) {\n int n = mat.length; \n int m = mat[0].length;\n for(int i=0;i List[List[int]]:\n n, m, d = len(A), len(A[0]), defaultdict(list)\n any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m))\n any(d[sum_].sort(reverse=1) for sum_ in d)\n return [[d[i-j].pop() for j in range(m)] for i in range(n)]", + "title": "1329. Sort the Matrix Diagonally", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"is2 sentence4 This1 a3\"Output:\"This is a sentence\"Explanation:Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Myself2 Me1 I4 and3\"Output:\"Me Myself and I\"Explanation:Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 59.85%) | Memory: 42 MB (Top 63.26%)\nclass Solution {\n public String sortSentence(String s) {\n String []res=new String[s.split(\" \").length];\n for(String st:s.split(\" \")){\n res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1);\n }\n return String.join(\" \",res);\n }\n}", + "title": "1859. Sorting the Sentence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"is2 sentence4 This1 a3\"Output:\"This is a sentence\"Explanation:Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.", + "image": null + }, + { + "text": "Example 2: Input:s = \"Myself2 Me1 I4 and3\"Output:\"Me Myself and I\"Explanation:Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 68 ms (Top 5.88%) | Memory: 13.7 MB (Top 96.86%)\nclass Solution:\n def sortSentence(self, s: str) -> str:\n\n x = s.split()\n dic = {}\n for i in x :\n dic[i[-1]] = i[:-1]\n return ' '.join([dic[j] for j in sorted(dic)])", + "title": "1859. Sorting the Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are two types of soup: type A and type B . Initially, we have n ml of each type of soup. There are four kinds of operations: When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25 . If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 50Output:0.62500Explanation:If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:0.71875", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.5%) | Memory: 39.56 MB (Top 93.7%)\n\nclass Solution {\n public double soupServings(int n) {\n if(n>4800) return 1;\n n=(int)Math.ceil(n*1.0/25);\n double dp[][]= new double[n+1][n+1];\n return helper(n,n,dp);\n }\n double helper(int a,int b,double dp[][]){\n if(a<=0 && b<=0) return 0.5;\n if(b<=0) return 0;\n if(a<=0) return 1;\n if(dp[a][b]>0) return dp[a][b];\n return dp[a][b]=0.25*(helper(a-4,b,dp)+helper(a-3,b-1,dp)+helper(a-2,b-2,dp)+helper(a-1,b-3,dp));\n }\n}\n// Upvote please !!", + "title": "808. Soup Servings", + "topic": "Stack" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "There are two types of soup: type A and type B . Initially, we have n ml of each type of soup. There are four kinds of operations: When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25 . If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. Note that we do not have an operation where all 100 ml's of soup B are used first. Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 50Output:0.62500Explanation:If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.", + "image": null + }, + { + "text": "Example 2: Input:n = 100Output:0.71875", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 62 ms (Top 34.5%) | Memory: 18.09 MB (Top 39.7%)\n\nclass Solution:\n def soupServings(self, n: int) -> float:\n if n > 4451: \n return 1.0\n n = (n + 24) // 25\n memo = dict()\n \n def dp(i, j):\n if (i, j) in memo:\n return memo[(i, j)]\n if i <= 0 and j <= 0: \n return 0.5\n if i <= 0: \n return 1.0\n if j <= 0: \n return 0.0\n memo[(i, j)] = 0.25 * (dp(i - 4, j) + dp(i - 3, j - 1) + dp(i - 2, j - 2) + dp(i - 1, j - 3))\n return memo[(i, j)]\n \n return dp(n, n)", + "title": "808. Soup Servings", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x . Notice that x does not have to be an element in nums . Return x if the array is special , otherwise, return -1 . It can be proven that if nums is special, the value for x is unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5]Output:2Explanation:There are 2 values (3 and 5) that are greater than or equal to 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0]Output:-1Explanation:No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,4,3,0,4]Output:3Explanation:There are 3 values that are greater than or equal to 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 88.84%) | Memory: 42.3 MB (Top 22.19%)\nclass Solution {\n public int specialArray(int[] nums) {\n int x = nums.length;\n int[] counts = new int[x+1];\n\n for(int elem : nums)\n if(elem >= x)\n counts[x]++;\n else\n counts[elem]++;\n\n int res = 0;\n for(int i = counts.length-1; i > 0; i--) {\n res += counts[i];\n if(res == i)\n return i;\n }\n\n return -1;\n }\n}", + "title": "1608. Special Array With X Elements Greater Than or Equal X", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x . Notice that x does not have to be an element in nums . Return x if the array is special , otherwise, return -1 . It can be proven that if nums is special, the value for x is unique . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,5]Output:2Explanation:There are 2 values (3 and 5) that are greater than or equal to 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0]Output:-1Explanation:No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,4,3,0,4]Output:3Explanation:There are 3 values that are greater than or equal to 3.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 23.2%) | Memory: 16.30 MB (Top 28.6%)\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(max(nums)+1):\n y=len(nums)-bisect.bisect_left(nums,i)\n if y==i:\n return i\n return -1\n\n \n ", + "title": "1608. Special Array With X Elements Greater Than or Equal X", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Special binary strings are binary strings with the following two properties: You are given a special binary string s . A move consists of choosing two consecutive, non-empty, special substrings of s , and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return the lexicographically largest resulting string possible after applying the mentioned operations on the string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of 0 's is equal to the number of 1 's.", + "Every prefix of the binary string has at least as many 1 's as 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"11011000\"Output:\"11100100\"Explanation:The strings \"10\" [occuring at s[1]] and \"1100\" [at s[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.", + "image": null + }, + { + "text": "Example 2: Input:s = \"10\"Output:\"10\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]=='1' else -1\n if balance==0:\n sublist.append(\"1\" + self.makeLargestSpecial(s[l+1:r])+ \"0\")\n l = r+1\n \n sublist.sort(reverse=True)\n return ''.join(sublist)", + "title": "761. Special Binary String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the number of special positions in mat . A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 100", + "mat[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[1,0,0],[0,0,1],[1,0,0]]Output:1Explanation:(1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.", + "image": "https://assets.leetcode.com/uploads/2021/12/23/special1.jpg" + }, + { + "text": "Example 2: Input:mat = [[1,0,0],[0,1,0],[0,0,1]]Output:3Explanation:(0, 0), (1, 1) and (2, 2) are special positions.", + "image": "https://assets.leetcode.com/uploads/2021/12/24/special-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSpecial(int[][] mat) {\n int count=0;\n for(int i=0;i int:\n def get_column_sum(col_idx):\n return sum(row[col_idx] for row in mat)\n\n special = 0\n for row in mat:\n if sum(row) == 1:\n col_idx = row.index(1)\n special += get_column_sum(col_idx) == 1\n\n return special\n", + "title": "1582. Special Positions in a Binary Matrix", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List spiralOrder(int[][] matrix) {\n List ans = new ArrayList<>();\n int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;\n\n while (top <= bottom && left <= right) \n {\n for (int i = left; i <= right; i++)\n ans.add(matrix[top][i]);\n top++;\n\n for (int i = top; i <= bottom; i++)\n ans.add(matrix[i][right]);\n right--;\n\n if (top <= bottom) {\n for (int i = right; i >= left; i--)\n ans.add(matrix[bottom][i]);\n bottom--;\n }\n\n if (left <= right) {\n for (int i = bottom; i >= top; i--)\n ans.add(matrix[i][left]);\n left++;\n }\n }\n return ans;\n }\n}", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n col, row = len(matrix[0]), len(matrix)\n l, t, r, b = 0, 0, col - 1, row - 1\n res = []\n while l <= r and t <= b:\n for i in range(l, r):\n res.append(matrix[t][i])\n for i in range(t, b):\n res.append(matrix[i][r])\n \n\t\t\t# Append the orphan left by the open interval\n if t == b:\n res.append(matrix[t][r])\n else:\n # From right to left at the bottom\n for i in range(r, l, -1):\n res.append(matrix[b][i])\n \n\t\t\t# Avoid duplicated appending if it is a square\n if l == r and t != b:\n res.append(matrix[b][r])\n else:\n # From bottom to top at the left\n for i in range(b, t, -1):\n res.append(matrix[i][l])\n l += 1\n t += 1\n r -= 1\n b -= 1\n\n return res\n", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer n , generate an n x n matrix filled with elements from 1 to n 2 in spiral order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[[1,2,3],[8,9,4],[7,6,5]]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.9 MB (Top 69.11%)\nclass Solution {\n public int[][] generateMatrix(int n) {\n int startingRow = 0;\n int endingRow = n-1;\n int startingCol = 0;\n int endingCol = n-1;\n\n int total = n*n;\n int element = 1;\n int[][] matrix = new int[n][n];\n\n while(element<=total){\n\n for(int i = startingCol; element<=total && i<=endingCol; i++){\n matrix[startingRow][i] = element;\n element++;\n }\n startingRow++;\n\n for(int i = startingRow; element<=total && i<=endingRow; i++){\n matrix[i][endingCol] = element;\n element++;\n }\n endingCol--;\n\n for(int i = endingCol; element<=total && i>=startingCol; i--){\n matrix[endingRow][i] = element;\n element++;\n }\n endingRow--;\n\n for(int i = endingRow; element<=total && i>=startingRow; i--){\n matrix[i][startingCol] = element;\n element++;\n }\n startingCol++;\n\n }\n\n return matrix;\n }\n}", + "title": "59. Spiral Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a positive integer n , generate an n x n matrix filled with elements from 1 to n 2 in spiral order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[[1,2,3],[8,9,4],[7,6,5]]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 84.25%) | Memory: 16.50 MB (Top 59.83%)\n\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n if not n:\n return []\n matrix = [[0 for _ in range(n)] for _ in range(n)]\n left, right, top, bottom, num = 0, n-1, 0, n-1, 1\n while left <= right and top <= bottom:\n for i in range(left, right+1):\n matrix[top][i] = num \n num += 1\n top += 1\n for i in range(top, bottom+1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left-1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top-1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n\n", + "title": "59. Spiral Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= rows, cols <= 100", + "0 <= rStart < rows", + "0 <= cStart < cols" + ], + "examples": [ + { + "text": "Example 1: Input:rows = 1, cols = 4, rStart = 0, cStart = 0Output:[[0,0],[0,1],[0,2],[0,3]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_1.png" + }, + { + "text": "Example 2: Input:rows = 5, cols = 6, rStart = 1, cStart = 4Output:[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n ans = [[rStart, cStart]]\n val = 1\n i, j = rStart, cStart\n def is_valid(i, j):\n if 0 <= i < rows and 0 <= j < cols:\n return True\n return False\n \n while True:\n if len(ans) == rows * cols:\n return ans\n \n # go right val times\n for _ in range(val):\n j+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go bottom val times\n for _ in range(val):\n i+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go left val+1 times\n for _ in range(val+1):\n j-=1\n if is_valid(i,j):\n ans.append([i,j])\n # go up val+1 times\n for _ in range(val+1):\n i-=1\n if is_valid(i,j):\n ans.append([i,j])\n val+=2\n", + "title": "885. Spiral Matrix III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: 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.\nNote that the remaining spaces in the matrix are filled with -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/09/ex1new.jpg" + }, + { + "text": "Example 2: 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.\nThe last space in the matrix is set to -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/11/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] spiralMatrix(int m, int n, ListNode head) {\n int[][] ans=new int[m][n];\n for(int[] arr:ans){\n Arrays.fill(arr,-1);\n }\n \n int rowBegin=0;\n int rowEnd=m-1;\n int columnBegin=0;\n int columnEnd=n-1;\n ListNode cur=head;\n \n \n while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){\n \n for(int i=columnBegin;i<=columnEnd && cur!=null;i++){\n if(cur!=null){\n ans[rowBegin][i]=cur.val;\n }\n \n cur=cur.next;\n \n \n }\n rowBegin++;\n for(int i=rowBegin;i<=rowEnd && cur!=null;i++){\n if(cur!=null){\n ans[i][columnEnd]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n columnEnd--;\n if(rowBegin<=rowEnd){\n for(int i=columnEnd;i>=columnBegin && cur!=null;i--){\n if(cur!=null){\n ans[rowEnd][i]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n rowEnd--;\n if(columnBegin<=columnEnd){\n for(int i=rowEnd;i>=rowBegin && cur!=null;i--){\n if(cur!=null){\n ans[i][columnBegin]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n columnBegin++;\n \n }\n return ans;\n \n }\n}\n", + "title": "2326. Spiral Matrix IV", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: 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.\nNote that the remaining spaces in the matrix are filled with -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/09/ex1new.jpg" + }, + { + "text": "Example 2: 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.\nThe last space in the matrix is set to -1.", + "image": "https://assets.leetcode.com/uploads/2022/05/11/ex2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2522 ms (Top 39.98%) | Memory: 66.3 MB (Top 18.63%)\nclass Solution:\n def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n num = m * n\n res = [[-1 for j in range(n)] for i in range(m)]\n x, y = 0, 0\n dx, dy = 1, 0\n while head:\n res[y][x] = head.val\n if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m or res[y+dy][x+dx] != -1:\n dx, dy = -dy, dx\n x = x + dx\n y = y + dy\n head = head.next\n return res", + "title": "2326. Spiral Matrix IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s , split it into some number of substrings such that: Return the maximum number of balanced strings you can obtain. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each substring is balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"RLRRLLRLRL\"Output:4Explanation:s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"RLRRRLLRLL\"Output:2Explanation:s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2ndand 5thsubstrings are not balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LLLLRRRR\"Output:1Explanation:s can be split into \"LLLLRRRR\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int balancedStringSplit(String s) {\n int nl = 0;\n int nr = 0;\n int count = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.substring(i,i+1).equals(\"L\")) ++nl;\n else ++nr;\n if (nr == nl) {\n ++count;\n }\n }\n return count;\n }\n}\n", + "title": "1221. Split a String in Balanced Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s , split it into some number of substrings such that: Return the maximum number of balanced strings you can obtain. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each substring is balanced." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"RLRRLLRLRL\"Output:4Explanation:s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.", + "image": null + }, + { + "text": "Example 2: Input:s = \"RLRRRLLRLL\"Output:2Explanation:s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2ndand 5thsubstrings are not balanced.", + "image": null + }, + { + "text": "Example 3: Input:s = \"LLLLRRRR\"Output:1Explanation:s can be split into \"LLLLRRRR\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n r_count=l_count=t_count=0\n for i in s:\n if i=='R':\n r_count+=1\n elif i=='L':\n l_count+=1\n if r_count==l_count:\n t_count+=1\n r_count=0\n l_count=0\n continue\n return t_count\n", + "title": "1221. Split a String in Balanced Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the maximum number of unique substrings that the given string can be split into . You can split string s into any list of non-empty substrings , where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababccc\"Output:5Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:2Explanation: One way to split maximally is ['a', 'ba'].", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\"Output:1Explanation: It is impossible to split the string any further.", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n int max = 0;\n public int maxUniqueSplit(String s) {\n int n = s.length();\n backtrack(s, 0, new HashSet());\n return max;\n }\n public void backtrack(String s, int start, Set h) {\n if(start == s.length()) {\n max = Math.max(max, h.size());\n }\n String res = \"\";\n \n for(int i = start;i < s.length();i++) {\n res += s.charAt(i);\n if(h.contains(res)) continue;\n h.add(res);\n backtrack(s, i+1, h);\n h.remove(res);\n }\n }\n}\n", + "title": "1593. Split a String Into the Max Number of Unique Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return the maximum number of unique substrings that the given string can be split into . You can split string s into any list of non-empty substrings , where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique . A substring is a contiguous sequence of characters within a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lower case English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababccc\"Output:5Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:2Explanation: One way to split maximally is ['a', 'ba'].", + "image": null + }, + { + "text": "Example 3: Input:s = \"aa\"Output:1Explanation: It is impossible to split the string any further.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ans, n = 0, len(s)\n def dfs(i, cnt, visited):\n nonlocal ans, n\n if i == n: ans = max(ans, cnt); return # stop condition\n for j in range(i+1, n+1): \n if s[i:j] in visited: continue # avoid re-visit/duplicates\n visited.add(s[i:j]) # update visited set\n dfs(j, cnt+1, visited) # backtracking\n visited.remove(s[i:j]) # recover visited set for next possibility\n dfs(0, 0, set()) # function call\n return ans\n", + "title": "1593. Split a String Into the Max Number of Unique Substrings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums that is sorted in non-decreasing order . Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Return true if you can split nums according to the above conditions, or false otherwise . A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [ 1 ,2, 3 ,4, 5 ] while [1,3,2] is not). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).", + "All subsequences have a length of 3 or more ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,5]Output:trueExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3,4,4,5,5]Output:trueExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4,5]Output:falseExplanation:It is impossible to split nums into consecutive increasing subsequences of length 3 or more.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 50 ms (Top 12.39%) | Memory: 45.60 MB (Top 38.5%)\n\nclass Solution {\n public boolean isPossible(int[] nums) {\n Map possibility = new HashMap<>();\n Map counts = new HashMap<>();\n for(int num:nums){\n counts.put(num,counts.getOrDefault(num,0)+1);\n }\n for(int num:nums){\n if(counts.get(num)==0)continue;\n if(possibility.getOrDefault(num,0)>0){\n possibility.put(num,possibility.getOrDefault(num,0)-1);\n possibility.put(num+1,possibility.getOrDefault(num+1,0)+1);\n }\n else if( counts.getOrDefault(num+1,0)>0 && counts.getOrDefault(num+2,0)>0 ){\n possibility.put(num+3,possibility.getOrDefault(num+3,0)+1);\n counts.put(num+1,counts.getOrDefault(num+1,0)-1);\n counts.put(num+2,counts.getOrDefault(num+2,0)-1);\n }\n else{\n return false;\n }\n counts.put(num,counts.get(num)-1);\n }\n return true;\n }\n}\n", + "title": "659. Split Array into Consecutive Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums that is sorted in non-decreasing order . Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: Return true if you can split nums according to the above conditions, or false otherwise . A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [ 1 ,2, 3 ,4, 5 ] while [1,3,2] is not). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).", + "All subsequences have a length of 3 or more ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,3,4,5]Output:trueExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,3,4,4,5,5]Output:trueExplanation:nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,4,5]Output:falseExplanation:It is impossible to split nums into consecutive increasing subsequences of length 3 or more.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\n from collections import defaultdict\n\n def isPossible(self, nums):\n # If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.\n if len(nums) < 3:\n return False\n\n # 'count' dictionary stores the frequency of each number in the input array.\n count = defaultdict(int)\n\n # 'tails' dictionary stores the number of subsequences that end at a certain number.\n tails = defaultdict(int)\n\n # Populate the 'count' dictionary with the frequency of each number.\n for num in nums:\n count[num] += 1\n\n # Iterate through the input array.\n for num in nums:\n # If the count of the current number is 0, it means this number has already been used in a subsequence.\n if count[num] == 0:\n continue\n # If there is a subsequence that ends with the current number minus 1,\n # it means we can extend that subsequence by adding the current number.\n elif tails[num - 1] > 0:\n tails[num - 1] -= 1 # Decrease the count of the tails that end with the current number minus 1.\n tails[num] += 1 # Increase the count of the tails that end with the current number.\n # If there are enough numbers after the current number to form a subsequence,\n # create a new subsequence starting with the current number.\n elif count[num + 1] > 0 and count[num + 2] > 0:\n count[num + 1] -= 1 # Decrease the count of the next number.\n count[num + 2] -= 1 # Decrease the count of the number after the next number.\n tails[num + 2] += 1 # Increase the count of the tails that end with the number after the next number.\n else:\n # If we can't extend an existing subsequence or start a new one, return False.\n return False\n\n # Decrease the count of the current number since it's used in a subsequence.\n count[num] -= 1\n\n # If the function successfully iterates through the entire array, return True.\n return True\n", + "title": "659. Split Array into Consecutive Subsequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string of digits num , such as \"123456579\" . We can split it into a Fibonacci-like sequence [123, 456, 579] . Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num , or return [] if it cannot be done. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= f[i] < 2 31 , (that is, each integer fits in a 32-bit signed integer type),", + "f.length >= 3 , and", + "f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1101111\"Output:[11,0,11,11]Explanation:The output [110, 1, 111] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:num = \"112358130\"Output:[]Explanation:The task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0123\"Output:[]Explanation:Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 97.83%) | Memory: 41.60 MB (Top 63.04%)\n\nclass Solution {\n List list=new ArrayList<>();\n public List splitIntoFibonacci(String num) {\n \n if(backtrack(num,0)) return list;\n else return new ArrayList();\n \n }\n boolean backtrack(String num,int index){\n if(index==num.length()) return list.size()>2;\n \n int n=0;\n for(int i=index;i= 3 , and", + "f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"1101111\"Output:[11,0,11,11]Explanation:The output [110, 1, 111] would also be accepted.", + "image": null + }, + { + "text": "Example 2: Input:num = \"112358130\"Output:[]Explanation:The task is impossible.", + "image": null + }, + { + "text": "Example 3: Input:num = \"0123\"Output:[]Explanation:Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.", + "image": null + } + ], + "follow_up": null, + "solution": "MAX=2**31\ndef consume_tail(current, s):\n # Following the definition of the fibonacci sequence\n # we know that the sum of the last two values in our \n # `current` list determines the next value in the sequence.\n # So that value, our \"target\", is what we're looking for next in\n # `s`.\n target = current[-1] + current[-2]\n \n if target > MAX:\n return False\n \n sTarget = str(target) \n # If the next value in the fibonacci sequence\n # is found at the beginning of s\n # we can continue to process the remaining \n # portion of the string.\n if s.find(sTarget) == 0:\n current.append(target)\n else:\n return False\n \n if sTarget != s:\n return consume_tail(current, s[len(sTarget):])\n \n return current\n \n\nclass Solution: \n def splitIntoFibonacci(self, num: str) -> List[int]:\n \n # Identify candidate for the first\n # number in fibonacci sequence\n for i in range(len(num)):\n if num[0] == \"0\" and i > 0:\n break\n \n first = num[0:i+1]\n \n # If our current candidate for the first number\n # of the sequence is already larger that our \n # maximum value in the spec, don't bother doing anymore work.\n if int(first) > MAX:\n return []\n \n tail = num[i+1:]\n \n # Identify candidate for the scond\n # number in fibonacci sequence\n for j in range(len(tail)):\n if tail[0] == \"0\" and j > 0:\n break\n \n second = tail[0:j+1]\n if int(second) > MAX:\n break\n \n # With our current candidates (first and second),\n # we can consume the remaining portion of the string (tail[j+1:])\n # to determine if it contains the correct values for a fibonacci sequence\n # beginning with [first, second]\n result = consume_tail([int(first), int(second)], tail[j+1:])\n if result:\n return result\n return []\n", + "title": "842. Split Array into Fibonacci Sequence", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array nums which consists of non-negative integers and an integer m , you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 10^6", + "1 <= m <= min(50, nums.length)" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [7,2,5,10,8], m = 2Output:18Explanation:There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8],\nwhere the largest sum among the two subarrays is only 18.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,4,5], m = 2Output:9", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,4,4], m = 3Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n int[] nums;\n public int splitArray(int[] nums, int m) {\n this.nums = nums;\n int low = 0, high = 0, min = Integer.MAX_VALUE;\n for(int i=0;i int:\n lo, hi = max(nums), sum(nums)\n while lo < hi:\n mid = (lo+hi)//2\n tot, cnt = 0, 1\n for num in nums:\n if tot+num<=mid: \n tot += num\n else:\n tot = num\n cnt += 1\n if cnt>m: lo = mid+1\n else: hi = mid\n return hi\n", + "title": "410. Split Array Largest Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B) . Return true if it is possible to achieve that and false otherwise. Note that for an array arr , average(arr) is the sum of all the elements of arr over the length of arr . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 30", + "0 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7,8]Output:trueExplanation:We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean splitArraySameAverage(int[] nums) {\n int n = nums.length, sum = Arrays.stream(nums).sum();\n Set[] a = new HashSet[n/2+1];\n Set[] b = new HashSet[n/2+2];\n Arrays.setAll(a, o -> new HashSet<>());\n Arrays.setAll(b, o -> new HashSet<>());\n gen(0, n/2, 0, 0, nums, a);\n gen(n/2, n, 0, 0, nums, b);\n for (int i = 0; i < a.length; i++){ // i = num of elements selected from A\n for (int j = 0; j < b.length; j++){ // j = num of elements selected from B\n if (i+j>0 && i+j < n && sum*(i+j)%n == 0){\n for (int cur : a[i]){ // do Two Sum\n if (b[j].contains(sum*(i+j)/n-cur)){\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n \n private void gen(int cur, int n, int bits, int sum, int[] nums, Set[] set){\n set[bits].add(sum);\n if (cur < n){\n gen(cur+1, n, bits+1, sum+nums[cur], nums, set);\n gen(cur+1, n, bits, sum, nums, set);\n }\n }\n}\n", + "title": "805. Split Array With Same Average", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B) . Return true if it is possible to achieve that and false otherwise. Note that for an array arr , average(arr) is the sum of all the elements of arr over the length of arr . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 30", + "0 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7,8]Output:trueExplanation:We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def splitArraySameAverage(self, A: List[int]) -> bool:\n A.sort()\n DP=[set() for _ in range(len(A)//2+1)] #DP[i] stores the all available sum with i items in a bracket\n all_sum=sum(A)\n DP[0]=set([0])\n for item in A: #iterate over items in the list\n for count in range(len(DP)-2,-1,-1): # iterate backwards w.r.t. the bracket size\n if len(DP[count])>0: # if DP[i] is not empty, then update DP[i+1] by adding the current item into all sums in DP[i]\n for a in DP[count]:\n DP[count+1].add(a+item)\n for size in range(1,len(DP)):\n if all_sum*size/len(A) in DP[size]:\n return True\n return False", + "title": "805. Split Array With Same Average", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5Output:[[1],[2],[3],[],[]]Explanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3Output:[[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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 69.17%) | Memory: 43.9 MB (Top 66.95%)\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n ListNode[] arr=new ListNode[k];\n\n if(k<2 || head==null || head.next==null){\n arr[0]=head;\n return arr;\n }\n\n ListNode temp=head;\n int len=1;\n while(temp.next!=null){\n len++;\n temp=temp.next;\n }\n\n int partition= len/k; //no of part 3\n int extra=len%k; //extra node 1 0\n\n ListNode curr=head;\n ListNode prev=null;\n int index=0;\n while(head!=null){\n arr[index++]=curr;\n for(int i=0; i0){\n prev=curr;\n curr=curr.next;\n extra--;\n }\n head=curr;\n prev.next=null;\n\n }\n return arr;\n }\n}", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5Output:[[1],[2],[3],[],[]]Explanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3Output:[[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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 81.38%) | Memory: 14.5 MB (Top 12.03%)\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n length = 0\n cur = head\n while cur:\n length += 1\n cur = cur.next\n # DON'T do following since this makes head become null\n # while head:\n # length += 1\n # head = head.next\n\n # calculate the base size and the number of parts contain extra number\n size, extra = length // k, length % k\n\n # create empty list to store split parts\n res = [[] for _ in range(k)]\n\n # use two ptrs to split parts\n prev, cur = None, head\n\n for i in range(k):\n res[i] = cur\n # if this part contains extra number, it has (size+1) number\n for j in range(size + (1 if extra > 0 else 0)):\n prev, cur = cur, cur.next\n if prev: prev.next = None\n extra -= 1\n\n return res", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index , splitting a into two strings: a prefix and a suffix where a = a prefix + a suffix , and splitting b into two strings: b prefix and b suffix where b = b prefix + b suffix . Check if a prefix + b suffix or b prefix + a suffix forms a palindrome. When you split a string s into s prefix and s suffix , either s suffix or s prefix is allowed to be empty. For example, if s = \"abc\" , then \"\" + \"abc\" , \"a\" + \"bc\" , \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false . Notice that x + y denotes the concatenation of strings x and y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^5", + "a.length == b.length", + "a and b consist of lowercase English letters" + ], + "examples": [ + { + "text": "Example 1: Input:a = \"x\", b = \"y\"Output:trueExplaination:If either a or b are palindromes the answer is true since you can split in the following way:\naprefix= \"\", asuffix= \"x\"\nbprefix= \"\", bsuffix= \"y\"\nThen, aprefix+ bsuffix= \"\" + \"y\" = \"y\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:a = \"xbdef\", b = \"xecab\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:a = \"ulacfd\", b = \"jizalu\"Output:trueExplaination:Split them at index 3:\naprefix= \"ula\", asuffix= \"cfd\"\nbprefix= \"jiz\", bsuffix= \"alu\"\nThen, aprefix+ bsuffix= \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 100.0%) | Memory: 45.60 MB (Top 14.69%)\n\nclass Solution {\n public boolean checkPalindromeFormation(String a, String b) {\n // either way of split should give us a palindrome\n return cut(a, b) || cut(b, a);\n }\n\n // method to match letters from both ends\n private boolean cut(String a, String b) {\n int i = 0, j = a.length() - 1;\n // converge from both ends till we have same letters\n while (i < j && a.charAt(i) == b.charAt(j)) {\n i++; j--;\n }\n\n // the case when we surpassed the mid point from both ends\n if (i >= j) return true;\n // the case when there is still a substring left in between\n // or say we didn't reach the mid point\n // we will check if that substring is a palindrome or not\n return isPalindrome(a, i, j) || isPalindrome(b, i, j);\n }\n\n // method to check if a string is palindrome\n private boolean isPalindrome(String s, int i, int j) {\n while (i < j) {\n if (s.charAt(i++) != s.charAt(j--)) {\n return false;\n }\n }\n\n return true;\n }\n}\n", + "title": "1616. Split Two Strings to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index , splitting a into two strings: a prefix and a suffix where a = a prefix + a suffix , and splitting b into two strings: b prefix and b suffix where b = b prefix + b suffix . Check if a prefix + b suffix or b prefix + a suffix forms a palindrome. When you split a string s into s prefix and s suffix , either s suffix or s prefix is allowed to be empty. For example, if s = \"abc\" , then \"\" + \"abc\" , \"a\" + \"bc\" , \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false . Notice that x + y denotes the concatenation of strings x and y . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^5", + "a.length == b.length", + "a and b consist of lowercase English letters" + ], + "examples": [ + { + "text": "Example 1: Input:a = \"x\", b = \"y\"Output:trueExplaination:If either a or b are palindromes the answer is true since you can split in the following way:\naprefix= \"\", asuffix= \"x\"\nbprefix= \"\", bsuffix= \"y\"\nThen, aprefix+ bsuffix= \"\" + \"y\" = \"y\", which is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:a = \"xbdef\", b = \"xecab\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:a = \"ulacfd\", b = \"jizalu\"Output:trueExplaination:Split them at index 3:\naprefix= \"ula\", asuffix= \"cfd\"\nbprefix= \"jiz\", bsuffix= \"alu\"\nThen, aprefix+ bsuffix= \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 271 ms (Top 15.83%) | Memory: 15.4 MB (Top 41.73%)\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n def pal(x):\n return x == x[::-1]\n if pal(a) or pal(b): return True\n # either grow from inside to outside, or vice versa\n ina = len(a)-1\n inb = 0\n outa = 0\n outb = len(b)-1\n\n while a[ina] == b[inb]:\n ina -= 1\n inb += 1\n if ina <= inb:\n return True # short circuit found break point\n # jump into each string now!?\n # is a or b a palindrome in this portion from inb to ina\n if pal(a[inb:ina+1]) or pal(b[inb:ina+1]):\n return True # either one is breakpoint, so check remainder is palindrome\n\n while a[outa] == b[outb]:\n outa += 1\n outb -= 1\n if outa >= outb:\n return True\n if pal(a[outa:outb+1]) or pal(b[outa:outb+1]):\n return True # either one is breakpoint, so check remainder\n\n return False", + "title": "1616. Split Two Strings to Make Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1 . Return true if it is possible to split s ​​​​​​ as described above , or false otherwise. A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89] . The values are in descending order and adjacent values differ by 1 , so this way is valid.", + "Another example, the string s = \"001\" can be split into [\"0\", \"01\"] , [\"00\", \"1\"] , or [\"0\", \"0\", \"1\"] . However all the ways are invalid because they have numerical values [0,1] , [0,1] , and [0,0,1] respectively, all of which are not in descending order." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1234\"Output:falseExplanation:There is no valid way to split s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"050043\"Output:trueExplanation:s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"9080701\"Output:falseExplanation:There is no valid way to split s.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean splitString(String s) {\n return isRemainingValid(s, null);\n }\n private boolean isRemainingValid(String s, Long previous) {\n long current =0;\n for(int i=0;i= 10000000000L) return false; // Avoid overflow\n if(previous == null) {\n if (isRemainingValid(s.substring(i+1), current)) \n return true;\n } else if(current == previous - 1 && (i==s.length()-1 || isRemainingValid(s.substring(i+1), current)))\n return true;\n }\n return false;\n }\n}\n", + "title": "1849. Splitting a String Into Descending Consecutive Values", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1 . Return true if it is possible to split s ​​​​​​ as described above , or false otherwise. A substring is a contiguous sequence of characters in a string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89] . The values are in descending order and adjacent values differ by 1 , so this way is valid.", + "Another example, the string s = \"001\" can be split into [\"0\", \"01\"] , [\"00\", \"1\"] , or [\"0\", \"0\", \"1\"] . However all the ways are invalid because they have numerical values [0,1] , [0,1] , and [0,0,1] respectively, all of which are not in descending order." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1234\"Output:falseExplanation:There is no valid way to split s.", + "image": null + }, + { + "text": "Example 2: Input:s = \"050043\"Output:trueExplanation:s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"9080701\"Output:falseExplanation:There is no valid way to split s.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 66 ms (Top 24.00%) | Memory: 13.8 MB (Top 70.18%)\nclass Solution:\n def splitString(self, s: str, last_val: int = None) -> bool:\n # Base case, remaining string is a valid solution\n if last_val and int(s) == last_val - 1:\n return True\n\n # Iterate through increasingly larger slices of s\n for i in range(1, len(s)):\n cur = int(s[:i])\n # If current slice is equal to last_val - 1, make\n # recursive call with remaining string and updated last_val\n if last_val is None or cur == last_val - 1:\n if self.splitString(s[i:], cur):\n return True\n\n return False", + "title": "1849. Splitting a String Into Descending Consecutive Values", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-negative integer x , compute and return the square root of x . Since the return type is an integer, the decimal digits are truncated , and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 4Output:2", + "image": null + }, + { + "text": "Example 2: Input:x = 8Output:2Explanation:The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 34 ms (Top 10.30%) | Memory: 41.3 MB (Top 62.51%)\n\nclass Solution {\n public int mySqrt(int x) {\n long answer = 0;\n while (answer * answer <= x) {\n answer += 1;\n }\n return (int)answer - 1;\n }\n}", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a non-negative integer x , compute and return the square root of x . Since the return type is an integer, the decimal digits are truncated , and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 4Output:2", + "image": null + }, + { + "text": "Example 2: Input:x = 8Output:2Explanation:The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def mySqrt(self, x: int) -> int:\n beg =0\n end =x\n while beg <=end:\n mid = (beg+end)//2\n sqr = mid*mid\n if sqr == x:\n return mid\n elif sqr < x:\n beg = mid+1\n else:\n end = mid-1\n return end\n \n", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-4,-1,0,3,10]Output:[0,1,9,16,100]Explanation:After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-7,-3,2,3,11]Output:[4,9,9,49,121]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 87.02%) | Memory: 54.8 MB (Top 82.69%)\nclass Solution {\n public int[] sortedSquares(int[] nums) {\n int s=0;\n int e=nums.length-1;\n int p=nums.length-1;\n int[] a=new int[nums.length];\n while(s<=e){\n if(nums[s]*nums[s]>nums[e]*nums[e]){\n a[p--]=nums[s]*nums[s];\n s++;\n }\n else{\n a[p--]=nums[e]*nums[e];\n e--;\n }\n }\n return a;\n }\n}", + "title": "977. Squares of a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-4,-1,0,3,10]Output:[0,1,9,16,100]Explanation:After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].", + "image": null + }, + { + "text": "Example 2: Input:nums = [-7,-3,2,3,11]Output:[4,9,9,49,121]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n l,r = 0, len(nums)-1\n pointer = 0\n arr = [0] *len(nums)\n pointer = r\n while l<=r:\n if abs(nums[r]) > abs(nums[l]):\n arr[pointer] = nums[r] **2\n r-=1\n pointer-=1\n else:\n arr[pointer] = nums[l] **2\n l+=1\n pointer-=1\n \n \n return arr\n \n \n \n", + "title": "977. Squares of a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth . We want to fit the stamps such that they follow the given restrictions and requirements : Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[r].length", + "1 <= m, n <= 10^5", + "1 <= m * n <= 2 * 10^5", + "grid[r][c] is either 0 or 1 .", + "1 <= stampHeight, stampWidth <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3Output:trueExplanation:We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/ex1.png" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2Output:falseExplanation:There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/11/03/ex2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]:\n ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))]\n \n for row in range(len(grid)):\n for col in range(1, len(grid[0])):\n ps[row][col] = ps[row][col-1] + grid[row][col]\n \n for row in range(1, len(grid)):\n for col in range(len(grid[0])):\n ps[row][col] = ps[row-1][col] + ps[row][col]\n \n return ps\n\t\t\t\n def sumRegion(self, ps, row1: int, col1: int, row2: int, col2: int) -> int:\n ans = 0\n if row1 == 0 and col1 == 0:\n ans = ps[row2][col2]\n elif row1 == 0:\n ans = ps[row2][col2] - ps[row2][col1-1]\n elif col1 == 0:\n ans = ps[row2][col2] - ps[row1-1][col2]\n else:\n ans = ps[row2][col2] - ps[row1-1][col2] - ps[row2][col1-1] + ps[row1-1][col1-1]\n return ans\n\n def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:\n diff = [[0 for col in range(len(grid[0])+1)]for row in range(len(grid)+1)]\n \n ps = self.prefix_sum(grid)\n cover = 0\n \n for row in range(len(grid)-(stampHeight-1)):\n for col in range(len(grid[0])-(stampWidth-1)):\n sub_sum = self.sumRegion(ps, row, col, row+stampHeight-1, col+stampWidth-1)\n if sub_sum == 0:\n diff[row][col] += 1\n diff[row][col+stampWidth] -= 1\n diff[row+stampHeight][col] -= 1\n diff[row+stampHeight][col+stampWidth] = 1\n pref_diff = self.prefix_sum(diff)\n m, n = len(grid), len(grid[0])\n \n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 0 and pref_diff[row][col] == 0: return False \n \n return True\n", + "title": "2132. Stamping the Grid", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two strings stamp and target . Initially, there is a string s of length target.length with all s[i] == '?' . In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp . We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn . If we cannot obtain target from s within 10 * target.length turns, return an empty array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if stamp = \"abc\" and target = \"abcba\" , then s is \"?????\" initially. In one turn you can: place stamp at index 0 of s to obtain \"abc??\" , place stamp at index 1 of s to obtain \"?abc?\" , or place stamp at index 2 of s to obtain \"??abc\" . Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s ).", + "place stamp at index 0 of s to obtain \"abc??\" ,", + "place stamp at index 1 of s to obtain \"?abc?\" , or", + "place stamp at index 2 of s to obtain \"??abc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:stamp = \"abc\", target = \"ababc\"Output:[0,2]Explanation:Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.", + "image": null + }, + { + "text": "Example 2: Input:stamp = \"abca\", target = \"aabcaca\"Output:[3,0,1]Explanation:Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] movesToStamp(String stamp, String target) {\n \n /*\n * Intitution:\n * Instead of creating target string from intial state,\n * create the intial state from the target string.\n * - take a window of stamp length\n * - reverse that window to the intail state \n * current state -> abcdefgh, window = def, \n * next state -> abc???gh \n *\n */\n \n int sLen = stamp.length();\n int tLen = target.length();\n \n //it save the index of reversed charcacter\n Queue reversedCharIndices= new LinkedList();\n \n //it mark Character of target, as reversed\n boolean[] isReversedCharOfThisIndex = new boolean[tLen];\n \n Stack stack = new Stack();\n \n List widowList = new ArrayList();\n \n for(int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++){\n \n Set matched = new HashSet();\n Set notMatched = new HashSet();\n \n for(int j = 0; j < sLen; j++){\n \n //char index of current window of the target\n int charIndex = windowStartIndex + j;\n \n if(stamp.charAt(j) == target.charAt(charIndex)){\n matched.add(charIndex);\n } else {\n notMatched.add(charIndex);\n }\n }\n \n //add the window\n widowList.add(new Window(matched, notMatched));\n \n //when all char of current window is matched with \n if(notMatched.isEmpty()){\n stack.push(windowStartIndex);\n \n for(int index : matched){\n if(!isReversedCharOfThisIndex[index]){\n \n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n \n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n \n }\n }\n \n \n \n //get all char index, one by once\n //see the impact of reverse char of this index, in ano\n while(!reversedCharIndices.isEmpty()){\n int reversedCharIndex = reversedCharIndices.remove();\n \n int start = Math.max(0, reversedCharIndex - sLen + 1);\n int end = Math.min(reversedCharIndex, tLen - sLen);\n \n for(int windowIndex = start; windowIndex <= end; windowIndex++){\n \n if(widowList.get(windowIndex).notMatched.contains(reversedCharIndex)){\n \n \n //as this char is reversed in another window\n //remove this char index from current window, \n widowList.get(windowIndex).notMatched.remove(reversedCharIndex);\n \n if(widowList.get(windowIndex).notMatched.isEmpty()){\n \n //as all of charcater reversed of current window\n //now add current window index\n stack.push(windowIndex);\n \n for(int index : widowList.get(windowIndex).matched){\n \n if(!isReversedCharOfThisIndex[index]){\n\n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n\n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n }\n }\n \n }\n }\n \n \n for(boolean reversed : isReversedCharOfThisIndex){\n if(!reversed){\n return new int[0];\n }\n }\n \n int i = 0;\n int[] result = new int[stack.size()];\n while(!stack.empty()){\n result[i++] = stack.pop();\n }\n \n \n return result;\n \n }\n}\n\nclass Window {\n Set matched;\n Set notMatched;\n \n public Window(Set matched, Set notMatched){\n this.matched = matched;\n this.notMatched = notMatched;\n }\n}\n", + "title": "936. Stamping The Sequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two strings stamp and target . Initially, there is a string s of length target.length with all s[i] == '?' . In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp . We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn . If we cannot obtain target from s within 10 * target.length turns, return an empty array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if stamp = \"abc\" and target = \"abcba\" , then s is \"?????\" initially. In one turn you can: place stamp at index 0 of s to obtain \"abc??\" , place stamp at index 1 of s to obtain \"?abc?\" , or place stamp at index 2 of s to obtain \"??abc\" . Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s ).", + "place stamp at index 0 of s to obtain \"abc??\" ,", + "place stamp at index 1 of s to obtain \"?abc?\" , or", + "place stamp at index 2 of s to obtain \"??abc\" ." + ], + "examples": [ + { + "text": "Example 1: Input:stamp = \"abc\", target = \"ababc\"Output:[0,2]Explanation:Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.", + "image": null + }, + { + "text": "Example 2: Input:stamp = \"abca\", target = \"aabcaca\"Output:[3,0,1]Explanation:Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def movesToStamp(self, S: str, T: str) -> List[int]:\n if S == T: return [0]\n S, T = list(S), list(T)\n slen, tlen = len(S), len(T) - len(S) + 1\n ans, tdiff, sdiff = [], True, True\n while tdiff:\n tdiff = False\n for i in range(tlen):\n sdiff = False\n for j in range(slen):\n if T[i+j] == \"*\": continue\n if T[i+j] != S[j]: break\n sdiff = True\n else: \n if sdiff:\n tdiff = True\n for j in range(i, i + slen): T[j] = \"*\"\n ans.append(i)\n for i in range(len(T)):\n if T[i] != \"*\": return []\n return reversed(ans)\n", + "title": "936. Stamping The Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a large sample of integers in the range [0, 255] . Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample. Calculate the following statistics: Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode] . Answers within 10 -5 of the actual answer will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "minimum : The minimum element in the sample.", + "maximum : The maximum element in the sample.", + "mean : The average of the sample, calculated as the total sum of all elements divided by the total number of elements.", + "median : If the sample has an odd number of elements, then the median is the middle element once the sample is sorted. If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.", + "If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.", + "If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.", + "mode : The number that appears the most in the sample. It is guaranteed to be unique ." + ], + "examples": [ + { + "text": "Example 1: Input:count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]Output:[1.00000,3.00000,2.37500,2.50000,3.00000]Explanation:The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.", + "image": null + }, + { + "text": "Example 2: Input:count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]Output:[1.00000,4.00000,2.18182,2.00000,1.00000]Explanation:The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double[] sampleStats(int[] count) {\n double[]ans=new double[5];\n ans[0]=-1;\n ans[1]=-1;\n int place=0;\n while(ans[0]==-1){\n if(count[place]>0)\n ans[0]=place;\n place++;\n }\n place=count.length-1;\n while(ans[1]==-1){\n if(count[place]>0)\n ans[1]=place;\n place--;\n }\n int countEl=count[0];\n int max=count[0];\n for(int i=1;imax){\n max=count[i];\n ans[4]=i;\n }\n }\n for(int i=0;i0){\n double tmp=count[i];\n tmp/=countEl;\n ans[2]+=tmp*i;\n }\n }\n place=0;\n int whereToStop=0;\n while(whereToStopmodev:modev,mode=n,i\n acc,cnt=acc+n*i,cnt+n\n \n midCnt,cc,midv,prei=cnt//2,0,0,i\n for i,n in enumerate(count):\n if n==0:continue\n if cc+n<=midCnt:\n cc,prei=cc+n,i\n continue\n if cnt%2==1:midv=i\n else:midv=(prei+i)/2.0 if cc==midCnt else i\n break\n return (minv,maxv,acc/cnt,midv,mode) \n", + "title": "1093. Statistics from a Large Sample", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n . You are also given an integer startValue representing the value of the start node s , and a different integer destValue representing the value of the destination node t . Find the shortest path starting from node s and ending at node t . Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L' , 'R' , and 'U' . Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'L' means to go from a node to its left child node.", + "'R' means to go from a node to its right child node.", + "'U' means to go from a node to its parent node." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6Output:\"UURL\"Explanation:The shortest path is: 3 → 1 → 5 → 2 → 6.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg1.png" + }, + { + "text": "Example 2: Input:root = [2,1], startValue = 2, destValue = 1Output:\"L\"Explanation:The shortest path is: 2 → 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) {\n if(currNode == null) return false;\n if(currNode.val == destVal) return true;\n if(DFS(currNode.left, path, destVal)) path.append(\"L\");\n else if(DFS(currNode.right, path, destVal)) path.append(\"R\");\n return path.length() > 0;\n }\n \n public String getDirections(TreeNode root, int startValue, int destValue) {\n StringBuilder startToRoot = new StringBuilder();\n StringBuilder endToRoot = new StringBuilder();\n \n DFS(root, startToRoot, startValue);\n DFS(root, endToRoot, destValue);\n \n int i = startToRoot.length(), j = endToRoot.length();\n int cnt = 0;\n while(i > 0 && j > 0 && startToRoot.charAt(i-1) == endToRoot.charAt(j-1)) {\n cnt++; i--; j--;\n }\n \n String sPath = \"U\".repeat(startToRoot.length() - cnt);\n String ePath = endToRoot.reverse().toString().substring(cnt, endToRoot.length());\n \n return sPath + ePath;\n }\n}\n", + "title": "2096. Step-By-Step Directions From a Binary Tree Node to Another", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n . You are also given an integer startValue representing the value of the start node s , and a different integer destValue representing the value of the destination node t . Find the shortest path starting from node s and ending at node t . Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L' , 'R' , and 'U' . Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'L' means to go from a node to its left child node.", + "'R' means to go from a node to its right child node.", + "'U' means to go from a node to its parent node." + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6Output:\"UURL\"Explanation:The shortest path is: 3 → 1 → 5 → 2 → 6.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg1.png" + }, + { + "text": "Example 2: Input:root = [2,1], startValue = 2, destValue = 1Output:\"L\"Explanation:The shortest path is: 2 → 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/15/eg2.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n def find(n: TreeNode, val: int, path: List[str]) -> bool:\n if n.val == val:\n return True\n if n.left and find(n.left, val, path):\n path += \"L\"\n elif n.right and find(n.right, val, path):\n path += \"R\"\n return path\n s, d = [], []\n find(root, startValue, s)\n find(root, destValue, d)\n while len(s) and len(d) and s[-1] == d[-1]:\n s.pop()\n d.pop()\n return \"\".join(\"U\" * len(s)) + \"\".join(reversed(d))\n", + "title": "2096. Step-By-Step Directions From a Binary Tree Node to Another", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed integer array nums . In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length . Return the number of steps performed until nums becomes a non-decreasing array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,4,4,7,3,6,11,8,5,11]Output:3Explanation:The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,7,7,13]Output:0Explanation:nums is already a non-decreasing array. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n \n \n public int totalSteps(int[] nums) {\n \n int n = nums.length;\n int ans = 0;\n \n Stack> st = new Stack();\n \n st.push(new Pair(nums[n-1],0));\n \n \n for(int i=n-2;i>=0;i--)\n {\n int count = 0;\n \n while(!st.isEmpty() && nums[i] > st.peek().getKey())\n {\n count = Math.max(count+1 , st.peek().getValue() );\n st.pop();\n }\n \n ans = Math.max(ans , count);\n st.push(new Pair(nums[i],count));\n }\n \n return ans;\n \n }\n}\n", + "title": "2289. Steps to Make Array Non-decreasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length . Return the number of steps performed until nums becomes a non-decreasing array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,3,4,4,7,3,6,11,8,5,11]Output:3Explanation:The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,7,7,13]Output:0Explanation:nums is already a non-decreasing array. Therefore, we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalSteps(self, nums: List[int]) -> int:\n st = []\n ans = 0\n for i in nums:\n t = 0\n while st and st[-1][0] <= i:\n t = max(t, st.pop()[1])\n x = 0 \n if st: \n x = t+1 \n st.append([i, x])\n ans = max(ans, x)\n return ans\n", + "title": "2289. Steps to Make Array Non-decreasing", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given n different types of stickers . Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target . If the task is impossible, return -1 . Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == stickers.length", + "1 <= n <= 50", + "1 <= stickers[i].length <= 10", + "1 <= target.length <= 15", + "stickers[i] and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"Output:3Explanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.", + "image": null + }, + { + "text": "Example 2: Input:stickers = [\"notice\",\"possible\"], target = \"basicbasic\"Output:-1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n HashMap>map;\n public int minStickers(String[] stickers, String target) {\n map = new HashMap<>();\n for(String sticker:stickers){\n HashMap temp = new HashMap<>();\n for(char ch:sticker.toCharArray())\n temp.put(ch,temp.getOrDefault(ch,0)+1);\n map.put(sticker,temp);\n }\n int count = memoization(target,new HashMap<>());\n return count<1||count>=Integer.MAX_VALUE?-1:count;\n }\n public int memoization(String target, HashMapdpmap){\n if(target.length()==0)return 0;\n if(dpmap.containsKey(target)) return dpmap.get(target);\n int count = Integer.MAX_VALUE;\n for(String str: map.keySet()){\n HashMap xd = new HashMap(map.get(str));\n String temp = target;\n char ch = temp.charAt(0);\n if(xd.containsKey(ch)){\n for(int i =0;i0){\n xd.put(ch,xd.get(ch)-1);\n temp = temp.substring(0,i)+temp.substring(i+1);\n i--;\n }\n }\n if(temp.length()!=target.length()){\n count = Math.min(count,1+memoization(temp,dpmap));\n dpmap.put(target,count); \n }\n }\n }\n return count;\n }\n}\n", + "title": "691. Stickers to Spell Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "We are given n different types of stickers . Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target . If the task is impossible, return -1 . Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == stickers.length", + "1 <= n <= 50", + "1 <= stickers[i].length <= 10", + "1 <= target.length <= 15", + "stickers[i] and target consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"Output:3Explanation:We can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.", + "image": null + }, + { + "text": "Example 2: Input:stickers = [\"notice\",\"possible\"], target = \"basicbasic\"Output:-1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.", + "image": null + } + ], + "follow_up": null, + "solution": "from functools import lru_cache\nfrom collections import Counter\nclass Solution(object):\n def minStickers(self, stickers, target):\n counter = [Counter(sticker) for sticker in stickers] \n n = len(counter)\n @lru_cache(None)\n def dfs(target):\n if not target: return 0\n targ_counter = Counter(target)\n res = float('inf')\n #using sticker[i] if it contains the first letter of target\n for i in range(n):\n if counter[i][target[0]] == 0:\n continue\n s = ''\n for j in 'abcdefghijklmnopqrstuvwxyz':\n s += j*max(targ_counter[j] - counter[i][j], 0) \n res = min(res, 1 + dfs(s)) if dfs(s) != -1 else res\n return -1 if res == float('inf') else res\n return dfs(target)", + "title": "691. Stickers to Spell Word", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Implement the StockPrice class: Example 1:", + "description_images": [], + "constraints": [ + "Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.", + "Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.", + "Finds the maximum price the stock has been based on the current records.", + "Finds the minimum price the stock has been based on the current records." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]Output[null, null, null, 5, 10, null, 5, null, 2]ExplanationStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class StockRecord {\n int timestamp;\n int price;\n \n public StockRecord(){}\n \n public StockRecord(int t, int p) {\n timestamp = t;\n price = p;\n }\n}\n\nclass StockPrice {\n \n PriorityQueue max = new PriorityQueue<>((sr1, sr2) -> (sr2.price - sr1.price));\n PriorityQueue min = new PriorityQueue<>((sr1, sr2) -> (sr1.price - sr2.price));\n StockRecord current_record;\n Map map = new HashMap<>();\n\n \n public StockPrice() {\n current_record = new StockRecord();\n }\n \n public void update(int timestamp, int price) {\n if(timestamp >= current_record.timestamp) {\n current_record.timestamp = timestamp;\n current_record.price = price;\n }\n \n StockRecord sr = new StockRecord(timestamp, price);\n max.add(sr);\n min.add(sr);\n map.put(timestamp, price);\n }\n \n public int current() {\n return current_record.price;\n }\n \n public int maximum() {\n StockRecord sp = max.peek();\n while(true) {\n sp = max.peek();\n if(sp.price != map.get(sp.timestamp))\n max.poll();\n else break;\n }\n return sp.price;\n }\n \n public int minimum() {\n StockRecord sp = min.peek();\n while(true) {\n sp = min.peek();\n if(sp.price != map.get(sp.timestamp))\n min.poll();\n else break;\n }\n return sp.price;\n }\n}\n", + "title": "2034. Stock Price Fluctuation", + "topic": "Algorithms" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Implement the StockPrice class: Example 1:", + "description_images": [], + "constraints": [ + "Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.", + "Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.", + "Finds the maximum price the stock has been based on the current records.", + "Finds the minimum price the stock has been based on the current records." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]Output[null, null, null, 5, 10, null, 5, null, 2]ExplanationStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class StockPrice:\n\n def __init__(self):\n self.timestamps = {}\n self.highestTimestamp = 0\n self.minHeap = []\n self.maxHeap = []\n\n def update(self, timestamp: int, price: int) -> None:\n\t #Keep track of current prices\n self.timestamps[timestamp] = price\n self.highestTimestamp = max(self.highestTimestamp, timestamp)\n \n\t\t#For maximum/minimum\n heappush(self.minHeap, (price, timestamp))\n heappush(self.maxHeap, (-price, timestamp))\n\n def current(self) -> int:\n\t #Just return the highest timestamp in O(1)\n return self.timestamps[self.highestTimestamp]\n\n def maximum(self) -> int:\n currPrice, timestamp = heappop(self.maxHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n while -currPrice != self.timestamps[timestamp]:\n currPrice, timestamp = heappop(self.maxHeap)\n \n heappush(self.maxHeap, (currPrice, timestamp))\n return -currPrice\n\n def minimum(self) -> int:\n currPrice, timestamp = heappop(self.minHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n while currPrice != self.timestamps[timestamp]:\n currPrice, timestamp = heappop(self.minHeap)\n \n heappush(self.minHeap, (currPrice, timestamp))\n return currPrice\n", + "title": "2034. Stock Price Fluctuation", + "topic": "Algorithms" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i] . The objective of the game is to end with the most stones. The total number of stones across all the piles is odd , so there are no ties. Alice and Bob take turns, with Alice starting first . Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins . Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= piles.length <= 500", + "piles.length is even .", + "1 <= piles[i] <= 500", + "sum(piles[i]) is odd ." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,3,4,5]Output:trueExplanation:Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:piles = [3,7,2,3]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n //This is the Easy One..\n //The main Thing is We(Alice) have to take win\n \n //alice going to check the even sum and the odd sum if even sum> odd sum alice start with 0 else start with n-1.\n public boolean stoneGame(int[] piles) {\n return true;\n }\n}\n", + "title": "877. Stone Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i] . The objective of the game is to end with the most stones. The total number of stones across all the piles is odd , so there are no ties. Alice and Bob take turns, with Alice starting first . Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins . Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= piles.length <= 500", + "piles.length is even .", + "1 <= piles[i] <= 500", + "sum(piles[i]) is odd ." + ], + "examples": [ + { + "text": "Example 1: Input:piles = [5,3,4,5]Output:trueExplanation:Alice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.", + "image": null + }, + { + "text": "Example 2: Input:piles = [3,7,2,3]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n", + "title": "877. Stone Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row , and each pile has a positive integer number of stones piles[i] .  The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first.  Initially, M = 1 . On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M .  Then, we set M = max(M, X) . The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 100", + "1 <= piles[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [2,7,9,4,4]Output:10Explanation:If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger.", + "image": null + }, + { + "text": "Example 2: Input:piles = [1,2,3,4,5,100]Output:104", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 884 ms (Top 5.06%) | Memory: 117.5 MB (Top 5.06%)\nclass Solution {\n public int stoneGameII(int[] piles) {\n Map memo = new HashMap<>();\n int diff = stoneGame(piles,1,0,0,memo);\n int totalSum = 0;\n for(int ele: piles)\n totalSum+=ele;\n return (diff+totalSum)/2;\n }\n\n public int stoneGame(int[] piles, int M, int index, int turn,Map memo )\n {\n if(index >= piles.length)\n return 0;\n if(memo.containsKey(index+\"-\"+M+\"-\"+turn))\n return memo.get(index+\"-\"+M+\"-\"+turn);\n int score=0,maxScore=Integer.MIN_VALUE;\n // Alice's turn\n if(turn == 0)\n {\n for(int X=1;X<=2*M && index+X-1 int:\n n = len(piles)\n dp = {} \n def recursion(index,M):\n # if we reached to the end we cannot score any value\n if index == n:\n return 0\n # we search if we have solved the same case earlier\n if (index,M) in dp:\n return dp[(index,M)] \n # total remaining score is the sum of array from index to the end\n total = sum(piles[index:]) \n # if we can take the complete array it is the best choice\n if index + 2*M >= n :return total\n # my_score is the score we are getting as the player who is playing\n my_score = 0\n for x in range(index,index+2*M):\n # opponent score will be calculated by next recursion\n opponent_score = recursion(x+1,max(M,x-index+1))\n # my_score is the remaining value of total - opponent_score\n my_score = max(my_score,total - opponent_score) \n # this is memoization part\n dp[(index,M)] = my_score\n # return the score\n return my_score\n \n return recursion(0,1)\n", + "title": "1140. Stone Game II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1 , 2 , or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally . Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 5 * 10^4", + "-1000 <= stoneValue[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3,7]Output:\"Bob\"Explanation:Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2,3,-9]Output:\"Alice\"Explanation:Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.", + "image": null + }, + { + "text": "Example 3: Input:values = [1,2,3,6]Output:\"Tie\"Explanation:Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tInteger[] dp;\n\n\tpublic String stoneGameIII(int[] stoneValue) {\n\t\tdp = new Integer[stoneValue.length + 1];\n\t\n\t\t\tArrays.fill(dp, null);\n\t\t\n\t\tint ans = stoneGameIII(0, stoneValue);\n\t\tif (ans == 0)\n\t\t\treturn \"Tie\";\n\t\telse if (ans > 0)\n\t\t\treturn \"Alice\";\n\t\telse\n\t\t\treturn \"Bob\";\n\t}\n\n\tpublic int stoneGameIII(int l, int[] s) {\n\t\tif (l >= s.length)\n\t\t\treturn 0;\n\t\tif (dp[l] != null)\n\t\t\treturn dp[l];\n\t\tint ans;\n\t\t\tans = Integer.MIN_VALUE;\n\t\t\tif (l < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] - stoneGameIII(l + 1, s));\n\t\t\t}\n\t\t\tif (l + 1 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] -stoneGameIII(l + 2, s));\n\t\t\t}\n\t\t\tif (l + 2 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] +s[l + 2] -stoneGameIII(l + 3, s));\n\t\t\t}\n\t\t \n\t\treturn dp[l] = ans;\n\t}\n}\n", + "title": "1406. Stone Game III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob continue their games with piles of stones. There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1 , 2 , or 3 stones from the first remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally . Return \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 5 * 10^4", + "-1000 <= stoneValue[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:values = [1,2,3,7]Output:\"Bob\"Explanation:Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.", + "image": null + }, + { + "text": "Example 2: Input:values = [1,2,3,-9]Output:\"Alice\"Explanation:Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.", + "image": null + }, + { + "text": "Example 3: Input:values = [1,2,3,6]Output:\"Tie\"Explanation:Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def stoneGameIII(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: str\n \"\"\"\n n = len(stoneValue)\n suffixSum = [0 for _ in range(n+1)]\n dp = [0 for _ in range(n+1)]\n for i in range(n-1, -1, -1):\n suffixSum[i] = suffixSum[i+1] + stoneValue[i]\n for i in range(n-1, -1, -1):\n dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1]\n for k in range(i+1, min(n, i+3)):\n dp[i] = max(dp[i], suffixSum[i] - dp[k+1])\n if dp[0]*2 == suffixSum[0]:\n return \"Tie\"\n elif dp[0]*2 > suffixSum[0]:\n return \"Alice\"\n else:\n return \"Bob\"\n", + "title": "1406. Stone Game III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n , return true if and only if Alice wins the game otherwise return false , assuming both players play optimally. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:trueExplanation:Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:falseExplanation:Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:trueExplanation:n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1188 ms (Top 5.04%) | Memory: 258.9 MB (Top 5.04%)\nclass Solution {\n // idea: Alice wins a game with n stones if and only if there exists\n // some perfect square p <= n such that Alice wins a game with\n // n - p stones... i.e., Bob DOES NOT win a game with n - p stones\n public boolean winnerSquareGame(int n) {\n // this bit would be better with just an array of booleans, but this\n // is how i thought of it at the time, so leaving it this way...\n // maybe it will be \"more explicit\" and help someone better understand dp?\n HashMap memo = new HashMap<>();\n memo.put(1, true); // if there is one stone in the pile to begin the game, the next player to go wins\n memo.put(0, false); // if there are zero stones in the pile to begin the game, the next player to go loses\n List perfectSquares = new ArrayList<>();\n int i = 1;\n while (i * i <= n) {\n perfectSquares.add(i * i);\n i++;\n }\n // if there are some perfect square number of stones in the pile to begin the game, the next player to go wins\n perfectSquares.forEach(p -> memo.put(p, true));\n // Alice goes first...\n return this.playerWins(n, perfectSquares, memo);\n }\n\n private boolean playerWins(int n, List P, HashMap m) {\n if (m.containsKey(n)) { return m.get(n); } // if we already computed the answer for n, just return it\n m.put(n, false); // otherwise, assume it's false to begin...\n for (Integer p : P) { // check every perfect square p...\n if (p <= n && !playerWins(n - p, P, m)) {\n // if p <= n AND the player who goes next (e.g., Bob) does not win a game that begins with\n // n - p stones, then we know that the player whose turn it is right now (e.g., Alice) wins\n // a game that begins with n stones, so record this discovery in the memo and then break out\n // of the loop because there's no more work to do...\n m.put(n, true);\n break;\n } // else p >= n OR taking p stones would not result in a win for the player whose turn it is right now...\n }\n // we put false in before the loop; if we never found a reason to change it to true,\n // then false is the correct result...\n return m.get(n);\n }\n\n}", + "title": "1510. Stone Game IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first. Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer n , return true if and only if Alice wins the game otherwise return false , assuming both players play optimally. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:trueExplanation:Alice can remove 1 stone winning the game because Bob doesn't have any moves.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:falseExplanation:Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).", + "image": null + }, + { + "text": "Example 3: Input:n = 4Output:trueExplanation:n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 189 ms (Top 93.6%) | Memory: 21.09 MB (Top 49.0%)\n\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n \n @cache\n def can_win(n: int) -> bool:\n return n and not all(can_win(n - s) for s in squares(n))\n \n return can_win(n)\n\n", + "title": "1510. Stone Game IV", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones , where stones[i] is the value of the i th stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones . The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3 . Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally , return true if Alice wins and false if Bob wins . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 10^5", + "1 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,1]Output:trueExplanation:The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [2]Output:falseExplanation:Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.", + "image": null + }, + { + "text": "Example 3: Input:stones = [5,1,2,4,3]Output:falseExplanation:Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean stoneGameIX(int[] stones) {\n Map div3 = new HashMap<>();\n div3.put(0, 0);\n div3.put(1, 0);\n div3.put(2, 0);\n \n for(int stone : stones){\n div3.put(stone%3, div3.get(stone%3)+1);\n }\n\t\t// the count of 3's don't matter, only whether it is even or odd\n div3.put(0, div3.get(0)%2);\n \n \n if(div3.get(1) == 0 && div3.get(2) == 0){\n return false;\n }\n \n int smaller = Math.min(div3.get(1), div3.get(2));\n int larger = Math.max(div3.get(2), div3.get(1));\n\t\t// the combinations of 1's and 2's will work with each other in a complementary way. \n\t\t// A pair of 1 and 2 makes modulo 3 to be 0\n\t\t// Three counts of 1 or 2 makes modulo 3 to be 0\n\t\t// so, we need only relative counts\n \n // if there are even 3's, then bob can't reverse alice's win\n // so, if all three digits chosen are the same then bob wins, but if there is another option then alice wins\n // [1,2,2,2] -> alice picks 1 and wins\n // [1,3,3,2] -> alice picks 1 or two and wins\n // [2,2,2] -> alice has to pick the third 2 and loses\n\n if(div3.get(0) == 0){\n return smaller != 0;\n }\n \n // all cases now have odd number of 3's, so result can be reversed\n \n // [1,1,1,1,3] -> 1,1,3,1 picked or 1,3,1,1 picked means alice wins\n // similar for 2 because the other number doesn't exist to make a %3 pair\n \n // if the difference of number counts is more than 2 then alice can always force bob\n // [3,1,2,2,2] -> \n\t\t// [3,1,2,2,2,2] ->\n if(larger > smaller + 2){\n return true;\n }\n \n return false;\n }\n}\n", + "title": "2029. Stone Game IX", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones , where stones[i] is the value of the i th stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones . The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3 . Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally , return true if Alice wins and false if Bob wins . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stones.length <= 10^5", + "1 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [2,1]Output:trueExplanation:The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.", + "image": null + }, + { + "text": "Example 2: Input:stones = [2]Output:falseExplanation:Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.", + "image": null + }, + { + "text": "Example 3: Input:stones = [5,1,2,4,3]Output:falseExplanation:Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2982 ms (Top 22.53%) | Memory: 27.5 MB (Top 95.77%)\nclass Solution:\n def stoneGameIX(self, stones: List[int]) -> bool:\n u, d, t = 0, 0, 0\n for stone in stones:\n if stone % 3 == 1:\n u += 1\n elif stone % 3 == 2:\n d += 1\n else:\n t += 1\n if not u and d <= 2 or u <= 2 and not d: #situation 1 part 2\n return False\n if not u and d > 2 or u > 2 and not d: #situation 1 part 1\n if not t % 2:\n return False\n else:\n return True\n if u == d or abs(u - d) <= 2: #situation 2 and situation 3\n if t % 2:\n return False\n else:\n return True\n return True #default situation", + "title": "2029. Stone Game IX", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are several stones arranged in a row , and each stone has an associated value which is an integer given in the array stoneValue . In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining . Alice's is initially zero . Return the maximum score that Alice can obtain . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= stoneValue.length <= 500", + "1 <= stoneValue[i] <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:stoneValue = [6,2,3,4,5,5]Output:18Explanation:In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.", + "image": null + }, + { + "text": "Example 2: Input:stoneValue = [7,7,7,7,7,7,7]Output:28", + "image": null + }, + { + "text": "Example 3: Input:stoneValue = [4]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 299 ms (Top 83.10%) | Memory: 42.5 MB (Top 97.18%)\nclass Solution {\n int dp[][];\n public int fnc(int a[], int i, int j, int sum){\n //System.out.println(i+\" \"+j);\n int n=a.length;\n if(i>j)\n return 0;\n if(j>n)\n return 0;\n if(i==j){\n dp[i][j]=-1;\n return 0;\n }\n if(dp[i][j]!=0)\n return dp[i][j];\n\n int temp=0;\n int ans=Integer.MIN_VALUE;\n\n for(int index=i;index<=j;index++){\n temp+=a[index];\n if(temp>sum-temp){\n ans=Math.max(ans,((sum-temp)+fnc(a,index+1,j,sum-temp)));\n }\n else if(temp int:\n n = len(stoneValue)\n dp = [[0]*n for _ in range(n)]\n left = [[0]*n for _ in range(n)]\n prefix = list(accumulate(stoneValue))\n prefix = [0]+prefix+[prefix[-1]]\n\n def sum(i,j):\n return prefix[j+1]-prefix[i]\n\n row_idx = [i for i in range(n)]\n for i in range(n):\n left[i][i] = stoneValue[i]\n for d in range(1,n):\n for i in range(n-d):\n j = i+d\n while sum(i,row_idx[i]) < sum(row_idx[i]+1,j):\n row_idx[i] +=1\n if sum(i, row_idx[i]) == sum(row_idx[i]+1,j):\n dp[i][j] = max(left[i][row_idx[i]], left[j][row_idx[i]+1])\n else:\n if row_idx[i] == i:\n dp[i][j] = left[j][i+1]\n elif row_idx[i] == j:\n dp[i][j] = left[i][j-1]\n else:\n dp[i][j] = max(left[i][row_idx[i]-1], left[j][row_idx[i]+1])\n left[j][i] = max(left[j][i+1],sum(i,j)+dp[i][j])\n left[i][j] = max(left[i][j-1],sum(i,j)+dp[i][j])\n return dp[0][n-1]", + "title": "1563. Stone Game V", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first. There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently . You are given two integer arrays of length n , aliceValues and bobValues . Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the i th stone. The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally . Both players know the other's values. Determine the result of the game, and: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If Alice wins, return 1 .", + "If Bob wins, return -1 .", + "If the game results in a draw, return 0 ." + ], + "examples": [ + { + "text": "Example 1: Input:aliceValues = [1,3], bobValues = [2,1]Output:1Explanation:If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.", + "image": null + }, + { + "text": "Example 2: Input:aliceValues = [1,2], bobValues = [3,1]Output:0Explanation:If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.", + "image": null + }, + { + "text": "Example 3: Input:aliceValues = [2,4,3], bobValues = [1,6,7]Output:-1Explanation:Regardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\nstatic class Pair\n{\n int sum=0;\n int alice=0;\n int bob=0;\n public Pair(int sum,int alice, int bob)\n{\n this.sum=sum;\n\tthis.alice = alice;\n\tthis.bob = bob;\n}\n}\n\n// class to define user defined conparator\nstatic class Compare {\n\t\n\tstatic void compare(Pair arr[], int n)\n\t{\n\t\t// Comparator to sort the pair according to second element\n\t\tArrays.sort(arr, new Comparator() {\n\t\t\t@Override public int compare(Pair p1, Pair p2)\n\t\t\t{\n\t\t\t\treturn p2.sum - p1.sum;\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t}\n}\n public int stoneGameVI(int[] aliceValues, int[] bobValues)\n {\n int n=aliceValues.length;\n Pair[] a=new Pair[n];\n for(int i=0;i0 else ( -1 if d<0 else 0 )", + "title": "1686. Stone Game VI", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference . Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the i th stone from the left , return the difference in Alice and Bob's score if they both play optimally . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == stones.length", + "2 <= n <= 1000", + "1 <= stones[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [5,3,1,4,2]Output:6Explanation:- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6.", + "image": null + }, + { + "text": "Example 2: Input:stones = [7,90,5,1,100,10,10,2]Output:122", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 6869 ms (Top 56.16%) | Memory: 13.9 MB (Top 96.15%)\nclass Solution:\n def stoneGameVII(self, S: List[int]) -> int:\n N, dp = len(S), [0] * len(S)\n for i in range(N - 2, -1, -1):\n total = S[i]\n for j in range(i + 1, N):\n total += S[j]\n dp[j] = max(total - S[i] - dp[j], total - S[j] - dp[j-1])\n return dp[-1]", + "title": "1690. Stone Game VII", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . There are n stones arranged in a row. On each player's turn, while the number of stones is more than one , they will do the following: The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score) . Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the i th stone from the left , return the score difference between Alice and Bob if they both play optimally . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == stones.length", + "2 <= n <= 10^5", + "-10^4 <= stones[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:stones = [-1,2,-3,4,-5]Output:5Explanation:- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\n value 2 on the left. stones = [2,-5].\n- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\n the left. stones = [-3].\nThe difference between their scores is 2 - (-3) = 5.", + "image": null + }, + { + "text": "Example 2: Input:stones = [7,-6,5,10,5,-2,-6]Output:13Explanation:- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\n stone of value 13 on the left. stones = [13].\nThe difference between their scores is 13 - 0 = 13.", + "image": null + }, + { + "text": "Example 3: Input:stones = [-10,-12]Output:-22Explanation:- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\n score and places a stone of value -22 on the left. stones = [-22].\nThe difference between their scores is (-22) - 0 = -22.", + "image": null + } + ], + "follow_up": null, + "solution": "# OJ: https://leetcode.com/problems/stone-game-viii/\n# Author: github.com/lzl124631x\nclass Solution:\n def stoneGameVIII(self, A: List[int]) -> int:\n return reduce(lambda memo, cur : max(memo, cur - memo), list(accumulate(A))[::-1][:-1])\n", + "title": "1872. Stone Game VIII", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a strange printer with the following two special properties: Given a string s , return the minimum number of turns the printer needed to print it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The printer can only print a sequence of the same character each time.", + "At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"Output:2Explanation:Print \"aaa\" first and then print \"bbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:2Explanation:Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\npublic int strangePrinter(String s) {\n if (s.equals(\"\")) return 0;\n int len = s.length();\n int[][] dp = new int[len][len];\n for (int i = 0; i < len; i++)\n dp[i][i] = 1;\n for (int l = 2; l <= len; l++) {\n for (int i = 0; i < len && l + i - 1 < len; i++) {\n int j = l + i - 1;\n dp[i][j] = dp[i][j - 1] + (s.charAt(i) == s.charAt(j) ? 0 : 1);\n for (int k = i + 1; k < j; k++) {\n if (s.charAt(k) == s.charAt(j)) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k][j - 1]);\n }\n }\n }\n }\n return dp[0][len - 1];\n}\n}", + "title": "664. Strange Printer", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a strange printer with the following two special properties: Given a string s , return the minimum number of turns the printer needed to print it . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The printer can only print a sequence of the same character each time.", + "At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabbb\"Output:2Explanation:Print \"aaa\" first and then print \"bbb\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aba\"Output:2Explanation:Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 878 ms (Top 47.91%) | Memory: 16.1 MB (Top 47.44%)\nclass Solution(object):\n def strangePrinter(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # remove duplicate letters from s.\n tmp = []\n for c in s:\n if len(tmp) == 0 or tmp[-1] != c:\n tmp.append(c)\n s = \"\".join(tmp)\n\n _m = {}\n def _dp(i, j, background):\n if j < i:\n return 0\n elif i == j:\n return 1 if background != s[i] else 0\n elif (i, j, background) in _m:\n return _m[(i, j, background)]\n\n ans = len(s)\n\n # shrink s[i:j+1] to s[i_:j_+1] according to the background letter\n i_ = i + 1 if s[i] == background else i\n j_ = j - 1 if s[j] == background else j\n\n if s[i_] == s[j_]:\n # case \"AxxxA\" => best strategy is printing A first\n ans = _dp(i_ + 1, j_ - 1, s[i_]) + 1\n else:\n # otherwise, print first letter, try every possible print length\n for p in range(i_, j_ + 1):\n # searching is needed only if s[p] == s[i_]\n # e.g. s=\"ABCDEA\"print 'A' on s[0:1] is equivalent to s[0:5]\n if s[p] != s[i_]:\n continue\n l = _dp(i_, p, s[i_])\n r = _dp(p + 1, j_, background)\n ans = min(ans, l + r + 1)\n _m[(i, j, background)] = ans\n return ans\n\n return _dp(0, len(s) - 1, '')", + "title": "664. Strange Printer", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a strange printer with the following two special requirements: You are given a m x n matrix targetGrid , where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.", + "Once the printer has used a color for the above operation, the same color cannot be used again ." + ], + "examples": [ + { + "text": "Example 1: Input:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print1.jpg" + }, + { + "text": "Example 2: Input:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print2.jpg" + }, + { + "text": "Example 3: Input:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]Output:falseExplanation:It is impossible to form targetGrid because it is not allowed to print the same color in different turns.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 85 ms (Top 41.74%) | Memory: 54.3 MB (Top 53.04%)\nclass Solution {\n // store each color's left, top, right, bottom\n private Set[] graph;\n private int[] indegrees;\n private int[][] ranges;\n private boolean[] exists;\n private int m;\n private int n;\n private int maxColor = 60;\n public boolean isPrintable(int[][] targetGrid) {\n this.m = targetGrid.length;\n this.n = targetGrid[0].length;\n buildRanges(targetGrid);\n buildGraph(targetGrid);\n int count = 0;\n int totalCount = 0;\n Queue queue = new LinkedList<>();\n for (int i = 1; i <= maxColor; i++) {\n if (exists[i]) {\n if (indegrees[i] == 0) {\n queue.offer(i);\n }\n totalCount++;\n }\n }\n while (!queue.isEmpty()) {\n count++;\n Integer current = queue.poll();\n for (Integer neighbor: graph[current]) {\n if (--indegrees[neighbor] == 0) {\n queue.offer(neighbor);\n }\n }\n }\n return count == totalCount;\n }\n private void buildRanges(int[][] targetGrid) {\n this.ranges = new int[maxColor + 1][4];\n for (int i = 1; i <= maxColor; i++) {\n ranges[i][0] = ranges[i][1] = Integer.MAX_VALUE;\n ranges[i][2] = ranges[i][3] = Integer.MIN_VALUE;\n }\n exists = new boolean[maxColor + 1];\n int max = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int color = targetGrid[i][j];\n exists[color] = true;\n max = Math.max(max, color);\n ranges[color][0] = Math.min(ranges[color][0], j);\n ranges[color][1] = Math.min(ranges[color][1], i);\n ranges[color][2] = Math.max(ranges[color][2], j);\n ranges[color][3] = Math.max(ranges[color][3], i);\n }\n }\n maxColor = max;\n }\n // TC O(n^3) to build graph\n private void buildGraph(int[][] targetGrid) {\n graph = new Set[maxColor + 1];\n indegrees = new int[maxColor + 1];\n for (int c = 1; c <= maxColor; c++) {\n if (exists[c]) {\n graph[c] = new HashSet<>();\n for (int i = ranges[c][1]; i <= ranges[c][3]; i++) {\n for (int j = ranges[c][0]; j <= ranges[c][2]; j++) {\n int other = targetGrid[i][j];\n if (other != c && !graph[c].contains(other)) {\n graph[c].add(other);\n indegrees[other]++;\n }\n }\n }\n }\n }\n }\n}", + "title": "1591. Strange Printer II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is a strange printer with the following two special requirements: You are given a m x n matrix targetGrid , where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid , otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.", + "Once the printer has used a color for the above operation, the same color cannot be used again ." + ], + "examples": [ + { + "text": "Example 1: Input:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print1.jpg" + }, + { + "text": "Example 2: Input:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/12/23/print2.jpg" + }, + { + "text": "Example 3: Input:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]Output:falseExplanation:It is impossible to form targetGrid because it is not allowed to print the same color in different turns.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 514 ms (Top 80.64%) | Memory: 14.5 MB (Top 44.35%)\nfrom graphlib import TopologicalSorter, CycleError\n\nColor = int\nCorner = Tuple[int, int]\nRect = Tuple[Corner, Corner] # [upper-left, lower-right (non-inclusive)]\nLayer = Tuple[Color, Rect]\n\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n # Runtime is the summation of several steps but is dominated by the second step\n # O(M*N + C*C*M*N + (O(C*C) + O(M*N)) + M*N) -> O(C*C*M*N)\n def compare(a:Layer, b:Layer) -> int:\n \"\"\"\n Determine if two rectangles overlap.\n\n Return:\n -1 if b is over a\n 0 if there is no overlap or an order cannot be determined (the overlap contains no elements of a or b)\n 1 if a is over b\n \"\"\"\n val_a, (a_ul, a_lr) = a\n val_b, (b_ul, b_lr) = b\n\n # Get overlap rectangle\n ul, lr = (\n (max(a_ul[0], b_ul[0]), max(a_ul[1], b_ul[1])),\n (min(a_lr[0], b_lr[0]), min(a_lr[1], b_lr[1])),\n )\n\n # If either dimension is non-positive, there is no overlap\n if lr[0] - ul[0] <= 0 or lr[1] - ul[1] <= 0:\n return 0\n\n # Find the first element matching a or b in the overlap rectangle.\n # We'll consider that the \"over\" value.\n for r in range(ul[0], lr[0]):\n for c in range(ul[1], lr[1]):\n if targetGrid[r][c] == val_b:\n return -1\n elif targetGrid[r][c] == val_a:\n return 1\n # We could find no values from a or b in the overlap.\n # The result is indeterminate.\n return 0\n\n # Generate the enclosing rectangles for each visible color (ie. layers).\n # O(M*N)\n rects:Dict[Color, Rect] = defaultdict(lambda: ([100, 100], [0, 0]))\n for r, row in enumerate(targetGrid):\n for c, val in enumerate(row):\n ul, lr = rects[val]\n rects[val] = (\n (min(ul[0], r), min(ul[1], c)),\n (max(lr[0], r + 1), max(lr[1], c + 1))\n )\n\n # Compare every pair of layers.\n # If overlap is detected, record that the \"upper\" rectangle depends on the \"lower\" one.\n # O(C*C*M*N) # Number of colors\n layers:List[Layer] = list(rects.items())\n graph:Dict[Layer, Set[Layer]] = {layer: set() for layer in layers}\n for i, a in enumerate(layers):\n for b in layers[i + 1 :]:\n if (cmp := compare(a, b)) < 0:\n graph[b].add(a)\n elif cmp > 0:\n graph[a].add(b)\n\n # Use topological sort on the graph to reproduce the printing order (in the absence\n # of cycles) and print our own grid.\n # O(C*C) + O(M*N) // O(C*C) is derived from topological sort O(V+E)\n try:\n grid = [[0] * len(targetGrid[0]) for _ in targetGrid]\n for color, (ul, lr) in TopologicalSorter(graph).static_order():\n for r in range(ul[0], lr[0]):\n for c in range(ul[1], lr[1]):\n grid[r][c] = color\n except CycleError:\n return False\n\n # Compare the grids\n # O(M*N)\n return grid == targetGrid", + "title": "1591. Strange Printer II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words . For example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a' , 'x' , 'y' , and 'z' , your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words . Implement the StreamChecker class: Example 1:", + "description_images": [], + "constraints": [ + "StreamChecker(String[] words) Initializes the object with the strings array words .", + "boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]Output[null, false, false, false, true, false, true, false, false, false, false, false, true]ExplanationStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist", + "image": null + } + ], + "follow_up": null, + "solution": "class StreamChecker {\n \n class TrieNode {\n boolean isWord;\n TrieNode[] next = new TrieNode[26];\n }\n \n TrieNode root = new TrieNode();\n StringBuilder sb = new StringBuilder();\n \n public StreamChecker(String[] words) {\n createTrie(words);\n }\n \n public boolean query(char letter){\n sb.append(letter);\n TrieNode node = root;\n for(int i=sb.length()-1; i>=0 && node!=null; i--){\n char ch = sb.charAt(i);\n node = node.next[ch - 'a'];\n if(node != null && node.isWord){\n return true;\n }\n }\n return false;\n }\n \n private void createTrie(String words[]){\n for(String s : words){\n TrieNode node = root;\n int len = s.length();\n for(int i = len-1; i>=0; i--){\n char ch = s.charAt(i);\n if(node.next[ch-'a'] == null){\n node.next[ch - 'a'] = new TrieNode();\n }\n node = node.next[ch - 'a'];\n }\n node.isWord = true;\n }\n }\n}\n", + "title": "1032. Stream of Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words . For example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a' , 'x' , 'y' , and 'z' , your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words . Implement the StreamChecker class: Example 1:", + "description_images": [], + "constraints": [ + "StreamChecker(String[] words) Initializes the object with the strings array words .", + "boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words ." + ], + "examples": [ + { + "text": "Example 1: Input[\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n[[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]Output[null, false, false, false, true, false, true, false, false, false, false, false, true]ExplanationStreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\nstreamChecker.query(\"a\"); // return False\nstreamChecker.query(\"b\"); // return False\nstreamChecker.query(\"c\"); // return False\nstreamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\nstreamChecker.query(\"e\"); // return False\nstreamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\nstreamChecker.query(\"g\"); // return False\nstreamChecker.query(\"h\"); // return False\nstreamChecker.query(\"i\"); // return False\nstreamChecker.query(\"j\"); // return False\nstreamChecker.query(\"k\"); // return False\nstreamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode:\n \n def __init__(self):\n self.children = {}\n self.endOfWord = False\n\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n self.root = TrieNode()\n self.qCur = self.root\n self.stream = collections.deque()\n cur = self.root\n for word in words:\n for i in range(len(word) - 1, -1, -1):\n ch = word[i]\n if ch not in cur.children:\n cur.children[ch] = TrieNode()\n cur = cur.children[ch]\n cur.endOfWord = True\n cur = self.root\n\n def query(self, letter: str) -> bool:\n self.stream.appendleft(letter)\n cur = self.root\n for ch in self.stream:\n if ch not in cur.children:\n return False\n else:\n cur = cur.children[ch]\n if cur.endOfWord:\n return True\n return False\n", + "title": "1032. Stream of Characters", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]Output:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]Explanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]Output:Return 1, and the first character of the input array should be: [\"a\"]Explanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]Output:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].Explanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compress(char[] chars) {\n int index = 0;\n int i = 0;\n\n while (i < chars.length) {\n int j = i;\n\n while (j < chars.length && chars[j] == chars[i]) {\n j++;\n }\n\n chars[index++] = chars[i];\n\n if (j - i > 1) {\n String count = j - i + \"\";\n\n for (char c : count.toCharArray()) {\n chars[index++] = c;\n }\n }\n\n i = j;\n }\n\n return index;\n }\n}\n\n// TC: O(n), SC: O(1)", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]Output:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]Explanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]Output:Return 1, and the first character of the input array should be: [\"a\"]Explanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]Output:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].Explanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def compress(self, chars: List[str]) -> int:\n stri = ''\n stack = [chars.pop(0)]\n \n while chars:\n p = chars.pop(0)\n \n if p in stack:\n stack.append(p)\n else:\n stri = stri + stack[-1] + str(len(stack) if len(stack) > 1 else '')\n stack = [p] \n \n o = list(stri + stack[-1] + str(len(stack) if len(stack) > 1 else ''))\n \n for i in o:\n chars.append(i)\n", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\" . Thus the compressed string becomes \"a2bc3\" . Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k . You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "0 <= k <= s.length", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabcccd\", k = 2Output:4Explanation:Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaa\", k = 2Output:2Explanation:If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaaaaaaaaaa\", k = 0Output:3Explanation:Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\t public int getLengthOfOptimalCompression(String s, int k) {\n Map memo = new HashMap<>();\n return recur(s, '\\u0000', 0, k, 0, memo);\n }\n\n private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map memo) {\n\n if (index == s.length()) {\n return 0;\n }\n String key = prevChar + \", \" + prevCharCount + \", \" + k + \", \" + index;\n Integer keyVal = memo.get(key);\n\n if (keyVal != null) {\n return keyVal;\n }\n char ch = s.charAt(index);\n int count = 1;\n int nextIndex = index + 1;\n\n for (int i = index + 1; i < s.length(); i++) {\n\n if (s.charAt(i) == ch) {\n count++;\n nextIndex = i + 1;\n } else {\n nextIndex = i;\n break;\n }\n }\n int totalCount = count;\n int prevCountRepresentation = 0;\n //if prev char is equal to current char that means we have removed middle element\n //So we have to subtract the previous representation length and add the new encoding\n //representation length\n if (ch == prevChar) {\n totalCount += prevCharCount;\n prevCountRepresentation = getLength(prevCharCount);\n }\n\n int representaionLength = getLength(totalCount);\n int ans = representaionLength + recur(s, ch, totalCount, k, nextIndex, memo) - prevCountRepresentation;\n\n if (k > 0) {\n\n for (int i = 1; i <= k && i <= count; i++) {\n int currentCount = totalCount - i;\n int length = getLength(currentCount);\n //checking if we have to send current char and current char count or previous char\n //and previous char count\n int holder = length + recur(s, currentCount == 0 ? prevChar : ch,\n currentCount == 0 ? prevCharCount : currentCount, k - i, nextIndex, memo) -\n prevCountRepresentation;\n ans = Math.min(ans, holder);\n }\n }\n memo.put(key, ans);\n return ans;\n }\n //Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc.\n private int getLength(int n) {\n\n if (n == 0) {\n return 0;\n } else if (n == 1) {\n return 1;\n } else if (n < 10) {\n return 2;\n } else if (n < 100) {\n return 3;\n } else {\n return 4;\n }\n }\n}\n", + "title": "1531. String Compression II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\" . Thus the compressed string becomes \"a2bc3\" . Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k . You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "0 <= k <= s.length", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aaabcccd\", k = 2Output:4Explanation:Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabbaa\", k = 2Output:2Explanation:If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.", + "image": null + }, + { + "text": "Example 3: Input:s = \"aaaaaaaaaaa\", k = 0Output:3Explanation:Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1997 ms (Top 68.37%) | Memory: 360.00 MB (Top 27.55%)\n\nclass Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n # We define f(i, curr_run_ch, run_length, nb_dels_remain) to return \n # the minimum, additional, number of characters it will cost to run-length \n # compress the substring s[i..n-1].\n # `curr_run_ch` is the character we have in the current \"run\", or the same\n # contiguous block of characters. \n # `run_length` is the length of the current \"run\", or the length of the\n # contiguous block of identical characters.\n\t\t# e.g. if we just encoded \"aaaaa\", `curr_run_ch` is \"a\" and `run_length` = 5\n # `nb_dels_remain` is the number of delete operations we have available to us,\n # should we choose to use them\n memo = {}\n def f(i, curr_run_ch, run_length, nb_dels_remain):\n if i == len(s):\n return 0\n \n key = (i, curr_run_ch, run_length, nb_dels_remain)\n if key in memo:\n return memo[key]\n \n # At character i, we have two possible options, we could choose to either\n # delete this character or keep this character. Each choice we make will\n # incurr some additional run-length encoding length for s[i..n-1]. We return\n # the minimum of the two.\n \n # Delete s[i]\n del_ch_cost = float('inf')\n if nb_dels_remain > 0:\n # Deleting s[i] means the latest character we kept stays the same AND\n # the current run-length of characters stays the same as well\n del_ch_cost = f(i + 1, curr_run_ch, run_length, nb_dels_remain - 1)\n \n # Keep s[i]\n keep_ch_cost = 0\n if s[i] == curr_run_ch:\n\t\t\t # The new character at s[i] we are about to encode is the same as the character in the\n\t\t\t\t# current \"run\", we could choose to include it into the current run of course.\n # Be careful that if we started with run-length of 1, 9, 99, 999 and etc, encoding another\n # character same as `curr_run_ch` into the same \"run\" will require an extra digit.\n # e.g. 'a' => '2a' '9a' => '10a', '99a' => '100a'\n extra_digit_cost = 0\n if run_length == 1 or len(str(run_length + 1)) > len(str(run_length)):\n extra_digit_cost = 1\n keep_ch_cost = extra_digit_cost + f(i + 1, curr_run_ch, run_length + 1, nb_dels_remain)\n else:\n # s[i] != curr_run_ch, we are going to need to run-length encode at least\n # one instance of s[i] which would cost 1, plus whatever the cost to encode\n # the rest. Of course that also means the current \"run\" will \"reset\" and start anew with\n\t\t\t\t# a single character s[i]\n keep_ch_cost = 1 + f(i + 1, s[i], 1, nb_dels_remain)\n \n memo[key] = min(keep_ch_cost, del_ch_cost)\n return memo[key]\n \n return f(0, '', 0, k)\n", + "title": "1531. String Compression II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of string words . Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j] , if can be obtained removing some characters to left and/or right side of words[j] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 30", + "words[i] contains only lowercase English letters.", + "It's guaranteed that words[i] will be unique." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"mass\",\"as\",\"hero\",\"superhero\"]Output:[\"as\",\"hero\"]Explanation:\"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"et\",\"code\"]Output:[\"et\",\"code\"]Explanation:\"et\", \"code\" are substring of \"leetcode\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"blue\",\"green\",\"bu\"]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List stringMatching(String[] words) {\n Listans = new ArrayList<>();\n for(int i=0; i= 0){\n ans.add(s);\n break;\n }\n }\n }\n return ans;\n }\n}\n", + "title": "1408. String Matching in an Array", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given an array of string words . Return all strings in words which is substring of another word in any order. String words[i] is substring of words[j] , if can be obtained removing some characters to left and/or right side of words[j] . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 30", + "words[i] contains only lowercase English letters.", + "It's guaranteed that words[i] will be unique." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"mass\",\"as\",\"hero\",\"superhero\"]Output:[\"as\",\"hero\"]Explanation:\"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"leetcode\",\"et\",\"code\"]Output:[\"et\",\"code\"]Explanation:\"et\", \"code\" are substring of \"leetcode\".", + "image": null + }, + { + "text": "Example 3: Input:words = [\"blue\",\"green\",\"bu\"]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def stringMatching(self, words: List[str]) -> List[str]:\n ans=set()\n l=len(words)\n for i in range(l):\n for j in range(l):\n if (words[i] in words[j]) & (i!=j):\n ans.add(words[i])\n return ans\n", + "title": "1408. String Matching in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Only the space character ' ' is considered a whitespace character.", + "Do not ignore any characters other than the leading whitespace or the rest of the string after the digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"42\"Output:42Explanation:The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231- 1], the final result is 42.", + "image": null + }, + { + "text": "Example 2: Input:s = \" -42\"Output:-42Explanation:Step 1: \"-42\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-42\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -42\" (\"42\" is read in)\n ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231- 1], the final result is -42.", + "image": null + }, + { + "text": "Example 3: Input:s = \"4193 with words\"Output:4193Explanation:Step 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"4193with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231- 1], the final result is 4193.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int myAtoi(String s) {\n long n=0;\n int i=0,a=0;\n s=s.trim();\n if(s.length()==0)\n return 0;\n if(s.charAt(i)=='+' || s.charAt(i)=='-')\n a=1;\n while(a='0' && s.charAt(i)<='9')\n n=n*10+(int)(s.charAt(i)-'0');\n else\n break;\n }\n if(s.charAt(0)=='-')\n n=-n;\n if(n>2147483647)\n n=2147483647;\n if(n<-2147483648)\n n=-2147483648;\n return (int)n;\n }\n}\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Only the space character ' ' is considered a whitespace character.", + "Do not ignore any characters other than the leading whitespace or the rest of the string after the digits." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"42\"Output:42Explanation:The underlined characters are what is read in, the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nThe parsed integer is 42.\nSince 42 is in the range [-231, 231- 1], the final result is 42.", + "image": null + }, + { + "text": "Example 2: Input:s = \" -42\"Output:-42Explanation:Step 1: \"-42\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-42\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -42\" (\"42\" is read in)\n ^\nThe parsed integer is -42.\nSince -42 is in the range [-231, 231- 1], the final result is -42.", + "image": null + }, + { + "text": "Example 3: Input:s = \"4193 with words\"Output:4193Explanation:Step 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"4193with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\nThe parsed integer is 4193.\nSince 4193 is in the range [-231, 231- 1], the final result is 4193.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 69 ms (Top 20.00%) | Memory: 13.9 MB (Top 79.88%)\n\nclass Solution:\n\n def assign_sign(self, sign):\n # verify that we haven't already got a sign\n # \"+42-\" -> we don't want to return -42; hence check\n if not self.is_neg and not self.is_pos:\n # no sign has been set yet\n if sign==\"+\":\n self.is_pos = True\n elif sign==\"-\":\n self.is_neg = True\n return\n\n def add_to_int(self, num):\n if not self.num:\n self.num = num\n else:\n self.num = (self.num*10) + num\n\n def myAtoi(self, s: str) -> int:\n # remove the leading and trailing spaces\n self.is_neg = False\n self.is_pos = False\n self.num = None\n s=s.strip()\n for i in s:\n # ignore the rest of the string if a non digit character is read\n if i in (\"+\",\"-\"):\n # only read the first symbol; break if second symbol is read\n if self.is_pos or self.is_neg or isinstance(self.num, int):\n # one of the two symbols is read or a number is read\n break\n self.assign_sign(i)\n continue\n try:\n i = int(i)\n self.add_to_int(i)\n except ValueError:\n # it's neither a sign, nor a number; terminate\n break\n\n # outside the loop; compile the result\n if not self.num:\n return 0\n upper_limit = 2**31 - 1\n if self.is_pos or (not self.is_pos and not self.is_neg):\n if self.num > upper_limit:\n self.num = upper_limit\n elif self.is_neg:\n if self.num > upper_limit+1:\n self.num = upper_limit+1\n self.num = -1 * self.num\n return self.num\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given two integers a and b , return any string s such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,", + "The substring 'aaa' does not occur in s , and", + "The substring 'bbb' does not occur in s ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2Output:\"abb\"Explanation:\"abb\", \"bab\" and \"bba\" are all correct answers.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 1Output:\"aabaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.03%) | Memory: 41.4 MB (Top 67.52%)\nclass Solution {\n public String strWithout3a3b(int a, int b) {\n StringBuilder sb = new StringBuilder();\n int x = Math.min(a, Math.min(b, Math.abs(a - b))); // TAKE THE MIN OF (a, b, abs(a - b))\n if (a > b){\n sb.append(\"aab\".repeat(x));\n b -= x;\n a -= 2 * x;\n }\n if (a < b){\n sb.append(\"bba\".repeat(x));\n b -= 2 * x;\n a -= x;\n }\n if (a == b){\n sb.append(\"ab\".repeat(a));\n }\n if (a == 0){\n sb.append(\"b\".repeat(b));\n }\n if (b == 0){\n sb.append(\"a\".repeat(a));\n }\n return sb.toString();\n }\n}", + "title": "984. String Without AAA or BBB", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers a and b , return any string s such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,", + "The substring 'aaa' does not occur in s , and", + "The substring 'bbb' does not occur in s ." + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2Output:\"abb\"Explanation:\"abb\", \"bab\" and \"bba\" are all correct answers.", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 1Output:\"aabaa\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if a<3 and b<3:\n return 'a'*a+'b'*b\n s=''\n if a>=b:\n k=a//b\n \n if a//b!=a/b:\n \n k+=1\n if k>=3:\n k=2\n while a>0 or b>0:\n \n if a>k:\n s+='a'*k \n else:\n s+='a'*a\n a-=k\n if b>0:\n s+='b'\n b-=1\n if a==b:\n k=1\n if a=3:\n k=2\n while b>0 or a>0:\n \n if b>k:\n s+='b'*k \n else:\n s+='b'*b\n b-=k\n if a>0:\n s+='a'\n a-=1\n if a==b:\n k=1\n return s\n", + "title": "984. String Without AAA or BBB", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A password is considered strong if the below conditions are all met: Given a string password , return the minimum number of steps required to make password strong. if password is already strong, return 0 . In one step, you can: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It has at least 6 characters and at most 20 characters.", + "It contains at least one lowercase letter, at least one uppercase letter, and at least one digit .", + "It does not contain three repeating characters in a row (i.e., \"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"a\"Output:5", + "image": null + }, + { + "text": "Example 2: Input:password = \"aA1\"Output:3", + "image": null + }, + { + "text": "Example 3: Input:password = \"1337C0d3\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int MIN_LENGTH = 6;\n private static final int MAX_LENGTH = 20;\n\n public int strongPasswordChecker(String password) {\n int numMissingComponents = getNumberOfMissingComponents(password);\n int n = password.length();\n\n if (n < MIN_LENGTH) {\n return Math.max(numMissingComponents, MIN_LENGTH - n);\n }\n\n List repeats = buildRepeatList(password);\n\n int over = Math.max(0, n - MAX_LENGTH);\n int numRemoval = over;\n\n // use overage for repeat % 3 == 0 case. One removal would reduce one replacement\n for (int i = 0; i < repeats.size() && over > 0; i++) {\n int repeat = repeats.get(i);\n if (repeat >= 3 && repeat % 3 == 0) {\n repeats.set(i, repeat - 1);\n over--;\n }\n }\n // use overage for repeat % 3 == 1 case. Two removal would reduce one replacement\n for (int i = 0; i < repeats.size() && over > 0; i++) {\n int repeat = repeats.get(i);\n if (repeat >= 3 && repeat % 3 == 1) {\n repeats.set(i, repeat - Math.min(over, 2));\n over -= Math.min(over, 2);\n }\n }\n\n int numReplace = 0;\n for (int repeat : repeats) {\n if (over > 0 && repeat >= 3) {\n int reduce = Math.min(over, repeat - 2);\n over -= reduce;\n repeat -= reduce;\n }\n if (repeat >= 3) {\n numReplace += repeat / 3;\n }\n }\n\n return Math.max(numReplace, numMissingComponents) + numRemoval;\n }\n\n private List buildRepeatList(String password) {\n List repeats = new ArrayList<>();\n for (int i = 0; i < password.length(); i++) {\n if (i == 0 || password.charAt(i) != password.charAt(i - 1)) {\n repeats.add(1);\n } else {\n int last = repeats.size() - 1;\n repeats.set(last, repeats.get(last) + 1);\n }\n }\n return repeats;\n }\n\n private int getNumberOfMissingComponents(String password) {\n int digit = 1;\n int upper = 1;\n int lower = 1;\n for (char c: password.toCharArray()) {\n if (Character.isDigit(c)) {\n digit = 0;\n }\n if (Character.isLowerCase(c)) {\n lower = 0;\n }\n if (Character.isUpperCase(c)) {\n upper = 0;\n }\n }\n return digit + upper + lower;\n }\n}\n", + "title": "420. Strong Password Checker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A password is considered strong if the below conditions are all met: Given a string password , return the minimum number of steps required to make password strong. if password is already strong, return 0 . In one step, you can: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It has at least 6 characters and at most 20 characters.", + "It contains at least one lowercase letter, at least one uppercase letter, and at least one digit .", + "It does not contain three repeating characters in a row (i.e., \"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"a\"Output:5", + "image": null + }, + { + "text": "Example 2: Input:password = \"aA1\"Output:3", + "image": null + }, + { + "text": "Example 3: Input:password = \"1337C0d3\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def strongPasswordChecker(self, password: str) -> int:\n #vimla_kushwaha\n s = password\n missing_type = 3\n if any('a' <= c <= 'z' for c in s): missing_type -= 1\n if any('A' <= c <= 'Z' for c in s): missing_type -= 1\n if any(c.isdigit() for c in s): missing_type -= 1\n\n change = 0\n one = two = 0\n p = 2\n while p < len(s):\n if s[p] == s[p-1] == s[p-2]:\n length = 2\n while p < len(s) and s[p] == s[p-1]:\n length += 1\n p += 1\n \n change += length // 3\n if length % 3 == 0: one += 1\n elif length % 3 == 1: two += 1\n else:\n p += 1\n \n if len(s) < 6:\n return max(missing_type, 6 - len(s))\n elif len(s) <= 20:\n return max(missing_type, change)\n else:\n delete = len(s) - 20\n \n change -= min(delete, one)\n change -= min(max(delete - one, 0), two * 2) // 2\n change -= max(delete - one - 2 * two, 0) // 3\n \n return int(delete + max(missing_type, change))\n", + "title": "420. Strong Password Checker", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "A password is said to be strong if it satisfies all the following criteria: Given a string password , return true if it is a strong password . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It has at least 8 characters.", + "It contains at least one lowercase letter.", + "It contains at least one uppercase letter.", + "It contains at least one digit .", + "It contains at least one special character . The special characters are the characters in the following string: \"!@#$%^&*()-+\" .", + "It does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"IloveLe3tcode!\"Output:trueExplanation:The password meets all the requirements. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:password = \"Me+You--IsMyDream\"Output:falseExplanation:The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.", + "image": null + }, + { + "text": "Example 3: Input:password = \"1aB!\"Output:falseExplanation:The password does not meet the length requirement. Therefore, we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean strongPasswordCheckerII(String password) {\n HashSet intAscii = new HashSet<>();\n String specialCharacters = \"!@#$%^&*()-+\";\n for (int i = 0; i < specialCharacters.length(); i++) {\n int ascii = specialCharacters.charAt(i);\n intAscii.add(ascii);\n }\n \n if(password.length() < 8){\n return false;\n }\n boolean small = false;\n boolean large = false;\n boolean numbers = false;\n boolean specialChars = false;\n for(int i = 0 ; i < password.length() ; i++){\n int ascii = (int)(password.charAt(i));\n if(ascii <= 90 && ascii>=65){\n large = true;\n }\n if(ascii <= 122 && ascii>=97){\n small = true;\n }\n if(ascii <=57 && ascii >=48){\n numbers = true;\n }\n if(intAscii.contains(ascii)){\n specialChars = true;\n }\n if(i> 0 && password.charAt(i)== password.charAt(i-1)){\n return false;\n }\n }\n if(large == false || small == false || numbers == false || specialChars ==false){\n return false;\n }\n return true;\n }\n}\n", + "title": "2299. Strong Password Checker II", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A password is said to be strong if it satisfies all the following criteria: Given a string password , return true if it is a strong password . Otherwise, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "It has at least 8 characters.", + "It contains at least one lowercase letter.", + "It contains at least one uppercase letter.", + "It contains at least one digit .", + "It contains at least one special character . The special characters are the characters in the following string: \"!@#$%^&*()-+\" .", + "It does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not)." + ], + "examples": [ + { + "text": "Example 1: Input:password = \"IloveLe3tcode!\"Output:trueExplanation:The password meets all the requirements. Therefore, we return true.", + "image": null + }, + { + "text": "Example 2: Input:password = \"Me+You--IsMyDream\"Output:falseExplanation:The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.", + "image": null + }, + { + "text": "Example 3: Input:password = \"1aB!\"Output:falseExplanation:The password does not meet the length requirement. Therefore, we return false.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 11.66%) | Memory: 13.9 MB (Top 19.37%)\n\nclass Solution:\n def strongPasswordCheckerII(self, pwd: str) -> bool:\n return (\n len(pwd) > 7\n and max(len(list(p[1])) for p in groupby(pwd)) == 1\n and reduce(\n lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0\n ) == 15\n )", + "title": "2299. Strong Password Checker II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: The student is eligible for an attendance award if they meet both of the following criteria: Return true if the student is eligible for an attendance award, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PPALLP\"Output:trueExplanation:The student has fewer than 2 absences and was never late 3 or more consecutive days.", + "image": null + }, + { + "text": "Example 2: Input:s = \"PPALLL\"Output:falseExplanation:The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkRecord(String s) {\n\n int size=s.length();\n if(s.replace(\"A\",\"\").length()<=size-2||s.indexOf(\"LLL\")!=-1)return false;\n\n return true;\n\n }\n}", + "title": "551. Student Attendance Record I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: The student is eligible for an attendance award if they meet both of the following criteria: Return true if the student is eligible for an attendance award, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PPALLP\"Output:trueExplanation:The student has fewer than 2 absences and was never late 3 or more consecutive days.", + "image": null + }, + { + "text": "Example 2: Input:s = \"PPALLL\"Output:falseExplanation:The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 76 ms (Top 5.14%) | Memory: 13.9 MB (Top 11.51%)\nclass Solution:\n def checkRecord(self, s: str) -> bool:\n eligible = True\n\n for i in range(0, len(s)-2):\n if s[i:i+3] == \"LLL\":\n eligible = False\n absent = 0\n for i in range(len(s)):\n if s[i] == \"A\":\n absent +=1\n\n if absent>=2:\n eligible = False\n\n return(eligible)", + "title": "551. Student Attendance Record I", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: Any student is eligible for an attendance award if they meet both of the following criteria: Given an integer n , return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:8Explanation:There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:3", + "image": null + }, + { + "text": "Example 3: Input:n = 10101Output:183236316", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 343 ms (Top 29.4%) | Memory: 78.58 MB (Top 12.2%)\n\nclass Solution {\n int mod=1000000000+7;\n public int checkRecord(int n) {\n int[][][] cache=new int[n+1][2][3];\n for(int i=0; i<=n; i++){\n for(int j=0; j<2; j++){\n for(int k=0; k<3; k++)cache[i][j][k]=-1;\n }\n }\n return populate(n, 0, 1, 2, cache);\n }\n public int populate(int n, int ptr, int aCount, int lCount, int[][][] cache){\n if(ptr>=n)return 1;\n if(cache[ptr][aCount][lCount]!=-1)return cache[ptr][aCount][lCount];\n long count=0;\n // Late\n if(lCount>0){\n count=populate(n, ptr+1, aCount, lCount-1, cache)%mod;\n }\n // Present\n count=(count+populate(n, ptr+1, aCount, 2, cache))%mod;\n // Absent\n if(aCount==1)count=(count+populate(n, ptr+1, aCount-1, 2, cache))%mod;\n cache[ptr][aCount][lCount]=(int)(count%mod);\n return cache[ptr][aCount][lCount];\n }\n}", + "title": "552. Student Attendance Record II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: Any student is eligible for an attendance award if they meet both of the following criteria: Given an integer n , return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "'A' : Absent.", + "'L' : Late.", + "'P' : Present." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:8Explanation:There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:3", + "image": null + }, + { + "text": "Example 3: Input:n = 10101Output:183236316", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 228 ms (Top 90.78%) | Memory: 35.80 MB (Top 36.89%)\n\nimport numpy as np\n\nclass Solution:\n \n def checkRecord(self, n: int) -> int:\n MODULUS = 10**9 + 7\n\n initial_counts = np.array(\n [1, 0, 0, 0, 0, 0], \n dtype=np.int64\n )\n\n adjacency_matrix = np.array([\n [1, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n ], dtype=np.int64)\n\n def power(A, exp):\n B = np.identity(len(A), dtype=np.int64)\n for bit in reversed(bin(exp)[2:]):\n if bit == '1':\n B = B @ A\n B %= MODULUS\n A = A @ A\n A %= MODULUS\n return B\n\n final_counts = power(adjacency_matrix, n) @ initial_counts\n\n return sum(final_counts) % MODULUS\n", + "title": "552. Student Attendance Record II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "1 <= nums[i] <= 1000", + "0 <= k <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,5,2,6], k = 100Output:8Explanation:The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 19.32%) | Memory: 47.80 MB (Top 5.49%)\n\nclass Solution {\n public int numSubarrayProductLessThanK(int[] nums, int k) {\n int n = nums.length;\n long p = 1l;\n int i = 0;\n int j = 0;\n int total = 0;\n while(j < n){\n p *= nums[j];\n while(i <= j&&p >= k){\n p /= nums[i];\n i++;\n }\n total += (j - i + 1);\n j++;\n }\n return total;\n }\n}", + "title": "713. Subarray Product Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers nums and an integer k , return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "1 <= nums[i] <= 1000", + "0 <= k <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,5,2,6], k = 100Output:8Explanation:The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n if k==0 or k==1:\n return 0\n p=1\n ini=0\n fin=0\n n=len(nums)\n c=0\n while fin=k :\n p=p//nums[ini]\n ini+=1\n\n n1=fin-ini+1\n c+=n1\n fin+=1\n return c\n", + "title": "713. Subarray Product Less Than K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the total number of subarrays whose sum equals to k . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-1000 <= nums[i] <= 1000", + "-10^7 <= k <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1], k = 2Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 3Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 80 ms (Top 15.87%) | Memory: 68.2 MB (Top 25.50%)\n/*\nRuntime: 21 ms, faster than 98.97% of Java online submissions for Subarray Sum Equals K.\nMemory Usage: 47.1 MB, less than 85.93% of Java online submissions for Subarray Sum Equals K.\n*/\nclass Solution {\n public int subarraySum(int[] nums, int k) {\n\n HashMap map = new HashMap<>();\n map.put(0,1);\n int count = 0;\n int sum = 0;\n\n for(int i=0; i int:\n\n\t\tans=0\n\t\tprefsum=0\n\t\td={0:1}\n\n\t\tfor num in nums:\n\t\t\tprefsum = prefsum + num\n\n\t\t\tif prefsum-k in d:\n\t\t\t\tans = ans + d[prefsum-k]\n\n\t\t\tif prefsum not in d:\n\t\t\t\td[prefsum] = 1\n\t\t\telse:\n\t\t\t\td[prefsum] = d[prefsum]+1\n\n\t\treturn ans\n", + "title": "560. Subarray Sum Equals K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of non-empty subarrays that have a sum divisible by k . A subarray is a contiguous part of an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "2 <= k <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,0,-2,-3,1], k = 5Output:7Explanation:There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 9Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int subarraysDivByK(int[] nums, int k) {\n HashMap map = new HashMap<>();\n int count = 0;\n int sum = 0;\n for(int i=0;i 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int validSubarraySize(int[] nums, int threshold) {\n int n = nums.length;\n int[] next_small = new int[n];\n int[] prev_small = new int[n];\n Stack stack = new Stack<>();\n stack.push(0);\n Arrays.fill(next_small, n);\n Arrays.fill(prev_small, -1);\n for(int i=1;i= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n prev_small[i] = stack.peek();\n }\n stack.push(i);\n }\n stack = new Stack<>();\n stack.push(n-1);\n for(int i=n-2;i>=0;i--){\n while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n next_small[i] = stack.peek();\n }\n stack.push(i);\n }\n for(int i=0;i 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3127 ms (Top 12.36%) | Memory: 28.8 MB (Top 64.23%)\nclass Solution:\n def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n nums = [0] + nums + [0]\n stack = [0]\n for i in range(1,len(nums)):\n while nums[i] < nums[stack[-1]]:\n tmp = nums[stack.pop()]\n if tmp > threshold / (i - stack[-1] - 1):\n return i - stack[-1] - 1\n stack.append(i)\n return -1", + "title": "2334. Subarray With Elements Greater Than Varying Threshold", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums and an integer k , return the number of good subarrays of nums . A good array is an array where the number of different integers in that array is exactly k . A subarray is a contiguous part of an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1,2,3,1,2] has 3 different integers: 1 , 2 , and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,3], k = 2Output:7Explanation:Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,4], k = 3Output:3Explanation:Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 139 ms (Top 8.32%) | Memory: 69.1 MB (Top 62.69%)\n\nclass Solution {\n public int subarraysWithKDistinct(int[] nums, int k) {\n return count(nums, k) - count(nums, k - 1);\n }\n\n public int count(int[] nums, int k){\n HashMap hm = new HashMap<>();\n\n int left = 0, right = 0, ans = 0;\n\n while(right < nums.length){\n hm.put(nums[right] , hm.getOrDefault(nums[right], 0) + 1);\n\n while(hm.size() == k + 1){\n hm.put(nums[left], hm.get(nums[left]) - 1);\n if(hm.get(nums[left]) == 0)\n hm.remove(nums[left]);\n left++;\n }\n ans += right - left + 1;\n right++;\n }\n return ans;\n\n }\n}", + "title": "992. Subarrays with K Different Integers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums and an integer k , return the number of good subarrays of nums . A good array is an array where the number of different integers in that array is exactly k . A subarray is a contiguous part of an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, [1,2,3,1,2] has 3 different integers: 1 , 2 , and 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,1,2,3], k = 2Output:7Explanation:Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,4], k = 3Output:3Explanation:Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n return self.lengthOfLongestSubstringKDistinct(nums, k) - self.lengthOfLongestSubstringKDistinct(nums, k-1)\n \n def lengthOfLongestSubstringKDistinct(self, s, k):\n n = len(s)\n if n * k == 0:\n return 0\n left = 0\n\n hashmap = collections.OrderedDict()\n\n subarray = 0\n for right in range(n):\n if s[right] in hashmap:\n del hashmap[s[right]]\n hashmap[s[right]] = right\n\n if len(hashmap) == k + 1:\n _, del_idx = hashmap.popitem(last = False)\n left = del_idx + 1\n subarray += right - left + 1\n\n return subarray\n \n \n \n", + "title": "992. Subarrays with K Different Integers", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\" , at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\" . When we visit a domain like \"discuss.leetcode.com\" , we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains , return an array of the count-paired domains of each subdomain in the input . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times." + ], + "examples": [ + { + "text": "Example 1: Input:cpdomains = [\"9001 discuss.leetcode.com\"]Output:[\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]Explanation:We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.", + "image": null + }, + { + "text": "Example 2: Input:cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]Output:[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]Explanation:We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List subdomainVisits(String[] cpdomains) {\n List result = new LinkedList<>();\n HashMap hmap = new HashMap<>();\n \n for(int i = 0; i < cpdomains.length; i++){\n String[] stringData = cpdomains[i].split(\" \");\n String[] str = stringData[1].split(\"\\\\.\");\n String subDomains = \"\";\n \n for(int j = str.length-1; j >= 0; j--){\n subDomains = str[j] + subDomains;\n \n if(!hmap.containsKey(subDomains))\n hmap.put(subDomains, Integer.parseInt(stringData[0]));\n else\n hmap.put(subDomains, hmap.get(subDomains) + Integer.parseInt(stringData[0]));\n subDomains = \".\" + subDomains;\n }\n \n }\n \n for(Map.Entry entry: hmap.entrySet()){\n result.add(entry.getValue() + \" \" + entry.getKey());\n }\n \n return result;\n }\n}\n", + "title": "811. Subdomain Visit Count", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\" , at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\" . When we visit a domain like \"discuss.leetcode.com\" , we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly. A count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. Given an array of count-paired domains cpdomains , return an array of the count-paired domains of each subdomain in the input . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times." + ], + "examples": [ + { + "text": "Example 1: Input:cpdomains = [\"9001 discuss.leetcode.com\"]Output:[\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]Explanation:We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.", + "image": null + }, + { + "text": "Example 2: Input:cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]Output:[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]Explanation:We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n output, ans = {}, []\n for domain in cpdomains : \n number, domain = domain.split(' ')\n sub_domain = domain.split('.')\n pair = ''\n print(sub_domain)\n for i in reversed(range(len(sub_domain))) :\n if i == len(sub_domain)-1 : \n pair += sub_domain[i]\n else : \n pair = sub_domain[i] +'.'+ pair \n print(pair)\n \n # output.append(str(number) + ' '+pair)\n if pair not in output.keys() : \n output[pair] = int(number)\n else : \n output[pair] += int(number)\n \n for key in output.keys() : \n ans.append(str(output[key]) + ' '+key)\n \n return ans\n", + "title": "811. Subdomain Visit Count", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) 2. getValue(int row, int col) Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]Output[null,1,null,5,5,null,10,5]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5", + "image": null + }, + { + "text": "Example 2: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]Output[null,1,null,100,100,null,20]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 53 ms (Top 20.07%) | Memory: 56.2 MB (Top 15.31%)\nclass SubrectangleQueries {\n int[][] rectangle;\n public SubrectangleQueries(int[][] rectangle) {\n this.rectangle = rectangle;\n }\n\n public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n for(int i=row1;i<=row2;i++){\n for(int j=col1;j<=col2;j++){\n rectangle[i][j] = newValue;\n }\n }\n }\n\n public int getValue(int row, int col) {\n return this.rectangle[row][col];\n }\n}\n\n/**\n * Your SubrectangleQueries object will be instantiated and called as such:\n * SubrectangleQueries obj = new SubrectangleQueries(rectangle);\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue);\n * int param_2 = obj.getValue(row,col);\n */", + "title": "1476. Subrectangle Queries", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) 2. getValue(int row, int col) Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2) ." + ], + "examples": [ + { + "text": "Example 1: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]Output[null,1,null,5,5,null,10,5]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5", + "image": null + }, + { + "text": "Example 2: Input[\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]Output[null,1,null,100,100,null,20]ExplanationSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20", + "image": null + } + ], + "follow_up": null, + "solution": "class SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.rectangle = rectangle\n\n def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n for i in range(row1,row2+1):\n for j in range(col1,col2+1):\n self.rectangle[i][j] = newValue\n \n def getValue(self, row: int, col: int) -> int:\n return self.rectangle[row][col]\n", + "title": "1476. Subrectangle Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n private static void solve(int[] nums, int i, List temp, List> subset){\n \n if(i == nums.length){\n subset.add(new ArrayList(temp));\n return;\n }\n \n temp.add(nums[i]);\n solve(nums, i + 1, temp, subset);\n \n temp.remove(temp.size() - 1);\n solve(nums, i + 1, temp, subset);\n }\n \n public List> subsets(int[] nums) {\n List> subset = new ArrayList();\n List temp = new ArrayList<>();\n \n if(nums.length == 0) return subset;\n\n int startInd = 0;\n \n solve(nums, startInd, temp, subset);\n \n return subset;\n }\n}\n", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 8.76%) | Memory: 14.1 MB (Top 82.26%)\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n self.final_list = []\n def subset(final_list,curr_list,listt,i):\n if i == len(listt):\n final_list.append(curr_list)\n return\n else:\n subset(final_list,curr_list,listt,i+1)\n subset(final_list,curr_list+[listt[i]],listt,i+1)\n subset(self.final_list,[],nums,0)\n return self.final_list", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]Output:[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 99.9%) | Memory: 44.19 MB (Top 7.0%)\n\nclass Solution {\n public List> subsetsWithDup(int[] nums) {\n // Sort the input array to handle duplicates properly\n Arrays.sort(nums);\n // Start the recursion with an empty prefix list\n return subset(new ArrayList(), nums);\n }\n \n // Recursive function to generate subsets\n public List> subset(ArrayList prefix, int[] nums) {\n List> result = new ArrayList<>();\n \n // Base case: If there are no elements in nums, add the current prefix to result\n if (nums.length == 0) {\n result.add(new ArrayList<>(prefix));\n return result;\n }\n \n // Include the first element of nums in the prefix\n ArrayList withCurrent = new ArrayList<>(prefix);\n withCurrent.add(nums[0]);\n \n // Recursive call with the first element included\n List> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));\n \n List> right = new ArrayList<>();\n \n // Check for duplicates in the prefix and decide whether to include the first element again\n if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {\n // If the current element is a duplicate, don't include it in the prefix\n // This avoids generating duplicate subsets\n } else {\n // If the current element is not a duplicate, include it in the prefix\n right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));\n }\n \n // Combine the subsets with and without the current element\n left.addAll(right);\n return left;\n }\n}", + "title": "90. Subsets II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,2]Output:[[],[1],[1,2],[1,2,2],[2],[2,2]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n ans = []\n nums.sort()\n def subset(p, up):\n if len(up) == 0:\n if p not in ans:\n ans.append(p)\n return \n ch = up[0]\n subset(p+[ch], up[1:])\n subset(p, up[1:])\n subset([], nums)\n return ans", + "title": "90. Subsets II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated. Return the starting indices of all the concatenated substrings in s . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]Output:[0,9]Explanation:Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.", + "image": null + }, + { + "text": "Example 2: Input:s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]Output:[]Explanation:Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]Output:[6,9,12]Explanation:Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 68 ms (Top 73.46%) | Memory: 43.2 MB (Top 88.65%)\nclass Solution {\n public List findSubstring(String s, String[] words) {\n\n HashMap input = new HashMap<>();\n int ID = 1;\n HashMap count = new HashMap<>();\n for(String word: words) {\n if(!input.containsKey(word))\n input.put(word, ID++);\n int id = input.get(word);\n count.put(id,count.getOrDefault(id,0)+1);\n\n }\n int len = s.length();\n int wordLen = words[0].length();\n int numWords = words.length;\n int windowLen = wordLen*numWords;\n int lastIndex = s.length()-windowLen;\n\n int curWordId[] = new int[len];\n String cur = \" \"+s.substring(0,wordLen-1);\n\n //Change to int array\n for(int i = 0; i< (len-wordLen+1); i++) {\n cur = cur.substring(1, cur.length())+s.charAt(i+wordLen-1);\n if(input.containsKey(cur)){\n curWordId[i] = input.get(cur);\n } else {\n curWordId[i] = -1;\n }\n }\n List res = new ArrayList<>();\n\n //compare using int make it faster 30 times in each comparison\n for(int i = 0; i<= lastIndex; i++) {\n\n HashMap winMap = new HashMap<>();\n for(int j = 0; j < windowLen && curWordId[i] != -1; j+=wordLen) {\n\n int candidate = curWordId[j+i];\n\n if(!count.containsKey(candidate))\n break;\n else{\n winMap.put(candidate, winMap.getOrDefault(candidate, 0)+1);\n }\n if(winMap.get(candidate) > count.get(candidate))\n break;\n\n if(j == (windowLen - wordLen) && winMap.size() == count.size()){\n res.add(i);\n\n }\n\n }\n }\n\n return res;\n }\n}", + "title": "30. Substring with Concatenation of All Words", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated. Return the starting indices of all the concatenated substrings in s . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]Output:[0,9]Explanation:Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.", + "image": null + }, + { + "text": "Example 2: Input:s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]Output:[]Explanation:Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.", + "image": null + }, + { + "text": "Example 3: Input:s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]Output:[6,9,12]Explanation:Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1522 ms (Top 17.46%) | Memory: 14.2 MB (Top 76.15%)\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n req={}\n for i in words:\n req[i]=1+req.get(i,0)\n l=0\n r=len(words)*len(words[0])\n ans=[]\n\n while r 0)\n maxVariance = Math.max(maxVariance, currBFreq - currAFreq);\n \n if(currBFreq < currAFreq && remainingA >= 1){\n currBFreq = 0;\n currAFreq = 0;\n }\n }\n }\n }\n \n return maxVariance;\n }\n}", + "title": "2272. Substring With Largest Variance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s . A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aababbb\"Output:3Explanation:All possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings \"a\", \"aa\", \"ab\", \"abab\", \"aababb\", \"ba\", \"b\", \"bb\", and \"bbb\".\n- Variance 1 for substrings \"aab\", \"aba\", \"abb\", \"aabab\", \"ababb\", \"aababbb\", and \"bab\".\n- Variance 2 for substrings \"aaba\", \"ababbb\", \"abbb\", and \"babb\".\n- Variance 3 for substring \"babbb\".\nSince the largest possible variance is 3, we return it.", + "image": null + }, + { + "text": "Example 2: Input:s = \"abcde\"Output:0Explanation:No letter occurs more than once in s, so the variance of every substring is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n class Solution:\n def largestVariance(self, s: str) -> int:\n \n def maxSubArray(nums: List[int]):\n ans=-float('inf')\n runningSum=0\n seen=False\n for x in (nums):\n if x<0:\n seen=True\n runningSum+=x\n if seen:\n ans=max(ans,runningSum)\n else:\n ans=max(ans,runningSum-1)\n if runningSum<0:\n runningSum=0\n seen=False\n return ans\n \n f=set()\n a=''\n for x in s:\n if x not in f:\n a+=x\n f.add(x)\n \n n=len(s)\n res=0\n for j in range(len(a)-1):\n for k in range(j+1,len(a)):\n x=a[j]\n y=a[k]\n arr=[]\n for i in range(n):\n if s[i]!=x and s[i]!=y:\n continue\n elif s[i]==x:\n arr.append(1)\n else:\n arr.append(-1)\n \n res=max(res,maxSubArray(arr),maxSubArray([-x for x in arr]))\n \n return res\n \n \n \n \n\n", + "title": "2272. Substring With Largest Variance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A string is good if there are no repeated characters. Given a string s ​​​​​, return the number of good substrings of length three in s ​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s ​​​​​​ consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"xyzzaz\"Output:1Explanation:There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \nThe only good substring of length 3 is \"xyz\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aababcabc\"Output:4Explanation:There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\nThe good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countGoodSubstrings(String s) {\n int res = 0;\n \n for(int i = 2 ; i< s.length();i++)\n if(s.charAt(i) != s.charAt(i-1) && s.charAt(i) != s.charAt(i-2) && s.charAt(i-1) != s.charAt(i-2))\n res++;\n return res;\n }\n}\n", + "title": "1876. Substrings of Size Three with Distinct Characters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 234Output:15Explanation:Product of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15", + "image": null + }, + { + "text": "Example 2: Input:n = 4421Output:21Explanation:Product of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 39.3 MB (Top 90.51%)\nclass Solution {\n public int subtractProductAndSum(int n) {\n int mul=1,sum=0;\n while(n!=0){\n sum=sum+n%10;\n mul=mul*(n%10);\n n=n/10;\n }\n return mul-sum;\n }\n}", + "title": "1281. Subtract the Product and Sum of Digits of an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 234Output:15Explanation:Product of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15", + "image": null + }, + { + "text": "Example 2: Input:n = 4421Output:21Explanation:Product of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def subtractProductAndSum(self, n: int) -> int:\n n_to_list = list(str(n))\n \n sum_of_digits = 0 \n for num in n_to_list:\n sum_of_digits = sum_of_digits + int(num)\n \n product_of_digits = 1\n for num in n_to_list:\n product_of_digits = product_of_digits * int(num)\n \n answer = product_of_digits - sum_of_digits\n \n return answer\n", + "title": "1281. Subtract the Product and Sum of Digits of an Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,4,5,1,2], subRoot = [4,1,2]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if subRoot == None:\n return True\n if root == None:\n return False\n \n sameTree = self.isSameTree(root, subRoot)\n subTreeOnLeft = self.isSubtree(root.left, subRoot)\n subTreeOnRight = self.isSubtree(root.right, subRoot)\n \n return subTreeOnLeft or subTreeOnRight or sameTree\n \n def isSameTree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if (root == None and subRoot == None):\n return True\n \n if (root == None or subRoot == None):\n return False\n \n if (root.val != subRoot.val):\n return False\n \n return self.isSameTree(root.left, subRoot.left) and self.isSameTree(root.right, subRoot.right)\n", + "title": "572. Subtree of Another Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7Output:[4,0,3]Explanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16Output:[2,0,2]Explanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 40 ms (Top 80.4%) | Memory: 58.00 MB (Top 19.8%)\n\nclass Solution {\n public int[] successfulPairs(int[] spells, int[] potions, long success) {\n int n = spells.length;\n int m = potions.length;\n int[] pairs = new int[n];\n Arrays.sort(potions);\n for (int i = 0; i < n; i++) {\n int spell = spells[i];\n int left = 0;\n int right = m - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n long product = (long) spell * potions[mid];\n if (product >= success) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n pairs[i] = m - left;\n }\n return pairs;\n }\n}\n", + "title": "2300. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7Output:[4,0,3]Explanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16Output:[2,0,2]Explanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 3070 ms (Top 29.46%) | Memory: 37.4 MB (Top 40.00%)\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n result = self.function(spells,potions,success)\n return result\n\n def function(self,arr1,arr2,success):\n n2 = len(arr2)\n arr2.sort() #Sorting Enables Us To Do Binary Search\n ans = []\n for i in arr1:\n val = math.ceil(success/i) #Finding the Value Of Portion With Least Strength So That It Can Be Greater Than Success\n idx = bisect.bisect_left(arr2,val) #Finding The Left Most Index So That The Value Can Be Inserted\n res = n2-idx+1 #Calculating the remaining numbers after finding the suitable index\n ans.append(res-1)\n return ans", + "title": "2300. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules : The '.' character indicates empty cells. Example 1:", + "description_images": [], + "constraints": [ + "board.length == 9", + "board[i].length == 9", + "board[i][j] is a digit or '.' .", + "It is guaranteed that the input board has only one solution." + ], + "examples": [ + { + "text": "Example 1: 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:[[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]Explanation:The input board is shown above and the only valid solution is shown below:", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 25 ms (Top 30.53%) | Memory: 41.7 MB (Top 44.25%)\nclass Solution {\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n boolean solve(char board[][]){\n for(int i = 0; i None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n full = set('123456789')\n\t\t# lets keep rows, columns and boxes sets in hashmaps\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n boxes = [[set() for _ in range(3)] for _ in range(3)]\n\t\t# and remember empty cell to fill them in\n empty = set()\n\n for i in range(9):\n for j in range(9):\n if board[i][j] == '.':\n empty.add((i,j))\n continue\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n def options(i, j):\n\t\t\t\"\"\"returns possible options for i,j intersecting options from row, col and box\"\"\"\n return (\n (full - rows[i]) &\n (full - cols[j]) &\n (full - boxes[i//3][j//3])\n )\n\n psingle = True # did we have single option decisions in previos traverse\n while empty:\n single = False # for single option decisions in this traverse\n \n for i, j in deepcopy(empty):\n opts = options(i, j)\n if len(opts) == 0:\n\t\t\t\t\t# we've made a wrong assumption - sudoku is unsolvable\n return None, None\n elif len(opts) == 2 and not psingle: # we have no single-option decisions so have to take an assumption\n board1 = deepcopy(board)\n board1[i][j] = opts.pop()\n board1, empty1 = self.solveSudoku(board1)\n if board1 != None: # if solved - we're done\n empty = empty1\n for i, b1 in enumerate(board1):\n board[i] = b1 # have to modify initial list, not just replace the reference\n return board, empty\n if len(opts) == 1: # hey, we have a predetermined choice. nice\n single = True\n board[i][j] = opts.pop()\n empty.remove((i, j))\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n psingle = single\n\n return board, empty\n ```", + "title": "37. Sudoku Solver", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Alice and Bob take turns playing a game, with Alice starting first . You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num : The game ends when there are no more '?' characters in num . For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal . Assuming Alice and Bob play optimally , return true if Alice will win and false if Bob will win . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the game ended with num = \"243801\" , then Bob wins because 2+4+3 = 8+0+1 . If the game ended with num = \"243803\" , then Alice wins because 2+4+3 != 8+0+3 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5023\"Output:falseExplanation:There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.", + "image": null + }, + { + "text": "Example 2: Input:num = \"25??\"Output:trueExplanation:Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.", + "image": null + }, + { + "text": "Example 3: Input:num = \"?3295???\"Output:falseExplanation:It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 18 ms (Top 22.45%) | Memory: 50.6 MB (Top 24.49%)\nclass Solution {\n public boolean sumGame(String num) {\n int q = 0, d = 0, n = num.length();\n for (int i = 0; i < n; i++){\n if (num.charAt(i) == '?'){\n q += 2* i < n? 1 : -1;\n }else{\n d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0');\n }\n }\n return (q & 1) > 0 || q * 9 + 2 * d != 0;\n }\n}", + "title": "1927. Sum Game", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Alice and Bob take turns playing a game, with Alice starting first . You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num : The game ends when there are no more '?' characters in num . For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal . Assuming Alice and Bob play optimally , return true if Alice will win and false if Bob will win . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if the game ended with num = \"243801\" , then Bob wins because 2+4+3 = 8+0+1 . If the game ended with num = \"243803\" , then Alice wins because 2+4+3 != 8+0+3 ." + ], + "examples": [ + { + "text": "Example 1: Input:num = \"5023\"Output:falseExplanation:There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.", + "image": null + }, + { + "text": "Example 2: Input:num = \"25??\"Output:trueExplanation:Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.", + "image": null + }, + { + "text": "Example 3: Input:num = \"?3295???\"Output:falseExplanation:It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 173 ms (Top 90.14%) | Memory: 14.9 MB (Top 69.01%)\nclass Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n q_cnt_1 = s1 = 0\n for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n if num[i] == '?':\n q_cnt_1 += 1\n else:\n s1 += int(num[i])\n q_cnt_2 = s2 = 0\n for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n if num[i] == '?':\n q_cnt_2 += 1\n else:\n s2 += int(num[i])\n s_diff = s1 - s2 # calculate sum difference and question mark difference\n q_diff = q_cnt_2 - q_cnt_1\n return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins", + "title": "1927. Sum Game", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i ( 0-indexed ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= nums[i + 1] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,5]Output:[4,3,5]Explanation:Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,6,8,10]Output:[24,15,13,15,21]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 26 ms (Top 7.55%) | Memory: 110.7 MB (Top 79.24%)\nclass Solution {\n public int[] getSumAbsoluteDifferences(int[] nums) {\n int n = nums.length;\n int[] res = new int[n];\n int sumBelow = 0;\n int sumTotal = Arrays.stream(nums).sum();\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n sumTotal -= num;\n res[i] = sumTotal - (n - i - 1) * num + i * num - sumBelow;\n sumBelow += num;\n }\n return res;\n }\n}", + "title": "1685. Sum of Absolute Differences in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i ( 0-indexed ). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^5", + "1 <= nums[i] <= nums[i + 1] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,5]Output:[4,3,5]Explanation:Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,4,6,8,10]Output:[24,15,13,15,21]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 733 ms (Top 62.5%) | Memory: 31.64 MB (Top 85.1%)\n\nfrom itertools import accumulate \n\nclass Solution(object):\n def getSumAbsoluteDifferences(self, nums):\n total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)\n return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumerate(nums), list(accumulate(nums)))]\n ", + "title": "1685. Sum of Absolute Differences in a Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of positive integers arr , return the sum of all possible odd-length subarrays of arr . A subarray is a contiguous subsequence of the array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 100", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,4,2,5,3]Output:58Explanation:The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]Output:3Explanation:There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.", + "image": null + }, + { + "text": "Example 3: Input:arr = [10,11,12]Output:66", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumOddLengthSubarrays(int[] arr) {\n \n // Using two loops in this question...\n int sum = 0;\n for(int i=0 ; i int:\n \n length = len(arr)\n ans = 0\n \n for i in range(length) :\n ans += ((i+1)*(length-i)+1)//2 * arr[i]\n return ans;\n", + "title": "1588. Sum of All Odd Length Subarrays", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "The XOR total of an array is defined as the bitwise XOR of all its elements , or 0 if the array is empty . Given an array nums , return the sum of all XOR totals for every subset of nums . Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3]Output:6Explanation:The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,6]Output:28Explanation:The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,5,6,7,8]Output:480Explanation:The sum of all XOR totals for every subset is 480.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.90 MB (Top 35.14%)\n\nclass Solution {\n int sum=0;\n public int subsetXORSum(int[] nums) {\n sum=0;\n return getAns(nums,0,0);\n }\n \n int getAns(int[] arr,int i,int cur){\n if(i==arr.length){\n return cur;\n }\n return getAns(arr,i+1,cur^arr[i]) + getAns(arr,i+1,cur);\n }\n}\n", + "title": "1863. Sum of All Subset XOR Totals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The XOR total of an array is defined as the bitwise XOR of all its elements , or 0 if the array is empty . Given an array nums , return the sum of all XOR totals for every subset of nums . Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3]Output:6Explanation:The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,1,6]Output:28Explanation:The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,4,5,6,7,8]Output:480Explanation:The sum of all XOR totals for every subset is 480.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 60 ms (Top 83.44%) | Memory: 13.8 MB (Top 70.65%)\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n def sums(term, idx):\n if idx == len(nums):\n return term\n return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)\n\n return sums(0, 0)", + "title": "1863. Sum of All Subset XOR Totals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array nums . For each index i ( 1 <= i <= nums.length - 2 ) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 , if nums[j] < nums[i] < nums[k] , for all 0 <= j < i and for all i < k <= nums.length - 1 .", + "1 , if nums[i - 1] < nums[i] < nums[i + 1] , and the previous condition is not satisfied.", + "0 , if none of the previous conditions holds." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:2Explanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6,4]Output:1Explanation:For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]Output:0Explanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 73.89%) | Memory: 94 MB (Top 67.52%)\nclass Solution {\n public int sumOfBeauties(int[] nums) {\n boolean[] left = new boolean[nums.length];\n boolean[] right = new boolean[nums.length];\n\n left[0] = true;\n int leftMax = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > leftMax) {\n left[i] = true;\n leftMax = nums[i];\n }\n }\n\n right[nums.length-1] = true;\n int rightMin = nums[nums.length-1];\n for(int i = nums.length-2; i >= 0; i--) {\n if(nums[i] < rightMin) {\n right[i] = true;\n rightMin = nums[i];\n }\n }\n\n int beautyCount = 0;\n for(int i = 1; i < nums.length-1; i++) {\n if(left[i] && right[i]) {\n beautyCount += 2;\n }\n\n else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) {\n beautyCount += 1;\n }\n\n }\n return beautyCount;\n }\n}", + "title": "2012. Sum of Beauty in the Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array nums . For each index i ( 1 <= i <= nums.length - 2 ) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 , if nums[j] < nums[i] < nums[k] , for all 0 <= j < i and for all i < k <= nums.length - 1 .", + "1 , if nums[i - 1] < nums[i] < nums[i + 1] , and the previous condition is not satisfied.", + "0 , if none of the previous conditions holds." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:2Explanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6,4]Output:1Explanation:For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]Output:0Explanation:For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n n = len(nums)\n max_dp = [0] * n\n min_dp = [float(inf)] * n\n max_dp[0] = nums[0]\n min_dp[-1] = nums[-1]\n \n for i in range(1, n):\n max_dp[i] = max(nums[i], max_dp[i-1])\n \n for i in range(n-2, -1, -1):\n min_dp[i] = min(nums[i], min_dp[i+1])\n \n ans = 0\n for i in range(1, n-1):\n if max_dp[i-1] < max_dp[i] and nums[i] < min_dp[i+1]:\n ans += 2\n elif nums[i-1] < nums[i] < nums[i+1]:\n ans += 1\n return ans\n", + "title": "2012. Sum of Beauty in the Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s , return the sum of beauty of all of its substrings. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the beauty of \"abaacc\" is 3 - 1 = 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcb\"Output:5Explanation:The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabcbaa\"Output:17", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int getMinCount(int[] charCount) {\n int min = Integer.MAX_VALUE;\n\t\t\n for (int i = 0; i < charCount.length; ++i) {\n if (charCount[i] != 0) {\n min = Math.min(min, charCount[i]);\n }\n }\n\t\t\n return min;\n }\n \n private int getMaxCount(int[] charCount) {\n int max = 0;\n\t\t\n for (int i = 0; i < charCount.length; ++i) {\n max = Math.max(max, charCount[i]);\n }\n\t\t\n return max;\n }\n \n public int beautySum(String s) {\n int sum = 0;\n \n for (int i = 0; i < s.length(); ++i) {\n int[] charCount = new int[26]; // initialize charCount to all 0\n \n for (int j = i; j < s.length(); ++j) {\n ++charCount[s.charAt(j) - 'a'];\n\n\t\t\t\t// get beauty of substring from i to j\n\t\t\t\tint beauty = getMaxCount(charCount) - getMinCount(charCount);\n sum += beauty;\n }\n }\n \n return sum;\n }\n}\n", + "title": "1781. Sum of Beauty of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s , return the sum of beauty of all of its substrings. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the beauty of \"abaacc\" is 3 - 1 = 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabcb\"Output:5Explanation:The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aabcbaa\"Output:17", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def beautySum(self, s: str) -> int:\n c, n, ans = Counter(s), len(s), 0\n for i in range(n-2):\n x=c.copy()\n for j in range(n-1,i+1,-1):\n ans+=max(x.values())-min(x.values())\n if x[s[j]]==1:\n del x[s[j]]\n else:\n x[s[j]]-=1\n if c[s[i]]==1:\n del c[s[i]]\n else:\n c[s[i]]-=1\n return ans\n", + "title": "1781. Sum of Beauty of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n (in base 10 ) and a base k , return the sum of the digits of n after converting n from base 10 to base k . After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "2 <= k <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:n = 34, k = 6Output:9Explanation:34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, k = 10Output:1Explanation:n is already in base 10. 1 + 0 = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.2 MB (Top 20.16%)\nclass Solution {\n public int sumBase(int n, int k) {\n int res = 0;\n for (; n > 0; n /= k)\n res += n % k;\n return res;\n }\n}", + "title": "1837. Sum of Digits in Base K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n (in base 10 ) and a base k , return the sum of the digits of n after converting n from base 10 to base k . After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 100", + "2 <= k <= 10" + ], + "examples": [ + { + "text": "Example 1: Input:n = 34, k = 6Output:9Explanation:34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.", + "image": null + }, + { + "text": "Example 2: Input:n = 10, k = 10Output:1Explanation:n is already in base 10. 1 + 0 = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 40 ms (Top 73.88%) | Memory: 13.8 MB (Top 97.86%)\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n cnt = 0\n while n:\n cnt += (n % k)\n n //= k\n print(cnt)\n return cnt", + "title": "1837. Sum of Digits in Base K", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s consisting of lowercase English letters, and an integer k . First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1 , 'b' with 2 , ..., 'z' with 26 ). Then, transform the integer by replacing it with the sum of its digits . Repeat the transform operation k times in total. For example, if s = \"zbax\" and k = 2 , then the resulting integer would be 8 by the following operations: Return the resulting integer after performing the operations described above . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Convert : \"zbax\" ➝ \"(26)(2)(1)(24)\" ➝ \"262124\" ➝ 262124", + "Transform #1 : 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17", + "Transform #2 : 17 ➝ 1 + 7 ➝ 8" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"iiii\", k = 1Output:36Explanation:The operations are as follows:\n- Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999\n- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36\nThus the resulting integer is 36.", + "image": null + }, + { + "text": "Example 2: Input:s = \"leetcode\", k = 2Output:6Explanation:The operations are as follows:\n- Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545\n- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33\n- Transform #2: 33 ➝ 3 + 3 ➝ 6\nThus the resulting integer is 6.", + "image": null + }, + { + "text": "Example 3: Input:s = \"zbax\", k = 2Output:8", + "image": null + } + ], + "follow_up": null, + "solution": "\nclass Solution {\n public int getLucky(String s, int k) {\n \n StringBuilder sb=new StringBuilder();\n\n for(int i=0;i0 && result.length()>1)\n { \n sum=0;\n for(int i=0;i int:\n nums = [str(ord(c) - ord('a') + 1) for c in s]\n for _ in range(k):\n nums = str(sum(int(digit) for num in nums for digit in num))\n return nums\n", + "title": "1945. Sum of Digits of String After Convert", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i th node in the tree and all other nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 3 * 10^4", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "The given input represents a valid tree." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]Output:[8,12,6,10,10,10]Explanation:The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" + }, + { + "text": "Example 2: Input:n = 1, edges = []Output:[0]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" + }, + { + "text": "Example 3: Input:n = 2, edges = [[1,0]]Output:[1,1]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n private Map> getGraph(int[][] edges) {\n Map> graph = new HashMap<>();\n for(int[] edge: edges) {\n graph.putIfAbsent(edge[0], new LinkedList<>());\n graph.putIfAbsent(edge[1], new LinkedList<>());\n \n graph.get(edge[0]).add(edge[1]);\n graph.get(edge[1]).add(edge[0]); \n }\n \n return graph;\n }\n \n public int[] sumOfDistancesInTree(int n, int[][] edges) { \n if(n < 2 || edges == null) {\n return new int[]{0};\n }\n \n int[] countSubNodes = new int[n];\n Arrays.fill(countSubNodes, 1);\n int[] distances = new int[n];\n Map> graph = getGraph(edges);\n postOrderTraversal(0, -1, countSubNodes, distances, graph);\n preOrderTraversal(0, -1, countSubNodes, distances, graph, n);\n return distances;\n }\n \n private void postOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n postOrderTraversal(child, node, countSubNodes, distances, graph);\n countSubNodes[node] += countSubNodes[child];\n distances[node] += distances[child] + countSubNodes[child];\n }\n }\n }\n \n private void preOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph, int n) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n\t\t\t\tdistances[child] = distances[node] + (n - countSubNodes[child]) - countSubNodes[child];\n\t\t\t\tpreOrderTraversal(child, node, countSubNodes, distances, graph, n); \n }\n }\n }\n}``\n", + "title": "834. Sum of Distances in Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i th node in the tree and all other nodes. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n <= 3 * 10^4", + "edges.length == n - 1", + "edges[i].length == 2", + "0 <= a i , b i < n", + "a i != b i", + "The given input represents a valid tree." + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]Output:[8,12,6,10,10,10]Explanation:The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" + }, + { + "text": "Example 2: Input:n = 1, edges = []Output:[0]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" + }, + { + "text": "Example 3: Input:n = 2, edges = [[1,0]]Output:[1,1]", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 1783 ms (Top 30.42%) | Memory: 59.4 MB (Top 95.18%)\nfrom typing import List\n\nROOT_PARENT = -1\n\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n @see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N)\n :param n:\n :param edges:\n :return:\n \"\"\"\n g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree\n\n root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)\n\n # considering \"root\" as starting node, we create a tree.\n # Now defining,\n # tree_nodes[i] = number of nodes in the tree rooted at node i\n # distances[i] = sum of distances of all nodes from ith node to all the\n # other nodes of the tree\n tree_nodes, distances = [0] * n, [0] * n\n\n def postorder(rt: int, parent: int):\n \"\"\"\n updating tree_nodes and distances from children of rt. To update them, we must know their\n values at children. And that is why post order traversal is used\n\n After the traversal is done,\n tree_nodes[rt] = all the nodes in tree rooted at rt\n distances[rt] = sum of distances from rt to all the nodes of tree rooted at rt\n\n :param rt:\n :param parent:\n \"\"\"\n tree_nodes[rt] = 1\n\n for c in g[rt]:\n if c != parent:\n postorder(c, rt)\n\n # adding number of nodes in subtree rooted at c to tree rooted at rt\n tree_nodes[rt] += tree_nodes[c]\n\n # moving to rt from c will increase distances by nodes in tree rooted at c\n distances[rt] += distances[c] + tree_nodes[c]\n\n def preorder(rt: int, parent: int):\n \"\"\"\n we start with \"root\" and update its children.\n distances[root] = sum of distances between root and all the other nodes in tree.\n\n In this function, we calculate distances[c] with the help of distances[root] and\n that is why preorder traversal is required.\n :param rt:\n :param parent:\n :return:\n \"\"\"\n for c in g[rt]:\n if c != parent:\n distances[c] = (\n (n - tree_nodes[c]) # rt -> c increase this much distance\n +\n (distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance\n )\n preorder(c, rt)\n\n postorder(root, ROOT_PARENT)\n preorder(root, ROOT_PARENT)\n\n return distances\n\n @staticmethod\n def create_undirected_graph(edges: List[List[int]], n: int):\n \"\"\"\n :param edges:\n :param n:\n :return: graph from edges. Note that this undirect graph is a tree. (Any node can be\n picked as root node)\n \"\"\"\n g = [[] for _ in range(n)]\n\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n\n return g", + "title": "834. Sum of Distances in Tree", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an array queries where queries[i] = [val i , index i ] . For each query i , first, apply nums[index i ] = nums[index i ] + val i , then print the sum of the even values of nums . Return an integer array answer where answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "1 <= queries.length <= 10^4", + "-10^4 <= val i <= 10^4", + "0 <= index i < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]Output:[8,6,2,4]Explanation:At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], queries = [[4,0]]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 90.94%) | Memory: 68.3 MB (Top 82.52%)\nclass Solution {\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int sum = 0;\n for (int i : nums) {\n if ((i & 1) == 0) { // (i % 2 == 0)\n sum += i;\n }\n }\n int[] ans = new int[nums.length];\n int k = 0;\n for (int[] q : queries) {\n int idx = q[1];\n if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n sum -= nums[idx];\n }\n nums[idx] += q[0];\n if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n sum += nums[idx];\n }\n ans[k++] = sum;\n }\n return ans;\n }\n}", + "title": "985. Sum of Even Numbers After Queries", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums and an array queries where queries[i] = [val i , index i ] . For each query i , first, apply nums[index i ] = nums[index i ] + val i , then print the sum of the even values of nums . Return an integer array answer where answer[i] is the answer to the i th query . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "1 <= queries.length <= 10^4", + "-10^4 <= val i <= 10^4", + "0 <= index i < nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]Output:[8,6,2,4]Explanation:At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], queries = [[4,0]]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1565 ms (Top 5.26%) | Memory: 20.6 MB (Top 46.36%)\nclass Solution:\n# O(n) || O(1)\n# Runtime: 583ms 72.40% || memory: 20.5mb 37.69%\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n totalEvenNumSum = sum([num for num in nums if num % 2 == 0])\n result = []\n\n for val, idx in queries:\n oldVal = nums[idx]\n nums[idx] += val\n\n if oldVal % 2 == 0:\n totalEvenNumSum -= oldVal\n\n if nums[idx] % 2 == 0:\n totalEvenNumSum += nums[idx]\n\n result.append(totalEvenNumSum)\n\n return result\n", + "title": "985. Sum of Even Numbers After Queries", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7 . The floor() function returns the integer part of the division. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,5,9]Output:10Explanation:floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up.", + "image": null + }, + { + "text": "Example 2: Input:nums = [7,7,7,7,7,7,7]Output:49", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumOfFlooredPairs(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length;\n long cnt[]=new long[nums[n-1]+2];\n for(int num:nums){\n cnt[num+1]++;\n }\n for(int i=1;i int:\n \n incs, counter=[0]*(max(nums)+1), Counter(nums) # To store all the quotients increases; counter\n for num in counter: # Loop over all the divisors\n for j in range(num, len(incs), num): # Loop over all the possible dividends where the quotient increases\n incs[j] += counter[num] # Increment the increases in quotients\n quots=list(accumulate(incs)) # Accumulate the increases to get the sum of quotients\n return sum([quots[num] for num in nums]) % 1_000_000_007 # Sum up all the quotients for all the numbers in the list.\n", + "title": "1862. Sum of Floored Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n , return the sum of the n smallest k-mirror numbers . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.", + "On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100 , which does not read the same both forward and backward." + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, n = 5Output:25Explanation:The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 7Output:499Explanation:The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.", + "image": null + }, + { + "text": "Example 3: Input:k = 7, n = 17Output:20379000Explanation:The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kMirror(self, k: int, n: int) -> int:\n\n def numberToBase(n, b):\n if n == 0:\n return [0]\n digits = []\n while n:\n digits.append(n % b)\n n //= b\n return digits[::-1]\n \n # not used\n def baseToNumber(arr, b):\n ans = 0\n for x in arr:\n ans = ans * b + int(x)\n return ans\n \n def is_mirror(s):\n l, r = 0, len(s)-1\n while l <= r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\n \n def gen():\n '''\n generate for value with different length\n when i == 0: num:[1, 10)\n size of num: 1, 2 -> 1 or 11\n when i == 1: [10, 100)\n size of num: 3, 4 -> 10 or 101\n when i == 2: [100, 1000)\n size of num: 5, 6 -> 10001 or 100001\n \n the num will be increasing\n '''\n for i in range(30):\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1][1:]\n yield int(s)\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1]\n yield int(s)\n \n ans = 0\n left = n\n for num in gen():\n base = numberToBase(num, k)\n\t\t\t# if is_mirror(base):\n if base == base[::-1]:\n ans += num\n left -= 1\n if left == 0:\n break\n\n return ans\n", + "title": "2081. Sum of k-Mirror Numbers", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:24Explanation:There are two left leaves in the binary tree, with values 9 and 15 respectively.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 57.76%)\nclass Solution {\n public int sumOfLeftLeaves(TreeNode root) {\n\n if(root==null)\n return 0;\n\n if(root.left!=null && root.left.left==null && root.left.right==null){\n return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }else{\n return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }\n\n }\n}", + "title": "404. Sum of Left Leaves", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:24Explanation:There are two left leaves in the binary tree, with values 9 and 15 respectively.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "def is_leaf(x):\n return x.left is None and x.right is None\n\nclass Solution:\n def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n if root is None:\n return 0\n if root.left and is_leaf(root.left):\n left = root.left.val\n else:\n left = self.sumOfLeftLeaves(root.left)\n return left + self.sumOfLeftLeaves(root.right)\n", + "title": "404. Sum of Left Leaves", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array arr and a target value target , return the integer value such that when we change all the integers larger than value in the given array to be equal to value , the sum of the array gets as close as possible (in absolute difference) to target . In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i], target <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,9,3], target = 10Output:3Explanation:When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,5], target = 10Output:5", + "image": null + }, + { + "text": "Example 3: Input:arr = [60864,25176,27249,21296,20204], target = 56803Output:11361", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 11 ms (Top 6.67%) | Memory: 47.2 MB (Top 65.28%)\nclass Solution {\n int max = 0;\n int len;\n public int findBestValue(int[] arr, int target) {\n this.len = arr.length;\n\n for (int i = 0; i < len; i++)\n max = Math.max(max, arr[i]);\n\n int l = 0;\n int r = max;\n while(l < r){\n int mid = l + (r-l) / 2;\n\n if(check(arr, mid, target) <= check(arr, mid+1, target))\n r = mid;\n else\n l = mid + 1;\n }\n return l;\n }\n\n private int check(int[] arr, int value, int target){\n int sum = 0;\n for(int e : arr){\n if(e > value)\n sum += value;\n else\n sum += e;\n }\n\n return Math.abs(sum-target);\n }\n}", + "title": "1300. Sum of Mutated Array Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array arr and a target value target , return the integer value such that when we change all the integers larger than value in the given array to be equal to value , the sum of the array gets as close as possible (in absolute difference) to target . In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from arr . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 10^4", + "1 <= arr[i], target <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [4,9,3], target = 10Output:3Explanation:When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.", + "image": null + }, + { + "text": "Example 2: Input:arr = [2,3,5], target = 10Output:5", + "image": null + }, + { + "text": "Example 3: Input:arr = [60864,25176,27249,21296,20204], target = 56803Output:11361", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findBestValue(self, arr: List[int], t: int) -> int:\n def getsum(x):\n s = 0\n for i in range(n):\n if arr[i] > x:\n s += x*(n-i)\n break\n else:\n s += arr[i]\n return s\n\t\t\t\n\t\tarr.sort()\n n = len(arr)\n l, r = 0, max(arr)\n ans = [inf, inf]\n while l <= r:\n m = l+(r-l)//2\n if abs(getsum(m)-t) <= ans[0]:\n if abs(getsum(m)-t) == ans[0]:\n ans[1] = min(m, ans[1])\n else:\n ans = [abs(getsum(m)-t), m]\n if getsum(m) > t:\n r = m-1\n else:\n l = m+1\n \n return ans[1]\n", + "title": "1300. Sum of Mutated Array Closest to Target", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent . If there are no nodes with an even-valued grandparent , return 0 . A grandparent of a node is the parent of its parent if it exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output:18Explanation:The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:0", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int sum=0;\n public int sumEvenGrandparent(TreeNode root) {\n dfs(root,null,null);\n return sum;\n }\n void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) {\n if (current == null) return; // base case \n if (grandParent != null && grandParent.val % 2 == 0) {\n sum += current.val;\n }\n\t\t\t\t//cur->cur.left ||cur.right , parent=cur,grandPrarent=parent\n dfs(current.left, current, parent)\n dfs(current.right, current, parent);\n }\n }\n", + "title": "1315. Sum of Nodes with Even-Valued Grandparent", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent . If there are no nodes with an even-valued grandparent , return 0 . A grandparent of a node is the parent of its parent if it exists. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]Output:18Explanation:The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:0", + "image": "https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef sumEvenGrandparent(self, root: TreeNode) -> int:\n\n\t\tdef dfs(root, p, gp):\n\t\t\tif not root: return 0\n\t\t\tif gp and gp.val%2==0:\n\t\t\t\treturn root.val + dfs(root.left,root,p)+dfs(root.right,root,p)\n\t\t\treturn 0 + dfs(root.left,root,p)+dfs(root.right,root,p)\n\n\t\treturn dfs(root,None,None)", + "title": "1315. Sum of Nodes with Even-Valued Grandparent", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers num and k , consider a set of positive integers with the following properties: Return the minimum possible size of such a set, or -1 if no such set exists. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The units digit of each integer is k .", + "The sum of the integers is num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 58, k = 9Output:2Explanation:One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.", + "image": null + }, + { + "text": "Example 2: Input:num = 37, k = 2Output:-1Explanation:It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.", + "image": null + }, + { + "text": "Example 3: Input:num = 0, k = 7Output:0Explanation:The sum of an empty set is considered 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 90.88%) | Memory: 40.7 MB (Top 84.12%)\n\nclass Solution\n{\n public int minimumNumbers(int num, int k)\n {\n if(num == 0)\n return 0;\n if(k == 0)\n if(num % 10 == 0) //E.g. 20,1590,3000\n return 1;\n else\n return -1;\n for(int i = 1; i <= num/k; i++) // Start with set size 1 and look for set having unit's digit equal to that of num\n if(num % 10 == ((i*k)%10)) // Look for equal unit's digit\n return i;\n\n return -1;\n }\n}", + "title": "2310. Sum of Numbers With Units Digit K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integers num and k , consider a set of positive integers with the following properties: Return the minimum possible size of such a set, or -1 if no such set exists. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The units digit of each integer is k .", + "The sum of the integers is num ." + ], + "examples": [ + { + "text": "Example 1: Input:num = 58, k = 9Output:2Explanation:One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.", + "image": null + }, + { + "text": "Example 2: Input:num = 37, k = 2Output:-1Explanation:It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.", + "image": null + }, + { + "text": "Example 3: Input:num = 0, k = 7Output:0Explanation:The sum of an empty set is considered 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def minimumNumbers(self, num: int, k: int) -> int:\n if num == 0:\n return 0\n \n if k == 0:\n return 1 if num % 10 == 0 else -1\n \n for n in range(1, min(num // k, 10) + 1):\n if (num - n * k) % 10 == 0:\n return n\n \n return -1\n", + "title": "2310. Sum of Numbers With Units Digit K", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree where each node has a value 0 or 1 . Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers . The test cases are generated so that the answer fits in a 32-bits integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the path is 0 -> 1 -> 1 -> 0 -> 1 , then this could represent 01101 in binary, which is 13 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,1,0,1,0,1]Output:22Explanation:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "image": "https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png" + }, + { + "text": "Example 2: Input:root = [0]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.80 MB (Top 51.65%)\n\nclass Solution {\n public int sumRootToLeaf(TreeNode root) {\n return sumRootToLeaf(root, 0);\n }\n public int sumRootToLeaf(TreeNode root, int sum){\n if(root == null) return 0;\n sum = (2 * sum) + root.val;\n if(root.left == null && root.right == null) return sum;\n return sumRootToLeaf(root.left, sum) + sumRootToLeaf(root.right, sum);\n }\n}\n", + "title": "1022. Sum of Root To Leaf Binary Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given the root of a binary tree where each node has a value 0 or 1 . Each root-to-leaf path represents a binary number starting with the most significant bit. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers . The test cases are generated so that the answer fits in a 32-bits integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the path is 0 -> 1 -> 1 -> 0 -> 1 , then this could represent 01101 in binary, which is 13 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,1,0,1,0,1]Output:22Explanation:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22", + "image": "https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png" + }, + { + "text": "Example 2: Input:root = [0]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n def path(root,p,ans):\n p.append(str(root.val))\n if root.left==None and root.right==None:\n t = int(\"\".join(p),2)\n p.pop()\n return t+ans\n if root.left==None:\n t = path(root.right,p,ans)\n p.pop()\n return t\n if root.right==None:\n t = path(root.left,p,ans)\n p.pop()\n return t\n t = path(root.left,p,ans)+path(root.right,p,ans)\n p.pop()\n return t\n return path(root,[],0)\n", + "title": "1022. Sum of Root To Leaf Binary Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n , where the string with length i is labeled s i . The score of s i is the length of the longest common prefix between s i and s n (Note that s == s n ). Given the final string s , return the sum of the score of every s i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, for s = \"abaca\" , s 1 == \"a\" , s 2 == \"ca\" , s 3 == \"aca\" , etc." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babab\"Output:9Explanation:For s1== \"b\", the longest common prefix is \"b\" which has a score of 1.\nFor s2== \"ab\", there is no common prefix so the score is 0.\nFor s3== \"bab\", the longest common prefix is \"bab\" which has a score of 3.\nFor s4== \"abab\", there is no common prefix so the score is 0.\nFor s5== \"babab\", the longest common prefix is \"babab\" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"azbazbzaz\"Output:14Explanation:For s2== \"az\", the longest common prefix is \"az\" which has a score of 2.\nFor s6== \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\nFor s9== \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long[] hsh, hsh2, pw, pw2;\n public int mod = (int) 1e9+7;\n public long sumScores(String s) {\n int n = s.length(), base = 131, base2 = 137;\n hsh = new long[n+1]; pw = new long[n+1];\n hsh2 = new long[n+1]; pw2 = new long[n+1];\n pw[0] = 1; pw2[0] = 1;\n for (int j = 1; j <= n; j++) {\n hsh[j] = (hsh[j-1]*base + s.charAt(j-1))%mod;\n pw[j] = pw[j-1]*base%mod;\n hsh2[j] = (hsh2[j-1]*base2 + s.charAt(j-1))%mod;\n pw2[j] = pw2[j-1]*base2%mod;\n }\n // binary search for score\n long ans = 0;\n for (int i = n; i >= 1; i--) {\n if (s.charAt(i-1)!=s.charAt(0)) continue;\n int lo = 0, hi = n-i+1, res = 0;\n while (lo<=hi) {\n int mid = (lo+hi)>>1;\n if (getSubstrHash(0, mid)==getSubstrHash(i-1, i+mid-1)) {\n lo = mid+1; res = mid;\n }\n else hi = mid-1;\n }\n ans+=res;\n }\n return ans;\n }\n public long getSubstrHash(int l, int r){\n long h1 = (hsh[r] - hsh[l] * pw[r-l] % mod + mod)%mod;\n long h2 = (hsh2[r] - hsh2[l] * pw2[r-l] % mod + mod)%mod;\n return (h1<<31) | h2;\n }\n}\n", + "title": "2223. Sum of Scores of Built Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n , where the string with length i is labeled s i . The score of s i is the length of the longest common prefix between s i and s n (Note that s == s n ). Given the final string s , return the sum of the score of every s i . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, for s = \"abaca\" , s 1 == \"a\" , s 2 == \"ca\" , s 3 == \"aca\" , etc." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babab\"Output:9Explanation:For s1== \"b\", the longest common prefix is \"b\" which has a score of 1.\nFor s2== \"ab\", there is no common prefix so the score is 0.\nFor s3== \"bab\", the longest common prefix is \"bab\" which has a score of 3.\nFor s4== \"abab\", there is no common prefix so the score is 0.\nFor s5== \"babab\", the longest common prefix is \"babab\" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.", + "image": null + }, + { + "text": "Example 2: Input:s = \"azbazbzaz\"Output:14Explanation:For s2== \"az\", the longest common prefix is \"az\" which has a score of 2.\nFor s6== \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\nFor s9== \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 200 ms (Top 85.96%) | Memory: 25.20 MB (Top 24.56%)\n\nclass Solution:\n def sumScores(self, s):\n n = len(s)\n\n dp, ans, j = [1]*n, [0]*n, 0 \n\n for i in range(1,n):\n while s[i] != s[j] and j > 0:\n j = ans[j-1]\n\n if s[i] == s[j]:\n dp[i] += dp[j]\n ans[i] = j+1\n j += 1 \n\n return sum(dp)\n\n\n\n\n\n\n\n \n", + "title": "2223. Sum of Scores of Built Strings", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5Output:trueExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 55.1%) | Memory: 39.57 MB (Top 27.7%)\n\nclass Solution {\n public boolean judgeSquareSum(int c) {\n long a = 0;\n long b = (long) Math.sqrt(c);\n\n while(a<=b){\n if(((a*a) + (b*b)) == c){\n return true;\n }\n else if((((a*a)+(b*b)) < c)){\n a++;\n }\n else{\n b--;\n }\n }\n return false;\n }\n}", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5Output:trueExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 669 ms (Top 21.17%) | Memory: 13.8 MB (Top 63.98%)\nimport math\n\nclass Solution:\n def judgeSquareSum(self, c: int) -> bool:\n\n a = 0\n\n while a ** 2 <= c:\n b = math.sqrt(c - a ** 2)\n\n if b.is_integer():\n return True\n\n a += 1\n\n return False", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr, find the sum of min(b) , where b ranges over every (contiguous) subarray of arr . Since the answer may be large, return the answer modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 3 * 10^4", + "1 <= arr[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,2,4]Output:17Explanation:Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,81,94,43,3]Output:444", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int sumSubarrayMins(int[] arr) {\n int n = arr.length;\n int ans1[] = nsl(arr);\n int ans2[] = nsr(arr);\n long sum=0;\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=arr.length-1;i>=0;i--){\n while(!s.isEmpty() && arr[s.peek()]>=arr[i]){\n s.pop();\n }\n if(s.isEmpty()){\n ans[i] = arr.length-i;\n s.push(i);\n }\n else{\n ans[i] = s.peek()-i;\n s.push(i);\n }\n }\n return ans;\n }\n}\n", + "title": "907. Sum of Subarray Minimums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr, find the sum of min(b) , where b ranges over every (contiguous) subarray of arr . Since the answer may be large, return the answer modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 3 * 10^4", + "1 <= arr[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [3,1,2,4]Output:17Explanation:Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.", + "image": null + }, + { + "text": "Example 2: Input:arr = [11,81,94,43,3]Output:444", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n n = len(arr)\n small_before = [-1]*n\n stack = []\n for i in range(n):\n while stack and arr[stack[-1]] >= arr[i]:\n stack.pop()\n if stack:small_before[i] = stack[-1]\n stack.append(i)\n best = [0]*(n+1)\n ans = 0\n for i in range(n):\n best[i] = best[small_before[i]] + (i - small_before[i])*arr[i]\n ans += best[i]\n return ans%1000000007", + "title": "907. Sum of Subarray Minimums", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:4Explanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,3]Output:4Explanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,-2,-3,4,1]Output:59Explanation:The sum of all subarray ranges of nums is 59.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n class Node{\n long val, displace;\n Node(long val, long displace){\n this.val = val;\n this.displace = displace;\n }\n }\n public long subArrayRanges(int[] nums) {\n \n //lesser than current element\n Stack stack = new Stack<>();\n //from left\n long [] lesserLeft = new long[nums.length];\n for (int i = 0; i< nums.length; i++){\n long count = 1;\n while(stack.size()>0 && stack.peek().val<=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n lesserLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] lesserRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val0 && stack.peek().val>=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] greaterRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val>nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterRight[i] = count;\n } \n \n long ans = 0;\n //Now we subtract the count of minimum occurrences from the count of maximum occurrences\n \n for (int i = 0; i< nums.length; i++){\n ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i];\n }\n return ans;\n }\n}\n", + "title": "2104. Sum of Subarray Ranges", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given an integer array nums . The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:4Explanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,3]Output:4Explanation:The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,-2,-3,4,1]Output:59Explanation:The sum of all subarray ranges of nums is 59.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n n = len(nums)\n \n # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n # so totalsum = maxsum - minsum\n # we calculate minsum and maxsum in two different loops\n minsum = maxsum = 0\n \n # first calculate sum{ Min(subarray) } over all subarrays\n # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1\n # where f(i) is number of subarrays where nums[i] is the minimum value\n # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i]\n # we can claculate these indices in linear time using a monotonically increasing stack.\n stack = []\n for next_smaller in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically increasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]):\n i = stack.pop()\n prev_smaller = stack[-1] if stack else -1\n minsum += nums[i] * (next_smaller - i) * (i - prev_smaller)\n stack.append(next_smaller)\n \n # then calculate sum{ Max(subarray) } over all subarrays\n # sum{ Max(subarray) } = sum(f'(i) * nums[i]) ; i=0..n-1\n # where f'(i) is number of subarrays where nums[i] is the maximum value\n # f'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i]\n # this time we use a monotonically decreasing stack.\n stack = []\n for next_larger in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically decreasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]):\n i = stack.pop()\n prev_larger = stack[-1] if stack else -1\n maxsum += nums[i] * (next_larger - i) * (i - prev_larger)\n stack.append(next_larger)\n \n return maxsum - minsum\n", + "title": "2104. Sum of Subarray Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums , return the sum of the widths of all the non-empty subsequences of nums . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 49 ms (Top 70.11%) | Memory: 74.1 MB (Top 69.83%)\nclass Solution {\n public int sumSubseqWidths(int[] nums) {\n int MOD = (int)1e9 + 7;\n Arrays.sort(nums);\n\n long ans = 0;\n long p = 1;\n for(int i = 0; i < nums.length; i++){\n ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD;\n p = (p * 2) % MOD;\n }\n return (int)ans;\n }\n}", + "title": "891. Sum of Subsequence Widths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums , return the sum of the widths of all the non-empty subsequences of nums . Since the answer may be very large, return it modulo 10^9 + 7 . A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n M = 10**9+7\n res = 0\n le = 1\n re = pow(2, n-1, M)\n #by Fermat's Little Thm\n #inverse of 2 modulo M\n inv = pow(2, M-2, M)\n for num in nums:\n res = (res + num * (le - re))%M\n le = (le * 2) % M\n re = (re * inv) % M\n return res", + "title": "891. Sum of Subsequence Widths", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength , where strength[i] denotes the strength of the i th wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength ), the total strength is defined as the product of the following two values: Return the sum of the total strengths of all contiguous groups of wizards . Since the answer may be very large, return it modulo 10^9 + 7 . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The strength of the weakest wizard in the group.", + "The total of all the individual strengths of the wizards in the group." + ], + "examples": [ + { + "text": "Example 1: Input:strength = [1,3,1,2]Output:44Explanation:The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.", + "image": null + }, + { + "text": "Example 2: Input:strength = [5,4,6]Output:213Explanation:The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 178 ms (Top 61.28%) | Memory: 109.5 MB (Top 34.27%)\nclass Solution {\n public int totalStrength(int[] strength) {\n int mod = 1000000007;\n\n int len = strength.length;\n\n long[] prefix = prefixSum(strength, len, mod);\n\n Deque stack = new ArrayDeque<>();\n stack.push(-1);\n\n long ans = 0;\n for(int i = 0; i < len; i++) {\n while(stack.peek() != -1 && strength[i] <= strength[stack.peek()]) {\n int mid = stack.pop();\n int left = stack.peek() + 1;\n int right = i - 1;\n\n int n = (mid - left);\n int t = (right - mid);\n\n long val = (1l * (1 + n) * (prefix[right + 2] - prefix[mid + 1]) + mod) % mod;\n val -= (1l * (1 + t) * (prefix[mid + 1] - prefix[left]) + mod) % mod;\n val *= strength[mid];\n\n ans += val;\n ans %= mod;\n }\n\n stack.push(i);\n }\n\n int right = len - 1;\n while(stack.peek() != -1) {\n int mid = stack.pop();\n int left = stack.peek() + 1;\n\n int n = (mid - left);\n int t = (right - mid);\n\n long val = (1l * (1 + n) * (prefix[right + 2] - prefix[mid + 1]) + mod) % mod;\n val -= (1l * (1 + t) * (prefix[mid + 1] - prefix[left]) + mod) % mod;\n val *= strength[mid];\n\n ans += val;\n ans %= mod;\n }\n\n return (int)((ans + mod) % mod);\n }\n\n private long[] prefixSum(int[] strength, int len, int mod) {\n long[] prefix = new long[len + 1];\n\n for(int i = 0; i < len; i++) {\n prefix[i + 1] = prefix[i] + strength[i];\n }\n\n long[] doublePrefix = new long[len + 2];\n for(int i = 0; i <= len; i++) {\n doublePrefix[i + 1] = (doublePrefix[i] + prefix[i]) % mod;\n }\n\n return doublePrefix;\n }\n}", + "title": "2281. Sum of Total Strength of Wizards", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "As the ruler of a kingdom, you have an army of wizards at your command. You are given a 0-indexed integer array strength , where strength[i] denotes the strength of the i th wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength ), the total strength is defined as the product of the following two values: Return the sum of the total strengths of all contiguous groups of wizards . Since the answer may be very large, return it modulo 10^9 + 7 . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The strength of the weakest wizard in the group.", + "The total of all the individual strengths of the wizards in the group." + ], + "examples": [ + { + "text": "Example 1: Input:strength = [1,3,1,2]Output:44Explanation:The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.", + "image": null + }, + { + "text": "Example 2: Input:strength = [5,4,6]Output:213Explanation:The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def totalStrength(self, stp: List[int]) -> int:\n st = []\n n = len(stp)\n m1 = defaultdict(lambda:-1)\n ps = [0]\n for i in range(n):\n while st and stp[st[-1]] >= stp[i]:\n st.pop()\n if st: m1[i] = st[-1]\n st.append(i)\n ps.append(ps[-1] + stp[i])\n pss = [0]\n for i in ps:\n pss.append(pss[-1] + i)\n st = []\n m2 = defaultdict(lambda:n)\n for i in range(n-1,-1,-1):\n while st and stp[st[-1]] > stp[i]:\n st.pop()\n if st: m2[i] = st[-1]\n st.append(i)\n\n ans = 0\n mod = 10**9 + 7\n for i in range(n):\n left = m1[i] + 1\n right = m2[i]\n p1 = (i+1-left)*(pss[right+1]-pss[i+1])\n p2 = (right-i)*(pss[i+1]- pss[left])\n ans = (ans + stp[i]*(p1 - p2)) % mod\n return ans\n", + "title": "2281. Sum of Total Strength of Wizards", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two integers a and b , return the sum of the two integers without using the operators + and - . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-1000 <= a, b <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2Output:3", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n \n public int getSum(int a, int b) {\n return Integer.sum(a, b);\n }\n}\n", + "title": "371. Sum of Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given two integers a and b , return the sum of the two integers without using the operators + and - . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-1000 <= a, b <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:a = 1, b = 2Output:3", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = 3Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n sol=(a,b)\n return sum(sol)\n\t```", + "title": "371. Sum of Two Integers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,2]Output:4Explanation:The unique elements are [1,3], and the sum is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1,1,1]Output:0Explanation:There are no unique elements, and the sum is 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5]Output:15Explanation:The unique elements are [1,2,3,4,5], and the sum is 15.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 86.10%) | Memory: 40.1 MB (Top 92.63%)\nclass Solution {\n public int sumOfUnique(int[] nums) {\n int res = 0;\n Map map = new HashMap<>();\n for(int i = 0;i int:\n hashmap = {}\n for i in nums:\n if i in hashmap.keys():\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n sum = 0\n for k, v in hashmap.items():\n if v == 1: sum += k\n return sum\n", + "title": "1748. Sum of Unique Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:25Explanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]Output:1026Explanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n int res;\n public int sumNumbers(TreeNode root) {\n res = 0;\n getSum(root, 0);\n \n return res;\n }\n \n public void getSum(TreeNode root, int sum){\n \n if(root.left == null && root.right == null) {\n res += (sum*10+root.val);\n }\n \n if(root.left != null)\n getSum(root.left, sum*10+root.val);\n \n \n if(root.right != null)\n getSum(root.right, sum*10+root.val);\n }\n}\n", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:25Explanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]Output:1026Explanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def sumNumbers(self, root: Optional[TreeNode]) -> int:\n \n int_list = []\n \n def traverse(node, input_string):\n \n nonlocal int_list\n \n if not node:\n return int_list\n \n input_string = input_string + str(node.val)\n\n if not (node.left or node.right):\n int_list.append(int(input_string))\n \n traverse(node.left, input_string)\n traverse(node.right, input_string)\n \n traverse(root, \"\")\n return sum(int_list)\n \n", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a sorted unique integer array nums . A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly . That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums . Each range [a,b] in the list should be output as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "\"a->b\" if a != b", + "\"a\" if a == b" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,4,5,7]Output:[\"0->2\",\"4->5\",\"7\"]Explanation:The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,2,3,4,6,8,9]Output:[\"0\",\"2->4\",\"6\",\"8->9\"]Explanation:The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 38 ms (Top 76.97%) | Memory: 13.8 MB (Top 98.42%)\n\nclass Solution(object):\n def summaryRanges(self, nums):\n\n if len(nums) == 0:\n return []\n\n l, r = 0, 0\n res = []\n\n while l<=r and r <= len(nums):\n\n if r == 0:\n r+=1\n\n while r < len(nums) and r>0 and nums[r-1] == nums[r]-1:\n r+=1\n\n if r-1 == l:\n res.append(str(nums[r-1]))\n else:\n res.append(str(nums[l]) + '->' + str(nums[r-1]))\n\n l=r\n r+=1\n\n return res", + "title": "228. Summary Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1, n = 2Output:2Explanation:Drop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, n = 6Output:3", + "image": null + }, + { + "text": "Example 3: Input:k = 3, n = 14Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 72 ms (Top 33.33%) | Memory: 54.3 MB (Top 43.02%)\nclass Solution {\n\n int [][]dp;\n public int superEggDrop(int k, int n) {\n dp=new int[k+1][n+1];\n\n for(int i=0;i<=k;i++){\n Arrays.fill(dp[i],-1);\n }\n\n return solve(k,n);\n\n }\n\n public int solve(int e, int f){\n if(f==0 || f==1){\n return f;\n }\n\n if(e==1){\n return f;\n }\n\n if(dp[e][f]!=-1){\n return dp[e][f];\n }\n\n int high=f;\n int low=1;\n int min=Integer.MAX_VALUE;\n\n while(low<=high){\n int k=low+(high-low)/2;\n\n int l=0;\n int r=0;\n\n if(dp[e-1][k-1]!=-1){\n l=dp[e-1][k-1];\n }else{\n l=solve(e-1,k-1);\n }\n\n if(dp[e][f-k]!=-1){\n r=dp[e][f-k];\n }else{\n r=solve(e,f-k);\n }\n\n if(l>r){\n high=k-1;\n }else{\n low=k+1;\n }\n\n int temp=Math.max(l,r)+1;\n min=Math.min(min,temp);\n }\n\n return dp[e][f]=min;\n }\n}\n\n//-------------------------TLE--------------------------\n\n// class Solution {\n// public int superEggDrop(int k, int n) {\n// int [][]dp=new int[k+1][n+1];\n\n// for(int i=1;i<=k;i++){\n// for(int j=1;j<=n;j++){\n// if(i==1){\n// dp[i][j]=j;\n// }else if(j==1){\n// dp[i][j]=1;\n// }else{\n// int min=Integer.MAX_VALUE;\n\n// for(int m=j-1,p=0;m>=0;m--,p++){\n// int max=Math.max(dp[i][m],dp[i-1][p]);\n\n// min=Math.min(min,max);\n// }\n\n// dp[i][j]=min+1;\n// }\n// }\n// }\n\n// return dp[k][n];\n// }\n// }", + "title": "887. Super Egg Drop", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n . You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break , and any egg dropped at or below floor f will not break . Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n ). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:k = 1, n = 2Output:2Explanation:Drop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, n = 6Output:3", + "image": null + }, + { + "text": "Example 3: Input:k = 3, n = 14Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def superEggDrop(self, e: int, f: int) -> int:\n dp = [[-1 for _ in range(e+1)] for _ in range(f+1)]\n \n def solve(floors,eggs):\n \n if eggs==1:\n dp[floors][eggs] = floors\n return floors\n\n if floors==0:\n dp[floors][eggs] = 0\n return 0\n \n if dp[floors][eggs]==-1:\n \n ans = math.inf\n low = 1\n high = floors\n # Binary Search for the floor where to drop the egg\n while low<=high:\n mid = (low+high)//2\n left = solve(mid-1,eggs-1)\n right = solve(floors-mid,eggs)\n tmp = 1 + max(left,right)\n if left < right:\n low = mid+1\n else:\n high = mid-1\n ans = min(ans,tmp)\n \n dp[floors][eggs] = ans\n \n return dp[floors][eggs]\n \n return solve(f,e)\n\n", + "title": "887. Super Egg Drop", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= left.length, right.length <= 18", + "left and right consist of only digits.", + "left and right cannot have leading zeros.", + "left and right represent integers in the range [1, 10^18 - 1] .", + "left is less than or equal to right ." + ], + "examples": [ + { + "text": "Example 1: Input:left = \"4\", right = \"1000\"Output:4Explanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:left = \"1\", right = \"2\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 92.59%) | Memory: 42.2 MB (Top 79.63%)\nclass Solution {\n public int superpalindromesInRange(String left, String right) {\n int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n\n for (int dig = 1; dig < 10; dig++) {\n boolean isOdd = dig % 2 > 0 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n char[] pal = new char[dig];\n Arrays.fill(pal, '0');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) {\n innerLim = 1;\n midLim = Math.min(midLim, 2);\n }\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n String innerStr = Integer.toString(inner, 2);\n while (innerStr.length() < innerLen)\n innerStr = \"0\" + innerStr;\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr.charAt(i);\n pal[dig-2-i] = innerStr.charAt(i);\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n String palin = new String(pal);\n long square = Long.parseLong(palin) * Long.parseLong(palin);\n if (square > Long.parseLong(right)) return ans;\n if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n\n private boolean isPal(String str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str.charAt(i) != str.charAt(j)) return false;\n return true;\n }\n}", + "title": "906. Super Palindromes", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= left.length, right.length <= 18", + "left and right consist of only digits.", + "left and right cannot have leading zeros.", + "left and right represent integers in the range [1, 10^18 - 1] .", + "left is less than or equal to right ." + ], + "examples": [ + { + "text": "Example 1: Input:left = \"4\", right = \"1000\"Output:4Explanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:left = \"1\", right = \"2\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n min_num, max_num = int(left), int(right)\n count, limit = 0, 20001\n \n # odd pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[:-1][::-1]\n num_sqr = int(pal) ** 2\n\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n # even pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[::-1]\n num_sqr = int(pal) ** 2\n\n if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n return count ", + "title": "906. Super Palindromes", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Your task is to calculate a b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a <= 2 31 - 1", + "1 <= b.length <= 2000", + "0 <= b[i] <= 9", + "b does not contain leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = [3]Output:8", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = [1,0]Output:1024", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = [4,3,3,8,5,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "import java.math.BigInteger;\nclass Solution {\n public int superPow(int a, int[] b) {\n StringBuilder bigNum = new StringBuilder();\n Arrays.stream(b).forEach(i -> bigNum.append(i));\n \n return \n BigInteger.valueOf(a)\n .modPow(new BigInteger(bigNum.toString()), BigInteger.valueOf(1337))\n .intValue();\n }\n}\n", + "title": "372. Super Pow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Your task is to calculate a b mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= a <= 2 31 - 1", + "1 <= b.length <= 2000", + "0 <= b[i] <= 9", + "b does not contain leading zeros." + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = [3]Output:8", + "image": null + }, + { + "text": "Example 2: Input:a = 2, b = [1,0]Output:1024", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = [4,3,3,8,5,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 260 ms (Top 32.64%) | Memory: 13.9 MB (Top 58.72%)\nclass Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n mod = 1337\n ans = 1\n\n for power in b:\n ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod\n\n return ans", + "title": "372. Super Pow", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes . Given an integer n and an array of integers primes , return the n th super ugly number . The n th super ugly number is guaranteed to fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= primes.length <= 100", + "2 <= primes[i] <= 1000", + "primes[i] is guaranteed to be a prime number.", + "All the values of primes are unique and sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, primes = [2,7,13,19]Output:32Explanation:[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].", + "image": null + }, + { + "text": "Example 2: Input:n = 1, primes = [2,3,5]Output:1Explanation:1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].", + "image": null + } + ], + "follow_up": null, + "solution": "//---------------------O(nlogk)-------------------------\n\nclass Solution {\n public int nthSuperUglyNumber(int n, int[] primes) {\n int []dp=new int[n+1];\n dp[1]=1;\n \n PriorityQueue pq=new PriorityQueue<>();\n \n for(int i=0;i0){\n pq.add(new Pair(curr.prime, curr.ptr+1,newval));\n }\n }\n \n return dp[n];\n }\n}\n\nclass Pair implements Comparable{\n int prime;\n int ptr;\n int val;\n \n public Pair(int prime, int ptr, int val){\n this.prime=prime;\n this.ptr=ptr;\n this.val=val;\n }\n \n public int compareTo(Pair o){\n return this.val-o.val;\n }\n}\n\n//-----------------------O(nk)---------------------------\n\n// class Solution {\n// public int nthSuperUglyNumber(int n, int[] primes) {\n// int []dp=new int[n+1];\n// dp[1]=1;\n \n// int []ptr=new int[primes.length];\n \n// Arrays.fill(ptr,1);\n \n// for(int i=2;i<=n;i++){\n \n// int min=Integer.MAX_VALUE;\n \n// for(int j=0;j0){\n// min=Math.min(min,val);\n// }\n \n// }\n \n// dp[i]=min;\n \n// for(int j=0;j0 && min==val){\n// ptr[j]++;\n// }\n// }\n// }\n \n// return dp[n];\n// }\n// }\n", + "title": "313. Super Ugly Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A super ugly number is a positive integer whose prime factors are in the array primes . Given an integer n and an array of integers primes , return the n th super ugly number . The n th super ugly number is guaranteed to fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^5", + "1 <= primes.length <= 100", + "2 <= primes[i] <= 1000", + "primes[i] is guaranteed to be a prime number.", + "All the values of primes are unique and sorted in ascending order ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, primes = [2,7,13,19]Output:32Explanation:[1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].", + "image": null + }, + { + "text": "Example 2: Input:n = 1, primes = [2,3,5]Output:1Explanation:1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\ndef nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n prime_nums = len(primes)\n index = [1]*prime_nums\n ret = [1]*(n+1)\n for i in range(2,n+1):\n ret[i] = min(primes[j]*ret[index[j]] for j in range(prime_nums))\n for k in range(prime_nums):\n if ret[i] == primes[k]*ret[index[k]]:\n index[k]+= 1\n \n return ret[-1]\n", + "title": "313. Super Ugly Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m ( 1 <= m <= n ) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses . If it is not possible to do it, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == machines.length", + "1 <= n <= 10^4", + "0 <= machines[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:machines = [1,0,5]Output:3Explanation:1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2", + "image": null + }, + { + "text": "Example 2: Input:machines = [0,3,0]Output:2Explanation:1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1", + "image": null + }, + { + "text": "Example 3: Input:machines = [0,2,0]Output:-1Explanation:It's impossible to make all three washing machines have the same number of dresses.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 44.60 MB (Top 13.21%)\n\nclass Solution {\n public int findMinMoves(int[] machines) {\n int avg = 0;\n\n for(int i = 0; i < machines.length; i++){\n avg += machines[i];\n \n }\n\n if(avg % machines.length != 0){\n return -1;\n }\n\n int res = 0, cnt = 0;\n avg = avg / machines.length;\n for (int m : machines) {\n cnt += m - avg;\n res = Math.max(res, Math.max(Math.abs(cnt), m - avg));\n }\n return res;\n }\n}\n", + "title": "517. Super Washing Machines", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. For each move, you could choose any m ( 1 <= m <= n ) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time. Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses . If it is not possible to do it, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == machines.length", + "1 <= n <= 10^4", + "0 <= machines[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:machines = [1,0,5]Output:3Explanation:1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2", + "image": null + }, + { + "text": "Example 2: Input:machines = [0,3,0]Output:2Explanation:1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1", + "image": null + }, + { + "text": "Example 3: Input:machines = [0,2,0]Output:-1Explanation:It's impossible to make all three washing machines have the same number of dresses.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 170 ms (Top 20.15%) | Memory: 15 MB (Top 44.78%)\nfrom itertools import accumulate\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n n = len(machines)\n summation = sum(machines)\n if summation%n:\n return -1\n avg = summation//n\n left = list(accumulate(machines))\n result = 0\n for i in range(n):\n move_to_right = max(left[i] - (i+1)*avg, 0)\n move_to_left = max(left[-1]-(left[i-1] if i!=0 else 0) - (n-i)*avg, 0)\n result = max(result, move_to_right + move_to_left)\n return result\n", + "title": "517. Super Washing Machines", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j) . After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return the total surface area of the resulting shapes . Note: The bottom face of each shape counts toward its surface area. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,2],[3,4]]Output:34", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid2.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,1,1],[1,0,1],[1,1,1]]Output:32", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid4.jpg" + }, + { + "text": "Example 3: Input:grid = [[2,2,2],[2,1,2],[2,2,2]]Output:46", + "image": "https://assets.leetcode.com/uploads/2021/01/08/tmp-grid5.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 63.77%) | Memory: 44.7 MB (Top 34.78%)\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n int n = grid.length;\n for(int i=0; i int: \n m, n = len(grid), len(grid[0])\n \n area = 0\n for r in range(m): \n for c in range(n):\n if grid[r][c] != 0:\n area += 2\n \n if r == 0 or r == m - 1:\n area += grid[r][c] if m != 1 else 2*grid[r][c]\n if r != m - 1: \n area += abs(grid[r][c] - grid[r+1][c])\n \n if c == 0 or c == n - 1:\n area += grid[r][c] if n != 1 else 2*grid[r][c]\n if c != n - 1: \n area += abs(grid[r][c] - grid[r][c+1]) \n \n return area", + "title": "892. Surface Area of 3D Shapes", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix board containing 'X' and 'O' , capture all regions that are 4-directionally surrounded by 'X' . A region is captured by flipping all 'O' s into 'X' s in that surrounded region. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is 'X' or 'O' ." + ], + "examples": [ + { + "text": "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:Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" + }, + { + "text": "Example 2: Input:board = [[\"X\"]]Output:[[\"X\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 54.99%) | Memory: 51.8 MB (Top 39.25%)\nclass Solution {\n boolean isClosed = true;\n\n public void solve(char[][] board) {\n int m = board.length;\n int n = board[0].length;\n\n // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value\n for(int i=0; i= board.length || j>=board[0].length || board[i][j] != 'O') return;\n\n board[i][j] = 'T'; // to put a temperory mark/ to mark as visited\n\n dfs(board, i, j+1); // Top\n dfs(board, i, j-1); // Bottom\n dfs(board, i+1, j); // Right\n dfs(board, i-1, j); // Left\n }\n}", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n matrix board containing 'X' and 'O' , capture all regions that are 4-directionally surrounded by 'X' . A region is captured by flipping all 'O' s into 'X' s in that surrounded region. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 200", + "board[i][j] is 'X' or 'O' ." + ], + "examples": [ + { + "text": "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:Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" + }, + { + "text": "Example 2: Input:board = [[\"X\"]]Output:[[\"X\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "# The question is an awesome example of multi-source bfs.\n# The intuition is to add the boundary to a heap if it is 'O'.\n# Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start\n# convertin all these 'O's to 'E's. \n# The last step is to traverse the matrix and if the element is still 'O' turn it to 'X' if it is 'E' turn it to 'O' and we get our answer.\n# Pro-Tip -> Try to reduce the number of append operations in python. The lesser the append operations the better is the runtime!\nfrom collections import deque\nclass Solution:\n def solve(self, bb: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n heap = deque()\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n r, c = len(bb), len(bb[0])\n for i in range(r):\n if bb[i][0] == 'O': heap.append((i, 0))\n if bb[i][c - 1] == 'O': heap.append((i, c - 1))\n for i in range(1, c - 1):\n if bb[0][i] == 'O': heap.append((0, i))\n if bb[r - 1][i] == 'O': heap.append((r - 1, i))\n visited = set()\n def isValid(nr, nc):\n if 0 <= nr < r and 0 <= nc < c: return True\n else: return False\n while heap:\n ri, ci = heap.popleft()\n bb[ri][ci] = 'E'\n for i, j in directions:\n nr, nc = ri + i, ci + j\n if isValid(nr, nc) and (nr, nc) not in visited and bb[nr][nc] == 'O':\n heap.append((nr, nc))\n visited.add((nr, nc))\n for i in range(r):\n for j in range(c):\n if bb[i][j] == 'O':\n bb[i][j] = 'X'\n if bb[i][j] == 'E':\n bb[i][j] = 'O'\n \n", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "In a string composed of 'L' , 'R' , and 'X' characters, like \"RXXLRXRXL\" , a move consists of either replacing one occurrence of \"XL\" with \"LX\" , or replacing one occurrence of \"RX\" with \"XR\" . Given the starting string start and the ending string end , return True if and only if there exists a sequence of moves to transform one string to the other. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= start.length <= 10^4", + "start.length == end.length", + "Both start and end will only consist of characters in 'L' , 'R' , and 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"Output:trueExplanation:We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX", + "image": null + }, + { + "text": "Example 2: Input:start = \"X\", end = \"L\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 74 ms (Top 5.17%) | Memory: 82 MB (Top 5.24%)\nclass Solution {\n public boolean canTransform(String start, String end) {\n int startL = 0, startR = 0;\n int endL = 0, endR = 0;\n String stLR = \"\", edLR = \"\";\n for(int i = 0; i < start.length(); i++) {\n if(start.charAt(i) != 'X') {\n if(start.charAt(i) == 'L') {\n startL++;\n } else{\n startR++;\n }\n stLR+= start.charAt(i);\n }\n if(end.charAt(i) != 'X') {\n if(end.charAt(i) == 'L') {\n endL++;\n } else{\n endR++;\n }\n edLR += end.charAt(i);\n }\n\n if(startL > endL || startR < endR) //Check conditions at each instant\n return false;\n }\n\n if(startL != endL || startR != endR || !stLR.equals(edLR)) //check their final count and positions\n return false;\n\n return true;\n }\n\n}", + "title": "777. Swap Adjacent in LR String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In a string composed of 'L' , 'R' , and 'X' characters, like \"RXXLRXRXL\" , a move consists of either replacing one occurrence of \"XL\" with \"LX\" , or replacing one occurrence of \"RX\" with \"XR\" . Given the starting string start and the ending string end , return True if and only if there exists a sequence of moves to transform one string to the other. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= start.length <= 10^4", + "start.length == end.length", + "Both start and end will only consist of characters in 'L' , 'R' , and 'X' ." + ], + "examples": [ + { + "text": "Example 1: Input:start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"Output:trueExplanation:We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX", + "image": null + }, + { + "text": "Example 2: Input:start = \"X\", end = \"L\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canTransform(self, start: str, end: str) -> bool:\n def chars(s):\n for i, c in enumerate(s):\n if c != 'X':\n yield i, c\n \n yield -1, ' '\n \n for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):\n if (startC != endC or\n (startC == 'L' and startI < endI) or\n (startC == 'R' and startI > endI)):\n return False\n \n return True", + "title": "777. Swap Adjacent in LR String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string text . You can swap two of the characters in the text . Return the length of the longest substring with repeated characters . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= text.length <= 2 * 10^4", + "text consist of lowercase English characters only." + ], + "examples": [ + { + "text": "Example 1: Input:text = \"ababa\"Output:3Explanation:We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.", + "image": null + }, + { + "text": "Example 2: Input:text = \"aaabaaa\"Output:6Explanation:Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.", + "image": null + }, + { + "text": "Example 3: Input:text = \"aaaaa\"Output:5Explanation:No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 14 ms (Top 27.8%) | Memory: 41.85 MB (Top 50.9%)\n\nclass Solution {\n\t\tpublic int maxRepOpt1(String s) {\n\t\t int[] count = new int[26];\n\t\t int[] left = new int[s.length()];\n\t\t int[] right = new int[s.length()];\n\t\t\tint max =0;\n\t\t\t// Left Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=0;i 0){\n\t\t\t\t\tif(s.charAt(i) == s.charAt(i-1)){\n\t\t\t\t\t\tleft[i] = left[i-1]+1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleft[i] = 1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tleft[i] =1;\n\t\t\t\t}\n\t\t\t\tmax = Math.max(max,left[i]);\n\t\t\t}\n\t\t\t// Right Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=s.length()-1;i>=0;i--){\n\t\t\t\tif(i < s.length()-1){\n\t\t\t\t\tif(s.charAt(i+1) == s.charAt(i)){\n\t\t\t\t\t\tright[i] = right[i+1] +1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tright[i] =1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tright[i] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Count The Length Of SubString Having Maximum Length When A Character Is Swapped\n\t\t\tfor(int i=1 ; i int:\n char_groups = []\n \n for char, group in groupby(text):\n group_len = len(list(group))\n char_groups.append((char, group_len))\n \n char_count = Counter(text)\n \n longest_substr_len = 1 # Each char itself is substring of len 1\n \n # Scenario-1: Get the longest substr length by just adding one more char to each group\n for char, group_len in char_groups:\n # NOTE: If the total count of the char across full string is < group_len+1,\n # make sure to take the total count only\n #\n # It means we don't have any extra char occurrence which we can add to the current group\n \n group_len_w_one_addition = min(group_len+1, char_count[char])\n longest_substr_len = max(longest_substr_len, group_len_w_one_addition)\n \n \n # Scenario-2: \n # If there are two groups of same char, separated by a group of different char with length=1:\n # 1) We can either swap that one char in the middle with the same char as those two groups \n # Ex: 'aaa b aaa c a'\n # - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index\n # - So after swapping, it will become 'aaa a aaa c b' \n # - hence longest substr len of same char 'a' = 7\n #\n # 2) We can merge the two groups\n # Ex: 'aaa b aaa' \n # -> here there are two groups of char 'a' with len = 3 each.\n # -> they are separated by a group of char 'b' with len = 1\n # -> hence, we can merge both groups of char 'a' - so that longest substr len = 6\n # -> basically, swap the 'b' with 'a' at very last index\n # -> the final string will look like 'aaaaaa b'\n #\n # We will take max length we can get from above two options.\n #\n # Since we need to check the group prior to curr_idx \"i\" and also next to curr_idx \"i\";\n # we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive\n \n for i in range(1, len(char_groups)-1):\n prev_group_char, prev_group_len = char_groups[i-1]\n curr_group_char, curr_group_len = char_groups[i]\n next_group_char, next_group_len = char_groups[i+1]\n \n if curr_group_len != 1 or prev_group_char != next_group_char:\n continue\n \n len_after_swapping = min(prev_group_len + next_group_len + 1, char_count[next_group_char])\n longest_substr_len = max(longest_substr_len, len_after_swapping)\n \n return longest_substr_len\n", + "title": "1156. Swap For Longest Repeated Character Substring", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]Output:[2,1,4,3]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + }, + { + "text": "Example 2: Input:head = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.8 MB (Top 55.04%)\n\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0) , prev = dummy , curr = head;\n dummy.next = head;\n while(curr != null && curr.next != null){\n prev.next = curr.next;\n curr.next = curr.next.next ;\n prev.next.next = curr;\n curr = curr.next ;\n prev = prev.next.next;\n }\n return dummy.next;\n }\n}\n", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4]Output:[2,1,4,3]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + }, + { + "text": "Example 2: Input:head = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1]Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 41 ms (Top 43.62%) | Memory: 17.40 MB (Top 6.56%)\n\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\n if not head or not head.next: return head\n\n dummy = ListNode(0)\n dummy.next = head\n curr = dummy\n\n while curr.next and curr.next.next:\n first = curr.next\n second = curr.next.next\n curr.next = second\n first.next = second.next\n second.next = first\n curr = curr.next.next\n \n return dummy.next\n", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 10^5", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" + }, + { + "text": "Example 2: Input:head = [7,9,6,6,7,8,3,0,9,5], k = 5Output:[7,9,6,6,8,7,3,0,9,5]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 56.9 MB (Top 96.11%)\nclass Solution {\n public ListNode swapNodes(ListNode head, int k) {\n ListNode fast = head;\n ListNode slow = head;\n ListNode first = head, second = head;\n\n // Put fast (k-1) nodes after slow\n for(int i = 0; i < k - 1; ++i)\n fast = fast.next;\n\n // Save the node for swapping\n first = fast;\n\n // Move until the end of the list\n while(fast.next != null) {\n slow = slow.next;\n fast = fast.next;\n }\n\n // Save the second node for swapping\n // Note that the pointer second isn't necessary: we could use slow for swapping as well\n // However, having second improves readability\n second = slow;\n\n // Swap values\n int temp = first.val;\n first.val = second.val;\n second.val = temp;\n\n return head;\n }\n}", + "title": "1721. Swapping Nodes in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 10^5", + "0 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" + }, + { + "text": "Example 2: Input:head = [7,9,6,6,7,8,3,0,9,5], k = 5Output:[7,9,6,6,8,7,3,0,9,5]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 784 ms (Top 40.9%) | Memory: 50.79 MB (Top 42.2%)\n\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n tot = 0 # initialise total\n Head = head\n while Head: # count total nodes\n Head = Head.next # move forward\n tot += 1 # incerse count by one for each node\n one, two = None, None # two pointers of one and two\n count = 1 # we're initialising to one because we have one based index for swapping\n Head = head # regain original head to traverse\n while Head:\n if one and two: break # if we have both one and two then break loop to save time\n if count == k: # if from forward we reach at node k then it's our first node\n one = Head\n if count == (tot-k+1): # if from backward we reach to node k then save it\n two = Head\n Head = Head.next # move further\n count += 1 # increse count\n one.val, two.val = two.val, one.val # now swap values\n return head # return head", + "title": "1721. Swapping Nodes in a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j) . The rain starts to fall. At time t , the depth of the water everywhere is t . 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 least 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: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] < n 2", + "Each value grid[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2],[1,3]]Output:3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg" + }, + { + "text": "Example 2: 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:16Explanation:The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int swimInWater(int[][] grid) {\n int len = grid.length;\n Map reverseMap = new HashMap<>();\n for (int i = 0; i < len; i++) {\n for (int j = 0; j < len; j++) {\n reverseMap.put(grid[i][j], new int[] { i, j });\n }\n }\n \n int left = grid[0][0]; // answer cannot be less than value of starting position\n int right = len * len - 1;\n \n int ans = right;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (canSwim(grid, reverseMap, mid, len)) {\n ans = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n \n return ans;\n }\n \n boolean canSwim(int[][] grid, Map reverseIndex, int ans, int len) {\n int[] x_diff = { 1, -1, 0, 0 };\n int[] y_diff = { 0, 0, 1, -1 };\n \n // BFS\n Queue container = new LinkedList<>();\n container.add(new int[] { 0, 0 });\n \n boolean[][] visited = new boolean[grid.length][grid[0].length];\n visited[0][0] = true;\n \n while (!container.isEmpty()) {\n int[] curr = container.poll();\n int currVal = grid[curr[0]][curr[1]];\n for (int i = 0; i < 4; i++) {\n int newX = curr[0] + x_diff[i];\n int newY = curr[1] + y_diff[i];\n if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) {\n if (newX == grid.length-1 && newY == grid[0].length-1) {\n return true;\n }\n visited[newX][newY] = true;\n container.add(new int[] { newX, newY });\n }\n } \n }\n \n return false;\n }\n \n boolean isValidCell(int[][] grid, int x, int y, int ans) {\n\t // check boundary and if grid elevation is greater than evaluated answer\n return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans);\n }\n}\n", + "title": "778. Swim in Rising Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j) . The rain starts to fall. At time t , the depth of the water everywhere is t . 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 least 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: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length", + "n == grid[i].length", + "1 <= n <= 50", + "0 <= grid[i][j] < n 2", + "Each value grid[i][j] is unique ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,2],[1,3]]Output:3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim1-grid.jpg" + }, + { + "text": "Example 2: 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:16Explanation:The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/swim2-grid-1.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 94 ms (Top 84.44%) | Memory: 17.90 MB (Top 8.02%)\n\nclass DSU(object):\n def __init__(self, N):\n self.par = list(range(N))\n self.rnk = [0] * N\n\n def find(self, x):\n if self.par[x] != x:\n self.par[x] = self.find(self.par[x])\n return self.par[x]\n\n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n elif self.rnk[xr] < self.rnk[yr]:\n self.par[xr] = yr\n elif self.rnk[xr] > self.rnk[yr]:\n self.par[yr] = xr\n else:\n self.par[yr] = xr\n self.rnk[xr] += 1\n return True\n\nclass Solution:\n def swimInWater(self, grid):\n d, N = {}, len(grid)\n for i,j in product(range(N), range(N)):\n d[grid[i][j]] = (i, j)\n \n dsu = DSU(N*N)\n grid = [[0] * N for _ in range(N)] \n neib_list = [[0,1],[0,-1],[1,0],[-1,0]]\n \n for i in range(N*N):\n x, y = d[i]\n grid[x][y] = 1\n for dx, dy in neib_list:\n if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1:\n dsu.union((x+dx)*N + y + dy, x*N + y)\n \n if dsu.find(0) == dsu.find(N*N-1): return i\n", + "title": "778. Swim in Rising Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 64.02%) | Memory: 42.7 MB (Top 25.40%)\nclass Solution {\n public boolean isSymmetric(TreeNode root) {\n return isSymmetric(root.left,root.right);\n }\n\n public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) {\n if(rootLeft == null && rootRight == null) {return true;}\n if(rootLeft == null || rootRight == null) {return false;}\n if (rootLeft.val != rootRight.val) {return false;}\n else\n return isSymmetric(rootLeft.right, rootRight.left) && isSymmetric(rootLeft.left, rootRight.right);\n }\n}", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 50 ms (Top 60.40%) | Memory: 13.9 MB (Top 94.25%)\n\nclass Solution:\n def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n return root is None or self.findSymmetric(root.left, root.right)\n\n def findSymmetric(self, left, right):\n if (left is None or right is None):\n return left == right\n\n if (left.val != right.val):\n return False\n\n return self.findSymmetric(left.left, right.right) and self.findSymmetric(left.right, right.left)", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= code.length <= 500", + "code consists of English letters, digits, '<' , '>' , '/' , '!' , '[' , ']' , '.' , and ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:code = \"
This is the first line ]]>
\"Output:trueExplanation:The code is wrapped in a closed tag :
and
. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.", + "image": null + }, + { + "text": "Example 2: Input:code = \"
>> ![cdata[]] ]>]]>]]>>]
\"Output:trueExplanation:We first separate the code into : start_tag|tag_content|end_tag.\nstart_tag ->\"
\"end_tag ->\"
\"tag_content could also be separated into : text1|cdata|text2.\ntext1 ->\">> ![cdata[]] \"cdata ->\"]>]]>\", where the CDATA_CONTENT is\"
]>\"text2 ->\"]]>>]\"The reason why start_tag is NOT\"
>>\"is because of the rule 6.\nThe reason why cdata is NOT\"]>]]>]]>\"is because of the rule 7.", + "image": null + }, + { + "text": "Example 3: Input:code = \" \"Output:falseExplanation:Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 66.89%) | Memory: 41.9 MB (Top 78.38%)\nclass Solution {\n // for the ease to check CDATA starting tag\n private static final char[] CDATA_TAG = {'[','C','D','A','T','A','['};\n public boolean isValid(String code) {\n // make sure it is possible to have a start tag and an end tag\n if (!code.startsWith(\"<\") || !code.endsWith(\">\")) {\n return false;\n }\n Deque stack = new ArrayDeque<>();\n for (int i = 0; i < code.length(); ++i) {\n char ch = code.charAt(i);\n // if it is a special tag\n if (ch == '<') {\n if (i == code.length() - 1) {\n return false;\n }\n ch = code.charAt(++i);\n // is end tag\n if (ch == '/') {\n // we should have a start tag to match the end tag\n if (stack.isEmpty()) {\n return false;\n }\n // get the end tag\n StringBuilder sb = new StringBuilder();\n // build tag and move i to the > for the next round\n i = buildTag(code, i + 1, sb);\n // if tag is unmatch, return false\n if (!stack.pop().equals(sb.toString())) {\n return false;\n }\n // if no start tag left and we are not at the end. The rest content is not enclosed. -> false\n if (stack.isEmpty() && i < code.length() - 1) {\n return false;\n }\n } else if (ch == '!') { // is CDATA tag\n // check if CDATA is encoded in a tag\n if (stack.isEmpty()) {\n return false;\n }\n // check CDATA and move i to the end of ]]> for the next round\n i = validAndMoveCDATA(code, i + 1);\n // the above function return -1 if CDATA is not valid\n if (i < 0) {\n return false;\n }\n } else { // start tag\n // TAG_NAME should not empty\n if (ch == '>') {\n return false;\n }\n StringBuilder sb = new StringBuilder();\n i = buildTag(code, i , sb);\n // TAG_NAME should less than 9\n if (sb.isEmpty() || sb.length() > 9) {\n return false;\n }\n stack.push(sb.toString());\n }\n }\n }\n return stack.isEmpty();\n }\n\n private int buildTag(String code, int start, StringBuilder sb) {\n int i = start;\n // we only go to 10 because the max length is 9\n for (; i < start + 10 && i < code.length(); ++i) {\n char ch = code.charAt(i);\n // find the end;\n if (ch == '>') {\n break;\n }\n // TAG_NAME should be in uppercase only\n if (!Character.isUpperCase(ch)) {\n // clear the string builder for invalid TAG_NAME\n sb.setLength(0);\n break;\n }\n sb.append(ch);\n }\n return i;\n }\n\n private int validAndMoveCDATA(String code, int start) {\n // the length of [CDATA[]]> is 10 we need at least 10 characters left\n if (code.length() - start < 10) {\n return -1;\n }\n // check the start part\n int i = start;\n for (int j = 0; j < CDATA_TAG.length; ++j) {\n char ch = code.charAt(i++);\n if (ch != CDATA_TAG[j]) {\n return -1;\n }\n }\n // keep the last two characters for identifying the end\n char prev0 = '\\0';\n char prev1 = '\\0';\n\n for (; i < code.length(); ++i) {\n char ch = code.charAt(i);\n if (ch == '>' && prev1 == ']' && prev0 == ']') {\n return i;\n }\n prev0 = prev1;\n prev1 = ch;\n }\n // no end found\n return -1;\n }\n}", + "title": "591. Tag Validator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= code.length <= 500", + "code consists of English letters, digits, '<' , '>' , '/' , '!' , '[' , ']' , '.' , and ' ' ." + ], + "examples": [ + { + "text": "Example 1: Input:code = \"
This is the first line ]]>
\"Output:trueExplanation:The code is wrapped in a closed tag :
and
. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.", + "image": null + }, + { + "text": "Example 2: Input:code = \"
>> ![cdata[]] ]>]]>]]>>]
\"Output:trueExplanation:We first separate the code into : start_tag|tag_content|end_tag.\nstart_tag ->\"
\"end_tag ->\"
\"tag_content could also be separated into : text1|cdata|text2.\ntext1 ->\">> ![cdata[]] \"cdata ->\"]>]]>\", where the CDATA_CONTENT is\"
]>\"text2 ->\"]]>>]\"The reason why start_tag is NOT\"
>>\"is because of the rule 6.\nThe reason why cdata is NOT\"]>]]>]]>\"is because of the rule 7.", + "image": null + }, + { + "text": "Example 3: Input:code = \" \"Output:falseExplanation:Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != '<' or code[-1] != '>': return False\n i, n = 0, len(code)\n stk = []\n while i < n:\n if code[i] == '<':\n if i != 0 and code[i: i + 9] == '': j += 1\n if code[j: j + 3] == ']]>': i = j + 3\n else: return False\n else:\n start = i\n isend = False\n i += 1\n if i >= n: return False\n if code[i] == r'/':\n isend = True\n i += 1\n if i >= n: return False\n tag = ''\n while i < n and code[i] != '>':\n if not code[i].isupper(): return False\n tag += code[i]\n i += 1\n if i >= n or len(tag) == 0 or len(tag) > 9: return False\n if isend:\n if not stk or stk[-1] != tag: return False\n stk.pop(-1)\n else:\n if start != 0 and not stk: return False\n stk.append(tag)\n i += 1\n else:\n if not stk: return False\n while i < n and code[i] != '<': i += 1\n return not stk\n", + "title": "591. Tag Validator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1 , 2 , and 3 , you can weld them together to make a support of length 6 . Return the largest possible height of your billboard installation . If you cannot support the billboard, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rods.length <= 20", + "1 <= rods[i] <= 1000", + "sum(rods[i]) <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:rods = [1,2,3,6]Output:6Explanation:We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:rods = [1,2,3,4,5,6]Output:10Explanation:We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.", + "image": null + }, + { + "text": "Example 3: Input:rods = [1,2]Output:0Explanation:The billboard cannot be supported, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tallestBillboard(int[] rods) {\n int[] result = new int[1];\n dfs(rods, 0, 0, 0, rods.length, result);\n return result[0];\n }\n private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {\n if (level == n) {\n if (left == right) {\n result[0] = Math.max(left, result[0]);\n }\n return;\n }\n \n dfs(rods, left, right, level + 1, n, result);\n dfs(rods, left + rods[level], right, level + 1, n, result);\n dfs(rods, left, right + rods[level], level + 1, n, result);\n }\n}\n", + "title": "956. Tallest Billboard", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1 , 2 , and 3 , you can weld them together to make a support of length 6 . Return the largest possible height of your billboard installation . If you cannot support the billboard, return 0 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= rods.length <= 20", + "1 <= rods[i] <= 1000", + "sum(rods[i]) <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:rods = [1,2,3,6]Output:6Explanation:We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.", + "image": null + }, + { + "text": "Example 2: Input:rods = [1,2,3,4,5,6]Output:10Explanation:We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.", + "image": null + }, + { + "text": "Example 3: Input:rods = [1,2]Output:0Explanation:The billboard cannot be supported, so we return 0.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 760 ms (Top 68.15%) | Memory: 14.5 MB (Top 56.05%)\n\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n dp = collections.defaultdict(int)\n dp[0] = 0\n for x in rods:\n nxt = dp.copy()\n for d, y in dp.items():\n # init state\n # ------|----- d -----| # tall side\n # - y --| # low side\n\n # put x to tall side\n # ------|----- d -----|---- x --|\n # - y --|\n nxt[d + x] = max(nxt.get(x + d, 0), y)\n\n nxt[abs(d - x)] = max(nxt.get(abs(d - x), 0), y + min(d, x))\n dp = nxt\n return dp[0]", + "title": "956. Tallest Billboard", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Return the number of different expressions that you can build, which evaluates to target . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 3Output:5Explanation:There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 89.09%) | Memory: 42.70 MB (Top 55.56%)\n\nclass Solution {\n public int findTargetSumWays(int[] nums, int target) {\n //Solution 1\n int sum = 0;\n for(int x : nums)\n sum += x;\n if(((sum - target) % 2 == 1) || (target > sum))\n return 0;\n \n int n = nums.length;\n int s2 = (sum - target)/2;\n int[][] t = new int[n + 1][s2 + 1];\n t[0][0] = 1;\n \n for(int i = 1; i < n + 1; i++) {\n for(int j = 0; j < s2 + 1; j++) {\n if(nums[i - 1] <= j)\n t[i][j] = t[i-1][j] + t[i - 1][j - nums[i - 1]];\n else\n t[i][j] = t[i - 1][j];\n }\n }\n return t[n][s2];\n \n //Solution 2\n// int sum = 0;\n// for(int x : nums)\n// sum += x;\n// if(((sum - target) % 2 != 0) || (target > sum))\n// return 0;\n \n// int n = nums.length;\n// int s2 = (sum - target)/2;\n \n// int[][] t = new int[n + 1][s2 + 1];\n// for(int i = 0; i < n + 1; i++) {\n// for(int j = 0; j < s2 + 1; j++) {\n// if(i == 0)\n// t[i][j] = 0;\n// if(j == 0)\n// t[i][j] = 1;\n// }\n// }\n \n// for(int i = 1; i < n + 1; i++) {\n// for(int j = 1; j < s2 + 1; j++) {\n// if((nums[i - 1] > j) || (nums[i - 1] == 0))\n// t[i][j] = t[i - 1][j];\n// else\n// t[i][j] = t[i - 1][j] + t[i - 1][j - nums[i - 1]];\n// }\n// }\n \n// int count = 0;\n// for(int x : nums)\n// if(x == 0)\n// count++;\n \n// return (int)(Math.pow(2,count)) * t[n][s2];\n }\n}\n", + "title": "494. Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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. Return the number of different expressions that you can build, which evaluates to target . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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\" ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,1,1], target = 3Output:5Explanation:There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], target = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findTargetSumWays(self, nums: List[int], target: int) -> int:\n @cache\n def dfs(i, sum_):\n if i == len(nums):\n if sum_ == target: return 1\n else: return 0\n return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i])\n if abs(target) > sum(nums): return 0\n return dfs(0, 0)\n", + "title": "494. Target Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a characters array tasks , representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= task.length <= 10^4", + "tasks[i] is upper-case English letter.", + "The integer n is in the range [0, 100] ." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2Output:8Explanation:A -> B -> idle -> A -> B -> idle -> A -> B\nThere is at least 2 units of time between any two same tasks.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 0Output:6Explanation:On this case any permutation of size 6 would work since n = 0.\n[\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"]\n[\"A\",\"B\",\"A\",\"B\",\"A\",\"B\"]\n[\"B\",\"B\",\"B\",\"A\",\"A\",\"A\"]\n...\nAnd so on.", + "image": null + }, + { + "text": "Example 3: Input:tasks = [\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], n = 2Output:16Explanation:One possible solution is\nA -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1043 ms (Top 25.15%) | Memory: 14.3 MB (Top 64.15%)\n\nclass Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n max_heap = []\n queue = deque()\n word_count = defaultdict(int)\n timer = 0\n for i in range(len(tasks)):\n word_count[tasks[i]] += 1\n for _ , val in word_count.items():\n heappush(max_heap, -1*val)\n while max_heap or queue:\n timer += 1\n if max_heap:\n v = -1* heappop(max_heap)\n v -= 1\n if v:\n queue.append((v, timer+n))\n if queue and queue[0][1] == timer:\n heappush(max_heap, -1*queue.popleft()[0])\n return timer", + "title": "621. Task Scheduler", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a 0-indexed array of positive integers tasks , representing tasks that need to be completed in order , where tasks[i] represents the type of the i th task. You are also given a positive integer space , which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Return the minimum number of days needed to complete all tasks . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Complete the next task from tasks , or", + "Take a break." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,1,2,3,1], space = 3Output:9Explanation:One way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,8,8,5], space = 2Output:6Explanation:One way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long taskSchedulerII(int[] tasks, int space) {\n HashMap map = new HashMap<>();\n long day = 0;\n\n for (int item : tasks) {\n if (map.containsKey(item) && map.get(item) > day)\n day = map.get(item);\n\n day++;\n map.put(item, day + space);\n }\n\n return day;\n }\n}\n", + "title": "2365. Task Scheduler II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed array of positive integers tasks , representing tasks that need to be completed in order , where tasks[i] represents the type of the i th task. You are also given a positive integer space , which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Return the minimum number of days needed to complete all tasks . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Complete the next task from tasks , or", + "Take a break." + ], + "examples": [ + { + "text": "Example 1: Input:tasks = [1,2,1,2,3,1], space = 3Output:9Explanation:One way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.", + "image": null + }, + { + "text": "Example 2: Input:tasks = [5,8,8,5], space = 2Output:6Explanation:One way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 2321 ms (Top 5.03%) | Memory: 29.8 MB (Top 75.04%)\nimport math\nclass Solution:\n def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n count_dict = {}\n total_days = 0\n for task in tasks:\n if task not in count_dict:\n count_dict[task] = -math.inf\n total_days = max(total_days + 1, count_dict[task] + space + 1)\n count_dict[task] = total_days\n return total_days", + "title": "2365. Task Scheduler II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1] . If Teemo attacks again before the poison effect ends, the timer for it is reset , and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries , where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i] , and an integer duration . Return the total number of seconds that Ashe is poisoned . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= timeSeries.length <= 10^4", + "0 <= timeSeries[i], duration <= 10^7", + "timeSeries is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:timeSeries = [1,4], duration = 2Output:4Explanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.", + "image": null + }, + { + "text": "Example 2: Input:timeSeries = [1,2], duration = 2Output:3Explanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.", + "image": null + } + ], + "follow_up": null, + "solution": "// Teemo Attacking\n// https://leetcode.com/problems/teemo-attacking/\n\nclass Solution {\n public int findPoisonedDuration(int[] timeSeries, int duration) {\n int sum = 0;\n for (int i = 0; i < timeSeries.length; i++) {\n if (i == 0) {\n sum += duration;\n } else {\n sum += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);\n }\n }\n return sum; \n }\n}\n", + "title": "495. Teemo Attacking", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1] . If Teemo attacks again before the poison effect ends, the timer for it is reset , and the poison effect will end duration seconds after the new attack. You are given a non-decreasing integer array timeSeries , where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i] , and an integer duration . Return the total number of seconds that Ashe is poisoned . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= timeSeries.length <= 10^4", + "0 <= timeSeries[i], duration <= 10^7", + "timeSeries is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:timeSeries = [1,4], duration = 2Output:4Explanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.", + "image": null + }, + { + "text": "Example 2: Input:timeSeries = [1,2], duration = 2Output:3Explanation:Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n \n \"\"\"\n timeDur = (timeSeries[0], timeSeries[0] + duration - 1)\n i = 1\n total = 0\n while i < len(timeSeries):\n if timeSeries[i] > timeDur[1]:\n total += (timeDur[1] - timeDur[0] + 1)\n else:\n total += (timeSeries[i] - timeDur[0])\n timeDur = (timeSeries[i], timeSeries[i] + duration - 1)\n i += 1\n total += (timeDur[1] - timeDur[0] + 1)\n return total\n \n \"\"\"\n # Between two interval, Ashe can be poisoned only for max duration time,\n # if time differece is less than duranton, then we that value\n total = 0\n for i in range(len(timeSeries)-1):\n total += min(duration, timeSeries[i+1] - timeSeries[i])\n return total + duration\n \n", + "title": "495. Teemo Attacking", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16Output:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16Output:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]Explanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20Output:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 15.97%) | Memory: 42.1 MB (Top 76.75%)\nclass Solution {\n public List fullJustify(String[] words, int maxWidth) {\n List unBalanced = new ArrayList<>();\n List balanced = new ArrayList<>();\n int numSpaces = 0;\n\n StringBuffer sb = new StringBuffer();\n //Following code creates a list of unbalanced lines by appending words and 1 space between them\n for(String word : words){\n\n if(sb.length() == 0){\n sb.append(word);\n }else{\n if(sb.length() + 1 + word.length() <= maxWidth){\n sb.append(\" \"+word);\n }else{\n unBalanced.add(sb.toString());\n sb = new StringBuffer(word);\n }\n }\n\n }\n\n if(sb.length() >0){\n unBalanced.add(sb.toString());\n }\n\n for(int j = 0; j < unBalanced.size(); j++){\n String line = unBalanced.get(j);\n numSpaces = maxWidth - line.length();\n StringBuffer lineB = new StringBuffer(line);\n //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces\n if(j == unBalanced.size()-1 || !line.contains(\" \")){\n int tempSpaces = maxWidth - lineB.length();\n while(tempSpaces > 0){\n lineB.append(\" \");\n tempSpaces --;\n }\n balanced.add(lineB.toString());\n continue;\n };\n // The following block checks for each character and appends 1 space during each loop\n //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word\n while(numSpaces > 0){\n int i = 0;\n while(i < lineB.length() - 1){\n if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){\n lineB.insert(i+1, ' ');\n i++;\n numSpaces --;\n if(numSpaces == 0) break;\n }\n i++;\n }\n }\n balanced.add(lineB.toString());\n }\n\n return balanced;\n }\n}", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16Output:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16Output:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]Explanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20Output:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 59.19%) | Memory: 14 MB (Top 55.27%)\nclass Solution:\n def fullJustify(self, words: List[str], maxwidth: int) -> List[str]:\n curr = 0\n last = []\n res = []\n for i in words:\n if curr + len(i) + len(res) <= maxwidth:\n curr += len(i)\n res.append(i)\n else:\n last.append(res)\n curr = len(i)\n res = [i]\n last.append(res)\n ans = []\n for idx ,row in enumerate(last):\n x = maxwidth-len(\"\".join(row))\n t = len(row)-1\n if t == 0:\n ans.append(row[0] + \" \"*(x))\n elif idx != len(last)-1:\n spaces = x//t\n rem = x%t\n res = row[0]\n for i in row[1:]:\n temp = spaces\n if rem:\n temp += 1\n rem -= 1\n res = res + \" \"*temp + i\n # print(res, temp)\n ans.append(res)\n else:\n res = row[0]\n for i in row[1:]:\n res = res + ' '+i\n res = res + \" \"*(maxwidth-len(res))\n ans.append(res)\n\n return ans", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1 ). In each round, the i th player from the front of the row competes against the i th player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n , firstPlayer , and secondPlayer , return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7 . Player 2 competes against player 6 . Player 4 automatically advances to the next round.", + "Player 1 competes against player 7 .", + "Player 2 competes against player 6 .", + "Player 4 automatically advances to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 11, firstPlayer = 2, secondPlayer = 4Output:[3,4]Explanation:One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4", + "image": null + }, + { + "text": "Example 2: Input:n = 5, firstPlayer = 1, secondPlayer = 5Output:[1,1]Explanation:The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution \n{\n int firstPlayer,secondPlayer,n;\n boolean enumerate(ArrayList ret,int mask,int start,int end)\n {\n if(start>=end)\n {\n ret.add(mask);\n return false;\n }\n else\n {\n while((start=end)\n return enumerate(ret,mask,start+1,end-1);\n else if(start==firstPlayer&&end==secondPlayer)\n return true;\n else if(start==firstPlayer||start==secondPlayer)\n return enumerate(ret,mask|1< arr=new ArrayList();\n if(enumerate(arr,mask,start,end))\n return 1;\n else\n {\n int q=Integer.MAX_VALUE;\n for(int x:arr)\n q=Math.min(q,1+minDFS(x));\n return q;\n }\n } \n int maxDFS(int mask)\n {\n int start=0,end=n-1;\n ArrayList arr=new ArrayList();\n if(enumerate(arr,mask,start,end))\n return 1;\n else\n {\n int q=Integer.MIN_VALUE;\n for(int x:arr)\n q=Math.max(q,1+maxDFS(x));\n return q;\n }\n }\n\n public int[] earliestAndLatest(int n, int firstPlayer, int secondPlayer) \n {\n this.n=n;\n this.firstPlayer=firstPlayer-1;\n this.secondPlayer=secondPlayer-1;\n return new int[]{minDFS(0),maxDFS(0)}; \n }\n}\n", + "title": "1900. The Earliest and Latest Rounds Where Players Compete", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1 ). In each round, the i th player from the front of the row competes against the i th player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n , firstPlayer , and secondPlayer , return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if the row consists of players 1, 2, 4, 6, 7 Player 1 competes against player 7 . Player 2 competes against player 6 . Player 4 automatically advances to the next round.", + "Player 1 competes against player 7 .", + "Player 2 competes against player 6 .", + "Player 4 automatically advances to the next round." + ], + "examples": [ + { + "text": "Example 1: Input:n = 11, firstPlayer = 2, secondPlayer = 4Output:[3,4]Explanation:One possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4", + "image": null + }, + { + "text": "Example 2: Input:n = 5, firstPlayer = 1, secondPlayer = 5Output:[1,1]Explanation:The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef earliestAndLatest(self, n: int, first: int, second: int) -> List[int]:\n\t\tdef ceiling_of_log2(x: int) -> int:\n\t\t\t\"\"\" Return the ceiling of the integer log 2, i.e. index(MSB) - 1 + (1 if x not pow2) \"\"\"\n\t\t\tassert 0 < x < 0x100000000\n\t\t\t# Use power of 2 test. offset is 1 iff x is NOT a power of 2\n\t\t\toffset = 1 if (x & (x - 1)) != 0 else 0\n\t\t\tx |= (x >> 1)\n\t\t\tx |= (x >> 2)\n\t\t\tx |= (x >> 4)\n\t\t\tx |= (x >> 8)\n\t\t\tx |= (x >> 16)\n\t\t\t# Remove offset to get floor_of_log2. floor(log2(x)) + 1 == ceil(log2(x)) iff x not a power of 2.\n\t\t\treturn popcount(x) - 1 + offset\n\n\t\tdef popcount(x: int) -> int:\n\t\t\t\"\"\" Return the number of set bits in 32 bit unsigned x (Hamming weight) \"\"\"\n\t\t\tassert 0 <= x < 0x100000000\n\t\t\tx = x - ((x >> 1) & 0x55555555)\n\t\t\tx = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n\t\t\treturn (((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24\n\n\t\tdef count_trailing_zeroes(x: int) -> int:\n\t\t\t\"\"\" Return the number of trailing zeroes in 32 bit unsigned x > 0 (LSB + 1). This method is similar to\n\t\t\t\tbranchless binary search, but there are many other methods using the integer log2\"\"\"\n\t\t\tassert 0 < x < 0x100000000\n\t\t\tif x & 0x1: return 0 # odd x, quick break\n\t\t\tc = 1\n\t\t\tif (x & 0xffff) == 0:\n\t\t\t\tx >>= 16\n\t\t\t\tc += 16\n\t\t\tif (x & 0xff) == 0:\n\t\t\t\tx >>= 8\n\t\t\t\tc += 8\n\t\t\tif (x & 0xf) == 0:\n\t\t\t\tx >>= 4\n\t\t\t\tc += 4\n\t\t\tif (x & 0x3) == 0:\n\t\t\t\tx >>= 2\n\t\t\t\tc += 2\n\t\t\treturn c - (x & 0x1)\n\n\t\t# Base case, we can return instantly\n\t\tif first + second == n + 1: return [1, 1]\n\n\t\t# This ensures that 'first' is closer to the left than 'second' is to the right.\n\t\t# Also, crucially ensures that the sum of first and second is minimal among equivalent configs.\n\t\tif first + second >= n + 1: first, second = n + 1 - second, n + 1 - first\n\n\t\tfirst_plus_second = first + second\n\n\t\t# Special case if first + 1 == second, since we then need to find which round will have an even # of players\n\t\tif first + 1 != second and first_plus_second >= (n + 1) // 2 + 1:\n\t\t\tif first_plus_second == n:\n\t\t\t\t# If n is 4k + 2, first is 2k, and second is 2k+2, then parity of n also matters.\n\t\t\t\tif n % 4 == 2 and first + 2 == second:\n\t\t\t\t\t# Using n // 4 instead of n//4 + 1 because trailing_zeroes(x-1) = rounds until x is even\n\t\t\t\t\tans_earliest = 3 + count_trailing_zeroes(n // 4)\n\t\t\t\telse:\n\t\t\t\t\tans_earliest = 3 - (first % 2)\n\t\t\telse:\n\t\t\t\tans_earliest = 2\n\n\t\t# If we are in a special case: Players are too far left and close together to meet next round\n\t\telse:\n\t\t\tans_earliest = 1 + ceiling_of_log2((n + first_plus_second - 2) // (first_plus_second - 1))\n\t\t\tif first + 1 == second:\n\t\t\t\tans_earliest += count_trailing_zeroes(((n + (1 << (ans_earliest-1)) - 1) >> (ans_earliest-1)) - 1)\n\n\t\t# ceiling_of_log2 of n is the number of rounds left until there are exactly 2 players remaining, starting at n.\n\t\t# This implicitly assumes that optimal strategy for ans_latest is moving 'first' and 'second' to pos. 1 and 2\n\t\tans_latest = min(ceiling_of_log2(n), n + 1 - second)\n\n\t\treturn [ans_earliest, ans_latest]\n", + "title": "1900. The Earliest and Latest Rounds Where Players Compete", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of integers arr and an integer k . A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m| , then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j] . Return a list of the strongest k values in the array. return the answer in any arbitrary order . Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For arr = [6, -3, 7, 2, 11] , n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2 . The median is 6 .", + "For arr = [-7, 22, 17, 3] , n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1 . The median is 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 2Output:[5,1]Explanation:Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is alsoacceptedanswer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,3,5,5], k = 2Output:[5,5]Explanation:Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,7,11,7,6,8], k = 5Output:[11,8,6,6,7]Explanation:Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] isaccepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 55 ms (Top 48.30%) | Memory: 81.3 MB (Top 78.98%)\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] result = new int[k];\n int n = arr.length, left = 0, right = n - 1, idx = 0;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n while (left <= right) {\n int diff_l = Math.abs(arr[left] - median);\n int diff_r = Math.abs(arr[right] - median);\n\n if (diff_r > diff_l)\n result[idx++] = arr[right--];\n else if (diff_l > diff_r)\n result[idx++] = arr[left++];\n else if (arr[right] > arr[left])\n result[idx++] = arr[right--];\n else\n result[idx++] = arr[left++];\n if (idx == k)\n break;\n }\n return result;\n }\n}", + "title": "1471. The k Strongest Values in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr and an integer k . A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| == |arr[j] - m| , then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j] . Return a list of the strongest k values in the array. return the answer in any arbitrary order . Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed) . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For arr = [6, -3, 7, 2, 11] , n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2 . The median is 6 .", + "For arr = [-7, 22, 17, 3] , n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1 . The median is 3 ." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,3,4,5], k = 2Output:[5,1]Explanation:Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is alsoacceptedanswer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,3,5,5], k = 2Output:[5,5]Explanation:Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].", + "image": null + }, + { + "text": "Example 3: Input:arr = [6,7,11,7,6,8], k = 5Output:[11,8,6,6,7]Explanation:Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] isaccepted.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 708 ms (Top 81.36%) | Memory: 29.90 MB (Top 95.48%)\n\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n mid = arr[(len(arr)-1)//2]\n ans = []\n l ,r = 0, len(arr)-1\n while(l <= r):\n if abs(arr[l] - mid) > abs(arr[r]-mid) :\n ans.append(arr[l])\n l+=1\n else:\n ans.append(arr[r])\n r-=1\n return ans[:k]\n", + "title": "1471. The k Strongest Values in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n binary matrix mat of 1 's (representing soldiers) and 0 's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1 's will appear to the left of all the 0 's in each row. A row i is weaker than a row j if one of the following is true: Return the indices of the k weakest rows in the matrix ordered from weakest to strongest . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of soldiers in row i is less than the number of soldiers in row j .", + "Both rows have the same number of soldiers and i < j ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3Output:[2,0,3]Explanation:The number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2Output:[0,2]Explanation:The number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 17.72%) | Memory: 48.7 MB (Top 54.45%)\nclass Solution {\n public int[] kWeakestRows(int[][] mat, int k) {\n Map map = new HashMap<>();\n List list = new ArrayList<>();\n int[] arr = new int[k];\n for (int i = 0; i < mat.length; i++){\n int n = getBits(mat[i]);\n map.put(i, n);\n list.add(n);\n }\n Collections.sort(list);\n int z = 0;\n for (int i = 0; i < k; i++){\n for (Map.Entry m : map.entrySet()){\n if (list.get(i).equals(m.getValue())){\n arr[z++] = m.getKey();\n map.remove(m.getKey(), m.getValue());\n break;\n }\n }\n }\n\n return arr;\n }\n\n private static Integer getBits(int[] arr) {\n int count = 0;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == 1) count++;\n }\n\n return count;\n }\n}", + "title": "1337. The K Weakest Rows in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an m x n binary matrix mat of 1 's (representing soldiers) and 0 's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1 's will appear to the left of all the 0 's in each row. A row i is weaker than a row j if one of the following is true: Return the indices of the k weakest rows in the matrix ordered from weakest to strongest . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of soldiers in row i is less than the number of soldiers in row j .", + "Both rows have the same number of soldiers and i < j ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3Output:[2,0,3]Explanation:The number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].", + "image": null + }, + { + "text": "Example 2: Input:mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2Output:[0,2]Explanation:The number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n\n row = []\n for i in range(len(mat)):\n row.append((sum(mat[i]), i))\n\n row.sort()\n ans = [idx for (val, idx) in row[:k]]\n\n return ans\n", + "title": "1337. The K Weakest Rows in a Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A happy string is a string that: For example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings. Given two integers n and k , consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "consists only of letters of the set ['a', 'b', 'c'] .", + "s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 3Output:\"c\"Explanation:The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 4Output:\"\"Explanation:There are only 3 happy strings of length 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 9Output:\"cab\"Explanation:There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9thstring = \"cab\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 32 ms (Top 59.76%) | Memory: 51.4 MB (Top 55.86%)\n\nclass Solution {\n\n public String getHappyString(int n, int k) {\n List innerList = new ArrayList<>();\n getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList);\n if (innerList.size() < k)\n return \"\";\n return innerList.get(k - 1);\n }\n\n public void getHappyStringUtil(int n, int k, char[] letter, StringBuilder tempString, List innerList) {\n // Base case\n if (tempString.length() == n) {\n innerList.add(tempString.toString());\n return;\n }\n\n // Recursive call\n for (int i = 0; i < 3; i++) {\n if (tempString.length() > 0 && tempString.charAt(tempString.length() - 1) == letter[i])\n continue;\n tempString.append(letter[i]);\n getHappyStringUtil(n, k, letter, tempString, innerList);\n tempString.deleteCharAt(tempString.length() - 1);\n }\n\n }\n}", + "title": "1415. The k-th Lexicographical String of All Happy Strings of Length n", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A happy string is a string that: For example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings. Given two integers n and k , consider a list of all happy strings of length n sorted in lexicographical order. Return the kth string of this list or return an empty string if there are less than k happy strings of length n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "consists only of letters of the set ['a', 'b', 'c'] .", + "s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, k = 3Output:\"c\"Explanation:The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 4Output:\"\"Explanation:There are only 3 happy strings of length 1.", + "image": null + }, + { + "text": "Example 3: Input:n = 3, k = 9Output:\"cab\"Explanation:There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9thstring = \"cab\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getHappyString(self, n: int, k: int) -> str:\n ans = []\n letters = ['a','b','c']\n def happystr(n,prev,temp):\n if n==0:\n ans.append(\"\".join(temp))\n return \n for l in letters: \n if l!=prev: \n happystr(n-1,l,temp+[l])\n happystr(n,\"\",[])\n if len(ans) list = new ArrayList<>();\n\n for (int i = 1; i <= n; i++) {\n\n if (n % i == 0){\n list.add(i);\n }\n }\n if (list.size() < k){\n return -1;\n }\n \n return list.get(k-1);\n }\n}\n", + "title": "1492. The kth Factor of n", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two positive integers n and k . A factor of an integer n is defined as an integer i where n % i == 0 . Consider a list of all factors of n sorted in ascending order , return the k th factor in this list or return -1 if n has less than k factors. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= k <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12, k = 3Output:3Explanation:Factors list is [1, 2, 3, 4, 6, 12], the 3rdfactor is 3.", + "image": null + }, + { + "text": "Example 2: Input:n = 7, k = 2Output:7Explanation:Factors list is [1, 7], the 2ndfactor is 7.", + "image": null + }, + { + "text": "Example 3: Input:n = 4, k = 4Output:-1Explanation:Factors list is [1, 2, 4], there is only 3 factors. We should return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def kthFactor(self, n: int, k: int) -> int:\n start=[1]\n end=[n]\n for i in range(2,math.ceil(math.sqrt(n))+1):\n if n%i==0:\n start.append(i)\n if i!=n//i:\n end.append(n//i)\n start=sorted(set(start).union(set(end)))\n if k<=len(start):\n return start[k-1]\n else:\n return -1\n", + "title": "1492. The kth Factor of n", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array buses of length n , where buses[i] represents the departure time of the i th bus. You are also given a 0-indexed integer array passengers of length m , where passengers[j] represents the arrival time of the j th passenger. All bus departure times are unique. All passenger arrival times are unique. You are given an integer capacity , which represents the maximum number of passengers that can get on each bus. When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x , and the bus is not full. Passengers with the earliest arrival times get on the bus first. More formally when a bus arrives, either: Return the latest time you may arrive at the bus station to catch a bus . You cannot arrive at the same time as another passenger. Note: The arrays buses and passengers are not necessarily sorted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or", + "The capacity passengers with the earliest arrival times will get on the bus." + ], + "examples": [ + { + "text": "Example 1: Input:buses = [10,20], passengers = [2,17,18,19], capacity = 2Output:16Explanation:Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0thpassenger. \nAt time 20, the second bus departs with you and the 1stpassenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1stpassenger to catch the bus.", + "image": null + }, + { + "text": "Example 2: Input:buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2Output:20Explanation:Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rdpassenger. \nAt time 20, the second bus departs with the 5thand 1stpassengers.\nAt time 30, the third bus departs with the 0thpassenger and you.\nNotice if you had arrived any later, then the 6thpassenger would have taken your seat on the third bus.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 59 ms (Top 40.13%) | Memory: 106.7 MB (Top 13.12%)\nclass Solution {\n public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) {\n Arrays.sort(buses);\n Arrays.sort(passengers);\n HashSet set = new HashSet<>();\n for(int val : passengers){\n set.add(val);\n }\n int n = buses.length;\n int m = passengers.length;\n int solb = capacity; // solb = space on last bus\n int lastPerson = 0;\n int i = 0, j = 0;\n while(i < n && j < m){\n int cc = capacity; // cc => current capacity;\n while(j < m && cc > 0 && buses[i] >= passengers[j]){\n cc--;\n lastPerson = passengers[j];\n j++;\n }\n i++;\n solb = cc;\n }\n int x = lastPerson;\n if(solb > 0 || i != n){\n x = buses[n - 1];\n }\n while(set.contains(x) == true){\n x--;\n }\n return x;\n }\n}", + "title": "2332. The Latest Time to Catch a Bus", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed integer array buses of length n , where buses[i] represents the departure time of the i th bus. You are also given a 0-indexed integer array passengers of length m , where passengers[j] represents the arrival time of the j th passenger. All bus departure times are unique. All passenger arrival times are unique. You are given an integer capacity , which represents the maximum number of passengers that can get on each bus. When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x , and the bus is not full. Passengers with the earliest arrival times get on the bus first. More formally when a bus arrives, either: Return the latest time you may arrive at the bus station to catch a bus . You cannot arrive at the same time as another passenger. Note: The arrays buses and passengers are not necessarily sorted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or", + "The capacity passengers with the earliest arrival times will get on the bus." + ], + "examples": [ + { + "text": "Example 1: Input:buses = [10,20], passengers = [2,17,18,19], capacity = 2Output:16Explanation:Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0thpassenger. \nAt time 20, the second bus departs with you and the 1stpassenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1stpassenger to catch the bus.", + "image": null + }, + { + "text": "Example 2: Input:buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2Output:20Explanation:Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rdpassenger. \nAt time 20, the second bus departs with the 5thand 1stpassengers.\nAt time 30, the third bus departs with the 0thpassenger and you.\nNotice if you had arrived any later, then the 6thpassenger would have taken your seat on the third bus.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n passengers.sort()\n cur = 0\n\n for time in sorted(buses):\n cap = capacity\n while cur < len(passengers) and passengers[cur] <= time and cap > 0:\n cur += 1\n cap -= 1\n\n best = time if cap > 0 else passengers[cur - 1]\n\n passengers = set(passengers)\n while best in passengers:\n best -= 1\n return best\n", + "title": "2332. The Latest Time to Catch a Bus", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00 , and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime , this means you have played from loginTime to midnight and from midnight to logoutTime . Return the number of full chess rounds you have played in the tournament . Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the second round starts at 00:15 , the fourth round starts at 00:45 , and the seventh round starts at 01:30 ." + ], + "examples": [ + { + "text": "Example 1: Input:loginTime = \"09:31\", logoutTime = \"10:14\"Output:1Explanation:You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.", + "image": null + }, + { + "text": "Example 2: Input:loginTime = \"21:30\", logoutTime = \"03:00\"Output:22Explanation:You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 91.49%) | Memory: 42.3 MB (Top 21.28%)\nclass Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n String[] arr1 = loginTime.split(\":\");\n String[] arr2 = logoutTime.split(\":\");\n\n int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]);\n int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]);\n\n if(time1 > time2) time2 = time2 + 24*60;\n if(time1%15 != 0) time1 = time1 + 15-time1%15;\n\n return (time2 - time1)/15;\n }\n}", + "title": "1904. The Number of Full Rounds You Have Played", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00 , and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime , this means you have played from loginTime to midnight and from midnight to logoutTime . Return the number of full chess rounds you have played in the tournament . Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the second round starts at 00:15 , the fourth round starts at 00:45 , and the seventh round starts at 01:30 ." + ], + "examples": [ + { + "text": "Example 1: Input:loginTime = \"09:31\", logoutTime = \"10:14\"Output:1Explanation:You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.", + "image": null + }, + { + "text": "Example 2: Input:loginTime = \"21:30\", logoutTime = \"03:00\"Output:22Explanation:You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 41 ms (Top 45.3%) | Memory: 16.25 MB (Top 71.7%)\n\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(\":\"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(\":\"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96", + "title": "1904. The Number of Full Rounds You Have Played", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 10^9 + 7 . A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums . Two subsets are different if and only if the chosen indices to delete are different. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums = [1, 2, 3, 4] : [2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.", + "[2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively.", + "[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:6Explanation:The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,15]Output:5Explanation:The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 100.0%) | Memory: 63.20 MB (Top 13.04%)\n\nclass Solution {\n static int MOD = 1_000_000_000 + 7;\n\n // These numbers contain duplicate factors (e.g 4, 8, 9, 25), will be excluded\n static List excludes = new ArrayList<>();\n\n // Distinct prime factors of composites\n // e.g 6 = 2 * 3, 15 = 3 * 5, 30 = 2 * 3 * 5\n static List[] factors = new List[31];\n\n // Coprime numbers permutation\n // Coprime means some composites don't have common factor and can coexist\n // e.g. 14 = 2 * 7 and 15 = 3 * 5\n static List coprimes_pmt = new ArrayList<>();\n\n static {\n List primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);\n int[] masks = new int[31];\n\n for (int i = 4; i <= 30; i++) {\n // exclude 4, 8, 9, 25 ...\n if (i % 4 == 0 || i % 9 == 0 || i % 25 == 0) {\n excludes.add(i);\n continue;\n }\n\n if (primes.contains(i)) {\n continue;\n }\n\n // Set distinct prime factors of composites\n for (int j = 0; j < primes.size(); j++) {\n if (i % primes.get(j) == 0) {\n if (factors[i] == null) {\n factors[i] = new ArrayList<>();\n }\n factors[i].add(primes.get(j));\n masks[i] |= (1 << j);\n }\n }\n }\n\n // Recursively build coprime permutation\n buildCoprimes(0, masks, 0, new int[]{});\n }\n\n static void buildCoprimes(int mask, int[] masks, int num, int[] prev) {\n for (; num < masks.length; num++) {\n if (masks[num] > 0 && (mask & masks[num]) == 0) {\n int[] arr = Arrays.copyOf(prev, prev.length + 1);\n arr[prev.length] = num;\n coprimes_pmt.add(arr);\n buildCoprimes(mask | masks[num], masks, num + 1, arr);\n }\n }\n }\n\n public int numberOfGoodSubsets(int[] nums) {\n\n int[] prime_count = new int[31];\n int[] composite_count = new int[31];\n\n for (int num : nums) {\n prime_count[num]++;\n }\n\n // exclude numbers having duplicate factors, like 4, 8, 9, 25...\n for (int ex : excludes) {\n prime_count[ex] = 0;\n }\n\n // split prime numbers and composite numbers\n for (int i = 0; i < prime_count.length; i++) {\n if (factors[i] != null) {\n composite_count[i] = prime_count[i];\n prime_count[i] = 0;\n }\n }\n\n // sum result for prime numbers\n long result = sum(prime_count, null);\n\n // sum result for coprime numbers\n for (int[] coprimes : coprimes_pmt) {\n long count_mul = 1;\n for (int composite : coprimes) {\n count_mul *= composite_count[composite];\n }\n\n if (count_mul > 0) {\n result = (result + (sum(prime_count, coprimes) + 1) * count_mul) % MOD;\n }\n }\n\n // Each `1` will double the result\n while (prime_count[1] > 0) {\n result = (result * 2) % MOD;\n prime_count[1]--;\n }\n\n return (int) result;\n }\n\n int sum(int[] prime_count, int[] coprimes) {\n int[] dp = Arrays.copyOf(prime_count, prime_count.length);\n\n // Exclude prime factors of coprime numbers\n if (coprimes != null) {\n for (int composite : coprimes) {\n for (int factor : factors[composite]) {\n dp[factor] = 0;\n }\n }\n }\n\n for (int i = 3; i <= 29 ; i++) {\n dp[i] = (int) ((dp[i - 1] + 1L * dp[i - 1] * dp[i] + dp[i]) % MOD);\n }\n return dp[29];\n }\n}\n", + "title": "1994. The Number of Good Subsets", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an integer array nums . We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. Return the number of different good subsets in nums modulo 10^9 + 7 . A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums . Two subsets are different if and only if the chosen indices to delete are different. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if nums = [1, 2, 3, 4] : [2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively. [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.", + "[2, 3] , [1, 2, 3] , and [1, 3] are good subsets with products 6 = 2*3 , 6 = 2*3 , and 3 = 3 respectively.", + "[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:6Explanation:The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,15]Output:5Explanation:The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "from collections import Counter\nfrom functools import lru_cache\nfrom typing import List, Tuple\n\nPRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29)\n\nBIG_NUMBER = 10 ** 9 + 7\n\n\n@lru_cache(maxsize=32)\ndef factor(n) -> Tuple[int, bool]:\n \"\"\"\n :param n: 1 < n <= max(PRIMES)\n :return: (factors in bit mask, has duplicate primes)\n \"\"\"\n output = 0\n\n for e in PRIMES:\n while n > 1 and n % e == 0:\n mask = 1 << e\n\n if mask & output:\n return -1, False\n\n output |= mask\n\n n //= e\n\n if n == 1:\n break\n\n return output, True\n\n\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n masks = []\n\n for e in nums:\n if 1 < e and (fr := factor(e))[1]:\n masks.append(fr[0])\n\n cnt = Counter(masks)\n good_nums = Counter({0: 0})\n\n for mask in cnt:\n for f in tuple(good_nums):\n if f & mask: # some prime dividing \"mask\" is also dividing the \"f\"\n continue\n\n new_mask = f | mask\n\n count_for_new_mask = good_nums[new_mask] + cnt[mask] * (good_nums[f] or 1)\n\n good_nums[new_mask] = count_for_new_mask % BIG_NUMBER\n\n effect_of_one = pow(2, nums.count(1), BIG_NUMBER)\n total_subsets_without_one = sum(good_nums.values()) % BIG_NUMBER\n\n return (effect_of_one * total_subsets_without_one) % BIG_NUMBER\n", + "title": "1994. The Number of Good Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity . When a friend arrives at the party, they sit on the unoccupied chair with the smallest number . When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrival i , leaving i ] , indicating the arrival and leaving times of the i th friend respectively, and an integer targetFriend . All arrival times are distinct . Return the chair number that the friend numbered targetFriend will sit on . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if chairs 0 , 1 , and 5 are occupied when a friend comes, they will sit on chair number 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:times = [[1,4],[2,3],[4,6]], targetFriend = 1Output:1Explanation:- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.", + "image": null + }, + { + "text": "Example 2: Input:times = [[3,10],[1,5],[2,6]], targetFriend = 0Output:2Explanation:- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 116 ms (Top 33.59%) | Memory: 71.2 MB (Top 32.82%)\nclass Solution {\n public int smallestChair(int[][] times, int targetFriend) {\n int targetStart = times[targetFriend][0];\n Arrays.sort(times, (a, b) -> a[0] - b[0]);\n\n PriorityQueue available = new PriorityQueue<>();\n for (int i = 0; i < times.length; ++ i) {\n available.offer(i);\n }\n\n PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n\n for (int i = 0; i < times.length; ++ i) {\n while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) {\n available.offer(pq.poll()[1]);\n }\n\n if (times[i][0] == targetStart) {\n break;\n }\n\n pq.offer(new int[]{times[i][1], available.poll()});\n }\n\n return available.peek();\n }\n}", + "title": "1942. The Number of the Smallest Unoccupied Chair", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity . When a friend arrives at the party, they sit on the unoccupied chair with the smallest number . When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrival i , leaving i ] , indicating the arrival and leaving times of the i th friend respectively, and an integer targetFriend . All arrival times are distinct . Return the chair number that the friend numbered targetFriend will sit on . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if chairs 0 , 1 , and 5 are occupied when a friend comes, they will sit on chair number 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:times = [[1,4],[2,3],[4,6]], targetFriend = 1Output:1Explanation:- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.", + "image": null + }, + { + "text": "Example 2: Input:times = [[3,10],[1,5],[2,6]], targetFriend = 0Output:2Explanation:- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n arrivals = []\n departures = []\n for ind, (x, y) in enumerate(times):\n heappush(arrivals, (x, ind))\n heappush(departures, (y, ind))\n d = {}\n occupied = [0] * len(times)\n while True:\n if arrivals and departures and arrivals[0][0] < departures[0][0]:\n _, ind = heappop(arrivals)\n d[ind] = occupied.index(0)\n occupied[d[ind]] = 1\n if ind == targetFriend:\n return d[ind]\n elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n _, ind = heappop(departures)\n occupied[d[ind]] = 0\n", + "title": "1942. The Number of the Smallest Unoccupied Chair", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense . You are given a 2D integer array properties where properties[i] = [attack i , defense i ] represents the properties of the i th character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attack j > attack i and defense j > defense i . Return the number of weak characters . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= properties.length <= 10^5", + "properties[i].length == 2", + "1 <= attack i , defense i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:properties = [[5,5],[6,3],[3,6]]Output:0Explanation:No character has strictly greater attack and defense than the other.", + "image": null + }, + { + "text": "Example 2: Input:properties = [[2,2],[3,3]]Output:1Explanation:The first character is weak because the second character has a strictly greater attack and defense.", + "image": null + }, + { + "text": "Example 3: Input:properties = [[1,5],[10,4],[4,3]]Output:1Explanation:The third character is weak because the second character has a strictly greater attack and defense.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 90.90%) | Memory: 138 MB (Top 23.61%)\nclass Solution {\n public int numberOfWeakCharacters(int[][] properties) {\n int[] maxH = new int[100002];\n int count = 0;\n for(int[] point:properties){\n maxH[point[0]] = Math.max(point[1],maxH[point[0]]);\n }\n for(int i=100000;i>=0;i--){\n maxH[i] = Math.max(maxH[i+1],maxH[i]);\n }\n\n for(int[] point:properties){\n if(point[1] attack i and defense j > defense i . Return the number of weak characters . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= properties.length <= 10^5", + "properties[i].length == 2", + "1 <= attack i , defense i <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:properties = [[5,5],[6,3],[3,6]]Output:0Explanation:No character has strictly greater attack and defense than the other.", + "image": null + }, + { + "text": "Example 2: Input:properties = [[2,2],[3,3]]Output:1Explanation:The first character is weak because the second character has a strictly greater attack and defense.", + "image": null + }, + { + "text": "Example 3: Input:properties = [[1,5],[10,4],[4,3]]Output:1Explanation:The third character is weak because the second character has a strictly greater attack and defense.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 4914 ms (Top 7.28%) | Memory: 66.6 MB (Top 91.64%)\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n\n properties.sort(key=lambda x: (-x[0],x[1]))\n\n ans = 0\n curr_max = 0\n\n for _, d in properties:\n if d < curr_max:\n ans += 1\n else:\n curr_max = d\n return ans", + "title": "1996. The Number of Weak Characters in the Game", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s that contains digits 0-9 , addition symbols '+' , and multiplication symbols '*' only , representing a valid math expression of single digit numbers (e.g., 3+5*2 ). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations : You are given an integer array answers of length n , which are the submitted answers of the students in no particular order. You are asked to grade the answers , by following these rules : Return the sum of the points of the students . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If an answer equals the correct answer of the expression, this student will be rewarded 5 points;", + "Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic , this student will be rewarded 2 points;", + "Otherwise, this student will be rewarded 0 points." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"7+3*1*2\", answers = [20,13,42]Output:7Explanation:As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.", + "image": "https://assets.leetcode.com/uploads/2021/09/17/student_solving_math.png" + }, + { + "text": "Example 2: Input:s = \"3+5*2\", answers = [13,0,10,13,13,16,16]Output:19Explanation:The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.", + "image": null + }, + { + "text": "Example 3: Input:s = \"6+0*1\", answers = [12,9,6,4,8,6]Output:10Explanation:The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 161 ms (Top 97.83%) | Memory: 45.80 MB (Top 93.48%)\n\nclass Solution {\n public int scoreOfStudents(String s, int[] answers) {\n BitSet[][] ok = new BitSet[32][32];\n solve(0, s.length()-1, s, ok);\n int ans = 0, correct = eval(s);\n for (int n : answers){\n if (correct == n){\n ans += 5;\n }else if (ok[0][s.length()-1].get(n)){\n ans += 2;\n }\n }\n return ans;\n }\n\n private BitSet solve(int lo, int hi, String s, BitSet[][] memo){\n if (memo[lo][hi] != null){ // memo\n return memo[lo][hi];\n }\n BitSet cur = new BitSet();\n if (lo == hi){ // base case -> number itself [0 - 9]\n cur.set(s.charAt(lo) - '0');\n return memo[lo][hi]=cur;\n }\n for (int i = lo; i <= hi; i++){\n if (s.charAt(i) == '+' || s.charAt(i) == '*'){\n BitSet l = solve(lo, i-1, s, memo); // left\n BitSet r = solve(i+1, hi, s, memo); // right\n for (int j = l.nextSetBit(0); j >= 0; j = l.nextSetBit(j+1)){\n for (int k = r.nextSetBit(0); k >= 0; k = r.nextSetBit(k+1)){\n int val = s.charAt(i) == '+'? j+k:j*k;\n if (val > 1000){\n break;\n }\n cur.set(val);\n }\n }\n }\n }\n return memo[lo][hi]=cur;\n }\n\n private int eval(String s){\n Deque stack = new ArrayDeque<>();\n Deque op = new ArrayDeque<>();\n for(char ch : s.toCharArray()){\n if (ch == '+' || ch == '*'){\n while(!op.isEmpty() && (ch == '+' || op.peek() == '*')){\n char w = op.pop();\n int r = stack.pop(), l = stack.pop();\n stack.push(w == '+'? l + r : l * r);\n }\n op.push(ch);\n }else{\n stack.push(ch-'0');\n }\n }\n while(!op.isEmpty()){\n char w = op.pop();\n int r = stack.pop(), l = stack.pop();\n stack.push(w == '+'? l + r : l * r);\n }\n\n return stack.pop();\n }\n}\n", + "title": "2019. The Score of Students Solving Math Expression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a string s that contains digits 0-9 , addition symbols '+' , and multiplication symbols '*' only , representing a valid math expression of single digit numbers (e.g., 3+5*2 ). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations : You are given an integer array answers of length n , which are the submitted answers of the students in no particular order. You are asked to grade the answers , by following these rules : Return the sum of the points of the students . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If an answer equals the correct answer of the expression, this student will be rewarded 5 points;", + "Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic , this student will be rewarded 2 points;", + "Otherwise, this student will be rewarded 0 points." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"7+3*1*2\", answers = [20,13,42]Output:7Explanation:As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.", + "image": "https://assets.leetcode.com/uploads/2021/09/17/student_solving_math.png" + }, + { + "text": "Example 2: Input:s = \"3+5*2\", answers = [13,0,10,13,13,16,16]Output:19Explanation:The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.", + "image": null + }, + { + "text": "Example 3: Input:s = \"6+0*1\", answers = [12,9,6,4,8,6]Output:10Explanation:The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \n @cache\n def fn(lo, hi): \n \"\"\"Return possible answers of s[lo:hi].\"\"\"\n if lo+1 == hi: return {int(s[lo])}\n ans = set()\n for mid in range(lo+1, hi, 2): \n for x in fn(lo, mid): \n for y in fn(mid+1, hi): \n if s[mid] == \"+\" and x + y <= 1000: ans.add(x + y)\n elif s[mid] == \"*\" and x * y <= 1000: ans.add(x * y)\n return ans \n \n target = eval(s)\n cand = fn(0, len(s))\n ans = 0 \n for x in answers: \n if x == target: ans += 5\n elif x in cand: ans += 2\n return ans ", + "title": "2019. The Score of Students Solving Math Expression", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively . The geometric information of each building is given in the array buildings where buildings[i] = [left i , right i , height i ] : You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 . The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x 1 ,y 1 ],[x 2 ,y 2 ],...] . Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] Example 1: Example 2:", + "description_images": [], + "constraints": [ + "left i is the x coordinate of the left edge of the i th building.", + "right i is the x coordinate of the right edge of the i th building.", + "height i is the height of the i th building." + ], + "examples": [ + { + "text": "Example 1: Input:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]Output:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]Explanation:Figure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" + }, + { + "text": "Example 2: Input:buildings = [[0,2,3],[2,5,3]]Output:[[0,3],[5,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class height implements Comparable{\n int val = -1;\n int pos = -1;\n boolean isStart = false;\n height(int a, int b, boolean c){\n val = a;\n pos = b;\n isStart = c;\n }\n public int compareTo(height h){\n if(this.pos != h.pos)\n return this.pos-h.pos;\n if(isStart)\n return -1;\n if(h.isStart)\n return 1;\n \n return this.val-h.val;\n }\n}\nclass Solution {\n public List> getSkyline(int[][] buildings) {\n \n PriorityQueue mQ = new PriorityQueue<>();\n int len = buildings.length;\n for(int[] b: buildings) {\n mQ.add(new height(b[2],b[0],true));\n mQ.add(new height(b[2],b[1],false));\n }\n PriorityQueue heap = new PriorityQueue<>(Collections.reverseOrder());\n heap.add(0);\n int prevHeight = 0;\n List> res = new ArrayList<>();\n List lst;\n while(mQ.size()>0) {\n height h = mQ.poll();\n if(h.isStart){\n heap.offer(h.val);\n } else {\n heap.remove(h.val);\n }\n \n if(prevHeight != heap.peek()){\n lst = new ArrayList<>();\n lst.add(h.pos);\n \n if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){\n lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1)));\n res.remove(res.size()-1);\n } else \n lst.add(heap.peek());\n res.add(lst);\n prevHeight = heap.peek();\n }\n }\n return res;\n }\n}\n", + "title": "218. The Skyline Problem", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively . The geometric information of each building is given in the array buildings where buildings[i] = [left i , right i , height i ] : You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0 . The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x 1 ,y 1 ],[x 2 ,y 2 ],...] . Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] Example 1: Example 2:", + "description_images": [], + "constraints": [ + "left i is the x coordinate of the left edge of the i th building.", + "right i is the x coordinate of the right edge of the i th building.", + "height i is the height of the i th building." + ], + "examples": [ + { + "text": "Example 1: Input:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]Output:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]Explanation:Figure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/merged.jpg" + }, + { + "text": "Example 2: Input:buildings = [[0,2,3],[2,5,3]]Output:[[0,3],[5,0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(list)\n \n for i,(start, end, height) in enumerate(buildings):\n d[start].append(height)\n d[end].append(-height)\n \n l = list(d.keys())\n l.sort()\n \n result = []\n \n active = []\n \n for key in l:\n o = d[key]\n o.sort(reverse=True)\n for j in o:\n if j > 0:\n if not result or not active:\n result.append([key, j])\n active.append(j)\n else:\n if j > active[-1]:\n result.append([key, j])\n active.append(j)\n else:\n active.insert(bisect_left(active, j), j)\n else:\n idx = active.index(-j)\n if idx == len(active) - 1:\n active.pop()\n if active:\n result.append([key, active[-1]])\n else:\n result.append([key, 0])\n else:\n active.pop(idx)\n \n return result\n \n", + "title": "218. The Skyline Problem", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a network of n servers, labeled from 0 to n - 1 . You are given a 2D integer array edges , where edges[i] = [u i , v i ] indicates there is a message channel between servers u i and v i , and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n . All servers are connected , i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally , so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0 , each data server sends its message to be processed. Starting from second 1 , at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.", + "Otherwise, no more resending will occur from this server." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1],[1,2]], patience = [0,2,1]Output:8Explanation:At (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/quiet-place-example1.png" + }, + { + "text": "Example 2: Input:edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]Output:3Explanation:Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/04/network_a_quiet_place_2.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 193 ms (Top 55.29%) | Memory: 195.4 MB (Top 40.00%)\n\nclass Solution {\n public int networkBecomesIdle(int[][] edges, int[] patience) {\n int n = patience.length;\n\n // creating adjacency list\n ArrayList> adj = new ArrayList<>();\n for(int i = 0 ; i < n ; i++ ) {\n adj.add(new ArrayList<>());\n }\n\n for(int[] edge : edges) {\n adj.get(edge[0]).add(edge[1]);\n adj.get(edge[1]).add(edge[0]);\n }\n\n // getting the distance array using dijkstra algorithm\n int[] dist = dijkstra(adj);\n\n // variable to store the result\n int ans = 0;\n\n // performing the calculations discussed above for each index\n for(int x = 1; x < n ; x++) {\n\n // round trip time\n int time = 2*dist[x];\n\n int p = patience[x];\n\n //total number of messages the station will send until it receives the reply of first message\n int numberOfMessagesSent = (time)/p;\n\n //handling an edge case if round trip time is a multiple of patience example time =24 patience = 4\n //then the reply would be received at 24 therefore station will not send any message at t = 24\n if(time%p == 0) {\n numberOfMessagesSent--;\n }\n\n // time of last message\n int lastMessage = numberOfMessagesSent*p;\n\n // updating the ans to store max of time at which the station becomes idle\n ans = Math.max(ans,lastMessage+ 2*dist[x]+1);\n\n }\n\n return ans;\n }\n\n // simple dijkstra algorithm implementation\n private int[] dijkstra(ArrayList> adj) {\n\n int n = adj.size();\n\n int[] dist = new int[n];\n boolean[] visited = new boolean[n];\n\n Arrays.fill(dist,Integer.MAX_VALUE);\n dist[0] = 0;\n\n PriorityQueue pq = new PriorityQueue<>((o1,o2)->o1[1]-o2[1]);\n\n pq.add(new int[]{0,0});\n\n while(!pq.isEmpty()) {\n int[] node = pq.remove();\n if(!visited[node[0]]) {\n visited[node[0]] = true;\n for(int nbr : adj.get(node[0])) {\n if(dist[nbr] > dist[node[0]]+1) {\n dist[nbr] = dist[node[0]]+1;\n pq.add(new int[]{nbr,dist[nbr]});\n }\n }\n }\n\n }\n\n return dist;\n }\n\n}\n", + "title": "2039. The Time When the Network Becomes Idle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There is a network of n servers, labeled from 0 to n - 1 . You are given a 2D integer array edges , where edges[i] = [u i , v i ] indicates there is a message channel between servers u i and v i , and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n . All servers are connected , i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally , so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0 , each data server sends its message to be processed. Starting from second 1 , at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.", + "Otherwise, no more resending will occur from this server." + ], + "examples": [ + { + "text": "Example 1: Input:edges = [[0,1],[1,2]], patience = [0,2,1]Output:8Explanation:At (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/22/quiet-place-example1.png" + }, + { + "text": "Example 2: Input:edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]Output:3Explanation:Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.", + "image": "https://assets.leetcode.com/uploads/2021/09/04/network_a_quiet_place_2.png" + } + ], + "follow_up": null, + "solution": "# Runtime: 2578 ms (Top 92.45%) | Memory: 69.3 MB (Top 19.78%)\nclass Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n\n #Build Adjency List\n adjList = defaultdict(list)\n\n for source, target in edges:\n adjList[source].append(target)\n adjList[target].append(source)\n\n #BFS to get the shortest route from node to master.\n shortest = {}\n queue = deque([(0,0)])\n seen = set()\n while queue:\n currPos, currDist = queue.popleft()\n\n if currPos in seen:\n continue\n seen.add(currPos)\n shortest[currPos] = currDist\n\n for nei in adjList[currPos]:\n queue.append((nei, currDist+1))\n\n #Calculate answer using shortest paths.\n ans = 0\n for index in range(1,len(patience)):\n resendInterval = patience[index]\n\n #The server will stop sending requests after it's been sent to the master node and back.\n shutOffTime = (shortest[index] * 2)\n\n # shutOffTime-1 == Last second the server can send a re-request.\n lastSecond = shutOffTime-1\n\n #Calculate the last time a packet is actually resent.\n lastResentTime = (lastSecond//resendInterval)*resendInterval\n\n # At the last resent time, the packet still must go through 2 more cycles to the master node and back.\n lastPacketTime = lastResentTime + shutOffTime\n\n ans = max(lastPacketTime, ans)\n\n #Add +1, the current answer is the last time the packet is recieved by the target server (still active).\n #We must return the first second the network is idle, therefore + 1\n return ans + 1", + "title": "2039. The Time When the Network Becomes Idle", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an integer array nums , return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1]Output:1Explanation:The first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]Output:2Explanation:The first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,3,1]Output:1Explanation:The first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 42.70 MB (Top 89.77%)\n\nclass Solution {\n public int thirdMax(int[] nums) {\n\t\n\t\t// taking long data type since array can contain Integer.MIN_VALUE\n long max = Long.MIN_VALUE, sMax = Long.MIN_VALUE, tMax = Long.MIN_VALUE;\n for (int i : nums) {\n if (i > max) {\n tMax = sMax;\n sMax = max;\n max = i;\n } else if (i > sMax && i != max) {\n tMax = sMax;\n sMax = i;\n } else if (i > tMax && i != sMax && i != max) {\n tMax = i;\n }\n }\n\t\t\n\t\t// if thirdMax was not updated, return the first Max\n\t\t\n return tMax == Long.MIN_VALUE ? (int) max : (int) tMax;\n }\n}\n", + "title": "414. Third Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1]Output:1Explanation:The first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2]Output:2Explanation:The first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,3,1]Output:1Explanation:The first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def thirdMax(self, nums: List[int]) -> int:\n nums_set = set(nums)\n sorted_set = sorted(nums_set)\n return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1]\n \n \n #use set() to remove dups\n #if len of nums after dups have been removed is at least 2, a third max val must exist\n #if not, just return the max\n \n \n #you can do it in 1 line like this but then you have to call the same functions repeatedly\n #return sorted(set(nums))[-3] if len(set(nums)) > 2 else sorted(set(nums))[-1]\n \n \n \n", + "title": "414. Third Maximum Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , add a dot (\".\") as the thousands separator and return it in string format. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 987Output:\"987\"", + "image": null + }, + { + "text": "Example 2: Input:n = 1234Output:\"1.234\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 39.69 MB (Top 67.9%)\n\nclass Solution {\n public String thousandSeparator(int n) {\n \n StringBuffer str = new StringBuffer(Integer.toString(n));\n int index = str.length() - 3;\n \n while(index >= 1){\n str.insert(index , '.');\n index = index - 3;\n }\n \n return str.toString();\n }\n}", + "title": "1556. Thousand Separator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , add a dot (\".\") as the thousands separator and return it in string format. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 987Output:\"987\"", + "image": null + }, + { + "text": "Example 2: Input:n = 1234Output:\"1.234\"", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 17 ms (Top 24.0%) | Memory: 13.24 MB (Top 48.1%)\n\nclass Solution(object):\n def thousandSeparator(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n n = str(n)\n if len(n) <= 3:\n return str(n)\n result = \"\" \n dot = '.'\n index = 0\n startPos = len(n) % 3 \n if startPos == 0:\n startPos += 3\n val = -1\n while index < len(n):\n result += n[index]\n if index == startPos - 1:\n result += dot\n val = 0\n if val != -1:\n val += 1\n if val > 3 and (val - 1) % 3 == 0 and index != len(n) - 1:\n result += dot\n val = 1 \n index += 1\n\n return result", + "title": "1556. Thousand Separator", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,6,4,1]Output:falseExplanation:There are no three consecutive odds.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,34,3,4,5,7,23,12]Output:trueExplanation:[5,7,23] are three consecutive odds.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean threeConsecutiveOdds(int[] arr) {\n int count = 0,n = arr.length;\n for(int i=0;i 0)\n {\n count++;\n if(count == 3) return true;\n }\n else\n {\n count = 0;\n }\n }\n return false;\n }\n}\n", + "title": "1550. Three Consecutive Odds", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "1 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,6,4,1]Output:falseExplanation:There are no three consecutive odds.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2,34,3,4,5,7,23,12]Output:trueExplanation:[5,7,23] are three consecutive odds.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 106 ms (Top 5.05%) | Memory: 14 MB (Top 60.17%)\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n c=0\n for i in arr:\n if i%2==0:\n c=0\n else:\n c+=1\n if c==3:\n return True\n return False", + "title": "1550. Three Consecutive Odds", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return true if n has exactly three positive divisors . Otherwise, return false . An integer m is a divisor of n if there exists an integer k such that n = k * m . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:falseExplantion:2 has only two divisors: 1 and 2.", + "image": null + }, + { + "text": "Example 2: Input:n = 4Output:trueExplantion:4 has three divisors: 1, 2, and 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isThree(int n) {\n if(n<4 ) return false;\n int res = (int)Math.sqrt(n);\n for(int i=2;i*i bool:\n return sum(n%i == 0 for i in range(1, n+1)) == 3\n", + "title": "1952. Three Divisors", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j , such that: If it is not possible, return [-1, -1] . Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3 . Also, leading zeros are allowed , so [0,1,1] and [1,1] represent the same value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr[0], arr[1], ..., arr[i] is the first part,", + "arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and", + "arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.", + "All three parts have equal binary values." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,1,0,1]Output:[0,3]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,0,1,1]Output:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,1,0,0,1]Output:[0,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 43.75%) | Memory: 48.2 MB (Top 87.50%)\nclass Solution {\n public int[] threeEqualParts(int[] arr) {\n List ones = new ArrayList<>();\n for (int i = 0; i < arr.length; i++){\n if (arr[i]==1){\n ones.add(i);\n }\n }\n if (ones.size()==0){ // edge case\n return new int[]{0,2};\n }\n int[] ans = new int[2];\n int each = ones.size()/3;\n for (int i = 0; i < 2 && ones.size()%3==0; i++){ // for the first 2 partitions\n for (int j = 0; j < each-1; j++){ // compare gaps\n if (ones.get(j+1+i*each)-ones.get(j+i*each)!=ones.get(j+2*each+1)-ones.get(j+2*each))\n return new int[]{-1, -1};\n }\n ans[i]=ones.get((i+1)*each-1)+i+(arr.length - 1 - ones.get(ones.size()-1)); // cut point\n }\n return ones.size()%3>0||ans[0]>=ones.get(each)||ans[1]>ones.get(2*each)?\n new int[]{-1, -1} : ans;\n }\n}", + "title": "927. Three Equal Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j , such that: If it is not possible, return [-1, -1] . Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3 . Also, leading zeros are allowed , so [0,1,1] and [1,1] represent the same value. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr[0], arr[1], ..., arr[i] is the first part,", + "arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and", + "arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.", + "All three parts have equal binary values." + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,0,1,0,1]Output:[0,3]", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,1,0,1,1]Output:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:arr = [1,1,0,0,1]Output:[0,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n n = len(arr)\n count_one = arr.count(1)\n if count_one == 0: return [0,n-1]\n if count_one % 3!= 0: return [-1,-1]\n target_ones = count_one // 3\n breaks = []\n one_count = 0\n for i , bit in enumerate(arr):\n if bit ==1 :\n one_count +=1\n if one_count in [1,target_ones+1,2*target_ones+1]:breaks.append(i) \n if one_count in [target_ones,2*target_ones,3*target_ones]:breaks.append(i)\n i1,j1,i2,j2,i3,j3 = breaks\n \n if not arr[i1:j1+1] == arr[i2:j2+1] == arr[i3:j3+1]:return [-1,-1]\n \n trailing_zeroes_left = i2 - j1 - 1\n trailing_zeroes_mid = i3 - j2 - 1\n trailing_zeroes_right = n - j3 - 1\n if trailing_zeroes_right > min(trailing_zeroes_left,trailing_zeroes_mid):return [-1,-1]\n j1 += trailing_zeroes_right\n j2 += trailing_zeroes_right\n return [j1,j2+1]\n \n", + "title": "927. Three Equal Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder) , which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. Using the above function, we can always obtain a unique order of inheritance. Implement the ThroneInheritance class: Example 1:", + "description_images": [], + "constraints": [ + "ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.", + "void birth(string parentName, string childName) Indicates that parentName gave birth to childName .", + "void death(string name) Indicates the death of name . The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.", + "string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people." + ], + "examples": [ + { + "text": "Example 1: Input[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]Output[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]ExplanationThroneInheritance t= new ThroneInheritance(\"king\"); // order:kingt.birth(\"king\", \"andy\"); // order: king >andyt.birth(\"king\", \"bob\"); // order: king > andy >bobt.birth(\"king\", \"catherine\"); // order: king > andy > bob >catherinet.birth(\"andy\", \"matthew\"); // order: king > andy >matthew> bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob >alex> catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex >asha> catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew >bob> alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]", + "image": null + }, + { + "text": "Successor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder", + "image": null + } + ], + "follow_up": null, + "solution": "class Tree{\n Listchild;\n String name;\n public Tree(String name,Listchild){\n this.name=name;\n this.child=child;\n }\n}\nclass ThroneInheritance {\n private Setdeath;\n private Tree tree;\n private MapaddtoTree;\n public ThroneInheritance(String kingName) {\n death=new HashSet<>(); \n tree=new Tree(kingName,new ArrayList());\n addtoTree=new HashMap();\n addtoTree.put(kingName,tree); \n }\n \n public void birth(String parentName, String childName) {\n Tree tmp =addtoTree.get(parentName);\n Tree childtree=new Tree(childName,new ArrayList());\n tmp.child.add(childtree);\n addtoTree.put( childName,childtree); \n }\n \n public void death(String name) {\n death.add(name);\n }\n \n public List getInheritanceOrder() {\n Listans=new ArrayList<>();\n preOreder(tree,ans,death);\n return ans;\n }\n \n void preOreder(Tree n,Listans,Setdeath){\n if(n==null)return;\n if(!death.contains(n.name))ans.add(n.name);\n for(Tree name:n.child){\n preOreder(name,ans,death);\n }\n }\n}\n", + "title": "1600. Throne Inheritance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder) , which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance. For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. Using the above function, we can always obtain a unique order of inheritance. Implement the ThroneInheritance class: Example 1:", + "description_images": [], + "constraints": [ + "ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.", + "void birth(string parentName, string childName) Indicates that parentName gave birth to childName .", + "void death(string name) Indicates the death of name . The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.", + "string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people." + ], + "examples": [ + { + "text": "Example 1: Input[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]Output[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]ExplanationThroneInheritance t= new ThroneInheritance(\"king\"); // order:kingt.birth(\"king\", \"andy\"); // order: king >andyt.birth(\"king\", \"bob\"); // order: king > andy >bobt.birth(\"king\", \"catherine\"); // order: king > andy > bob >catherinet.birth(\"andy\", \"matthew\"); // order: king > andy >matthew> bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob >alex> catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex >asha> catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew >bob> alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]", + "image": null + }, + { + "text": "Successor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1338 ms (Top 35.29%) | Memory: 68.8 MB (Top 82.35%)\n\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n # Taking kingName as root\n self.root = kingName\n\n # notDead will hold all the people who are alive and their level number\n self.alive = {}\n self.alive[kingName] = 0\n\n # hold edges existing in our graph\n self.edges = {self.root:[]}\n\n def birth(self, parentName: str, childName: str) -> None:\n # birth --> new child so update alive\n self.alive[childName] = self.alive[parentName]+1\n\n # add parent to child edges in the edges dictionary\n if parentName in self.edges:\n self.edges[parentName].append(childName)\n if childName not in self.edges:\n self.edges[childName] = []\n else:\n if childName not in self.edges:\n self.edges[childName] = []\n self.edges[parentName] = [childName]\n\n def death(self, name: str) -> None:\n # removing the dead people from alive map\n del self.alive[name]\n\n def getInheritanceOrder(self) -> List[str]:\n\n hierarchy = []\n def dfs(cur,parent=-1):\n nonlocal hierarchy\n\n # current person available in alive then only add in hierarchy\n if cur in self.alive:\n hierarchy.append(cur)\n\n # traverse all the children of current node\n for i in self.edges[cur]:\n if i!=parent:\n dfs(i,cur)\n dfs(self.root)\n return hierarchy", + "title": "1600. Throne Inheritance", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a rectangle of size n x m , return the minimum number of integer-sided squares that tile the rectangle . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/17/sample_11_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_22_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_33_1592.png" + ], + "constraints": [ + "1 <= n, m <= 13" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3Output:3Explanation:3squares are necessary to cover the rectangle.2(squares of1x1)1(square of2x2)", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 8Output:5", + "image": null + }, + { + "text": "Example 3: Input:n = 11, m = 13Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 31.8%) | Memory: 39.08 MB (Top 78.7%)\n\nclass Solution {\n int ret; // store the final result\n int m, n; // m is the height, and n is the width\n\t\n\t// Note: original signature is changed from n,m to m,n\n public int tilingRectangle(int m, int n) { \n this.m = m;\n this.n = n;\n this.ret = m * n; // initilize the result as m*n if cut rectangle to be all 1*1 squares\n int[][] mat = new int[m][n]; // record the status of every location, 0 means not covered, 1 means covered\n backtrack(mat, 0); // start backtracking\n return ret;\n }\n \n\t// the size means how many squares cut now\n public void backtrack(int[][] mat, int size) {\n if (size > ret) return; // if we already have more squares than the min result, no need to go forward\n \n\t\t// find out the leftmost and topmost postion where is not covered yet\n int x = -1, y = -1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n x = i;\n y = j;\n break;\n }\n }\n if (x != -1 && y != -1) break;\n }\n\t\t// if not found, we know that all positions are covered\n if (x == -1 && y == -1) {\n\t\t // update the result\n ret = Math.min(size, ret);\n }\n else {\n int len = findWidth(x, y, mat); // find the maximum width to cut the square\n while(len >= 1) {\n cover(x, y, len, mat, 1); // cover the current square\n backtrack(mat, size + 1);\n cover(x, y, len, mat, 0); // uncover the previous result\n len--; // decrement the square width by 1\n }\n }\n }\n \n public int findWidth(int x, int y, int[][] mat) {\n int len = 1;\n while(x + len < m && y + len < n) {\n boolean flag = true; // flag means the len is reachable\n for (int i = 0; i <= len; i++) {\n\t\t\t // check the right i-th column and the bottom i-th row away from (x, y) \n if (mat[x + i][y + len] == 1 || mat[x + len][y + i] == 1) {\n flag = false;\n break;\n }\n }\n if (!flag) break;\n len++;\n }\n return len;\n }\n \n public void cover(int x, int y, int len, int[][] mat, int val) {\n for (int i = x; i < x + len; i++) {\n for (int j = y; j < y + len; j++) {\n mat[i][j] = val;\n }\n }\n }\n}", + "title": "1240. Tiling a Rectangle with the Fewest Squares", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a rectangle of size n x m , return the minimum number of integer-sided squares that tile the rectangle . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/10/17/sample_11_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_22_1592.png", + "https://assets.leetcode.com/uploads/2019/10/17/sample_33_1592.png" + ], + "constraints": [ + "1 <= n, m <= 13" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2, m = 3Output:3Explanation:3squares are necessary to cover the rectangle.2(squares of1x1)1(square of2x2)", + "image": null + }, + { + "text": "Example 2: Input:n = 5, m = 8Output:5", + "image": null + }, + { + "text": "Example 3: Input:n = 11, m = 13Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 197 ms (Top 21.3%) | Memory: 16.48 MB (Top 34.6%)\n\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n # try brute force backtracking?\n board = [[0 for _ in range(n)] for _ in range(m)]\n\n ans = math.inf\n def bt(counts):\n nonlocal ans\n if counts >= ans:\n return\n \n pos = None\n found = False\n for row in range(m):\n for col in range(n):\n if board[row][col] == 0:\n pos = (row, col)\n found = True\n break\n if found:\n break\n if not found:\n ans = min(ans, counts)\n return\n\n # see how many difference size of squares we can place from this spot\n r, c = pos\n offset = 0\n while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n offset += 1\n # max can place size is offset\n for row in range(r, r + offset):\n for col in range(c, c + offset):\n board[row][col] = 1\n # do bt and shrink\n while offset > 0:\n bt(counts + 1)\n # shrink\n for row in range(r, r + offset):\n board[row][c + offset - 1] = 0\n for col in range(c, c + offset):\n board[r + offset - 1][col] = 0\n offset -= 1\n\n bt(0)\n return ans", + "title": "1240. Tiling a Rectangle with the Fewest Squares", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap {\n private Map> map;\n private final String NOT_FOUND = \"\";\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n List entries = map.getOrDefault(key, new ArrayList<>());\n entries.add(new Entry(value, timestamp));\n map.put(key, entries);\n }\n \n public String get(String key, int timestamp) {\n List entries = map.get(key);\n if (entries == null) {\n return NOT_FOUND;\n }\n return binarySearch(entries, timestamp);\n }\n \n private String binarySearch(List entries, int timestamp) {\n int lo = 0, hi = entries.size() - 1, mid = -1;\n String ans = \"\";\n \n // Base cases - if value is not set, return empty\n if (entries.get(lo).timestamp > timestamp) {\n return NOT_FOUND;\n }\n // If timestamp is equal or greater, return the last value saved in map against this key, since that will have the largest timestamp\n else if (entries.get(hi).timestamp <= timestamp) {\n return entries.get(hi).value;\n }\n \n // Else apply binary search to get correct value\n while (lo <= hi) {\n mid = lo + (hi-lo)/2;\n Entry entry = entries.get(mid);\n // System.out.println(\"mid: \"+mid);\n if (entry.timestamp == timestamp) {\n return entry.value;\n }\n // Save ans, and look for ans on right half to find greater timestamp\n else if (entry.timestamp < timestamp) {\n ans = entry.value;\n lo = mid + 1;\n }\n else {\n hi = mid - 1;\n }\n }\n return ans;\n }\n}\n\nclass Entry {\n String value;\n int timestamp;\n \n public Entry(String value, int timestamp) {\n this.value = value;\n this.timestamp = timestamp;\n }\n}\n", + "title": "981. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap:\n\n def __init__(self):\n self.dict = {}\n \n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if key not in self.dict:\n self.dict[key] = ([], [])\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n else:\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n \n \n def bsearch(self, nums, target):\n beg = 0\n end = len(nums)-1\n lastIndex = len(nums)-1\n \n while beg<=end:\n mid = (beg+end)//2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n end = mid-1\n elif target > nums[mid]:\n beg = mid+1\n \n \n if target < nums[mid] and mid == 0:\n return -1\n if target > nums[mid]:\n return mid\n return mid-1\n \n def get(self, key: str, timestamp: int) -> str:\n if key not in self.dict:\n return \"\"\n \n index = self.bsearch(self.dict[key][1], timestamp)\n return self.dict[key][0][index] if 0 <= index < len(self.dict[key][0]) else \"\"\n \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n", + "title": "981. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n people in a line queuing to buy tickets, where the 0 th person is at the front of the line and the (n - 1) th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the i th person would like to buy is tickets[i] . Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously ) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person at position k (0-indexed) to finish buying tickets . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == tickets.length", + "1 <= n <= 100", + "1 <= tickets[i] <= 100", + "0 <= k < n" + ], + "examples": [ + { + "text": "Example 1: Input:tickets = [2,3,2], k = 2Output:6Explanation:- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.", + "image": null + }, + { + "text": "Example 2: Input:tickets = [5,1,1,1], k = 0Output:8Explanation:- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].\n- In the next 4 passes, only the person in position 0 is buying tickets.\nThe person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 62.6%) | Memory: 40.11 MB (Top 61.2%)\n\nclass Solution {\n public int timeRequiredToBuy(int[] tickets, int k){\n int n= tickets.length;\n int time=0;\n \n if(tickets[k]==1) return k+1;\n while(tickets[k]>0){\n for(int i=0;i int:\n return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t))\n", + "title": "2073. Time Needed to Buy Tickets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, headID = 0, manager = [-1], informTime = [0]Output:0Explanation:The head of the company is the only employee in the company.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]Output:1Explanation: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.\nThe tree structure of the employees in the company is shown.", + "image": "https://assets.leetcode.com/uploads/2020/02/27/graph.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 89 ms (Top 45.5%) | Memory: 63.76 MB (Top 32.3%)\n\nclass Solution {\n public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {\n Map> graph = new HashMap<>();\n for(int i=0; i());\n graph.get(manager[i]).add(i);\n }\n return dfs(graph, headID, informTime);\n }\n\n int dfs(Map> graph, int curHead, int[] informTime) {\n int curMax = 0;\n if(!graph.containsKey(curHead)){\n return curMax;\n }\n for(int subordinate : graph.get(curHead)) {\n curMax = Math.max(curMax, dfs(graph, subordinate, informTime));\n }\n return curMax + informTime[curHead];\n }\n}", + "title": "1376. Time Needed to Inform All Employees", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1, headID = 0, manager = [-1], informTime = [0]Output:0Explanation:The head of the company is the only employee in the company.", + "image": null + }, + { + "text": "Example 2: Input:n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]Output:1Explanation: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.\nThe tree structure of the employees in the company is shown.", + "image": "https://assets.leetcode.com/uploads/2020/02/27/graph.png" + } + ], + "follow_up": null, + "solution": "import queue\nclass Solution:\n\tdef numOfMinutes(self, n: int, headID: int, manager: List[int],time: List[int]) -> int:\n\t\tnodes = []\n\t\tfor i in range(n): nodes.append([])\n\t\tfor i in range(n): \n\t\t\tif i != headID: nodes[manager[i]].append(i)\n\n\t\tq = queue.LifoQueue()\n\t\tq.put([headID,0])\n\t\tans = 0\n\t\twhile not q.empty():\n\t\t\tcur = q.get()\n\t\t\tfor nxt in nodes[cur[0]]:\n\t\t\t\tq.put([nxt,cur[1]+time[cur[0]]])\n\t\t\t\tans = max(ans,cur[1]+time[cur[0]])\n\t\treturn ans", + "title": "1376. Time Needed to Inform All Employees", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , return the string after replacing every uppercase letter with the same lowercase letter . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 100", + "s consists of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello\"Output:\"hello\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"here\"Output:\"here\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"LOVELY\"Output:\"lovely\"", + "image": null + } + ], + "follow_up": null, + "solution": "#approach -1\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n ch = \"\"\n for i in s:\n asc = ord(i)\n if asc > 64 and asc < 91:\n ch += chr(asc+32)\n else:\n ch +=chr(asc)\n return ch\n \n#approach -2\nclass Solution:\n return s.lower()\n", + "title": "709. To Lower Case", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an m x n matrix , return true if the matrix is Toeplitz. Otherwise, return false . A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 20", + "0 <= matrix[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]Output:trueExplanation:In the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2],[2,2]]Output:falseExplanation:The diagonal \"[1, 2]\" has different elements.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isToeplitzMatrix(int[][] matrix) {\n \n \n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int i = 0; i < m; i++){\n int row = 0;\n int col = i;\n int e = matrix[row++][col++];\n while(row < n && col< m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n } \n }\n \n for(int r = 1; r < n; r++){\n int row = r;\n int col = 0;\n int e =matrix[row++][col++];\n while(row < n && col < m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n }\n }\n \n return true;\n }\n}\n", + "title": "766. Toeplitz Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an m x n matrix , return true if the matrix is Toeplitz. Otherwise, return false . A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 20", + "0 <= matrix[i][j] <= 99" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]Output:trueExplanation:In the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,2],[2,2]]Output:falseExplanation:The diagonal \"[1, 2]\" has different elements.", + "image": "https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg" + } + ], + "follow_up": null, + "solution": "###########################################################################################\n# Runtime: O(MN)\n# Number of rows(M) x expected numbers(N)\n# Space: O(N)\n# We need to store the expected numbers in list\n############################################################################################\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n # Validate Input\n if not matrix or not matrix[0]:\n return False \n \n # Create a deque tracking the expected values for the next row\n expected = matrix[0]\n # We only care about the elements before last element\n expected.pop()\n \n # From the second row, pop out the last element of the expected numbers and compare it with the target row[1:]\n for row in matrix[1:]:\n # Compare row with expected numbers, invalidate it as soon as we find the numbers are not the same (O(N))\n if row[1:] != expected:\n return False\n else:\n # Pop the last element from row, use it as the expected numbers for the next iteration\n row.pop()\n expected = row\n # If we've reached here, all diagonals aligned\n return True\n", + "title": "766. Toeplitz Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2Output:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tpublic int[] topKFrequent(int[] nums, int k) {\n\t\tMap map = new HashMap<>();\n\n\t\tfor (int num : nums) { \n\t\t\tmap.merge(num, 1, Integer::sum);\n\t\t}\n\n\t\treturn map.entrySet()\n\t\t\t.stream()\n\t\t\t.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n\t\t\t.map(Map.Entry::getKey)\n\t\t\t.mapToInt(x -> x)\n\t\t\t.limit(k)\n\t\t\t.toArray();\n\t}\n}\n", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2Output:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [i[0] for i in Counter(nums).most_common(k)]\n", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of strings words and an integer k , return the k most frequent strings . Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 500", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters.", + "k is in the range [1, The number of unique words[i]]" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2Output:[\"i\",\"love\"]Explanation:\"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4Output:[\"the\",\"is\",\"sunny\",\"day\"]Explanation:\"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public List topKFrequent(String[] words, int k) {\n Map map=new LinkedHashMap<>();\n for(String word:words) \n map.put(word,map.getOrDefault(word,0)+1);\n PriorityQueue> queue=new PriorityQueue<>(new Comparator>(){\n @Override\n public int compare(Pair a,Pair b){\n if(a.getValue()!=b.getValue()) return b.getValue()-a.getValue();\n return a.getKey().compareTo(b.getKey());\n }\n });\n map.forEach((key,val)->{\n queue.add(new Pair(key,val));\n });\n List list=new ArrayList<>();\n while(k>0){\n list.add(queue.poll().getKey());\n k--;\n }\n return list;\n }\n}", + "title": "692. Top K Frequent Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of strings words and an integer k , return the k most frequent strings . Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 500", + "1 <= words[i].length <= 10", + "words[i] consists of lowercase English letters.", + "k is in the range [1, The number of unique words[i]]" + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2Output:[\"i\",\"love\"]Explanation:\"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4Output:[\"the\",\"is\",\"sunny\",\"day\"]Explanation:\"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "import heapq\nclass Solution:\n def topKFrequent(self, words: List[str], k: int) -> List[str]:\n \n li = {}\n for i in words:\n if i in li:\n li[i]+=1\n else:\n li[i]=1\n \n heap = []\n for i in li:\n heap.append([-li[i],i])\n \n heapq.heapify(heap)\n \n ans = []\n for i in range(k):\n ans.append(heapq.heappop(heap)[1])\n \n return ans", + "title": "692. Top K Frequent Words", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The appeal of a string is the number of distinct characters found in the string. Given a string s , return the total appeal of all of its substrings . A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbca\"Output:28Explanation:The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.", + "image": null + }, + { + "text": "Example 2: Input:s = \"code\"Output:20Explanation:The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 9 ms (Top 66.9%) | Memory: 43.90 MB (Top 92.4%)\n\nclass Solution {\n public long appealSum(String s) {\n long res = 0;\n char[] cs = s.toCharArray();\n int n = cs.length;\n int[] pos = new int[26];\n Arrays.fill(pos, -1);\n for (int i = 0; i < n; ++i) {\n int j = cs[i] - 'a', prev = pos[j]; \n res += (i - prev) * (long) (n - i);\n pos[j] = i;\n }\n return res;\n }\n}", + "title": "2262. Total Appeal of A String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "The appeal of a string is the number of distinct characters found in the string. Given a string s , return the total appeal of all of its substrings . A substring is a contiguous sequence of characters within a string. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a' , 'b' , and 'c' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abbca\"Output:28Explanation:The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.", + "image": null + }, + { + "text": "Example 2: Input:s = \"code\"Output:20Explanation:The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 201 ms (Top 33.23%) | Memory: 18.20 MB (Top 28.53%)\n\nclass Solution:\n def appealSum(self, s: str) -> int:\n res, n, prev = 0, len(s), defaultdict(lambda: -1)\n for i, ch in enumerate(s):\n res += (i - prev[ch]) * (n - i)\n prev[ch] = i\n return res\n", + "title": "2262. Total Appeal of A String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums , return the sum of Hamming distances between all the pairs of the integers in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^9", + "The answer for the given input will fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,14,2]Output:6Explanation:In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,14,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 24 ms (Top 19.37%) | Memory: 53.8 MB (Top 78.38%)\nclass Solution {\n public int totalHammingDistance(int[] nums) {\n int total = 0;\n int[][] cnt = new int[2][32];\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < 32; j++) {\n int idx = (nums[i] >> j) & 1;\n total += cnt[idx ^ 1][j];\n cnt[idx][j]++;\n }\n }\n return total;\n }\n}", + "title": "477. Total Hamming Distance", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums , return the sum of Hamming distances between all the pairs of the integers in nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^9", + "The answer for the given input will fit in a 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,14,2]Output:6Explanation:In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,14,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 947 ms (Top 34.04%) | Memory: 15.5 MB (Top 30.97%)\nclass Solution:\n def totalHammingDistance(self, arr: List[int]) -> int:\n\n total = 0\n for i in range(0,31):\n count = 0\n for j in arr :\n count+= (j >> i) & 1\n total += count*(len(arr)-count)\n return total", + "title": "477. Total Hamming Distance", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n binary grid board . In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board . If the task is impossible, return -1 . A chessboard board is a board where no 0 's and no 1 's are 4-directionally adjacent. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == board.length", + "n == board[i].length", + "2 <= n <= 30", + "board[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]Output:2Explanation:One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[0,1],[1,0]]Output:0Explanation:Also note that the board with 0 in the top left corner, is also a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[1,0],[1,0]]Output:-1Explanation:No matter what sequence of moves you make, you cannot end with a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int movesToChessboard(int[][] board) {\n int N = board.length, colToMove = 0, rowToMove = 0, rowOneCnt = 0, colOneCnt = 0;\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++) {\n if (((board[0][0] ^ board[i][0]) ^ (board[i][j] ^ board[0][j])) == 1) {\n return -1;\n }\n }\n }\n for (int i = 0; i < N; i++) {\n rowOneCnt += board[0][i];\n colOneCnt += board[i][0];\n if (board[i][0] == i % 2) {\n rowToMove++;\n }\n if (board[0][i] == i % 2) {\n colToMove++;\n }\n }\n if (rowOneCnt < N / 2 || rowOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (N % 2 == 1) {\n // we cannot make it when ..ToMove is odd\n if (colToMove % 2 == 1) {\n colToMove = N - colToMove;\n }\n if (rowToMove % 2 == 1) {\n rowToMove = N - rowToMove;\n }\n } else {\n colToMove = Math.min(colToMove, N - colToMove);\n rowToMove = Math.min(rowToMove, N - rowToMove);\n }\n return (colToMove + rowToMove) / 2;\n }\n\n}\n", + "title": "782. Transform to Chessboard", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an n x n binary grid board . In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board . If the task is impossible, return -1 . A chessboard board is a board where no 0 's and no 1 's are 4-directionally adjacent. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == board.length", + "n == board[i].length", + "2 <= n <= 30", + "board[i][j] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]Output:2Explanation:One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [[0,1],[1,0]]Output:0Explanation:Also note that the board with 0 in the top left corner, is also a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [[1,0],[1,0]]Output:-1Explanation:No matter what sequence of moves you make, you cannot end with a valid chessboard.", + "image": "https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def movesToChessboard(self, board):\n N = len(board)\n ans = 0\n # For each count of lines from {rows, columns}...\n for count in (collections.Counter(map(tuple, board)), # get row\n collections.Counter(zip(*board))): #get column\n\n # If there are more than 2 kinds of lines,\n # or if the number of kinds is not appropriate ...\n if len(count) != 2 or sorted(count.values()) != [N/2, (N+1)/2]:\n return -1\n\n # If the lines are not opposite each other, impossible\n line1, line2 = count\n if not all(x ^ y for x, y in zip(line1, line2)):\n return -1\n\n # starts = what could be the starting value of line1\n # If N is odd, then we have to start with the more\n # frequent element\n starts = [int(line1.count(1) * 2 > N)] if N%2 else [0, 1]\n\n # To transform line1 into the ideal line [i%2 for i ...],\n # we take the number of differences and divide by two\n ans += min(sum((x-i) % 2 for i, x in enumerate(line1, start))\n for start in starts) / 2 \n\n return ans\n", + "title": "782. Transform to Chessboard", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 2D integer array matrix , return the transpose of matrix . The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png" + ], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "-10^9 <= matrix[i][j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[[1,4,7],[2,5,8],[3,6,9]]", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[4,5,6]]Output:[[1,4],[2,5],[3,6]]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 43.1 MB (Top 92.66%)\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n int[][] trans = new int[n][m];\n\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n trans[i][j] = matrix[j][i];\n }\n }\n\n return trans;\n }\n}", + "title": "867. Transpose Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a 2D integer array matrix , return the transpose of matrix . The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png" + ], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 1000", + "1 <= m * n <= 10^5", + "-10^9 <= matrix[i][j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[[1,4,7],[2,5,8],[3,6,9]]", + "image": null + }, + { + "text": "Example 2: Input:matrix = [[1,2,3],[4,5,6]]Output:[[1,4],[2,5],[3,6]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n rows=len(matrix)\n cols=len(matrix[0])\n ans=[[0]*rows]*cols\n for i in range(cols):\n for j in range(rows):\n ans[i][j]=matrix[j][i]\n return ans\n", + "title": "867. Transpose Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]Output:6Explanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trap(int[] height) {\n int left = 0;\n int right = height.length - 1;\n \n int l_max = height[left];\n int r_max = height[right];\n int res = 0;\n \n while(left < right) {\n if(l_max < r_max) {\n left+=1;\n l_max = Math.max(l_max, height[left]);\n res += l_max - height[left];\n }\n else{\n right-=1;\n r_max = Math.max(r_max, height[right]);\n res += r_max - height[right];\n }\n }\n \n return res;\n }\n}\n", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]Output:6Explanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 254 ms (Top 43.79%) | Memory: 16.1 MB (Top 46.67%)\nclass Solution:\n def trap(self, a: List[int]) -> int:\n l=0\n r=len(a)-1\n maxl=0\n maxr=0\n res=0\n\n while (l<=r):\n if a[l]<=a[r]:\n if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >=\n else: res+=maxl-a[l] #adding captured water when maxl>a[l]\n l+=1\n else:\n if a[r]>=maxr: maxr=a[r]\n else: res+=maxr-a[r]\n r-=1\n return res\n", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == heightMap.length", + "n == heightMap[i].length", + "1 <= m, n <= 200", + "0 <= heightMap[i][j] <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]Output:4Explanation:After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" + }, + { + "text": "Example 2: Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]Output:10", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public class pair implements Comparable{\n int row;\n int col;\n int val;\n pair(int row, int col,int val){\n this.row = row;\n this.col = col;\n this.val = val;\n }\n public int compareTo(pair o){\n return this.val - o.val;\n }\n }\n int[][] dir = {{1,0},{0,-1},{-1,0},{0,1}};\n public int trapRainWater(int[][] heightMap) {\n int n = heightMap.length;\n int m = heightMap[0].length;\n \n PriorityQueue pq = new PriorityQueue<>();\n \n boolean[][] visited = new boolean[n][m];\n \n // add all the boundary elements in pq\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(i == 0 || j == 0 || i == n-1 || j == m-1){\n pq.add(new pair(i, j, heightMap[i][j]));\n visited[i][j] = true;\n }\n }\n }\n \n int ans = 0;\n \n while(pq.size() > 0){\n pair rem = pq.remove();\n for(int i = 0; i < 4; i++){\n \n int rowdash = rem.row + dir[i][0];\n int coldash = rem.col + dir[i][1];\n \n if(rowdash >= 0 && coldash >= 0 && rowdash < n && coldash < m && visited[rowdash][coldash] == false){\n visited[rowdash][coldash] = true;\n if(heightMap[rowdash][coldash] >= rem.val){\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated\n }else{\n int waterstored = rem.val - heightMap[rowdash][coldash];\n ans += waterstored; // now this will act as a wall add in pq\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));\n }\n }\n }\n }\n return ans;\n }\n}\n", + "title": "407. Trapping Rain Water II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == heightMap.length", + "n == heightMap[i].length", + "1 <= m, n <= 200", + "0 <= heightMap[i][j] <= 2 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]Output:4Explanation:After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" + }, + { + "text": "Example 2: Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]Output:10", + "image": "https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" + } + ], + "follow_up": null, + "solution": "import heapq\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n ROW, COL = len(heightMap), len(heightMap[0])\n\n pq = []\n heapq.heapify(pq)\n visited = {}\n \n for row in range(ROW):\n for col in range(COL):\n if row == 0 or row == ROW-1 or col == 0 or col == COL-1:\n heapq.heappush(pq, (heightMap[row][col],row,col))\n visited[(row,col)] = True\n \n def getnbr(row,col):\n res = []\n if row-1 >=0:\n res.append((row-1,col))\n if col-1 >=0:\n res.append((row, col-1))\n if row+1 < ROW:\n res.append((row+1,col))\n if col+1 < COL:\n res.append((row, col+1))\n\n return res\n \n res = 0\n \n while pq:\n h, i, j = heapq.heappop(pq)\n \n for dx, dy in getnbr(i,j):\n if (dx,dy) not in visited: \n \n res += max(0, h-heightMap[dx][dy])\n \n heapq.heappush(pq, (max(h, heightMap[dx][dy]),dx,dy))\n visited[(dx,dy)] = True\n\n return res\n", + "title": "407. Trapping Rain Water II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0 . To represent this tree, you are given an integer array nums and a 2D array edges . Each nums[i] represents the i th node's value, and each edges[j] = [u j , v j ] represents an edge between nodes u j and v j in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y . An ancestor of a node i is any other node on the shortest path from node i to the root . A node is not considered an ancestor of itself. Return an array ans of size n , where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime , or -1 if there is no such ancestor . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram.png", + "https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram1.png" + ], + "constraints": [ + "nums.length == n", + "1 <= nums[i] <= 50", + "1 <= n <= 10^5", + "edges.length == n - 1", + "edges[j].length == 2", + "0 <= u j , v j < n", + "u j != v j" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]Output:[-1,0,0,1]Explanation:In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]Output:[-1,0,-1,0,0,0,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n //made TreeNode class for simple implementation in recurring function\n class TreeNode{\n int id;\n int val;\n List child;\n public TreeNode(int id,int val){\n this.id=id;this.val=val;child=new ArrayList<>();\n }\n }\n public int[] getCoprimes(int[] nums, int[][] edges) {\n // making tree/graph with edges\n TreeNode[] tr=new TreeNode[nums.length];\n for(int i=0;i List[int]:\n \n gcdset = [set() for i in range(51)]\n for i in range(1,51):\n for j in range(1,51):\n if math.gcd(i,j) == 1:\n gcdset[i].add(j)\n gcdset[j].add(i)\n \n graph = defaultdict(list)\n for v1, v2 in edges:\n graph[v1].append(v2)\n graph[v2].append(v1)\n \n ans = [-1]*len(nums)\n q = [[0, {}]]\n seen = set([0])\n depth = 0\n while q:\n temp = []\n for node, ancestors in q:\n index_depth = (-1,-1)\n for anc in list(ancestors.keys()):\n if anc in gcdset[nums[node]]:\n index, d = ancestors[anc]\n if d > index_depth[1]:\n index_depth = (index,d)\n ans[node] = index_depth[0]\n \n copy = ancestors.copy()\n copy[nums[node]] = (node,depth)\n \n for child in graph[node]:\n if child not in seen:\n seen.add(child)\n temp.append([child, copy])\n q = temp\n depth += 1\n return ans", + "title": "1766. Tree of Coprimes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a triangle array, return the minimum path sum from top to bottom . For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= triangle.length <= 200", + "triangle[0].length == 1", + "triangle[i].length == triangle[i - 1].length + 1", + "-10^4 <= triangle[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]Output:11Explanation:The triangle looks like:234\n 657\n418 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).", + "image": null + }, + { + "text": "Example 2: Input:triangle = [[-10]]Output:-10", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 6 ms (Top 41.54%) | Memory: 43.9 MB (Top 66.49%)\nclass Solution {\n public int minimumTotal(List> triangle) {\n\n int n = triangle.get( triangle.size() - 1).size();\n int dp[] = new int[n + 1];\n\n for(int i = triangle.size() - 1; i>=0; i--)\n {\n for(int j = 0; j int:\n dp = []\n dp.append(t[0])\n \n r = len(t)\n answer = float('inf')\n for i in range(1, r):\n c = len(t[i])\n dp.append([])\n for j in range(0, c):\n if j == 0:\n val = dp[i - 1][j] + t[i][j]\n elif j == c - 1:\n val = dp[i - 1][j - 1] + t[i][j]\n else:\n val = min(dp[i - 1][j], dp[i - 1][j - 1]) + t[i][j]\n if i == r - 1:\n answer = min(answer, val)\n dp[i].append(val)\n return answer if r > 1 else t[0][0]\n", + "title": "120. Triangle", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high , trim the tree so that all its elements lies in [low, high] . Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer . Return the root of the trimmed binary search tree . Note that the root may change depending on the given bounds. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The value of each node in the tree is unique .", + "root is guaranteed to be a valid binary search tree.", + "0 <= low <= high <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,2], low = 1, high = 2Output:[1,null,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg" + }, + { + "text": "Example 2: Input:root = [3,0,4,null,2,null,null,1], low = 1, high = 3Output:[3,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 45.6 MB (Top 46.04%)\nclass Solution {\n public TreeNode trimBST(TreeNode root, int low, int high) {\n if (root == null) return root;\n while (root.val < low || root.val > high) {\n root = root.val < low ? root.right : root.left;\n if (root == null)\n return root;\n }\n root.left = trimBST(root.left, low, high);\n root.right = trimBST(root.right, low, high);\n return root;\n }\n}", + "title": "669. Trim a Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given the root of a binary search tree and the lowest and highest boundaries as low and high , trim the tree so that all its elements lies in [low, high] . Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer . Return the root of the trimmed binary search tree . Note that the root may change depending on the given bounds. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "0 <= Node.val <= 10^4", + "The value of each node in the tree is unique .", + "root is guaranteed to be a valid binary search tree.", + "0 <= low <= high <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,0,2], low = 1, high = 2Output:[1,null,2]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg" + }, + { + "text": "Example 2: Input:root = [3,0,4,null,2,null,null,1], low = 1, high = 3Output:[3,2,null,1]", + "image": "https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 58 ms (Top 27.96%) | Memory: 20.40 MB (Top 38.8%)\n\nclass Solution:\n\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\tif not root: return root\n\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\troot.left = self.trimBST(root.left, low, high)\n\t\troot.right = self.trimBST(root.right, low, high)\n\t\treturn root", + "title": "669. Trim a Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums, return the number of AND triples . An AND triple is a triple of indices (i, j, k) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < nums.length", + "0 <= j < nums.length", + "0 <= k < nums.length", + "nums[i] & nums[j] & nums[k] == 0 , where & represents the bitwise-AND operator." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:12Explanation:We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]Output:27", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 113 ms (Top 49.3%) | Memory: 43.66 MB (Top 52.1%)\n\nclass Solution {\n public int countTriplets(int[] nums) {\n int[] count = new int[1 << 16];\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < nums.length; j++) {\n count[nums[i] & nums[j]]++;\n }\n }\n int ans = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < 1 << 16; j++) {\n if ((nums[i] & j) == 0) {\n ans += count[j];\n }\n }\n }\n return ans;\n }\n}", + "title": "982. Triples with Bitwise AND Equal To Zero", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array nums, return the number of AND triples . An AND triple is a triple of indices (i, j, k) such that: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= i < nums.length", + "0 <= j < nums.length", + "0 <= k < nums.length", + "nums[i] & nums[j] & nums[k] == 0 , where & represents the bitwise-AND operator." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,3]Output:12Explanation:We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0]Output:27", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 549 ms (Top 98.6%) | Memory: 23.43 MB (Top 9.7%)\n\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans ", + "title": "982. Triples with Bitwise AND Equal To Zero", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). You are given a sentence s ​​​​​​ and an integer k ​​​​​​. You want to truncate s ​​​​​​ such that it contains only the first k ​​​​​​ words. Return s ​​​​ ​​ after truncating it. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"Hello World\" , \"HELLO\" , and \"hello world hello world\" are all sentences." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello how are you Contestant\", k = 4Output:\"Hello how are you\"Explanation:The words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"What is the solution to this problem\", k = 4Output:\"What is the solution\"Explanation:The words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"chopper is not a tanuki\", k = 5Output:\"chopper is not a tanuki\"", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 77.37%)\n\nclass Solution {\n public String truncateSentence(String s, int k) {\n int n = s.length();\n int count = 0;\n int i = 0;\n while(i str:\n words = s.split(\" \")\n return \" \".join(words[0:k])\n", + "title": "1816. Truncate Sentence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a , b , c , and d are elements of nums , and a != b != c != d . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "All elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,4,6]Output:8Explanation:There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,5,10]Output:16Explanation:There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tupleSameProduct(int[] nums) {\n \n if(nums.length < 4){\n return 0;\n }\n \n int res = 0;\n \n HashMap map = new HashMap<>();\n \n for(int i = 0; i < nums.length - 1; i++){\n \n for(int j = i + 1; j < nums.length; j++){\n \n int val = nums[i] * nums[j];\n map.put(val, map.getOrDefault(val, 0) + 1);\n }\n }\n \n for(int key : map.keySet()){\n \n int val = map.get(key);\n \n if(val > 1){\n res += val * (val - 1) * 4; // (val * (val - 1) / 2) * 8\n }\n }\n \n return res;\n }\n}\n", + "title": "1726. Tuple with Same Product", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a , b , c , and d are elements of nums , and a != b != c != d . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "All elements in nums are distinct ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,4,6]Output:8Explanation:There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,4,5,10]Output:16Explanation:There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1072 ms (Top 44.44%) | Memory: 42.9 MB (Top 86.75%)\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n\n from itertools import combinations\n mydict=defaultdict(int)\n ans=0\n\n for a,b in combinations(nums,2):\n mydict[a*b]+=1\n\n for i,j in mydict.items():\n if j>1:\n ans+=(j*(j-1)//2)*8\n\n return ans", + "title": "1726. Tuple with Same Product", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute , hour , or day ). For example, the period [10, 10000] (in seconds ) would be partitioned into the following time chunks with these frequencies: Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period ( 10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: Example:", + "description_images": [], + "constraints": [ + "Every minute (60-second chunks): [10,69] , [70,129] , [130,189] , ... , [9970,10000]", + "Every hour (3600-second chunks): [10,3609] , [3610,7209] , [7210,10000]", + "Every day (86400-second chunks): [10,10000]" + ], + "examples": [ + { + "text": "Example: Input[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]Output[null,null,null,null,[2],[2,1],null,[4]]ExplanationTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 351 ms (Top 16.84%) | Memory: 93.3 MB (Top 14.74%)\nclass TweetCounts {\n Map> map;\n public TweetCounts() {\n map = new HashMap<>();\n }\n\n public void recordTweet(String tweetName, int time) {\n map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time);\n }\n\n public List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {\n List res = new ArrayList<>();\n if(map.containsKey(tweetName)) {\n Collections.sort(map.get(tweetName));\n while(startTime<=endTime) {\n int interval = Freq.valueOf(freq).getVal();\n int end = Math.min(startTime+interval-1, endTime); // need this to handle the last interval\n res.add(getFreq(map.get(tweetName), startTime, end));\n startTime=end+1; // ex: for minute, the interval is 60 so our end is 59. The next startTime is end+1\n }\n }\n return res;\n }\n\n public int getFreq(List list, int start, int end) {\n int st = Collections.binarySearch(list, start);\n if(st<0) {\n st = (st+1)*-1; // our exact start time might not be in the list, to get the 1st timestamp greater than start\n }\n int en = Collections.binarySearch(list, end);\n if(en<0) {\n en = (en+2)*-1; // our exact end time might not be in the list, to get the last timestamp just smaller than end\n }\n\n return en-st+1; // the freq count\n }\n}\n\n enum Freq {\n minute(60), hour(3600), day(86400);\n Map map = new HashMap<>();\n Freq(int val) {\n map.put(this, val);\n }\n\n public int getVal() {\n return map.get(this);\n }\n\n}\n\n/**\n * Your TweetCounts object will be instantiated and called as such:\n * TweetCounts obj = new TweetCounts();\n * obj.recordTweet(tweetName,time);\n * List param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);\n */\n", + "title": "1348. Tweet Counts Per Frequency", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute , hour , or day ). For example, the period [10, 10000] (in seconds ) would be partitioned into the following time chunks with these frequencies: Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period ( 10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: Example:", + "description_images": [], + "constraints": [ + "Every minute (60-second chunks): [10,69] , [70,129] , [130,189] , ... , [9970,10000]", + "Every hour (3600-second chunks): [10,3609] , [3610,7209] , [7210,10000]", + "Every day (86400-second chunks): [10,10000]" + ], + "examples": [ + { + "text": "Example: Input[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]Output[null,null,null,null,[2],[2,1],null,[4]]ExplanationTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets", + "image": null + } + ], + "follow_up": null, + "solution": "import bisect\nclass TweetCounts:\n\n def __init__(self):\n self.tweets = {}\n \n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if not tweetName in self.tweets:\n self.tweets[tweetName] = []\n index = bisect.bisect_left(self.tweets[tweetName], time)\n self.tweets[tweetName].insert(index, time)\n \n \n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n \n def find(step):\n nonlocal tweet\n result = []\n for i in range(startTime, endTime+1, step):\n result.append(bisect.bisect_right(tweet, min(endTime, i + step - 1)) - bisect.bisect_left(tweet, i))\n return result\n \n \n tweet = self.tweets[tweetName]\n if freq == \"minute\":\n return find(60)\n elif freq == \"hour\":\n return find(3600)\n else:\n return find(86400)", + "title": "1348. Tweet Counts Per Frequency", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array of events where events[i] = [startTime i , endTime i , value i ] . The i th event starts at startTime i and ends at endTime i , and if you attend this event, you will receive a value of value i . You can choose at most two non-overlapping events to attend such that the sum of their values is maximized . Return this maximum sum. Note that the start time and end time is inclusive : that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t , the next event must start at or after t + 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= events.length <= 10^5", + "events[i].length == 3", + "1 <= startTime i <= endTime i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,3,2],[4,5,2],[2,4,3]]Output:4Explanation:Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture5.png" + }, + { + "text": "Example 2: Input:events = [[1,3,2],[4,5,2],[1,5,5]]Output:5Explanation:Choose event 2 for a sum of 5.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture1.png" + }, + { + "text": "Example 3: Input:events = [[1,5,3],[1,5,1],[6,6,5]]Output:8Explanation:Choose events 0 and 2 for a sum of 3 + 5 = 8.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture3.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 92 ms (Top 45.29%) | Memory: 159.8 MB (Top 35.88%)\nclass Solution {\n public int maxTwoEvents(int[][] events) {\n Arrays.sort(events, (a, b) -> a[0] - b[0]);\n int onRight = 0, maxOne = 0, n = events.length;\n int[] rightMax = new int[n+1];\n for (int i = n - 1; i >= 0; i--) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n maxOne = Math.max(val, maxOne);\n rightMax[i] = Math.max(rightMax[i+1], val);\n }\n int two = 0;\n for (int i = 0; i < n; i++) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n int idx = binarySearch(end, events);\n if (idx < n) {\n two = Math.max(rightMax[idx] + val, two);\n }\n }\n return Math.max(two, maxOne);\n }\n\n public int binarySearch(int end, int[][] arr) {\n int left = 0, right = arr.length;\n while (left < right) {\n int mid = left + (right - left) / 2;\n if (arr[mid][0] > end) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n}", + "title": "2054. Two Best Non-Overlapping Events", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a 0-indexed 2D integer array of events where events[i] = [startTime i , endTime i , value i ] . The i th event starts at startTime i and ends at endTime i , and if you attend this event, you will receive a value of value i . You can choose at most two non-overlapping events to attend such that the sum of their values is maximized . Return this maximum sum. Note that the start time and end time is inclusive : that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t , the next event must start at or after t + 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= events.length <= 10^5", + "events[i].length == 3", + "1 <= startTime i <= endTime i <= 10^9", + "1 <= value i <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:events = [[1,3,2],[4,5,2],[2,4,3]]Output:4Explanation:Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture5.png" + }, + { + "text": "Example 2: Input:events = [[1,3,2],[4,5,2],[1,5,5]]Output:5Explanation:Choose event 2 for a sum of 5.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture1.png" + }, + { + "text": "Example 3: Input:events = [[1,5,3],[1,5,1],[6,6,5]]Output:8Explanation:Choose events 0 and 2 for a sum of 3 + 5 = 8.", + "image": "https://assets.leetcode.com/uploads/2021/09/21/picture3.png" + } + ], + "follow_up": null, + "solution": "class Solution:\ndef maxTwoEvents(self, events: List[List[int]]) -> int:\n \n events.sort()\n heap = []\n res2,res1 = 0,0\n for s,e,p in events:\n while heap and heap[0][0] Integer.compare(c2[1] - c2[0], c1[1] - c1[0]));// biggest to smallest\n int minCost = 0; \n int n = costs.length;\n for (int i = 0; i < n; i++) {\n minCost += i < n/2? costs[i][0] : costs[i][1];//First half -> A; Last half -> B 259 + 184 + 577 + 54 + 667 + 118\n }\n return minCost;\n }\n}\n", + "title": "1029. Two City Scheduling", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCost i , bCost i ] , the cost of flying the i th person to city a is aCost i , and the cost of flying the i th person to city b is bCost i . Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 * n == costs.length", + "2 <= costs.length <= 100", + "costs.length is even.", + "1 <= aCost i , bCost i <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:costs = [[10,20],[30,200],[400,50],[30,20]]Output:110Explanation:The first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.", + "image": null + }, + { + "text": "Example 2: Input:costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]Output:1859", + "image": null + }, + { + "text": "Example 3: Input:costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]Output:3086", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n n = len(costs)\n m = n // 2\n \n @lru_cache(None)\n def dfs(cur, a):\n\t\t\t# cur is the current user index\n\t\t\t# `a` is the number of people travel to city `a`\n\t\t\t\n if cur == n:\n return 0\n \n\t\t\t# people to b city\n b = cur - a\n ans = float('inf')\n \n\t\t\t# the number of people to `a` city number did not reach to limit, \n\t\t\t# then current user can trval to city `a`\n\t\t\t\n if a < m:\n ans = min(dfs(cur+1, a+1)+costs[cur][0], ans)\n \n\t\t\t# the number of people to `b` city number did not reach to limit\n\t\t\t# then current user can trval to city `b`\n if b < m:\n ans = min(dfs(cur+1, a)+costs[cur][1], ans)\n \n return ans\n \n return dfs(0, 0)\n", + "title": "1029. Two City Scheduling", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n , where colors[i] represents the color of the i th house. Return the maximum distance between two houses with different colors . The distance between the i th and j th houses is abs(i - j) , where abs(x) is the absolute value of x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == colors.length", + "2 <= n <= 100", + "0 <= colors[i] <= 100", + "Test data are generated such that at least two houses have different colors." + ], + "examples": [ + { + "text": "Example 1: Input:colors = [1,1,1,6,1,1,1]Output:3Explanation:In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg1.png" + }, + { + "text": "Example 2: Input:colors = [1,8,3,8,3]Output:4Explanation:In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg2.png" + }, + { + "text": "Example 3: Input:colors = [0,1]Output:1Explanation:The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 42.7 MB (Top 13.21%)\nclass Solution {\n public int maxDistance(int[] colors) {\n int l = 0, r = colors.length-1;\n while(colors[colors.length-1] == colors[l]) l++;\n while(colors[0] == colors[r]) r--;\n return Math.max(r, colors.length - 1 - l);\n }\n}", + "title": "2078. Two Furthest Houses With Different Colors", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n , where colors[i] represents the color of the i th house. Return the maximum distance between two houses with different colors . The distance between the i th and j th houses is abs(i - j) , where abs(x) is the absolute value of x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == colors.length", + "2 <= n <= 100", + "0 <= colors[i] <= 100", + "Test data are generated such that at least two houses have different colors." + ], + "examples": [ + { + "text": "Example 1: Input:colors = [1,1,1,6,1,1,1]Output:3Explanation:In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg1.png" + }, + { + "text": "Example 2: Input:colors = [1,8,3,8,3]Output:4Explanation:In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.", + "image": "https://assets.leetcode.com/uploads/2021/10/31/eg2.png" + }, + { + "text": "Example 3: Input:colors = [0,1]Output:1Explanation:The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 33 ms (Top 98.18%) | Memory: 17.40 MB (Top 5.01%)\n\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n\t\t#first pass\n l, r = 0, len(colors)-1\n dist = 0\n \n while r > l:\n if colors[r] != colors[l]:\n dist = r-l\n\t\t\t\t#slight performance increase, break out if you find it \n\t\t\t\t#because it can't get bigger than this\n break \n r -= 1\n\t\t\t\n #second pass, backwards\n l, r = 0, len(colors)-1\n while r > l:\n if colors[r] != colors[l]:\n dist = max(dist, r-l)\n break\n l += 1\n \n return dist\n\t\n", + "title": "2078. Two Furthest Houses With Different Colors", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length, nums3.length <= 100", + "1 <= nums1[i], nums2[j], nums3[k] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]Output:[3,2]Explanation:The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]Output:[2,3,1]Explanation:The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]Output:[]Explanation:No value is present in at least two arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 97.56%) | Memory: 46.7 MB (Top 58.76%)\nclass Solution {\n public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {\n int[] bits = new int[101];\n for (int n : nums1) bits[n] |= 0b110;\n for (int n : nums2) bits[n] |= 0b101;\n for (int n : nums3) bits[n] |= 0b011;\n List result = new ArrayList();\n for (int i = bits.length - 1; i > 0; i--)\n if (bits[i] == 0b111)\n result.add(i);\n return result;\n }\n}", + "title": "2032. Two Out of Three", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length, nums3.length <= 100", + "1 <= nums1[i], nums2[j], nums3[k] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]Output:[3,2]Explanation:The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]Output:[2,3,1]Explanation:The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]Output:[]Explanation:No value is present in at least two arrays.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 93.8%) | Memory: 16.30 MB (Top 83.7%)\n\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n output = []\n for i in nums1:\n if i in nums2 or i in nums3:\n if i not in output:\n output.append(i)\n for j in nums2:\n if j in nums3 or j in nums1:\n if j not in output:\n output.append(j)\n return output", + "title": "2032. Two Out of Three", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9Output:[0,1]Explanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6Output:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6Output:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] twoSum(int[] nums, int target) {\n int[] answer = new int[2];\n\t\t// Two for loops for selecting two numbers and check sum equal to target or not\n\t\t\n for(int i = 0; i < nums.length; i++){\n for(int j = i+1; j < nums.length; j++) {\n\t\t\t // j = i + 1; no need to check back elements it covers in i;\n if(nums[i] + nums[j] == target) {\n\t\t\t\t// Check sum == target or not\n answer[0] = i;\n answer[1] = j;\n return answer;\n }\n } \n }\n return null;\n }\n}\n", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9Output:[0,1]Explanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6Output:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6Output:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "// Runtime: 2571 ms (Top 18.27%) | Memory: 17.10 MB (Top 86.21%)\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n n = len(nums)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n return [] # No solution found\n\n", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "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 , added 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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:numbers = [2,7,11,15], target = 9Output:[1,2]Explanation:The sum of 2 and 7 is 9. Therefore, index1= 1, index2= 2. We return [1, 2].", + "image": null + }, + { + "text": "Example 2: Input:numbers = [2,3,4], target = 6Output:[1,3]Explanation:The sum of 2 and 4 is 6. Therefore index1= 1, index2= 3. We return [1, 3].", + "image": null + }, + { + "text": "Example 3: Input:numbers = [-1,0], target = -1Output:[1,2]Explanation:The sum of -1 and 0 is -1. Therefore index1= 1, index2= 2. We return [1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n s=0\n e=len(numbers)-1\n while s set = new HashSet<>();\n public boolean findTarget(TreeNode root, int k) {\n if(root == null){\n return false;\n }\n if(set.contains(k-root.val)){\n return true;\n }\n set.add(root.val);\n return findTarget(root.left,k) || findTarget(root.right,k);\n }\n}\n", + "title": "653. Two Sum IV - Input is a BST", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given the root of a Binary Search Tree and a target number k , return true if there exist two elements in the BST such that their sum is equal to the given target . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^4 <= Node.val <= 10^4", + "root is guaranteed to be a valid binary search tree.", + "-10^5 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], k = 9Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], k = 28Output:false", + "image": "https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg" + } + ], + "follow_up": null, + "solution": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n def inorder(root,l):\n if root:\n inorder(root.left,l)\n l.append(root.val)\n inorder(root.right,l)\n l = []\n inorder(root,l)\n left,right=0,len(l)-1\n while left!=right:\n sum = l[left] + l[right]\n if sum > k :\n right -=1\n elif sum bool:\n if n == 0:\n return False\n res=[2, 3, 5]\n while n!= 1:\n for i in res:\n if n%i==0:\n n=n//i\n break\n else:\n return False\n return True", + "title": "263. Ugly Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "An ugly number is a positive integer whose prime factors are limited to 2 , 3 , and 5 . Given an integer n , return the n th ugly number . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1690" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:12Explanation:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1Explanation:1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 41.12%) | Memory: 41.5 MB (Top 87.73%)\n// Ugly number II\n// https://leetcode.com/problems/ugly-number-ii/\n\nclass Solution {\n public int nthUglyNumber(int n) {\n int[] dp = new int[n];\n dp[0] = 1;\n int i2 = 0, i3 = 0, i5 = 0;\n for (int i = 1; i < n; i++) {\n dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5));\n if (dp[i] == dp[i2] * 2) i2++;\n if (dp[i] == dp[i3] * 3) i3++;\n if (dp[i] == dp[i5] * 5) i5++;\n }\n return dp[n - 1];\n }\n}", + "title": "264. Ugly Number II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An ugly number is a positive integer whose prime factors are limited to 2 , 3 , and 5 . Given an integer n , return the n th ugly number . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1690" + ], + "examples": [ + { + "text": "Example 1: Input:n = 10Output:12Explanation:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:1Explanation:1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 354 ms (Top 28.01%) | Memory: 13.9 MB (Top 55.93%)\nimport heapq\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n h1, h2, h3 = [], [], []\n heapq.heappush(h1, 1)\n heapq.heappush(h2, 1)\n heapq.heappush(h3, 1)\n ugly_number = 1\n last_ugly_number = 1\n count = 1\n while count < n:\n if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:\n # pop from h1\n x = heapq.heappop(h1)\n ugly_number = 2 * x\n if ugly_number == last_ugly_number:\n # do nothing\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:\n # pop from h2\n x = heapq.heappop(h2)\n ugly_number = 3 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n else:\n # pop from h3\n x = heapq.heappop(h3)\n ugly_number = 5 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n return last_ugly_number", + "title": "264. Ugly Number II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "An ugly number is a positive integer that is divisible by a , b , or c . Given four integers n , a , b , and c , return the n th ugly number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n, a, b, c <= 10^9", + "1 <= a * b * c <= 10^18", + "It is guaranteed that the result will be in range [1, 2 * 10^9 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, a = 2, b = 3, c = 5Output:4Explanation:The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rdis 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3, c = 4Output:6Explanation:The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4this 6.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, a = 2, b = 11, c = 13Output:10Explanation:The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5this 10.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 40.60 MB (Top 12.2%)\n\nclass Solution {\n public int nthUglyNumber(int n, int a, int b, int c) {\n int left = 1;\n int right = Integer.MAX_VALUE;\n int count = 0;\n while (left < right) {\n int middle = left + (right - left) / 2;\n if (isUgly(middle, a, b, c, n)) {\n right = middle;\n }\n else\n left = middle + 1;\n }\n return left;\n }\n public boolean isUgly(long middle, long a, long b, long c, long n) {\n return (int) (middle/a + middle/b + middle/c - middle/lcm(a, b) - middle/lcm(b, c) - middle/lcm(c, a) + middle/lcm(a, lcm(b, c))) >= n;\n }\n public long gcd(long a, long b) {\n if (a == 0)\n return b;\n else return gcd(b%a, a);\n }\n public long lcm(long a, long b) {\n return a * b / (gcd(a, b)); \n }\n}\n", + "title": "1201. Ugly Number III", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "An ugly number is a positive integer that is divisible by a , b , or c . Given four integers n , a , b , and c , return the n th ugly number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= n, a, b, c <= 10^9", + "1 <= a * b * c <= 10^18", + "It is guaranteed that the result will be in range [1, 2 * 10^9 ] ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 3, a = 2, b = 3, c = 5Output:4Explanation:The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rdis 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, a = 2, b = 3, c = 4Output:6Explanation:The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4this 6.", + "image": null + }, + { + "text": "Example 3: Input:n = 5, a = 2, b = 11, c = 13Output:10Explanation:The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5this 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n times = [1,1,1]\n smallest = inf\n while n != 0:\n smallest = min ( times[0]*a,times[1]*b,times[2]*c)\n if times[0]*a == smallest: times[0] += 1\n if times[1]*b == smallest: times[1] += 1\n if times[2]*c == smallest: times[2] += 1\n n -= 1\n return smallest\n", + "title": "1201. Ugly Number III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences s1 and s2 , return a list of all the uncommon words . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 200", + "s1 and s2 consist of lowercase English letters and spaces.", + "s1 and s2 do not have leading or trailing spaces.", + "All the words in s1 and s2 are separated by a single space." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"this apple is sweet\", s2 = \"this apple is sour\"Output:[\"sweet\",\"sour\"]", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"apple apple\", s2 = \"banana\"Output:[\"banana\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String[] uncommonFromSentences(String s1, String s2) {\n List list=new LinkedList<>();\n Map map=new HashMap<>();\n String[] arr1=s1.split(\" \");\n String[] arr2=s2.split(\" \");\n for(int i=0;i entry:map.entrySet()){\n if(entry.getValue()==1)\n list.add(entry.getKey());\n }\n String[] res=new String[list.size()];\n for(int i=0;i List[str]:\n x = dict(Counter(s1.split() + s2.split()))\n ans = []\n for key in x:\n if x[key] == 1:\n ans.append(key)\n \n return ans", + "title": "884. Uncommon Words from Two Sentences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 . We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums1[i] == nums2[j] , and", + "the line we draw does not intersect any other connecting (non-horizontal) line." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,4,2], nums2 = [1,2,4]Output:2Explanation:We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.", + "image": "https://assets.leetcode.com/uploads/2019/04/26/142.png" + }, + { + "text": "Example 2: Input:nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]Output:3", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxUncrossedLines(int[] nums1, int[] nums2) {\n int m = nums1.length;\n int n = nums2.length;\n int[][] dp = new int[m + 1][n + 1];\n for(int i = 1; i <= m; i ++){\n for(int j = 1; j <= n; j ++){\n if(nums1[i - 1] == nums2[j - 1])\n dp[i][j] = dp[i - 1][j - 1] + 1;\n else\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n return dp[m][n];\n }\n}\n", + "title": "1035. Uncrossed Lines", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two integer arrays nums1 and nums2 . We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums1[i] == nums2[j] , and", + "the line we draw does not intersect any other connecting (non-horizontal) line." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,4,2], nums2 = [1,2,4]Output:2Explanation:We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.", + "image": "https://assets.leetcode.com/uploads/2019/04/26/142.png" + }, + { + "text": "Example 2: Input:nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]Output:3", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n \n @lru_cache(None)\n def dp(a,b):\n if a>=len(nums1) or b>=len(nums2): return 0\n if nums1[a]==nums2[b]: return 1+dp(a+1,b+1)\n else: return max(dp(a+1,b),dp(a,b+1))\n \n return dp(0,0)\n", + "title": "1035. Uncrossed Lines", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer n , return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 19" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:5", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numTrees(int n) {\n // Create 'sol' array of length n+1...\n int[] sol = new int[n+1];\n // The value of the first index will be 1.\n sol[0] = 1;\n // Run a loop from 1 to n+1...\n for(int i = 1; i <= n; i++) {\n // Within the above loop, run a nested loop from 0 to i...\n for(int j = 0; j < i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n }\n}\n", + "title": "96. Unique Binary Search Trees", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer n , return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 19" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:5", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 58 ms (Top 20.54%) | Memory: 13.9 MB (Top 13.32%)\nclass Solution(object):\n def numTrees(self, n):\n if n == 0 or n == 1:\n return 1\n # Create 'sol' array of length n+1...\n sol = [0] * (n+1)\n # The value of the first index will be 1.\n sol[0] = 1\n # Run a loop from 1 to n+1...\n for i in range(1, n+1):\n # Within the above loop, run a nested loop from 0 to i...\n for j in range(i):\n # Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1]\n # Return the value of the nth index of the array to get the solution...\n return sol[n]", + "title": "96. Unique Binary Search Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return all the structurally unique BST' s (binary search trees), which has exactly n nodes of unique values from 1 to n . Return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List generateTrees(int n) {\n return helper(1,n);\n }\n \n public List helper(int lo, int hi){\n List res=new ArrayList<>();\n if(lo>hi){\n res.add(null);\n return res;\n }\n \n \n for(int i=lo;i<=hi;i++){\n List left=helper(lo,i-1);\n List right=helper(i+1,hi);\n \n for(TreeNode l:left){\n for(TreeNode r:right){\n TreeNode head=new TreeNode(i);\n head.left=l;\n head.right=r;\n \n res.add(head);\n }\n }\n }\n \n return res;\n }\n}\n", + "title": "95. Unique Binary Search Trees II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer n , return all the structurally unique BST' s (binary search trees), which has exactly n nodes of unique values from 1 to n . Return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]", + "image": "https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 73 ms (Top 74.11%) | Memory: 15.7 MB (Top 42.55%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n # define a sorted list of the numbers, for each num in that list , leftvalues\n# are left tree and right val are rightree, then for each number create a tree\n# assign the left and right to that root and append the root to the ans\n nums = list(range(1,n+1))\n def dfs(nums):\n if not nums:\n return [None]\n ans = []\n for i in range(len(nums)):\n leftTrees = dfs(nums[:i])\n rightTrees = dfs(nums[i+1:])\n\n for l in leftTrees:\n for r in rightTrees:\n root = TreeNode(nums[i])\n root.left = l\n root.right = r\n ans.append(root)\n return ans\n\n return dfs(nums)\n", + "title": "95. Unique Binary Search Trees II", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Every valid email consists of a local name and a domain name , separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+' . If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names . If you add a plus '+' in the local name , everything after the first plus sign will be ignored . This allows certain emails to be filtered. Note that this rule does not apply to domain names . It is possible to use both of these rules at the same time. Given an array of strings emails where we send one email to each emails[i] , return the number of different addresses that actually receive mails . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, in \"alice@leetcode.com\" , \"alice\" is the local name , and \"leetcode.com\" is the domain name ." + ], + "examples": [ + { + "text": "Example 1: Input:emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]Output:2Explanation:\"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.", + "image": null + }, + { + "text": "Example 2: Input:emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 27 ms (Top 57.45%) | Memory: 46.9 MB (Top 71.39%)\nclass Solution {\n public int numUniqueEmails(String[] emails) {\n\n Set finalEmails = new HashSet<>();\n for(String email: emails){\n StringBuilder name = new StringBuilder();\n boolean ignore = false;\n for(int i=0;i int:\n def ets(email):\n s, domain = email[:email.index('@')], email[email.index('@'):]\n s = s.replace(\".\", \"\")\n s = s[:s.index('+')] if '+' in s else s\n return s+domain\n dict = {}\n for i in emails:\n dict[ets(i)] = 1\n return len(dict)\n", + "title": "929. Unique Email Addresses", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"Output:3Explanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"Output:0Explanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"Output:4Explanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int countPalindromicSubsequence(String s) {\n \n int n = s.length();\n \n char[] chArr = s.toCharArray();\n \n int[] firstOcc = new int[26];\n int[] lastOcc = new int[26];\n \n Arrays.fill(firstOcc, -1);\n Arrays.fill(lastOcc, -1);\n \n for(int i = 0; i < n; i++){\n \n char ch = chArr[i];\n \n if(firstOcc[ch - 'a'] == -1){\n firstOcc[ch - 'a'] = i;\n }\n \n lastOcc[ch - 'a'] = i;\n }\n \n int ans = 0, count = 0;\n \n boolean[] visited;\n \n\t\t// check for each character ( start or end of palindrome )\n for(int i = 0; i < 26; i++){\n \n int si = firstOcc[i]; // si - starting index\n int ei = lastOcc[i]; // ei - ending index\n \n visited = new boolean[26];\n \n count = 0;\n \n\t\t\t// check for unique charcters ( middle of palindrome )\n for(int j = si + 1; j < ei; j++){\n \n if(!visited[chArr[j] - 'a']){\n visited[chArr[j] - 'a'] = true;\n count++;\n }\n }\n \n ans += count;\n }\n \n return ans;\n }\n}\n", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"Output:3Explanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"Output:0Explanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"Output:4Explanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countPalindromicSubsequence(self, s):\n d=defaultdict(list)\n for i,c in enumerate(s):\n d[c].append(i)\n ans=0\n for el in d:\n if len(d[el])<2:\n continue\n a=d[el][0]\n b=d[el][-1]\n ans+=len(set(s[a+1:b]))\n return(ans)\n", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s , return the number of unique palindromes of length three that are a subsequence of s . Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once . A palindrome is a string that reads the same forwards and backwards. 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. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \" a b c d e \" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aabca\"Output:3Explanation:The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")", + "image": null + }, + { + "text": "Example 2: Input:s = \"adc\"Output:0Explanation:There are no palindromic subsequences of length 3 in \"adc\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"bbcbaba\"Output:4Explanation:The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution(object):\n def countPalindromicSubsequence(self, s):\n d=defaultdict(list)\n for i,c in enumerate(s):\n d[c].append(i)\n ans=0\n for el in d:\n if len(d[el])<2:\n continue\n a=d[el][0]\n b=d[el][-1]\n ans+=len(set(s[a+1:b]))\n return(ans)\n\t\t", + "title": "1930. Unique Length-3 Palindromic Subsequences", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: For convenience, the full table for the 26 letters of the English alphabet is given below: Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. Return the number of different transformations among all words we have . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'a' maps to \".-\" ,", + "'b' maps to \"-...\" ,", + "'c' maps to \"-.-.\" , and so on." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"gin\",\"zen\",\"gig\",\"msg\"]Output:2Explanation:The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\"]Output:1", + "image": null + }, + { + "text": "[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniqueMorseRepresentations(String[] words) {\n HashSet set = new HashSet<>();\n String[] morse = new String[]{\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n \n for (int i = 0; i < words.length; ++i) {\n String temp = \"\";\n for (int j = 0; j < words[i].length(); ++j) {\n temp += morse[(int)words[i].charAt(j)-'a'];\n }\n set.add(temp);\n }\n return set.size();\n }\n}\n", + "title": "804. Unique Morse Code Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: For convenience, the full table for the 26 letters of the English alphabet is given below: Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. Return the number of different transformations among all words we have . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'a' maps to \".-\" ,", + "'b' maps to \"-...\" ,", + "'c' maps to \"-.-.\" , and so on." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"gin\",\"zen\",\"gig\",\"msg\"]Output:2Explanation:The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".", + "image": null + }, + { + "text": "Example 2: Input:words = [\"a\"]Output:1", + "image": null + }, + { + "text": "[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 43 ms (Top 50.2%) | Memory: 17.50 MB (Top 5.12%)\n\nclass Solution:\n def uniqueMorseRepresentations(self, words: List[str]) -> int:\n \n # create a dictionary for morse code (You can just copy & paste it! ^.^)\n ENG_to_MORSE = { \n 'a':\".-\", 'b':\"-...\", 'c':\"-.-.\", 'd':\"-..\", 'e':\".\",\n 'f':\"..-.\", 'g':\"--.\", 'h':\"....\", 'i':\"..\", 'j':\".---\",\n 'k':\"-.-\", 'l':\".-..\", 'm':\"--\", 'n':\"-.\", 'o':\"---\",\n 'p':\".--.\", 'q':\"--.-\", 'r':\".-.\", 's':\"...\", 't':\"-\",\n 'u':\"..-\", 'v':\"...-\", 'w':\".--\", 'x':\"-..-\", 'y':\"-.--\", 'z':\"--..\",\n }\n \n cnt = {} # dictionary for different transformations\n \n for word in words: # loop through every word\n \n tmp = \"\"\n \n for c in word: # loop through every character\n tmp += ENG_to_MORSE[c] # convert the word to morse code\n \n if tmp not in cnt:\n cnt[tmp] = 0\n else:\n cnt[tmp] += 1\n\n return len(cnt) # return how many different elements in cnt\n", + "title": "804. Unique Morse Code Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]Output:trueExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean uniqueOccurrences(int[] arr) {\n Arrays.sort(arr);\n HashSet set = new HashSet<>();\n\n int c = 1;\n for(int i = 1; i < arr.length; i++)\n {\n if(arr[i] == arr[i-1]) c++;\n\n else\n {\n if(set.contains(c)) return false;\n\n set.add(c);\n\n c = 1;\n }\n }\n\n if(set.contains(c)) return false;\n\n return true;\n }\n}", + "title": "1207. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique , or false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]Output:trueExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n\t\t# defining dictionary\n occ = dict()\n \n\t\t# adding elements with their counts in dictionary\n for element in arr:\n if element not in occ:\n occ[element] = 0\n else:\n occ[element] += 1\n \n\t\t# list of count of elements\n values = list(occ.values())\n\t\t# Unique count\n unique = set(values)\n \n if len(values) == len(unique):\n return True\n else:\n return False\n", + "title": "1207. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7Output:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2Output:3Explanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePaths(int m, int n) {\n int[][] dp = new int[m][n];\n \n for(int i = 0; i < m; i ++) {\n for(int j = 0; j < n; j ++) {\n dp[i][j] = -1;\n }\n }\n \n return helper(m, 0, n, 0, dp);\n }\n \n private int helper(int m, int i, int n, int j, int[][] dp) {\n if(i == m || j == n) {\n return 0;\n }\n \n if(i == m-1 && j == n-1) {\n dp[i][j] = 1;\n }\n \n if(dp[i][j] == -1) {\n dp[i][j] = helper(m, i+1, n, j, dp) + helper(m, i, n, j+1, dp);\n }\n \n return dp[i][j];\n }\n}", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7Output:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2Output:3Explanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 39 ms (Top 53.95%) | Memory: 17.30 MB (Top 9.72%)\n\nclass Solution:\n def uniquePaths(self, m, n):\n dp = [[1]*n for i in range(m)]\n for i, j in product(range(1, m), range(1, n)):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n return dp[-1][-1]\n", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]Output:2Explanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.0%) | Memory: 41.40 MB (Top 60.59%)\n\nclass Solution {\n public int uniquePathsWithObstacles(int[][] OG) {\n if (OG[0][0] == 1) return 0;\n int m = OG.length, n = OG[0].length;\n int[][] dp = new int[m][n];\n dp[0][0] = 1;\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n if (OG[i][j] == 1 || (i == 0 && j == 0)) continue;\n else dp[i][j] = (i > 0 ? dp[i-1][j] : 0) + (j > 0 ? dp[i][j-1] : 0);\n return dp[m-1][n-1];\n }\n}\n", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]Output:2Explanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 75 ms (Top 36.49%) | Memory: 14 MB (Top 43.32%)\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n def valid(r,c,matrix):\n return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0])\n\n dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))]\n dp[0][0] = 1 ^ obstacleGrid[0][0]\n\n for r in range(len(obstacleGrid)):\n for c in range(len(obstacleGrid[0])):\n if obstacleGrid[r][c] != 1:\n if valid(r-1, c, dp) and obstacleGrid[r-1][c] != 1:\n dp[r][c] += dp[r-1][c]\n if valid(r, c-1, dp) and obstacleGrid[r][c-1] != 1:\n dp[r][c] += dp[r][c-1]\n\n return dp[-1][-1]", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an m x n integer array grid where grid[i][j] could be: Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 representing the starting square. There is exactly one starting square.", + "2 representing the ending square. There is exactly one ending square.", + "0 representing empty squares we can walk over.", + "-1 representing obstacles that we cannot walk over." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]Output:2Explanation:We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]Output:4Explanation:We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,1],[2,0]]Output:0Explanation:There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 41.86%) | Memory: 42.7 MB (Top 13.82%)\nclass Solution {\n int walk = 0;\n public int uniquePathsIII(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0) {\n walk++;\n }\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n return ways(grid, i, j, m, n, 0);\n }\n }\n }\n return 0;\n }\n public int ways(int[][] grid, int cr, int cc, int m, int n, int count) {\n if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) {\n return 0;\n }\n if (grid[cr][cc] == 2) {\n if (count - 1 == walk) return 1;\n return 0;\n }\n grid[cr][cc] = -1;\n int ans = 0;\n int[] r = {0, 1, 0, -1};\n int[] c = {1, 0, -1, 0};\n for (int i = 0; i < 4; i++) {\n ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1);\n }\n grid[cr][cc] = 0;\n return ans;\n }\n}", + "title": "980. Unique Paths III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an m x n integer array grid where grid[i][j] could be: Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 representing the starting square. There is exactly one starting square.", + "2 representing the ending square. There is exactly one ending square.", + "0 representing empty squares we can walk over.", + "-1 representing obstacles that we cannot walk over." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]Output:2Explanation:We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]Output:4Explanation:We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg" + }, + { + "text": "Example 3: Input:grid = [[0,1],[2,0]]Output:0Explanation:There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.", + "image": "https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ans, empty = 0, 1\n \n def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None:\n if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1:\n return\n nonlocal ans\n if grid[row][col] == 2:\n if empty == count:\n ans += 1\n return\n if (row, col) not in visited:\n visited.add((row, col))\n dfs(grid, row + 1, col, count + 1, visited)\n dfs(grid, row - 1, col, count + 1, visited)\n dfs(grid, row, col + 1, count + 1, visited)\n dfs(grid, row, col - 1, count + 1, visited)\n visited.remove((row, col))\n \n row, col = 0, 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n row, col = i, j\n elif grid[i][j] == 0:\n empty += 1\n dfs(grid, row, col, 0, set())\n return ans\n", + "title": "980. Unique Paths III", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\" , so s will look like this: Given a string p , return the number of unique non-empty substrings of p are present in s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\" ." + ], + "examples": [ + { + "text": "Example 1: Input:p = \"a\"Output:1\nExplanation: Only the substring \"a\" of p is in s.", + "image": null + }, + { + "text": "Example 2: Input:p = \"cac\"Output:2Explanation:There are two substrings (\"a\", \"c\") of p in s.", + "image": null + }, + { + "text": "Example 3: Input:p = \"zab\"Output:6Explanation:There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.", + "image": null + } + ], + "follow_up": null, + "solution": "// One Pass Counting Solution\n// 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring.\n// 2. counts to track the longest continuos subtring starting with current character.\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int findSubstringInWraproundString(String p) {\n final int N = p.length();\n int res = 0, len = 1;\n int[] counts = new int[26];\n for (int i = 0; i < N; i++) {\n char ch = p.charAt(i);\n if (i > 0 && (ch - p.charAt(i-1) == 1 || ch - p.charAt(i-1) == -25)) {\n len++;\n } else {\n len = 1;\n }\n int idx = ch - 'a';\n counts[idx] = Math.max(counts[idx], len);\n }\n for (int count : counts) {\n res += count;\n }\n return res;\n }\n}\n", + "title": "467. Unique Substrings in Wraparound String", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\" , so s will look like this: Given a string p , return the number of unique non-empty substrings of p are present in s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\" ." + ], + "examples": [ + { + "text": "Example 1: Input:p = \"a\"Output:1\nExplanation: Only the substring \"a\" of p is in s.", + "image": null + }, + { + "text": "Example 2: Input:p = \"cac\"Output:2Explanation:There are two substrings (\"a\", \"c\") of p in s.", + "image": null + }, + { + "text": "Example 3: Input:p = \"zab\"Output:6Explanation:There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.", + "image": null + } + ], + "follow_up": null, + "solution": "def get_next(char):\n x = ord(char)-ord('a')\n x = (x+1)%26\n return chr(ord('a') + x)\nclass Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n i = 0\n n = len(p)\n map_ = collections.defaultdict(int)\n while i bool:\n val1 = root.val\n self.tracker = False\n def dfs(root,val1):\n if not root:\n return \n if root.val!=val1:\n self.tracker=True\n dfs(root.left,val1)\n dfs(root.right,val1)\n return \n dfs(root,val1)\n \n if self.tracker == False:\n return True\n return False\n", + "title": "965. Univalued Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: This is how the UTF-8 encoding would work: x denotes a bit in the binary form of a byte that may be either 0 or 1 . Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= data.length <= 2 * 10^4", + "0 <= data[i] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:data = [197,130,1]Output:trueExplanation:data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.", + "image": null + }, + { + "text": "Example 2: Input:data = [235,140,4]Output:falseExplanation:data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.", + "image": null + }, + { + "text": "Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 100.00%) | Memory: 48.5 MB (Top 26.95%)\nclass Solution {\n public boolean validUtf8(int[] data) {\n return help(data,0);\n }\n\n public boolean help(int[] data,int index) {\n int n=data.length-index;\n if(n==0){\n return true;\n }\n int c0=count(data[index]);\n if(c0<0||c0>n){\n return false;\n }\n for(int i=index+1;i>3)==0b11110){\n return 4;\n }else if((a>>4)==0b1110){\n return 3;\n }else if((a>>5)==0b110){\n return 2;\n }else if((a>>7)==0){\n return 1;\n }\n return -1;\n }\n}", + "title": "393. UTF-8 Validation", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: This is how the UTF-8 encoding would work: x denotes a bit in the binary form of a byte that may be either 0 or 1 . Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= data.length <= 2 * 10^4", + "0 <= data[i] <= 255" + ], + "examples": [ + { + "text": "Example 1: Input:data = [197,130,1]Output:trueExplanation:data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.", + "image": null + }, + { + "text": "Example 2: Input:data = [235,140,4]Output:falseExplanation:data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.", + "image": null + }, + { + "text": "Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validUtf8(self, data: List[int]) -> bool:\n # Keep track of how many continuation bytes are left\n\t\t# Start at 0 since we are not expecting any continuation bytes at the beginning.\n cont_bytes_left = 0\n for byte in data:\n if cont_bytes_left == 0:\n\t\t\t # If we don't expect any continuation bytes\n\t\t\t # then there are 4 valid case for the current byte\n # byte >> 5 gives us the first 3 bits (8 bits - 5 = 3).\n if byte >> 5 == 0b110:\n\t\t\t\t # After seeing a byte that starts with 110,\n\t\t\t\t\t# we expect to see one continuation byte\n cont_bytes_left = 1\n elif byte >> 4 == 0b1110:\n cont_bytes_left = 2\n elif byte >> 3 == 0b11110:\n cont_bytes_left = 3\n # finally if the first bit isn't 0 then it's invalid\n elif byte >> 7 != 0:\n return False\n else:\n\t\t\t # If we are expecting a continuation byte there is only one valid case.\n # It's invalid if the continuation byte doesn't start with 10\n if byte >> 6 != 0b10:\n return False\n cont_bytes_left -= 1\n \n\t\t# Only valid if we aren't expecting any more continuation bytes\n return cont_bytes_left == 0\n", + "title": "393. UTF-8 Validation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and t , return true if t is an anagram of s , and false otherwise . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"anagram\", t = \"nagaram\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\", t = \"car\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 73.70%) | Memory: 42.2 MB (Top 97.84%)\nclass Solution {\n public boolean isAnagram(String s, String t) {\n if (s.length() != t.length()) return false;\n int[] haha1 = new int[26];//26 because input contains of only lower english letters\n int[] haha2 = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n haha1[(int)s.charAt(i)-97] += 1;//omitting 97 because 'a' is 97, it will be 0 now\n haha2[(int)t.charAt(i)-97] += 1;\n }\n for (int i = 0; i < haha1.length; ++i) {\n if (haha1[i] != haha2[i]) return false;\n }\n return true;\n }\n}", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two strings s and t , return true if t is an anagram of s , and false otherwise . An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"anagram\", t = \"nagaram\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"rat\", t = \"car\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 86 ms (Top 42.25%) | Memory: 14.4 MB (Top 67.11%)\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n return Counter(s) == Counter(t)\n", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [start i , end i ] . An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length , we have end i-1 == start i . Return any valid arrangement of pairs . Note: The inputs will be generated such that there exists a valid arrangement of pairs . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pairs.length <= 10^5", + "pairs[i].length == 2", + "0 <= start i , end i <= 10^9", + "start i != end i", + "No two pairs are exactly the same.", + "There exists a valid arrangement of pairs ." + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[5,1],[4,5],[11,9],[9,4]]Output:[[11,9],[9,4],[4,5],[5,1]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 9 == 9 = start1end1= 4 == 4 = start2end2= 5 == 5 = start3", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,3],[3,2],[2,1]]Output:[[1,3],[3,2],[2,1]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 3 == 3 = start1end1= 2 == 2 = start2The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.", + "image": null + }, + { + "text": "Example 3: Input:pairs = [[1,2],[1,3],[2,1]]Output:[[1,2],[2,1],[1,3]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 2 == 2 = start1end1= 1 == 1 = start2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] validArrangement(int[][] pairs) {\n int n = pairs.length;\n \n int[][] ans = new int[n][2];\n for (int[] a : ans) {\n a[0] = -1;\n a[1] = -1;\n }\n \n Map outdegree = new HashMap<>();\n Map> out = new HashMap<>();\n \n for (int[] pair : pairs) {\n outdegree.put(pair[0], outdegree.getOrDefault(pair[0], 0) + 1);\n outdegree.put(pair[1], outdegree.getOrDefault(pair[1], 0) - 1);\n \n out.computeIfAbsent(pair[0], k -> new ArrayDeque<>());\n out.computeIfAbsent(pair[1], k -> new ArrayDeque<>());\n \n out.get(pair[0]).addLast(pair[1]);\n }\n \n for (Map.Entry entry : outdegree.entrySet()) {\n if (entry.getValue() == 1) ans[0][0] = entry.getKey();\n if (entry.getValue() == -1) ans[n - 1][1] = entry.getKey();\n }\n \n if (ans[0][0] == -1) {\n ans[0][0] = pairs[0][0];\n ans[n - 1][1] = pairs[0][0];\n }\n \n int i = 0;\n int j = n - 1;\n while (i < j) {\n int from = ans[i][0];\n \n Deque toList = out.get(from);\n \n if (toList.size() == 0) {\n ans[j][0] = ans[--i][0];\n ans[--j][1] = ans[j + 1][0];\n } else {\n ans[i++][1] = toList.removeLast();\n ans[i][0] = ans[i - 1][1];\n }\n }\n \n return ans;\n }\n}\n", + "title": "2097. Valid Arrangement of Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [start i , end i ] . An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length , we have end i-1 == start i . Return any valid arrangement of pairs . Note: The inputs will be generated such that there exists a valid arrangement of pairs . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pairs.length <= 10^5", + "pairs[i].length == 2", + "0 <= start i , end i <= 10^9", + "start i != end i", + "No two pairs are exactly the same.", + "There exists a valid arrangement of pairs ." + ], + "examples": [ + { + "text": "Example 1: Input:pairs = [[5,1],[4,5],[11,9],[9,4]]Output:[[11,9],[9,4],[4,5],[5,1]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 9 == 9 = start1end1= 4 == 4 = start2end2= 5 == 5 = start3", + "image": null + }, + { + "text": "Example 2: Input:pairs = [[1,3],[3,2],[2,1]]Output:[[1,3],[3,2],[2,1]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 3 == 3 = start1end1= 2 == 2 = start2The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.", + "image": null + }, + { + "text": "Example 3: Input:pairs = [[1,2],[1,3],[2,1]]Output:[[1,2],[2,1],[1,3]]Explanation:This is a valid arrangement since endi-1always equals starti.\nend0= 2 == 2 = start1end1= 1 == 1 = start2", + "image": null + } + ], + "follow_up": null, + "solution": "#Hierholzer Algorithm\nfrom collections import defaultdict\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n G = defaultdict(list)\n din = defaultdict(int)\n dout = defaultdict(int)\n for v, w in pairs:\n G[v].append(w)\n dout[v] += 1\n din[w] += 1\n start = pairs[0][0]\n for v in G:\n if din[v]+1 == dout[v]:\n start = v\n route = []\n def dfs(v):\n while G[v]:\n w = G[v].pop()\n dfs(w)\n route.append(v)\n dfs(start)\n route.reverse()\n return [[route[i],route[i+1]] for i in range(len(route)-1)]\n", + "title": "2097. Valid Arrangement of Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array points where points[i] = [x i , y i ] represents a point on the X-Y plane, return true if these points are a boomerang . A boomerang is a set of three points that are all distinct and not in a straight line . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "points.length == 3", + "points[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,3],[3,2]]Output:true", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 58.12%) | Memory: 42.3 MB (Top 12.94%)\nclass Solution {\n public boolean isBoomerang(int[][] points) {\n double a, b, c, d, area;\n a=points[0][0]-points[1][0];\n b=points[1][0]-points[2][0];\n c=points[0][1]-points[1][1];\n d=points[1][1]-points[2][1];\n area=0.5*((a*d)-(b*c));\n return area!=0;\n }\n}", + "title": "1037. Valid Boomerang", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array points where points[i] = [x i , y i ] represents a point on the X-Y plane, return true if these points are a boomerang . A boomerang is a set of three points that are all distinct and not in a straight line . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "points.length == 3", + "points[i].length == 2", + "0 <= x i , y i <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,3],[3,2]]Output:true", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,1],[2,2],[3,3]]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n a,b,c=points\n return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0])\n", + "title": "1037. Valid Boomerang", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers arr , return true if and only if it is a valid mountain array . Recall that arr is a mountain array if and only if: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1]Output:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,5,5]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,3,2,1]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 77.02%) | Memory: 54.3 MB (Top 41.77%)\nclass Solution {\n public boolean validMountainArray(int[] arr) {\n // edge case\n if(arr.length < 3) return false;\n // keep 2 pointers\n int i=0;\n int j=arr.length-1;\n // use i pointer to iterate through steep increase from LHS\n while(ii && arr[j]0;\n }\n}", + "title": "941. Valid Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given an array of integers arr , return true if and only if it is a valid mountain array . Recall that arr is a mountain array if and only if: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "arr.length >= 3", + "There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1]", + "arr[0] < arr[1] < ... < arr[i - 1] < arr[i]", + "arr[i] > arr[i + 1] > ... > arr[arr.length - 1]" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [2,1]Output:false", + "image": null + }, + { + "text": "Example 2: Input:arr = [3,5,5]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [0,3,2,1]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 153 ms (Top 95.7%) | Memory: 18.70 MB (Top 43.81%)\n\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr)<=2 or max(arr)==arr[0] or max(arr)==arr[len(arr)-1]:\n return False\n f=True\n for i in range(len(arr)-1):\n if f and arr[i]>=arr[i+1]:\n f=False\n if not f and arr[i]<=arr[i+1]:\n return False\n return True\n", + "title": "941. Valid Mountain Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"] , while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"] . Given a string s , return true if s is a valid number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "s consists of only English letters (both uppercase and lowercase), digits ( 0-9 ), plus '+' , minus '-' , or dot '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"e\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:s = \".\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 8 ms (Top 19.3%) | Memory: 44.65 MB (Top 6.2%)\n\nclass Solution {\n public boolean isNumber(String s) {\n try{\n int l=s.length();\n if(s.equals(\"Infinity\")||s.equals(\"-Infinity\")||s.equals(\"+Infinity\")||s.charAt(l-1)=='f'||s.charAt(l-1)=='d'||s.charAt(l-1)=='D'||s.charAt(l-1)=='F')\n return false;\n double x=Double.parseDouble(s);\n return true;\n }\n catch(Exception e){\n return false;\n }\n \n }\n}", + "title": "65. Valid Number", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"] , while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"] . Given a string s , return true if s is a valid number . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "s consists of only English letters (both uppercase and lowercase), digits ( 0-9 ), plus '+' , minus '-' , or dot '.' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"0\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"e\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:s = \".\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isNumber(self, s: str) -> bool:\n if s == \"inf\" or s == \"-inf\" or s == \"+inf\" or s == \"Infinity\" or s == \"-Infinity\" or s == \"+Infinity\":\n return False\n try:\n float(s)\n except (Exception):\n return False\n return True\n", + "title": "65. Valid Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s consists only of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"A man, a plan, a canal: Panama\"Output:trueExplanation:\"amanaplanacanalpanama\" is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"race a car\"Output:falseExplanation:\"raceacar\" is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \" \"Output:trueExplanation:s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 313 ms (Top 34.84%) | Memory: 43.9 MB (Top 52.81%)\nclass Solution {\n public boolean isPalindrome(String s) {\n if(s.length()==1 || s.length()==0)\n {\n return true;\n }\n\n s=s.trim().toLowerCase();\n //s=s.toLowerCase();\n String a=\"\";\n boolean bool=false;\n for(int i=0;i='a' && s.charAt(i)<='z') || (s.charAt(i)>='0' && s.charAt(i)<='9'))\n {\n a=a+s.charAt(i);\n }\n }\n if(a.length()==1 || a.length()==0)\n {\n return true;\n }\n for(int i=0;i bool:\n cleaned = \"\"\n for c in s:\n if c.isalnum():\n cleaned += c.lower()\n return (cleaned == cleaned[::-1])\n\n \n", + "title": "125. Valid Palindrome", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , return true if the s can be palindrome after deleting at most one character from it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"Output:trueExplanation:You could delete the character 'c'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n boolean first = false;\n public boolean validPalindrome(String s) {\n int left = 0;\n int right = s.length()-1;\n \n \n while(left <= right){\n if( s.charAt(left) == (s.charAt(right))){\n left++;\n right--;\n }else if(!first){\n first = true;\n String removeLeft = s.substring(0,left).concat(s.substring(left+1));\n String removeright = s.substring(0,right).concat(s.substring(right+1));\n left++;\n right--;\n return validPalindrome(removeLeft) || validPalindrome(removeright); \n } else {\n return false;\n }\n }\n return true; \n }\n}\n", + "title": "680. Valid Palindrome II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a string s , return true if the s can be palindrome after deleting at most one character from it . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aba\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"abca\"Output:trueExplanation:You could delete the character 'c'.", + "image": null + }, + { + "text": "Example 3: Input:s = \"abc\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 9164 ms (Top 5.04%) | Memory: 645.8 MB (Top 5.21%)\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n has_deleted = False\n\n def compare(s, has_deleted):\n\n if len(s) <= 1:\n return True\n\n if s[0] == s[-1]:\n return compare(s[1:-1], has_deleted)\n else:\n if not has_deleted:\n return compare(s[1:], True) or compare(s[:-1], True)\n else:\n return False\n\n return compare(s, has_deleted)", + "title": "680. Valid Palindrome II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"()[]{}\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(]\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 84.7%) | Memory: 40.80 MB (Top 15.0%)\n\nclass Solution {\n public boolean isValid(String s) {\n Stack stack = new Stack(); // create an empty stack\n for (char c : s.toCharArray()) { // loop through each character in the string\n if (c == '(') // if the character is an opening parenthesis\n stack.push(')'); // push the corresponding closing parenthesis onto the stack\n else if (c == '{') // if the character is an opening brace\n stack.push('}'); // push the corresponding closing brace onto the stack\n else if (c == '[') // if the character is an opening bracket\n stack.push(']'); // push the corresponding closing bracket onto the stack\n else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket\n // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack\n // does not match the closing bracket, the string is not valid, so return false\n return false;\n }\n // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n return stack.isEmpty();\n }\n}\n", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"()[]{}\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(]\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isValid(self, string: str) -> bool:\n while True:\n if '()' in string:\n string = string.replace('()', '')\n elif '{}' in string:\n string = string.replace('{}', '')\n elif '[]' in string:\n string = string.replace('[]', '')\n\n else:\n return not string\n", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing only three types of characters: '(' , ')' and '*' , return true if s is valid . The following rules define a valid string: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"(*)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(*))\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution{\n\tpublic boolean checkValidString(String s){\n\t\tStack stack = new Stack<>();\n\t\tStack star = new Stack<>();\n\t\tfor(int i=0;i bool:\n left,right,star = deque(), deque(), deque() #indexes of all unmatched left right parens and all '*'\n # O(n) where n=len(s)\n for i,c in enumerate(s):\n if c == '(': # we just append left paren's index\n left.append(i)\n elif c == ')': # we check if we can find a match of left paren\n if left and left[-1] < i:\n left.pop()\n else:\n right.append(i)\n else: #'*' case we just add the postion\n star.append(i)\n if not left and not right: return True\n elif not star: return False #no star to save the string, return False\n l,r = 0 ,len(star)-1\n #O(n) since star will be length less than n\n # Note: left, right,and star are always kept in ascending order! And for any i in left, j in right, i > j, or they would have been matched in the previous for loop.\n while l<=r:\n if left:\n if left[-1]< star[r]: # we keep using right most star to match with right most '('\n left.pop()\n r -= 1\n else: return False # even the right most '*' can not match a '(', we can not fix the string.\n if right:\n if right[0] > star[l]:\n right.popleft()\n l += 1\n else: return False\n if not left and not right: return True #if after some fix, all matched, we return True\n", + "title": "678. Valid Parenthesis String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a positive integer num , write a function which returns True if num is a perfect square else False. Follow up: Do not use any built-in library function such as sqrt . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= num <= 2^31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:num = 16Output:true", + "image": null + }, + { + "text": "Example 2: Input:num = 14Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 40.6 MB (Top 74.32%)\n\nclass Solution {\n public boolean isPerfectSquare(int num) {\n long start = 1;\n long end = num;\n\n while(start<=end){\n long mid = start +(end - start)/2;\n\n if(mid*mid==num){\n return true;\n }\n else if(mid*mid bool:\n if num == 1:\n return True\n lo = 2\n hi = num // 2\n while lo <= hi:\n mid = lo + (hi - lo) //2\n print(mid)\n if mid * mid == num:\n return True\n if mid * mid > num:\n hi = mid - 1\n else:\n lo = mid + 1\n return False\n", + "title": "367. Valid Perfect Square", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a string s of length n where s[i] is either: A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i : Return the number of valid permutations perm . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'D' means decreasing, or", + "'I' means increasing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"DID\"Output:5Explanation:The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)", + "image": null + }, + { + "text": "Example 2: Input:s = \"D\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 88.89%) | Memory: 42.50 MB (Top 24.07%)\n\nclass Solution {\n\tpublic int numPermsDISequence(String s) {\n\t\tint length = s.length();\n\t\tint mod = 1000000007;\n\t\tint[] dp1 = new int[length + 1];\n\t\tint[] dp2 = new int[length];\n\t\tfor (int j = 0; j <= length; j++) {\n\t\t\tdp1[j] = 1;\n\t\t}\n\t\tfor (int i = 0; i < length; i++) {\n\t\t\tif (s.charAt(i) == 'I') {\n\t\t\t\tfor (int j = 0, curr = 0; j < length - i; j++) {\n\t\t\t\t\tdp2[j] = curr = (curr + dp1[j]) % mod;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (int j = length - i - 1, curr = 0; j >= 0; j--) {\n\t\t\t\t\tdp2[j] = curr = (curr + dp1[j + 1]) % mod;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdp1 = Arrays.copyOf(dp2, length);\n\t\t}\n\t\treturn dp1[0];\n\t}\n}\n", + "title": "903. Valid Permutations for DI Sequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are given a string s of length n where s[i] is either: A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i : Return the number of valid permutations perm . Since the answer may be large, return it modulo 10^9 + 7 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "'D' means decreasing, or", + "'I' means increasing." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"DID\"Output:5Explanation:The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)", + "image": null + }, + { + "text": "Example 2: Input:s = \"D\"Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 46 ms (Top 80.0%) | Memory: 18.80 MB (Top 54.55%)\n\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [[None for j in range(n-i+1)] for i in range(n)]\n for j in range(n-1, 0-1, -1):\n if s[j] == \"I\":\n if j == n-1:\n dp[j][0] = 1\n dp[j][1] = 0\n else:\n dp[j][n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[j][i] = dp[j+1][i]+dp[j][i+1]\n else:\n if j == n-1:\n dp[j][0] = 0\n dp[j][1] = 1\n else:\n dp[j][0] = 0\n for i in range(1, n-j+1):\n dp[j][i] = dp[j+1][i-1]+dp[j][i-1]\n return sum([dp[0][i] for i in range(n+1)])%(10**9+7)\n", + "title": "903. Valid Permutations for DI Sequence", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the coordinates of four points in 2D space p1 , p2 , p3 and p4 , return true if the four points construct a square . The coordinate of a point p i is represented as [x i , y i ] . The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "p1.length == p2.length == p3.length == p4.length == 2", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]Output:true", + "image": null + }, + { + "text": "Example 2: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]Output:false", + "image": null + }, + { + "text": "Example 3: Input:p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 81.1%) | Memory: 40.42 MB (Top 51.8%)\n\nclass Solution {\n // This method returns true if the given 4 points form a square, false otherwise\n public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n // We use a set to store the distances between the points\n Set set = new HashSet();\n // Calculate the distances between all pairs of points and add them to the set\n set.add(distanceSquare(p1,p2));\n set.add(distanceSquare(p1,p3));\n set.add(distanceSquare(p1,p4));\n set.add(distanceSquare(p2,p3));\n set.add(distanceSquare(p2,p4));\n set.add(distanceSquare(p3,p4));\n // A square must have 4 equal sides, so the set must contain 2 different values (the lengths of the sides and the diagonals)\n // The set should not contain 0, as that would mean that two points have the same coordinates\n return !set.contains(0) && set.size() == 2;\n }\n // This method calculates the distance between two points and returns its square\n private int distanceSquare(int[] a, int[] b){\n // We use the Pythagorean theorem to calculate the distance between the points\n return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]);\n }\n}\n", + "title": "593. Valid Square", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the coordinates of four points in 2D space p1 , p2 , p3 and p4 , return true if the four points construct a square . The coordinate of a point p i is represented as [x i , y i ] . The input is not given in any order. A valid square has four equal sides with positive length and four equal angles (90-degree angles). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "p1.length == p2.length == p3.length == p4.length == 2", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]Output:true", + "image": null + }, + { + "text": "Example 2: Input:p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]Output:false", + "image": null + }, + { + "text": "Example 3: Input:p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 65 ms (Top 24.05%) | Memory: 13.9 MB (Top 50.57%)\nclass Solution:\n def validSquare(self, p1, p2, p3, p4):\n\n def cal(A, B):\n return abs(A[0] - B[0]) + abs(A[1] - B[1])\n\n d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)]\n d.sort()\n\n return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5]\n", + "title": "593. Valid Square", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:falseExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": " for(int i=0; i<9; i++){\n for(int j=0; j<9; j++){\n if(board[i][j] != '.'){ \n char currentVal = board[i][j];\n if(!(seen.add(currentVal + \"found in row \"+ i)) ||\n !(seen.add(currentVal + \"found in column \"+ j) ) ||\n !(seen.add(currentVal + \"found in sub box \"+ i/3 + \"-\"+ j/3)))\n return false;\n }\n \n } \n \n }\n return true;\n}\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:falseExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 104 ms (Top 89.12%) | Memory: 14 MB (Top 35.48%)\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n\n hrow = {}\n hcol = {}\n hbox = defaultdict(list)\n\n #CHECK FOR DUPLICATES ROWWISE\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[i][j] != '.':\n\n if board[i][j] not in hrow:\n hrow[board[i][j]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS ROW\n hrow.clear()\n print(\"TRUE1\")\n #CHECK FOR DUPLICATES COLUMNWISE\n\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[j][i] != '.':\n\n if board[j][i] not in hcol:\n hcol[board[j][i]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS COL\n\n hcol.clear()\n\n print('TRUE2')\n\n #CHECK DUPLICATE IN BOX, THIS IS WHERE KEY DESIGN SKILLS COME INTO PLAY, FOR SUDOKU YOU COMBINE ROW INDICES AND COL INDICES\n\n for i in range(9):\n for j in range(9):\n\n i_3 = i //3\n j_3 = j//3\n\n # print(hbox)\n if board[i][j] != '.':\n\n #CHECK ELEMENT OF ORIGINAL INDICE present in key i_3 , j_3\n if board[i][j] not in hbox[i_3 , j_3]:\n# #CHECKED IN NEW KEY\n hbox[i_3 ,j_3 ]= hbox[i_3 ,j_3 ] + [board[i][j]]\n\n else:\n return False\n\n return True\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a Tic-Tac-Toe board as a string array board , return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ' , 'X' , and 'O' . The ' ' character represents an empty square. Here are the rules of Tic-Tac-Toe: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player always places 'X' characters, while the second player always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"O \",\" \",\" \"]Output:falseExplanation:The first player always plays \"X\".", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [\"XOX\",\" X \",\" \"]Output:falseExplanation:Players take turns making moves.", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [\"XOX\",\"O O\",\"XOX\"]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 71.13%) | Memory: 41.6 MB (Top 42.96%)\nclass Solution {\n public boolean validTicTacToe(String[] board) {\n //cnt number of X and O\n int x = cntNumber('X', board);\n //this check can be omitted, it can be covered in the second number check.\n if(x >5){\n return false;\n }\n int o = cntNumber('O', board);\n if(x < o || x > o + 1){\n return false;\n }\n //if(x <3 ) true, no need to see winning\n if(o >= 3){\n //if x has won, but game doesnt stop\n if(x == o && hasWon('X', board)){\n return false;\n }\n //if o has won, but game doesnt stop\n if( x > o && hasWon('O', board) ){\n return false;\n }\n }\n return true;\n }\n\n private int cntNumber(char target, String[] board){\n int res = 0;\n for(int i = 0; i<3; i++) {\n for(int j = 0; j<3; j++) {\n if(target == board[i].charAt(j)){\n res++;\n }\n }\n }\n return res;\n }\n\n private boolean hasWon(char target, String[] board){\n String toWin = Character.toString(target).repeat(3);\n for(int i = 0; i<3; i++) {\n if(board[i].equals(toWin)){\n return true;\n }\n }\n for(int j = 0; j<3; j++) {\n boolean col = true;\n for(int i = 0; i<3; i++) {\n col = col && target == board[i].charAt(j);\n if(!col){\n break;\n }\n }\n if(col){\n return true;\n }\n }\n //check diagonal. If center is not target, not possible to form diag win.\n if(target != board[1].charAt(1)){\n return false;\n }\n\n boolean diagonal1 = target == board[0].charAt(0);\n //only proceed if the first letter match. Otherwise might get false positive\n if(diagonal1){\n if(target == board[2].charAt(2)){\n return true;\n }\n }\n\n boolean diagonal2 = target == board[0].charAt(2);\n if(diagonal2){\n if(target == board[2].charAt(0)){\n return true;\n }\n }\n return false;\n }\n}", + "title": "794. Valid Tic-Tac-Toe State", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given a Tic-Tac-Toe board as a string array board , return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array that consists of characters ' ' , 'X' , and 'O' . The ' ' character represents an empty square. Here are the rules of Tic-Tac-Toe: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Players take turns placing characters into empty squares ' ' .", + "The first player always places 'X' characters, while the second player always places 'O' characters.", + "'X' and 'O' characters are always placed into empty squares, never filled ones.", + "The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.", + "The game also ends if all squares are non-empty.", + "No more moves can be played if the game is over." + ], + "examples": [ + { + "text": "Example 1: Input:board = [\"O \",\" \",\" \"]Output:falseExplanation:The first player always plays \"X\".", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg" + }, + { + "text": "Example 2: Input:board = [\"XOX\",\" X \",\" \"]Output:falseExplanation:Players take turns making moves.", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg" + }, + { + "text": "Example 3: Input:board = [\"XOX\",\"O O\",\"XOX\"]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def validTicTacToe(self, board: List[str]) -> bool:\n # The two criteria for a valid board are:\n # 1) num of Xs - num of Os is 0 or 1\n # 2) X is not a winner if the # of moves is even, and\n # O is not a winner if the # of moves is odd.\n\n d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array\n s = [d[ch] for ch in ''.join(board)] # Ex: [\"XOX\",\" X \",\" \"] --> [1,-1,1,0,1,0,0,0,0]\n sm = sum(s)\n\n if sm>>1: return False # <-- criterion 1\n \n n = -3 if sm == 1 else 3 # <-- criterion 2.\n if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], \n s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are \n s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags\n \n return True # <-- both criteria are true", + "title": "794. Valid Tic-Tac-Toe State", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,4]Output:3Explanation:Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 95.13%) | Memory: 43.50 MB (Top 23.38%)\n\nclass Solution {\n public int triangleNumber(int[] a) {\n Arrays.sort(a);\n int n=a.length;\n int count=0;\n for(int i=n-1;i>=1;i--){\n int left=0,right=i-1;\n while(lefta[i]){\n count+=right-left;\n right--;\n }\n else\n left++;\n }\n }\n return count;\n }\n}\n", + "title": "611. Valid Triangle Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an integer array nums , return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "0 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,4]Output:3Explanation:Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,2,3,4]Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}\n", + "title": "611. Valid Triangle Number", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]Output:falseExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValidBST(TreeNode root) {\n return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);\n }\n \n public boolean dfs(TreeNode root, int min, int max) {\n if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) || (root.val == Integer.MAX_VALUE && root.right != null)) return false;\n boolean leftRight = true;\n if (root.left == null && root.right == null) return true;\n if (root.left != null) {\n leftRight = dfs(root.left, min, root.val - 1);\n }\n if (root.right != null) {\n leftRight = dfs(root.right, root.val + 1, max) && leftRight;\n }\n return leftRight;\n }\n}\n", + "title": "98. Validate Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]Output:falseExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 89 ms (Top 18.35%) | Memory: 16.5 MB (Top 80.77%)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n\n def valid(node,left,right):\n if not node: # checking node is none\n return True\n if not (node.val>left and node.val 1) {\n return false;\n }\n }\n if (r != -1) {\n // Same thing for parent node and the right child node\n if (!uf.union(i, r) || ++indeg[r] > 1) {\n return false;\n }\n }\n }\n return uf.connected();\n }\n}\n", + "title": "1361. Validate Binary Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i] , return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1 , similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == leftChild.length == rightChild.length", + "1 <= n <= 10^4", + "-1 <= leftChild[i], rightChild[i] <= n - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]Output:true", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex1.png" + }, + { + "text": "Example 2: Input:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]Output:false", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex2.png" + }, + { + "text": "Example 3: Input:n = 2, leftChild = [1,0], rightChild = [-1,-1]Output:false", + "image": "https://assets.leetcode.com/uploads/2019/08/23/1503_ex3.png" + } + ], + "follow_up": null, + "solution": " class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \n left_set=set(leftChild)\n right_set=set(rightChild) \n\n que=[]\n\n for i in range(n):\n if i not in left_set and i not in right_set:\n que.append(i)\n \n if len(que)>1 or len(que)==0:\n return False\n \n \n graph=defaultdict(list)\n\n for i in range(n):\n graph[i]=[]\n\n if leftChild[i]!=-1:\n graph[i].append(leftChild[i])\n\n if rightChild[i]!=-1:\n graph[i].append(rightChild[i])\n \n visited=set()\n visited.add(que[0])\n \n \n while len(que)>0:\n item=que.pop(0)\n \n\n children=graph[item]\n\n for child in children:\n if child not in visited:\n que.append(child)\n visited.add(child)\n else:\n return False\n\n\n for i in range(n):\n if i not in visited:\n return False\n\n return True\n", + "title": "1361. Validate Binary Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string queryIP , return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form \"x 1 .x 2 .x 3 .x 4 \" where 0 <= x i <= 255 and x i cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\" , \"192.168.1.00\" , and \"192.168@1.1\" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form \"x 1 :x 2 :x 3 :x 4 :x 5 :x 6 :x 7 :x 8 \" where: For example, \" 2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \" 2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \" 2001:0db8:85a3::8A2E:037j:7334\" and \" 02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= x i .length <= 4", + "x i is a hexadecimal string which may contain digits, lowercase English letter ( 'a' to 'f' ) and upper-case English letters ( 'A' to 'F' ).", + "Leading zeros are allowed in x i ." + ], + "examples": [ + { + "text": "Example 1: Input:queryIP = \"172.16.254.1\"Output:\"IPv4\"Explanation:This is a valid IPv4 address, return \"IPv4\".", + "image": null + }, + { + "text": "Example 2: Input:queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"Output:\"IPv6\"Explanation:This is a valid IPv6 address, return \"IPv6\".", + "image": null + }, + { + "text": "Example 3: Input:queryIP = \"256.256.256.256\"Output:\"Neither\"Explanation:This is neither a IPv4 address nor a IPv6 address.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 94.74%) | Memory: 41.50 MB (Top 35.64%)\n\nclass Solution {\n public String validIPAddress(String IP) {\n if(IP.length()==0) return \"Neither\";\n \n if(IP.indexOf(\".\")>=0) return validateIPV4(IP);\n \n if(IP.indexOf(\":\")>=0) return validateIPV6(IP);\n \n return \"Neither\";\n }\n \n private String validateIPV4(String ip){\n\t // step 1 \n if(ip.charAt(0)=='.' || ip.charAt(ip.length()-1)=='.') return \"Neither\";\n \n\t\t //step 2 \n String[] component=ip.split(\"\\\\.\");\n \n\t\t //step 3\n if(component.length!=4) return \"Neither\";\n \n\t\t //step 4\n for(String comp:component){\n if(comp.length()==0 || comp.length()>3 || (comp.charAt(0)=='0' && comp.length()>1)){\n return \"Neither\";\n }\n \n\t\t\t //step5\n for(char ch:comp.toCharArray()){\n if(ch<'0' || ch>'9') return \"Neither\";\n }\n \n\t\t\t //step6\n int num=Integer.parseInt(comp);\n if(num<0 || num>255) return \"Neither\";\n \n }\n \n return \"IPv4\";\n }\n \n private String validateIPV6(String ip){\n if(ip.charAt(0)==':' || ip.charAt(ip.length()-1)==':') return \"Neither\";\n \n String[] component=ip.split(\":\");\n \n if(component.length!=8) return \"Neither\";\n \n for(String comp:component){\n if(comp.length()==0 || comp.length()>4) return \"Neither\";\n \n \n for(char ch:comp.toLowerCase().toCharArray()){\n if((ch<'0' || ch>'9') && (ch!='a' && ch!='b' && ch!='c' && ch!='d' && ch!='e' && ch!='f')){\n return \"Neither\";\n } \n }\n }\n return \"IPv6\";\n }\n }\n", + "title": "468. Validate IP Address", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given a string queryIP , return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form \"x 1 .x 2 .x 3 .x 4 \" where 0 <= x i <= 255 and x i cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\" , \"192.168.1.00\" , and \"192.168@1.1\" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form \"x 1 :x 2 :x 3 :x 4 :x 5 :x 6 :x 7 :x 8 \" where: For example, \" 2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \" 2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \" 2001:0db8:85a3::8A2E:037j:7334\" and \" 02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= x i .length <= 4", + "x i is a hexadecimal string which may contain digits, lowercase English letter ( 'a' to 'f' ) and upper-case English letters ( 'A' to 'F' ).", + "Leading zeros are allowed in x i ." + ], + "examples": [ + { + "text": "Example 1: Input:queryIP = \"172.16.254.1\"Output:\"IPv4\"Explanation:This is a valid IPv4 address, return \"IPv4\".", + "image": null + }, + { + "text": "Example 2: Input:queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"Output:\"IPv6\"Explanation:This is a valid IPv6 address, return \"IPv6\".", + "image": null + }, + { + "text": "Example 3: Input:queryIP = \"256.256.256.256\"Output:\"Neither\"Explanation:This is neither a IPv4 address nor a IPv6 address.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validIPAddress(self, queryIP: str) -> str:\n queryIP = queryIP.replace(\".\",\":\")\n ct = 0\n for i in queryIP.split(\":\"):\n if i != \"\":\n ct += 1\n if ct == 4:\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if i.isnumeric():\n if len(i) > 1:\n if i.count('0') == len(i) or int(i) > 255 or i[0] == '0':\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv4\"\n elif ct == 8:\n a = ['a','b','c','d','e','f','A','B','C','D','E','F']\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if len(i) < 5:\n for j in i:\n if j not in a and j.isdigit() == False:\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv6\"\n else:\n return \"Neither\"\n \n\n\n ", + "title": "468. Validate IP Address", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= pushed.length <= 1000", + "0 <= pushed[i] <= 1000", + "All the elements of pushed are unique .", + "popped.length == pushed.length", + "popped is a permutation of pushed ." + ], + "examples": [ + { + "text": "Example 1: Input:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]Output:trueExplanation:We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1", + "image": null + }, + { + "text": "Example 2: Input:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]Output:falseExplanation:1 cannot be popped before 2.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 57.66%) | Memory: 44.5 MB (Top 82.21%)\n\nclass Solution {\n public boolean validateStackSequences(int[] pushed, int[] popped) {\n Stack st = new Stack<>(); // Create a stack\n\n int j = 0; // Intialise one pointer pointing on popped array\n\n for(int val : pushed){\n st.push(val); // insert the values in stack\n while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j];\n st.pop(); // then pop out\n j++; // increment j\n }\n }\n return st.isEmpty(); // check if stack is empty return true else false\n }\n}", + "title": "946. Validate Stack Sequences", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= pushed.length <= 1000", + "0 <= pushed[i] <= 1000", + "All the elements of pushed are unique .", + "popped.length == pushed.length", + "popped is a permutation of pushed ." + ], + "examples": [ + { + "text": "Example 1: Input:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]Output:trueExplanation:We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1", + "image": null + }, + { + "text": "Example 2: Input:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]Output:falseExplanation:1 cannot be popped before 2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n i=0\n for num in pushed:\n stack.append(num) #we are pushing the number to the stack\n while len(stack) >0 and stack[len(stack)-1] == popped[i] :\n #if the last element of the stack is equal to the popped element\n stack.pop()\n i+=1 #we are incrementing i\n return True if len(stack) ==0 else False\n\t\t\n", + "title": "946. Validate Stack Sequences", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Return true if the equation is solvable, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each character is decoded as one digit (0 - 9).", + "No two characters can map to the same digit.", + "Each words[i] and result are decoded as one number without leading zeros.", + "Sum of numbers on the left side ( words ) will equal to the number on the right side ( result )." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"SEND\",\"MORE\"], result = \"MONEY\"Output:trueExplanation:Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652", + "image": null + }, + { + "text": "Example 2: Input:words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"Output:trueExplanation:Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214", + "image": null + }, + { + "text": "Example 3: Input:words = [\"LEET\",\"CODE\"], result = \"POINT\"Output:falseExplanation:There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 96.2%) | Memory: 40.32 MB (Top 56.2%)\n\nclass Solution {\n public static boolean isSolvable(String[] words, String result) {\n\t // reverse all strings to facilitate add calculation.\n for (int i = 0; i < words.length; i++) {\n words[i] = new StringBuilder(words[i]).reverse().toString();\n }\n result = new StringBuilder(result).reverse().toString();\n if (!checkLength(words, result)) {\n return false;\n }\n boolean[] visited = new boolean[10]; // digit 0, 1, ..., 9\n int[] chToDigit = new int[26];\n Arrays.fill(chToDigit, -1);\n return dfs(0, 0, 0, visited, chToDigit, words, result);\n }\n\n /**\n * Elminate the case where result is too long\n * word1: AAA\n * word2: BBB\n * result: XXXXXXXXX\n */\n private static boolean checkLength(String[] words, String result) {\n int maxLen = 0;\n for (String word : words) {\n maxLen = Math.max(maxLen, word.length());\n }\n return result.length() == maxLen || result.length() == maxLen + 1;\n }\n\n /*\n Put all words like this:\n w1: ABC\n w2: EF\n w3: GHIJ\n result: KLMNO\n i, is the row\n j, is the column\n carrier, the one contributed from previous calculation\n chToDigit, 26 int array, which records choosen digit for 'A', 'B', 'C', ... If not choosen any, default is -1 \n */\n private static boolean dfs(int i, int j, int carrier, boolean[] visited, int[] chToDigit, String[] words, String result) {\n if (i == words.length) {\n char ch = result.charAt(j);\n // (i, i) at bottom right corner. final check\n if (j == result.length() - 1) {\n // 1. check if carrier is equal or greater than 10. If so, false.\n if (carrier >= 10) {\n return false;\n }\n // 2. check if result.length() > 1 && result.lastCh is zero. If so the false.\n if (j > 0 && j == result.length() - 1 && chToDigit[ch - 'A'] == 0) {\n return false;\n }\n // not selected, can select any. True.\n if (chToDigit[ch - 'A'] == -1) {\n System.out.println(Arrays.toString(chToDigit));\n return true;\n } else { // if selected, check if it matches with carrier. Also, carrier can't be 0. result = '00' is invalid\n return chToDigit[ch - 'A'] == carrier;\n }\n } else { // reached normal result line.\n // 1. if not selected. Use current carrier's unit digit\n if (chToDigit[ch - 'A'] == -1) {\n int selectedDigit = carrier % 10;\n // For example carrier = 13. selectedDigit = 3. ch = 'H'. Should set 3 to 'H'.\n // But 3 is already taken by 'B' previously. So wrong.\n if (visited[selectedDigit]) {\n return false;\n }\n visited[selectedDigit] = true;\n chToDigit[ch - 'A'] = selectedDigit;\n if (dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result)) {\n return true;\n }\n chToDigit[ch - 'A'] = -1;\n visited[selectedDigit] = false;\n } else { // 2. selected\n // just need to check if ch.digit equals to unit digit.\n if (chToDigit[ch - 'A'] != carrier % 10) {\n return false;\n }\n boolean ans = dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result);\n return ans;\n }\n } //\n } else { // normal word\n String word = words[i];\n // 1. check if j is equal or greater than word.len. If so pass to next word.\n if (j >= word.length()) {\n boolean ans = dfs(i + 1, j, carrier, visited, chToDigit, words, result);\n return ans;\n }\n // 2. check if it's last ch, word.len is greater than 1, and is '0'. If so false;\n if (j == word.length() - 1 && word.length() > 1 && chToDigit[word.charAt(j) - 'A'] == 0) {\n return false;\n }\n char ch = word.charAt(j);\n // 3. check if word.ch is selected. Just add current digit and move to next word.\n if (chToDigit[ch - 'A'] != -1) {\n int newSum = carrier + chToDigit[ch - 'A'];\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n return ans;\n } else {\n for (int k = 0; k < visited.length; k++) {\n if (visited[k]) {\n continue;\n }\n visited[k] = true;\n chToDigit[ch - 'A'] = k;\n int newSum = k + carrier;\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n if (ans) {\n return true;\n }\n visited[k] = false;\n chToDigit[ch - 'A'] = -1;\n }\n }\n }\n return false;\n }\n}", + "title": "1307. Verbal Arithmetic Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Return true if the equation is solvable, otherwise return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Each character is decoded as one digit (0 - 9).", + "No two characters can map to the same digit.", + "Each words[i] and result are decoded as one number without leading zeros.", + "Sum of numbers on the left side ( words ) will equal to the number on the right side ( result )." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"SEND\",\"MORE\"], result = \"MONEY\"Output:trueExplanation:Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652", + "image": null + }, + { + "text": "Example 2: Input:words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"Output:trueExplanation:Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214", + "image": null + }, + { + "text": "Example 3: Input:words = [\"LEET\",\"CODE\"], result = \"POINT\"Output:falseExplanation:There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n \n # reverse words\n words = [i[::-1] for i in words]\n result = result[::-1]\n allWords = words + [result]\n \n # chars that can not be 0\n nonZero = set()\n for word in allWords:\n if len(word) > 1:\n nonZero.add(word[-1])\n \n # numbers selected in backtracking\n selected = set()\n # char to Int map\n charToInt = dict()\n mxLen = max([len(i) for i in allWords])\n \n def res(i = 0, c = 0, sm = 0):\n if c == mxLen:\n return 1 if sm == 0 else 0\n elif i == len(words):\n num = sm % 10\n carry = sm // 10\n if c >= len(result):\n if num == 0:\n return res(0, c+1, carry)\n else:\n return 0\n # result[c] should be mapped to num if a mapping exists\n if result[c] in charToInt:\n if charToInt[result[c]] != num:\n return 0\n else:\n return res(0, c+1, carry)\n elif num in selected:\n return 0\n # if mapping does not exist, create a mapping\n elif (num == 0 and result[c] not in nonZero) or num > 0:\n selected.add(num)\n charToInt[result[c]] = num\n ret = res(0, c + 1, carry)\n del charToInt[result[c]]\n selected.remove(num)\n return ret\n else:\n return 0\n else:\n word = words[i]\n if c >= len(word):\n return res(i+1, c, sm)\n elif word[c] in charToInt:\n return res(i+1, c, sm + charToInt[word[c]])\n else:\n ret = 0\n # possibilities for word[c]\n for j in range(10):\n if (j == 0 and word[c] not in nonZero) or j > 0:\n if j not in selected:\n selected.add(j)\n charToInt[word[c]] = j\n ret += res(i + 1, c, sm + j)\n del charToInt[word[c]]\n selected.remove(j)\n return ret\n \n return res() > 0", + "title": "1307. Verbal Arithmetic Puzzle", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "One way to serialize a binary tree is to use preorder traversal . When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#' . For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\" , where '#' represents a null node. Given a string of comma-separated values preorder , return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. Note: You are not allowed to reconstruct the tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, it could never contain two consecutive commas, such as \"1,,3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:preorder = \"1,#\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:preorder = \"9,#,#,1\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isValidSerialization(String preorder) {\n String[] strs = preorder.split(\",\");\n //In starting we have one vacany for root\n int vacancy = 1;\n \n for(String str : strs){\n \n if(--vacancy < 0 ) return false;\n \n // whenever we encounter a new node vacancy decreases by 1 and left and right two vacancy for that node will added in total\n if(!str.equals(\"#\")) \n vacancy += 2;\n \n }\n \n \n return vacancy == 0;\n \n }\n}\n", + "title": "331. Verify Preorder Serialization of a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "One way to serialize a binary tree is to use preorder traversal . When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#' . For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\" , where '#' represents a null node. Given a string of comma-separated values preorder , return true if it is a correct preorder traversal serialization of a binary tree. It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer. You may assume that the input format is always valid. Note: You are not allowed to reconstruct the tree. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, it could never contain two consecutive commas, such as \"1,,3\" ." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:preorder = \"1,#\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:preorder = \"9,#,#,1\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 77 ms (Top 11.09%) | Memory: 13.8 MB (Top 99.05%)\nclass Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n nodes = preorder.split(',')\n counter=1\n for i, node in enumerate(nodes):\n if node != '#':\n counter+=1\n else:\n if counter <= 1 and i != len(nodes) - 1:\n return False\n counter-=1\n return counter == 0", + "title": "331. Verify Preorder Serialization of a Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order . The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "order.length == 26", + "All characters in words[i] and order are English lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"Output:trueExplanation:As 'h' comes before 'l' in this language, then the sequence is sorted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"Output:falseExplanation:As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"Output:falseExplanation:The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 80.43%) | Memory: 42.9 MB (Top 28.86%)\nclass Solution {\n public boolean isAlienSorted(String[] words, String order) {\n int val=1;\n int[] alp = new int[26];\n\n for(int i=0;i alp[words[i+1].charAt(j)-'a']) {\n return false;\n } else if(alp[words[i].charAt(j)-'a'] < alp[words[i+1].charAt(j)-'a']) {\n flag=1;\n break;\n }\n }\n if(flag==0 && words[i].length()>words[i+1].length()) {\n return false; // if second word is sub string of first word starting from the beginning, return false.\n }\n }\n\n return true;\n }\n}", + "title": "953. Verifying an Alien Dictionary", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order . The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= words.length <= 100", + "1 <= words[i].length <= 20", + "order.length == 26", + "All characters in words[i] and order are English lowercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"Output:trueExplanation:As 'h' comes before 'l' in this language, then the sequence is sorted.", + "image": null + }, + { + "text": "Example 2: Input:words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"Output:falseExplanation:As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"Output:falseExplanation:The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 74 ms (Top 17.14%) | Memory: 13.7 MB (Top 99.39%)\nclass Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n order_index = {key:index for index, key in enumerate(order)}\n\n for i in range(len(words)-1):\n w1,w2 = words[i] , words[i + 1]\n for j in range(len(w1)):\n if j == len(w2):\n return False\n if w1[j] != w2[j]:\n if order_index.get(w2[j]) < order_index.get(w1[j]):\n return False\n break\n return True", + "title": "953. Verifying an Alien Dictionary", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col) , its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0) . The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[9],[3,15],[20],[7]]Explanation:Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7]Output:[[4],[2],[1,5,6],[3],[7]]Explanation:Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2,3,4,6,5,7]Output:[[4],[2],[1,5,6],[3],[7]]Explanation:This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg" + } + ], + "follow_up": null, + "solution": "// Runtime: 3 ms (Top 94.64%) | Memory: 42.3 MB (Top 95.72%)\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n private static class MNode {\n TreeNode Node;\n int hDist;\n int level;\n MNode(TreeNode node, int hd, int l) {\n Node = node;\n hDist = hd;\n level = l;\n }\n }\n\n public List> verticalTraversal(TreeNode root) {\n Map> map = new TreeMap<>();\n Queue q = new LinkedList<>();\n\n q.add(new MNode(root, 0, 0));\n\n while(!q.isEmpty()) {\n\n MNode curr = q.poll();\n if(map.containsKey(curr.hDist))\n map.get(curr.hDist).add(curr);\n\n else {\n PriorityQueue pq = new PriorityQueue<>\n ((a,b) -> (a.level == b.level)? a.Node.val - b.Node.val: a.level - b.level);\n pq.add(curr);\n map.put(curr.hDist, pq);\n }\n\n if(curr.Node.left != null)\n q.add(new MNode(curr.Node.left, curr.hDist -1, curr.level + 1));\n\n if(curr.Node.right != null)\n q.add(new MNode(curr.Node.right, curr.hDist +1, curr.level + 1));\n }\n\n List> ans = new ArrayList<>();\n for(Integer key: map.keySet()) {\n List temp = new ArrayList<>();\n while(!map.get(key).isEmpty()) { temp.add(map.get(key).poll().Node.val); }\n ans.add(new ArrayList<>(temp));\n }\n\n return ans;\n\n }\n\n}", + "title": "987. Vertical Order Traversal of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col) , its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0) . The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[9],[3,15],[20],[7]]Explanation:Column -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3,4,5,6,7]Output:[[4],[2],[1,5,6],[3],[7]]Explanation:Column -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg" + }, + { + "text": "Example 3: Input:root = [1,2,3,4,6,5,7]Output:[[4],[2],[1,5,6],[3],[7]]Explanation:This case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.", + "image": "https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg" + } + ], + "follow_up": null, + "solution": "# Runtime: 69 ms (Top 15.25%) | Memory: 14.3 MB (Top 28.85%)\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def verticalTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n q = [(0, 0, root)]\n l = []\n while q:\n col, row, node = q.pop()\n l.append((col, row, node.val))\n if node.left:\n q.append((col-1, row+1, node.left))\n if node.right:\n q.append((col+1, row+1, node.right))\n l.sort()\n print(l)\n ans = []\n ans.append([l[0][-1]])\n for i in range(1, len(l)):\n if l[i][0] > l[i-1][0]:\n ans.append([l[i][-1]])\n else:\n ans[-1].append(l[i][-1])\n return ans\n", + "title": "987. Vertical Order Traversal of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [start i , end i ] indicates that the ith clip started at start i and ended at end i . We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time] . If the task is impossible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7] ." + ], + "examples": [ + { + "text": "Example 1: Input:clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10Output:3Explanation:We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].", + "image": null + }, + { + "text": "Example 2: Input:clips = [[0,1],[1,2]], time = 5Output:-1Explanation:We cannot cover [0,5] with only [0,1] and [1,2].", + "image": null + }, + { + "text": "Example 3: Input:clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9Output:3Explanation:We can take clips [0,4], [4,7], and [6,9].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int videoStitching(int[][] clips, int time) {\n Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);\n int n = clips.length;\n int interval[] = new int[2];\n int cuts = 0;\n while(true){\n cuts++;\n int can_reach = 0;\n for(int i = interval[0]; i <= interval[1]; i++){\n int j = 0;\n while(j < n){\n if(clips[j][0] < i){\n j++;\n }\n else if(clips[j][0] == i){\n can_reach = Math.max(can_reach , clips[j][1]);\n j++;\n }\n else{\n break;\n }\n }\n if(can_reach >= time) return cuts;\n }\n interval[0] = interval[1] + 1;\n interval[1] = can_reach;\n if(interval[0] > interval[1]) return -1;\n }\n }\n}", + "title": "1024. Video Stitching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [start i , end i ] indicates that the ith clip started at start i and ended at end i . We can cut these clips into segments freely. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time] . If the task is impossible, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7] ." + ], + "examples": [ + { + "text": "Example 1: Input:clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10Output:3Explanation:We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].", + "image": null + }, + { + "text": "Example 2: Input:clips = [[0,1],[1,2]], time = 5Output:-1Explanation:We cannot cover [0,5] with only [0,1] and [1,2].", + "image": null + }, + { + "text": "Example 3: Input:clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9Output:3Explanation:We can take clips [0,4], [4,7], and [6,9].", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 46 ms (Top 41.2%) | Memory: 16.25 MB (Top 82.7%)\n\nclass Solution:\n def videoStitching(self, clips: List[List[int]], T: int) -> int:\n dp = [float('inf')] * (T + 1)\n dp[0] = 0\n for i in range(1, T + 1):\n for start, end in clips:\n if start <= i <= end:\n dp[i] = min(dp[start] + 1, dp[i])\n if dp[T] == float('inf'):\n return -1\n return dp[T]", + "title": "1024. Video Stitching", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a wordlist , we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: In addition, the spell checker operates under the following precedence rules: Given some queries , return a list of words answer , where answer[i] is the correct word for query = queries[i] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Capitalization: If the query matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\" Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\" Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\"", + "Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\" Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match) Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\"", + "Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)" + ], + "examples": [ + { + "text": "Example 1: Input:wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]Output:[\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]", + "image": null + }, + { + "text": "Example 2: Input:wordlist = [\"yellow\"], queries = [\"YellOw\"]Output:[\"yellow\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 184 ms (Top 7.48%) | Memory: 114.1 MB (Top 5.44%)\nclass Solution {\n public String[] spellchecker(String[] wordlist, String[] queries) {\n String[] ans = new String[queries.length];\n Map[] map = new HashMap[3];\n Arrays.setAll(map, o -> new HashMap<>());\n String pattern = \"[aeiou]\";\n\n for (String w : wordlist){\n String lo = w.toLowerCase();\n map[0].put(w, \"\");\n map[1].putIfAbsent(lo, w);\n map[2].putIfAbsent(lo.replaceAll(pattern, \".\"), map[1].getOrDefault(w, w));\n }\n\n int i = 0;\n for (String q : queries){\n String lo = q.toLowerCase();\n String re = lo.replaceAll(pattern, \".\");\n if (map[0].containsKey(q)){\n ans[i] = q;\n }else if (map[1].containsKey(lo)){\n ans[i] = map[1].get(lo);\n }else if (map[2].containsKey(re)){\n ans[i] = map[2].get(re);\n }else{\n ans[i] = \"\";\n }\n i++;\n }\n\n return ans;\n }\n}", + "title": "966. Vowel Spellchecker", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a wordlist , we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: In addition, the spell checker operates under the following precedence rules: Given some queries , return a list of words answer , where answer[i] is the correct word for query = queries[i] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Capitalization: If the query matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\" Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\" Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"YellOw\" : correct = \"yellow\"", + "Example: wordlist = [\"Yellow\"] , query = \"yellow\" : correct = \"Yellow\"", + "Example: wordlist = [\"yellow\"] , query = \"yellow\" : correct = \"yellow\"", + "Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist ( case-insensitive ), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\" Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match) Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yollow\" : correct = \"YellOw\"", + "Example: wordlist = [\"YellOw\"] , query = \"yeellow\" : correct = \"\" (no match)", + "Example: wordlist = [\"YellOw\"] , query = \"yllw\" : correct = \"\" (no match)" + ], + "examples": [ + { + "text": "Example 1: Input:wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]Output:[\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]", + "image": null + }, + { + "text": "Example 2: Input:wordlist = [\"yellow\"], queries = [\"YellOw\"]Output:[\"yellow\"]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 166 ms (Top 89.12%) | Memory: 19.20 MB (Top 76.17%)\n\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n capital={i.lower():i for i in wordlist[::-1]}\n vovel={''.join([j if j not in \"aeiou\" else '.' for j in i.lower()]):i for i in wordlist[::-1]}\n wordlist=set(wordlist)\n res=[]\n for i in queries:\n if i in wordlist:\n res.append(i)\n elif i.lower() in capital:\n res.append(capital[i.lower()])\n elif ''.join([j if j not in \"aeiou\" else '.' for j in i.lower()]) in vovel:\n res.append(vovel[''.join([j if j not in \"aeiou\" else '.' for j in i.lower()])])\n else:\n res.append(\"\")\n return res\n", + "title": "966. Vowel Spellchecker", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string word , return the sum of the number of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) in every substring of word . A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 10^5", + "word consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"Output:6Explanation:All possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:word = \"abc\"Output:3Explanation:All possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.", + "image": null + }, + { + "text": "Example 3: Input:word = \"ltcd\"Output:0Explanation:There are no vowels in any substring of \"ltcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 23 ms (Top 33.08%) | Memory: 50 MB (Top 44.62%)\nclass Solution {\n\n boolean isVowel(char ch) {\n return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';\n }\n\n public long countVowels(String word) {\n long count = 0;\n int len = word.length();\n\n for(int pos = 0; pos < len; pos++) {\n if(isVowel(word.charAt(pos))) {\n count += (long)(len - pos) * (long)(pos + 1);\n }\n }\n\n return count;\n }\n}", + "title": "2063. Vowels of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string word , return the sum of the number of vowels ( 'a' , 'e' , 'i' , 'o' , and 'u' ) in every substring of word . A substring is a contiguous (non-empty) sequence of characters within a string. Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word.length <= 10^5", + "word consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word = \"aba\"Output:6Explanation:All possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.", + "image": null + }, + { + "text": "Example 2: Input:word = \"abc\"Output:3Explanation:All possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.", + "image": null + }, + { + "text": "Example 3: Input:word = \"ltcd\"Output:0Explanation:There are no vowels in any substring of \"ltcd\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def countVowels(self, word: str) -> int:\n count = vowelIndexSum = 0\n vowels = {'a', 'e', 'i', 'o', 'u'}\n\n for i, c in enumerate(word, start=1):\n if c in vowels:\n vowelIndexSum += i\n count += vowelIndexSum\n \n return count", + "title": "2063. Vowels of All Substrings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands : Some of the grid squares are obstacles . The i th obstacle is at grid point obstacles[i] = (x i , y i ) . If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5 , return 25 ) . Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 : Turn left 90 degrees.", + "-1 : Turn right 90 degrees.", + "1 <= k <= 9 : Move forward k units, one unit at a time." + ], + "examples": [ + { + "text": "Example 1: Input:commands = [4,-1,3], obstacles = []Output:25Explanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32+ 42= 25 units away.", + "image": null + }, + { + "text": "Example 2: Input:commands = [4,-1,4,-2,4], obstacles = [[2,4]]Output:65Explanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12+ 82= 65 units away.", + "image": null + }, + { + "text": "Example 3: Input:commands = [6,-1,-1,6], obstacles = []Output:36Explanation:The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62= 36 units away.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 162 ms (Top 8.26%) | Memory: 66.8 MB (Top 51.38%)\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n int dir = 0; // states 0north-1east-2south-3west\n int farthestSofar = 0;\n\n int xloc = 0;\n int yloc = 0;\n\n Set set = new HashSet<>();\n for (int[] obs : obstacles) {\n set.add(obs[0] + \",\" + obs[1]);\n }\n\n int steps;\n\n for(int i: commands){\n\n if( i == -1){//turn right 90\n dir++;\n }\n else if (i == -2){//turn left 90\n dir--;\n }\n else{//move forward value of i baring no obsticals\n dir = dir%4;\n if (dir== -1){\n dir = 3;\n }\n else if(dir == -3){\n dir = 1;\n }\n else if(dir == -2){\n dir = 2;\n }\n // dir %4 = -1 -> 3\n // dir %4 = -2 -> 2\n // dir %4 = -3 -> 1\n if(dir == 0){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc+1))) {\n yloc++;\n steps++;\n }\n }\n else if (dir == 1){\n steps = 0;\n while (steps < i && !set.contains((xloc+1) + \",\" + (yloc))) {\n xloc++;\n steps++;\n }\n }\n else if (dir == 2){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc-1))) {\n yloc--;\n steps++;\n }\n }\n else{ //case dir == 3\n steps = 0;\n while (steps < i && !set.contains((xloc-1) + \",\" + (yloc))) {\n xloc--;\n steps++;\n }\n }\n }\n farthestSofar = Math.max(farthestSofar, xloc*xloc + yloc*yloc);\n }\n return farthestSofar;\n }\n}", + "title": "874. Walking Robot Simulation", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands : Some of the grid squares are obstacles . The i th obstacle is at grid point obstacles[i] = (x i , y i ) . If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command. Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5 , return 25 ) . Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 : Turn left 90 degrees.", + "-1 : Turn right 90 degrees.", + "1 <= k <= 9 : Move forward k units, one unit at a time." + ], + "examples": [ + { + "text": "Example 1: Input:commands = [4,-1,3], obstacles = []Output:25Explanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32+ 42= 25 units away.", + "image": null + }, + { + "text": "Example 2: Input:commands = [4,-1,4,-2,4], obstacles = [[2,4]]Output:65Explanation:The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12+ 82= 65 units away.", + "image": null + }, + { + "text": "Example 3: Input:commands = [6,-1,-1,6], obstacles = []Output:36Explanation:The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62= 36 units away.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 970 ms (Top 9.86%) | Memory: 20.6 MB (Top 59.47%)\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obs = set(tuple(o) for o in obstacles)\n x = y = a = out = 0\n move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}\n for c in commands:\n if c == -1:\n a += 90\n elif c == -2:\n a -= 90\n else:\n direction = a % 360\n dx, dy = move[direction]\n for _ in range(c):\n if (x + dx, y + dy) in obs:\n break\n x += dx\n y += dy\n out = max(out, x**2 + y**2)\n return out", + "title": "874. Walking Robot Simulation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1) . The grid is aligned with the four cardinal directions ( \"North\" , \"East\" , \"South\" , and \"West\" ). A robot is initially at cell (0, 0) facing direction \"East\" . The robot can be instructed to move for a specific number of steps . For each step, it does the following. After the robot finishes moving the number of steps required, it stops and awaits the next instruction. Implement the Robot class: Example 1:", + "description_images": [], + "constraints": [ + "Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\" .", + "void step(int num) Instructs the robot to move forward num steps.", + "int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y] .", + "String getDir() Returns the current direction of the robot, \"North\" , \"East\" , \"South\" , or \"West\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]Output[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]ExplanationRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and facesNorth(not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"", + "image": "https://assets.leetcode.com/uploads/2021/10/09/example-1.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 134 ms (Top 50.88%) | Memory: 98.9 MB (Top 12.28%)\nclass Robot {\n\n int p;\n int w;\n int h;\n public Robot(int width, int height) {\n w = width - 1;\n h = height - 1;\n p = 0;\n }\n\n public void step(int num) {\n p += num;\n }\n\n public int[] getPos() {\n int remain = p % (2 * (w + h));\n if (remain <= w)\n return new int[]{remain, 0};\n remain -= w;\n if (remain <= h)\n return new int[]{w, remain};\n remain -= h;\n if (remain <= w)\n return new int[]{w - remain, h};\n remain -= w;\n return new int[]{0, h - remain};\n }\n\n public String getDir() {\n int[] pos = getPos();\n if (p == 0 || pos[1] == 0 && pos[0] > 0)\n return \"East\";\n else if (pos[0] == w && pos[1] > 0)\n return \"North\";\n else if (pos[1] == h && pos[0] < w)\n return \"West\";\n else\n return \"South\";\n }\n}", + "title": "2069. Walking Robot Simulation II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1) . The grid is aligned with the four cardinal directions ( \"North\" , \"East\" , \"South\" , and \"West\" ). A robot is initially at cell (0, 0) facing direction \"East\" . The robot can be instructed to move for a specific number of steps . For each step, it does the following. After the robot finishes moving the number of steps required, it stops and awaits the next instruction. Implement the Robot class: Example 1:", + "description_images": [], + "constraints": [ + "Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\" .", + "void step(int num) Instructs the robot to move forward num steps.", + "int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y] .", + "String getDir() Returns the current direction of the robot, \"North\" , \"East\" , \"South\" , or \"West\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]Output[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]ExplanationRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and facesNorth(not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"", + "image": "https://assets.leetcode.com/uploads/2021/10/09/example-1.png" + } + ], + "follow_up": null, + "solution": "class Robot:\n\n def __init__(self, width: int, height: int):\n self.perimeter = 2*width + 2*(height - 2)\n self.pos = 0\n self.atStart = True\n\n self.bottomRight = width - 1\n self.topRight = self.bottomRight + (height - 1)\n self.topLeft = self.topRight + (width - 1)\n\n def step(self, num: int) -> None:\n self.atStart = False\n self.pos = (self.pos + num) % self.perimeter\n\n def getPos(self) -> List[int]:\n if 0 <= self.pos <= self.bottomRight:\n return [self.pos, 0]\n\n if self.bottomRight < self.pos <= self.topRight:\n return [self.bottomRight, self.pos - self.bottomRight]\n\n if self.topRight < self.pos <= self.topLeft:\n return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]\n \n return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]\n\n def getDir(self) -> str:\n if self.atStart or 0 < self.pos <= self.bottomRight:\n return 'East'\n\n if self.bottomRight < self.pos <= self.topRight:\n return 'North'\n\n if self.topRight < self.pos <= self.topLeft:\n return 'West'\n \n return 'Sout", + "title": "2069. Walking Robot Simulation II", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Fill any of the jugs with water.", + "Empty any of the jugs.", + "Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty." + ], + "examples": [ + { + "text": "Example 1: Input:jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4Output:trueExplanation:The famousDie Hardexample", + "image": null + }, + { + "text": "Example 2: Input:jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5Output:false", + "image": null + }, + { + "text": "Example 3: Input:jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static int gcd(int a,int b){\n if(b==0)return a;\n return gcd(b,a%b);\n }\n public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n if(targetCapacity>jug1Capacity+jug2Capacity){\n return false;\n }\n int g=gcd(jug1Capacity,jug2Capacity);\n return (targetCapacity%g==0);\n }\n}\n", + "title": "365. Water and Jug Problem", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs. If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end. Operations allowed: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Fill any of the jugs with water.", + "Empty any of the jugs.", + "Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty." + ], + "examples": [ + { + "text": "Example 1: Input:jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4Output:trueExplanation:The famousDie Hardexample", + "image": null + }, + { + "text": "Example 2: Input:jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5Output:false", + "image": null + }, + { + "text": "Example 3: Input:jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:\n n1, n2, t = jug1Capacity, jug2Capacity, targetCapacity\n if n1 == t or n2 == t or n1 + n2 == t:\n return True\n if n1 + n2 < t:\n return False\n if n1 < n2:\n n1, n2 = n2, n1\n stack = []\n visited = set()\n d = n1 - n2\n if d == t:\n return True\n while d > n2:\n d -= n2\n if d == t:\n return True\n stack.append(d)\n while stack:\n #print(stack)\n d = stack.pop()\n visited.add(d)\n n = n1 + d\n if n == t:\n return True\n n = n1 - d\n if n == t:\n return True\n while n > n2:\n n -= n2\n if n == t:\n return True\n if n < n2 and n not in visited:\n stack.append(n)\n n = n2 - d\n if n == t:\n return True\n if n not in visited:\n stack.append(n)\n return False\n", + "title": "365. Water and Jug Problem", + "topic": "Others" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange , return the maximum number of water bottles you can drink . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= numBottles <= 100", + "2 <= numExchange <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:numBottles = 9, numExchange = 3Output:13Explanation:You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_1_1875.png" + }, + { + "text": "Example 2: Input:numBottles = 15, numExchange = 4Output:19Explanation:You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_2_1875.png" + } + ], + "follow_up": null, + "solution": "// Runtime: 0 ms (Top 100.00%) | Memory: 41.6 MB (Top 8.35%)\nclass Solution {\n public int numWaterBottles(int numBottles, int numExchange) {\n int drinkedBottles = numBottles;\n int emptyBottles = numBottles;\n\n while(emptyBottles >= numExchange){\n int gainedBottles = emptyBottles / numExchange;\n\n drinkedBottles += gainedBottles;\n\n int unusedEmptyBottles = emptyBottles % numExchange;\n\n emptyBottles = gainedBottles + unusedEmptyBottles;\n }\n return drinkedBottles;\n }\n}", + "title": "1518. Water Bottles", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers numBottles and numExchange , return the maximum number of water bottles you can drink . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= numBottles <= 100", + "2 <= numExchange <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:numBottles = 9, numExchange = 3Output:13Explanation:You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_1_1875.png" + }, + { + "text": "Example 2: Input:numBottles = 15, numExchange = 4Output:19Explanation:You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.", + "image": "https://assets.leetcode.com/uploads/2020/07/01/sample_2_1875.png" + } + ], + "follow_up": null, + "solution": "class Solution:\n def numWaterBottles(self, a: int, b: int) -> int:\n \n def sol(a,b,e,res):\n if a!=0: res += a\n if (a+e)=plants[i]){\n c-=plants[i];\n count++;\n }\n else {\n c=capacity;\n count=count+i+(i+1);\n c-=plants[i];\n }\n }\n return count;\n }\n}\n", + "title": "2079. Watering Plants", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: You are initially at the river (i.e., x = -1 ). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Water the plants in order from left to right.", + "After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.", + "You cannot refill the watering can early." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacity = 5Output:14Explanation:Start at the river with a full watering can:\n- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.\n- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.\n- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).\n- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.\n- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).\n- Walk to plant 3 (4 steps) and water it.\nSteps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.", + "image": null + }, + { + "text": "Example 2: Input:plants = [1,1,1,4,2,3], capacity = 4Output:30Explanation:Start at the river with a full watering can:\n- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).\n- Water plant 3 (4 steps). Return to river (4 steps).\n- Water plant 4 (5 steps). Return to river (5 steps).\n- Water plant 5 (6 steps).\nSteps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.", + "image": null + }, + { + "text": "Example 3: Input:plants = [7,7,7,7,7,7,7], capacity = 8Output:49Explanation:You have to refill before watering each plant.\nSteps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 93 ms (Top 33.43%) | Memory: 14.1 MB (Top 44.38%)\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n result = 0\n curCap = capacity\n\n for i in range(len(plants)):\n if curCap >= plants[i]:\n curCap -= plants[i]\n result += 1\n\n else:\n result += i * 2 + 1\n curCap = capacity - plants[i]\n\n return result", + "title": "2079. Watering Plants", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full . They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Alice waters the plants in order from left to right , starting from the 0 th plant. Bob waters the plants in order from right to left , starting from the (n - 1) th plant. They begin watering the plants simultaneously .", + "It takes the same amount of time to water each plant regardless of how much water it needs.", + "Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.", + "In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacityA = 5, capacityB = 5Output:1Explanation:- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:plants = [2,2,3,3], capacityA = 3, capacityB = 4Output:2Explanation:- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.", + "image": null + }, + { + "text": "Example 3: Input:plants = [5], capacityA = 10, capacityB = 8Output:0Explanation:- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 4 ms (Top 96.18%) | Memory: 57.70 MB (Top 65.65%)\n\nclass Solution {\n public int minimumRefill(int[] p, int ca, int cb) { \n\t\n int refill= 0,oca = ca, ocb = cb;// let save our orginal capacity , needed to refill can again\n int i=0, j = p.length-1; // starting both end \n \n while(i<=j){\n\t\t\n if(i==j){// mean both at same position\n if(ca>=cb){\n if(p[i]>ca){\n refill++;\n } \n }\n else{ \n if(p[j]>cb){\n refill++; \n } \n }\n\t\t\t\t // no more plant left for watering so break loop \n break; \n }\n \n // first check if they have sufficient amount of water \n // if not then refill it with orginal capacity \n\t\t\t\n if(p[i]>ca){\n refill++;\n ca = oca;\n } \n if(p[j]>cb){\n refill++;\n cb= ocb;\n }\n \n\t\t\t// decrease consumed water \n ca-=p[i] ; \n cb-=p[j]; \n\t\t\t\n\t\t\t// move both \n\t\t\ti++; \n j--;\t\t\t \n }\n return refill; \n }\n}\n", + "title": "2105. Watering Plants II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the i th plant is located at x = i . Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full . They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the i th plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Alice waters the plants in order from left to right , starting from the 0 th plant. Bob waters the plants in order from right to left , starting from the (n - 1) th plant. They begin watering the plants simultaneously .", + "It takes the same amount of time to water each plant regardless of how much water it needs.", + "Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.", + "In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant." + ], + "examples": [ + { + "text": "Example 1: Input:plants = [2,2,3,3], capacityA = 5, capacityB = 5Output:1Explanation:- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.", + "image": null + }, + { + "text": "Example 2: Input:plants = [2,2,3,3], capacityA = 3, capacityB = 4Output:2Explanation:- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.", + "image": null + }, + { + "text": "Example 3: Input:plants = [5], capacityA = 10, capacityB = 8Output:0Explanation:- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 591 ms (Top 95.38%) | Memory: 31.60 MB (Top 92.31%)\n\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n canA, canB = capacityA, capacityB\n while lo < hi: \n if canA < plants[lo]: ans += 1; canA = capacityA\n canA -= plants[lo]\n if canB < plants[hi]: ans += 1; canB = capacityB\n canB -= plants[hi]\n lo, hi = lo+1, hi-1\n if lo == hi and max(canA, canB) < plants[lo]: ans += 1\n return ans \n", + "title": "2105. Watering Plants II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums . You can choose exactly one index ( 0-indexed ) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1] : An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choosing to remove index 1 results in nums = [6,7,4,1] .", + "Choosing to remove index 2 results in nums = [6,1,4,1] .", + "Choosing to remove index 4 results in nums = [6,1,7,4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,6,4]Output:1Explanation:Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:3Explanation:You can remove any index and the remaining array is fair.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:0Explanation:You cannot make a fair array after removing any index.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 5 ms (Top 97.91%) | Memory: 58.00 MB (Top 9.21%)\n\nclass Solution {\n public int waysToMakeFair(int[] nums) {\n int esum = 0; // Sum of even-indexed elements\n int osum = 0; // Sum of odd-indexed elements\n int n=nums.length;\n for (int i = 0; i < n; i++) {\n if (i % 2 == 0) {\n osum += nums[i];\n } else {\n esum += nums[i];\n }\n }\n int count = 0;\n int prev = 0;\n for (int i = 0; i < n; i++) {\n if (i % 2 == 0) {\n osum = osum - nums[i] + prev;\n } else {\n esum = esum - nums[i] + prev;\n }\n if (esum == osum) {\n count++;\n }\n prev = nums[i];\n }\n return count;\n }\n}\n\n", + "title": "1664. Ways to Make a Fair Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You are given an integer array nums . You can choose exactly one index ( 0-indexed ) and remove the element. Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1] : An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choosing to remove index 1 results in nums = [6,7,4,1] .", + "Choosing to remove index 2 results in nums = [6,1,4,1] .", + "Choosing to remove index 4 results in nums = [6,1,7,4] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,1,6,4]Output:1Explanation:Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,1,1]Output:3Explanation:You can remove any index and the remaining array is fair.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:0Explanation:You cannot make a fair array after removing any index.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n\tdef waysToMakeFair(self, nums: List[int]) -> int:\n\t\tif len(nums) == 1:\n\t\t\treturn 1\n\n\t\tif len(nums) == 2:\n\t\t\treturn 0\n\n\t\tprefixEven = sum(nums[2::2])\n\t\tprefixOdd = sum(nums[1::2])\n\t\tresult = 0\n\n\t\tif prefixEven == prefixOdd and len(set(nums)) == 1:\n\t\t\tresult += 1\n\n\t\tfor i in range(1,len(nums)):\n\t\t\tif i == 1:\n\t\t\t\tprefixOdd, prefixEven = prefixEven, prefixOdd \n\n\t\t\tif i > 1:\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tprefixEven -= nums[i-1]\n\t\t\t\t\tprefixEven += nums[i-2]\n\n\t\t\t\telse:\n\t\t\t\t\tprefixOdd -= nums[i-1]\n\t\t\t\t\tprefixOdd += nums[i-2]\n\n\t\t\tif prefixOdd == prefixEven:\n\t\t\t\tresult += 1\n\n\t\treturn result\n", + "title": "1664. Ways to Make a Fair Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "A split of an integer array is good if: Given nums , an array of non-negative integers, return the number of good ways to split nums . As the number may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The array is split into three non-empty contiguous subarrays - named left , mid , right respectively from left to right.", + "The sum of the elements in left is less than or equal to the sum of the elements in mid , and the sum of the elements in mid is less than or equal to the sum of the elements in right ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]Output:1Explanation:The only good way to split nums is [1] [1] [1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,5,0]Output:3Explanation:There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]Output:0Explanation:There is no good way to split nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int waysToSplit(int[] nums) {\n int size = nums.length;\n for (int i = 1; i < size; ++i) {\n nums[i] += nums[i - 1];\n }\n int res = 0;\n int mod = 1_000_000_007;\n for (int i = 0; i < size - 2; ++i) {\n int left = searchLeft(nums, i, size - 1);\n int right = searchRight(nums, i, size - 1);\n if (left == -1 || right == -1) {\n continue;\n }\n res = (res + right - left + 1) % mod;\n }\n return res;\n }\n \n private int searchLeft(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n hi = mi - 1;\n }\n }\n return pos;\n }\n \n private int searchRight(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n lo = mi + 1;\n }\n }\n return pos;\n }\n \n}\n", + "title": "1712. Ways to Split Array Into Three Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "A split of an integer array is good if: Given nums , an array of non-negative integers, return the number of good ways to split nums . As the number may be too large, return it modulo 10^9 + 7 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The array is split into three non-empty contiguous subarrays - named left , mid , right respectively from left to right.", + "The sum of the elements in left is less than or equal to the sum of the elements in mid , and the sum of the elements in mid is less than or equal to the sum of the elements in right ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1]Output:1Explanation:The only good way to split nums is [1] [1] [1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,2,2,5,0]Output:3Explanation:There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,2,1]Output:0Explanation:There is no good way to split nums.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 1271 ms (Top 38.4%) | Memory: 29.79 MB (Top 48.0%)\n\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007", + "title": "1712. Ways to Split Array Into Three Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the i th column at the top, or -1 if the ball gets stuck in the box . Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/26/ball.jpg" + ], + "constraints": [ + "A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1 .", + "A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1 ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]Output:[1,-1,-1,-1,-1]Explanation:This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.", + "image": null + }, + { + "text": "Example 2: Input:grid = [[-1]]Output:[-1]Explanation:The ball gets stuck against the left wall.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]Output:[0,1,2,3,4,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1 ms (Top 93.85%) | Memory: 54.4 MB (Top 47.92%)\nclass Solution {\n public int dfs(int[][] grid, int i, int j){\n if(i==grid.length)\n return j;\n\n if(j<0 || j>=grid[0].length)\n return -1;\n\n if(grid[i][j]==1 && j+1=0 && grid[i][j-1]==-1)\n return dfs(grid,i+1,j-1);\n\n return -1;\n }\n public int[] findBall(int[][] grid) {\n int m = grid[0].length;\n int[] ar = new int[m];\n\n for(int j=0;j List[int]:\n\n m,n=len(grid),len(grid[0])\n for i in range(m):\n grid[i].insert(0,1)\n grid[i].append(-1)\n res=[]\n\n for k in range(1,n+1):\n i , j = 0 , k\n struck = False\n while idiff){\n diff=arr[i]-arr[i-1];\n }\n }\n return diff;\n }\n}", + "title": "1637. Widest Vertical Area Between Two Points Containing No Points", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given n points on a 2D plane where points[i] = [x i , y i ] , Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == points.length", + "2 <= n <= 10^5", + "points[i].length == 2", + "0 <= x i , y i <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[8,7],[9,9],[7,4],[9,7]]Output:1Explanation:Both the red and the blue area are optimal.", + "image": "https://assets.leetcode.com/uploads/2020/09/19/points3.png" + }, + { + "text": "Example 2: Input:points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n # only taking x-axis point as it's relevant\n arr = [i[0] for i in points]\n \n arr.sort()\n \n diff = -1\n for i in range(1, len(arr)):\n diff = max(diff, arr[i] - arr[i - 1])\n \n return diff\n", + "title": "1637. Widest Vertical Area Between Two Points Containing No Points", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , reorder it such that nums[0] < nums[1] > nums[2] < nums[3]... . You may assume the input array always has a valid answer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5000", + "It is guaranteed that there will be an answer for the given input nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,1,1,6,4]Output:[1,6,1,5,1,4]Explanation:[1,4,1,5,1,6] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,2,3,1]Output:[2,3,1,3,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 7 ms (Top 77.52%) | Memory: 56 MB (Top 40.18%)\nclass Solution {\n public void wiggleSort(int[] nums) {\n int a[]=nums.clone();\n Arrays.sort(a);\n int left=(nums.length-1)/2;\n int right=nums.length-1;\n for(int i=0;i nums[2] < nums[3]... . You may assume the input array always has a valid answer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^4", + "0 <= nums[i] <= 5000", + "It is guaranteed that there will be an answer for the given input nums ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,1,1,6,4]Output:[1,6,1,5,1,4]Explanation:[1,4,1,5,1,6] is also accepted.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2,2,3,1]Output:[2,3,1,3,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Heap:\n\tdef __init__(self):\n\t\tself.q = []\n\tdef push(self,data):\n\t\ti = len(self.q)\n\t\tself.q.append(data)\n\t\twhile i>0:\n\t\t\tif self.q[i] > self.q[(i-1)//2]:\n\t\t\t\tself.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i]\n\t\t\t\ti = (i-1)//2\n\t\t\telse: return \n\tdef pop(self):\n\t\tif len(self.q)==0:return\n\t\tself.q[0] = self.q[-1]\n\t\tself.q.pop()\n\t\tdef heapify(i):\n\t\t\tind = i\n\t\t\tl = 2*i+1\n\t\t\tr = 2*i+2\n\t\t\tif r None:\n\t\tn = len(nums)\n\t\th = Heap()\n\t\tfor i in nums: h.push(i)\n\t\tfor i in range(1,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()\n\t\tfor i in range(0,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()", + "title": "324. Wiggle Sort II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums , return the length of the longest wiggle subsequence of nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.", + "In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,4,9,2,5]Output:6Explanation:The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,17,5,10,13,15,10,5,16,8]Output:7Explanation:There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 150 ms (Top 5.98%) | Memory: 74.5 MB (Top 5.03%)\nclass Solution {\n int n;\n int dp[][][];\n public int wiggleMaxLength(int[] nums) {\n n = nums.length;\n dp = new int[n][1005][2];\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int pos = f(0 , 0 , nums , -1);\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int neg = f(0 , 1 , nums , 1001);\n return Math.max(pos , neg);\n }\n int f(int i , int posPre , int a[] , int prev){\n if(i == n) return 0;\n if(dp[i][prev + 1][posPre] != -1) return dp[i][prev + 1][posPre];\n if(posPre == 0){\n int not = f(i + 1 , 0 , a , prev);\n int take = 0;\n if(a[i] - prev > 0){\n take = f(i + 1 , 1 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n else{\n int not = f(i + 1 , 1 , a , prev);\n int take = 0;\n if(a[i] - prev < 0){\n take = f(i + 1 , 0 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n }\n}", + "title": "376. Wiggle Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array nums , return the length of the longest wiggle subsequence of nums . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.", + "In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,4,9,2,5]Output:6Explanation:The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,17,5,10,13,15,10,5,16,8]Output:7Explanation:There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,4,5,6,7,8,9]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 47 ms (Top 48.8%) | Memory: 16.22 MB (Top 87.1%)\n\n#####################################################################################################################\n# Problem: Wiggle Subsequence\n# Solution : Dynamic Programming\n# Time Complexity : O(n) \n# Space Complexity : O(1)\n#####################################################################################################################\n\nclass Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n \n positive, negative = 1, 1\n \n if len(nums) < 2:\n return len(nums)\n \n for i in range(1, len(nums)):\n if nums[i] > nums[i - 1]:\n positive = negative + 1\n elif nums[i] < nums[i - 1]:\n negative = positive + 1\n \n return max(positive, negative)", + "title": "376. Wiggle Subsequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string ( s ) and a pattern ( p ), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "'?' Matches any single character.", + "'*' Matches any sequence of characters (including the empty sequence)." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aa\", p = \"a\"Output:falseExplanation:\"a\" does not match the entire string \"aa\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"aa\", p = \"*\"Output:trueExplanation:'*' matches any sequence.", + "image": null + }, + { + "text": "Example 3: Input:s = \"cb\", p = \"?a\"Output:falseExplanation:'?' matches 'c', but the second letter is 'a', which does not match 'b'.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 2 ms (Top 100.00%) | Memory: 42.3 MB (Top 99.02%)\nclass Solution {\n public boolean isMatch(String s, String p) {\n int i=0;\n int j=0;\n int starIdx=-1;\n int lastMatch=-1;\n\n while(i bool:\n m= len(s)\n n= len(p)\n\n dp = [[False]*(n+1) for i in range(m+1)]\n\n dp[0][0] = True\n\n for j in range(len(p)):\n if p[j] == \"*\":\n dp[0][j+1] = dp[0][j]\n\n for i in range(1,m+1):\n for j in range(1,n+1):\n if p[j-1] == \"*\":\n dp[i][j] = dp[i-1][j] or dp[i][j-1]\n\n elif s[i-1] == p[j-1] or p[j-1] == \"?\":\n dp[i][j] = dp[i-1][j-1]\n\n return dp[-1][-1]", + "title": "44. Wildcard Matching", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", wordDict = [\"leet\",\"code\"]Output:trueExplanation:Return true because \"leetcode\" can be segmented as \"leet code\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]Output:trueExplanation:Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 20 ms (Top 16.65%) | Memory: 47.4 MB (Top 24.65%)\nclass Solution {\n Mapmap= new HashMap<>();\n public boolean wordBreak(String s, List wordDict) {\n\n if(wordDict.contains(s)){\n return true;\n }\n if(map.containsKey(s)){\n return map.get(s);\n }\n for(int i=0;i bool:\n memo = {}\n\n\n def can_construct(target, strings_bank, memo): \n if target in memo:\n return memo[target]\n if target == \"\":\n return True\n for element in strings_bank: # for every element in our dict we check if we can start constructing the string \"s\"\n if element == target[0:len(element)]: # the remaining of the string \"s\" (which is the suffix) is the new target \n suffix = target[len(element):]\n if can_construct(suffix, strings_bank, memo):\n memo[target] = True\n return True\n memo[target] = False\n return False\n\n\n return can_construct(s, wordDict, memo)", + "title": "139. Word Break", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and a dictionary of strings wordDict , add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order . Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "1 <= wordDict.length <= 1000", + "1 <= wordDict[i].length <= 10", + "s and wordDict[i] consist of only lowercase English letters.", + "All the strings of wordDict are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]Output:[\"cats and dog\",\"cat sand dog\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]Output:[\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]Explanation:Note that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\tList res = new ArrayList<>();\n\tString s;\n\tint index = 0;\n\tSet set = new HashSet<>();\n public List wordBreak(String s, List wordDict) {\n this.s = s;\n\t\tfor (String word: wordDict) set.add(word);\n\t\tbacktrack(\"\");\n\t\treturn res;\n }\n\tpublic void backtrack(String sentence) {\n\t if (index == s.length()) {\n\t res.add(sentence.trim());\n\t return;\n }\n int indexCopy = index;\n for (int i = index + 1; i <= s.length(); i++) {\n\t String str = s.substring(index, i);\n\t if (set.contains(str)) {\n\t index = i;\n\t backtrack(sentence + \" \" + str);\n\t index = indexCopy;\n }\n }\n return;\n }\n}\n", + "title": "140. Word Break II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Given a string s and a dictionary of strings wordDict , add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order . Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 20", + "1 <= wordDict.length <= 1000", + "1 <= wordDict[i].length <= 10", + "s and wordDict[i] consist of only lowercase English letters.", + "All the strings of wordDict are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]Output:[\"cats and dog\",\"cat sand dog\"]", + "image": null + }, + { + "text": "Example 2: Input:s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]Output:[\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]Explanation:Note that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 56 ms (Top 49.21%) | Memory: 14 MB (Top 33.37%)\nclass Solution(object):\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: List[str]\n \"\"\"\n\n dic = defaultdict(list)\n for w in wordDict:\n dic[w[0]].append(w)\n result = []\n def recursion(idx , ans):\n if idx >= len(s):\n result.append(\" \".join(ans))\n return\n\n for w in dic[s[idx]]:\n if s[idx : idx+len(w)] == w:\n ans.append(w)\n recursion(idx+len(w), ans)\n ans.pop()\n\n return\n recursion(0, [])\n return result\n", + "title": "140. Word Break II", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: 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: Example 2:", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]Output:5Explanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]Output:0Explanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int ladderLength(String beginWord, String endWord, List wordList) {\n int count = 1;\n Set words = new HashSet<>(wordList);\n Queue q = new LinkedList();\n q.add(beginWord);\n \n while(!q.isEmpty()) {\n int size = q.size();\n \n while(size-- > 0) {\n String word = q.poll();\n char[] chList = word.toCharArray();\n \n for(int i=0; i s 1 -> s 2 -> ... -> s k such that: 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: Example 2:", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]Output:5Explanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]Output:0Explanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n e = defaultdict(list)\n m = len(beginWord)\n for word in wordList + [beginWord]:\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n e[w].append(word)\n q = deque([beginWord])\n used = set([beginWord])\n d = 0\n while q:\n d += 1\n for _ in range(len(q)):\n word = q.popleft()\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n if w in e:\n for v in e[w]:\n if v == endWord:\n return d + 1\n if v not in used:\n q.append(v)\n used.add(v)\n e.pop(w)\n return 0\n", + "title": "127. Word Ladder", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Given two words, beginWord and endWord , and a dictionary wordList , return all the shortest transformation sequences from beginWord to endWord , or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s 1 , s 2 , ..., s k ] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]Output:[[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]Explanation:There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]Output:[]Explanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> findLadders(String beginWord, String endWord, List wordList) {\n Set dict = new HashSet(wordList);\n if( !dict.contains(endWord) )\n return new ArrayList();\n \n // adjacent words for each word\n Map> adjacency = new HashMap();\n Queue queue = new LinkedList();\n // does path exist?\n boolean found = false;\n \n // BFS for shortest path, keep removing visited words\n queue.offer(beginWord);\n dict.remove(beginWord);\n \n while( !found && !queue.isEmpty() ) {\n int size = queue.size();\n // adjacent words in current level\n HashSet explored = new HashSet();\n\n while( size-- > 0 ) {\n String word = queue.poll();\n \n if( adjacency.containsKey(word) )\n continue;\n \n // remove current word from dict, and search for adjacent words\n dict.remove(word);\n List adjacents = getAdjacents(word, dict);\n adjacency.put(word, adjacents);\n\n for(String adj : adjacents) {\n if( !found && adj.equals(endWord) ) \n found = true;\n \n explored.add(adj);\n queue.offer(adj);\n }\n }\n // remove words explored in current level from dict\n for(String word : explored)\n dict.remove(word);\n }\n\n // if a path exist, dfs to find all the paths\n if( found ) \n return dfs(beginWord, endWord, adjacency, new HashMap());\n else\n return new ArrayList();\n }\n \n private List getAdjacents(String word, Set dict) {\n List adjs = new ArrayList();\n char[] wordChars = word.toCharArray();\n \n for(int i=0; i> dfs(String src, String dest, \n Map> adjacency, \n Map>> memo) {\n if( memo.containsKey(src) )\n return memo.get(src);\n \n List> paths = new ArrayList();\n \n\t\t// reached dest? return list with dest word\n if( src.equals( dest ) ) {\n paths.add( new ArrayList(){{ add(dest); }} );\n return paths;\n }\n\n\t\t// no adjacent for curr word? return empty list\n List adjacents = adjacency.get(src);\n if( adjacents == null || adjacents.isEmpty() )\n return paths;\n\n for(String adj : adjacents) {\n List> adjPaths = dfs(adj, dest, adjacency, memo);\n \n for(List path : adjPaths) {\n if( path.isEmpty() ) continue;\n \n List newPath = new ArrayList(){{ add(src); }};\n newPath.addAll(path);\n \n paths.add(newPath);\n }\n } \n memo.put(src, paths);\n return paths;\n }\n}\n", + "title": "126. Word Ladder II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "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: Given two words, beginWord and endWord , and a dictionary wordList , return all the shortest transformation sequences from beginWord to endWord , or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s 1 , s 2 , ..., s k ] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]Output:[[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]Explanation:There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]Output:[]Explanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 80 ms (Top 72.71%) | Memory: 14.5 MB (Top 54.17%)\nclass Solution:\n\n WILDCARD = \".\"\n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \"\"\"\n Given a wordlist, we perform BFS traversal to generate a word tree where\n every node points to its parent node.\n\n Then we perform a DFS traversal on this tree starting at the endWord.\n \"\"\"\n if endWord not in wordList:\n # end word is unreachable\n return []\n\n # first generate a word tree from the wordlist\n word_tree = self.getWordTree(beginWord, endWord, wordList)\n\n # then generate a word ladder from the word tree\n return self.getLadders(beginWord, endWord, word_tree)\n\n def getWordTree(self,\n beginWord: str,\n endWord: str,\n wordList: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n BFS traversal from begin word until end word is encountered.\n\n This functions constructs a tree in reverse, starting at the endWord.\n \"\"\"\n # Build an adjacency list using patterns as keys\n # For example: \".it\" -> (\"hit\"), \"h.t\" -> (\"hit\"), \"hi.\" -> (\"hit\")\n adjacency_list = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n adjacency_list[pattern].append(word)\n\n # Holds the tree of words in reverse order\n # The key is an encountered word.\n # The value is a list of preceding words.\n # For example, we got to beginWord from no other nodes.\n # {a: [b,c]} means we got to \"a\" from \"b\" and \"c\"\n visited_tree = {beginWord: []}\n\n # start off the traversal without finding the word\n found = False\n\n q = deque([beginWord])\n while q and not found:\n n = len(q)\n\n # keep track of words visited at this level of BFS\n visited_this_level = {}\n\n for i in range(n):\n word = q.popleft()\n\n for i in range(len(word)):\n # for each pattern of the current word\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n for next_word in adjacency_list[pattern]:\n if next_word == endWord:\n # we don't return immediately because other\n # sequences might reach the endWord in the same\n # BFS level\n found = True\n if next_word not in visited_tree:\n if next_word not in visited_this_level:\n visited_this_level[next_word] = [word]\n # queue up next word iff we haven't visited it yet\n # or already are planning to visit it\n q.append(next_word)\n else:\n visited_this_level[next_word].append(word)\n\n # add all seen words at this level to the global visited tree\n visited_tree.update(visited_this_level)\n\n return visited_tree\n\n def getLadders(self,\n beginWord: str,\n endWord: str,\n wordTree: Dict[str, List[str]]) -> List[List[str]]:\n \"\"\"\n DFS traversal from endWord to beginWord in a given tree.\n \"\"\"\n def dfs(node: str) -> List[List[str]]:\n if node == beginWord:\n return [[beginWord]]\n if node not in wordTree:\n return []\n\n res = []\n parents = wordTree[node]\n for parent in parents:\n res += dfs(parent)\n for r in res:\n r.append(node)\n return res\n\n return dfs(endWord)", + "title": "126. Word Ladder II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a pattern and a string s , find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= pattern.length <= 300", + "pattern contains only lower-case English letters.", + "1 <= s.length <= 3000", + "s contains only lowercase English letters and spaces ' ' .", + "s does not contain any leading or trailing spaces.", + "All the words in s are separated by a single space ." + ], + "examples": [ + { + "text": "Example 1: Input:pattern = \"abba\", s = \"dog cat cat dog\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:pattern = \"abba\", s = \"dog cat cat fish\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:pattern = \"aaaa\", s = \"dog cat cat dog\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean wordPattern(String pattern, String s) {\n String[] arr=s.split(\" \");\n if(pattern.length()!=arr.length) return false;\n Map map=new HashMap();\n \n for(int i=0;i=board.length || cd>=board[0].length\n || vis[rd][cd]==true ||\n board[rd][cd]!=word.charAt(idx)) continue;\n boolean is=isexist(rd,cd,board,vis,idx+1,word);\n if(is) return true;\n }\n vis[r][c]=false;\n return false;\n }\n}", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word2.jpg" + }, + { + "text": "Example 2: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg" + }, + { + "text": "Example 3: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/15/word3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n m = len(board)\n n = len(board[0])\n \n marked = set() # visited by the dfs\n def dfs(cell: Tuple[int, int], wp: int) -> bool:\n i = cell[0]\n j = cell[1]\n \n if wp == len(word):\n return True\n \n # Get appropriate neighbours and perform dfs on them\n # When going on dfs, we mark certain cells, we should remove # \n #them from the marked list after we return from the dfs\n marked.add((i,j))\n neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]\n for x, y in neibs:\n if (\n x < 0 or y < 0 or\n x >= m or y >= n or\n (x, y) in marked or\n board[x][y] != word[wp]\n ):\n continue\n \n if dfs((x,y), wp + 1):\n return True\n \n marked.remove((i,j))\n return False\n \n \n for i in range(m):\n for j in range(n):\n if board[i][j] == word[0]:\n if dfs((i,j), 1):\n return True\n \n return False\n", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: 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\"]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" + }, + { + "text": "Example 2: Input:board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]Output:[]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n class TrieNode {\n Map children = new HashMap();\n boolean word = false;\n public TrieNode() {}\n }\n \n int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};\n \n public List findWords(char[][] board, String[] words) {\n Set res = new HashSet<>();\n TrieNode root = new TrieNode();\n int m = board.length;\n int n = board[0].length;\n \n for(String word : words){\n char[] cArr = word.toCharArray();\n TrieNode dummy = root;\n \n for(char c : cArr){\n if(!dummy.children.containsKey(c)){\n dummy.children.put(c, new TrieNode());\n }\n dummy = dummy.children.get(c);\n }\n \n dummy.word = true;\n }\n \n for(int i=0; i(res);\n }\n \n Set dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word){\n Set res = new HashSet<>();\n \n if(root.word){\n res.add(word);\n root.word = false;\n }\n \n visited[i][j] = true;\n \n for(int[] dir : dirs){\n int newI = i + dir[0];\n int newJ = j + dir[1];\n \n if(newI>=0 && newI=0 && newJ List[str]:\n solution = set()\n trie = self.make_trie(words)\n visited = set()\n for i in range(len(board)):\n for j in range(len(board[0])):\n self.dfs(i,j,board,trie,visited,\"\",solution)\n return solution\n \n def dfs(self,i,j,board,trie,visited,word,solution):\n if \"*\" in trie:\n if len(trie.keys()) == 0:\n return\n else:\n solution.add(word)\n del trie[\"*\"]\n if (i,j) in visited:\n return\n if (i < 0 or i == len(board) or j < 0 or j == len(board[0])):\n return\n if board[i][j] not in trie:\n return\n if len(trie[board[i][j]]) == 0:\n del trie[board[i][j]]\n return\n visited.add((i,j))\n neighbours = [(i,j-1),(i-1,j),(i,j+1),(i+1,j)]\n for n_x,n_y in neighbours:\n self.dfs(n_x,n_y,board,trie[board[i][j]],visited,word+board[i][j],solution) \n visited.remove((i,j))\n \n def make_trie(self,words):\n trie = {}\n for word in words:\n current = trie\n for char in word:\n if char not in current:\n current[char] = {}\n current = current[char]\n current[\"*\"] = \"*\"\n return trie\n\n", + "title": "212. Word Search II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two string arrays words1 and words2 . A string b is a subset of string a if every letter in b occurs in a including multiplicity. A string a from words1 is universal if for every string b in words2 , b is a subset of a . Return an array of all the universal strings in words1 . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\" ." + ], + "examples": [ + { + "text": "Example 1: Input:words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]Output:[\"facebook\",\"google\",\"leetcode\"]", + "image": null + }, + { + "text": "Example 2: Input:words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]Output:[\"apple\",\"google\",\"leetcode\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List wordSubsets(String[] words1, String[] words2) {\n List list=new ArrayList<>();\n int[] bmax=count(\"\");\n for(String w2:words2)\n {\n int[] b=count(w2);\n for(int i=0;i<26;i++)\n {\n bmax[i]=Math.max(bmax[i],b[i]);\n }\n }\n for(String w1:words1)\n {\n int[] a=count(w1);\n for(int i=0;i<26;i++)\n {\n if(a[i] List[str]:\n freq = [0]*26 \n \n for w in B: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n for i in range(26): freq[i] = max(freq[i], temp[i])\n \n ans = []\n for w in A: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n if all(freq[i] <= temp[i] for i in range(26)): ans.append(w)\n return ans ", + "title": "916. Word Subsets", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each group has exactly X cards.", + "All the cards in each group have the same integer." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [1,2,3,4,4,3,2,1]Output:trueExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1,1,2,2,2,3,3]Output:falseExplanation: No possible partition.", + "image": null + } + ], + "follow_up": null, + "solution": "// X of a Kind in a Deck of Cards\n// Leetcode problem : https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/\n\nclass Solution {\n public boolean hasGroupsSizeX(int[] deck) {\n int[] count = new int[10000];\n for(int i : deck)\n count[i]++;\n int gcd = 0;\n for(int i : count)\n if(i != 0)\n gcd = gcd == 0 ? i : gcd(gcd, i);\n return gcd >= 2; \n }\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}\n", + "title": "914. X of a Kind in a Deck of Cards", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each group has exactly X cards.", + "All the cards in each group have the same integer." + ], + "examples": [ + { + "text": "Example 1: Input:deck = [1,2,3,4,4,3,2,1]Output:trueExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].", + "image": null + }, + { + "text": "Example 2: Input:deck = [1,1,1,2,2,2,3,3]Output:falseExplanation: No possible partition.", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 130 ms (Top 52.6%) | Memory: 16.56 MB (Top 64.6%)\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n \n f=defaultdict(int)\n \n for j in deck:\n f[j]+=1\n \n \n import math\n \n u=list(f.values())\n \n g=u[0]\n \n for j in range(1,len(u)):\n g=math.gcd(g,u[j])\n return g!=1\n \n ", + "title": "914. X of a Kind in a Deck of Cards", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer n and an integer start . Define an array nums where nums[i] = start + 2 * i ( 0-indexed ) and n == nums.length . Return the bitwise XOR of all elements of nums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000", + "0 <= start <= 1000", + "n == nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, start = 0Output:8Explanation:Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.", + "image": null + }, + { + "text": "Example 2: Input:n = 4, start = 3Output:8Explanation:Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int xorOperation(int n, int start) {\n int nums[]=new int[n];\n for(int i=0;i int:\n nums = [start + 2*i for i in range(n)] #generate list of numbers\n ans = nums[0]\n for i in range(1,n):\n ans = ans^nums[i] # XOR operation\n return ans\n \n \n", + "title": "1486. XOR Operation in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [left i, right i ] . For each query i compute the XOR of elements from left i to right i (that is, arr[left i ] XOR arr[left i + 1] XOR ... XOR arr[right i ] ). Return an array answer where answer[i] is the answer to the i th query. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length, queries.length <= 3 * 10^4", + "1 <= arr[i] <= 10^9", + "queries[i].length == 2", + "0 <= left i <= right i < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]Output:[2,7,14,8]Explanation:The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]Output:[8,0,4,4]", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 748 ms (Top 12.05%) | Memory: 68.5 MB (Top 10.97%)\nclass Solution\n{\n public int[] xorQueries(int[] arr, int[][] queries)\n {\n int[] ans = new int[queries.length];\n int[] xor = new int[arr.length];\n xor[0] = arr[0];\n // computing prefix XOR of arr\n for(int i = 1; i < arr.length; i++)\n {\n xor[i] = arr[i] ^ xor[i-1];\n }\n for(int i = 0; i < queries.length; i++)\n {\n // if query starts from something other than 0 (say i), then we XOR all values from arr[0] to arr[i-1]\n if(queries[i][0] != 0)\n {\n ans[i] = xor[queries[i][1]];\n for(int j = 0; j < queries[i][0]; j++)\n {\n ans[i] = arr[j] ^ ans[i];\n }\n }\n // if start of query is 0, then we striaght up use the prefix XOR till ith element\n else\n ans[i] = xor[queries[i][1]];\n }\n return ans;\n }\n}", + "title": "1310. XOR Queries of a Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [left i, right i ] . For each query i compute the XOR of elements from left i to right i (that is, arr[left i ] XOR arr[left i + 1] XOR ... XOR arr[right i ] ). Return an array answer where answer[i] is the answer to the i th query. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= arr.length, queries.length <= 3 * 10^4", + "1 <= arr[i] <= 10^9", + "queries[i].length == 2", + "0 <= left i <= right i < arr.length" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]Output:[2,7,14,8]Explanation:The binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8", + "image": null + }, + { + "text": "Example 2: Input:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]Output:[8,0,4,4]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n\n\n \"\"\"\n\n arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\n\n find pref xor of arr\n\n pref = [x,x,x,x]\n\n for each query find the left and right indices\n the xor for range (l, r) would be pref[r] xor pref[l-1]\n \n \"\"\" \n n, m = len(queries), len(arr)\n\n answer = [1]*n\n\n pref = [1]*m\n pref[0] = arr[0]\n if m > 1:\n for i in range(1,m):\n pref[i] = pref[i-1] ^ arr[i]\n\n for (i, (l,r)) in enumerate(queries):\n if l == 0: answer[i] = pref[r] \n else: answer[i] = pref[r] ^ pref[l-1]\n\n return answer", + "title": "1310. XOR Queries of a Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3Output:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4Output:\"PINALSIGYAHRPI\"Explanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1Output:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convert(String s, int numRows) {\n if (numRows==1)return s;\n StringBuilder builder = new StringBuilder();\n for (int i=1;i<=numRows;i++){\n int ind = i-1;\n boolean up = true;\n while (ind < s.length()){\n builder.append(s.charAt(ind));\n if (i==1){\n ind += 2*(numRows-i);\n } else if (i==numRows){\n ind += 2*(i-1);\n } else {\n ind += up ? 2*(numRows-i) : 2*(i-1);\n up=!up;\n }\n }\n }\n return builder.toString();\n }\n}\n", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3Output:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4Output:\"PINALSIGYAHRPI\"Explanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1Output:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "# Runtime: 96 ms (Top 61.23%) | Memory: 14 MB (Top 75.15%)\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n\n # safety check to not process single row\n if numRows == 1:\n return s\n\n # safety check to not process strings shorter/equal than numRows\n if len(s) <= numRows:\n return s\n\n # safety check to not process double rows\n if numRows == 2:\n # slice every other character\n return s[0::2] + s[1::2]\n\n # list that stores the lines\n # add lines with initial letters\n lines: list[str] = [letter for letter in s[:numRows]]\n\n # positive direction goes down\n # lines are created, so it's going up\n direction: int = -1\n\n # track the position at which the letter will be added\n # position after bouncing off, after adding initial lines\n line_index: int = numRows - 2\n\n # edge indexes\n # 0 can only be reached by going up\n # numRows only by going down\n edges: set[int] = {0, numRows}\n\n for letter in s[numRows:]:\n # add letter at tracked index position\n lines[line_index] += letter\n\n # prepare index before next loop iteration\n line_index += direction\n\n # reaching one of the edges\n if line_index in edges:\n # change direction\n direction = -direction\n # bounce off if bottom edge\n if line_index == numRows:\n line_index += direction * 2\n\n return \"\".join(lines)", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R' , yellow 'Y' , blue 'B' , green 'G' , or white 'W' . You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Given a string board , representing the row of balls on the board, and a string hand , representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.", + "If there is a group of three or more consecutive balls of the same color , remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If there are no more balls on the board, then you win the game.", + "Repeat this process until you either win or do not have any more balls in your hand." + ], + "examples": [ + { + "text": "Example 1: Input:board = \"WRRBBW\", hand = \"RB\"Output:-1Explanation:It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.", + "image": null + }, + { + "text": "Example 2: Input:board = \"WWRRBBWW\", hand = \"WRBRW\"Output:2Explanation:To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW ->WWWW-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + }, + { + "text": "Example 3: Input:board = \"G\", hand = \"GGGGG\"Output:2Explanation:To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG.GGG-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + } + ], + "follow_up": null, + "solution": "// Runtime: 1091 ms (Top 50.54%) | Memory: 147.1 MB (Top 58.06%)\nclass Solution {\n static class Hand {\n int red;\n int yellow;\n int green;\n int blue;\n int white;\n\n Hand(String hand) {\n // add an extra character, because .split() throws away trailing empty strings\n String splitter = hand + \"x\";\n red = splitter.split(\"R\").length - 1;\n yellow = splitter.split(\"Y\").length - 1;\n green = splitter.split(\"G\").length - 1;\n blue = splitter.split(\"B\").length - 1;\n white = splitter.split(\"W\").length - 1;\n }\n Hand(Hand hand) {\n red = hand.red;\n yellow = hand.yellow;\n blue = hand.blue;\n green = hand.green;\n white = hand.white;\n }\n boolean isEmpty() {\n return red == 0 && yellow == 0 && green == 0 && blue == 0 && white == 0;\n }\n List colors() {\n List res = new ArrayList<>();\n if(red > 0) res.add(\"R\");\n if(yellow > 0) res.add(\"Y\");\n if(green > 0) res.add(\"G\");\n if(blue > 0) res.add(\"B\");\n if(white > 0) res.add(\"W\");\n return res;\n }\n void removeColor(String color) {\n switch(color) {\n case \"R\":\n red--;\n break;\n case \"Y\":\n yellow--;\n break;\n case \"G\":\n green--;\n break;\n case \"B\":\n blue--;\n break;\n case \"W\":\n white--;\n break;\n }\n }\n public StringBuilder buildStringWithColon() {\n return new StringBuilder().append(red)\n .append(\",\")\n .append(yellow)\n .append(\",\")\n .append(green)\n .append(\",\")\n .append(blue)\n .append(\",\")\n .append(white)\n .append(\":\");\n }\n }\n\n /** key = hand + \":\" + board */\n private final Map boardHandToMinStep = new HashMap<>();\n\n /**\n store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n for each color in your hand:\n try to insert the color in each *effective* location\n - effective location means \"one preceding a same-color set of balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n resolve the board\n if inserting to that location finishes the game, return 1\n otherwise, recur to the resulting hand\n minstep for this setup == minimum of all resulting hands + 1\n memoize this minstep, then return it\n */\n public int findMinStep(String board, String hand) {\n // store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n Hand h = new Hand(hand);\n return findMinStep(board, h, 9999);\n }\n\n private int findMinStep(String board, Hand hand, int remainingDepth) {\n // resolve board, i.e. remove triples and higher\n board = resolve(board);\n final String key = hand.buildStringWithColon().append(board).toString();\n if(board.length() == 0) {\n return 0;\n } else if(boardHandToMinStep.containsKey(key)) {\n return boardHandToMinStep.get(key);\n }\n\n // OPTIMIZATION #3 - reduced time by 25%\n // don't go deeper than the deepest known solution - 1\n if (remainingDepth <= 0\n // OPTIMIZATION #2 - lowered from 1min to 4sec reduced time by 93%\n // for each color in the board, if there are ever fewer than three of that color in the board and hand combined, fast fail\n || !canWin(board, hand)) {\n boardHandToMinStep.put(key, -1);\n return -1;\n }\n\n int minStep = -1;\n // for each color in your hand:\n for(String color : hand.colors()) {\n // Store a new \"next hand\" and remove the color\n Hand nextHand = new Hand(hand);\n nextHand.removeColor(color);\n // for each *effective* insert location\n // - effective location means \"one preceding same-color ball(s)\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n for(int loc : effectiveLocations(color, board, nextHand.isEmpty())) {\n // insert the color and store as \"next board\"\n String nextBoard = board.substring(0, loc) + color + board.substring(loc);\n // recur to the resulting hand\n int childMinStep = findMinStep(nextBoard, nextHand, minStep == -1 ? remainingDepth - 1 : minStep - 2);\n if(childMinStep != -1) {\n // minstep for this setup == minimum of all resulting hands + 1\n minStep = minStep == -1 ? (1 + childMinStep) : Math.min(minStep, 1 + childMinStep);\n }\n }\n }\n // memoize this minstep, then return it\n boardHandToMinStep.put(key, minStep);\n return minStep;\n }\n\n private boolean canWin(String board, Hand hand) {\n String splitter = board + \"x\";\n int red = splitter.split(\"R\").length - 1;\n int yellow = splitter.split(\"Y\").length - 1;\n int green = splitter.split(\"G\").length - 1;\n int blue = splitter.split(\"B\").length - 1;\n int white = splitter.split(\"W\").length - 1;\n\n return (red == 0 || red + hand.red > 2)\n && (yellow == 0 || yellow + hand.yellow > 2)\n && (green == 0 || green + hand.green > 2)\n && (blue == 0 || blue + hand.blue > 2)\n && (white == 0 || white + hand.white > 2);\n }\n\n /**\n * effective location means \"one preceding a same-color set of 1 or more balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n * ^^ The above first pass is incorrect. Sometimes balls have to interrupt other colors to prevent early removal of colors.\n *\n * effective location means \"all locations except after a same-color ball\"\n *\n */\n private List effectiveLocations(String color, String board, boolean isLastInHand) {\n List res = new ArrayList<>();\n\n // OPTIMIZATION #4 - prefer greedy locations by adding them in this order: - reduced time by 93%\n // - preceding 2 of the same color\n // - preceding exactly 1 of the same color\n // - neighboring 0 of the same color\n List greedy2 = new ArrayList<>();\n List greedy3 = new ArrayList<>();\n\n // Preceding 2 of the same color:\n for (int i = 0; i <= board.length(); i++) {\n if (i < board.length() - 1 && board.substring(i, i + 2).equals(color + color)) {\n res.add(i);\n // skip the next 2 locations; they would be part of the same consecutive set of \"this\" color\n i+=2;\n } else if(i < board.length() && board.substring(i,i+1).equals(color)) {\n greedy2.add(i);\n // skip the next 1 location; it would be part of the same consecutive set of \"this\" color\n i++;\n } else {\n // OPTIMIZATION #5 - if a ball is not next to one of the same color, it must be between two identical, of a different color - 10s to .8s\n// greedy3.add(i);\n if(i > 0 && board.length() > i && board.substring(i-1, i).equals(board.substring(i, i+1))) {\n greedy3.add(i);\n }\n }\n }\n // OPTIMIZATION #1 - reduced time by 90%\n // if this is the last one in the hand, then it MUST be added to 2 others of the same color\n if(isLastInHand) {\n return res;\n }\n res.addAll(greedy2);\n res.addAll(greedy3);\n return res;\n }\n\n /**\n * repeatedly collapse sets of 3 or more\n */\n private String resolve(String board) {\n String copy = \"\";\n while(!board.equals(copy)) {\n copy = board;\n // min 3 in a row\n board = copy.replaceFirst(\"(.)\\\\1\\\\1+\", \"\");\n }\n return board;\n }\n}", + "title": "488. Zuma Game", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "python", + "description": "You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R' , yellow 'Y' , blue 'B' , green 'G' , or white 'W' . You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Given a string board , representing the row of balls on the board, and a string hand , representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.", + "If there is a group of three or more consecutive balls of the same color , remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.", + "If there are no more balls on the board, then you win the game.", + "Repeat this process until you either win or do not have any more balls in your hand." + ], + "examples": [ + { + "text": "Example 1: Input:board = \"WRRBBW\", hand = \"RB\"Output:-1Explanation:It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.", + "image": null + }, + { + "text": "Example 2: Input:board = \"WWRRBBWW\", hand = \"WRBRW\"Output:2Explanation:To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW ->WWWW-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + }, + { + "text": "Example 3: Input:board = \"G\", hand = \"GGGGG\"Output:2Explanation:To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG.GGG-> empty.\n2 balls from your hand were needed to clear the board.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \n # start from i and remove continues ball\n def remove_same(s, i):\n if i < 0:\n return s\n \n left = right = i\n while left > 0 and s[left-1] == s[i]:\n left -= 1\n while right+1 < len(s) and s[right+1] == s[i]:\n right += 1\n \n length = right - left + 1\n if length >= 3:\n new_s = s[:left] + s[right+1:]\n return remove_same(new_s, left-1)\n else:\n return s\n\n\n\n hand = \"\".join(sorted(hand))\n\n # board, hand and step\n q = collections.deque([(board, hand, 0)])\n visited = set([(board, hand)])\n\n while q:\n curr_board, curr_hand, step = q.popleft()\n for i in range(len(curr_board)+1):\n for j in range(len(curr_hand)):\n # skip the continue balls in hand\n if j > 0 and curr_hand[j] == curr_hand[j-1]:\n continue\n \n # only insert at the begin of continue balls in board\n if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color\n continue\n \n pick = False\n # 1. same color with right\n # 2. left and right are same but pick is different\n if i < len(curr_board) and curr_board[i] == curr_hand[j]:\n pick = True\n if 0 None:\n with self.cv:\n self.cv.wait_for(lambda : -2 <= self.sum <= 1)\n self.sum += 1\n releaseHydrogen()\n self.cv.notifyAll()\n\n def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:\n with self.cv:\n self.cv.wait_for(lambda : 0 <= self.sum <= 2)\n self.sum -= 2\n releaseOxygen()\n self.cv.notifyAll()", + "title": "1117. Building H2O", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz , buzz , fizzbuzz and number . The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, \"fizz\", 4, \"buzz\", ...] where the i th token ( 1-indexed ) of the series is: Implement the FizzBuzz class: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "printFizz that prints the word \"fizz\" to the console,", + "printBuzz that prints the word \"buzz\" to the console,", + "printFizzBuzz that prints the word \"fizzbuzz\" to the console, and", + "printNumber that prints a given integer to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 15Output:[1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[1,2,\"fizz\",4,\"buzz\"]", + "image": null + } + ], + "follow_up": null, + "solution": "import threading\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.fz = threading.Semaphore(0)\n self.bz = threading.Semaphore(0)\n self.fzbz = threading.Semaphore(0)\n self.num = threading.Semaphore(1)\n\n def fizz(self, printFizz):\n for i in range(self.n/3-self.n/15):\n self.fz.acquire()\n printFizz()\n self.num.release()\n\n def buzz(self, printBuzz):\n for i in range(self.n/5-self.n/15):\n self.bz.acquire()\n printBuzz()\n self.num.release()\n\n def fizzbuzz(self, printFizzBuzz):\n for i in range(self.n/15):\n self.fzbz.acquire()\n printFizzBuzz()\n self.num.release()\n \n def number(self, printNumber):\n for i in range(1, self.n+1):\n self.num.acquire()\n if i%3==0 and i%5 ==0:\n self.fzbz.release()\n elif i%3==0:\n self.fz.release()\n elif i%5==0:\n self.bz.release()\n else:\n printNumber(i)\n self.num.release()\n \n", + "title": "1195. Fizz Buzz Multithreaded", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose you are given the following code: The same instance of FooBar will be passed to two different threads: Modify the given program to output \"foobar\" n times. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "thread A will call foo() , while", + "thread B will call bar() ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:\"foobar\"Explanation:There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n\"foobar\" is being output 1 time.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:\"foobarfoobar\"Explanation:\"foobar\" is being output 2 times.", + "image": null + }, + { + "text": "class FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n self.bar_lock.acquire()\n\n\n def foo(self, printFoo: 'Callable[[], None]') -> None:\n for i in range(self.n):\n self.foo_lock.acquire()\n # printFoo() outputs \"foo\". Do not change or remove this line.\n printFoo()\n self.bar_lock.release()\n\n\n def bar(self, printBar: 'Callable[[], None]') -> None:\n for i in range(self.n):\n self.bar_lock.acquire()\n # printBar() outputs \"bar\". Do not change or remove this line.\n printBar()\n self.foo_lock.release()\n", + "title": "1115. Print FooBar Alternately", + "topic": "Concurrency" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Suppose we have a class: The same instance of Foo will be passed to three different threads. Thread A will call first() , thread B will call second() , and thread C will call third() . Design a mechanism and modify the program to ensure that second() is executed after first() , and third() is executed after second() . Note: We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "nums is a permutation of [1, 2, 3] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:\"firstsecondthird\"Explanation:There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). \"firstsecondthird\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,2]Output:\"firstsecondthird\"Explanation:The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). \"firstsecondthird\" is the correct output.", + "image": null + }, + { + "text": "public class Foo {\n public void first() { print(\"first\"); }\n public void second() { print(\"second\"); }\n public void third() { print(\"third\"); }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "import threading\n\nclass Foo:\n def __init__(self):\n\t\t# create lock to control sequence between first and second functions\n self.lock1 = threading.Lock()\n\t\tself.lock1.acquire()\n\t\t\n\t\t# create another lock to control sequence between second and third functions\n self.lock2 = threading.Lock()\n self.lock2.acquire()\n\n def first(self, printFirst: 'Callable[[], None]') -> None:\n printFirst()\n\t\t\n\t\t# since second function is waiting for the lock1, let's release it\n self.lock1.release()\n\n def second(self, printSecond: 'Callable[[], None]') -> None:\n\t\t# wait for first funtion to finish\n self.lock1.acquire()\n \n\t\tprintSecond()\n\t\t\n\t\t# let's release lock2, so third function can run\n self.lock2.release()\n\n def third(self, printThird: 'Callable[[], None]') -> None:\n\t\t# wait for second funtion to finish\n self.lock2.acquire()\n\t\t\n printThird()\n", + "title": "1114. Print in Order", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "python", + "description": "You have a function printNumber that can be called with an integer parameter and prints it to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero , even , and odd . The same instance of ZeroEvenOdd will be passed to three different threads: Modify the given class to output the series \"010203040506...\" where the length of the series must be 2n . Implement the ZeroEvenOdd class: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, calling printNumber(7) prints 7 to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:\"0102\"Explanation:There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n\"0102\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:\"0102030405\"", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Semaphore\nclass ZeroEvenOdd:\n def __init__(self, n):\n self.n = n\n self.semOdd = Semaphore(0) # Permission to write an Odd Number\n self.semEven = Semaphore(0) # Permission to write an Even Number\n self.semZero = Semaphore(1) # Permission to write a Zero\n\t# printNumber(x) outputs \"x\", where x is an integer.\n def zero(self, printNumber):\n for i in range(1,self.n+1):\n # A) Request Permission to Write a Zero\n self.semZero.acquire()\n printNumber(0)\n # B) Check if \"i\" if Odd or Even, and give permission to write the number\n if i&1:\n self.semOdd.release()\n else:\n self.semEven.release()\n # C) Permission to write a zero is returned by another Thread ( release triggers a change)\n def even(self, printNumber):\n # A) Iterate only through Even numbers\n for i in range(2,self.n+1,2):\n # B) Request Permission to Write Current Number\n self.semEven.acquire()\n printNumber(i)\n # C) Return Permission to Write a Zero (if applicable)\n self.semZero.release()\n def odd(self, printNumber):\n # A) Iterate only through Odd numbers\n for i in range(1,self.n+1,2):\n # B) Request Permission to Write Current Number\n self.semOdd.acquire()\n printNumber(i)\n # C) Return Permission to Write a Zero (if applicable)\n self.semZero.release()\n", + "title": "1116. Print Zero Even Odd", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "python", + "description": "Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers. Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks. Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed. Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e. , each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think. The problem statement and the image above are taken from wikipedia.org The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where: Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends. Example 1:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/09/24/an_illustration_of_the_dining_philosophers_problem.png" + ], + "constraints": [ + "philosopher is the id of the philosopher who wants to eat.", + "pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.", + "eat is a function you can call to let the philosopher eat once he has picked both forks.", + "putLeftFork and putRightFork are functions you can call to put down the corresponding forks of that philosopher.", + "The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number)." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:[[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]Explanation:n is the number of times each philosopher will call the function.\nThe output array describes the calls you made to the functions controlling the forks and the eat function, its format is:\noutput[i] = [a, b, c] (three integers)\n- a is the id of a philosopher.\n- b specifies the fork: {1 : left, 2 : right}.\n- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.", + "image": null + } + ], + "follow_up": null, + "solution": "from threading import Semaphore\n\nclass DiningPhilosophers:\n def __init__(self):\n self.sizelock = Semaphore(4)\n self.locks = [Semaphore(1) for _ in range(5)]\n\n def wantsToEat(self, index, *actions):\n left, right = index, (index - 1) % 5\n with self.sizelock:\n with self.locks[left], self.locks[right]:\n for action in actions:\n action()\n", + "title": "1226. The Dining Philosophers", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= nums.length <= 10^4", + "-10^9 <= nums[i] <= 10^9", + "-10^9 <= target <= 10^9", + "Only one valid answer exists." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,7,11,15], target = 9Output:[0,1]Explanation:Because nums[0] + nums[1] == 9, we return [0, 1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,4], target = 6Output:[1,2]", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3], target = 6Output:[0,1]", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int[] twoSum(int[] nums, int target) { // Time: O(n), Space: O(1)\n\n for (int i = 1; i < nums.length; i++) {\n\n for (int j = i; j < nums.length; j++) {\n\n if (nums[j] + nums[j - i] == target) {\n return new int[] { j - i, j };\n }\n }\n }\n\n return new int[] {};\n }\n}", + "title": "1. Two Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:l1 = [2,4,3], l2 = [5,6,4]Output:[7,0,8]Explanation:342 + 465 = 807.", + "image": "https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" + }, + { + "text": "Example 2: Input:l1 = [0], l2 = [0]Output:[0]", + "image": null + }, + { + "text": "Example 3: Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]Output:[8,9,9,9,0,0,0,1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n\n ListNode head = new ListNode(0);\n ListNode current = head;\n int carry = 0;\n\n while (l1 != null || l2 != null) {\n\n int x = (l1 != null) ? l1.val : 0;\n int y = (l2 != null) ? l2.val : 0;\n int sum = x + y + carry;\n\n carry = sum / 10;\n current.next = new ListNode(sum % 10);\n current = current.next;\n\n if (l1 != null)\n l1 = l1.next;\n if (l2 != null)\n l2 = l2.next;\n }\n\n if (carry > 0) {\n current.next = new ListNode(carry);\n }\n\n return head.next;\n }\n}", + "title": "2. Add Two Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , find the length of the longest substring without repeating characters. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 5 * 10^4", + "s consists of English letters, digits, symbols and spaces." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abcabcbb\"Output:3Explanation:The answer is \"abc\", with the length of 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"bbbbb\"Output:1Explanation:The answer is \"b\", with the length of 1.", + "image": null + }, + { + "text": "Example 3: Input:s = \"pwwkew\"Output:3Explanation:The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLongestSubstring(String s) { // Sliding Window + Hash Table (ASCII Array)\n\n // approach 2\n // int left = 0, maxLength = 0;\n // HashSet charSet = new HashSet<>();\n\n // for (int right = 0; right < s.length(); right++) {\n\n // while (charSet.contains(s.charAt(right))) {\n // charSet.remove(s.charAt(left));\n // left++;\n // }\n\n // charSet.add(s.charAt(right));\n // maxLength = Math.max(maxLength, right - left + 1);\n // }\n // return maxLength;\n\n // approach 2\n\n int[] charIndex = new int[128]; // ASCII characters\n int maxLength = 0, left = 0;\n\n for (int right = 0; right < s.length(); right++) {\n\n left = Math.max(left, charIndex[s.charAt(right)]);\n maxLength = Math.max(maxLength, right - left + 1);\n\n charIndex[s.charAt(right)] = right + 1;\n }\n\n return maxLength;\n }\n}", + "title": "3. Longest Substring Without Repeating Characters", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3], nums2 = [2]Output:2.00000Explanation:merged array = [1,2,3] and median is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2], nums2 = [3,4]Output:2.50000Explanation:merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n\n if (nums1.length > nums2.length) {\n return findMedianSortedArrays(nums2, nums1); // Ensure nums1 is smaller\n }\n\n int m = nums1.length, n = nums2.length;\n int left = 0, right = m;\n\n while (left <= right) {\n int i = left + (right - left) / 2;\n int j = (m + n + 1) / 2 - i;\n\n int maxLeft1 = (i == 0) ? Integer.MIN_VALUE : nums1[i - 1];\n int minRight1 = (i == m) ? Integer.MAX_VALUE : nums1[i];\n\n int maxLeft2 = (j == 0) ? Integer.MIN_VALUE : nums2[j - 1];\n int minRight2 = (j == n) ? Integer.MAX_VALUE : nums2[j];\n\n if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n\n if ((m + n) % 2 == 0) {\n return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;\n } else {\n return Math.max(maxLeft1, maxLeft2);\n }\n\n } else if (maxLeft1 > minRight2) {\n right = i - 1; // Move left\n } else {\n left = i + 1; // Move right\n }\n }\n\n throw new IllegalArgumentException(\"Input arrays are not sorted.\");\n }\n}", + "title": "4. Median of Two Sorted Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s , return the longest palindromic substring in s . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consist of only digits and English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"babad\"Output:\"bab\"Explanation:\"aba\" is also a valid answer.", + "image": null + }, + { + "text": "Example 2: Input:s = \"cbbd\"Output:\"bb\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String longestPalindrome(String s) {\n if (s == null || s.length() < 1)\n return \"\";\n\n int start = 0, end = 0;\n for (int i = 0; i < s.length(); i++) {\n int len1 = expandFromCenter(s, i, i); // Odd length\n int len2 = expandFromCenter(s, i, i + 1); // Even length\n int len = Math.max(len1, len2);\n\n if (len > end - start) {\n start = i - (len - 1) / 2;\n end = i + len / 2;\n }\n }\n\n return s.substring(start, end + 1);\n }\n\n private int expandFromCenter(String s, int left, int right) {\n\n while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {\n left--;\n right++;\n }\n return right - left - 1;\n }\n}", + "title": "5. Longest Palindromic Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) And then read line by line: \"PAHNAPLSIIGYIR\" Write the code that will take a string and make this conversion given a number of rows: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 1000", + "s consists of English letters (lower-case and upper-case), ',' and '.' .", + "1 <= numRows <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"PAYPALISHIRING\", numRows = 3Output:\"PAHNAPLSIIGYIR\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"PAYPALISHIRING\", numRows = 4Output:\"PINALSIGYAHRPI\"Explanation:P I N\nA L S I G\nY A H R\nP I", + "image": null + }, + { + "text": "Example 3: Input:s = \"A\", numRows = 1Output:\"A\"", + "image": null + }, + { + "text": "P A H N\nA P L S I I G\nY I R", + "image": null + }, + { + "text": "string convert(string s, int numRows);", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convert(String s, int numRows) {\n\n // Edge case: if numRows is 1, no zigzag needed\n if (numRows == 1)\n return s;\n\n StringBuilder[] rows = new StringBuilder[numRows];\n for (int i = 0; i < numRows; i++) {\n rows[i] = new StringBuilder();\n }\n\n int currentRow = 0;\n boolean goingDown = false;\n\n // Iterate through each character in the string\n for (char c : s.toCharArray()) {\n rows[currentRow].append(c);\n\n // Change direction at the top and bottom\n if (currentRow == 0 || currentRow == numRows - 1) {\n goingDown = !goingDown;\n }\n\n // Move to the next row\n currentRow += goingDown ? 1 : -1;\n }\n\n StringBuilder result = new StringBuilder();\n for (StringBuilder row : rows) {\n result.append(row);\n }\n\n return result.toString();\n }\n}", + "title": "6. Zigzag Conversion", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 123Output:321", + "image": null + }, + { + "text": "Example 2: Input:x = -123Output:-321", + "image": null + }, + { + "text": "Example 3: Input:x = 120Output:21", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int reverse(int x) {\n \n int result = 0;\n\n while (x != 0) {\n \n int pop = x % 10;\n x /= 10;\n\n // Check for overflow\n if (result > Integer.MAX_VALUE / 10 || \n (result == Integer.MAX_VALUE / 10 && pop > 7)) {\n \n return 0;\n }\n \n // Check for underflow\n if (result < Integer.MIN_VALUE / 10 || \n (result == Integer.MIN_VALUE / 10 && pop < -8)) {\n return 0;\n }\n\n result = result * 10 + pop;\n }\n\n return result;\n }\n}", + "title": "7. Reverse Integer", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Return the integer as the final result. Example 1: Input: s = \"42\" Output: 42 Explanation: Example 2: Input: s = \" -042\" Output: -42 Explanation: Example 3: Input: s = \"1337c0d3\" Output: 1337 Explanation: Example 4: Input: s = \"0-1\" Output: 0 Explanation: Example 5: Input: s = \"words and 987\" Output: 0 Explanation: Reading stops at the first non-digit character 'w'.", + "description_images": [], + "constraints": [ + "0 <= s.length <= 200", + "s consists of English letters (lower-case and upper-case), digits ( 0-9 ), ' ' , '+' , '-' , and '.' ." + ], + "examples": [ + { + "text": "Example 1: The underlined characters are what is read in and the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^", + "image": null + }, + { + "text": "Example 2: Step 1: \"-042\" (leading whitespace is read and ignored)\n ^\nStep 2: \"-042\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -042\" (\"042\" is read in, leading zeros ignored in the result)\n ^", + "image": null + }, + { + "text": "Example 3: Step 1: \"1337c0d3\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"1337c0d3\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"1337c0d3\" (\"1337\" is read in; reading stops because the next character is a non-digit)\n ^", + "image": null + }, + { + "text": "Example 4: Step 1: \"0-1\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"0-1\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"0-1\" (\"0\" is read in; reading stops because the next character is a non-digit)\n ^", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int myAtoi(String s) {\n \n int index = 0, sign = 1, total = 0;\n int n = s.length();\n \n // Check if the string is empty\n if (n == 0) return 0;\n \n // Triming whitespaces --> 1. Whitespace: Ignore any leading whitespace (\" \").\n while (index < n && s.charAt(index) == ' ') {\n index++;\n }\n \n \n // removing whitespaces, if the index is 0 or not \n if (index == n) return 0;\n \n \n // --> 2. Signedness: checking if the next character is '-' or '+'\n if (s.charAt(index) == '+' || s.charAt(index) == '-') {\n sign = (s.charAt(index) == '-') ? -1 : 1;\n index++;\n }\n \n // Convert the number and avoid non-digit characters --> 3. Rounding: If the integer \n while (index < n) {\n \n char currentChar = s.charAt(index);\n \n if (currentChar < '0' || currentChar > '9') break;\n\n // Check for overflow and underflow\n if (total > (Integer.MAX_VALUE - (currentChar - '0')) / 10) {\n return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;\n }\n \n // Append current digit to the total\n total = total * 10 + (currentChar - '0');\n index++;\n }\n \n // --> Return the final result with the correct sign\n return total * sign;\n }\n}\n", + "title": "8. String to Integer (atoi)", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer x , return true if x is a palindrome , and false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-2 31 <= x <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:x = 121Output:trueExplanation:121 reads as 121 from left to right and from right to left.", + "image": null + }, + { + "text": "Example 2: Input:x = -121Output:falseExplanation:From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:x = 10Output:falseExplanation:Reads 01 from right to left. Therefore it is not a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(int x) {\n if (x < 0 || (x != 0 && x % 10 == 0))\n return false;\n\n int revHalf = 0;\n while (x > revHalf) {\n revHalf = revHalf * 10 + x % 10;\n x /= 10;\n }\n\n return x == revHalf || x == revHalf / 10;\n }\n}", + "title": "9. Palindrome Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == height.length", + "2 <= n <= 10^5", + "0 <= height[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:height = [1,8,6,2,5,4,8,3,7]Output:49Explanation: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.", + "image": "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg" + }, + { + "text": "Example 2: Input:height = [1,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxArea(int[] height) { // two pointer approach\n\n int start = 0, end = height.length - 1, maxArea = 0;\n\n while (start < end) {\n // MaxArea -> height * min width from start or end\n maxArea = Math.max(maxArea, (end - start) * Math.min(height[start], height[end]));\n\n if (height[start] < height[end]) {\n start++;\n } else {\n end--;\n }\n }\n\n return maxArea;\n }\n}", + "title": "11. Container With Most Water", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Seven different symbols represent Roman numerals with the following values: 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: Given an integer, convert it to a Roman numeral. Example 1: Input: num = 3749 Output: \"MMMDCCXLIX\" Explanation: Example 2: Input: num = 58 Output: \"LVIII\" Explanation: Example 3: Input: num = 1994 Output: \"MCMXCIV\" Explanation:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n 40 = XL as 10 (X) less of 50 (L)\n 9 = IX as 1 (I) less of 10 (X)\nNote: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places", + "image": null + }, + { + "text": "Example 2: 50 = L\n 8 = VIII", + "image": null + }, + { + "text": "Example 3: 1000 = M\n 900 = CM\n 90 = XC\n 4 = IV", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n private static final int[] n = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };\n private static final String[] s = { \"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\" };\n\n public String intToRoman(int num) {\n\n StringBuilder roman = new StringBuilder();\n\n for (int i = 0; i < n.length; i++) {\n\n while (num >= n[i]) { // Deduct values as long as the current numeral can be used\n roman.append(s[i]);\n num -= n[i];\n }\n }\n\n return roman.toString();\n }\n}", + "title": "12. Integer to Roman", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Roman numerals are represented by seven different symbols: I , V , X , L , C , D and M . For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII , which is simply X + II . The number 27 is written as XXVII , which is XX + V + II . Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII . Instead, the number four is written as IV . Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX . There are six instances where subtraction is used: Given a roman numeral, convert it to an integer. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "I can be placed before V (5) and X (10) to make 4 and 9.", + "X can be placed before L (50) and C (100) to make 40 and 90.", + "C can be placed before D (500) and M (1000) to make 400 and 900." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"III\"Output:3Explanation:III = 3.", + "image": null + }, + { + "text": "Example 2: Input:s = \"LVIII\"Output:58Explanation:L = 50, V= 5, III = 3.", + "image": null + }, + { + "text": "Example 3: Input:s = \"MCMXCIV\"Output:1994Explanation:M = 1000, CM = 900, XC = 90 and IV = 4.", + "image": null + }, + { + "text": "SymbolValueI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int romanToInt(String s) {\n\n int ans = 0, num = 0;\n\n for (int i = s.length() - 1; i >= 0; i--) {\n\n switch (s.charAt(i)) {\n case 'I':\n num = 1;\n break;\n case 'V':\n num = 5;\n break;\n case 'X':\n num = 10;\n break;\n case 'L':\n num = 50;\n break;\n case 'C':\n num = 100;\n break;\n case 'D':\n num = 500;\n break;\n case 'M':\n num = 1000;\n break;\n }\n\n if (4 * num < ans)\n ans -= num;\n else\n ans += num;\n }\n\n return ans;\n\n // Map roman = new HashMap<>();\n // roman.put('I', 1);\n // roman.put('V', 5);\n // roman.put('X', 10);\n // roman.put('L', 50);\n // roman.put('C', 100);\n // roman.put('D', 500);\n // roman.put('M', 1000);\n\n // int result = 0;\n // int n = s.length();\n\n // for (int i = 0; i < n; i++) {\n\n // if (i + 1 < n && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) {\n // result -= roman.get(s.charAt(i));\n // } else {\n // result += roman.get(s.charAt(i));\n // }\n // }\n\n // return result;\n }\n}", + "title": "13. Roman to Integer", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= strs.length <= 200", + "0 <= strs[i].length <= 200", + "strs[i] consists of only lowercase English letters if it is non-empty." + ], + "examples": [ + { + "text": "Example 1: Input:strs = [\"flower\",\"flow\",\"flight\"]Output:\"fl\"", + "image": null + }, + { + "text": "Example 2: Input:strs = [\"dog\",\"racecar\",\"car\"]Output:\"\"Explanation:There is no common prefix among the input strings.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public String longestCommonPrefix(String[] strs) {\n\n if (strs.length == 0) {\n return \"\";\n }\n\n String firstEliment = strs[0];\n\n for (int i = 1; i < strs.length; i++) {\n\n while (strs[i].indexOf(firstEliment) != 0) {\n firstEliment = firstEliment.substring(0, firstEliment.length() - 1);\n }\n }\n return firstEliment;\n }\n}", + "title": "14. Longest Common Prefix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 3000", + "-10^5 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: 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.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1]Output:[]Explanation:The only possible triplet does not sum up to 0.", + "image": null + }, + { + "text": "Example 3: Input:nums = [0,0,0]Output:[[0,0,0]]Explanation:The only possible triplet sums up to 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> threeSum(int[] nums) {\n \n List> res = new ArrayList<>();\n Arrays.sort(nums); // Sorting the array (O(n log n))\n\n for (int i = 0; i < nums.length - 2; i++) { // Avoid unnecessary iterations\n if (i > 0 && nums[i] == nums[i - 1])\n continue; // Skip duplicates for i\n\n int j = i + 1, k = nums.length - 1;\n\n while (j < k) {\n int sum = nums[i] + nums[j] + nums[k];\n\n if (sum > 0) {\n k--;\n } else if (sum < 0) {\n j++;\n } else {\n res.add(Arrays.asList(nums[i], nums[j], nums[k]));\n\n // Move pointers to avoid duplicates\n while (j < k && nums[j] == nums[j + 1])\n j++; // Skip duplicate for j\n while (j < k && nums[k] == nums[k - 1])\n k--; // Skip duplicate for k\n\n j++;\n k--;\n }\n }\n }\n return res;\n }\n}\n", + "title": "15. 3Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums of length n and an integer target , find three integers in nums such that the sum is closest to target . Return the sum of the three integers . You may assume that each input would have exactly one solution. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "3 <= nums.length <= 500", + "-1000 <= nums[i] <= 1000", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,2,1,-4], target = 1Output:2Explanation:The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,0], target = 1Output:0Explanation:The sum that is closest to the target is 0. (0 + 0 + 0 = 0).", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int threeSumClosest(int[] nums, int target) {\n Arrays.sort(nums);\n int n = nums.length;\n int closesSum = nums[0] + nums[1] + nums[2];\n\n for (int i = 0; i < n - 2; i++) {\n int left = i + 1;\n int right = n - 1;\n\n while (left < right) {\n\n int curSum = nums[i] + nums[left] + nums[right];\n\n if (Math.abs(curSum - target) < Math.abs(closesSum - target)) {\n closesSum = curSum;\n }\n\n if (curSum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n\n return closesSum;\n }\n}", + "title": "16. 3Sum Closest", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= digits.length <= 4", + "digits[i] is a digit in the range ['2', '9'] ." + ], + "examples": [ + { + "text": "Example 1: Input:digits = \"23\"Output:[\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]", + "image": null + }, + { + "text": "Example 2: Input:digits = \"\"Output:[]", + "image": null + }, + { + "text": "Example 3: Input:digits = \"2\"Output:[\"a\",\"b\",\"c\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public static List letterCombinations(String digits) {\n if (digits == null || digits.isEmpty())\n return new ArrayList<>();\n\n Map phoneMap = Map.of(\n '2', \"abc\", '3', \"def\", '4', \"ghi\", '5', \"jkl\",\n '6', \"mno\", '7', \"pqrs\", '8', \"tuv\", '9', \"wxyz\");\n\n List result = new ArrayList<>();\n backtrack(result, digits, phoneMap, new StringBuilder(), 0);\n return result;\n }\n\n private static void backtrack(\n List result,\n String digits,\n Map phoneMap,\n StringBuilder path,\n int index) {\n\n if (index == digits.length()) {\n result.add(path.toString());\n return;\n }\n\n String letters = phoneMap.get(digits.charAt(index));\n for (char letter : letters.toCharArray()) {\n path.append(letter);\n\n backtrack(result, digits, phoneMap, path, index + 1);\n path.deleteCharAt(path.length() - 1); // Backtrack\n }\n }\n}", + "title": "17. Letter Combinations of a Phone Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= a, b, c, d < n", + "a , b , c , and d are distinct .", + "nums[a] + nums[b] + nums[c] + nums[d] == target" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,0,-1,0,-2,2], target = 0Output:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,2,2,2], target = 8Output:[[2,2,2,2]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> fourSum(int[] nums, int target) {\n List> result = new ArrayList<>();\n Arrays.sort(nums);\n int n = nums.length;\n\n for (int i = 0; i < n - 3; i++) {\n\n if (i > 0 && nums[i] == nums[i - 1])\n continue;\n\n for (int j = i + 1; j < n - 2; j++) {\n\n if (j > i + 1 && nums[j] == nums[j - 1])\n continue;\n\n int left = j + 1;\n int right = n - 1;\n\n while (left < right) {\n long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];\n\n if (sum == target) {\n result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));\n\n while (left < right && nums[left] == nums[left + 1])\n left++;\n\n while (left < right && nums[right] == nums[right - 1])\n right--;\n\n left++;\n right--;\n\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n }\n }\n }\n\n return result;\n }\n}", + "title": "18. 4Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, remove the n th node from the end of the list and return its head. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is sz .", + "1 <= sz <= 30", + "0 <= Node.val <= 100", + "1 <= n <= sz" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], n = 2Output:[1,2,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1], n = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [1,2], n = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n\n ListNode fast = dummy, slow = dummy;\n\n for (int i = 0; i <= n; i++) {\n fast = fast.next;\n }\n\n while (fast != null) {\n fast = fast.next;\n slow = slow.next;\n }\n\n slow.next = slow.next.next;\n\n return dummy.next;\n }\n}", + "title": "19. Remove Nth Node From End of List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']' , determine if the input string is valid. An input string is valid if: Example 1: Input: s = \"()\" Output: true Example 2: Input: s = \"()[]{}\" Output: true Example 3: Input: s = \"(]\" Output: false Example 4: Input: s = \"([])\" Output: true", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of parentheses only '()[]{}' ." + ], + "examples": [], + "follow_up": null, + "solution": "import java.util.Stack;\n\nclass Solution {\n public boolean isValid(String s) {\n\n char[] chars = new char[s.length()];\n int top = -1;\n\n for (char c : s.toCharArray()) {\n\n if (c == '(' || c == '{' || c == '[') {\n top += 1;\n chars[top] = c;\n\n } else {\n\n if (top == -1)\n return false;\n char pop = chars[top];\n top -= 1;\n\n if (!((pop == '(' && c == ')') ||\n (pop == '[' && c == ']') ||\n (pop == '{' && c == '}'))) {\n return false;\n }\n }\n }\n\n return top == -1;\n }\n}", + "title": "20. Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:list1 = [1,2,4], list2 = [1,3,4]Output:[1,1,2,3,4,4]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg" + }, + { + "text": "Example 2: Input:list1 = [], list2 = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:list1 = [], list2 = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n\n ListNode head = new ListNode(0);\n ListNode current = head;\n\n while (list1 != null && list2 != null) {\n\n if (list1.val <= list2.val) {\n current.next = list1;\n list1 = list1.next;\n } else {\n current.next = list2;\n list2 = list2.next;\n }\n\n current = current.next;\n }\n\n if (list1 != null)\n current.next = list1;\n if (list2 != null)\n current.next = list2;\n\n return head.next;\n }\n}", + "title": "21. Merge Two Sorted Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 8" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", + "image": null + }, + { + "text": "Example 2: Input:n = 1Output:[\"()\"]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List generateParenthesis(int n) {\n List result = new ArrayList<>();\n \n backtrack(result, new StringBuilder(), 0, 0, n);\n return result;\n }\n\n private void backtrack(List result, StringBuilder current, int open, int close, int n) {\n if (current.length() == 2 * n) {\n result.add(current.toString());\n return;\n }\n\n if (open < n) {\n current.append('(');\n backtrack(result, current, open + 1, close, n);\n current.deleteCharAt(current.length() - 1);\n }\n\n if (close < open) {\n current.append(')');\n backtrack(result, current, open, close + 1, n);\n current.deleteCharAt(current.length() - 1);\n }\n }\n}", + "title": "22. Generate Parentheses", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:lists = [[1,4,5],[1,3,4],[2,6]]Output:[1,1,2,3,4,4,5,6]Explanation:The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6", + "image": null + }, + { + "text": "Example 2: Input:lists = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:lists = [[]]Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);\n\n for (ListNode list : lists) {\n if (list != null) {\n minHeap.add(list);\n }\n }\n\n ListNode dummy = new ListNode(0);\n ListNode tail = dummy;\n\n while (!minHeap.isEmpty()) {\n ListNode smallest = minHeap.poll();\n tail.next = smallest;\n tail = tail.next;\n\n if (smallest.next != null) {\n minHeap.add(smallest.next);\n }\n }\n\n return dummy.next;\n }\n}", + "title": "23. Merge k Sorted Lists", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3] Explanation: Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1,2,3] Output: [2,1,3]", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" + ], + "constraints": [ + "The number of nodes in the list is in the range [0, 100] .", + "0 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n\n ListNode prev = dummy;\n\n while (head != null && head.next != null) {\n ListNode first = head;\n ListNode second = head.next;\n\n prev.next = second;\n first.next = second.next;\n second.next = first;\n\n prev = first;\n head = first.next;\n }\n\n return dummy.next;\n }\n}", + "title": "24. Swap Nodes in Pairs", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= k <= n <= 5000", + "0 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[2,1,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5], k = 3Output:[3,2,1,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" + } + ], + "follow_up": "Follow-up:", + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n\n if (head == null || k == 1)\n return head;\n\n ListNode temp = head;\n int count = 0;\n\n while (temp != null && count < k) {\n temp = temp.next;\n count++;\n }\n\n if (count < k)\n return head;\n\n ListNode prev = null, curr = head, next = null;\n\n for (int i = 0; i < k; i++) {\n next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n head.next = reverseKGroup(curr, k);\n\n return prev;\n }\n}", + "title": "25. Reverse Nodes in k-Group", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove the duplicates in-place such that each unique element appears only once . The relative order of the elements should be kept the same . Then return the number of unique elements in nums . Consider the number of unique elements of nums to be k , to get accepted, you need to do the following things: Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums .", + "Return k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2]Output:2, nums = [1,2,_]Explanation:Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,2,2,3,3,4]Output:5, nums = [0,1,2,3,4,_,_,_,_,_]Explanation:Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeDuplicates(int[] nums) {\n\n int k = 1;\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] != nums[i - 1]) {\n nums[k] = nums[i];\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "26. Remove Duplicates from Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer val , remove all occurrences of val in nums in-place . The order of the elements may be changed. Then return the number of elements in nums which are not equal to val . Consider the number of elements in nums which are not equal to val be k , to get accepted, you need to do the following things: Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Change the array nums such that the first k elements of nums contain the elements which are not equal to val . The remaining elements of nums are not important as well as the size of nums .", + "Return k ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,2,3], val = 3Output:2, nums = [2,2,_,_]Explanation:Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,2,2,3,0,4,2], val = 2Output:5, nums = [0,1,4,0,3,_,_,_]Explanation:Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeElement(int[] nums, int val) {\n \n int k = 0;\n\n for (int i = 0; i < nums.length; i++) {\n\n if(nums[i] != val) {\n nums[k] = nums[i]; // shifting elements if if not equal to val\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "27. Remove Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings needle and haystack , return the index of the first occurrence of needle in haystack , or -1 if needle is not part of haystack . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= haystack.length, needle.length <= 10^4", + "haystack and needle consist of only lowercase English characters." + ], + "examples": [ + { + "text": "Example 1: Input:haystack = \"sadbutsad\", needle = \"sad\"Output:0Explanation:\"sad\" occurs at index 0 and 6.\nThe first occurrence is at index 0, so we return 0.", + "image": null + }, + { + "text": "Example 2: Input:haystack = \"leetcode\", needle = \"leeto\"Output:-1Explanation:\"leeto\" did not occur in \"leetcode\", so we return -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int strStr(String haystack, String needle) { // Time complexity: O(n∗m) || Space complexity: O(1)\n\n if (haystack.length() < needle.length()) {\n return -1;\n }\n\n for (int i = 0; i <= haystack.length() - needle.length(); i++) {\n\n if (haystack.substring(i, i + needle.length()).equals(needle)) { // sliding window approach\n return i;\n }\n }\n\n return -1;\n }\n}", + "title": "28. Find the Index of the First Occurrence in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8 , and -2.7335 would be truncated to -2 . Return the quotient after dividing dividend by divisor . Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1] . For this problem, if the quotient is strictly greater than 2 31 - 1 , then return 2 31 - 1 , and if the quotient is strictly less than -2 31 , then return -2 31 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "-2 31 <= dividend, divisor <= 2 31 - 1", + "divisor != 0" + ], + "examples": [ + { + "text": "Example 1: Input:dividend = 10, divisor = 3Output:3Explanation:10/3 = 3.33333.. which is truncated to 3.", + "image": null + }, + { + "text": "Example 2: Input:dividend = 7, divisor = -3Output:-2Explanation:7/-3 = -2.33333.. which is truncated to -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int divide(int dividend, int divisor) {\n if (dividend == Integer.MIN_VALUE && divisor == -1) {\n return Integer.MAX_VALUE;\n }\n\n long a = Math.abs((long) dividend);\n long b = Math.abs((long) divisor);\n int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;\n\n int result = 0;\n\n for (int i = 31; i >= 0; i--) {\n if ((a >> i) >= b) {\n result += 1 << i;\n a -= b << i;\n }\n }\n\n return sign * result;\n }\n}", + "title": "29. Divide Two Integers", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given a string s and an array of strings words . All the strings of words are of the same length . A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated. Return an array of the starting indices of all the concatenated substrings in s . You can return the answer in any order . Example 1: Input: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"] Output: [0,9] Explanation: The substring starting at 0 is \"barfoo\" . It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words . The substring starting at 9 is \"foobar\" . It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words . Example 2: Input: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"] Output: [] Explanation: There is no concatenated substring. Example 3: Input: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"] Output: [6,9,12] Explanation: The substring starting at 6 is \"foobarthe\" . It is the concatenation of [\"foo\",\"bar\",\"the\"] . The substring starting at 9 is \"barthefoo\" . It is the concatenation of [\"bar\",\"the\",\"foo\"] . The substring starting at 12 is \"thefoobar\" . It is the concatenation of [\"the\",\"foo\",\"bar\"] .", + "description_images": [], + "constraints": [ + "For example, if words = [\"ab\",\"cd\",\"ef\"] , then \"abcdef\" , \"abefcd\" , \"cdabef\" , \"cdefab\" , \"efabcd\" , and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated string because it is not the concatenation of any permutation of words ." + ], + "examples": [], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List findSubstring(String s, String[] words) {\n List result = new ArrayList<>();\n if (s == null || words == null || words.length == 0)\n return result;\n\n int wordLen = words[0].length();\n int wordCount = words.length;\n int windowLen = wordLen * wordCount;\n\n if (s.length() < windowLen)\n return result;\n\n // Store word frequency\n Map wordMap = new HashMap<>();\n for (String word : words) {\n wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);\n }\n\n // Iterate over possible start positions\n for (int i = 0; i < wordLen; i++) {\n int left = i, right = i;\n Map seenWords = new HashMap<>();\n\n while (right + wordLen <= s.length()) {\n String word = s.substring(right, right + wordLen);\n right += wordLen;\n\n if (wordMap.containsKey(word)) {\n seenWords.put(word, seenWords.getOrDefault(word, 0) + 1);\n\n // checks if the current window has more occurrences of word than allowed\n while (seenWords.get(word) > wordMap.get(word)) {\n String leftWord = s.substring(left, left + wordLen);\n seenWords.put(leftWord, seenWords.get(leftWord) - 1);\n left += wordLen;\n }\n\n if (right - left == windowLen) {\n result.add(left);\n }\n } else {\n // Reset everything if word not found\n seenWords.clear();\n left = right;\n }\n }\n }\n\n return result;\n }\n}\n", + "title": "30. Substring with Concatenation of All Words", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums , find the next permutation of nums . The replacement must be in place and use only constant extra memory. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, for arr = [1,2,3] , the following are all the permutations of arr : [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1] ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[1,3,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1]Output:[1,2,3]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,5]Output:[1,5,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void nextPermutation(int[] nums) {\n if (nums == null || nums.length <= 1)\n return;\n\n int i = nums.length - 2;\n\n while (i >= 0 && nums[i] >= nums[i + 1]) {\n i--;\n }\n\n if (i >= 0) {\n int j = nums.length - 1;\n\n while (nums[j] <= nums[i]) {\n j--;\n }\n\n swap(nums, i, j);\n }\n\n reverse(nums, i + 1, nums.length - 1);\n }\n\n private void reverse(int[] nums, int left, int right) {\n while (left < right) {\n swap(nums, left++, right--);\n }\n }\n\n private void swap(int[] nums, int i, int j) {\n int tmp = nums[i];\n nums[i] = nums[j];\n nums[j] = tmp;\n }\n}", + "title": "31. Next Permutation", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string containing just the characters '(' and ')' , return the length of the longest valid (well-formed) parentheses substring . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 3 * 10^4", + "s[i] is '(' , or ')' ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"(()\"Output:2Explanation:The longest valid parentheses substring is \"()\".", + "image": null + }, + { + "text": "Example 2: Input:s = \")()())\"Output:4Explanation:The longest valid parentheses substring is \"()()\".", + "image": null + }, + { + "text": "Example 3: Input:s = \"\"Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestValidParentheses(String s) {\n Stack stack = new Stack<>();\n stack.push(-1);\n int maxLength = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (s.charAt(i) == '(') {\n stack.push(i);\n } else {\n stack.pop();\n \n if (stack.isEmpty()) {\n stack.push(i);\n } else {\n maxLength = Math.max(maxLength, i - stack.peek());\n }\n }\n }\n\n return maxLength;\n }\n}", + "title": "32. Longest Valid Parentheses", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot 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 rotated at pivot index 3 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: Example 2: Example 3:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [4,5,6,7,0,1,2], target = 0Output:4", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2], target = 3Output:-1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1], target = 0Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1; // Prevents overflow\n\n if (nums[mid] == target) {\n return mid; // base case\n }\n\n // Determine the sorted half\n if (nums[low] <= nums[mid]) { // Left half is sorted\n\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1; // Search left\n } else {\n low = mid + 1; // Search right\n }\n\n } else { // Right half is sorted\n\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1; // Search right\n } else {\n high = mid - 1; // Search left\n }\n }\n }\n\n return -1;\n }\n}", + "title": "33. Search in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] . You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "nums is a non-decreasing array.", + "-10^9 <= target <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [5,7,7,8,8,10], target = 8Output:[3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,7,7,8,8,10], target = 6Output:[-1,-1]", + "image": null + }, + { + "text": "Example 3: Input:nums = [], target = 0Output:[-1,-1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] searchRange(int[] nums, int target) {\n int[] result = new int[] { -1, -1 };\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n\n if (nums[mid] == target) {\n\n int left = mid;\n while (left - 1 >= low && nums[left - 1] == target) {\n left--;\n }\n result[0] = left;\n\n int right = mid;\n while (right + 1 <= high && nums[right + 1] == target) {\n right++;\n }\n result[1] = right;\n\n break;\n }\n\n if (nums[mid] < target) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return result;\n }\n}", + "title": "34. Find First and Last Position of Element in Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums contains distinct values sorted in ascending order.", + "-10^4 <= target <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,5,6], target = 5Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,3,5,6], target = 2Output:1", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,3,5,6], target = 7Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int searchInsert(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] < target) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return low;\n }\n}", + "title": "35. Search Insert Position", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules : Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:true", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + }, + { + "text": "Example 2: Input:board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]Output:falseExplanation:Same as Example 1, except with the5in the top left corner being modified to8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n\n public static boolean isValidSudoku(char[][] board) {\n int[] rows = new int[9]; // Track numbers in rows\n int[] cols = new int[9]; // Track numbers in columns\n int[] boxes = new int[9]; // Track numbers in 3x3 boxes\n\n for (int i = 0; i < 9; i++) {\n\n for (int j = 0; j < 9; j++) {\n char num = board[i][j];\n\n if (num != '.') {\n int val = num - '1'; // Convert '1'-'9' to 0-8\n int boxIndex = (i / 3) * 3 + (j / 3);\n\n int mask = 1 << val; // Bit mask for current number\n if ((rows[i] & mask) != 0 || (cols[j] & mask) != 0 || (boxes[boxIndex] & mask) != 0) {\n return false; // Duplicate detected\n }\n\n // Mark the number in row, column, and box\n rows[i] |= mask;\n cols[j] |= mask;\n boxes[boxIndex] |= mask;\n }\n }\n }\n\n return true;\n }\n}\n", + "title": "36. Valid Sudoku", + "topic": "Shell" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules : The '.' character indicates empty cells. Example 1:", + "description_images": [], + "constraints": [ + "board.length == 9", + "board[i].length == 9", + "board[i][j] is a digit or '.' .", + "It is guaranteed that the input board has only one solution." + ], + "examples": [ + { + "text": "Example 1: 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:[[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]Explanation:The input board is shown above and the only valid solution is shown below:", + "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n\n private boolean solve(char[][] board) {\n\n for (int row = 0; row < 9; row++) {\n for (int col = 0; col < 9; col++) {\n\n if (board[row][col] == '.') {\n\n for (char d = '1'; d <= '9'; d++) {\n\n if (isValid(board, row, col, d)) {\n board[row][col] = d;\n if (solve(board))\n return true;\n board[row][col] = '.'; // backtrack\n }\n }\n return false;\n }\n }\n }\n return true;\n }\n\n private boolean isValid(char[][] board, int row, int col, char d) {\n\n for (int i = 0; i < 9; i++) {\n if (board[row][i] == d)\n return false; // check row\n if (board[i][col] == d)\n return false; // check col\n if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == d)\n return false; // check box\n }\n\n return true;\n }\n}", + "title": "37. Sudoku Solver", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 30", + "2 <= candidates[i] <= 40", + "All elements of candidates are distinct .", + "1 <= target <= 40" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [2,3,6,7], target = 7Output:[[2,2,3],[7]]Explanation:2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,3,5], target = 8Output:[[2,2,2,2],[2,3,3],[3,5]]", + "image": null + }, + { + "text": "Example 3: Input:candidates = [2], target = 1Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public List> combinationSum(int[] candidates, int target) {\n List> result = new ArrayList<>();\n backtrack(0, candidates, target, new ArrayList<>(), result);\n\n return result;\n }\n\n private void backtrack(int index, int[] candidates, int target, List path, List> result) {\n if (target == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = index; i < candidates.length; i++) {\n\n if (candidates[i] <= target) {\n path.add(candidates[i]);\n backtrack(i, candidates, target - candidates[i], path, result);\n path.removeLast(); // Backtrack\n }\n }\n }\n}", + "title": "39. Combination Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= candidates.length <= 100", + "1 <= candidates[i] <= 50", + "1 <= target <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:candidates = [10,1,2,7,6,1,5], target = 8Output:[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]", + "image": null + }, + { + "text": "Example 2: Input:candidates = [2,5,2,1,2], target = 5Output:[\n[1,2,2],\n[5]\n]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combinationSum2(int[] candidates, int target) {\n Arrays.sort(candidates);\n List> result = new ArrayList<>();\n \n backtrack(candidates, 0, target, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int[] candidates, int start, int target, List path, List> result) {\n if (target == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i < candidates.length; i++) {\n\n if (i > start && candidates[i] == candidates[i - 1])\n continue;\n\n if (candidates[i] > target)\n break;\n\n path.add(candidates[i]);\n backtrack(candidates, i + 1, target - candidates[i], path, result);\n path.removeLast();\n }\n }\n}", + "title": "40. Combination Sum II", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an unsorted integer array nums . Return the smallest positive integer that is not present in nums . You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,0]Output:3Explanation:The numbers in the range [1,2] are all in the array.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,4,-1,1]Output:2Explanation:1 is in the array but 2 is missing.", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,8,9,11,12]Output:1Explanation:The smallest positive integer 1 is missing.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int firstMissingPositive(int[] nums) {\n int n = nums.length;\n\n for (int i = 0; i < n; i++) {\n while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {\n swap(nums, i, nums[i] - 1);\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (nums[i] != i + 1)\n return i + 1;\n }\n\n return n + 1;\n }\n\n private void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}", + "title": "41. First Missing Positive", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == height.length", + "1 <= n <= 2 * 10^4", + "0 <= height[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:height = [0,1,0,2,1,0,1,3,2,1,2,1]Output:6Explanation: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.", + "image": "https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" + }, + { + "text": "Example 2: Input:height = [4,2,0,3,2,5]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trap(int[] height) {\n\n int n = height.length;\n int left = 0, right = n - 1;\n int leftMax = height[left], rightMax = height[right];\n int result = 0;\n\n if (n < 1)\n return 0;\n\n while (left < right) {\n\n if (leftMax < rightMax) {\n left++;\n leftMax = leftMax > height[left] ? leftMax : height[left];\n result += leftMax - height[left];\n\n } else {\n right--;\n rightMax = rightMax > height[right] ? rightMax : height[right];\n result += rightMax - height[right];\n }\n }\n\n return result;\n }\n}", + "title": "42. Trapping Rain Water", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed array of integers nums of length n . You are initially positioned at nums[0] . Each element nums[i] represents the maximum length of a forward jump from index i . In other words, if you are at nums[i] , you can jump to any nums[i + j] where: Return the minimum number of jumps to reach nums[n - 1] . The test cases are generated such that you can reach nums[n - 1] . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= j <= nums[i] and", + "i + j < n" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]Output:2Explanation: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.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,3,0,1,4]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int jump(int[] nums) {\n int farthest = 0; // farthest index\n int end = 0; // farthest end to reach\n int jump = 0; // number of jumps taken to reach the goal\n int n = nums.length; // last index\n\n for (int i = 0; i < n - 1; i++) {\n\n if (farthest < i + nums[i]) {\n farthest = i + nums[i];\n }\n\n if (i == end) {\n jump++;\n end = farthest;\n }\n }\n return jump;\n }\n}", + "title": "45. Jump Game II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 6", + "-10 <= nums[i] <= 10", + "All the integers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1]Output:[[0,1],[1,0]]", + "image": null + }, + { + "text": "Example 3: Input:nums = [1]Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> permute(int[] nums) {\n List> result = new ArrayList<>();\n boolean[] used = new boolean[nums.length];\n\n backtrack(nums, new ArrayList<>(), used, result);\n return result;\n }\n\n private void backtrack(int[] nums, List path, boolean[] used, List> result) {\n\n if (path.size() == nums.length) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = 0; i < nums.length; i++) {\n\n if (!used[i]) {\n used[i] = true;\n path.add(nums[i]);\n backtrack(nums, path, used, result);\n path.removeLast();\n used[i] = false;\n }\n }\n }\n}", + "title": "46. Permutations", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == matrix.length == matrix[i].length", + "1 <= n <= 20", + "-1000 <= matrix[i][j] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[[7,4,1],[8,5,2],[9,6,3]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[][] matrix) {\n int n = matrix.length;\n\n // Step 1: Transpose the matrix\n for (int i = 0; i < n; i++) {\n\n for (int j = i + 1; j < n; j++) {\n\n int temp = matrix[i][j];\n matrix[i][j] = matrix[j][i];\n matrix[j][i] = temp;\n }\n }\n\n // Step 2: Reverse each row\n for (int i = 0; i < n; i++) {\n\n for (int j = 0; j < n / 2; j++) {\n\n int temp = matrix[i][j];\n matrix[i][j] = matrix[i][n - j - 1];\n matrix[i][n - j - 1] = temp;\n }\n }\n }\n}", + "title": "48. Rotate Image", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Input: strs = [\"\"] Output: [[\"\"]] Example 3: Input: strs = [\"a\"] Output: [[\"a\"]]", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public List> groupAnagrams(String[] strs) {\n Map> map = new HashMap<>();\n\n for (String str : strs) {\n int[] count = new int[26]; // Array to count frequency of each character\n\n // Count frequency of characters\n for (char c : str.toCharArray()) {\n count[c - 'a']++;\n }\n\n // Convert the frequency count array to a string (for use as a key)\n StringBuilder key = new StringBuilder();\n for (int c : count) {\n key.append(\"#\"); // Separate frequencies for better uniqueness\n key.append(c);\n }\n\n // Group anagrams based on the frequency count\n map.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(str);\n }\n\n return new ArrayList<>(map.values());\n }\n}", + "title": "49. Group Anagrams", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement pow(x, n) , which calculates x raised to the power n (i.e., x n ). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-100.0 < x < 100.0", + "-2 31 <= n <= 2 31 -1", + "n is an integer.", + "Either x is not zero or n > 0 .", + "-10^4 <= x n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:x = 2.00000, n = 10Output:1024.00000", + "image": null + }, + { + "text": "Example 2: Input:x = 2.10000, n = 3Output:9.26100", + "image": null + }, + { + "text": "Example 3: Input:x = 2.00000, n = -2Output:0.25000Explanation:2-2= 1/22= 1/4 = 0.25", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double myPow(double x, int n) {\n if (n == 0)\n return 1.0;\n\n long power = n;\n if (n < 0) {\n x = 1 / x; // Handle negative exponent\n power = -power; // Convert to positive\n }\n\n double result = 1.0;\n while (power > 0) {\n\n if ((power & 1) == 1) { // If current bit is set, multiply\n result *= x;\n }\n\n x *= x; // Square x\n power >>= 1; // Divide power by 2\n }\n\n return result;\n }\n}", + "title": "50. Pow(x, n)", + "topic": "Others" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:[[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]Explanation:There exist two distinct solutions to the 4-queens puzzle as shown above", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:[[\"Q\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private List> solutions = new ArrayList<>();\n\n public List> solveNQueens(int n) {\n char[][] board = new char[n][n];\n\n for (char[] row : board) {\n Arrays.fill(row, '.');\n }\n\n backtrack(0, n, 0, 0, 0, board);\n return solutions;\n }\n\n private void backtrack(int row, int n, int cols, int diagonals, int antiDiagonals, char[][] board) {\n if (row == n) {\n solutions.add(constructBoard(board));\n return;\n }\n\n int availablePositions = ((1 << n) - 1) & ~(cols | diagonals | antiDiagonals);\n\n while (availablePositions != 0) {\n int position = availablePositions & -availablePositions; // Get rightmost available position\n availablePositions -= position; // Remove this position\n\n int col = Integer.bitCount(position - 1); // Convert bitmask to column index\n\n board[row][col] = 'Q'; // Place queen\n backtrack(row + 1,\n n,\n cols | position,\n (diagonals | position) << 1,\n (antiDiagonals | position) >> 1,\n board);\n board[row][col] = '.'; // Backtrack\n }\n }\n\n private List constructBoard(char[][] board) {\n List res = new ArrayList<>();\n\n for (char[] row : board) {\n res.add(new String(row));\n }\n return res;\n }\n}", + "title": "51. N-Queens", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:2Explanation:There are two distinct solutions to the 4-queens puzzle as shown.", + "image": "https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private int count = 0;\n\n public int totalNQueens(int n) {\n backtrack(0, n, 0, 0, 0);\n return count;\n }\n\n private void backtrack(int row, int n, int cols, int diagonals, int antiDiagonals) {\n if (row == n) {\n count++;\n return;\n }\n\n int availablePositions = ((1 << n) - 1) & ~(cols | diagonals | antiDiagonals);\n\n while (availablePositions != 0) {\n int position = availablePositions & -availablePositions; // Get rightmost available position\n availablePositions -= position; // Remove this position\n\n backtrack(row + 1, n, cols | position, (diagonals | position) << 1, (antiDiagonals | position) >> 1);\n }\n }\n}", + "title": "52. N-Queens II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , find the subarray with the largest sum, and return its sum . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-2,1,-3,4,-1,2,1,-5,4]Output:6Explanation:The subarray [4,-1,2,1] has the largest sum 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1]Output:1Explanation:The subarray [1] has the largest sum 1.", + "image": null + }, + { + "text": "Example 3: Input:nums = [5,4,-1,7,8]Output:23Explanation:The subarray [5,4,-1,7,8] has the largest sum 23.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubArray(int[] nums) {\n int maxSum = Integer.MIN_VALUE;\n int currentSum = 0;\n\n for (int num : nums) {\n currentSum += num;\n maxSum = Math.max(maxSum, currentSum);\n\n if (currentSum < 0)\n currentSum = 0;\n }\n\n return maxSum;\n }\n}", + "title": "53. Maximum Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n matrix , return all elements of the matrix in spiral order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 10", + "-100 <= matrix[i][j] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]Output:[1,2,3,6,9,8,7,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" + }, + { + "text": "Example 2: 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]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List spiralOrder(int[][] matrix) {\n List result = new ArrayList<>();\n\n if (matrix == null || matrix.length == 0)\n return result;\n\n int m = matrix.length, n = matrix[0].length;\n int top = 0, bottom = m - 1, left = 0, right = n - 1;\n\n while (top <= bottom && left <= right) {\n // Move Right\n for (int i = left; i <= right; i++)\n result.add(matrix[top][i]);\n top++;\n\n // Move Down\n for (int i = top; i <= bottom; i++)\n result.add(matrix[i][right]);\n right--;\n\n // Move Left (Check if we still have rows left)\n if (top <= bottom) {\n for (int i = right; i >= left; i--)\n result.add(matrix[bottom][i]);\n bottom--;\n }\n\n // Move Up (Check if we still have columns left)\n if (left <= right) {\n for (int i = bottom; i >= top; i--)\n result.add(matrix[i][left]);\n left++;\n }\n }\n \n return result;\n }\n}\n", + "title": "54. Spiral Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "0 <= nums[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,1,1,4]Output:trueExplanation:Jump 1 step from index 0 to 1, then 3 steps to the last index.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,1,0,4]Output:falseExplanation: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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canJump(int[] nums) {\n\n int steps = 0;\n\n for (int i = 0; i < nums.length; i++) {\n\n if (steps < i) {\n return false;\n }\n\n steps = Math.max(steps, i + nums[i]);\n\n if (steps >= nums.length - 1) {\n return true;\n }\n }\n return false;\n }\n}", + "title": "55. Jump Game", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^4", + "intervals[i].length == 2", + "0 <= start i <= end i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,4],[4,5]]Output:[[1,5]]Explanation:Intervals [1,4] and [4,5] are considered overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] merge(int[][] intervals) {\n\n Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));\n int index = 0;\n\n for (int i = 1; i < intervals.length; i++) {\n\n if (intervals[index][1] >= intervals[i][0]) {\n intervals[index][1] = Math.max(intervals[index][1], intervals[i][1]);\n } else {\n index++;\n intervals[index] = intervals[i];\n }\n }\n\n return Arrays.copyOfRange(intervals, 0, index + 1);\n }\n}\n", + "title": "56. Merge Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,3],[6,9]], newInterval = [2,5]Output:[[1,5],[6,9]]", + "image": null + }, + { + "text": "Example 2: 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].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n\n List result = new ArrayList<>();\n int i = 0, n = intervals.length;\n\n // Step 1: Add all intervals before newInterval\n while (i < n && intervals[i][1] < newInterval[0]) {\n result.add(intervals[i]);\n i++;\n }\n\n // Step 2: Merge overlapping intervals\n while (i < n && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(newInterval[0], intervals[i][0]);\n newInterval[1] = Math.max(newInterval[1], intervals[i][1]);\n i++;\n }\n result.add(newInterval);\n\n // Step 3: Add remaining intervals\n while (i < n) {\n result.add(intervals[i]);\n i++;\n }\n\n int[][] resultList = new int[result.size()][2];\n for (int j = 0; j < result.size(); j++) {\n resultList[j] = result.get(j);\n }\n \n return resultList;\n }\n}", + "title": "57. Insert Interval", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s consists of only English letters and spaces ' ' .", + "There will be at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"Hello World\"Output:5Explanation:The last word is \"World\" with length 5.", + "image": null + }, + { + "text": "Example 2: Input:s = \" fly me to the moon \"Output:4Explanation:The last word is \"moon\" with length 4.", + "image": null + }, + { + "text": "Example 3: Input:s = \"luffy is still joyboy\"Output:6Explanation:The last word is \"joyboy\" with length 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLastWord(String s) {\n\n String[] words = s.split(\" \");\n return words[words.length - 1].length();\n\n // int length = 0;\n // boolean count = false;\n\n // for (char c : s.toCharArray()) {\n\n // if (c != ' ') {\n\n // if (!count) {\n\n // count = true;\n // length = 1;\n // } else {\n // length++;\n // }\n // } else {\n // count = false;\n // }\n // }\n // return length;\n\n }\n}", + "title": "58. Length of Last Word", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, rotate the list to the right by k places. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 500] .", + "-100 <= Node.val <= 100", + "0 <= k <= 2 * 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], k = 2Output:[4,5,1,2,3]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg" + }, + { + "text": "Example 2: Input:head = [0,1,2], k = 4Output:[2,0,1]", + "image": "https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode rotateRight(ListNode head, int k) {\n\n if (head == null || head.next == null || k == 0)\n return head;\n\n ListNode tail = head;\n int length = 1;\n\n while (tail.next != null) {\n tail = tail.next;\n length++;\n }\n\n k = k % length;\n if (k == 0)\n return head;\n\n ListNode newTail = head;\n for (int i = 0; i < length - k - 1; i++) {\n newTail = newTail.next;\n }\n\n ListNode newHead = newTail.next;\n newTail.next = null;\n tail.next = head;\n\n return newHead;\n }\n}", + "title": "61. Rotate List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= m, n <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:m = 3, n = 7Output:28", + "image": "https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" + }, + { + "text": "Example 2: Input:m = 3, n = 2Output:3Explanation:From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePaths(int m, int n) { // Combinatorics\n long paths = 1;\n\n for (int i = 1; i <= m - 1; i++) { // The total number of unique ways = C(m+n-2, m-1)\n paths = paths * (n - 1 + i) / i;\n }\n\n return (int) paths;\n }\n}", + "title": "62. Unique Paths", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer array grid . There is a robot 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. An obstacle and space are marked as 1 or 0 respectively in grid . A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner . The testcases are generated so that the answer will be less than or equal to 2 * 10^9 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == obstacleGrid.length", + "n == obstacleGrid[i].length", + "1 <= m, n <= 100", + "obstacleGrid[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]Output:2Explanation:There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" + }, + { + "text": "Example 2: Input:obstacleGrid = [[0,1],[0,0]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n int[] dp = new int[obstacleGrid[0].length];\n\n dp[0] = obstacleGrid[0][0] == 0 ? 1 : 0;\n\n for (int[] row : obstacleGrid) {\n for (int col = 0; col < obstacleGrid[0].length; col++) {\n\n if (row[col] == 1)\n dp[col] = 0;\n else if (col > 0)\n dp[col] += dp[col - 1];\n }\n }\n\n return dp[obstacleGrid[0].length - 1];\n }\n}", + "title": "63. Unique Paths II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 200", + "0 <= grid[i][j] <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[1,3,1],[1,5,1],[4,2,1]]Output:7Explanation:Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.", + "image": "https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" + }, + { + "text": "Example 2: Input:grid = [[1,2,3],[4,5,6]]Output:12", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n int[][] dp = new int[m][n];\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n\n if (i == 0 && j == 0)\n dp[i][j] = grid[i][j];\n else {\n int up = i > 0 ? dp[i - 1][j] : Integer.MAX_VALUE;\n int left = j > 0 ? dp[i][j - 1] : Integer.MAX_VALUE;\n dp[i][j] = grid[i][j] + Math.min(up, left);\n }\n }\n }\n\n return dp[m - 1][n - 1];\n }\n}", + "title": "64. Minimum Path Sum", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= digits.length <= 100", + "0 <= digits[i] <= 9", + "digits does not contain any leading 0 's." + ], + "examples": [ + { + "text": "Example 1: Input:digits = [1,2,3]Output:[1,2,4]Explanation:The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].", + "image": null + }, + { + "text": "Example 2: Input:digits = [4,3,2,1]Output:[4,3,2,2]Explanation:The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].", + "image": null + }, + { + "text": "Example 3: Input:digits = [9]Output:[1,0]Explanation:The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] plusOne(int[] digits) {\n int n = digits.length;\n\n for (int i = n - 1; i >= 0; i--) {\n\n if (digits[i] < 9) {\n digits[i]++;\n return digits;\n }\n digits[i] = 0;\n }\n\n int[] newDigits = new int[n + 1];\n newDigits[0] = 1;\n return newDigits;\n }\n}", + "title": "66. Plus One", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two binary strings a and b , return their sum as a binary string . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= a.length, b.length <= 10^4", + "a and b consist only of '0' or '1' characters.", + "Each string does not contain leading zeros except for the zero itself." + ], + "examples": [ + { + "text": "Example 1: Input:a = \"11\", b = \"1\"Output:\"100\"", + "image": null + }, + { + "text": "Example 2: Input:a = \"1010\", b = \"1011\"Output:\"10101\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String addBinary(String a, String b) {\n\n StringBuilder result = new StringBuilder();\n int i = a.length() - 1, j = b.length() - 1, carry = 0;\n\n while (i >= 0 || j >= 0 || carry > 0) {\n int sum = carry;\n\n if (i >= 0)\n sum += a.charAt(i--) - '0'; // Convert char to int\n\n if (j >= 0)\n sum += b.charAt(j--) - '0';\n\n result.append(sum % 2);\n carry = sum / 2;\n }\n\n return result.reverse().toString();\n }\n}", + "title": "67. Add Binary", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of strings words and a width maxWidth , format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "A word is defined as a character sequence consisting of non-space characters only.", + "Each word's length is guaranteed to be greater than 0 and not exceed maxWidth .", + "The input array words contains at least one word." + ], + "examples": [ + { + "text": "Example 1: Input:words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16Output:[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]", + "image": null + }, + { + "text": "Example 2: Input:words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16Output:[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]Explanation:Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.", + "image": null + }, + { + "text": "Example 3: Input:words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20Output:[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n public List fullJustify(String[] words, int maxWidth) {\n List result = new ArrayList<>();\n int i = 0;\n\n while (i < words.length) {\n int j = i, lineLength = 0;\n // Find words that fit into the current line\n while (j < words.length && lineLength + words[j].length() + (j - i) <= maxWidth) {\n lineLength += words[j].length();\n j++;\n }\n\n int numWords = j - i;\n int numSpaces = maxWidth - lineLength;\n StringBuilder line = new StringBuilder();\n\n // If it's the last line or contains only one word -> left-justify\n if (j == words.length || numWords == 1) {\n for (int k = i; k < j; k++) {\n line.append(words[k]);\n if (k < j - 1)\n line.append(\" \"); // Space between words\n }\n // Fill the remaining spaces to match maxWidth\n while (line.length() < maxWidth) {\n line.append(\" \");\n }\n }\n // Otherwise, distribute spaces evenly\n else {\n int spacesBetween = numSpaces / (numWords - 1);\n int extraSpaces = numSpaces % (numWords - 1);\n\n for (int k = i; k < j; k++) {\n line.append(words[k]);\n if (k < j - 1) {\n int spaces = spacesBetween + (extraSpaces > 0 ? 1 : 0);\n extraSpaces--;\n for (int s = 0; s < spaces; s++) {\n line.append(\" \");\n }\n }\n }\n }\n\n result.add(line.toString());\n i = j; // Move to the next group of words\n }\n\n return result;\n }\n}\n", + "title": "68. Text Justification", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a non-negative integer x , return the square root of x rounded down to the nearest integer . The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python." + ], + "examples": [ + { + "text": "Example 1: Input:x = 4Output:2Explanation:The square root of 4 is 2, so we return 2.", + "image": null + }, + { + "text": "Example 2: Input:x = 8Output:2Explanation:The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int mySqrt(int x) {\n if (x < 2)\n return x;\n\n long num;\n int mid, low = 2, high = x / 2;\n\n while (low <= high) {\n mid = low + high >>> 1;\n num = (long) mid * mid;\n\n if (num > x) {\n high = mid - 1;\n } else if (num < x) {\n low = mid + 1;\n } else {\n return mid;\n }\n }\n\n return high;\n }\n}", + "title": "69. Sqrt(x)", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 45" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:2Explanation:There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps", + "image": null + }, + { + "text": "Example 2: Input:n = 3Output:3Explanation:There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int climbStairs(int n) {\n if(n == 1) return 1;\n int prev2 = 1, prev1 = 2;\n\n for(int i = 3; i <= n; i++) {\n int cur = prev1 + prev2;\n prev2 = prev1;\n prev1 = cur;\n }\n\n return prev1;\n }\n}", + "title": "70. Climbing Stairs", + "topic": "Stack" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an absolute path for a Unix-style file system, which always begins with a slash '/' . Your task is to transform this absolute path into its simplified canonical path . The rules of a Unix-style file system are as follows: The simplified canonical path should follow these rules : Return the simplified canonical path . Example 1: Input: path = \"/home/\" Output: \"/home\" Explanation: The trailing slash should be removed. Example 2: Input: path = \"/home//foo/\" Output: \"/home/foo\" Explanation: Multiple consecutive slashes are replaced by a single one. Example 3: Input: path = \"/home/user/Documents/../Pictures\" Output: \"/home/user/Pictures\" Explanation: A double period \"..\" refers to the directory up a level (the parent directory). Example 4: Input: path = \"/../\" Output: \"/\" Explanation: Going one level up from the root directory is not possible. Example 5: Input: path = \"/.../a/../b/c/../d/./\" Output: \"/.../b/d\" Explanation: \"...\" is a valid name for a directory in this problem.", + "description_images": [], + "constraints": [ + "A single period '.' represents the current directory.", + "A double period '..' represents the previous/parent directory.", + "Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/' .", + "Any sequence of periods that does not match the rules above should be treated as a valid directory or file name . For example, '...' and '....' are valid directory or file names." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public String simplifyPath(String path) {\n\n Stack stack = new Stack<>();\n String[] split = path.split(\"/\");\n\n for (String dir : split) {\n\n if (dir.equals(\"..\")) {\n\n if (!stack.isEmpty())\n stack.pop();\n\n } else if (!dir.isEmpty() && !dir.equals(\".\")) {\n stack.push(dir);\n }\n }\n\n return \"/\" + String.join(\"/\", stack);\n }\n}", + "title": "71. Simplify Path", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Insert a character", + "Delete a character", + "Replace a character" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"horse\", word2 = \"ros\"Output:3Explanation:horse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"intention\", word2 = \"execution\"Output:5Explanation:intention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minDistance(String word1, String word2) {\n int m = word1.length(), n = word2.length();\n Integer[][] memo = new Integer[m + 1][n + 1];\n \n return dp(word1, word2, m, n, memo);\n }\n\n private int dp(String word1, String word2, int i, int j, Integer[][] memo) {\n if (i == 0)\n return j;\n if (j == 0)\n return i;\n\n if (memo[i][j] != null)\n return memo[i][j];\n\n if (word1.charAt(i - 1) == word2.charAt(j - 1)) {\n memo[i][j] = dp(word1, word2, i - 1, j - 1, memo);\n\n } else {\n int insert = dp(word1, word2, i, j - 1, memo);\n int delete = dp(word1, word2, i - 1, j, memo);\n int replace = dp(word1, word2, i - 1, j - 1, memo);\n\n memo[i][j] = 1 + Math.min(insert, Math.min(delete, replace));\n }\n\n return memo[i][j];\n }\n}", + "title": "72. Edit Distance", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[0].length", + "1 <= m, n <= 200", + "-2 31 <= matrix[i][j] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]Output:[[1,0,1],[0,0,0],[1,0,1]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg" + }, + { + "text": "Example 2: 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]]", + "image": "https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void setZeroes(int[][] matrix) {\n\n int m = matrix.length, n = matrix[0].length;\n boolean firstRowZero = false, firstColZero = false;\n\n // Step 1: Check if first row/column should be zero\n for (int i = 0; i < m; i++) {\n if (matrix[i][0] == 0) {\n firstColZero = true;\n break;\n }\n }\n \n for (int j = 0; j < n; j++) {\n if (matrix[0][j] == 0) {\n firstRowZero = true;\n break;\n }\n }\n\n // Step 2: Mark zeroes using first row/column\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Step 3: Set zeroes using first row/column markers\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Step 4: Handle first row & column separately\n if (firstColZero) {\n for (int i = 0; i < m; i++) {\n matrix[i][0] = 0;\n }\n }\n\n if (firstRowZero) {\n for (int j = 0; j < n; j++) {\n matrix[0][j] = 0;\n }\n }\n\n }\n}", + "title": "73. Set Matrix Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n integer matrix matrix with the following two properties: 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: Example 2:", + "description_images": [], + "constraints": [ + "Each row is sorted in non-decreasing order.", + "The first integer of each row is greater than the last integer of the previous row." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return false;\n\n int rows = matrix.length, cols = matrix[0].length;\n int low = 0, high = rows * cols - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1; // Prevents overflow\n int midValue = matrix[mid / cols][mid % cols]; // Convert 1D index to 2D\n\n if (midValue == target)\n return true;\n else if (midValue < target)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return false;\n }\n}", + "title": "74. Search a 2D Matrix", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0 , 1 , and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 300", + "nums[i] is either 0 , 1 , or 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,0,2,1,1,0]Output:[0,0,1,1,2,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,0,1]Output:[0,1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void sortColors(int[] nums) {\n int[] count = new int[3];\n\n for (int num : nums) {\n count[num]++;\n }\n\n int index = 0;\n for (int i = 0; i <= 2; i++) {\n\n while (count[i]-- > 0) {\n nums[index++] = i;\n }\n }\n }\n}", + "title": "75. Sort Colors", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == s.length", + "n == t.length", + "1 <= m, n <= 10^5", + "s and t consist of uppercase and lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ADOBECODEBANC\", t = \"ABC\"Output:\"BANC\"Explanation:The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\", t = \"a\"Output:\"a\"Explanation:The entire string s is the minimum window.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a\", t = \"aa\"Output:\"\"Explanation:Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String minWindow(String s, String t) {\n // checking base cases\n if (s == null || t == null || s.length() == 0 || t.length() == 0 || s.length() < t.length()) {\n return \"\";\n }\n\n int[] map = new int[128];\n int count = t.length();\n int start = 0, minLen = Integer.MAX_VALUE, startIndex = 0;\n\n for (char ch : t.toCharArray()) { // creating a int map to store char frequency\n map[ch]++;\n }\n\n for (int end = 0; end < s.length(); end++) {\n // If character at `end` exists in `t`, decrement the count\n if (map[s.charAt(end)]-- > 0) {\n count--;\n }\n\n while (count == 0) {\n // Update minimum window size and starting index\n if (end - start + 1 < minLen) {\n startIndex = start;\n minLen = end - start + 1;\n }\n\n // Try to shrink the window from the left\n if (map[s.charAt(start)]++ == 0) {\n count++;\n }\n start++;\n }\n }\n\n return minLen == Integer.MAX_VALUE ? \"\" : s.substring(startIndex, startIndex + minLen);\n }\n}", + "title": "76. Minimum Window Substring", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 20", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, k = 2Output:[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Explanation:There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, k = 1Output:[[1]]Explanation:There is 1 choose 1 = 1 total combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combine(int n, int k) {\n List> result = new ArrayList<>();\n backtrack(1, new ArrayList<>(), n, k, result);\n return result;\n }\n\n private void backtrack(int start, List path, int n, int k, List> result) {\n if (path.size() == k) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i <= n; i++) {\n path.add(i);\n backtrack(i + 1, path, n, k, result);\n path.removeLast();\n }\n }\n}", + "title": "77. Combinations", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10", + "-10 <= nums[i] <= 10", + "All the numbers of nums are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3]Output:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[[],[0]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> subsets(int[] nums) {\n List> result = new ArrayList<>();\n List subset = new ArrayList<>();\n\n createSubset(nums, 0, result, subset);\n return result;\n }\n\n private void createSubset(int[] nums, int index, List> result, List subset) {\n if (index == nums.length) {\n result.add(new ArrayList<>(subset));\n return;\n }\n\n subset.add(nums[index]);\n createSubset(nums, index + 1, result, subset);\n\n subset.remove(subset.removeLast());\n createSubset(nums, index + 1, result, subset);\n }\n}", + "title": "78. Subsets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word2.jpg" + }, + { + "text": "Example 2: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg" + }, + { + "text": "Example 3: Input:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/15/word3.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length, n = board[0].length;\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (dfs(board, i, j, word, 0)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n private boolean dfs(char[][] board, int i, int j, String word, int index) {\n\n if (index == word.length()) {\n return true; // Word found\n }\n\n if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index)) {\n return false;\n }\n\n char temp = board[i][j];\n board[i][j] = '#'; // Mark visited\n\n boolean found = dfs(board, i + 1, j, word, index + 1) || // Down\n dfs(board, i - 1, j, word, index + 1) || // Up\n dfs(board, i, j + 1, word, index + 1) || // Right\n dfs(board, i, j - 1, word, index + 1); // Left\n\n board[i][j] = temp; // Backtrack\n return found;\n }\n}", + "title": "79. Word Search", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums sorted in non-decreasing order , remove some duplicates in-place such that each unique element appears at most twice . The relative order of the elements should be kept the same . Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums . More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums . Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in non-decreasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3]Output:5, nums = [1,1,2,2,3,_]Explanation:Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,1,1,2,3,3]Output:7, nums = [0,0,1,1,2,3,3,_,_]Explanation:Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).", + "image": null + }, + { + "text": "int[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int removeDuplicates(int[] nums) {\n\n int k = 1;\n\n for (int i = 1; i < nums.length; i++) {\n\n if (k == 1 || nums[i] != nums[k - 2]) {\n nums[k] = nums[i];\n k++;\n }\n }\n\n return k;\n }\n}", + "title": "80. Remove Duplicates from Sorted Array II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list . Return the linked list sorted as well . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,3,4,4,5]Output:[1,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,1,2,3]Output:[2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n\n if (head == null)\n return null;\n\n ListNode dummy = new ListNode(0, head);\n ListNode prev = dummy;\n ListNode current = head;\n\n while (current != null) {\n boolean isDuplicate = false;\n\n while (current.next != null && current.val == current.next.val) {\n isDuplicate = true;\n current = current.next;\n }\n\n if (isDuplicate) {\n prev.next = current.next;\n } else {\n prev = prev.next;\n }\n\n current = current.next;\n }\n\n return dummy.next;\n }\n}", + "title": "82. Remove Duplicates from Sorted List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once . Return the linked list sorted as well . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 300] .", + "-100 <= Node.val <= 100", + "The list is guaranteed to be sorted in ascending order." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,1,2]Output:[1,2]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/list1.jpg" + }, + { + "text": "Example 2: Input:head = [1,1,2,3,3]Output:[1,2,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/list2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n\n ListNode current = head;\n\n while (current != null && current.next != null) {\n\n if (current.val == current.next.val) {\n current.next = current.next.next;\n } else {\n current = current.next;\n }\n }\n\n return head;\n }\n}", + "title": "83. Remove Duplicates from Sorted List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= heights.length <= 10^5", + "0 <= heights[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:heights = [2,1,5,6,2,3]Output:10Explanation:The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.", + "image": "https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg" + }, + { + "text": "Example 2: Input:heights = [2,4]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestRectangleArea(int[] heights) {\n int n = heights.length;\n int[] newHeights = new int[n + 2];\n System.arraycopy(heights, 0, newHeights, 1, n);\n\n Stack stack = new Stack<>();\n int maxArea = 0;\n\n for (int i = 0; i < newHeights.length; i++) {\n\n while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {\n int height = newHeights[stack.pop()];\n int width = i - stack.peek() - 1;\n maxArea = Math.max(maxArea, height * width);\n }\n stack.push(i);\n }\n\n return maxArea;\n }\n}", + "title": "84. Largest Rectangle in Histogram", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 200] .", + "-100 <= Node.val <= 100", + "-200 <= x <= 200" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,4,3,2,5,2], x = 3Output:[1,2,2,4,3,5]", + "image": "https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" + }, + { + "text": "Example 2: Input:head = [2,1], x = 2Output:[1,2]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode partition(ListNode head, int x) {\n\n if (head == null || head.next == null)\n return head;\n\n ListNode lessHead = new ListNode(0);\n ListNode greaterHead = new ListNode(0);\n\n ListNode less = lessHead;\n ListNode greater = greaterHead;\n ListNode current = head;\n\n while (current != null) {\n\n if (current.val < x) {\n less.next = current;\n less = less.next;\n } else {\n greater.next = current;\n greater = greater.next;\n }\n\n current = current.next;\n }\n\n greater.next = null;\n less.next = greaterHead.next;\n\n return lessHead.next;\n }\n}", + "title": "86. Partition List", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 , sorted in non-decreasing order , and two integers m and n , representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order . The final sorted array should not be returned by the function, but instead be stored inside the array nums1 . To accommodate this, nums1 has a length of m + n , where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "nums1.length == m + n", + "nums2.length == n", + "0 <= m, n <= 200", + "1 <= m + n <= 200", + "-10^9 <= nums1[i], nums2[j] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3Output:[1,2,2,3,5,6]Explanation:The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1], m = 1, nums2 = [], n = 0Output:[1]Explanation:The arrays we are merging are [1] and [].\nThe result of the merge is [1].", + "image": null + }, + { + "text": "Example 3: Input:nums1 = [0], m = 0, nums2 = [1], n = 1Output:[1]Explanation:The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // using two-pointer approch\n\n int p1 = m - 1; // Last valid element in nums1\n int p2 = n - 1; // Last element in nums2\n int p = m + n - 1; // Last position in nums1\n\n while (p1 >= 0 && p2 >= 0) {\n\n if (nums1[p1] > nums2[p2]) {\n nums1[p] = nums1[p1];\n p1--;\n\n } else {\n nums1[p] = nums2[p2];\n p2--;\n }\n p--;\n }\n\n // copying remaining to nums1\n while (p2 >= 0) {\n nums1[p] = nums2[p2];\n p2--;\n p--;\n }\n }\n}", + "title": "88. Merge Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list and two integers left and right where left <= right , reverse the nodes of the list from position left to position right , and return the reversed list . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is n .", + "1 <= n <= 500", + "-500 <= Node.val <= 500", + "1 <= left <= right <= n" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5], left = 2, right = 4Output:[1,4,3,2,5]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg" + }, + { + "text": "Example 2: Input:head = [5], left = 1, right = 1Output:[5]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if (head == null || left == right)\n return head;\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n ListNode prev = dummy;\n\n // Move `prev` to just before `left`\n for (int i = 1; i < left; i++) {\n prev = prev.next;\n }\n\n // Reverse sublist from `left` to `right`\n ListNode curr = prev.next;\n ListNode next = null;\n ListNode prevSublist = null;\n\n for (int i = left; i <= right; i++) {\n next = curr.next;\n curr.next = prevSublist;\n prevSublist = curr;\n curr = next;\n }\n\n prev.next.next = curr; // Connect end of reversed list to remaining list\n prev.next = prevSublist; // Connect start of reversed list to prev node\n\n return dummy.next;\n }\n}", + "title": "92. Reverse Linked List II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the inorder traversal of its nodes' values . Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,2,6,5,7,1,3,9,8] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1]", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List inorderTraversal(TreeNode root) {\n List list = new ArrayList<>();\n inorder(root, list);\n return list;\n }\n\n private void inorder(TreeNode root, List list) {\n if (root == null)\n return;\n\n inorder(root.left, list);\n list.add(root.val);\n inorder(root.right, list);\n }\n}", + "title": "94. Binary Tree Inorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Note: a + b is the concatenation of strings a and b . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 + ..." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"Output:trueExplanation:One way to obtain s3 is:\nSplit s1 into s1 = \"aa\" + \"bc\" + \"c\", and s2 into s2 = \"dbbc\" + \"a\".\nInterleaving the two splits, we get \"aa\" + \"dbbc\" + \"bc\" + \"a\" + \"c\" = \"aadbbcbcac\".\nSince s3 can be obtained by interleaving s1 and s2, we return true.", + "image": "https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg" + }, + { + "text": "Example 2: Input:s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"Output:falseExplanation:Notice how it is impossible to interleave s2 with any other string to obtain s3.", + "image": null + }, + { + "text": "Example 3: Input:s1 = \"\", s2 = \"\", s3 = \"\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isInterleave(String s1, String s2, String s3) {\n\n if (s1.length() + s2.length() != s3.length())\n return false;\n Boolean[][] memo = new Boolean[s1.length() + 1][s2.length() + 1];\n return dfs(0, 0, s1, s2, s3, memo);\n }\n\n private boolean dfs(int i, int j, String s1, String s2, String s3, Boolean[][] memo) {\n if (i == s1.length() && j == s2.length())\n return true;\n if (memo[i][j] != null)\n return memo[i][j];\n\n int k = i + j;\n\n if (i < s1.length() && s1.charAt(i) == s3.charAt(k)) {\n if (dfs(i + 1, j, s1, s2, s3, memo)) {\n return memo[i][j] = true;\n }\n }\n\n if (j < s2.length() && s2.charAt(j) == s3.charAt(k)) {\n if (dfs(i, j + 1, s1, s2, s3, memo)) {\n return memo[i][j] = true;\n }\n }\n\n return memo[i][j] = false;\n }\n}", + "title": "97. Interleaving String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, determine if it is a valid binary search tree (BST) . A valid BST is defined as follows: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The left subtree of a node contains only nodes with keys less than the node's key.", + "The right subtree of a node contains only nodes with keys greater than the node's key.", + "Both the left and right subtrees must also be binary search trees." + ], + "examples": [ + { + "text": "Example 1: Input:root = [2,1,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,1,4,null,null,3,6]Output:falseExplanation:The root node's value is 5 but its right child's value is 4.", + "image": "https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return validate(root, null, null);\n }\n\n private boolean validate(TreeNode node, Integer min, Integer max) {\n if (node == null)\n return true;\n\n if ((min != null && node.val <= min) || (max != null && node.val >= max))\n return false;\n\n return validate(node.left, min, node.val) && validate(node.right, node.val, max);\n }\n}", + "title": "98. Validate Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in both trees is in the range [0, 100] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:p = [1,2,3], q = [1,2,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" + }, + { + "text": "Example 2: Input:p = [1,2], q = [1,null,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" + }, + { + "text": "Example 3: Input:p = [1,2,1], q = [1,1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n\n if (p == null && q == null)\n return true;\n if (p == null || q == null)\n return false;\n if (p.val != q.val)\n return false;\n\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}", + "title": "100. Same Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 1000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,2,3,4,4,3]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,null,3,null,3]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isSymmetric(TreeNode root) {\n\n if (root == null)\n return true;\n\n return isMirror(root.left, root.right);\n }\n\n private boolean isMirror(TreeNode t1, TreeNode t2) {\n\n if (t1 == null && t2 == null)\n return true;\n if (t1 == null || t2 == null)\n return false;\n if (t1.val != t2.val)\n return false;\n\n return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);\n }\n}", + "title": "101. Symmetric Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[3],[9,20],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> levelOrder(TreeNode root) {\n List> result = new ArrayList<>();\n Queue queue = new LinkedList<>();\n\n if(root == null) return result;\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n int level = queue.size();\n List levelNodes = new ArrayList<>();\n\n for (int i = 0; i < level; i++) {\n TreeNode node = queue.poll();\n levelNodes.add(node.val);\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(levelNodes);\n }\n\n return result;\n }\n}", + "title": "102. Binary Tree Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values . (i.e., from left to right, then right to left for the next level and alternate between). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 2000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[[3],[20,9],[15,7]]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [1]Output:[[1]]", + "image": null + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List> zigzagLevelOrder(TreeNode root) {\n\n List> result = new ArrayList<>();\n if (root == null)\n return result;\n\n Queue queue = new LinkedList<>();\n queue.offer(root);\n boolean leftToRight = true;\n\n while (!queue.isEmpty()) {\n int levelSize = queue.size();\n Deque levelNodes = new LinkedList<>();\n\n for (int i = 0; i < levelSize; i++) {\n TreeNode node = queue.poll();\n\n if (leftToRight) {\n levelNodes.addLast(node.val);\n } else {\n levelNodes.addFirst(node.val);\n }\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(new ArrayList<>(levelNodes));\n leftToRight = !leftToRight;\n }\n\n return result;\n }\n}", + "title": "103. Binary Tree Zigzag Level Order Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" + }, + { + "text": "Example 2: Input:root = [1,null,2]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxDepth(TreeNode root) {\n \n if (root == null) {\n return 0;\n }\n return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));\n }\n}", + "title": "104. Maximum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:preorder = [-1], inorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n int preIndex = 0;\n HashMap inMap;\n\n public TreeNode buildTree(int[] preorder, int[] inorder) {\n inMap = new HashMap<>();\n\n for (int i = 0; i < inorder.length; i++) {\n inMap.put(inorder[i], i); // (key,value) -> (array value, index)\n }\n\n return build(preorder, 0, inorder.length - 1);\n }\n\n private TreeNode build(int[] preorder, int left, int right) {\n if (left > right)\n return null;\n\n int rootValue = preorder[preIndex++];\n int inIndex = inMap.get(rootValue);\n TreeNode root = new TreeNode(rootValue);\n\n root.left = build(preorder, left, inIndex - 1);\n root.right = build(preorder, inIndex + 1, right);\n\n return root;\n }\n}", + "title": "105. Construct Binary Tree from Preorder and Inorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= inorder.length <= 3000", + "postorder.length == inorder.length", + "-3000 <= inorder[i], postorder[i] <= 3000", + "inorder and postorder consist of unique values.", + "Each value of postorder also appears in inorder .", + "inorder is guaranteed to be the inorder traversal of the tree.", + "postorder is guaranteed to be the postorder traversal of the tree." + ], + "examples": [ + { + "text": "Example 1: Input:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]Output:[3,9,20,null,null,15,7]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" + }, + { + "text": "Example 2: Input:inorder = [-1], postorder = [-1]Output:[-1]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n\n private static int postIndex;\n private static HashMap inorderMap;\n\n public static TreeNode buildTree(int[] inorder, int[] postorder) {\n inorderMap = new HashMap<>();\n postIndex = postorder.length - 1;\n\n for (int i = 0; i < inorder.length; i++) {\n inorderMap.put(inorder[i], i);\n }\n return build(postorder, 0, inorder.length - 1);\n }\n\n private static TreeNode build(int[] postorder, int left, int right) {\n if (left > right)\n return null;\n\n int rootValue = postorder[postIndex--];\n TreeNode root = new TreeNode(rootValue);\n int inorderIndex = inorderMap.get(rootValue);\n\n root.right = build(postorder, inorderIndex + 1, right);\n root.left = build(postorder, left, inorderIndex - 1);\n\n return root;\n }\n}", + "title": "106. Construct Binary Tree from Inorder and Postorder Traversal", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums where the elements are sorted in ascending order , convert it to a height-balanced binary search tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-10^4 <= nums[i] <= 10^4", + "nums is sorted in a strictly increasing order." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-10,-3,0,5,9]Output:[0,-3,9,-10,null,5]Explanation:[0,-10,5,null,-3,null,9] is also accepted:", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" + }, + { + "text": "Example 2: Input:nums = [1,3]Output:[3,1]Explanation:[1,null,3] and [3,1] are both height-balanced BSTs.", + "image": "https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode sortedArrayToBST(int[] nums) {\n return constructBST(nums, 0, nums.length - 1);\n }\n\n private TreeNode constructBST(int[] nums, int left, int right) {\n if (left > right)\n return null;\n\n int mid = left + (right - left) / 2;\n TreeNode root = new TreeNode(nums[mid]);\n\n root.left = constructBST(nums, left, mid - 1);\n root.right = constructBST(nums, mid + 1, right);\n\n return root;\n }\n}", + "title": "108. Convert Sorted Array to Binary Search Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree, determine if it is height-balanced . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-10^4 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,2,3,3,null,null,4,4]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" + }, + { + "text": "Example 3: Input:root = []Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isBalanced(TreeNode root) {\n return findH(root) == -1 ? false : true;\n }\n\n public int findH(TreeNode root) {\n if (root == null)\n return 0;\n int left = findH(root.left);\n if (left == -1)\n return -1;\n int right = findH(root.right);\n if (right == -1)\n return -1;\n if (Math.abs(left - right) > 1)\n return -1;\n return 1 + Math.max(left, right);\n }\n}", + "title": "110. Balanced Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^5 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" + }, + { + "text": "Example 2: Input:root = [2,null,3,null,4,null,5,null,6]Output:5", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int minDepth(TreeNode root) {\n if (root == null)\n return 0;\n\n if (root.left == null)\n return minDepth(root.right) + 1;\n\n if (root.right == null)\n return minDepth(root.left) + 1;\n\n return Math.min(minDepth(root.left), minDepth(root.right)) + 1;\n }\n}", + "title": "111. Minimum Depth of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5000] .", + "-1000 <= Node.val <= 1000", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output:trueExplanation:The root-to-leaf path with the target sum is shown.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" + }, + { + "text": "Example 2: Input:root = [1,2,3], targetSum = 5Output:falseExplanation:There are two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.", + "image": "https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" + }, + { + "text": "Example 3: Input:root = [], targetSum = 0Output:falseExplanation:Since the tree is empty, there are no root-to-leaf paths.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n\n if (root == null)\n return false;\n\n if (root.left == null && root.right == null) {\n return targetSum == root.val;\n }\n\n return hasPathSum(root.left, targetSum - root.val) ||\n hasPathSum(root.right, targetSum - root.val);\n }\n}", + "title": "112. Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, flatten the tree into a \"linked list\": Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null .", + "The \"linked list\" should be in the same order as a pre-order traversal of the binary tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,5,3,4,null,6]Output:[1,null,2,null,3,null,4,null,5,null,6]", + "image": "https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "Example 3: Input:root = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public void flatten(TreeNode root) {\n\n while (root != null) {\n\n if (root.left != null) {\n TreeNode rightmost = root.left;\n\n while (rightmost.right != null) {\n rightmost = rightmost.right;\n }\n\n rightmost.right = root.right;\n root.right = root.left;\n root.left = null;\n }\n\n root = root.right;\n }\n }\n}", + "title": "114. Flatten Binary Tree to Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL . Initially, all next pointers are set to NULL . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 6000] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,null,7]Output:[1,#,2,3,#,4,5,7,#]Explanation:Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.", + "image": "https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + }, + { + "text": "struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public Node left;\n public Node right;\n public Node next;\n\n public Node() {}\n \n public Node(int _val) {\n val = _val;\n }\n\n public Node(int _val, Node _left, Node _right, Node _next) {\n val = _val;\n left = _left;\n right = _right;\n next = _next;\n }\n};\n*/\n\nclass Solution {\n public Node connect(Node root) { // LinkedList Implementation to achieve Space Complexity O(1)\n\n Node dummy = new Node(0);\n Node prev = dummy;\n Node curr = root;\n\n while (curr != null) {\n\n if (curr.left != null) {\n prev.next = curr.left;\n prev = prev.next;\n }\n\n if (curr.right != null) {\n prev.next = curr.right;\n prev = prev.next;\n }\n\n curr = curr.next;\n if (curr == null) {\n curr = dummy.next;\n dummy.next = null;\n prev = dummy;\n }\n }\n\n return root;\n }\n}", + "title": "117. Populating Next Right Pointers in Each Node II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer numRows , return the first numRows of Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= numRows <= 30" + ], + "examples": [ + { + "text": "Example 1: Input:numRows = 5Output:[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]", + "image": null + }, + { + "text": "Example 2: Input:numRows = 1Output:[[1]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> generate(int numRows) {\n List> result = new ArrayList<>();\n if (numRows == 0) {\n return result;\n }\n\n if (numRows == 1) {\n List firstRow = new ArrayList<>();\n firstRow.add(1);\n result.add(firstRow);\n return result;\n }\n\n result = generate(numRows - 1);\n List prevRow = result.get(numRows - 2);\n List currentRow = new ArrayList<>();\n currentRow.add(1);\n\n for (int i = 1; i < numRows - 1; i++) {\n currentRow.add(prevRow.get(i - 1) + prevRow.get(i));\n }\n\n currentRow.add(1);\n result.add(currentRow);\n\n return result;\n }\n}", + "title": "118. Pascal's Triangle", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle . In Pascal's triangle , each number is the sum of the two numbers directly above it as shown: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= rowIndex <= 33" + ], + "examples": [ + { + "text": "Example 1: Input:rowIndex = 3Output:[1,3,3,1]", + "image": null + }, + { + "text": "Example 2: Input:rowIndex = 0Output:[1]", + "image": null + }, + { + "text": "Example 3: Input:rowIndex = 1Output:[1,1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List getRow(int rowIndex) {\n List row = new ArrayList<>();\n long value = 1;\n row.add(1);\n\n for (int k = 1; k <= rowIndex; k++) {\n value = value * (rowIndex - k + 1) / k;\n row.add((int) value);\n }\n\n return row;\n }\n}", + "title": "119. Pascal's Triangle II", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a triangle array, return the minimum path sum from top to bottom . For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= triangle.length <= 200", + "triangle[0].length == 1", + "triangle[i].length == triangle[i - 1].length + 1", + "-10^4 <= triangle[i][j] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]Output:11Explanation:The triangle looks like:234\n 657\n418 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).", + "image": null + }, + { + "text": "Example 2: Input:triangle = [[-10]]Output:-10", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minimumTotal(List> triangle) {\n int n = triangle.size();\n int[] dp = new int[n];\n\n for (int i = 0; i < n; i++) {\n dp[i] = triangle.get(n - 1).get(i);\n }\n\n for (int row = n - 2; row >= 0; row--) {\n for (int col = 0; col <= row; col++) {\n dp[col] = triangle.get(row).get(col) + Math.min(dp[col], dp[col + 1]);\n }\n }\n\n return dp[0];\n }\n}", + "title": "120. Triangle", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:5Explanation:Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.", + "image": null + }, + { + "text": "Example 2: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transactions are done and the max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "// class Solution { // solution - 1 : Kadane's Algorithm -> takes 2ms time\n// public int maxProfit(int[] prices) {\n\n// int buy = prices[0], maxProfit = 0;\n\n// for (int i = 1; i < prices.length; i++) {\n\n// if (prices[i] < buy) { // lower price to buy\n// buy = prices[i]; // update min price to buy\n// } else if (prices[i] - buy > maxProfit) {\n// maxProfit = prices[i] - buy; // profit = selling price - buying price\n// }\n// }\n\n// return maxProfit;\n// }\n// }\n\nclass Solution { // solution - 1 : DP -> takes 0ms time\n public int maxProfit(int[] prices) {\n \n int minPrice = Integer.MAX_VALUE;\n int maxProfit = 0;\n \n for (int currentPrice : prices) {\n minPrice = Math.min(currentPrice, minPrice);\n maxProfit = Math.max(maxProfit, currentPrice - minPrice);\n }\n \n return maxProfit;\n }\n}", + "title": "121. Best Time to Buy and Sell Stock", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day . Find and return the maximum profit you can achieve . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 3 * 10^4", + "0 <= prices[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [7,1,5,3,6,4]Output:7Explanation:Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n\n // using simple array iteration\n int profit = 0;\n for (int i = 1; i < prices.length; i++) {\n\n if (prices[i] > prices[i - 1]) {\n profit += prices[i] - prices[i - 1];\n }\n }\n\n return profit;\n }\n}", + "title": "122. Best Time to Buy and Sell Stock II", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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 at most two transactions . Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= prices.length <= 10^5", + "0 <= prices[i] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:prices = [3,3,5,0,0,3,1,4]Output:6Explanation:Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,2,3,4,5]Output:4Explanation:Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.", + "image": null + }, + { + "text": "Example 3: Input:prices = [7,6,4,3,1]Output:0Explanation:In this case, no transaction is done, i.e. max profit = 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices) {\n int buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE;\n int sell1 = 0, sell2 = 0;\n\n for (int price : prices) {\n buy1 = Math.max(buy1, -price);\n sell1 = Math.max(sell1, buy1 + price);\n buy2 = Math.max(buy2, sell1 - price);\n sell2 = Math.max(sell2, buy2 + price);\n }\n\n return sell2;\n }\n}", + "title": "123. Best Time to Buy and Sell Stock III", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 3 * 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:6Explanation:The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg" + }, + { + "text": "Example 2: Input:root = [-10,9,20,null,null,15,7]Output:42Explanation:The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.", + "image": "https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxSum = Integer.MIN_VALUE;\n\n public int maxPathSum(TreeNode root) {\n dfs(root);\n return maxSum;\n }\n\n private int dfs(TreeNode node) {\n if (node == null)\n return 0;\n\n int left = Math.max(0, dfs(node.left));\n int right = Math.max(0, dfs(node.right));\n maxSum = Math.max(maxSum, left + right + node.val);\n\n return Math.max(left, right) + node.val;\n }\n}", + "title": "124. Binary Tree Maximum Path Sum", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2 * 10^5", + "s consists only of printable ASCII characters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"A man, a plan, a canal: Panama\"Output:trueExplanation:\"amanaplanacanalpanama\" is a palindrome.", + "image": null + }, + { + "text": "Example 2: Input:s = \"race a car\"Output:falseExplanation:\"raceacar\" is not a palindrome.", + "image": null + }, + { + "text": "Example 3: Input:s = \" \"Output:trueExplanation:s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isPalindrome(String s) { // two pinter approach\n\n s = s.toLowerCase().replaceAll(\"[^a-z0-9]\", \"\");\n int start = 0, end = s.length() - 1;\n\n while (start < end) {\n\n if (s.charAt(start) != s.charAt(end)) {\n return false;\n }\n start++;\n end--;\n }\n return true;\n }\n}", + "title": "125. Valid Palindrome", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: 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: Example 2:", + "description_images": [], + "constraints": [ + "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" + ], + "examples": [ + { + "text": "Example 1: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]Output:5Explanation:One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.", + "image": null + }, + { + "text": "Example 2: Input:beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]Output:0Explanation:The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int ladderLength(String beginWord, String endWord, List wordList) {\n Set wordSet = new HashSet<>(wordList);\n\n if (!wordSet.contains(endWord))\n return 0;\n\n Queue queue = new LinkedList<>();\n queue.offer(beginWord);\n int level = 1;\n\n Set visited = new HashSet<>();\n visited.add(beginWord);\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n String currentWord = queue.poll();\n char[] wordArray = currentWord.toCharArray();\n\n for (int j = 0; j < wordArray.length; j++) {\n char originalChar = wordArray[j];\n\n // Try all letters from 'a' to 'z'\n for (char c = 'a'; c <= 'z'; c++) {\n wordArray[j] = c;\n String newWord = new String(wordArray);\n\n // If newWord is in the other set, we have found a path\n if (newWord.equals(endWord)) {\n return level + 1;\n }\n\n // If newWord exists in wordSet and hasn't been visited\n if (wordSet.contains(newWord) && !visited.contains(newWord)) {\n queue.offer(newWord);\n visited.add(newWord);\n }\n }\n\n wordArray[j] = originalChar; // Restore the original character\n }\n }\n level++;\n }\n\n return 0;\n }\n}", + "title": "127. Word Ladder", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "0 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [100,4,200,1,3,2]Output:4Explanation:The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,3,7,2,5,8,4,6,0,1]Output:9", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestConsecutive(int[] nums) {\n if (nums.length == 0)\n return 0;\n\n HashSet set = new HashSet<>();\n for (int n : nums) {\n set.add(n);\n }\n\n int longestSeq = 0;\n for (int num : set) {\n\n if (!set.contains(num - 1)) {\n int currentNum = num;\n int currentSeq = 1;\n\n while (set.contains(currentNum + 1)) {\n currentNum++;\n currentSeq++;\n }\n\n longestSeq = Math.max(longestSeq, currentSeq);\n }\n }\n\n return longestSeq;\n }\n}", + "title": "128. Longest Consecutive Sequence", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. Return the total sum of all root-to-leaf numbers . Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123 ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3]Output:25Explanation:The root-to-leaf path1->2represents the number12.\nThe root-to-leaf path1->3represents the number13.\nTherefore, sum = 12 + 13 =25.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg" + }, + { + "text": "Example 2: Input:root = [4,9,0,5,1]Output:1026Explanation:The root-to-leaf path4->9->5represents the number 495.\nThe root-to-leaf path4->9->1represents the number 491.\nThe root-to-leaf path4->0represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026.", + "image": "https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg" + } + ], + "follow_up": null, + "solution": "\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int sumNumbers(TreeNode root) {\n return dfs(root, 0);\n }\n\n private int dfs(TreeNode node, int currentSum) {\n if (node == null)\n return 0;\n\n currentSum = currentSum * 10 + node.val;\n\n // If it's a leaf node, return the accumulated sum\n if (node.left == null && node.right == null) {\n return currentSum;\n }\n\n // Recursively sum left and right subtrees\n return dfs(node.left, currentSum) + dfs(node.right, currentSum);\n }\n}", + "title": "129. Sum Root to Leaf Numbers", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix board containing letters 'X' and 'O' , capture regions that are surrounded : 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\"]]", + "description_images": [], + "constraints": [ + "Connect : A cell is connected to adjacent cells horizontally or vertically.", + "Region : To form a region connect every 'O' cell.", + "Surround : The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public void solve(char[][] board) {\n if (board == null || board.length == 0)\n return;\n\n int rows = board.length, cols = board[0].length;\n Queue queue = new LinkedList<>();\n\n // Step 1: Capture all border 'O's into the queue\n for (int i = 0; i < rows; i++) {\n\n if (board[i][0] == 'O')\n queue.offer(new int[] { i, 0 });\n\n if (board[i][cols - 1] == 'O')\n queue.offer(new int[] { i, cols - 1 });\n }\n\n for (int j = 0; j < cols; j++) {\n\n if (board[0][j] == 'O')\n queue.offer(new int[] { 0, j });\n\n if (board[rows - 1][j] == 'O')\n queue.offer(new int[] { rows - 1, j });\n }\n\n // Step 2: BFS to mark connected 'O's as safe ('#')\n int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int r = cell[0], c = cell[1];\n\n if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != 'O')\n continue;\n\n board[r][c] = '#';\n\n for (int[] dir : directions) {\n queue.offer(new int[] { r + dir[0], c + dir[1] });\n }\n }\n\n // Step 3: Flip surrounded 'O' to 'X' and restore '#' to 'O'\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n\n if (board[i][j] == 'O')\n board[i][j] = 'X'; // Flip surrounded\n\n if (board[i][j] == '#')\n board[i][j] = 'O'; // Restore safe regions\n }\n }\n }\n\n}", + "title": "130. Surrounded Regions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 16", + "s contains only lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"aab\"Output:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:[[\"a\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> partition(String s) {\n return dfs(s, 0, new HashMap<>());\n }\n\n private List> dfs(String s, int start, Map>> memo) {\n if (memo.containsKey(start)) {\n return memo.get(start);\n }\n\n List> result = new ArrayList<>();\n if (start == s.length()) {\n result.add(new ArrayList<>());\n }\n\n for (int end = start; end < s.length(); end++) {\n\n if (isPalindrome(s, start, end)) {\n String prefix = s.substring(start, end + 1);\n\n for (List sub : dfs(s, end + 1, memo)) {\n List newList = new ArrayList<>();\n newList.add(prefix);\n newList.addAll(sub);\n result.add(newList);\n }\n }\n }\n\n memo.put(start, result);\n return result;\n }\n\n private boolean isPalindrome(String s, int l, int r) {\n while (l < r) {\n if (s.charAt(l++) != s.charAt(r--))\n return false;\n }\n return true;\n }\n}", + "title": "131. Palindrome Partitioning", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. 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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: 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.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).", + "image": "https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" + }, + { + "text": "Example 2: 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.", + "image": "https://assets.leetcode.com/uploads/2020/01/07/graph.png" + }, + { + "text": "Example 3: Input:adjList = []Output:[]Explanation:This an empty graph, it does not have any nodes.", + "image": null + }, + { + "text": "class Node {\n public int val;\n public List neighbors;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public Node cloneGraph(Node node) {\n if (node == null)\n return null;\n\n Map clonedNodes = new HashMap<>();\n\n return dfs(node, clonedNodes);\n }\n\n private Node dfs(Node node, Map clonedNodes) {\n\n if (clonedNodes.containsKey(node))\n return clonedNodes.get(node);\n\n Node clone = new Node(node.val);\n clonedNodes.put(node, clone);\n\n for (Node neighbor : node.neighbors) {\n clone.neighbors.add(dfs(neighbor, clonedNodes));\n }\n\n return clone;\n }\n}", + "title": "133. Clone Graph", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == gas.length == cost.length", + "1 <= n <= 10^5", + "0 <= gas[i], cost[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:gas = [1,2,3,4,5], cost = [3,4,5,1,2]Output:3Explanation:Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.", + "image": null + }, + { + "text": "Example 2: Input:gas = [2,3,4], cost = [3,4,3]Output:-1Explanation:You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int canCompleteCircuit(int[] gas, int[] cost) { // using gready approach\n\n int totalGas = 0, totalCost = 0;\n int total = 0, start = 0;\n int n = gas.length;\n\n for (int i = 0; i < n; i++) {\n totalGas += gas[i];\n totalCost += cost[i];\n }\n\n if (totalGas < totalCost) {\n return -1;\n }\n\n for (int i = 0; i < n; i++) {\n total += gas[i] - cost[i];\n\n if (total < 0) {\n total = 0;\n start = i + 1;\n }\n }\n\n return start;\n }\n}", + "title": "134. Gas Station", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings . You are giving candies to these children subjected to the following requirements: Return the minimum number of candies you need to have to distribute the candies to the children . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Each child must have at least one candy.", + "Children with a higher rating get more candies than their neighbors." + ], + "examples": [ + { + "text": "Example 1: Input:ratings = [1,0,2]Output:5Explanation:You can allocate to the first, second and third child with 2, 1, 2 candies respectively.", + "image": null + }, + { + "text": "Example 2: Input:ratings = [1,2,2]Output:4Explanation:You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int candy(int[] ratings) { // using gready approach\n\n int n = ratings.length;\n int[] candies = new int[n];\n Arrays.fill(candies, 1);\n int total = 0;\n\n for (int i = 1; i < n; i++) {\n if (ratings[i] > ratings[i - 1]) {\n candies[i] = candies[i - 1] + 1;\n }\n }\n\n for (int i = n - 2; i >= 0; i--) {\n if (ratings[i] > ratings[i + 1]) {\n candies[i] = candies[i + 1] + 1 > candies[i] ? candies[i + 1] + 1 : candies[i];\n }\n }\n\n for (int candy : candies) {\n total += candy;\n }\n\n return total;\n }\n}", + "title": "135. Candy", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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", + "description_images": [], + "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." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int singleNumber(int[] nums) {\n int result = 0;\n\n for (int num : nums) {\n result ^= num;\n }\n\n return result;\n }\n}", + "title": "136. Single Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums where every element appears three times except for one, which appears exactly once . Find the single element and return it . You must implement a solution with a linear runtime complexity and use only constant extra space. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 3 * 10^4", + "-2 31 <= nums[i] <= 2 31 - 1", + "Each element in nums appears exactly three times except for one element which appears once ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,2,3,2]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,1,0,1,99]Output:99", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int singleNumber(int[] nums) {\n int ones = 0, twos = 0;\n\n for (int num : nums) {\n ones = (ones ^ num) & ~twos; // Add new number or remove it if seen twice\n twos = (twos ^ num) & ~ones; // Track numbers that appear twice\n }\n\n return ones;\n }\n}", + "title": "137. Single Number II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Your code will only be given the head of the original linked list. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2019/12/18/e3.png" + ], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]Output:[[7,null],[13,0],[11,4],[10,2],[1,0]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e1.png" + }, + { + "text": "Example 2: Input:head = [[1,1],[2,1]]Output:[[1,1],[2,1]]", + "image": "https://assets.leetcode.com/uploads/2019/12/18/e2.png" + }, + { + "text": "Example 3: Input:head = [[3,null],[3,0],[3,null]]Output:[[3,null],[3,0],[3,null]]", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a Node.\nclass Node {\n int val;\n Node next;\n Node random;\n\n public Node(int val) {\n this.val = val;\n this.next = null;\n this.random = null;\n }\n}\n*/\n\nclass Solution {\n public Node copyRandomList(Node head) {\n\n if (head == null)\n return null;\n\n Node current = head;\n while (current != null) {\n Node copy = new Node(current.val);\n copy.next = current.next;\n current.next = copy;\n current = copy.next;\n }\n\n current = head;\n while (current != null) {\n if (current.random != null) {\n current.next.random = current.random.next;\n }\n current = current.next.next;\n }\n\n Node dummyHead = new Node(0);\n Node copyCurrent = dummyHead;\n current = head;\n\n while (current != null) {\n copyCurrent.next = current.next;\n copyCurrent = copyCurrent.next;\n current.next = current.next.next;\n current = current.next;\n }\n\n return dummyHead.next;\n }\n}", + "title": "138. Copy List with Random Pointer", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leetcode\", wordDict = [\"leet\",\"code\"]Output:trueExplanation:Return true because \"leetcode\" can be segmented as \"leet code\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]Output:trueExplanation:Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.", + "image": null + }, + { + "text": "Example 3: Input:s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean wordBreak(String s, List wordDict) {\n Set wordSet = new HashSet<>(wordDict);\n boolean[] dp = new boolean[s.length() + 1];\n dp[0] = true; // for empty \"\" string\n\n for (int i = 1; i <= s.length(); i++) {\n for (int j = 0; j < i; j++) {\n\n if (dp[j] && wordSet.contains(s.substring(j, i))) {\n dp[i] = true;\n break;\n }\n }\n }\n\n return dp[s.length()];\n }\n}", + "title": "139. Word Break", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:trueExplanation:There is a cycle in the linked list, where the tail connects to the 0th node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:falseExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public boolean hasCycle(ListNode head) {\n\n if (head == null || head.next == null)\n return false;\n\n ListNode slow = head;\n ListNode fast = head;\n\n while (fast != null && fast.next != null) {\n\n slow = slow.next;\n fast = fast.next.next;\n\n if (slow == fast) {\n return true;\n }\n }\n\n return false;\n }\n}", + "title": "141. Linked List Cycle", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null . 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 ( 0-indexed ). It is -1 if there is no cycle. Note that pos is not passed as a parameter . Do not modify the linked list. Example 1: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:head = [3,2,0,-4], pos = 1Output:tail connects to node index 1Explanation:There is a cycle in the linked list, where tail connects to the second node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" + }, + { + "text": "Example 2: Input:head = [1,2], pos = 0Output:tail connects to node index 0Explanation:There is a cycle in the linked list, where tail connects to the first node.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" + }, + { + "text": "Example 3: Input:head = [1], pos = -1Output:no cycleExplanation:There is no cycle in the linked list.", + "image": "https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public ListNode detectCycle(ListNode head) {\n if (head == null || head.next == null)\n return null;\n\n ListNode slow = head;\n ListNode fast = head;\n\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n\n if (fast == slow) {\n ListNode entry = head;\n\n while (entry != slow) {\n entry = entry.next;\n slow = slow.next;\n }\n\n return entry;\n }\n }\n\n return null;\n }\n}", + "title": "142. Linked List Cycle II", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the preorder traversal of its nodes' values . Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [1,2,4,5,6,7,3,8,9] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1]", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List preorderTraversal(TreeNode root) {\n List preorderList = new ArrayList<>();\n helper(root, preorderList);\n return preorderList;\n }\n\n public void helper(TreeNode root, List preorderList) {\n if (root == null)\n return;\n\n preorderList.add(root.val);\n helper(root.left, preorderList);\n helper(root.right, preorderList);\n }\n}", + "title": "144. Binary Tree Preorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, return the postorder traversal of its nodes' values . Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,6,7,5,2,9,8,3,1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1]", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png", + "https://assets.leetcode.com/uploads/2024/08/29/tree_2.png" + ], + "constraints": [ + "The number of the nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List postorderTraversal(TreeNode root) {\n List postorderList = new ArrayList<>();\n helper(root, postorderList);\n return postorderList;\n }\n\n public void helper(TreeNode root, List postorderList) {\n if (root == null)\n return;\n\n helper(root.left, postorderList);\n helper(root.right, postorderList);\n postorderList.add(root.val);\n }\n}", + "title": "145. Binary Tree Postorder Traversal", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache . Implement the LRUCache class: The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[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]ExplanationLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4", + "image": null + } + ], + "follow_up": null, + "solution": "class LRUCache {\n\n private class Node {\n int key, value;\n Node prev, next;\n\n Node(int key, int value) {\n this.key = key;\n this.value = value;\n }\n }\n\n private int capacity;\n private Map cache;\n private Node head, tail;\n\n public LRUCache(int capacity) {\n this.capacity = capacity;\n this.cache = new HashMap<>();\n\n head = new Node(0, 0);\n tail = new Node(0, 0);\n head.next = tail;\n tail.prev = head;\n }\n\n public int get(int key) {\n\n if (!cache.containsKey(key)) {\n return -1;\n }\n\n Node node = cache.get(key);\n remove(node);\n insertAtFront(node);\n\n return node.value;\n }\n\n public void put(int key, int value) {\n\n if (cache.containsKey(key)) {\n remove(cache.get(key));\n }\n\n if (cache.size() == capacity) {\n remove(tail.prev);\n }\n\n insertAtFront(new Node(key, value));\n }\n\n private void remove(Node node) {\n cache.remove(node.key);\n node.prev.next = node.next;\n node.next.prev = node.prev;\n }\n\n private void insertAtFront(Node node) {\n cache.put(node.key, node);\n\n node.next = head.next;\n node.prev = head;\n head.next.prev = node;\n head.next = node;\n }\n}\n\n/**\n * Your LRUCache object will be instantiated and called as such:\n * LRUCache obj = new LRUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */", + "title": "146. LRU Cache", + "topic": "Others" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a linked list, return the list after sorting it in ascending order . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 5 * 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:head = [4,2,1,3]Output:[1,2,3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" + }, + { + "text": "Example 2: Input:head = [-1,5,3,4,0]Output:[-1,0,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode sortList(ListNode head) { // Fast & Slow Pointer - Two Pointer Approach\n if (head == null || head.next == null)\n return head;\n\n ListNode mid = findMiddle(head);\n ListNode rightHead = mid.next;\n mid.next = null;\n\n ListNode left = sortList(head);\n ListNode right = sortList(rightHead);\n\n return mergeTwoLists(left, right);\n }\n\n private ListNode findMiddle(ListNode head) {\n ListNode slow = head, fast = head.next;\n\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n return slow;\n }\n\n private ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode current = dummy;\n\n while (l1 != null && l2 != null) {\n\n if (l1.val < l2.val) {\n current.next = l1;\n l1 = l1.next;\n } else {\n current.next = l2;\n l2 = l2.next;\n }\n current = current.next;\n }\n\n if (l1 != null)\n current.next = l1;\n if (l2 != null)\n current.next = l2;\n\n return dummy.next;\n }\n}", + "title": "148. Sort List", + "topic": "Linked List" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given an array of points where points[i] = [x i , y i ] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 300", + "points[i].length == 2", + "-10^4 <= x i , y i <= 10^4", + "All the points are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,1],[2,2],[3,3]]Output:3", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg" + }, + { + "text": "Example 2: Input:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]Output:4", + "image": "https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxPoints(int[][] points) {\n if (points.length < 2)\n return points.length;\n\n int maxPoints = 1; // Minimum answer is at least 1\n\n for (int i = 0; i < points.length; i++) {\n Map slopeMap = new HashMap<>();\n int duplicate = 0, localMax = 1;\n\n for (int j = i + 1; j < points.length; j++) {\n int dx = points[j][0] - points[i][0];\n int dy = points[j][1] - points[i][1];\n\n // If the points are identical\n if (dx == 0 && dy == 0) {\n duplicate++;\n continue;\n }\n\n // Normalize the slope by reducing (dy/dx) to lowest terms\n int gcd = gcd(dx, dy);\n dx /= gcd;\n dy /= gcd;\n\n // Ensure a consistent representation\n String slope = dx + \"/\" + dy;\n\n slopeMap.put(slope, slopeMap.getOrDefault(slope, 1) + 1);\n localMax = Math.max(localMax, slopeMap.get(slope));\n }\n\n // Add duplicate points to max count\n maxPoints = Math.max(maxPoints, localMax + duplicate);\n }\n\n return maxPoints;\n }\n\n // Compute GCD to normalize slope representation\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}", + "title": "149. Max Points on a Line", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]Output:9Explanation:((2 + 1) * 3) = 9", + "image": null + }, + { + "text": "Example 2: Input:tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]Output:6Explanation:(4 + (13 / 5)) = 6", + "image": null + }, + { + "text": "Example 3: Input:tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]Output:22Explanation:((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int evalRPN(String[] tokens) {\n\n Stack stack = new Stack<>();\n\n for (String token : tokens) {\n\n if (token.equals(\"+\") || token.equals(\"-\") || token.equals(\"*\") || token.equals(\"/\")) {\n\n int b = stack.pop(); // Second operand\n int a = stack.pop(); // First operand\n\n int result = cal(a, b, token);\n\n stack.push(result);\n } else {\n stack.push(Integer.parseInt(token));\n }\n }\n\n return stack.pop();\n\n }\n\n private int cal(int a, int b, String operator) {\n\n switch (operator) {\n case \"+\":\n return a + b;\n case \"-\":\n return a - b;\n case \"*\":\n return a * b;\n case \"/\":\n return a / b;\n default:\n throw new IllegalArgumentException(\"Invalid operator: \" + operator);\n }\n }\n}", + "title": "150. Evaluate Reverse Polish Notation", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an input string s , reverse the order of the words . A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^4", + "s contains English letters (upper-case and lower-case), digits, and spaces ' ' .", + "There is at least one word in s ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"the sky is blue\"Output:\"blue is sky the\"", + "image": null + }, + { + "text": "Example 2: Input:s = \" hello world \"Output:\"world hello\"Explanation:Your reversed string should not contain leading or trailing spaces.", + "image": null + }, + { + "text": "Example 3: Input:s = \"a good example\"Output:\"example good a\"Explanation:You need to reduce multiple spaces between two words to a single space in the reversed string.", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public String reverseWords(String s) {\n\n String[] arr = s.trim().split(\"\\\\s+\");\n StringBuilder reversed = new StringBuilder();\n\n for (int i = arr.length - 1; i >= 0; i--) {\n\n reversed.append(arr[i]);\n\n if (i != 0) { // Add a space between words, but not after the last word\n reversed.append(\" \");\n }\n }\n\n return reversed.toString();\n }\n}", + "title": "151. Reverse Words in a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Example 1: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-2,4]Output:6Explanation:[2,3] has the largest product 6.", + "image": null + }, + { + "text": "Example 2: Input:nums = [-2,0,-1]Output:0Explanation:The result cannot be 2, because [-2,-1] is not a subarray.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProduct(int[] nums) {\n int maxProduct = nums[0];\n int currentMax = nums[0];\n int currentMin = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] < 0) {\n int temp = currentMax;\n currentMax = currentMin;\n currentMin = temp;\n }\n\n currentMax = Math.max(nums[i], currentMax * nums[i]);\n currentMin = Math.min(nums[i], currentMin * nums[i]);\n\n maxProduct = Math.max(maxProduct, currentMax);\n }\n\n return maxProduct;\n }\n}", + "title": "152. Maximum Product Subarray", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "[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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:1Explanation:The original array was [1,2,3,4,5] rotated 3 times.", + "image": null + }, + { + "text": "Example 2: Input:nums = [4,5,6,7,0,1,2]Output:0Explanation:The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.", + "image": null + }, + { + "text": "Example 3: Input:nums = [11,13,15,17]Output:11Explanation:The original array was [11,13,15,17] and it was rotated 4 times.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMin(int[] nums) {\n int left = 0, right = nums.length - 1;\n\n while (left < right) {\n int mid = (left + right) >>> 1;\n\n if (nums[mid] > nums[right]) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n return nums[left];\n }\n}", + "title": "153. Find Minimum in Rotated Sorted Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: You must implement a solution with O(1) time complexity for each function. Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n[[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2", + "image": null + } + ], + "follow_up": null, + "solution": "class MinStack {\n\n private int min;\n private final Stack stack;\n\n public MinStack() {\n stack = new Stack<>();\n min = Integer.MAX_VALUE; // Initially set min to a large value\n }\n\n public void push(int x) {\n // only push the old minimum value when the current\n // minimum value changes after pushing the new value x\n\n if (x <= min) {\n stack.push(min);\n min = x;\n }\n\n stack.push(x);\n }\n\n public void pop() {\n // if pop operation could result in the changing of the current minimum value,\n // pop twice and change the current minimum value to the last minimum value.\n if (stack.pop() == min)\n min = stack.pop();\n }\n\n public int top() {\n return stack.peek();\n }\n\n public int getMin() {\n return min;\n }\n}\n\n/**\n * Your MinStack object will be instantiated and called as such:\n * MinStack obj = new MinStack();\n * obj.push(val);\n * obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.getMin();\n */", + "title": "155. Min Stack", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the heads of two singly linked-lists headA and headB , return the node at which the two lists intersect . If the two linked lists have no intersection at all, return null . For example, the following two linked lists begin to intersect at node c1 : The test cases are generated such that there are no cycles anywhere in the entire linked structure. Note that the linked lists must retain their original structure after the function returns. Custom Judge: The inputs to the judge are given as follows (your program is not given these inputs): The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.", + "listA - The first linked list.", + "listB - The second linked list.", + "skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.", + "skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node." + ], + "examples": [ + { + "text": "Example 1: Input:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3Output:Intersected at '8'Explanation:The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2ndnode in A and 3rdnode in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rdnode in A and 4thnode in B) point to the same location in memory.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" + }, + { + "text": "Example 2: Input:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1Output:Intersected at '2'Explanation:The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" + }, + { + "text": "Example 3: Input:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2Output:No intersectionExplanation:From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.", + "image": "https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode(int x) {\n * val = x;\n * next = null;\n * }\n * }\n */\npublic class Solution {\n public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n if (headA == null || headB == null)\n return null;\n\n ListNode pA = headA, pB = headB;\n\n while (pA != pB) {\n pA = (pA == null) ? headB : pA.next;\n pB = (pB == null) ? headA : pB.next;\n }\n\n return pA;\n }\n}", + "title": "160. Intersection of Two Linked Lists", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums , find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks . You may imagine that nums[-1] = nums[n] = -∞ . In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "-2 31 <= nums[i] <= 2 31 - 1", + "nums[i] != nums[i + 1] for all valid i ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:2Explanation:3 is a peak element and your function should return the index number 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,1,3,5,6,4]Output:5Explanation:Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findPeakElement(int[] nums) {\n int low = 0, high = nums.length - 1;\n\n while (low < high) {\n int mid = (low + high) >>> 1;\n\n if (nums[mid] < nums[mid + 1]) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n }\n}", + "title": "162. Find Peak Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 , added 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: Example 2: Example 3:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:numbers = [2,7,11,15], target = 9Output:[1,2]Explanation:The sum of 2 and 7 is 9. Therefore, index1= 1, index2= 2. We return [1, 2].", + "image": null + }, + { + "text": "Example 2: Input:numbers = [2,3,4], target = 6Output:[1,3]Explanation:The sum of 2 and 4 is 6. Therefore index1= 1, index2= 3. We return [1, 3].", + "image": null + }, + { + "text": "Example 3: Input:numbers = [-1,0], target = -1Output:[1,2]Explanation:The sum of -1 and 0 is -1. Therefore index1= 1, index2= 2. We return [1, 2].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] twoSum(int[] numbers, int target) { // two pointer approach\n\n int start = 0, end = numbers.length - 1;\n\n while (start < end) {\n int sum = numbers[start] + numbers[end];\n\n if (sum > target) {\n end--; \n } else if (sum < target) {\n start++; \n } else {\n return new int[] { start + 1, end + 1 }; \n }\n }\n\n return new int[] { -1, -1 }; \n }\n}", + "title": "167. Two Sum II - Input Array Is Sorted", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnNumber <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:columnNumber = 1Output:\"A\"", + "image": null + }, + { + "text": "Example 2: Input:columnNumber = 28Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:columnNumber = 701Output:\"ZY\"", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String convertToTitle(int columnNumber) {\n StringBuilder res = new StringBuilder();\n\n while (columnNumber > 0) {\n int num = (columnNumber - 1) % 26;\n res.append((char) ('A' + num));\n columnNumber = (columnNumber - 1) / 26;\n }\n\n return res.reverse().toString();\n }\n}", + "title": "168. Excel Sheet Column Title", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums of size n , return the majority element . The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 5 * 10^4", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,3]Output:3", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,2,1,1,1,2,2]Output:2", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class Solution {\n public int majorityElement(int[] nums) {\n\n // using Moore Voting Algorithm\n int count = 0;\n int candidate = 0;\n\n for (int num : nums) {\n if (count == 0) {\n candidate = num;\n }\n\n if (num == candidate) {\n count++;\n } else {\n count--;\n }\n }\n\n return candidate;\n }\n}", + "title": "169. Majority Element", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number . For example: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= columnTitle.length <= 7", + "columnTitle consists only of uppercase English letters.", + "columnTitle is in the range [\"A\", \"FXSHRXW\"] ." + ], + "examples": [ + { + "text": "Example 1: Input:columnTitle = \"A\"Output:1", + "image": null + }, + { + "text": "Example 2: Input:columnTitle = \"AB\"Output:28", + "image": null + }, + { + "text": "Example 3: Input:columnTitle = \"ZY\"Output:701", + "image": null + }, + { + "text": "A -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int titleToNumber(String columnTitle) {\n int result = 0;\n for (char c : columnTitle.toCharArray()) {\n result = result * 26 + (c - 'A' + 1);\n }\n return result;\n }\n}", + "title": "171. Excel Sheet Column Number", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the number of trailing zeroes in n! . Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:0Explanation:3! = 6, no trailing zero.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:1Explanation:5! = 120, one trailing zero.", + "image": null + }, + { + "text": "Example 3: Input:n = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int trailingZeroes(int n) {\n int count = 0;\n\n while (n >= 5) {\n count += n / 5;\n n /= 5;\n }\n\n return count;\n }\n}", + "title": "172. Factorial Trailing Zeroes", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST): Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST. You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called. Example 1:", + "description_images": [], + "constraints": [ + "BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.", + "boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false .", + "int next() Moves the pointer to the right, then returns the number at the pointer." + ], + "examples": [ + { + "text": "Example 1: Input[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False", + "image": "https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass BSTIterator {\n private final Stack stack;\n\n public BSTIterator(TreeNode root) {\n this.stack = new Stack<>();\n pushLeftNodes(root);\n }\n\n public int next() {\n TreeNode node = this.stack.pop();\n\n pushLeftNodes(node.right);\n return node.val;\n }\n\n public boolean hasNext() {\n return !this.stack.isEmpty();\n }\n\n private void pushLeftNodes(TreeNode node) {\n\n while (node != null) {\n this.stack.push(node);\n node = node.left;\n }\n }\n}\n\n/**\n * Your BSTIterator object will be instantiated and called as such:\n * BSTIterator obj = new BSTIterator(root);\n * int param_1 = obj.next();\n * boolean param_2 = obj.hasNext();\n */", + "title": "173. Binary Search Tree Iterator", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= 100", + "1 <= prices.length <= 1000", + "0 <= prices[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, prices = [2,4,1]Output:2Explanation:Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.", + "image": null + }, + { + "text": "Example 2: Input:k = 2, prices = [3,2,6,5,0,3]Output:7Explanation:Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int k, int[] prices) {\n int n = prices.length;\n if (n == 0 || k == 0)\n return 0;\n\n if (k >= n / 2) {\n int maxProfit = 0;\n\n for (int i = 1; i < n; i++) {\n if (prices[i] > prices[i - 1]) {\n maxProfit += prices[i] - prices[i - 1];\n }\n }\n return maxProfit;\n }\n\n int[] prev = new int[n];\n int[] cur = new int[n];\n\n for (int t = 1; t <= k; t++) {\n int maxDiff = -prices[0];\n\n for (int d = 1; d < n; d++) {\n cur[d] = Math.max(cur[d - 1], prices[d] + maxDiff);\n maxDiff = Math.max(maxDiff, prev[d] - prices[d]);\n }\n\n int[] temp = prev;\n prev = cur;\n cur = temp;\n }\n\n return prev[n - 1];\n }\n}", + "title": "188. Best Time to Buy and Sell Stock IV", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , rotate the array to the right by k steps, where k is non-negative. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-2 31 <= nums[i] <= 2 31 - 1", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5,6,7], k = 3Output:[5,6,7,1,2,3,4]Explanation:rotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,-100,3,99], k = 2Output:[3,99,-1,-100]Explanation:rotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void rotate(int[] nums, int k) {\n\n int len = nums.length;\n k = k % len;\n\n reversed(nums, 0, len - 1); // reverse full array\n reversed(nums, 0, k - 1); // reverse till k-th elements\n reversed(nums, k, len - 1); // reverse las elements\n }\n\n private void reversed(int[] nums, int p1, int p2) {\n\n while (p1 < p2) { // swaping values\n int temp = nums[p1];\n nums[p1] = nums[p2];\n nums[p2] = temp;\n p1++;\n p2--;\n }\n }\n}\n", + "title": "189. Rotate Array", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Reverse bits of a given 32 bits unsigned integer. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.", + "In Java, the compiler represents the signed integers using 2's complement notation . Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825 ." + ], + "examples": [ + { + "text": "Example 2 Input:n = 00000010100101000001111010011100Output:964176192 (00111001011110000010100101000000)Explanation:The input binary string00000010100101000001111010011100represents the unsigned integer 43261596, so return 964176192 which its binary representation is00111001011110000010100101000000.", + "image": null + }, + { + "text": "Example 2: Input:n = 11111111111111111111111111111101Output:3221225471 (10111111111111111111111111111111)Explanation:The input binary string11111111111111111111111111111101represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is10111111111111111111111111111111.", + "image": null + } + ], + "follow_up": null, + "solution": "public class Solution {\n // you need treat n as an unsigned value\n public int reverseBits(int n) {\n int result = 0;\n\n for(int i = 0; i < 32; i++) {\n int bit = (n & 1);\n result = (result << 1) | bit;\n n >>>= 1;\n }\n\n return result;\n }\n}", + "title": "190. Reverse Bits", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= n <= 2 31 - 1" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int hammingWeight(int n) {\n int count = 0;\n while (n != 0) {\n count += (n & 1); // Check if last bit is 1\n n >>>= 1; // Unsigned right shift\n }\n return count;\n }\n}", + "title": "191. Number of 1 Bits", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "0 <= nums[i] <= 400" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1]Output:4Explanation:Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,7,9,3,1]Output:12Explanation:Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int rob(int[] nums) {\n if (nums.length == 0)\n return 0;\n if (nums.length == 1)\n return nums[0];\n\n int prev2 = 0, prev1 = 0;\n for (int num : nums) {\n int curr = Math.max(prev1, prev2 + num);\n prev2 = prev1;\n prev1 = curr;\n }\n \n return prev1;\n }\n}", + "title": "198. House Robber", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: []", + "description_images": [ + "https://assets.leetcode.com/uploads/2024/11/24/tmpd5jn43fs-1.png", + "https://assets.leetcode.com/uploads/2024/11/24/tmpkpe40xeh-1.png" + ], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List rightSideView(TreeNode root) {\n List result = new ArrayList<>();\n dfs(root, 0, result);\n\n return result;\n }\n\n private void dfs(TreeNode node, int depth, List result) {\n\n if (node == null)\n return;\n if (depth == result.size())\n result.add(node.val);\n\n dfs(node.right, depth + 1, result);\n dfs(node.left, depth + 1, result);\n }\n}", + "title": "199. Binary Tree Right Side View", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "m == grid.length", + "n == grid[i].length", + "1 <= m, n <= 300", + "grid[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]Output:1", + "image": null + }, + { + "text": "Example 2: Input:grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numIslands(char[][] grid) {\n if (grid == null || grid.length == 0)\n return 0;\n\n int numIslands = 0;\n int rows = grid.length, cols = grid[0].length;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (grid[r][c] == '1') {\n numIslands++;\n dfs(grid, r, c);\n }\n }\n }\n\n return numIslands;\n }\n\n private void dfs(char[][] grid, int r, int c) {\n if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == '0') {\n return;\n }\n\n grid[r][c] = '0';\n\n dfs(grid, r + 1, c);\n dfs(grid, r - 1, c);\n dfs(grid, r, c + 1);\n dfs(grid, r, c - 1);\n }\n}", + "title": "200. Number of Islands", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two integers left and right that represent the range [left, right] , return the bitwise AND of all numbers in this range, inclusive . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 <= left <= right <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:left = 5, right = 7Output:4", + "image": null + }, + { + "text": "Example 2: Input:left = 0, right = 0Output:0", + "image": null + }, + { + "text": "Example 3: Input:left = 1, right = 2147483647Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int rangeBitwiseAnd(int left, int right) {\n int shiftCount = 0;\n\n while (left < right) {\n left >>= 1;\n right >>= 1;\n shiftCount++;\n }\n\n return left << shiftCount;\n }\n}", + "title": "201. Bitwise AND of Numbers Range", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Return true if n is a happy number, and false if not . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input:n = 19Output:trueExplanation:12+ 92= 82\n82+ 22= 68\n62+ 82= 100\n12+ 02+ 02= 1", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n // Floyd’s Cycle Detection (Tortoise and Hare)\n public boolean isHappy(int n) {\n\n int slow = n, fast = getNext(n);\n\n while (fast != 1 && slow != fast) {\n slow = getNext(slow);\n fast = getNext(getNext(fast)); // Move fast twice\n }\n\n return fast == 1;\n }\n\n private int getNext(int n) {\n int squareSum = 0;\n\n while (n > 0) {\n int digit = n % 10;\n squareSum += digit * digit;\n n /= 10;\n }\n\n return squareSum;\n }\n}\n", + "title": "202. Happy Number", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a linked list and an integer val , remove all the nodes of the linked list that has Node.val == val , and return the new head . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 10^4 ] .", + "1 <= Node.val <= 50", + "0 <= val <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,6,3,4,5,6], val = 6Output:[1,2,3,4,5]", + "image": "https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg" + }, + { + "text": "Example 2: Input:head = [], val = 1Output:[]", + "image": null + }, + { + "text": "Example 3: Input:head = [7,7,7,7], val = 7Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode removeElements(ListNode head, int val) {\n ListNode result = new ListNode(0, head);\n ListNode dummy = result;\n\n while (dummy != null) {\n while (dummy.next != null && dummy.next.val == val) {\n dummy.next = dummy.next.next;\n }\n dummy = dummy.next;\n }\n\n return result.next;\n }\n}", + "title": "203. Remove Linked List Elements", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , determine if they are isomorphic . Two strings s and t are isomorphic if the characters in s can be replaced to get t . All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1: Input: s = \"egg\", t = \"add\" Output: true Explanation: The strings s and t can be made identical by: Example 2: Input: s = \"foo\", t = \"bar\" Output: false Explanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r' . Example 3: Input: s = \"paper\", t = \"title\" Output: true", + "description_images": [], + "constraints": [ + "Mapping 'e' to 'a' .", + "Mapping 'g' to 'd' ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean isIsomorphic(String s, String t) {\n\n Map map = new HashMap<>();\n Set mappedValues = new HashSet<>();\n\n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n\n if (map.containsKey(charS)) {\n if (map.get(charS) != charT)\n return false; // Conflict\n } else {\n if (mappedValues.contains(charT))\n return false; // Prevent multiple mappings\n map.put(charS, charT);\n mappedValues.add(charT);\n }\n }\n\n return true;\n }\n}", + "title": "205. Isomorphic Strings", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, reverse the list, and return the reversed list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is the range [0, 5000] .", + "-5000 <= Node.val <= 5000" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[5,4,3,2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]Output:[2,1]", + "image": "https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" + }, + { + "text": "Example 3: Input:head = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n ListNode node = null;\n\n while (head != null) {\n ListNode temp = head.next;\n head.next = node;\n node = head;\n head = temp;\n }\n\n return node;\n }\n}", + "title": "206. Reverse Linked List", + "topic": "Linked List" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . Return true if you can finish all courses. Otherwise, return false . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:numCourses = 2, prerequisites = [[1,0]]Output:trueExplanation:There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.", + "image": null + }, + { + "text": "Example 2: Input:numCourses = 2, prerequisites = [[1,0],[0,1]]Output:falseExplanation:There are a total of 2 courses to take. \nTo 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.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canFinish(int numCourses, int[][] prerequisites) {\n\n // Build graph and in-degree array\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n\n for (int[] pre : prerequisites) {\n int course = pre[0], prereq = pre[1];\n graph.putIfAbsent(prereq, new ArrayList<>());\n graph.get(prereq).add(course);\n inDegree[course]++;\n }\n\n // Find courses with no prerequisites\n Queue queue = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0)\n queue.offer(i);\n }\n\n // Process courses in BFS order\n int count = 0;\n while (!queue.isEmpty()) {\n int curr = queue.poll();\n count++;\n\n if (graph.containsKey(curr)) {\n\n for (int neighbor : graph.get(curr)) {\n inDegree[neighbor]--;\n if (inDegree[neighbor] == 0)\n queue.offer(neighbor);\n }\n }\n }\n\n return count == numCourses;\n }\n}", + "title": "207. Course Schedule", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]Output[null, null, true, false, true, null, true]ExplanationTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\"); // return True\ntrie.search(\"app\"); // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "class TrieNode {\n TrieNode[] children = new TrieNode[26];\n boolean isWord;\n}\n\nclass Trie { // Array Based - fixed size\n private TrieNode root;\n\n public Trie() {\n root = new TrieNode();\n }\n\n public void insert(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.isWord = true;\n }\n\n public boolean search(String word) {\n TrieNode node = findNode(word);\n return node != null && node.isWord;\n }\n\n public boolean startsWith(String prefix) {\n return findNode(prefix) != null;\n }\n\n private TrieNode findNode(String prefix) {\n TrieNode node = root;\n \n for (char c : prefix.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n return null;\n }\n node = node.children[index];\n }\n return node;\n }\n}", + "title": "208. Implement Trie (Prefix Tree)", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of positive integers nums and a positive integer target , return the minimal length of a subarray whose sum is greater than or equal to target . If there is no such subarray, return 0 instead. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= target <= 10^9", + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:target = 7, nums = [2,3,1,2,4,3]Output:2Explanation:The subarray [4,3] has the minimal length under the problem constraint.", + "image": null + }, + { + "text": "Example 2: Input:target = 4, nums = [1,4,4]Output:1", + "image": null + }, + { + "text": "Example 3: Input:target = 11, nums = [1,1,1,1,1,1,1,1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minSubArrayLen(int target, int[] nums) { // sliding window approach - Time: O(n) || Space: O(1)\n\n int left = 0, sum = 0;\n int minLength = Integer.MAX_VALUE;\n\n for (int right = 0; right < nums.length; right++) {\n sum += nums[right];\n\n while (sum >= target) {\n minLength = Math.min(minLength, right - left + 1);\n sum -= nums[left];\n left++;\n }\n }\n\n return minLength != Integer.MAX_VALUE ? minLength : 0;\n }\n}", + "title": "209. Minimum Size Subarray Sum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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 . 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, the pair [0, 1] , indicates that to take course 0 you have to first take course 1 ." + ], + "examples": [ + { + "text": "Example 1: 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].", + "image": null + }, + { + "text": "Example 2: 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.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].", + "image": null + }, + { + "text": "Example 3: Input:numCourses = 1, prerequisites = []Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] findOrder(int numCourses, int[][] prerequisites) {\n\n // Build graph and in-degree array\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n\n for (int[] pre : prerequisites) {\n int course = pre[0], prereq = pre[1];\n graph.putIfAbsent(prereq, new ArrayList<>());\n graph.get(prereq).add(course);\n inDegree[course]++;\n }\n\n // Find courses with no prerequisites\n Queue queue = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0)\n queue.offer(i);\n }\n\n // Process courses in BFS order\n int[] order = new int[numCourses];\n int index = 0; // To track course order\n\n while (!queue.isEmpty()) {\n int curr = queue.poll();\n order[index++] = curr;\n\n if (graph.containsKey(curr)) {\n\n for (int neighbor : graph.get(curr)) {\n inDegree[neighbor]--;\n if (inDegree[neighbor] == 0)\n queue.offer(neighbor);\n }\n }\n }\n\n return index == numCourses ? order : new int[0];\n }\n}", + "title": "210. Course Schedule II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: Example:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example: Input[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]Output[null,null,null,null,false,true,true,true]ExplanationWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True", + "image": null + } + ], + "follow_up": null, + "solution": "public class TrieNode {\n TrieNode[] children;\n public boolean isWord;\n\n public TrieNode() {\n this.children = new TrieNode[26];\n this.isWord = false;\n }\n}\n\nclass WordDictionary {\n\n private final TrieNode root;\n\n public WordDictionary() {\n this.root = new TrieNode();\n }\n\n // Add a word to the Trie\n public void addWord(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a'; // Convert char to index (0 to 25)\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.isWord = true;\n }\n\n // Search a word with support for '.'\n public boolean search(String word) {\n return dfsSearch(word, 0, root);\n }\n\n private boolean dfsSearch(String word, int index, TrieNode node) {\n if (node == null)\n return false;\n if (index == word.length())\n return node.isWord;\n\n char c = word.charAt(index);\n if (c == '.') {\n\n // Wildcard case: Try all 26 children\n for (TrieNode child : node.children) {\n if (child != null && dfsSearch(word, index + 1, child)) {\n return true;\n }\n }\n return false;\n } else {\n // Regular character lookup\n int charIndex = c - 'a';\n return dfsSearch(word, index + 1, node.children[charIndex]);\n }\n }\n\n}\n\n/**\n * Your WordDictionary object will be instantiated and called as such:\n * WordDictionary obj = new WordDictionary();\n * obj.addWord(word);\n * boolean param_2 = obj.search(word);\n */", + "title": "211. Design Add and Search Words Data Structure", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: 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\"]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search1.jpg" + }, + { + "text": "Example 2: Input:board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]Output:[]", + "image": "https://assets.leetcode.com/uploads/2020/11/07/search2.jpg" + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass Solution {\n static class TrieNode {\n TrieNode[] children = new TrieNode[26];\n String word = null; \n }\n\n private final TrieNode root = new TrieNode();\n private final List result = new ArrayList<>();\n\n private void insertWord(String word) {\n TrieNode node = root;\n\n for (char c : word.toCharArray()) {\n int index = c - 'a';\n if (node.children[index] == null) {\n node.children[index] = new TrieNode();\n }\n node = node.children[index];\n }\n node.word = word; \n }\n\n public List findWords(char[][] board, String[] words) {\n for (String word : words) {\n insertWord(word);\n }\n\n int m = board.length, n = board[0].length;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n dfs(board, i, j, root);\n }\n }\n return result;\n }\n\n private void dfs(char[][] board, int i, int j, TrieNode node) {\n char c = board[i][j];\n\n if (c == '#' || node.children[c - 'a'] == null)\n return;\n\n node = node.children[c - 'a'];\n\n if (node.word != null) {\n result.add(node.word);\n node.word = null; // Avoid duplicate results\n }\n\n board[i][j] = '#';\n \n if (i > 0)\n dfs(board, i - 1, j, node); // Up\n if (i < board.length - 1)\n dfs(board, i + 1, j, node); // Down\n if (j > 0)\n dfs(board, i, j - 1, node); // Left\n if (j < board[0].length - 1)\n dfs(board, i, j + 1, node); // Right\n\n // Step 7: Restore cell\n board[i][j] = c;\n }\n}\n", + "title": "212. Word Search II", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,2,1,5,6,4], k = 2Output:5", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,2,3,1,2,4,5,5,6], k = 4Output:4", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findKthLargest(int[] nums, int k) {\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for (int num : nums) {\n minHeap.offer(num);\n\n if (minHeap.size() > k)\n minHeap.poll();\n }\n\n return minHeap.peek();\n }\n}", + "title": "215. Kth Largest Element in an Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true: Return a list of all possible valid combinations . The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Only numbers 1 through 9 are used.", + "Each number is used at most once ." + ], + "examples": [ + { + "text": "Example 1: Input:k = 3, n = 7Output:[[1,2,4]]Explanation:1 + 2 + 4 = 7\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, n = 9Output:[[1,2,6],[1,3,5],[2,3,4]]Explanation:1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.", + "image": null + }, + { + "text": "Example 3: Input:k = 4, n = 1Output:[]Explanation:There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> combinationSum3(int k, int n) {\n List> result = new ArrayList<>();\n backtrack(result, new ArrayList<>(), k, n, 1);\n return result;\n }\n\n private void backtrack(List> result, List path, int k, int n, int start) {\n\n if (path.size() == k && n == 0) {\n result.add(new ArrayList<>(path));\n return;\n }\n\n for (int i = start; i <= 9; i++) {\n path.add(i);\n backtrack(result, path, k, n - i, i + 1);\n path.removeLast();\n }\n }\n}", + "title": "216. Combination Sum III", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean containsDuplicate(int[] nums) {\n HashSet seen = new HashSet<>();\n for (int num : nums) {\n if (seen.contains(num)) {\n return true;\n }\n seen.add(num);\n }\n\n return false;\n }\n}", + "title": "217. Contains Duplicate", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums and an integer k , return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^9 <= nums[i] <= 10^9", + "0 <= k <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,1], k = 3Output:true", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1], k = 1Output:true", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3,1,2,3], k = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean containsNearbyDuplicate(int[] nums, int k) { // Using HashMap for Index Tracking\n\n HashMap map = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n\n if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {\n return true;\n }\n map.put(nums[i], i);\n }\n\n return false;\n }\n}", + "title": "219. Contains Duplicate II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix filled with 0 's and 1 's, find the largest square containing only 1 's and return its area . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "m == matrix.length", + "n == matrix[i].length", + "1 <= m, n <= 300", + "matrix[i][j] is '0' or '1' ." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]Output:4", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" + }, + { + "text": "Example 2: Input:matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]Output:1", + "image": "https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" + }, + { + "text": "Example 3: Input:matrix = [[\"0\"]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maximalSquare(char[][] matrix) {\n if (matrix == null || matrix.length == 0)\n return 0;\n\n int m = matrix.length, n = matrix[0].length;\n int[][] dp = new int[m + 1][n + 1]; // add padding\n int maxSide = 0;\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n\n if (matrix[i - 1][j - 1] == '1') {\n dp[i][j] = 1 + Math.min(\n dp[i - 1][j],\n Math.min(dp[i][j - 1], dp[i - 1][j - 1]));\n maxSide = Math.max(maxSide, dp[i][j]);\n }\n }\n }\n\n return maxSide * maxSide;\n }\n}", + "title": "221. Maximal Square", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia , every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2 h nodes inclusive at the last level h . Design an algorithm that runs in less than O(n) time complexity. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 5 * 10^4 ] .", + "0 <= Node.val <= 5 * 10^4", + "The tree is guaranteed to be complete ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5,6]Output:6", + "image": "https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" + }, + { + "text": "Example 2: Input:root = []Output:0", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int countNodes(TreeNode root) {\n if (root == null)\n return 0;\n return 1 + countNodes(root.left) + countNodes(root.right);\n }\n}", + "title": "222. Count Complete Tree Nodes", + "topic": "Tree" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation . Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval() . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consists of digits, '+' , '-' , '(' , ')' , and ' ' .", + "s represents a valid expression.", + "'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).", + "'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).", + "There will be no two consecutive operators in the input.", + "Every number and running calculation will fit in a signed 32-bit integer." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"1 + 1\"Output:2", + "image": null + }, + { + "text": "Example 2: Input:s = \" 2-1 + 2 \"Output:3", + "image": null + }, + { + "text": "Example 3: Input:s = \"(1+(4+5+2)-3)+(6+8)\"Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int calculate(String s) {\n\n Stack stack = new Stack<>();\n\n int num = 0, result = 0, sign = 1; // `sign = 1` means positive, `-1` means negative\n\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n if (Character.isDigit(c)) {\n num = num * 10 + (c - '0'); // Extract full number\n\n } else if (c == '+' || c == '-') {\n result += sign * num;\n num = 0;\n sign = c == '+' ? 1 : -1;\n\n } else if (c == '(') {\n stack.push(result); // Store the current result\n stack.push(sign); // Store the current sign\n result = 0;\n sign = 1;\n\n } else if (c == ')') {\n result += sign * num; // Complete the last pending operation\n num = 0;\n result *= stack.pop(); // Apply sign before '('\n result += stack.pop(); // Add result before '('\n }\n }\n\n return result + (sign * num); // Add last number to result\n\n }\n}", + "title": "224. Basic Calculator", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a binary tree, invert the tree, and return its root . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 100] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3,6,9]Output:[4,7,2,9,6,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [2,1,3]Output:[2,3,1]", + "image": "https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg" + }, + { + "text": "Example 3: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode invertTree(TreeNode root) {\n\n if (root == null)\n return null;\n\n TreeNode left = invertTree(root.left);\n TreeNode right = invertTree(root.right);\n\n root.left = right;\n root.right = left;\n \n return root;\n }\n}", + "title": "226. Invert Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given a sorted unique integer array nums . A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly . That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums . Each range [a,b] in the list should be output as: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "\"a->b\" if a != b", + "\"a\" if a == b" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,2,4,5,7]Output:[\"0->2\",\"4->5\",\"7\"]Explanation:The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,2,3,4,6,8,9]Output:[\"0\",\"2->4\",\"6\",\"8->9\"]Explanation:The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List summaryRanges(int[] nums) {\n\n List result = new ArrayList<>();\n if (nums.length == 0)\n return result;\n\n int start = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n\n if (nums[i] != nums[i - 1] + 1) {\n result.add(formatRange(start, nums[i - 1]));\n start = nums[i];\n }\n }\n\n result.add(formatRange(start, nums[nums.length - 1]));\n return result;\n }\n\n private String formatRange(int start, int end) {\n return (start == end) ? String.valueOf(start) : start + \"->\" + end;\n }\n}\n", + "title": "228. Summary Ranges", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is n .", + "1 <= k <= n <= 10^4", + "0 <= Node.val <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,null,2], k = 1Output:1", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,null,1], k = 3Output:3", + "image": "https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int kthSmallest(TreeNode root, int k) {\n int leftSize = countNodes(root.left);\n\n if (k == leftSize + 1)\n return root.val;\n else if (k <= leftSize)\n return kthSmallest(root.left, k);\n else\n return kthSmallest(root.right, k - leftSize - 1);\n }\n\n private int countNodes(TreeNode node) {\n if (node == null)\n return 0;\n return 1 + countNodes(node.left) + countNodes(node.right);\n }\n}", + "title": "230. Kth Smallest Element in a BST", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue ( push , peek , pop , and empty ). Implement the MyQueue class: Notes: Example 1:", + "description_images": [], + "constraints": [ + "void push(int x) Pushes element x to the back of the queue.", + "int pop() Removes the element from the front of the queue and returns it.", + "int peek() Returns the element at the front of the queue.", + "boolean empty() Returns true if the queue is empty, false otherwise." + ], + "examples": [ + { + "text": "Example 1: Input[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]Output[null, null, null, 1, 1, false]ExplanationMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false", + "image": null + } + ], + "follow_up": "Follow-up:", + "solution": "class MyQueue {\n\n Stack input;\n Stack output;\n\n public MyQueue() {\n this.input = new Stack();\n this.output = new Stack();\n }\n\n public void push(int x) {\n this.input.push(x);\n }\n\n public int pop() {\n this.peek();\n return this.output.pop();\n }\n\n public int peek() {\n if (this.output.isEmpty()) {\n while (!this.input.isEmpty()) {\n this.output.push(this.input.pop());\n }\n }\n return this.output.peek();\n }\n\n public boolean empty() {\n return this.input.isEmpty() && this.output.isEmpty();\n }\n}\n\n/**\n * Your MyQueue object will be instantiated and called as such:\n * MyQueue obj = new MyQueue();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.peek();\n * boolean param_4 = obj.empty();\n */", + "title": "232. Implement Queue using Stacks", + "topic": "Stack" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return true if it is a palindrome or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 10^5 ] .", + "0 <= Node.val <= 9" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,2,1]Output:true", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [1,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n ListNode curr;\n\n public boolean isPalindrome(ListNode head) {\n curr = head;\n return solve(head);\n }\n\n public boolean solve(ListNode head) {\n if (head == null)\n return true;\n \n boolean ans = solve(head.next) && head.val == curr.val;\n curr = curr.next;\n return ans;\n }\n}", + "title": "234. Palindrome Linked List", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8Output:6Explanation:The LCA of nodes 2 and 8 is 6.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 2: Input:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4Output:2Explanation:The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" + }, + { + "text": "Example 3: Input:root = [2,1], p = 2, q = 1Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n \n while (root != null) {\n if (p.val < root.val && q.val < root.val) {\n root = root.left;\n } else if (p.val > root.val && q.val > root.val) {\n root = root.right;\n } else {\n return root;\n }\n }\n\n return null;\n }\n}", + "title": "235. Lowest Common Ancestor of a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 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: Example 2: Example 3:", + "description_images": [], + "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 tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1Output:3Explanation:The LCA of nodes 5 and 1 is 3.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 2: Input:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4Output:5Explanation:The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.", + "image": "https://assets.leetcode.com/uploads/2018/12/14/binarytree.png" + }, + { + "text": "Example 3: Input:root = [1,2], p = 1, q = 2Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n\n // Base case: If root is null return null\n if (root == null)\n return null;\n\n // if we find either p or q, return root\n if (root.val == p.val || root.val == q.val)\n return root;\n\n // Search in the left and right subtree\n TreeNode left = lowestCommonAncestor(root.left, p, q);\n TreeNode right = lowestCommonAncestor(root.right, p, q);\n\n // If both left and right are non-null, root is the LCA\n if (left != null && right != null)\n return root;\n\n // Otherwise, return whichever side is non-null\n return left != null ? left : right;\n }\n}", + "title": "236. Lowest Common Ancestor of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4]Output:[24,12,8,6]", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,1,0,-3,3]Output:[0,0,9,0,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n static {\n for (int i = 0; i < 500; i++) {\n productExceptSelf(new int[] { 0, 0 });\n }\n }\n\n public static int[] productExceptSelf(int[] nums) {\n // Time: O(n) || Space: O(1)\n\n int n = nums.length;\n int answer[] = new int[n];\n\n answer[n - 1] = 1;\n int multiply = nums[0];\n\n for (int i = n - 2; i >= 0; i--) {\n answer[i] = nums[i + 1] * answer[i + 1];\n }\n\n for (int i = 1; i < n; i++) {\n answer[i] = multiply * answer[i];\n multiply = multiply * nums[i];\n }\n\n return answer;\n }\n}\n\n// Example go throuth -->\n// Input: nums = [1, 2, 3, 4]\n//\n// First Pass (Right-to-Left):\n// Initialize: answer = [0, 0, 0, 1].\n// Iteration:\n// i = 2: answer[2] = nums[3] * answer[3] = 4 * 1 = 4.\n// i = 1: answer[1] = nums[2] * answer[2] = 3 * 4 = 12.\n// i = 0: answer[0] = nums[1] * answer[1] = 2 * 12 = 24.\n// After first pass: answer = [24, 12, 4, 1].\n\n// Second Pass (Left-to-Right):\n// Initialize: multiply = nums[0] = 1.\n// Iteration:\n// i = 1: answer[1] = multiply * answer[1] = 1 * 12 = 12. Update multiply =\n// multiply * nums[1] = 1 * 2 = 2.\n// i = 2: answer[2] = multiply * answer[2] = 2 * 4 = 8. Update multiply =\n// multiply * nums[2] = 2 * 3 = 6.\n// i = 3: answer[3] = multiply * answer[3] = 6 * 1 = 6. Update multiply =\n// multiply * nums[3] = 6 * 4 = 24.\n// After second pass: answer = [24, 12, 8, 6].\n\n// Output:\n\n// [24, 12, 8, 6]", + "title": "238. Product of Array Except Self", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "-10^4 <= nums[i] <= 10^4", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,-1,-3,5,3,6,7], k = 3Output:[3,3,5,5,6,7]Explanation:Window position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 731 [3 -1 -3] 5 3 6 731 3 [-1 -3 5] 3 6 751 3 -1 [-3 5 3] 6 751 3 -1 -3 [5 3 6] 761 3 -1 -3 5 [3 6 7]7", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] maxSlidingWindow(int[] nums, int k) {\n if (nums.length == 0 || k == 0)\n return new int[0];\n\n int n = nums.length;\n int[] result = new int[n - k + 1];\n Deque deque = new ArrayDeque<>();\n\n for (int i = 0; i < n; i++) {\n\n if (!deque.isEmpty() && deque.peek() <= i - k) {\n deque.poll();\n }\n\n while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {\n deque.pollLast();\n }\n\n deque.offer(i);\n\n if (i >= k - 1) {\n result[i - k + 1] = nums[deque.peek()];\n }\n }\n\n return result;\n }\n}", + "title": "239. Sliding Window Maximum", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix . This matrix has the following properties: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Integers in each row are sorted in ascending from left to right.", + "Integers in each column are sorted in ascending from top to bottom." + ], + "examples": [ + { + "text": "Example 1: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5Output:true", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg" + }, + { + "text": "Example 2: Input:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20Output:false", + "image": "https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return false;\n\n int row = 0;\n int col = matrix[0].length - 1;\n\n while (row < matrix.length && col >= 0) {\n int value = matrix[row][col];\n \n if (value == target) {\n return true;\n } else if (value > target) {\n col--;\n } else {\n row++;\n }\n }\n\n return false;\n }\n}", + "title": "240. Search a 2D Matrix II", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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", + "description_images": [], + "constraints": [ + "1 <= s.length, t.length <= 5 * 10^4", + "s and t consist of lowercase English letters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean isAnagram(String s, String t) {\n\n if (s.length() != t.length()) {\n return false;\n }\n\n int[] alphabets = new int[26];\n\n for (char c : s.toCharArray()) {\n alphabets[c - 'a']++;\n }\n\n for (char c : t.toCharArray()) {\n alphabets[c - 'a']--;\n }\n\n for (int alphabet : alphabets) {\n if (alphabet != 0) {\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "242. Valid Anagram", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their i th paper, return the researcher's h-index . According to the definition of h-index on Wikipedia : The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == citations.length", + "1 <= n <= 5000", + "0 <= citations[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:citations = [3,0,6,1,5]Output:3Explanation:[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.", + "image": null + }, + { + "text": "Example 2: Input:citations = [1,3,1]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int hIndex(int[] citations) { // Time: O(n) || Space: O(n + 1) -> 1 n for using counting array\n\n int n = citations.length;\n int[] count = new int[n + 1];\n int max = 0;\n\n for (int citation : citations) {\n ++count[Math.min(citation, n)];\n }\n\n for (int i = n; i >= 0; --i) { // i is the candidate's h-index\n max += count[i];\n if (max >= i)\n return i;\n }\n\n return 0;\n }\n}\n", + "title": "274. H-Index", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= bad <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:n = 5, bad = 4Output:4Explanation:call isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.", + "image": null + }, + { + "text": "Example 2: Input:n = 1, bad = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/* The isBadVersion API is defined in the parent class VersionControl.\n boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n public int firstBadVersion(int n) {\n int low = 1, high = n;\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n if (isBadVersion(mid)) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n return low;\n }\n}", + "title": "278. First Bad Version", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer n , return the least number of perfect square numbers that sum to n . A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1 , 4 , 9 , and 16 are perfect squares while 3 and 11 are not. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:n = 12Output:3Explanation:12 = 4 + 4 + 4.", + "image": null + }, + { + "text": "Example 2: Input:n = 13Output:2Explanation:13 = 4 + 9.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numSquares(int n) {\n int[] dp = new int[n + 1];\n\n for (int i = 1; i <= n; i++) {\n dp[i] = Integer.MAX_VALUE;\n \n for (int j = 1; j * j <= i; j++) {\n dp[i] = Math.min(dp[i], dp[i - j * j] + 1);\n }\n }\n\n return dp[n];\n }\n}", + "title": "279. Perfect Squares", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , move all 0 's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [0,1,0,3,12]Output:[1,3,12,0,0]", + "image": null + }, + { + "text": "Example 2: Input:nums = [0]Output:[0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public void moveZeroes(int[] nums) { // Two Pointer Approach\n int left = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n if (nums[right] != 0) {\n int temp = nums[right];\n nums[right] = nums[left];\n nums[left] = temp;\n left++;\n }\n }\n }\n}", + "title": "283. Move Zeroes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3,4,2,2]Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,2]Output:3", + "image": null + }, + { + "text": "Example 3: Input:nums = [3,3,3,3,3]Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findDuplicate(int[] nums) {\n int slow = nums[0];\n int fast = nums[0];\n\n // First part: find the intersection point\n do {\n slow = nums[slow];\n fast = nums[nums[fast]];\n } while (slow != fast);\n\n // Second part: find the entrance to the cycle\n slow = nums[0];\n while (slow != fast) {\n slow = nums[slow];\n fast = nums[fast];\n }\n\n return slow;\n }\n}", + "title": "287. Find the Duplicate Number", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "According to Wikipedia's article : \"The Game of Life , also known simply as Life , is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\" The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1 ) or dead (represented by a 0 ). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board . In this process, births and deaths occur simultaneously . Given the current state of the board , update the board to reflect its next state. Note that you do not need to return anything. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == board.length", + "n == board[i].length", + "1 <= m, n <= 25", + "board[i][j] is 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]Output:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" + }, + { + "text": "Example 2: Input:board = [[1,1],[1,0]]Output:[[1,1],[1,1]]", + "image": "https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public void gameOfLife(int[][] board) {\n int m = board.length, n = board[0].length;\n\n // Directions for 8 neighbors\n int[] dx = { -1, -1, -1, 0, 0, 1, 1, 1 };\n int[] dy = { -1, 0, 1, -1, 1, -1, 0, 1 };\n\n // Step 1: Encode changes in-place\n for (int i = 0; i < m; i++) {\n\n for (int j = 0; j < n; j++) {\n int liveNeighbors = 0;\n\n // Count live neighbors\n for (int d = 0; d < 8; d++) {\n int ni = i + dx[d], nj = j + dy[d];\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && Math.abs(board[ni][nj]) == 1) {\n liveNeighbors++;\n }\n }\n\n // Apply rules using encoded values\n if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {\n board[i][j] = -1; // Alive → Dead\n } else if (board[i][j] == 0 && liveNeighbors == 3) {\n board[i][j] = 2; // Dead → Alive\n }\n }\n }\n\n // Step 2: Decode the matrix\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n\n if (board[i][j] == -1)\n board[i][j] = 0;\n if (board[i][j] == 2)\n board[i][j] = 1;\n }\n }\n }\n}", + "title": "289. Game of Life", + "topic": "Dynamic Programming" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a pattern and a string s , find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s . Specifically: Example 1: Input: pattern = \"abba\", s = \"dog cat cat dog\" Output: true Explanation: The bijection can be established as: Example 2: Input: pattern = \"abba\", s = \"dog cat cat fish\" Output: false Example 3: Input: pattern = \"aaaa\", s = \"dog cat cat dog\" Output: false", + "description_images": [], + "constraints": [ + "Each letter in pattern maps to exactly one unique word in s .", + "Each unique word in s maps to exactly one letter in pattern .", + "No two letters map to the same word, and no two words map to the same letter." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public boolean wordPattern(String pattern, String s) {\n String[] words = s.split(\" \");\n\n if (pattern.length() != words.length)\n return false;\n\n Map map = new HashMap<>();\n Set mappedWords = new HashSet<>();\n\n for (int i = 0; i < pattern.length(); i++) {\n\n char c = pattern.charAt(i);\n String word = words[i];\n\n if (map.containsKey(c)) {\n\n if (!map.get(c).equals(word))\n return false;\n\n } else {\n\n if (mappedWords.contains(word))\n return false;\n\n map.put(c, word);\n mappedWords.add(word);\n }\n }\n\n return true;\n }\n}", + "title": "290. Word Pattern", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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. Implement the MedianFinder class: Example 1:", + "description_images": [], + "constraints": [ + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]Output[null, null, null, 1.5, null, 2.0]ExplanationMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0", + "image": null + } + ], + "follow_up": null, + "solution": "class MedianFinder {\n\n private final PriorityQueue maxHeap;\n private final PriorityQueue minHeap;\n\n public MedianFinder() {\n maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n minHeap = new PriorityQueue<>();\n }\n\n public void addNum(int num) {\n if (maxHeap.isEmpty() || num <= maxHeap.peek()) {\n maxHeap.offer(num);\n } else {\n minHeap.offer(num);\n }\n\n if (maxHeap.size() > minHeap.size() + 1) {\n minHeap.offer(maxHeap.poll());\n } else if (minHeap.size() > maxHeap.size()) {\n maxHeap.offer(minHeap.poll());\n }\n }\n\n public double findMedian() {\n if (maxHeap.size() > minHeap.size()) {\n return maxHeap.peek(); // Odd number of elements\n }\n\n return (maxHeap.peek() + minHeap.peek()) / 2.0; // Even number of elements\n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * MedianFinder obj = new MedianFinder();\n * obj.addNum(num);\n * double param_2 = obj.findMedian();\n */", + "title": "295. Find Median from Data Stream", + "topic": "Math" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-1000 <= Node.val <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,null,null,4,5]Output:[1,2,3,null,null,4,5]", + "image": "https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" + }, + { + "text": "Example 2: Input:root = []Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n\npublic class Codec {\n\n public String serialize(TreeNode root) {\n if (root == null)\n return \"null\";\n\n StringBuilder sb = new StringBuilder();\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n TreeNode node = queue.poll();\n if (node == null) {\n sb.append(\"null,\");\n continue;\n }\n sb.append(node.val).append(\",\");\n queue.offer(node.left);\n queue.offer(node.right);\n }\n\n sb.setLength(sb.length() - 1);\n return sb.toString();\n }\n\n public TreeNode deserialize(String data) {\n if (data.equals(\"null\"))\n return null;\n\n String[] values = data.split(\",\");\n TreeNode root = new TreeNode(Integer.parseInt(values[0]));\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n for (int i = 1; i < values.length; i++) {\n TreeNode parent = queue.poll();\n\n if (!values[i].equals(\"null\")) {\n parent.left = new TreeNode(Integer.parseInt(values[i]));\n queue.offer(parent.left);\n }\n i++;\n\n if (i < values.length && !values[i].equals(\"null\")) {\n parent.right = new TreeNode(Integer.parseInt(values[i]));\n queue.offer(parent.right);\n }\n }\n\n return root;\n }\n}\n\n// Your Codec object will be instantiated and called as such:\n// Codec ser = new Codec();\n// Codec deser = new Codec();\n// TreeNode ans = deser.deserialize(ser.serialize(root));", + "title": "297. Serialize and Deserialize Binary Tree", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return the length of the longest strictly increasing subsequence . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2500", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [10,9,2,5,3,7,101,18]Output:4Explanation:The longest increasing subsequence is [2,3,7,101], therefore the length is 4.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,0,3,2,3]Output:4", + "image": null + }, + { + "text": "Example 3: Input:nums = [7,7,7,7,7,7,7]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int lengthOfLIS(int[] nums) {\n int n = nums.length;\n int[] tails = new int[n]; // Max possible size is n\n int size = 0;\n\n for (int num : nums) {\n int idx = binarySearch(tails, 0, size - 1, num);\n\n if (idx == size) {\n tails[size++] = num; // Extend the sequence\n } else {\n tails[idx] = num; // Replace to maintain minimal tails\n }\n }\n\n return size;\n }\n\n // Binary search: Find first index where tails[i] >= target\n private int binarySearch(int[] tails, int left, int right, int target) {\n while (left <= right) {\n int mid = (left + right) >>> 1;\n\n if (tails[mid] >= target) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left; // Insertion point\n }\n}", + "title": "300. Longest Increasing Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following type: Implement the NumArray class: Example 1:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"sumRange\", \"sumRange\"]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]Output[null, 1, -1, -3]ExplanationNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3", + "image": null + } + ], + "follow_up": null, + "solution": "class NumArray {\n\n private final int[] prefix;\n\n public NumArray(int[] nums) {\n prefix = new int[nums.length + 1];\n\n for (int i = 0; i < nums.length; i++) {\n prefix[i + 1] = prefix[i] + nums[i];\n }\n }\n\n public int sumRange(int left, int right) {\n return prefix[right + 1] - prefix[left];\n }\n}\n\n/**\n * Your NumArray object will be instantiated and called as such:\n * NumArray obj = new NumArray(nums);\n * int param_1 = obj.sumRange(left,right);\n */", + "title": "303. Range Sum Query - Immutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , handle multiple queries of the following types: Implement the NumArray class: Example 1:", + "description_images": [], + "constraints": [ + "NumArray(int[] nums) Initializes the object with the integer array nums .", + "void update(int index, int val) Updates the value of nums[index] to be val .", + "int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right] )." + ], + "examples": [ + { + "text": "Example 1: Input[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]Output[null, 9, null, 8]ExplanationNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8", + "image": null + } + ], + "follow_up": null, + "solution": "public class NumArray {\n private int[] tree;\n private int n;\n\n public NumArray(int[] nums) {\n if (nums.length > 0) {\n n = nums.length;\n tree = new int[2 * n];\n buildTree(nums);\n }\n }\n\n private void buildTree(int[] nums) {\n\n // fill leaf nodes\n if (n >= 0) System.arraycopy(nums, 0, tree, n, n);\n\n // build the tree by calculating parents\n for (int i = n - 1; i > 0; --i) {\n tree[i] = tree[2 * i] + tree[2 * i + 1];\n }\n }\n\n public void update(int index, int val) {\n index += n; // Move to leaf\n tree[index] = val;\n\n while (index > 0) {\n\n int left = index;\n int right = index;\n\n if (index % 2 == 0) {\n right = index + 1;\n } else {\n left = index - 1;\n }\n\n // move one level up\n tree[index / 2] = tree[left] + tree[right];\n index /= 2;\n }\n }\n\n public int sumRange(int left, int right) {\n left += n;\n right += n;\n int sum = 0;\n\n while (left <= right) {\n\n if (left % 2 == 1) {\n sum += tree[left];\n left++;\n }\n if (right % 2 == 0) {\n sum += tree[right];\n right--;\n }\n left /= 2;\n right /= 2;\n }\n\n return sum;\n }\n}\n\n/**\n * Your NumArray object will be instantiated and called as such:\n * NumArray obj = new NumArray(nums);\n * obj.update(index,val);\n * int param_2 = obj.sumRange(left,right);\n */", + "title": "307. Range Sum Query - Mutable", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1 , and an array of n - 1 edges where edges[i] = [a i , b i ] indicates that there is an undirected edge between the two nodes a i and b i in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h . Among all possible rooted trees, those with minimum height (i.e. min(h) )  are called minimum height trees (MHTs). Return a list of all MHTs' root labels . You can return the answer in any order . The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 2 * 10^4", + "edges.length == n - 1", + "0 <= a i , b i < n", + "a i != b i", + "All the pairs (a i , b i ) are distinct.", + "The given input is guaranteed to be a tree and there will be no repeated edges." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4, edges = [[1,0],[1,2],[1,3]]Output:[1]Explanation:As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e1.jpg" + }, + { + "text": "Example 2: Input:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]Output:[3,4]", + "image": "https://assets.leetcode.com/uploads/2020/09/01/e2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findMinHeightTrees(int n, int[][] edges) {\n if (n == 1)\n return Collections.singletonList(0);\n\n List> graph = new ArrayList<>();\n for (int i = 0; i < n; i++)\n graph.add(new HashSet<>());\n \n for (int[] e : edges) {\n graph.get(e[0]).add(e[1]);\n graph.get(e[1]).add(e[0]);\n }\n\n List leaves = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n if (graph.get(i).size() == 1) {\n leaves.add(i);\n }\n }\n\n int remaining = n;\n while (remaining > 2) {\n remaining -= leaves.size();\n List newLeaves = new ArrayList<>();\n\n for (int leaf : leaves) {\n int neighbor = graph.get(leaf).iterator().next();\n graph.get(neighbor).remove(leaf);\n if (graph.get(neighbor).size() == 1) {\n newLeaves.add(neighbor);\n }\n }\n\n leaves = newLeaves;\n }\n\n return leaves;\n }\n}", + "title": "310. Minimum Height Trees", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= coins.length <= 12", + "1 <= coins[i] <= 2 31 - 1", + "0 <= amount <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:coins = [1,2,5], amount = 11Output:3Explanation:11 = 5 + 5 + 1", + "image": null + }, + { + "text": "Example 2: Input:coins = [2], amount = 3Output:-1", + "image": null + }, + { + "text": "Example 3: Input:coins = [1], amount = 0Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int coinChange(int[] coins, int amount) { // Bottom-Up DP (Tabulation) \n int max = amount + 1;\n int[] dp = new int[amount + 1];\n Arrays.fill(dp, max);\n dp[0] = 0;\n\n for (int i = 1; i <= amount; i++) {\n for (int coin : coins) {\n \n if (i - coin >= 0) {\n dp[i] = Math.min(dp[i], dp[i - coin] + 1);\n }\n }\n }\n\n return dp[amount] == max ? -1 : dp[amount];\n }\n}", + "title": "322. Coin Change", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list . The first node is considered odd , and the second node is even , and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the linked list is in the range [0, 10^4 ] .", + "-10^6 <= Node.val <= 10^6" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[1,3,5,2,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg" + }, + { + "text": "Example 2: Input:head = [2,1,3,5,6,4,7]Output:[2,3,6,7,1,5,4]", + "image": "https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode oddEvenList(ListNode head) {\n if (head == null || head.next == null)\n return head;\n\n ListNode odd = head, even = head.next, evenHead = even;\n\n while (even != null && even.next != null) {\n odd.next = even.next;\n odd = odd.next;\n even.next = even.next.next;\n even = even.next;\n }\n \n odd.next = evenHead;\n return head;\n }\n}", + "title": "328. Odd Even Linked List", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Given a sorted integer array nums and an integer n , add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 1000", + "1 <= nums[i] <= 10^4", + "nums is sorted in ascending order .", + "1 <= n <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,3], n = 6Output:1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,5,10], n = 20Output:2\nExplanation: The two patches can be [2, 4].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,2], n = 5Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minPatches(int[] nums, int n) {\n \n long miss = 1; // Start with the smallest number we need to cover\n int i = 0; // Index to traverse the nums array\n int patches = 0; // Number of patches added\n\n while (miss <= n) {\n \n if (i < nums.length && nums[i] <= miss) {\n \n // If nums[i] can contribute to forming the number `miss`\n miss += nums[i];\n i++;\n \n } else { // Otherwise, patch the array with `miss`\n miss += miss;\n patches++;\n }\n }\n\n return patches;\n }\n}", + "title": "330. Patching Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an integer array nums , return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k] . If no such indices exists, return false . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 5 * 10^5", + "-2 31 <= nums[i] <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4,5]Output:trueExplanation:Any triplet where i < j < k is valid.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,4,3,2,1]Output:falseExplanation:No triplet exists.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,5,0,4,6]Output:trueExplanation:The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;\n\n for (int num : nums) {\n \n if (num <= first)\n first = num;\n else if (num <= second)\n second = num;\n else\n return true;\n }\n\n return false;\n }\n}", + "title": "334. Increasing Triplet Subsequence", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:[0,1,1]Explanation:0 --> 0\n1 --> 1\n2 --> 10", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:[0,1,1,2,1,2]Explanation:0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] countBits(int n) {\n int[] ans = new int[n + 1];\n\n for (int i = 1; i <= n; i++) {\n ans[i] = ans[i >> 1] + (i & 1);\n }\n\n return ans;\n }\n}", + "title": "338. Counting Bits", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , reverse only all the vowels in the string and return it. The vowels are 'a' , 'e' , 'i' , 'o' , and 'u' , and they can appear in both lower and upper cases, more than once. Example 1: Input: s = \"IceCreAm\" Output: \"AceCreIm\" Explanation: The vowels in s are ['I', 'e', 'e', 'A'] . On reversing the vowels, s becomes \"AceCreIm\" . Example 2: Input: s = \"leetcode\" Output: \"leotcede\"", + "description_images": [], + "constraints": [ + "1 <= s.length <= 3 * 10^5", + "s consist of printable ASCII characters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public String reverseVowels(String s) {\n if (s == null || s.length() == 0)\n return s;\n\n Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u',\n 'A', 'E', 'I', 'O', 'U'));\n\n char[] chars = s.toCharArray();\n int i = 0, j = s.length() - 1;\n\n while (i < j) {\n while (i < j && !vowels.contains(chars[i])) {\n i++;\n }\n\n while (i < j && !vowels.contains(chars[j])) {\n j--;\n }\n\n if (i < j) {\n char temp = chars[i];\n chars[i] = chars[j];\n chars[j] = temp;\n i++;\n j--;\n }\n }\n\n return new String(chars);\n }\n}", + "title": "345. Reverse Vowels of a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,2,2,3], k = 2Output:[1,2]", + "image": null + }, + { + "text": "Example 2: Input:nums = [1], k = 1Output:[1]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] topKFrequent(int[] nums, int k) {\n Map freqMap = new HashMap<>();\n\n for (int num : nums) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n\n List[] bucket = new List[nums.length + 1];\n for (int key : freqMap.keySet()) {\n int freq = freqMap.get(key);\n\n if (bucket[freq] == null)\n bucket[freq] = new ArrayList<>();\n bucket[freq].add(key);\n }\n\n List result = new ArrayList<>();\n for (int i = bucket.length - 1; i >= 0 && result.size() < k; i--) {\n if (bucket[i] != null)\n result.addAll(bucket[i]);\n }\n\n return result.stream().mapToInt(i -> i).toArray();\n }\n}", + "title": "347. Top K Frequent Elements", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k . Define a pair (u, v) which consists of one element from the first array and one element from the second array. Return the k pairs (u 1 , v 1 ), (u 2 , v 2 ), ..., (u k , v k ) with the smallest sums . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length, nums2.length <= 10^5", + "-10^9 <= nums1[i], nums2[i] <= 10^9", + "nums1 and nums2 both are sorted in non-decreasing order .", + "1 <= k <= 10^4", + "k <= nums1.length * nums2.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,7,11], nums2 = [2,4,6], k = 3Output:[[1,2],[1,4],[1,6]]Explanation:The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,1,2], nums2 = [1,2,3], k = 2Output:[[1,1],[1,1]]Explanation:The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n List> result = new ArrayList<>();\n\n // Edge case\n if (nums1.length == 0 || nums2.length == 0) {\n return result;\n }\n\n PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n\n for (int i = 0; i < nums1.length; i++) {\n minHeap.offer(new int[] { nums1[i] + nums2[0], i, 0 }); // Store (sum, i, j)\n }\n\n // Extract the k smallest pairs\n while (k-- > 0 && !minHeap.isEmpty()) {\n int[] current = minHeap.poll();\n int i = current[1], j = current[2];\n\n result.add(Arrays.asList(nums1[i], nums2[j]));\n\n if (j + 1 < nums2.length) {\n minHeap.offer(new int[] { nums1[i] + nums2[j + 1], i, j + 1 });\n }\n }\n\n return result;\n }\n}", + "title": "373. Find K Pairs with Smallest Sums", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "We are playing the Guess Game. The game is as follows: I pick a number from 1 to n . You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num) , which returns three possible results: Return the number that I picked . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "-1 : Your guess is higher than the number I picked (i.e. num > pick ).", + "1 : Your guess is lower than the number I picked (i.e. num < pick ).", + "0 : your guess is equal to the number I picked (i.e. num == pick )." + ], + "examples": [ + { + "text": "Example 1: Input:n = 10, pick = 6Output:6", + "image": null + }, + { + "text": "Example 2: Input:n = 1, pick = 1Output:1", + "image": null + }, + { + "text": "Example 3: Input:n = 2, pick = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/** \n * Forward declaration of guess API.\n * @param num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n public int guessNumber(int n) {\n int low = 0;\n int high = n;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n\n if (guess(mid) == 0) {\n return mid;\n } else if (guess(mid) == -1) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n \n return -1;\n }\n}", + "title": "374. Guess Number Higher or Lower", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Implement the RandomizedSet class: You must implement the functions of the class such that each function works in average O(1) time complexity. Example 1:", + "description_images": [], + "constraints": [ + "RandomizedSet() Initializes the RandomizedSet object.", + "bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.", + "bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.", + "int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned." + ], + "examples": [ + { + "text": "Example 1: Input[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]Output[null, true, false, true, 2, true, false, 2]ExplanationRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.", + "image": null + } + ], + "follow_up": null, + "solution": "import java.util.*;\n\nclass RandomizedSet {\n\n private ArrayList list;\n private Map map; // Maps value to its index in the list\n private int size = 0;\n private Random rand;\n\n public RandomizedSet() {\n this.list = new ArrayList<>();\n this.map = new HashMap<>();\n this.rand = new Random();\n }\n\n private boolean search(int val) {\n return map.containsKey(val);\n }\n\n public boolean insert(int val) {\n\n if (search(val))\n return false;\n\n map.put(val, list.size());\n list.add(val);\n size++;\n\n return true;\n }\n\n public boolean remove(int val) {\n\n if (!search(val))\n return false;\n\n int index = map.get(val);\n int temp = list.get(size - 1);\n\n list.set(index, temp);\n map.put(temp, index);\n\n list.remove(size - 1);\n map.remove(val);\n size--;\n\n return true;\n }\n\n public int getRandom() {\n return list.get(rand.nextInt(list.size()));\n }\n}\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * boolean param_1 = obj.insert(val);\n * boolean param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */", + "title": "380. Insert Delete GetRandom O(1)", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings ransomNote and magazine , return true if ransomNote can be constructed by using the letters from magazine and false otherwise . Each letter in magazine can only be used once in ransomNote . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= ransomNote.length, magazine.length <= 10^5", + "ransomNote and magazine consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:ransomNote = \"a\", magazine = \"b\"Output:false", + "image": null + }, + { + "text": "Example 2: Input:ransomNote = \"aa\", magazine = \"ab\"Output:false", + "image": null + }, + { + "text": "Example 3: Input:ransomNote = \"aa\", magazine = \"aab\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canConstruct(String ransomNote, String magazine) {\n int[] count = new int[26];\n\n // Count occurrences of characters in the magazine\n for (char c : magazine.toCharArray()) {\n count[c - 'a']++;\n }\n\n // Check if we can construct the ransomNote from the magazine\n for (char c : ransomNote.toCharArray()) {\n if (count[c - 'a'] == 0) {\n return false; // Not enough characters in magazine\n }\n count[c - 'a']--; \n }\n\n return true;\n }\n}\n\n// class Solution {\n// public boolean canConstruct(String ransomNote, String magazine) {\n\n// HashMap map = new HashMap<>();\n\n// for (char c : magazine.toCharArray()) {\n// map.put(c, map.getOrDefault(c, 0) + 1);\n// }\n\n// for (char c : ransomNote.toCharArray()) {\n// if (!map.containsKey(c) || map.get(c) <= 0) {\n// return false;\n// }\n// map.put(c, map.get(c) - 1);\n// }\n\n// return true;\n// }\n// }", + "title": "383. Ransom Note", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s , find the first non-repeating character in it and return its index. If it does not exist, return -1 . Example 1: Input: s = \"leetcode\" Output: 0 Explanation: The character 'l' at index 0 is the first character that does not occur at any other index. Example 2: Input: s = \"loveleetcode\" Output: 2 Example 3: Input: s = \"aabb\" Output: -1", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of only lowercase English letters." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int firstUniqChar(String s) {\n int[] freq = new int[26];\n\n for (char c : s.toCharArray()) {\n freq[c - 'a']++;\n }\n\n for (int i = 0; i < s.length(); i++) {\n if (freq[s.charAt(i) - 'a'] == 1) {\n return i;\n }\n }\n\n return -1;\n }\n}", + "title": "387. First Unique Character in a String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two strings s and t , return true if s is a subsequence of t , or false otherwise . A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \" a b c d e \" while \"aec\" is not). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= s.length <= 100", + "0 <= t.length <= 10^4", + "s and t consist only of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abc\", t = \"ahbgdc\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"axc\", t = \"ahbgdc\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isSubsequence(String s, String t) {\n\n int p1 = 0, p2 = 0;\n\n while (p1 < s.length() && p2 < t.length()) {\n\n if (s.charAt(p1) == t.charAt(p2)) {\n p1++;\n }\n p2++;\n }\n return p1 == s.length();\n }\n}", + "title": "392. Is Subsequence", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string] , where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k . For example, there will not be input like 3a or 2[4] . The test cases are generated so that the length of the output will never exceed 10^5 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 30", + "s consists of lowercase English letters, digits, and square brackets '[]' .", + "s is guaranteed to be a valid input.", + "All the integers in s are in the range [1, 300] ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"3[a]2[bc]\"Output:\"aaabcbc\"", + "image": null + }, + { + "text": "Example 2: Input:s = \"3[a2[c]]\"Output:\"accaccacc\"", + "image": null + }, + { + "text": "Example 3: Input:s = \"2[abc]3[cd]ef\"Output:\"abcabccdcdcdef\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String decodeString(String s) {\n Stack countStack = new Stack<>();\n Stack stringStack = new Stack<>();\n StringBuilder current = new StringBuilder();\n int k = 0;\n\n for (char ch : s.toCharArray()) {\n\n if (Character.isDigit(ch)) {\n k = k * 10 + (ch - '0');\n } else if (ch == '[') {\n countStack.push(k);\n stringStack.push(current);\n current = new StringBuilder();\n k = 0;\n } else if (ch == ']') {\n StringBuilder decoded = stringStack.pop();\n int repeat = countStack.pop();\n \n decoded.append(String.valueOf(current).repeat(repeat));\n current = decoded;\n } else {\n current.append(ch);\n }\n }\n\n return current.toString();\n }\n}", + "title": "394. Decode String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of variable pairs equations and an array of real numbers values , where equations[i] = [A i , B i ] and values[i] represent the equation A i / B i = values[i] . Each A i or B i is a string that represents a single variable. You are also given some queries , where queries[j] = [C j , D j ] represents the j th query where you must find the answer for C j / D j = ? . Return the answers to all queries . If a single answer cannot be determined, return -1.0 . Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction. Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= equations.length <= 20", + "equations[i].length == 2", + "1 <= A i .length, B i .length <= 5", + "values.length == equations.length", + "0.0 < values[i] <= 20.0", + "1 <= queries.length <= 20", + "queries[i].length == 2", + "1 <= C j .length, D j .length <= 5", + "A i , B i , C j , D j consist of lower case English letters and digits." + ], + "examples": [ + { + "text": "Example 1: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]Output:[6.00000,0.50000,-1.00000,1.00000,-1.00000]Explanation:Given:a / b = 2.0,b / c = 3.0queries are:a / c = ?,b / a = ?,a / e = ?,a / a = ?,x / x = ?return: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnote: x is undefined => -1.0", + "image": null + }, + { + "text": "Example 2: Input:equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]Output:[3.75000,0.40000,5.00000,0.20000]", + "image": null + }, + { + "text": "Example 3: Input:equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]Output:[0.50000,2.00000,-1.00000,-1.00000]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private Map> graph = new HashMap<>();\n\n public double[] calcEquation(List> equations, double[] values, List> queries) {\n\n // Step 1: Build the Graph\n for (int i = 0; i < equations.size(); i++) {\n String a = equations.get(i).get(0);\n String b = equations.get(i).get(1);\n double value = values[i];\n\n graph.putIfAbsent(a, new HashMap<>());\n graph.putIfAbsent(b, new HashMap<>());\n\n graph.get(a).put(b, value);\n graph.get(b).put(a, 1.0 / value);\n }\n\n // Step 2: Process Queries using DFS\n double[] results = new double[queries.size()];\n\n for (int i = 0; i < queries.size(); i++) {\n String start = queries.get(i).get(0);\n String end = queries.get(i).get(1);\n results[i] = dfs(start, end, new HashSet<>());\n }\n\n return results;\n }\n\n private double dfs(String start, String end, Set visited) {\n\n // If nodes are not in graph, return -1\n if (!graph.containsKey(start) || !graph.containsKey(end))\n return -1.0;\n\n // If start and end are the same, return 1.0\n if (start.equals(end))\n return 1.0;\n\n visited.add(start);\n Map neighbors = graph.get(start);\n\n for (String neighbor : neighbors.keySet()) {\n\n if (!visited.contains(neighbor)) {\n double weight = neighbors.get(neighbor);\n double result = dfs(neighbor, end, visited);\n\n if (result != -1.0)\n return weight * result;\n }\n }\n\n return -1.0;\n }\n}", + "title": "399. Evaluate Division", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive , for example, \"Aa\" is not considered a palindrome. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 2000", + "s consists of lowercase and/or uppercase English letters only." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abccccdd\"Output:7Explanation:One longest palindrome that can be built is \"dccaccd\", whose length is 7.", + "image": null + }, + { + "text": "Example 2: Input:s = \"a\"Output:1Explanation:The longest palindrome that can be built is \"a\", whose length is 1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestPalindrome(String s) {\n int oddCount = 0;\n Map map = new HashMap<>();\n\n for (char ch : s.toCharArray()) {\n map.put(ch, map.getOrDefault(ch, 0) + 1);\n\n if (map.get(ch) % 2 == 1)\n oddCount++;\n else\n oddCount--;\n }\n\n return oddCount > 1 ? s.length() - oddCount + 1 : s.length();\n }\n}", + "title": "409. Longest Palindrome", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 200", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,5,11,5]Output:trueExplanation:The array can be partitioned as [1, 5, 5] and [11].", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3,5]Output:falseExplanation:The array cannot be partitioned into equal sum subsets.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPartition(int[] nums) {\n int total = Arrays.stream(nums).sum();\n \n if (total % 2 != 0)\n return false;\n int target = total / 2;\n\n boolean[] dp = new boolean[target + 1];\n dp[0] = true;\n\n for (int num : nums) {\n for (int i = target; i >= num; i--) {\n dp[i] |= dp[i - num];\n }\n }\n\n return dp[target];\n }\n}", + "title": "416. Partition Equal Subset Sum", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: Note that each function must run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "AllOne() Initializes the object of the data structure.", + "inc(String key) Increments the count of the string key by 1 . If key does not exist in the data structure, insert it with count 1 .", + "dec(String key) Decrements the count of the string key by 1 . If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.", + "getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\" .", + "getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]Output[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]ExplanationAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"", + "image": null + } + ], + "follow_up": null, + "solution": "public class AllOne {\n\n class Bucket {\n int count;\n Set keys;\n Bucket prev, next;\n\n Bucket(int count) {\n this.count = count;\n this.keys = new LinkedHashSet<>();\n }\n }\n\n private Map keyCount;\n private Map countBucket;\n private Bucket head, tail;\n\n public AllOne() {\n keyCount = new HashMap<>();\n countBucket = new HashMap<>();\n head = new Bucket(Integer.MIN_VALUE);\n tail = new Bucket(Integer.MAX_VALUE);\n head.next = tail;\n tail.prev = head;\n }\n\n public void inc(String key) {\n int count = keyCount.getOrDefault(key, 0);\n keyCount.put(key, count + 1);\n\n Bucket currBucket = countBucket.get(count);\n Bucket newBucket = countBucket.get(count + 1);\n\n if (newBucket == null) {\n newBucket = new Bucket(count + 1);\n countBucket.put(count + 1, newBucket);\n insertAfter(currBucket == null ? head : currBucket, newBucket);\n }\n\n newBucket.keys.add(key);\n\n if (currBucket != null) {\n currBucket.keys.remove(key);\n if (currBucket.keys.isEmpty()) {\n remove(currBucket);\n countBucket.remove(count);\n }\n }\n }\n\n public void dec(String key) {\n if (!keyCount.containsKey(key))\n return;\n\n int count = keyCount.get(key);\n Bucket currBucket = countBucket.get(count);\n\n if (count == 1) {\n keyCount.remove(key);\n } else {\n keyCount.put(key, count - 1);\n Bucket newBucket = countBucket.get(count - 1);\n if (newBucket == null) {\n newBucket = new Bucket(count - 1);\n countBucket.put(count - 1, newBucket);\n insertBefore(currBucket, newBucket);\n }\n newBucket.keys.add(key);\n }\n\n currBucket.keys.remove(key);\n if (currBucket.keys.isEmpty()) {\n remove(currBucket);\n countBucket.remove(count);\n }\n }\n\n public String getMaxKey() {\n if (tail.prev == head)\n return \"\";\n return tail.prev.keys.iterator().next();\n }\n\n public String getMinKey() {\n if (head.next == tail)\n return \"\";\n return head.next.keys.iterator().next();\n }\n\n private void insertAfter(Bucket prev, Bucket newBucket) {\n newBucket.next = prev.next;\n newBucket.prev = prev;\n prev.next.prev = newBucket;\n prev.next = newBucket;\n }\n\n private void insertBefore(Bucket next, Bucket newBucket) {\n newBucket.prev = next.prev;\n newBucket.next = next;\n next.prev.next = newBucket;\n next.prev = newBucket;\n }\n\n private void remove(Bucket bucket) {\n bucket.prev.next = bucket.next;\n bucket.next.prev = bucket.prev;\n }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */", + "title": "432. All O`one Data Structure", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "A gene string can be represented by an 8-character long string, with choices from 'A' , 'C' , 'G' , and 'T' . Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string. Given the two gene strings startGene and endGene and the gene bank bank , return the minimum number of mutations needed to mutate from startGene to endGene . If there is no such a mutation, return -1 . Note that the starting point is assumed to be valid, so it might not be included in the bank. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation." + ], + "examples": [ + { + "text": "Example 1: Input:startGene = \"AACCGGTT\", endGene = \"AACCGGTA\", bank = [\"AACCGGTA\"]Output:1", + "image": null + }, + { + "text": "Example 2: Input:startGene = \"AACCGGTT\", endGene = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minMutation(String startGene, String endGene, String[] bank) {\n Queue queue = new LinkedList<>();\n boolean[] visited = new boolean[bank.length];\n\n queue.offer(startGene);\n int mutations = 0;\n\n // Process the queue using BFS\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n String currentGene = queue.poll();\n\n // If we've reached the end gene, return the number of mutations\n if (currentGene.equals(endGene)) {\n return mutations;\n }\n\n // Try all genes in the bank to see if they differ by exactly one character\n for (int j = 0; j < bank.length; j++) {\n\n if (visited[j])\n continue;\n\n if (isOneMutationApart(bank[j], currentGene)) {\n visited[j] = true; // Mark as visited\n queue.offer(bank[j]);\n }\n }\n }\n mutations++;\n }\n\n return -1;\n }\n\n // Helper function to check if two genes differ by exactly one character\n private boolean isOneMutationApart(String gene1, String gene2) {\n int differences = 0;\n\n for (int i = 0; i < gene1.length(); i++) {\n\n if (gene1.charAt(i) != gene2.charAt(i)) {\n differences++;\n if (differences > 1)\n return false;\n }\n }\n return differences == 1;\n }\n}", + "title": "433. Minimum Genetic Mutation", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= intervals.length <= 10^5", + "intervals[i].length == 2", + "-5 * 10^4 <= start i < end i <= 5 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:intervals = [[1,2],[2,3],[3,4],[1,3]]Output:1Explanation:[1,3] can be removed and the rest of the intervals are non-overlapping.", + "image": null + }, + { + "text": "Example 2: Input:intervals = [[1,2],[1,2],[1,2]]Output:2Explanation:You need to remove two [1,2] to make the rest of the intervals non-overlapping.", + "image": null + }, + { + "text": "Example 3: Input:intervals = [[1,2],[2,3]]Output:0Explanation:You don't need to remove any of the intervals since they're already non-overlapping.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int eraseOverlapIntervals(int[][] intervals) {\n if (intervals.length == 0)\n return 0;\n\n Arrays.sort(intervals, Comparator.comparingInt(a -> a[1]));\n\n int count = 1;\n int end = intervals[0][1];\n\n for (int i = 1; i < intervals.length; i++) {\n if (intervals[i][0] >= end) {\n count++;\n end = intervals[i][1];\n }\n }\n\n return intervals.length - count;\n }\n}", + "title": "435. Non-overlapping Intervals", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 1000] .", + "-10^9 <= Node.val <= 10^9", + "-1000 <= targetSum <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8Output:3Explanation:The paths that sum to 8 are shown.", + "image": "https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int pathSum(TreeNode root, int targetSum) {\n HashMap prefixSum = new HashMap<>();\n prefixSum.put(0L, 1); // Base case for prefix sum\n\n return dfs(root, 0L, targetSum, prefixSum);\n }\n\n private int dfs(TreeNode node, long currentSum, int targetSum, HashMap prefixSum) {\n if (node == null)\n return 0;\n\n currentSum += node.val;\n int count = prefixSum.getOrDefault(currentSum - targetSum, 0);\n\n prefixSum.put(currentSum, prefixSum.getOrDefault(currentSum, 0) + 1);\n\n count += dfs(node.left, currentSum, targetSum, prefixSum);\n count += dfs(node.right, currentSum, targetSum, prefixSum);\n\n prefixSum.put(currentSum, prefixSum.get(currentSum) - 1);\n\n return count;\n }\n}\n", + "title": "437. Path Sum III", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given two strings s and p , return an array of all the start indices of p 's anagrams in s . You may return the answer in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length, p.length <= 3 * 10^4", + "s and p consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"cbaebabacd\", p = \"abc\"Output:[0,6]Explanation:The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"abab\", p = \"ab\"Output:[0,1,2]Explanation:The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List findAnagrams(String s, String p) {\n List result = new ArrayList<>();\n\n if (p.length() > s.length())\n return result;\n\n int[] pFreq = new int[26];\n int[] sFreq = new int[26];\n\n for (int i = 0; i < p.length(); i++) {\n pFreq[p.charAt(i) - 'a']++;\n sFreq[s.charAt(i) - 'a']++;\n }\n\n if (Arrays.equals(pFreq, sFreq))\n result.add(0);\n\n for (int i = p.length(); i < s.length(); i++) {\n sFreq[s.charAt(i) - 'a']++;\n sFreq[s.charAt(i - p.length()) - 'a']--;\n\n if (Arrays.equals(pFreq, sFreq))\n result.add(i - p.length() + 1);\n }\n\n return result;\n }\n}", + "title": "438. Find All Anagrams in a String", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of characters chars , compress it using the following algorithm: Begin with an empty string s . For each group of consecutive repeating characters in chars : The compressed string s should not be returned separately , but instead, be stored in the input character array chars . Note that group lengths that are 10 or longer will be split into multiple characters in chars . After you are done modifying the input array, return the new length of the array . You must write an algorithm that uses only constant extra space. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "If the group's length is 1 , append the character to s .", + "Otherwise, append the character followed by the group's length." + ], + "examples": [ + { + "text": "Example 1: Input:chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]Output:Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]Explanation:The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".", + "image": null + }, + { + "text": "Example 2: Input:chars = [\"a\"]Output:Return 1, and the first character of the input array should be: [\"a\"]Explanation:The only group is \"a\", which remains uncompressed since it's a single character.", + "image": null + }, + { + "text": "Example 3: Input:chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]Output:Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].Explanation:The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int compress(char[] chars) {\n int write = 0;\n int read = 0;\n\n while (read < chars.length) {\n char currentChar = chars[read];\n int count = 0;\n\n while (read < chars.length && chars[read] == currentChar) {\n read++;\n count++;\n }\n\n chars[write++] = currentChar;\n\n if (count > 1) {\n for (char c : String.valueOf(count).toCharArray()) {\n chars[write++] = c;\n }\n }\n }\n\n return write;\n }\n}", + "title": "443. String Compression", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST . Basically, the deletion can be divided into two stages: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [0, 10^4 ] .", + "-10^5 <= Node.val <= 10^5", + "Each node has a unique value.", + "root is a valid binary search tree.", + "-10^5 <= key <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [5,3,6,2,4,null,7], key = 3Output:[5,4,6,2,null,null,7]Explanation:Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.", + "image": "https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg" + }, + { + "text": "Example 2: Input:root = [5,3,6,2,4,null,7], key = 0Output:[5,3,6,2,4,null,7]Explanation:The tree does not contain a node with value = 0.", + "image": null + }, + { + "text": "Example 3: Input:root = [], key = 0Output:[]", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode deleteNode(TreeNode root, int key) {\n if (root == null)\n return null;\n\n if (key < root.val) {\n root.left = deleteNode(root.left, key);\n } else if (key > root.val) {\n root.right = deleteNode(root.right, key);\n } else {\n // Case 1 & 2: one child or no child\n if (root.left == null)\n return root.right;\n if (root.right == null)\n return root.left;\n\n // Case 3: Two children\n TreeNode successor = findMin(root.right);\n root.val = successor.val;\n root.right = deleteNode(root.right, successor.val);\n }\n\n return root;\n }\n\n // Helper to find inorder successor (min in right subtree)\n private static TreeNode findMin(TreeNode node) {\n while (node.left != null)\n node = node.left;\n return node;\n }\n}", + "title": "450. Delete Node in a BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [x start , x end ] denotes a balloon whose horizontal diameter stretches between x start and x end . You do not know the exact y-coordinates of the balloons. Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with x start and x end is burst by an arrow shot at x if x start <= x <= x end . There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array points , return the minimum number of arrows that must be shot to burst all balloons . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= points.length <= 10^5", + "points[i].length == 2", + "-2 31 <= x start < x end <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[10,16],[2,8],[1,6],[7,12]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].", + "image": null + }, + { + "text": "Example 2: Input:points = [[1,2],[3,4],[5,6],[7,8]]Output:4Explanation:One arrow needs to be shot for each balloon for a total of 4 arrows.", + "image": null + }, + { + "text": "Example 3: Input:points = [[1,2],[2,3],[3,4],[4,5]]Output:2Explanation:The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMinArrowShots(int[][] points) {\n\n if (points.length == 0)\n return 0;\n \n Arrays.sort(points, Comparator.comparingInt(a -> a[1]));\n\n int arrows = 1;\n int arrowPosition = points[0][1];\n\n for (int i = 1; i < points.length; i++) {\n if (points[i][0] > arrowPosition) {\n arrowPosition = points[i][1];\n arrows++;\n }\n }\n\n return arrows;\n }\n}", + "title": "452. Minimum Number of Arrows to Burst Balloons", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity. Example 1:", + "description_images": [], + "constraints": [ + "LFUCache(int capacity) Initializes the object with the capacity of the data structure.", + "int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1 .", + "void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity , it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated." + ], + "examples": [ + { + "text": "Example 1: Input[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]Output[null, null, null, 1, null, -1, 3, null, -1, 3, 4]Explanation// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3", + "image": null + } + ], + "follow_up": null, + "solution": "class LFUCache {\n\n private final int capacity;\n private int minFreq;\n private final Map keyToVal;\n private final Map keyToFreq;\n private final Map> freqToKeys;\n\n public LFUCache(int capacity) {\n this.capacity = capacity;\n this.minFreq = 0;\n this.keyToVal = new HashMap<>();\n this.keyToFreq = new HashMap<>();\n this.freqToKeys = new HashMap<>();\n }\n\n public int get(int key) {\n if (!keyToVal.containsKey(key))\n return -1;\n\n int freq = keyToFreq.get(key);\n keyToFreq.put(key, freq + 1);\n\n freqToKeys.get(freq).remove(key);\n if (freqToKeys.get(freq).isEmpty()) {\n freqToKeys.remove(freq);\n if (freq == minFreq)\n minFreq++;\n }\n\n freqToKeys.computeIfAbsent(freq + 1, k -> new LinkedHashSet<>()).add(key);\n return keyToVal.get(key);\n }\n\n public void put(int key, int value) {\n if (capacity == 0)\n return;\n\n if (keyToVal.containsKey(key)) {\n keyToVal.put(key, value);\n get(key); // update frequency\n return;\n }\n\n if (keyToVal.size() >= capacity) {\n LinkedHashSet minFreqKeys = freqToKeys.get(minFreq);\n int evictKey = minFreqKeys.iterator().next();\n minFreqKeys.remove(evictKey);\n if (minFreqKeys.isEmpty())\n freqToKeys.remove(minFreq);\n\n keyToVal.remove(evictKey);\n keyToFreq.remove(evictKey);\n }\n\n keyToVal.put(key, value);\n keyToFreq.put(key, 1);\n freqToKeys.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);\n minFreq = 1;\n }\n}\n\n/**\n * Your LFUCache object will be instantiated and called as such:\n * LFUCache obj = new LFUCache(capacity);\n * int param_1 = obj.get(key);\n * obj.put(key,value);\n */", + "title": "460. LFU Cache", + "topic": "Hash Table" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a binary array nums , return the maximum number of consecutive 1 's in the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1,1,1]Output:3Explanation:The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,0,1,1,0,1]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMaxConsecutiveOnes(int[] nums) {\n int res = 0;\n int count = 0;\n\n for (int n : nums) {\n if (n == 0) {\n count = 0;\n } else {\n count++;\n }\n\n if (res < count) {\n res = count;\n }\n }\n\n return res;\n }\n}", + "title": "485. Max Consecutive Ones", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2 , where nums1 is a subset of nums2 . For each 0 <= i < nums1.length , find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2 . If there is no next greater element, then the answer for this query is -1 . Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums1.length <= nums2.length <= 1000", + "0 <= nums1[i], nums2[i] <= 10^4", + "All integers in nums1 and nums2 are unique .", + "All the integers of nums1 also appear in nums2 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [4,1,2], nums2 = [1,3,4,2]Output:[-1,3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [2,4], nums2 = [1,2,3,4]Output:[3,-1]Explanation:The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n Map ng = new HashMap<>();\n Deque st = new ArrayDeque<>();\n\n for (int num : nums2) {\n while (!st.isEmpty() && st.peek() < num) {\n ng.put(st.pop(), num);\n }\n st.push(num);\n }\n\n int[] res = new int[nums1.length];\n for (int i = 0; i < nums1.length; i++) {\n res[i] = ng.getOrDefault(nums1[i], -1);\n }\n \n return res;\n }\n}", + "title": "496. Next Greater Element I", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO . Since it has limited resources, it can only finish at most k distinct projects before the IPO . Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the i th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital , and return the final maximized capital . The answer is guaranteed to fit in a 32-bit signed integer. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= 10^5", + "0 <= w <= 10^9", + "n == profits.length", + "n == capital.length", + "1 <= n <= 10^5", + "0 <= profits[i] <= 10^4", + "0 <= capital[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]Output:4Explanation:Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.", + "image": null + }, + { + "text": "Example 2: Input:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n int n = profits.length;\n\n PriorityQueue minCapitalHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.capital));\n PriorityQueue maxProfitHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n for (int i = 0; i < n; i++) {\n minCapitalHeap.offer(new Project(capital[i], profits[i]));\n }\n\n // Perform up to k projects\n for (int i = 0; i < k; i++) {\n\n // Add all projects we can afford to maxProfitHeap\n while (!minCapitalHeap.isEmpty() && minCapitalHeap.peek().capital <= w) {\n maxProfitHeap.offer(minCapitalHeap.poll().profit);\n }\n\n if (maxProfitHeap.isEmpty()) {\n break;\n }\n\n w += maxProfitHeap.poll();\n }\n\n return w;\n }\n\n private static class Project {\n int capital;\n int profit;\n\n Project(int capital, int profit) {\n this.capital = capital;\n this.profit = profit;\n }\n }\n}", + "title": "502. IPO", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [2, 10^4 ] .", + "0 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,6,1,3]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg" + }, + { + "text": "Example 2: Input:root = [1,0,48,null,null,12,49]Output:1", + "image": "https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n private int minDiff = Integer.MAX_VALUE;\n private Integer prev = null;\n\n public int getMinimumDifference(TreeNode root) {\n inorder(root);\n return minDiff;\n }\n\n private void inorder(TreeNode node) {\n if (node == null)\n return;\n\n inorder(node.left);\n\n if (prev != null) {\n minDiff = Math.min(minDiff, node.val - prev);\n }\n prev = node.val;\n\n inorder(node.right);\n }\n}", + "title": "530. Minimum Absolute Difference in BST", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an m x n binary matrix mat , return the distance of the nearest 0 for each cell . The distance between two cells sharing a common edge is 1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "m == mat.length", + "n == mat[i].length", + "1 <= m, n <= 10^4", + "1 <= m * n <= 10^4", + "mat[i][j] is either 0 or 1 .", + "There is at least one 0 in mat ." + ], + "examples": [ + { + "text": "Example 1: Input:mat = [[0,0,0],[0,1,0],[0,0,0]]Output:[[0,0,0],[0,1,0],[0,0,0]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" + }, + { + "text": "Example 2: Input:mat = [[0,0,0],[0,1,0],[1,1,1]]Output:[[0,0,0],[0,1,0],[1,2,1]]", + "image": "https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] updateMatrix(int[][] mat) {\n int m = mat.length, n = mat[0].length;\n Queue queue = new LinkedList<>();\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n queue.offer(new int[] { i, j });\n } else {\n mat[i][j] = -1;\n }\n }\n }\n\n int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int x = cell[0], y = cell[1];\n for (int[] d : dirs) {\n int nx = x + d[0], ny = y + d[1];\n if (nx >= 0 && ny >= 0 && nx < m && ny < n && mat[nx][ny] == -1) {\n mat[nx][ny] = mat[x][y] + 1;\n queue.offer(new int[] { nx, ny });\n }\n }\n }\n\n return mat;\n }\n}", + "title": "542. 01 Matrix", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-100 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,2,3,4,5]Output:3Explanation:3 is the length of the path [4,2,1,3] or [5,2,1,3].", + "image": "https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" + }, + { + "text": "Example 2: Input:root = [1,2]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution { // DFS (Post-order)\n private int maxDiameter = 0;\n\n public int diameterOfBinaryTree(TreeNode root) {\n depth(root);\n return maxDiameter;\n }\n\n private int depth(TreeNode node) {\n if (node == null)\n return 0;\n\n int left = depth(node.left);\n int right = depth(node.right);\n\n maxDiameter = Math.max(maxDiameter, left + right);\n\n return Math.max(left, right) + 1;\n }\n}", + "title": "543. Diameter of Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b , and city b is connected directly with city c , then city a is connected indirectly with city c . A province is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the i th city and the j th city are directly connected, and isConnected[i][j] = 0 otherwise. Return the total number of provinces . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 200", + "n == isConnected.length", + "n == isConnected[i].length", + "isConnected[i][j] is 1 or 0 .", + "isConnected[i][i] == 1", + "isConnected[i][j] == isConnected[j][i]" + ], + "examples": [ + { + "text": "Example 1: Input:isConnected = [[1,1,0],[1,1,0],[0,0,1]]Output:2", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg" + }, + { + "text": "Example 2: Input:isConnected = [[1,0,0],[0,1,0],[0,0,1]]Output:3", + "image": "https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findCircleNum(int[][] isConnected) {\n int n = isConnected.length;\n boolean[] visited = new boolean[n];\n int provinceCount = 0;\n\n for (int i = 0; i < n; i++) {\n if (!visited[i]) {\n dfs(isConnected, visited, i);\n provinceCount++;\n }\n }\n\n return provinceCount;\n }\n\n private void dfs(int[][] isConnected, boolean[] visited, int city) {\n visited[city] = true;\n\n for (int j = 0; j < isConnected.length; j++) {\n if (isConnected[city][j] == 1 && !visited[j]) {\n dfs(isConnected, visited, j);\n }\n }\n }\n \n}", + "title": "547. Number of Provinces", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k , return the total number of subarrays whose sum equals to k . A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 2 * 10^4", + "-1000 <= nums[i] <= 1000", + "-10^7 <= k <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1], k = 2Output:2", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3], k = 3Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int subarraySum(int[] nums, int k) {\n Map prefSum = new HashMap<>();\n int count = 0, sum = 0;\n\n prefSum.put(0, 1); // base case\n\n for (int num : nums) {\n sum += num;\n\n if (prefSum.containsKey(sum - k)) {\n count += prefSum.get(sum - k);\n }\n\n prefSum.put(sum, prefSum.getOrDefault(sum, 0) + 1);\n }\n\n return count;\n }\n}", + "title": "560. Subarray Sum Equals K", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s1.length, s2.length <= 10^4", + "s1 and s2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s1 = \"ab\", s2 = \"eidbaooo\"Output:trueExplanation:s2 contains one permutation of s1 (\"ba\").", + "image": null + }, + { + "text": "Example 2: Input:s1 = \"ab\", s2 = \"eidboaoo\"Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkInclusion(String s1, String s2) {\n int s1Freq[] = new int[26];\n int s2Freq[] = new int[26];\n\n for (char c : s1.toCharArray()) {\n s1Freq[c - 'a']++;\n }\n\n for (int i = 0; i < s2.length(); i++) {\n s2Freq[s2.charAt(i) - 'a']++;\n\n if (i >= s1.length()) {\n s2Freq[(s2.charAt(i - s1.length())) - 'a']--;\n }\n\n if (Arrays.equals(s1Freq, s2Freq)) {\n return true;\n }\n }\n\n return false;\n }\n}", + "title": "567. Permutation in String", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0 's and 1 's, where 0 means empty and 1 means not empty, and an integer n , return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= flowerbed.length <= 2 * 10^4", + "flowerbed[i] is 0 or 1 .", + "There are no two adjacent flowers in flowerbed .", + "0 <= n <= flowerbed.length" + ], + "examples": [ + { + "text": "Example 1: Input:flowerbed = [1,0,0,0,1], n = 1Output:true", + "image": null + }, + { + "text": "Example 2: Input:flowerbed = [1,0,0,0,1], n = 2Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canPlaceFlowers(int[] flowerbed, int n) {\n\n if (n == 0)\n return true;\n\n for (int i = 0; i < flowerbed.length; i++) {\n\n if ((i == 0 || flowerbed[i - 1] == 0) &&\n (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) &&\n flowerbed[i] == 0) {\n\n flowerbed[i] = 1;\n n--;\n }\n }\n\n return n <= 0;\n }\n}", + "title": "605. Can Place Flowers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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.", + "description_images": [], + "constraints": [ + "1 <= tasks.length <= 10^4", + "tasks[i] is an uppercase English letter.", + "0 <= n <= 100" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int leastInterval(char[] tasks, int n) {\n int[] freq = new int[26];\n for (char task : tasks) {\n freq[task - 'A']++;\n }\n\n int maxFreq = 0;\n for (int f : freq) {\n maxFreq = Math.max(maxFreq, f);\n }\n\n int countMax = 0;\n for (int f : freq) {\n if (f == maxFreq)\n countMax++;\n }\n\n return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + countMax);\n }\n}", + "title": "621. Task Scheduler", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= c <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:c = 5Output:trueExplanation:1 * 1 + 2 * 2 = 5", + "image": null + }, + { + "text": "Example 2: Input:c = 3Output:false", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean judgeSquareSum(int c) {\n \n if (c < 0) {\n return false;\n }\n \n int left = 0;\n int right = (int) Math.sqrt(c); // Find the upper bound for right\n \n while (left <= right) {\n \n long sum = (long) left * left + (long) right * right; // Use long to prevent overflow\n \n if (sum == c) {\n return true;\n } else if (sum < c) {\n left++;\n } else {\n right--;\n }\n }\n \n return false;\n }\n}", + "title": "633. Sum of Square Numbers", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-2 31 <= Node.val <= 2 31 - 1" + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,9,20,null,null,15,7]Output:[3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" + }, + { + "text": "Example 2: Input:root = [3,9,20,15,7]Output:[3.00000,14.50000,11.00000]", + "image": "https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public List averageOfLevels(TreeNode root) {\n List result = new ArrayList<>();\n \n if (root == null)\n return result;\n\n Queue queue = new LinkedList<>();\n queue.offer(root);\n\n while (!queue.isEmpty()) {\n int levelSize = queue.size();\n double sum = 0;\n\n for (int i = 0; i < levelSize; i++) {\n\n TreeNode node = queue.poll();\n sum += node.val;\n\n if (node.left != null)\n queue.offer(node.left);\n if (node.right != null)\n queue.offer(node.right);\n }\n\n result.add(sum / levelSize);\n }\n\n return result;\n }\n}", + "title": "637. Average of Levels in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums consisting of n elements, and an integer k . Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value . Any answer with a calculation error less than 10 -5 will be accepted. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= k <= n <= 10^5", + "-10^4 <= nums[i] <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,12,-5,-6,50,3], k = 4Output:12.75000Explanation:Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75", + "image": null + }, + { + "text": "Example 2: Input:nums = [5], k = 1Output:5.00000", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public double findMaxAverage(int[] nums, int k) {\n int sum = 0;\n\n for (int i = 0; i < k; i++) {\n sum += nums[i];\n }\n\n double maxSum = sum;\n for (int i = k; i < nums.length; i++) {\n sum += nums[i] - nums[i - k];\n maxSum = Math.max(maxSum, sum);\n }\n\n return maxSum / k;\n }\n}", + "title": "643. Maximum Average Subarray I", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n . The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\" . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.", + "Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game." + ], + "examples": [ + { + "text": "Example 1: Input:senate = \"RD\"Output:\"Radiant\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + }, + { + "text": "Example 2: Input:senate = \"RDD\"Output:\"Dire\"Explanation:The first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String predictPartyVictory(String senate) {\n int n = senate.length();\n Queue radiant = new LinkedList<>();\n Queue dire = new LinkedList<>();\n\n for (int i = 0; i < n; i++) {\n if (senate.charAt(i) == 'R') {\n radiant.offer(i);\n } else {\n dire.offer(i);\n }\n }\n\n while (!radiant.isEmpty() && !dire.isEmpty()) {\n int r = radiant.poll();\n int d = dire.poll();\n\n if (r < d) {\n radiant.offer(r + n);\n } else {\n dire.offer(d + n);\n }\n }\n\n return radiant.isEmpty() ? \"Dire\" : \"Radiant\";\n }\n}", + "title": "649. Dota2 Senate", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s containing only three types of characters: '(' , ')' and '*' , return true if s is valid . The following rules define a valid string: Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"()\"Output:true", + "image": null + }, + { + "text": "Example 2: Input:s = \"(*)\"Output:true", + "image": null + }, + { + "text": "Example 3: Input:s = \"(*))\"Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean checkValidString(String s) {\n int min = 0, max = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (s.charAt(i) == '(') {\n min += 1;\n max += 1;\n } else if (s.charAt(i) == ')') {\n min -= 1;\n max -= 1;\n } else {\n min -= 1;\n max += 1;\n }\n\n if (min < 0) {\n min = 0;\n }\n \n if (max < 0) {\n return false;\n }\n }\n\n return min == 0;\n }\n}", + "title": "678. Valid Parenthesis String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array prices where prices[i] is the price of a given stock on the i th day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).", + "The transaction fee is only charged once for each stock purchase and sale." + ], + "examples": [ + { + "text": "Example 1: Input:prices = [1,3,2,8,4,9], fee = 2Output:8Explanation:The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.", + "image": null + }, + { + "text": "Example 2: Input:prices = [1,3,7,5,10,3], fee = 3Output:6", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfit(int[] prices, int fee) {\n int cash = 0;\n int hold = -prices[0];\n\n for (int i = 1; i < prices.length; i++) {\n cash = Math.max(cash, hold + prices[i] - fee); // Sell\n hold = Math.max(hold, cash - prices[i]); // Buy\n }\n\n return cash;\n }\n}", + "title": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order . The accounts themselves can be returned in any order . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= accounts.length <= 1000", + "2 <= accounts[i].length <= 10", + "1 <= accounts[i][j].length <= 30", + "accounts[i][0] consists of English letters.", + "accounts[i][j] (for j > 0) is a valid email." + ], + "examples": [ + { + "text": "Example 1: Input:accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Output:[[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]Explanation:The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.", + "image": null + }, + { + "text": "Example 2: Input:accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]Output:[[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> accountsMerge(List> accounts) {\n Map emailToName = new HashMap<>();\n Map parent = new HashMap<>();\n \n // Step 1: Initialize parent pointers\n for (List account : accounts) {\n String name = account.get(0);\n for (int i = 1; i < account.size(); i++) {\n String email = account.get(i);\n parent.putIfAbsent(email, email);\n emailToName.put(email, name);\n }\n }\n\n // Step 2: Union emails in same account\n for (List account : accounts) {\n String firstEmail = account.get(1);\n for (int i = 2; i < account.size(); i++) {\n union(parent, firstEmail, account.get(i));\n }\n }\n\n // Step 3: Group emails by root parent\n Map> unions = new HashMap<>();\n for (String email : parent.keySet()) {\n String root = find(parent, email);\n unions.putIfAbsent(root, new TreeSet<>());\n unions.get(root).add(email);\n }\n\n // Step 4: Build result\n List> res = new ArrayList<>();\n for (String root : unions.keySet()) {\n List merged = new ArrayList<>();\n merged.add(emailToName.get(root));\n merged.addAll(unions.get(root));\n res.add(merged);\n }\n\n return res;\n }\n\n private String find(Map parent, String s) {\n if (!parent.get(s).equals(s)) {\n parent.put(s, find(parent, parent.get(s)));\n }\n return parent.get(s);\n }\n\n private void union(Map parent, String a, String b) {\n String pa = find(parent, a);\n String pb = find(parent, b);\n if (!pa.equals(pb)) {\n parent.put(pa, pb);\n }\n }\n}", + "title": "721. Accounts Merge", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers nums , calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index . If no such index exists, return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^4", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,7,3,6,5,6]Output:3Explanation:The pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,2,3]Output:-1Explanation:There is no index that satisfies the conditions in the problem statement.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,1,-1]Output:0Explanation:The pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int pivotIndex(int[] nums) {\n int totalSum = 0;\n\n for (int num : nums) {\n totalSum += num;\n }\n\n int leftSum = 0;\n for (int i = 0; i < nums.length; i++) {\n\n int rigthSum = totalSum - leftSum - nums[i];\n if (leftSum == rigthSum)\n return i;\n leftSum += nums[i];\n }\n\n return -1;\n }\n}", + "title": "724. Find Pivot Index", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [0, 1000] .", + "0 <= Node.val <= 1000", + "1 <= k <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3], k = 5Output:[[1],[2],[3],[],[]]Explanation:The first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6,7,8,9,10], k = 3Output:[[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.", + "image": "https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n ListNode[] result = new ListNode[k];\n int length = 0;\n ListNode current = head;\n\n while (current != null) {\n length++;\n current = current.next;\n }\n\n int partSize = length / k;\n int longerParts = length % k;\n\n current = head;\n for (int i = 0; i < k; i++) {\n result[i] = current;\n int currentPartSize = partSize + (i < longerParts ? 1 : 0);\n\n for (int j = 0; j < currentPartSize - 1 && current != null; j++) {\n current = current.next;\n }\n\n if (current != null) {\n ListNode nextPartHead = current.next;\n current.next = null;\n current = nextPartHead;\n }\n }\n\n return result;\n }\n}", + "title": "725. Split Linked List in Parts", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an image represented by an m x n grid of integers image , where image[i][j] represents the pixel value of the image. You are also given three integers sr , sc , and color . Your task is to perform a flood fill on the image starting from the pixel image[sr][sc] . To perform a flood fill : Return the modified image after performing the flood fill. Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel. Example 2: Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0 Output: [[0,0,0],[0,0,0]] Explanation: The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg" + ], + "constraints": [ + "m == image.length", + "n == image[i].length", + "1 <= m, n <= 50", + "0 <= image[i][j], color < 2 16", + "0 <= sr < m", + "0 <= sc < n" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n private int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n public int[][] floodFill(int[][] image, int sr, int sc, int color) {\n int oldColor = image[sr][sc];\n if (oldColor == color)\n return image;\n\n dfs(image, sr, sc, oldColor, color);\n\n return image;\n }\n\n private void dfs(int[][] image, int r, int c, int oldColor, int newColor) {\n if (r < 0 || r >= image.length || c < 0 || c >= image[0].length)\n return;\n if (image[r][c] != oldColor)\n return;\n\n image[r][c] = newColor;\n for (int[] dir : directions) {\n dfs(image, r + dir[0], c + dir[1], oldColor, newColor);\n }\n }\n}", + "title": "733. Flood Fill", + "topic": "Graph" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= asteroids.length <= 10^4", + "-1000 <= asteroids[i] <= 1000", + "asteroids[i] != 0" + ], + "examples": [ + { + "text": "Example 1: Input:asteroids = [5,10,-5]Output:[5,10]Explanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.", + "image": null + }, + { + "text": "Example 2: Input:asteroids = [8,-8]Output:[]Explanation:The 8 and -8 collide exploding each other.", + "image": null + }, + { + "text": "Example 3: Input:asteroids = [10,2,-5]Output:[10]Explanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Deque stack = new ArrayDeque<>();\n\n for (int a : asteroids) {\n boolean alive = true;\n\n while (alive && a < 0 && !stack.isEmpty() && stack.peek() > 0) {\n int top = stack.peek();\n\n if (top < -a) {\n stack.pop();\n } else if (top == -a) {\n stack.pop();\n alive = false;\n } else {\n alive = false;\n }\n }\n\n if (alive) {\n stack.push(a);\n }\n }\n\n int[] result = new int[stack.size()];\n for (int i = stack.size() - 1; i >= 0; i--) {\n result[i] = stack.pop();\n }\n\n return result;\n }\n}", + "title": "735. Asteroid Collision", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= temperatures.length <= 10^5", + "30 <= temperatures[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:temperatures = [73,74,75,71,69,72,76,73]Output:[1,1,4,2,1,1,0,0]", + "image": null + }, + { + "text": "Example 2: Input:temperatures = [30,40,50,60]Output:[1,1,1,0]", + "image": null + }, + { + "text": "Example 3: Input:temperatures = [30,60,90]Output:[1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] dailyTemperatures(int[] temperatures) {\n int n = temperatures.length;\n int[] answer = new int[n];\n Deque stack = new ArrayDeque<>();\n\n for (int i = 0; i < n; i++) {\n\n while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {\n int prevIndex = stack.pop();\n answer[prevIndex] = i - prevIndex;\n }\n\n stack.push(i);\n }\n\n return answer;\n }\n}", + "title": "739. Daily Temperatures", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "2 <= cost.length <= 1000", + "0 <= cost[i] <= 999" + ], + "examples": [ + { + "text": "Example 1: Input:cost = [10,15,20]Output:15Explanation:You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.", + "image": null + }, + { + "text": "Example 2: Input:cost = [1,100,1,1,1,100,1,1,100,1]Output:6Explanation:You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int first = cost[0];\n int second = cost[1];\n\n if (n <= 2)\n return Math.min(first, second);\n\n for (int i = 2; i < n; i++) {\n int curr = cost[i] + Math.min(first, second);\n first = second;\n second = curr;\n }\n\n return Math.min(first, second);\n }\n}", + "title": "747. Min Cost Climbing Stairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 500", + "s consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"ababcbacadefegdehijhklij\"Output:[9,7,8]Explanation:The partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.", + "image": null + }, + { + "text": "Example 2: Input:s = \"eccbbbbdec\"Output:[10]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List partitionLabels(String s) {\n List result = new ArrayList<>();\n int[] lastIndex = new int[26];\n\n for (int i = 0; i < s.length(); i++) {\n lastIndex[s.charAt(i) - 'a'] = i;\n }\n\n int start = 0, end = 0;\n\n for (int i = 0; i < s.length(); i++) {\n end = Math.max(end, lastIndex[s.charAt(i) - 'a']);\n if (i == end) {\n result.add(end - start + 1);\n start = i + 1;\n }\n }\n\n return result;\n }\n}", + "title": "768. Partition Labels", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. Return the root of the Quad-Tree representing grid . A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: We can construct a Quad-Tree from a two-dimensional area using the following steps: If you want to know more about the Quad-Tree, you can refer to the wiki . Quad-Tree format: You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val] . If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0 . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/02/12/e2mat.png" + ], + "constraints": [ + "val : True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer.", + "isLeaf : True if the node is a leaf node on the tree or False if the node has four children." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[0,1],[1,0]]Output:[[0,1],[1,0],[1,1],[1,1],[1,0]]Explanation:The explanation of this example is shown below:\nNotice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.", + "image": "https://assets.leetcode.com/uploads/2020/02/11/grid1.png" + }, + { + "text": "Example 2: Input:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]Output:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]Explanation:All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:", + "image": null + }, + { + "text": "class Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}", + "image": null + } + ], + "follow_up": null, + "solution": "/*\n// Definition for a QuadTree node.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n\n \n public Node() {\n this.val = false;\n this.isLeaf = false;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = null;\n this.topRight = null;\n this.bottomLeft = null;\n this.bottomRight = null;\n }\n \n public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {\n this.val = val;\n this.isLeaf = isLeaf;\n this.topLeft = topLeft;\n this.topRight = topRight;\n this.bottomLeft = bottomLeft;\n this.bottomRight = bottomRight;\n }\n}\n*/\n\nclass Solution {\n public Node construct(int[][] grid) {\n return buildQuadTree(grid, 0, 0, grid.length);\n }\n\n private Node buildQuadTree(int[][] grid, int row, int col, int size) {\n\n if (isUniform(grid, row, col, size)) {\n return new Node(grid[row][col] == 1, true);\n }\n\n int half = size / 2;\n Node topLeft = buildQuadTree(grid, row, col, half);\n Node topRight = buildQuadTree(grid, row, col + half, half);\n Node bottomLeft = buildQuadTree(grid, row + half, col, half);\n Node bottomRight = buildQuadTree(grid, row + half, col + half, half);\n\n return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);\n }\n\n private boolean isUniform(int[][] grid, int row, int col, int size) {\n int val = grid[row][col];\n\n for (int i = row; i < row + size; i++) {\n for (int j = col; j < col + size; j++) {\n if (grid[i][j] != val)\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "772. Construct Quad Tree", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given the root of a binary search tree (BST) and an integer val . Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 5000] .", + "1 <= Node.val <= 10^7", + "root is a binary search tree.", + "1 <= val <= 10^7" + ], + "examples": [ + { + "text": "Example 1: Input:root = [4,2,7,1,3], val = 2Output:[2,1,3]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" + }, + { + "text": "Example 2: Input:root = [4,2,7,1,3], val = 5Output:[]", + "image": "https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode searchBST(TreeNode root, int val) {\n if (root == null)\n return null;\n\n if (root.val == val)\n return root;\n else if (root.val < val)\n return searchBST(root.right, val);\n else\n return searchBST(root.left, val);\n }\n}", + "title": "783. Search in a Binary Search Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "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." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [-1,0,3,5,9,12], target = 9Output:4Explanation:9 exists in nums and its index is 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [-1,0,3,5,9,12], target = 2Output:-1Explanation:2 does not exist in nums so return -1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int search(int[] nums, int target) {\n int left = 0, right = nums.length - 1;\n\n while (left <= right) {\n int mid = (left + right) >> 1;\n\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n return -1;\n }\n}", + "title": "792. Binary Search", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return the number of ways to tile an 2 x n board . Since the answer may be very large, return it modulo 10^9 + 7 . In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= n <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:n = 3Output:5Explanation:The five different ways are shown above.", + "image": "https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" + }, + { + "text": "Example 2: Input:n = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n private static final int MOD = 1_000_000_007;\n\n public int numTilings(int n) {\n if (n == 0)\n return 1;\n if (n == 1)\n return 1;\n if (n == 2)\n return 2;\n\n long[] dp = new long[n + 1];\n dp[0] = 1;\n dp[1] = 1;\n dp[2] = 2;\n\n for (int i = 3; i <= n; i++) {\n dp[i] = (2 * dp[i - 1] + dp[i - 3]) % MOD;\n }\n\n return (int) dp[n];\n }\n}", + "title": "806. Domino and Tromino Tiling", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have n jobs and m workers. You are given three arrays: difficulty , profit , and worker where: Every worker can be assigned at most one job , but one job can be completed multiple times . Return the maximum profit we can achieve after assigning the workers to the jobs. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "difficulty[i] and profit[i] are the difficulty and the profit of the i th job, and", + "worker[j] is the ability of j th worker (i.e., the j th worker can only complete a job with difficulty at most worker[j] )." + ], + "examples": [ + { + "text": "Example 1: Input:difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]Output:100Explanation:Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.", + "image": null + }, + { + "text": "Example 2: Input:difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n \n int n = difficulty.length;\n int m = worker.length;\n\n // Combine and sort jobs based on difficulty\n int[][] jobs = new int[n][2];\n \n for (int i = 0; i < n; i++) {\n \n jobs[i][0] = difficulty[i];\n jobs[i][1] = profit[i];\n }\n \n Arrays.sort(jobs, (a, b) -> a[0] - b[0]);\n\n // Sort workers\n Arrays.sort(worker);\n\n // Track the maximum profit available for any given difficulty\n int maxProfit = 0;\n int jobIndex = 0;\n int totalProfit = 0;\n\n // Assign jobs to workers\n for (int ability : worker) {\n \n while (jobIndex < n && ability >= jobs[jobIndex][0]) {\n \n maxProfit = Math.max(maxProfit, jobs[jobIndex][1]);\n jobIndex++;\n }\n \n totalProfit += maxProfit;\n }\n\n return totalProfit;\n }\n}", + "title": "826. Most Profit Assigning Work", + "topic": "Array" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "You are given an array routes representing bus routes where routes[i] is a bus route that the i th bus repeats forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target . You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target . Return -1 if it is not possible. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, if routes[0] = [1, 5, 7] , this means that the 0 th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever." + ], + "examples": [ + { + "text": "Example 1: Input:routes = [[1,2,7],[3,6,7]], source = 1, target = 6Output:2Explanation:The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.", + "image": null + }, + { + "text": "Example 2: Input:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12Output:-1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target)\n return 0;\n\n Map> stopToBuses = new HashMap<>();\n\n for (int i = 0; i < routes.length; i++) {\n for (int stop : routes[i]) {\n stopToBuses.computeIfAbsent(stop, k -> new ArrayList<>()).add(i);\n }\n }\n\n Queue queue = new LinkedList<>();\n Set visitedStops = new HashSet<>();\n Set visitedBuses = new HashSet<>();\n\n for (int bus : stopToBuses.getOrDefault(source, new ArrayList<>())) {\n queue.offer(bus);\n visitedBuses.add(bus);\n }\n\n int busesTaken = 1;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n\n for (int i = 0; i < size; i++) {\n int bus = queue.poll();\n\n for (int stop : routes[bus]) {\n if (stop == target)\n return busesTaken;\n\n if (visitedStops.contains(stop))\n continue;\n visitedStops.add(stop);\n\n for (int nextBus : stopToBuses.getOrDefault(stop, new ArrayList<>())) {\n if (!visitedBuses.contains(nextBus)) {\n visitedBuses.add(nextBus);\n queue.offer(nextBus);\n }\n }\n }\n }\n\n busesTaken++;\n }\n\n return -1;\n }\n}", + "title": "833. Bus Routes", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= hand.length <= 10^4", + "0 <= hand[i] <= 10^9", + "1 <= groupSize <= hand.length" + ], + "examples": [ + { + "text": "Example 1: Input:hand = [1,2,3,6,2,3,4,7,8], groupSize = 3Output:trueExplanation:Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]", + "image": null + }, + { + "text": "Example 2: Input:hand = [1,2,3,4,5], groupSize = 4Output:falseExplanation:Alice's hand can not be rearranged into groups of 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean isNStraightHand(int[] hand, int groupSize) {\n \n boolean output = false;\n \n if (hand.length % groupSize != 0) return false;\n \n TreeMap countMap = new TreeMap<>();\n \n for (int card : hand) {\n countMap.put(card, countMap.getOrDefault(card, 0) + 1);\n }\n\n while (!countMap.isEmpty()) {\n int first = countMap.firstKey();\n for (int i = 0; i < groupSize; i++) {\n int current = first + i;\n if (!countMap.containsKey(current)) return false;\n int count = countMap.get(current);\n if (count == 1) {\n countMap.remove(current);\n } else {\n countMap.put(current, count - 1);\n }\n }\n }\n\n return true;\n }\n}", + "title": "846. Hand of Straights", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0 . Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i , return true if you can visit all the rooms, or false otherwise . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == rooms.length", + "2 <= n <= 1000", + "0 <= rooms[i].length <= 1000", + "1 <= sum(rooms[i].length) <= 3000", + "0 <= rooms[i][j] < n", + "All the values of rooms[i] are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:rooms = [[1],[2],[3],[]]Output:trueExplanation:We visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.", + "image": null + }, + { + "text": "Example 2: Input:rooms = [[1,3],[3,0,1],[2],[0]]Output:falseExplanation:We can not enter room number 2 since the only key that unlocks it is in that room.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean canVisitAllRooms(List> rooms) {\n int n = rooms.size();\n boolean[] visited = new boolean[n];\n Queue queue = new LinkedList<>();\n queue.offer(0);\n visited[0] = true;\n\n while (!queue.isEmpty()) {\n int room = queue.poll();\n for (int key : rooms.get(room)) {\n if (!visited[key]) {\n visited[key] = true;\n queue.offer(key);\n }\n }\n }\n\n for (boolean v : visited) {\n if (!v)\n return false;\n }\n\n return true;\n }\n}", + "title": "871. Keys and Rooms", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence . For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8) . Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Example 2:", + "description_images": [ + "https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" + ], + "constraints": [ + "The number of nodes in each tree will be in the range [1, 200] .", + "Both of the given trees will have values in the range [0, 200] ." + ], + "examples": [ + { + "text": "Example 1: Input:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]Output:true", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg" + }, + { + "text": "Example 2: Input:root1 = [1,2,3], root2 = [1,3,2]Output:false", + "image": "https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n List list1 = new ArrayList<>();\n List list2 = new ArrayList<>();\n\n helper(list1, root1);\n helper(list2, root2);\n\n return list1.equals(list2) ? true : false;\n }\n\n private void helper(List list, TreeNode root) {\n if (root == null)\n return;\n\n if (root.left == null && root.right == null) {\n list.add(root.val);\n return;\n\n } else {\n helper(list, root.left);\n helper(list, root.right);\n }\n }\n}", + "title": "904. Leaf-Similar Trees", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= piles.length <= 10^4", + "piles.length <= h <= 10^9", + "1 <= piles[i] <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:piles = [3,6,7,11], h = 8Output:4", + "image": null + }, + { + "text": "Example 2: Input:piles = [30,11,23,4,20], h = 5Output:30", + "image": null + }, + { + "text": "Example 3: Input:piles = [30,11,23,4,20], h = 6Output:23", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public static int minEatingSpeed(int[] piles, int h) {\n int low = 1;\n int high = Arrays.stream(piles).max().getAsInt();\n\n while (low < high) {\n int mid = low + (high - low) / 2;\n\n if (canFinish(piles, mid, h)) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n return low;\n }\n\n private static boolean canFinish(int[] piles, int k, int h) {\n int hours = 0;\n\n for (int pile : piles) {\n hours += (pile + k - 1) / k; // ceil(pile / k)\n }\n\n return hours <= h;\n }\n\n}", + "title": "907. Koko Eating Bananas", + "topic": "String" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given the head of a singly linked list, return the middle node of the linked list . If there are two middle nodes, return the second middle node. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the list is in the range [1, 100] .", + "1 <= Node.val <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,2,3,4,5]Output:[3,4,5]Explanation:The middle node of the list is node 3.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist1.jpg" + }, + { + "text": "Example 2: Input:head = [1,2,3,4,5,6]Output:[4,5,6]Explanation:Since the list has two middle nodes with values 3 and 4, we return the second one.", + "image": "https://assets.leetcode.com/uploads/2021/07/23/lc-midlist2.jpg" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode middleNode(ListNode head) {\n if (head == null || head.next == null)\n return head;\n \n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n return slow;\n }\n}", + "title": "908. Middle of the Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. Implement the StockSpanner class: Example 1:", + "description_images": [], + "constraints": [ + "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." + ], + "examples": [ + { + "text": "Example 1: Input[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]Output[null, 1, 1, 1, 2, 1, 4, 6]ExplanationStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6", + "image": null + } + ], + "follow_up": null, + "solution": "class StockSpanner {\n private Deque stack;\n\n public StockSpanner() {\n stack = new ArrayDeque<>();\n }\n\n public int next(int price) {\n int span = 1;\n\n while (!stack.isEmpty() && stack.peek()[0] <= price) {\n span += stack.pop()[1];\n }\n\n stack.push(new int[] { price, span });\n return span;\n }\n\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */", + "title": "937. Online Stock Span", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an n x n integer matrix board where the cells are labeled from 1 to n 2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0] ) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr , do the following: A board square on row r and column c has a snake or ladder if board[r][c] != -1 . The destination of that snake or ladder is board[r][c] . Squares 1 and n 2 are not the starting points of any snake or ladder. Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. Return the least number of dice rolls required to reach the square n 2 . If it is not possible to reach the square, return -1 . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n 2 )] . This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "This choice simulates the result of a standard 6-sided die roll : i.e., there are always at most 6 destinations, regardless of the size of the board.", + "If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next .", + "The game ends when you reach the square n 2 ." + ], + "examples": [ + { + "text": "Example 1: Input:board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]Output:4Explanation:In the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.", + "image": "https://assets.leetcode.com/uploads/2018/09/23/snakes.png" + }, + { + "text": "Example 2: Input:board = [[-1,-1],[-1,3]]Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int snakesAndLadders(int[][] board) { // BFS\n int N = board.length;\n int[] flattenBoard = new int[N * N + 1]; // 1-based indexing\n boolean leftToRight = true;\n int index = 1;\n\n // Step 1: Flatten 2D board into 1D array\n for (int row = N - 1; row >= 0; row--) {\n\n if (leftToRight) {\n for (int col = 0; col < N; col++) {\n flattenBoard[index++] = board[row][col];\n }\n } else {\n for (int col = N - 1; col >= 0; col--) {\n flattenBoard[index++] = board[row][col];\n }\n }\n\n leftToRight = !leftToRight;\n }\n\n // Step 2: BFS to find the shortest path\n Queue queue = new LinkedList<>();\n boolean[] visited = new boolean[N * N + 1];\n \n queue.offer(new int[] { 1, 0 }); // {current square, moves}\n visited[1] = true;\n\n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n int pos = current[0], moves = current[1];\n\n // If we reached the last square, return moves\n if (pos == N * N)\n return moves;\n\n // Roll dice (1 to 6)\n for (int i = 1; i <= 6; i++) {\n int nextPos = pos + i;\n\n if (nextPos > N * N)\n break; // Out of bounds\n\n if (flattenBoard[nextPos] != -1) {\n nextPos = flattenBoard[nextPos]; // Ladder or snake\n }\n\n if (!visited[nextPos]) {\n visited[nextPos] = true;\n queue.offer(new int[] { nextPos, moves + 1 });\n }\n }\n }\n\n return -1; // No way to reach the last square\n }\n}", + "title": "945. Snakes and Ladders", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a circular integer array nums of length n , return the maximum possible sum of a non-empty subarray of nums . A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n] . A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j] , there does not exist i <= k1 , k2 <= j with k1 % n == k2 % n . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == nums.length", + "1 <= n <= 3 * 10^4", + "-3 * 10^4 <= nums[i] <= 3 * 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,-2,3,-2]Output:3Explanation:Subarray [3] has maximum sum 3.", + "image": null + }, + { + "text": "Example 2: Input:nums = [5,-3,5]Output:10Explanation:Subarray [5,5] has maximum sum 5 + 5 = 10.", + "image": null + }, + { + "text": "Example 3: Input:nums = [-3,-2,-3]Output:-2Explanation:Subarray [-2] has maximum sum -2.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxSubarraySumCircular(int[] nums) {\n int maxKadane = kadane(nums);\n\n int totalSum = 0;\n for (int i = 0; i < nums.length; i++) {\n totalSum += nums[i];\n nums[i] = -nums[i];\n }\n\n int minKadane = kadane(nums);\n int maxCircular = totalSum + minKadane;\n\n if (maxCircular == 0)\n return maxKadane;\n\n return Math.max(maxKadane, maxCircular);\n }\n\n private int kadane(int[] nums) {\n int maxSum = Integer.MIN_VALUE, currentSum = 0;\n for (int num : nums) {\n currentSum = Math.max(num, currentSum + num);\n maxSum = Math.max(maxSum, currentSum);\n }\n\n return maxSum;\n }\n}", + "title": "954. Maximum Sum Circular Subarray", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. Example 1:", + "description_images": [], + "constraints": [ + "RecentCounter() Initializes the counter with zero recent requests.", + "int ping(int t) Adds a new request at time t , where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t] ." + ], + "examples": [ + { + "text": "Example 1: Input[\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n[[], [1], [100], [3001], [3002]]Output[null, 1, 2, 3, 3]ExplanationRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1,100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1,100,3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1,100,3001,3002], range is [2,3002], return 3", + "image": null + } + ], + "follow_up": null, + "solution": "class RecentCounter {\n\n private Queue queue;\n\n public RecentCounter() {\n queue = new LinkedList<>();\n }\n\n public int ping(int t) {\n queue.offer(t);\n\n while(queue.peek() < t - 3000) {\n queue.poll();\n }\n\n return queue.size();\n }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */", + "title": "969. Number of Recent Calls", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "1 <= k <= points.length <= 10^4", + "-10^4 <= x i , y i <= 10^4" + ], + "examples": [ + { + "text": "Example 1: Input:points = [[1,3],[-2,2]], k = 1Output:[[-2,2]]Explanation:The distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].", + "image": "https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" + }, + { + "text": "Example 2: Input:points = [[3,3],[5,-1],[-2,4]], k = 2Output:[[3,3],[-2,4]]Explanation:The answer [[-2,4],[3,3]] would also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] kClosest(int[][] points, int K) {\n \n PriorityQueue heap = new PriorityQueue(new Comparator() { \n @Override\n public int compare(int[] left, int[] right) {\n return getDistance(right) - getDistance(left);\n }\n });\n \n for (int[] point: points) {\n heap.add(point);\n \n if (heap.size() > K)\n heap.poll();\n }\n \n int[][] result = new int[K][2];\n while (K > 0)\n result[--K] = heap.poll();\n \n return result;\n \n }\n \n private int getDistance(int [] point) {\n return point[0] * point[0] + point[1] * point[1];\n }\n}", + "title": "1014. K Closest Points to Origin", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 1:", + "description_images": [], + "constraints": [ + "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 \"\" ." + ], + "examples": [ + { + "text": "Example 1: Input[\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n[[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]Output[null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]ExplanationTimeMap timeMap = new TimeMap();\ntimeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\ntimeMap.get(\"foo\", 1); // return \"bar\"\ntimeMap.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\".\ntimeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\ntimeMap.get(\"foo\", 4); // return \"bar2\"\ntimeMap.get(\"foo\", 5); // return \"bar2\"", + "image": null + } + ], + "follow_up": null, + "solution": "class TimeMap {\n\n private Map> map;\n\n public TimeMap() {\n map = new HashMap<>();\n }\n\n // O(log n)\n public void set(String key, String value, int timestamp) {\n map.putIfAbsent(key, new TreeMap<>());\n map.get(key).put(timestamp, value);\n }\n \n // O(log n)\n public String get(String key, int timestamp) {\n if (!map.containsKey(key)) \n return \"\";\n\n TreeMap tree = map.get(key);\n Integer floorKey = tree.floorKey(timestamp);\n\n if (floorKey == null) \n return \"\"; \n\n return tree.get(floorKey);\n }\n}\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap obj = new TimeMap();\n * obj.set(key,value,timestamp);\n * String param_2 = obj.get(key,timestamp);\n */", + "title": "1023. Time Based Key-Value Store", + "topic": "Hash Table" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n grid where each cell can have one of three values: 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: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "0 representing an empty cell,", + "1 representing a fresh orange, or", + "2 representing a rotten orange." + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[2,1,1],[1,1,0],[0,1,1]]Output:4", + "image": "https://assets.leetcode.com/uploads/2019/02/16/oranges.png" + }, + { + "text": "Example 2: Input:grid = [[2,1,1],[0,1,1],[1,0,1]]Output:-1Explanation:The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.", + "image": null + }, + { + "text": "Example 3: Input:grid = [[0,2]]Output:0Explanation:Since there are already no fresh oranges at minute 0, the answer is just 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int orangesRotting(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n\n Queue queue = new LinkedList<>();\n int freshCount = 0;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n\n if (grid[r][c] == 2) {\n queue.offer(new int[] { r, c });\n } else if (grid[r][c] == 1) {\n freshCount++;\n }\n }\n }\n\n int minutes = 0;\n int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty() && freshCount >= 1) {\n int size = queue.size();\n minutes++;\n\n for (int i = 0; i < size; i++) {\n int[] pos = queue.poll();\n int r = pos[0], c = pos[1];\n\n for (int[] d : directions) {\n int newR = r + d[0];\n int newC = c + d[1];\n\n if (newR >= 0 && newR < rows && newC >= 0 && newC < cols && grid[newR][newC] == 1) {\n grid[newR][newC] = 2;\n queue.offer(new int[] { newR, newC });\n freshCount--;\n }\n }\n }\n }\n\n return freshCount == 0 ? minutes : -1;\n }\n}", + "title": "1036. Rotting Oranges", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums and an integer k , return the maximum number of consecutive 1 's in the array if you can flip at most k 0 's. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 .", + "0 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2Output:6Explanation:[1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3Output:10Explanation:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestOnes(int[] nums, int k) {\n int left = 0, maxLen = 0, zeroCount = 0;\n\n for (int right = 0; right < nums.length; right++) {\n if (nums[right] == 0) {\n zeroCount++;\n }\n\n while (zeroCount > k) {\n if (nums[left] == 0)\n zeroCount--;\n left++;\n }\n maxLen = Math.max(maxLen, right - left + 1);\n }\n\n return maxLen;\n }\n}", + "title": "1046. Max Consecutive Ones III", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the i th minute and all those customers leave after the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i th minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == customers.length == grumpy.length", + "1 <= minutes <= n <= 2 * 10^4", + "0 <= customers[i] <= 1000", + "grumpy[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3Output:16Explanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.", + "image": null + }, + { + "text": "Example 2: Input:customers = [1], grumpy = [0], minutes = 1Output:1", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n int n = customers.length;\n int unrealizedCustomers = 0;\n\n // Calculate initial number of unrealized customers in first 'minutes' window\n for (int i = 0; i < minutes; i++) {\n unrealizedCustomers += customers[i] * grumpy[i];\n }\n\n int maxUnrealizedCustomers = unrealizedCustomers;\n\n // Slide the 'minutes' window across the rest of the customers array\n for (int i = minutes; i < n; i++) {\n // Add the current minute's unsatisfied customers if the owner is grumpy\n // and remove the customers that are out of the current window\n unrealizedCustomers += customers[i] * grumpy[i];\n unrealizedCustomers -= customers[i - minutes] * grumpy[i - minutes];\n\n // Update the maximum unrealized customers\n maxUnrealizedCustomers = Math.max(\n maxUnrealizedCustomers,\n unrealizedCustomers\n );\n }\n\n // Start with maximum possible satisfied customers due to secret technique\n int totalCustomers = maxUnrealizedCustomers;\n\n // Add the satisfied customers during non-grumpy minutes\n for (int i = 0; i < customers.length; i++) {\n totalCustomers += customers[i] * (1 - grumpy[i]);\n }\n\n // Return the maximum number of satisfied customers\n return totalCustomers;\n }\n}", + "title": "1052. Grumpy Bookstore Owner", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given the root of a binary tree, the level of its root is 1 , the level of its children is 2 , and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The number of nodes in the tree is in the range [1, 10^4 ] .", + "-10^5 <= Node.val <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,7,0,7,-8,null,null]Output:2Explanation:Level 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.", + "image": "https://assets.leetcode.com/uploads/2019/05/03/capture.JPG" + }, + { + "text": "Example 2: Input:root = [989,null,10250,98693,-89388,null,null,null,-32127]Output:2", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int maxLevelSum(TreeNode root) {\n if (root == null)\n return 0;\n\n Queue queue = new LinkedList<>();\n queue.add(root);\n\n int maxSum = Integer.MIN_VALUE;\n int maxLevel = 1;\n int level = 1;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n int levelSum = 0;\n\n for (int i = 0; i < size; i++) {\n TreeNode curr = queue.poll();\n levelSum += curr.val;\n\n if (curr.left != null)\n queue.add(curr.left);\n if (curr.right != null)\n queue.add(curr.right);\n }\n\n if (levelSum > maxSum) {\n maxSum = levelSum;\n maxLevel = level;\n }\n\n level++;\n }\n\n return maxLevel;\n }\n}", + "title": "1116. Maximum Level Sum of a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "For two strings s and t , we say \" t divides s \" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2 , return the largest string x such that x divides both str1 and str2 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= str1.length, str2.length <= 1000", + "str1 and str2 consist of English uppercase letters." + ], + "examples": [ + { + "text": "Example 1: Input:str1 = \"ABCABC\", str2 = \"ABC\"Output:\"ABC\"", + "image": null + }, + { + "text": "Example 2: Input:str1 = \"ABABAB\", str2 = \"ABAB\"Output:\"AB\"", + "image": null + }, + { + "text": "Example 3: Input:str1 = \"LEET\", str2 = \"CODE\"Output:\"\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String gcdOfStrings(String str1, String str2) {\n\n if (str1.length() < str2.length())\n return gcdOfStrings(str2, str1);\n\n if (!str1.startsWith(str2))\n return \"\";\n\n if (str2.isEmpty())\n return str1;\n\n return gcdOfStrings(str1.substring(str2.length()), str2);\n }\n}", + "title": "1146. Greatest Common Divisor of Strings", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Suppose you are given the following code: The same instance of FooBar will be passed to two different threads: Modify the given program to output \"foobar\" n times. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "thread A will call foo() , while", + "thread B will call bar() ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 1Output:\"foobar\"Explanation:There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n\"foobar\" is being output 1 time.", + "image": null + }, + { + "text": "Example 2: Input:n = 2Output:\"foobarfoobar\"Explanation:\"foobar\" is being output 2 times.", + "image": null + }, + { + "text": "class FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n}", + "image": null + } + ], + "follow_up": null, + "solution": "public class FooBar {\n private int n;\n private Semaphore fooSemaphore = new Semaphore(1);\n private Semaphore barSemaphore = new Semaphore(0);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n fooSemaphore.acquire();\n printFoo.run();\n barSemaphore.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n barSemaphore.acquire();\n printBar.run();\n fooSemaphore.release();\n }\n }\n}", + "title": "1187. Print FooBar Alternately", + "topic": "Concurrency" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a function printNumber that can be called with an integer parameter and prints it to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero , even , and odd . The same instance of ZeroEvenOdd will be passed to three different threads: Modify the given class to output the series \"010203040506...\" where the length of the series must be 2n . Implement the ZeroEvenOdd class: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "For example, calling printNumber(7) prints 7 to the console." + ], + "examples": [ + { + "text": "Example 1: Input:n = 2Output:\"0102\"Explanation:There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n\"0102\" is the correct output.", + "image": null + }, + { + "text": "Example 2: Input:n = 5Output:\"0102030405\"", + "image": null + } + ], + "follow_up": null, + "solution": "class ZeroEvenOdd {\n private final int n;\n private final Lock lock = new ReentrantLock();\n private final Condition zeroCondition = lock.newCondition();\n private final Condition numbCondition = lock.newCondition();\n private volatile boolean zeroTime = true;\n private final AtomicInteger curr = new AtomicInteger(1);\n\n public ZeroEvenOdd(int n) {\n this.n = n;\n }\n\n // printNumber.accept(x) outputs \"x\", where x is an integer.\n public void zero(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() <= n) {\n try {\n lock.lock();\n while (!zeroTime) {\n zeroCondition.await();\n }\n if (curr.get() <= n) {\n printNumber.accept(0);\n }\n\n zeroTime = false;\n numbCondition.signalAll();\n } finally {\n lock.unlock();\n }\n }\n }\n\n public void even(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() < n) {\n try {\n lock.lock();\n while (zeroTime || curr.get() % 2 != 0) {\n numbCondition.await();\n }\n\n if (curr.get() <= n) {\n printNumber.accept(curr.get());\n }\n\n curr.getAndIncrement();\n zeroTime = true;\n zeroCondition.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n\n public void odd(IntConsumer printNumber) throws InterruptedException {\n while (curr.get() <= n) {\n try {\n lock.lock();\n while (zeroTime || curr.get() % 2 == 0) {\n numbCondition.await();\n }\n\n if (curr.get() <= n) {\n printNumber.accept(curr.get());\n }\n curr.getAndIncrement();\n zeroTime = true;\n zeroCondition.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n}", + "title": "1216. Print Zero Even Odd", + "topic": "Math" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "The Tribonacci sequence T n is defined as follows: T 0 = 0, T 1 = 1, T 2 = 1, and T n+3 = T n + T n+1 + T n+2 for n >= 0. Given n , return the value of T n . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "0 <= n <= 37", + "The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:n = 4Output:4Explanation:T_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4", + "image": null + }, + { + "text": "Example 2: Input:n = 25Output:1389537", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int tribonacci(int n) {\n if (n == 0)\n return 0;\n if (n == 1 || n == 2)\n return 1;\n\n int t0 = 0, t1 = 1, t2 = 1, tn = 0;\n\n for (int i = 3; i <= n; i++) {\n tn = t0 + t1 + t2;\n t0 = t1;\n t1 = t2;\n t2 = tn;\n }\n\n return tn;\n }\n}", + "title": "1236. N-th Tribonacci Number", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer k . A continuous subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 50000", + "1 <= nums[i] <= 10^5", + "1 <= k <= nums.length" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,2,1,1], k = 3Output:2Explanation:The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,4,6], k = 1Output:0Explanation:There are no odd numbers in the array.", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,2,2,1,2,2,1,2,2,2], k = 2Output:16", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n public int numberOfSubarrays(int[] nums, int k) {\n Queue oddIndices = new LinkedList<>();\n int subarrays = 0;\n int lastPopped = -1;\n int initialGap = -1;\n\n for (int i = 0; i < nums.length; i++) {\n // If element is odd, append its index to the list.\n if (nums[i] % 2 == 1) {\n oddIndices.offer(i);\n }\n // If the number of odd numbers exceeds k, remove the first odd index.\n if (oddIndices.size() > k) {\n lastPopped = oddIndices.poll();\n }\n // If there are exactly k odd numbers, add the number of even numbers\n // in the beginning of the subarray to the result.\n if (oddIndices.size() == k) {\n initialGap = oddIndices.element() - lastPopped;\n subarrays += initialGap;\n }\n }\n\n return subarrays;\n }\n}", + "title": "1248. Count Number of Nice Subarrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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. A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, \"ace\" is a subsequence of \"abcde\" ." + ], + "examples": [ + { + "text": "Example 1: Input:text1 = \"abcde\", text2 = \"ace\"Output:3Explanation:The longest common subsequence is \"ace\" and its length is 3.", + "image": null + }, + { + "text": "Example 2: Input:text1 = \"abc\", text2 = \"abc\"Output:3Explanation:The longest common subsequence is \"abc\" and its length is 3.", + "image": null + }, + { + "text": "Example 3: Input:text1 = \"abc\", text2 = \"def\"Output:0Explanation:There is no such common subsequence, so the result is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestCommonSubsequence(String text1, String text2) {\n int m = text1.length(), n = text2.length();\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n \n if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n dp[i][j] = 1 + dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n return dp[m][n];\n }\n}", + "title": "1250. Longest Common Subsequence", + "topic": "String" + }, + { + "difficulty": "Hard", + "language": "java", + "description": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the i th person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the i th person can see the j th person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]) . Return an array answer of length n where answer[i] is the number of people the i th person can see to their right in the queue . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/05/29/queue-plane.jpg" + ], + "constraints": [ + "n == heights.length", + "1 <= n <= 10^5", + "1 <= heights[i] <= 10^5", + "All the values of heights are unique ." + ], + "examples": [ + { + "text": "Example 1: Input:heights = [10,6,8,5,11,9]Output:[3,1,2,1,1,0]Explanation:Person 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.", + "image": null + }, + { + "text": "Example 2: Input:heights = [5,1,2,3,10]Output:[4,1,1,1,0]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] canSeePersonsCount(int[] heights) {\n int n = heights.length;\n int[] res = new int[n];\n Deque stack = new ArrayDeque<>();\n\n for (int i = n - 1; i >= 0; i--) {\n int count = 0;\n\n while (!stack.isEmpty() && heights[i] > stack.peek()) {\n stack.pop();\n count++;\n }\n\n if (!stack.isEmpty())\n count++; // taller or equal \n res[i] = count;\n stack.push(heights[i]);\n }\n\n return res;\n }\n}", + "title": "1305. Number of Visible People in a Queue", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array of integers arr , return true if the number of occurrences of each value in the array is unique or false otherwise . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= arr.length <= 1000", + "-1000 <= arr[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:arr = [1,2,2,1,1,3]Output:trueExplanation:The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.", + "image": null + }, + { + "text": "Example 2: Input:arr = [1,2]Output:false", + "image": null + }, + { + "text": "Example 3: Input:arr = [-3,0,1,-3,1,1,1,-3,10,0]Output:true", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean uniqueOccurrences(int[] arr) {\n Map freqMap = new HashMap<>();\n\n for (int num : arr) {\n freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);\n }\n\n Set seenFreq = new HashSet<>();\n for (int count : freqMap.values()) {\n if (!seenFreq.add(count)) {\n return false;\n }\n }\n\n return true;\n }\n}", + "title": "1319. Unique Number of Occurrences", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given two 0-indexed integer arrays nums1 and nums2 , return a list answer of size 2 where: Note that the integers in the lists may be returned in any order. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "answer[0] is a list of all distinct integers in nums1 which are not present in nums2 .", + "answer[1] is a list of all distinct integers in nums2 which are not present in nums1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,2,3], nums2 = [2,4,6]Output:[[1,3],[4,6]]Explanation:For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums1. Therefore, answer[1] = [4,6].", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [1,2,3,3], nums2 = [1,1,2,2]Output:[[3],[]]Explanation:For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n Set set1 = new HashSet<>();\n Set set2 = new HashSet<>();\n\n for (int n : nums1)\n set1.add(n);\n \n for (int n : nums2)\n set2.add(n);\n\n List onlyInNums1 = new ArrayList<>();\n List onlyInNums2 = new ArrayList<>();\n\n for (int n : set1) {\n if (!set2.contains(n)) {\n onlyInNums1.add(n);\n }\n }\n\n for (int n : set2) {\n if (!set1.contains(n)) {\n onlyInNums2.add(n);\n }\n }\n\n return List.of(onlyInNums1, onlyInNums2);\n }\n}", + "title": "1392. Find the Difference of Two Arrays", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an array of strings products and a string searchWord . Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord . If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= products.length <= 1000", + "1 <= products[i].length <= 3000", + "1 <= sum(products[i].length) <= 2 * 10^4", + "All the strings of products are unique .", + "products[i] consists of lowercase English letters.", + "1 <= searchWord.length <= 1000", + "searchWord consists of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"Output:[[\"mobile\",\"moneypot\",\"monitor\"],[\"mobile\",\"moneypot\",\"monitor\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"]]Explanation:products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"].\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"].\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"].", + "image": null + }, + { + "text": "Example 2: Input:products = [\"havana\"], searchWord = \"havana\"Output:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]Explanation:The only word \"havana\" will be always suggested while typing the search word.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List> suggestedProducts(String[] products, String searchWord) {\n Arrays.sort(products);\n List> result = new ArrayList<>();\n int n = products.length;\n String prefix = \"\";\n \n for (char ch : searchWord.toCharArray()) {\n prefix += ch;\n List suggestions = new ArrayList<>();\n\n int start = lowerBound(products, prefix);\n\n for (int i = start; i < Math.min(start + 3, n); i++) {\n if (products[i].startsWith(prefix)) {\n suggestions.add(products[i]);\n } else {\n break;\n }\n }\n result.add(suggestions);\n }\n\n return result;\n }\n\n private int lowerBound(String[] products, String prefix) {\n int low = 0, high = products.length;\n\n while (low < high) {\n int mid = (low + high) >> 1;\n\n if (products[mid].compareTo(prefix) < 0) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n\n return low;\n }\n}", + "title": "1397. Search Suggestions System", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given an array of integers nums and an integer limit , return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "0 <= limit <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [8,2,4,7], limit = 4Output:2Explanation:All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.", + "image": null + }, + { + "text": "Example 2: Input:nums = [10,1,2,4,7,2], limit = 5Output:4Explanation:The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.", + "image": null + }, + { + "text": "Example 3: Input:nums = [4,2,2,2,4,4,2,2], limit = 0Output:3", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums, int limit) {\n Deque maxDeque = new LinkedList<>();\n Deque minDeque = new LinkedList<>();\n\n int left = 0, maxLen = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n while (!maxDeque.isEmpty() && nums[right] > maxDeque.peekLast()) {\n maxDeque.pollLast();\n }\n maxDeque.offerLast(nums[right]);\n\n while (!minDeque.isEmpty() && nums[right] < minDeque.peekLast()) {\n minDeque.pollLast();\n }\n minDeque.offerLast(nums[right]);\n\n while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {\n if (maxDeque.peekFirst() == nums[left])\n maxDeque.pollFirst();\n if (minDeque.peekFirst() == nums[left])\n minDeque.pollFirst();\n left++;\n }\n\n maxLen = Math.max(maxLen, right - left + 1);\n }\n\n return maxLen;\n }\n}", + "title": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given 3 positives numbers a , b and c . Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation). Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation. Example 1: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png" + ], + "constraints": [ + "1 <= a <= 10^9", + "1 <= b <= 10^9", + "1 <= c <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:a = 2, b = 6, c = 5Output:3Explanation:After flips a = 1 , b = 4 , c = 5 such that (aORb==c)", + "image": null + }, + { + "text": "Example 2: Input:a = 4, b = 2, c = 7Output:1", + "image": null + }, + { + "text": "Example 3: Input:a = 1, b = 2, c = 3Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minFlips(int a, int b, int c) {\n int flips = 0;\n\n for (int i = 0; i < 32; i++) {\n int aBit = (a >> i) & 1;\n int bBit = (b >> i) & 1;\n int cBit = (c >> i) & 1;\n\n int orBit = aBit | bBit;\n\n if (orBit == cBit) {\n continue; // no flips needed\n }\n\n if (cBit == 0) {\n flips += aBit + bBit; // need to flip 1s to 0\n } else {\n flips += 1; // cBit == 1 but orBit == 0 → flip one to 1\n }\n }\n\n return flips;\n }\n}", + "title": "1441. Minimum Flips to Make a OR b Equal to c", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Choose any node in the binary tree and a direction (right or left).", + "If the current direction is right, move to the right child of the current node; otherwise, move to the left child.", + "Change the direction from right to left or from left to right.", + "Repeat the second and third steps until you can't move in the tree." + ], + "examples": [ + { + "text": "Example 1: Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]Output:3Explanation:Longest ZigZag path in blue nodes (right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" + }, + { + "text": "Example 2: Input:root = [1,1,1,null,1,null,null,1,1,null,1]Output:4Explanation:Longest ZigZag path in blue nodes (left -> right -> left -> right).", + "image": "https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" + }, + { + "text": "Example 3: Input:root = [1]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n int maxPath = 0;\n\n public int longestZigZag(TreeNode root) {\n if (root == null)\n return 0;\n\n dfs(root.left, 1, true);\n dfs(root.right, 1, false);\n\n return maxPath;\n }\n\n private void dfs(TreeNode node, int length, boolean isLeft) {\n if (node == null)\n return;\n\n maxPath = Math.max(maxPath, length);\n\n if (isLeft) {\n dfs(node.right, length + 1, false); // turn right\n dfs(node.left, 1, true); // reset\n } else {\n dfs(node.left, length + 1, true); // turn left\n dfs(node.right, 1, false); // reset\n }\n }\n}", + "title": "1474. Longest ZigZag Path in a Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array bloomDay , an integer m and an integer k . You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden. The garden consists of n flowers, the i th flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet. Return the minimum number of days you need to wait to be able to make m bouquets from the garden . If it is impossible to make m bouquets return -1 . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "bloomDay.length == n", + "1 <= n <= 10^5", + "1 <= bloomDay[i] <= 10^9", + "1 <= m <= 10^6", + "1 <= k <= n" + ], + "examples": [ + { + "text": "Example 1: Input:bloomDay = [1,10,3,10,2], m = 3, k = 1Output:3Explanation:Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.", + "image": null + }, + { + "text": "Example 2: Input:bloomDay = [1,10,3,10,2], m = 3, k = 2Output:-1Explanation:We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.", + "image": null + }, + { + "text": "Example 3: Input:bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3Output:12Explanation:We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n\n // Return the number of maximum bouquets that can be made on day mid.\n private int getNumOfBouquets(int[] bloomDay, int mid, int k) {\n int numOfBouquets = 0;\n int count = 0;\n\n for (int i = 0; i < bloomDay.length; i++) {\n // If the flower is bloomed, add to the set. Else reset the count.\n if (bloomDay[i] <= mid) {\n count++;\n } else {\n count = 0;\n }\n\n if (count == k) {\n numOfBouquets++;\n count = 0;\n }\n }\n\n return numOfBouquets;\n }\n\n public int minDays(int[] bloomDay, int m, int k) {\n int start = 0;\n int end = 0;\n for (int day : bloomDay) {\n end = Math.max(end, day);\n }\n\n int minDays = -1;\n while (start <= end) {\n int mid = (start + end) / 2;\n\n if (getNumOfBouquets(bloomDay, mid, k) >= m) {\n minDays = mid;\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n\n return minDays;\n }\n}", + "title": "1482. Minimum Number of Days to Make m Bouquets", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= votes.length <= 1000", + "1 <= votes[i].length <= 26", + "votes[i].length == votes[j].length for 0 <= i, j < votes.length .", + "votes[i][j] is an English uppercase letter.", + "All characters of votes[i] are unique.", + "All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length ." + ], + "examples": [ + { + "text": "Example 1: Input:votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]Output:\"ACB\"Explanation:Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third.", + "image": null + }, + { + "text": "Example 2: Input:votes = [\"WXYZ\",\"XYZW\"]Output:\"XWYZ\"Explanation:X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position.", + "image": null + }, + { + "text": "Example 3: Input:votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]Output:\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"Explanation:Only one voter, so their votes are used for the ranking.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String rankTeams(String[] votes) {\n if (votes == null || votes.length == 0) return \"\";\n\n int numPositions = votes[0].length();\n Map countMap = new HashMap<>();\n\n // Initialize map\n for (char c : votes[0].toCharArray()) {\n countMap.put(c, new int[numPositions]);\n }\n\n // Count votes\n for (String vote : votes) {\n for (int i = 0; i < vote.length(); i++) {\n char team = vote.charAt(i);\n countMap.get(team)[i]++;\n }\n }\n\n // Sort with custom comparator\n List teams = new ArrayList<>(countMap.keySet());\n teams.sort((a, b) -> {\n for (int i = 0; i < numPositions; i++) {\n if (countMap.get(a)[i] != countMap.get(b)[i]) {\n return countMap.get(b)[i] - countMap.get(a)[i];\n }\n }\n return Character.compare(a, b);\n });\n\n // Build result\n StringBuilder sb = new StringBuilder();\n for (char c : teams) sb.append(c);\n return sb.toString();\n }\n}\n", + "title": "1483. Rank Teams by Votes", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There are n kids with candies. You are given an integer array candies , where each candies[i] represents the number of candies the i th kid has, and an integer extraCandies , denoting the number of extra candies that you have. Return a boolean array result of length n , where result[i] is true if, after giving the i th kid all the extraCandies , they will have the greatest number of candies among all the kids , or false otherwise . Note that multiple kids can have the greatest number of candies. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "n == candies.length", + "2 <= n <= 100", + "1 <= candies[i] <= 100", + "1 <= extraCandies <= 50" + ], + "examples": [ + { + "text": "Example 1: Input:candies = [2,3,5,1,3], extraCandies = 3Output:[true,true,true,false,true]Explanation:If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.", + "image": null + }, + { + "text": "Example 2: Input:candies = [4,2,1,1,2], extraCandies = 1Output:[true,false,false,false,false]Explanation:There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.", + "image": null + }, + { + "text": "Example 3: Input:candies = [12,1,12], extraCandies = 10Output:[true,false,true]", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public List kidsWithCandies(int[] candies, int extraCandies) {\n int maxCandies = 0;\n\n for (int candy : candies) {\n if (candy > maxCandies) {\n maxCandies = candy;\n }\n }\n\n List result = new ArrayList<>();\n for (int candy : candies) {\n result.add(candy + extraCandies >= maxCandies);\n }\n\n return result;\n }\n}", + "title": "1528. Kids With the Greatest Number of Candies", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2: Example 3:", + "description_images": [ + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png", + "https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" + ], + "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] ." + ], + "examples": [ + { + "text": "Example 1: Input:root = [3,1,4,3,null,1,5]Output:4Explanation:Nodes in blue aregood.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.", + "image": null + }, + { + "text": "Example 2: Input:root = [3,3,null,4,2]Output:3Explanation:Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.", + "image": null + }, + { + "text": "Example 3: Input:root = [1]Output:1Explanation:Root is considered asgood.", + "image": null + } + ], + "follow_up": null, + "solution": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public int goodNodes(TreeNode root) {\n return dfs(root, root.val);\n }\n\n private int dfs(TreeNode node, int maxSoFar) {\n if (node == null)\n return 0;\n\n int good = node.val >= maxSoFar ? 1 : 0;\n maxSoFar = Math.max(maxSoFar, node.val);\n good += dfs(node.left, maxSoFar);\n good += dfs(node.right, maxSoFar);\n\n return good;\n }\n}", + "title": "1544. Count Good Nodes in Binary Tree", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a string s and an integer k , return the maximum number of vowel letters in any substring of s with length k . Vowel letters in English are 'a' , 'e' , 'i' , 'o' , and 'u' . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= s.length <= 10^5", + "s consists of lowercase English letters.", + "1 <= k <= s.length" + ], + "examples": [ + { + "text": "Example 1: Input:s = \"abciiidef\", k = 3Output:3Explanation:The substring \"iii\" contains 3 vowel letters.", + "image": null + }, + { + "text": "Example 2: Input:s = \"aeiou\", k = 2Output:2Explanation:Any substring of length 2 contains 2 vowels.", + "image": null + }, + { + "text": "Example 3: Input:s = \"leetcode\", k = 3Output:2Explanation:\"lee\", \"eet\" and \"ode\" contain 2 vowels.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxVowels(String s, int k) {\n Set vowels = Set.of('a', 'e', 'i', 'o', 'u');\n int maxVowels = 0, currVowels = 0;\n\n for (int i = 0; i < s.length(); i++) {\n\n if (vowels.contains(s.charAt(i))) {\n currVowels++;\n }\n\n if (i >= k && vowels.contains(s.charAt(i - k))) {\n currVowels--;\n }\n\n maxVowels = Math.max(maxVowels, currVowels);\n }\n\n return maxVowels;\n }\n}", + "title": "1567. Maximum Number of Vowels in a Substring of Given Length", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [a i , b i ] represents a road from city a i to city b i . This year, there will be a big event in the capital (city 0 ), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0 . Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "2 <= n <= 5 * 10^4", + "connections.length == n - 1", + "connections[i].length == 2", + "0 <= a i , b i <= n - 1", + "a i != b i" + ], + "examples": [ + { + "text": "Example 1: Input:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]Output:3Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png" + }, + { + "text": "Example 2: Input:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]Output:2Explanation:Change the direction of edges show in red such that each node can reach the node 0 (capital).", + "image": "https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png" + }, + { + "text": "Example 3: Input:n = 3, connections = [[1,0],[2,0]]Output:0", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int minReorder(int n, int[][] connections) {\n Map> graph = new HashMap<>();\n Set directedEdges = new HashSet<>();\n\n for (int[] conn : connections) {\n int from = conn[0], to = conn[1];\n graph.computeIfAbsent(from, x -> new ArrayList<>()).add(to);\n graph.computeIfAbsent(to, x -> new ArrayList<>()).add(from);\n directedEdges.add(from + \"->\" + to);\n }\n\n boolean[] visited = new boolean[n];\n return dfs(0, graph, directedEdges, visited);\n }\n\n private int dfs(int curr, Map> graph, Set directedEdges, boolean[] visited) {\n visited[curr] = true;\n int changes = 0;\n\n for (int neighbor : graph.getOrDefault(curr, new ArrayList<>())) {\n\n if (!visited[neighbor]) {\n if (directedEdges.contains(curr + \"->\" + neighbor)) {\n changes++;\n }\n changes += dfs(neighbor, graph, directedEdges, visited);\n }\n }\n\n return changes;\n }\n}", + "title": "1576. Reorder Routes to Make All Paths Lead to the City Zero", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a binary array nums , you should delete one element from it. Return the size of the longest non-empty subarray containing only 1 's in the resulting array . Return 0 if there is no such subarray. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "nums[i] is either 0 or 1 ." + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,1,0,1]Output:3Explanation:After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.", + "image": null + }, + { + "text": "Example 2: Input:nums = [0,1,1,1,0,1,1,0,1]Output:5Explanation:After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,1,1]Output:2Explanation:You must delete one element.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int longestSubarray(int[] nums) {\n int left = 0, maxLength = 0, zeroCount = 0;\n\n for (int right = 0; right < nums.length; right++) {\n\n if (nums[right] == 0)\n zeroCount++;\n\n while (zeroCount > 1) {\n\n if (nums[left] == 0)\n zeroCount--;\n left++;\n }\n\n maxLength = Math.max(maxLength, right - left);\n }\n\n return maxLength;\n }\n}", + "title": "1586. Longest Subarray of 1's After Deleting One Element", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Two strings are considered close if you can attain one from the other using the following operations: You can use the operations on either string as many times as necessary. Given two strings, word1 and word2 , return true if word1 and word2 are close , and false otherwise. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "Operation 1: Swap any two existing characters. For example, a b cd e -> a e cd b", + "For example, a b cd e -> a e cd b", + "Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)", + "For example, aa c abb -> bb c baa (all a 's turn into b 's, and all b 's turn into a 's)" + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"bca\"Output:trueExplanation:You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"a\", word2 = \"aa\"Output:falseExplanation:It is impossible to attain word2 from word1, or vice versa, in any number of operations.", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"cabbba\", word2 = \"abbccc\"Output:trueExplanation:You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"\nApply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length())\n return false;\n\n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n\n for (int i = 0; i < word1.length(); i++) {\n freq1[word1.charAt(i) - 'a']++;\n freq2[word2.charAt(i) - 'a']++;\n }\n\n for (int i = 0; i < 26; i++) {\n if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {\n return false;\n }\n }\n\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n\n return Arrays.equals(freq1, freq2);\n }\n}", + "title": "1777. Determine if Two Strings Are Close", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums and an integer k . In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array . Example 1: Example 2:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 10^5", + "1 <= nums[i] <= 10^9", + "1 <= k <= 10^9" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [1,2,3,4], k = 5Output:2Explanation:Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.", + "image": null + }, + { + "text": "Example 2: Input:nums = [3,1,3,4,3], k = 6Output:1Explanation:Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int maxOperations(int[] nums, int k) {\n Map freq = new HashMap<>();\n int count = 0;\n\n for (int num : nums) {\n int complement = k - num;\n\n if (freq.getOrDefault(complement, 0) > 0) {\n count++;\n freq.put(complement, freq.get(complement) - 1);\n } else {\n freq.put(num, freq.getOrDefault(num, 0) + 1);\n }\n }\n\n return count;\n }\n}", + "title": "1798. Max Number of K-Sum Pairs", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0 . You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i ​​​​​​ and i + 1 for all ( 0 <= i < n) . Return the highest altitude of a point. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == gain.length", + "1 <= n <= 100", + "-100 <= gain[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:gain = [-5,1,5,0,-7]Output:1Explanation:The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.", + "image": null + }, + { + "text": "Example 2: Input:gain = [-4,-3,-2,-1,4,3,2]Output:0Explanation:The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int largestAltitude(int[] gain) {\n int altitude = 0, maxAltitude = 0;\n\n for (int i : gain) {\n altitude += i;\n maxAltitude = Math.max(maxAltitude, altitude);\n }\n\n return maxAltitude;\n }\n}", + "title": "1833. Find the Highest Altitude", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized . Return an integer matrix height of size m x n where height[i][j] is cell (i, j) 's height. If there are multiple solutions, return any of them . Example 1: Example 2:", + "description_images": [ + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png", + "https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" + ], + "constraints": [ + "If isWater[i][j] == 0 , cell (i, j) is a land cell.", + "If isWater[i][j] == 1 , cell (i, j) is a water cell." + ], + "examples": [ + { + "text": "Example 1: Input:isWater = [[0,1],[0,0]]Output:[[1,0],[2,1]]Explanation:The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.", + "image": null + }, + { + "text": "Example 2: Input:isWater = [[0,0,1],[1,0,0],[0,0,0]]Output:[[1,1,0],[0,1,1],[1,2,2]]Explanation:A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[][] highestPeak(int[][] isWater) {\n int m = isWater.length, n = isWater[0].length;\n int[][] height = new int[m][n];\n Deque queue = new ArrayDeque<>();\n\n for (int[] row : height)\n Arrays.fill(row, -1);\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (isWater[i][j] == 1) {\n height[i][j] = 0;\n queue.offer(new int[] { i, j });\n }\n }\n }\n\n int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int x = cell[0], y = cell[1];\n\n for (int[] d : dirs) {\n int nx = x + d[0], ny = y + d[1];\n\n if (nx >= 0 && ny >= 0 && nx < m && ny < n && height[nx][ny] == -1) {\n height[nx][ny] = height[x][y] + 1;\n queue.offer(new int[] { nx, ny });\n }\n }\n }\n\n return height;\n }\n}", + "title": "1876. Map of Highest Peak", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given an array nums , return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero) . Otherwise, return false . There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length] , where % is the modulo operation. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "1 <= nums[i] <= 100" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [3,4,5,1,2]Output:trueExplanation:[1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].", + "image": null + }, + { + "text": "Example 2: Input:nums = [2,1,3,4]Output:falseExplanation:There is no sorted array once rotated that can make nums.", + "image": null + }, + { + "text": "Example 3: Input:nums = [1,2,3]Output:trueExplanation:[1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public boolean check(int[] nums) {\n int count = 0, n = nums.length;\n \n for (int i = 0; i < n; i++) {\n if (nums[i] > nums[(i + 1) % n]) \n count++;\n if (count > 1) \n return false;\n }\n \n return true;\n }\n}", + "title": "1878. Check if Array Is Sorted and Rotated", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given two strings word1 and word2 . Merge the strings by adding letters in alternating order, starting with word1 . If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= word1.length, word2.length <= 100", + "word1 and word2 consist of lowercase English letters." + ], + "examples": [ + { + "text": "Example 1: Input:word1 = \"abc\", word2 = \"pqr\"Output:\"apbqcr\"Explanation:The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r", + "image": null + }, + { + "text": "Example 2: Input:word1 = \"ab\", word2 = \"pqrs\"Output:\"apbqrs\"Explanation:Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s", + "image": null + }, + { + "text": "Example 3: Input:word1 = \"abcd\", word2 = \"pq\"Output:\"apbqcd\"Explanation:Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String mergeAlternately(String word1, String word2) {\n StringBuilder merged = new StringBuilder();\n int maxLength = Math.max(word1.length(), word2.length());\n\n for (int i = 0; i < maxLength; i++) {\n\n if (i < word1.length()) {\n merged.append(word1.charAt(i));\n }\n\n if (i < word2.length()) {\n merged.append(word2.charAt(i));\n }\n }\n\n return merged.toString();\n }\n}", + "title": "1894. Merge Strings Alternately", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an m x n matrix maze ( 0-indexed ) with empty cells (represented as '.' ) and walls (represented as '+' ). You are also given the entrance of the maze, where entrance = [entrance row , entrance col ] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up , down , left , or right . You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance . An exit is defined as an empty cell that is at the border of the maze . The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "maze.length == m", + "maze[i].length == n", + "1 <= m, n <= 100", + "maze[i][j] is either '.' or '+' .", + "entrance.length == 2", + "0 <= entrance row < m", + "0 <= entrance col < n", + "entrance will always be an empty cell." + ], + "examples": [ + { + "text": "Example 1: Input:maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]Output:1Explanation:There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" + }, + { + "text": "Example 2: Input:maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]Output:2Explanation:There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" + }, + { + "text": "Example 3: Input:maze = [[\".\",\"+\"]], entrance = [0,0]Output:-1Explanation:There are no exits in this maze.", + "image": "https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length;\n int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\n Queue queue = new LinkedList<>();\n queue.offer(new int[] { entrance[0], entrance[1], 0 });\n\n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n int r = current[0], c = current[1], steps = current[2];\n\n if ((r != entrance[0] || c != entrance[1]) &&\n (r == 0 || r == rows - 1 || c == 0 || c == cols - 1)) {\n return steps;\n }\n\n for (int[] dir : directions) {\n int nr = r + dir[0], nc = c + dir[1];\n\n if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && maze[nr][nc] == '.') {\n queue.offer(new int[] { nr, nc, steps + 1 });\n maze[nr][nc] = '+';\n }\n }\n }\n\n return -1;\n }\n}", + "title": "2038. Nearest Exit from Entrance in Maze", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "Given a 0-indexed integer array nums , find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1] . If middleIndex == 0 , the left side sum is considered to be 0 . Similarly, if middleIndex == nums.length - 1 , the right side sum is considered to be 0 . Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "1 <= nums.length <= 100", + "-1000 <= nums[i] <= 1000" + ], + "examples": [ + { + "text": "Example 1: Input:nums = [2,3,-1,8,4]Output:3Explanation:The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4", + "image": null + }, + { + "text": "Example 2: Input:nums = [1,-1,4]Output:2Explanation:The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0", + "image": null + }, + { + "text": "Example 3: Input:nums = [2,5]Output:-1Explanation:There is no valid middleIndex.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int findMiddleIndex(int[] nums) {\n int totalSum = 0;\n\n for (int num : nums) {\n totalSum += num;\n }\n\n int leftSum = 0;\n for (int i = 0; i < nums.length; i++) {\n\n int rigthSum = totalSum - leftSum - nums[i];\n if (leftSum == rigthSum)\n return i;\n\n leftSum += nums[i];\n }\n\n return -1;\n }\n}", + "title": "2102. Find the Middle Index in Array", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given the head of a linked list. Delete the middle node , and return the head of the modified linked list . The middle node of a linked list of size n is the ⌊n / 2⌋ th node from the start using 0-based indexing , where ⌊x⌋ denotes the largest integer less than or equal to x . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For n = 1 , 2 , 3 , 4 , and 5 , the middle nodes are 0 , 1 , 1 , 2 , and 2 , respectively." + ], + "examples": [ + { + "text": "Example 1: Input:head = [1,3,4,7,1,2,6]Output:[1,3,4,1,2,6]Explanation:The above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [1,2,3,4]Output:[1,2,4]Explanation:The above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [2,1]Output:[2]Explanation:The above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.", + "image": "https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode deleteMiddle(ListNode head) {\n if (head == null || head.next == null)\n return null;\n\n ListNode fast = head;\n ListNode slow = new ListNode(0);\n slow.next = head;\n\n while (fast != null && fast.next != null) {\n fast = fast.next.next;\n slow = slow.next;\n }\n\n slow.next = slow.next.next;\n return head;\n }\n}", + "title": "2216. Delete the Middle Node of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "In a linked list of size n , where n is even , the i th node ( 0-indexed ) of the linked list is known as the twin of the (n-1-i) th node, if 0 <= i <= (n / 2) - 1 . The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list . Example 1: Example 2: Example 3:", + "description_images": [], + "constraints": [ + "For example, if n = 4 , then node 0 is the twin of node 3 , and node 1 is the twin of node 2 . These are the only nodes with twins for n = 4 ." + ], + "examples": [ + { + "text": "Example 1: Input:head = [5,4,2,1]Output:6Explanation:Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" + }, + { + "text": "Example 2: Input:head = [4,2,2,3]Output:7Explanation:The nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" + }, + { + "text": "Example 3: Input:head = [1,100000]Output:100001Explanation:There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.", + "image": "https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" + } + ], + "follow_up": null, + "solution": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int pairSum(ListNode head) {\n // Step 1: Find the middle of the list\n ListNode slow = head, fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n // Step 2: Reverse the second half\n ListNode prev = null, curr = slow;\n while (curr != null) {\n ListNode next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n // Step 3: Calculate twin sums\n int maxSum = Integer.MIN_VALUE;\n ListNode left = head;\n ListNode right = prev; // Head of reversed second half\n\n while (right != null) {\n int sum = left.val + right.val;\n maxSum = Math.max(maxSum, sum);\n left = left.next;\n right = right.next;\n }\n\n return maxSum;\n }\n}", + "title": "2236. Maximum Twin Sum of a Linked List", + "topic": "Tree" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "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: Example 2:", + "description_images": [], + "constraints": [ + "n == spells.length", + "m == potions.length", + "1 <= n, m <= 10^5", + "1 <= spells[i], potions[i] <= 10^5", + "1 <= success <= 10^10" + ], + "examples": [ + { + "text": "Example 1: Input:spells = [5,1,3], potions = [1,2,3,4,5], success = 7Output:[4,0,3]Explanation:- 0thspell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1stspell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2ndspell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.", + "image": null + }, + { + "text": "Example 2: Input:spells = [3,1,2], potions = [8,5,8], success = 16Output:[2,0,2]Explanation:- 0thspell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1stspell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2ndspell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public int[] successfulPairs(int[] spells, int[] potions, long success) {\n Arrays.sort(potions);\n int m = potions.length;\n int[] ans = new int[spells.length];\n\n for (int i = 0; i < spells.length; i++) {\n long required = (success + spells[i] - 1) / spells[i]; // ceil division\n int idx = lowerBound(potions, required);\n ans[i] = m - idx;\n }\n return ans;\n }\n\n private int lowerBound(int[] arr, long target) {\n int l = 0, r = arr.length;\n\n while (l < r) { // binary search\n int mid = l + (r - l) / 2;\n if (arr[mid] < target)\n l = mid + 1;\n else\n r = mid;\n }\n\n return l;\n }\n}", + "title": "2392. Successful Pairs of Spells and Potions", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You have a set which contains all positive integers [1, 2, 3, 4, 5, ...] . Implement the SmallestInfiniteSet class: Example 1:", + "description_images": [], + "constraints": [ + "SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.", + "int popSmallest() Removes and returns the smallest integer contained in the infinite set.", + "void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set." + ], + "examples": [ + { + "text": "Example 1: Input[\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n[[], [2], [], [], [], [1], [], [], []]Output[null, null, 1, 2, 3, null, 1, 4, 5]ExplanationSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.", + "image": null + } + ], + "follow_up": null, + "solution": "class SmallestInfiniteSet {\n\n private PriorityQueue minHeap;\n private int current;\n\n public SmallestInfiniteSet() {\n minHeap = new PriorityQueue<>();\n current = 1;\n }\n\n public int popSmallest() {\n\n if (!minHeap.isEmpty()) {\n return minHeap.poll();\n } else {\n return current++;\n }\n }\n\n public void addBack(int num) {\n if (num < current && !minHeap.contains(num)) {\n minHeap.offer(num);\n }\n }\n}\n\n/**\n * Your SmallestInfiniteSet object will be instantiated and called as such:\n * SmallestInfiniteSet obj = new SmallestInfiniteSet();\n * int param_1 = obj.popSmallest();\n * obj.addBack(num);\n */", + "title": "2413. Smallest Number in Infinite Set", + "topic": "Math" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "Given a 0-indexed n x n integer matrix grid , return the number of pairs (r i , c j ) such that row r i and column c j are equal . A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array). Example 1: Example 2:", + "description_images": [], + "constraints": [ + "n == grid.length == grid[i].length", + "1 <= n <= 200", + "1 <= grid[i][j] <= 10^5" + ], + "examples": [ + { + "text": "Example 1: Input:grid = [[3,2,1],[1,7,6],[2,7,7]]Output:1Explanation:There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex1.jpg" + }, + { + "text": "Example 2: Input:grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]Output:3Explanation:There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]", + "image": "https://assets.leetcode.com/uploads/2022/06/01/ex2.jpg" + } + ], + "follow_up": null, + "solution": "class Solution {\n public int equalPairs(int[][] grid) {\n int n = grid.length;\n Map rowMap = new HashMap<>();\n int count = 0;\n\n for (int[] row : grid) {\n String key = encode(row);\n rowMap.put(key, rowMap.getOrDefault(key, 0) + 1);\n }\n\n for (int c = 0; c < n; c++) {\n int[] col = new int[n];\n \n for (int r = 0; r < n; r++) {\n col[r] = grid[r][c];\n }\n\n String colKey = encode(col);\n count += rowMap.getOrDefault(colKey, 0);\n }\n\n return count;\n }\n\n private static String encode(int[] arr) {\n StringBuilder sb = new StringBuilder();\n for (int num : arr) {\n sb.append(num).append(\"#\");\n }\n return sb.toString();\n }\n}", + "title": "2428. Equal Row and Column Pairs", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a string s , which contains stars * . In one operation, you can: Return the string after all stars have been removed . Note: Example 1: Example 2:", + "description_images": [], + "constraints": [ + "Choose a star in s .", + "Remove the closest non-star character to its left , as well as remove the star itself." + ], + "examples": [ + { + "text": "Example 1: Input:s = \"leet**cod*e\"Output:\"lecoe\"Explanation:Performing the removals from left to right:\n- The closest character to the 1ststar is 't' in \"leet**cod*e\". s becomes \"lee*cod*e\".\n- The closest character to the 2ndstar is 'e' in \"lee*cod*e\". s becomes \"lecod*e\".\n- The closest character to the 3rdstar is 'd' in \"lecod*e\". s becomes \"lecoe\".\nThere are no more stars, so we return \"lecoe\".", + "image": null + }, + { + "text": "Example 2: Input:s = \"erase*****\"Output:\"\"Explanation:The entire string is removed, so we return an empty string.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public String removeStars(String s) {\n Deque stack = new ArrayDeque<>();\n\n for (char c : s.toCharArray()) {\n if (c == '*') {\n stack.pollLast();\n } else {\n stack.addLast(c);\n }\n }\n\n // Convert stack to string\n StringBuilder sb = new StringBuilder();\n for (char ch : stack) {\n sb.append(ch);\n }\n\n return sb.toString();\n }\n}", + "title": "2470. Removing Stars From a String", + "topic": "String" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the i th worker. You are also given two integers k and candidates . We want to hire exactly k workers according to the following rules: Return the total cost to hire exactly k workers. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "You will run k sessions and hire exactly one worker in each session.", + "In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index. For example, if costs = [3,2,7,7,1,2] and candidates = 2 , then in the first hiring session, we will choose the 4 th worker because they have the lowest cost [ 3,2 ,7,7, 1 ,2 ] . In the second hiring session, we will choose 1 st worker because they have the same lowest cost as 4 th worker but they have the smallest index [ 3, 2 ,7, 7,2 ] . Please note that the indexing may be changed in the process.", + "For example, if costs = [3,2,7,7,1,2] and candidates = 2 , then in the first hiring session, we will choose the 4 th worker because they have the lowest cost [ 3,2 ,7,7, 1 ,2 ] .", + "In the second hiring session, we will choose 1 st worker because they have the same lowest cost as 4 th worker but they have the smallest index [ 3, 2 ,7, 7,2 ] . Please note that the indexing may be changed in the process.", + "If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.", + "A worker can only be chosen once." + ], + "examples": [ + { + "text": "Example 1: Input:costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4Output:11Explanation:We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.\n- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.\n- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.\nThe total hiring cost is 11.", + "image": null + }, + { + "text": "Example 2: Input:costs = [1,2,4,1], k = 3, candidates = 3Output:4Explanation:We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.\n- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.\n- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.\nThe total hiring cost is 4.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long totalCost(int[] costs, int k, int candidates) {\n int n = costs.length;\n long total = 0;\n int left = 0, right = n - 1;\n PriorityQueue heap = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n\n for (int i = 0; i < candidates && left <= right; i++) {\n heap.offer(new int[] { costs[left], left });\n left++;\n }\n\n for (int i = 0; i < candidates && left <= right; i++) {\n heap.offer(new int[] { costs[right], right });\n right--;\n }\n\n for (int hired = 0; hired < k; hired++) {\n int[] curr = heap.poll();\n int cost = curr[0];\n int idx = curr[1];\n total += cost;\n\n if (idx < left) { // Came from left side\n if (left <= right) {\n heap.offer(new int[] { costs[left], left });\n left++;\n }\n } else { // Came from right side\n if (left <= right) {\n heap.offer(new int[] { costs[right], right });\n right--;\n }\n }\n }\n\n return total;\n }\n}", + "title": "2553. Total Cost to Hire K Workers", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k . You must choose a subsequence of indices from nums1 of length k . For chosen indices i 0 , i 1 , ..., i k - 1 , your score is defined as: Return the maximum possible score. A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements. Example 1: Example 2:", + "description_images": [], + "constraints": [ + "The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2 .", + "It can defined simply as: (nums1[i 0 ] + nums1[i 1 ] +...+ nums1[i k - 1 ]) * min(nums2[i 0 ] , nums2[i 1 ], ... ,nums2[i k - 1 ]) ." + ], + "examples": [ + { + "text": "Example 1: Input:nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3Output:12Explanation:The four possible subsequence scores are:\n- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.\n- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6. \n- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12. \n- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.\nTherefore, we return the max score, which is 12.", + "image": null + }, + { + "text": "Example 2: Input:nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1Output:30Explanation:Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.", + "image": null + } + ], + "follow_up": null, + "solution": "class Solution {\n public long maxScore(int[] nums1, int[] nums2, int k) {\n int n = nums1.length;\n int[][] pairs = new int[n][2];\n\n for (int i = 0; i < n; i++) {\n pairs[i][0] = nums2[i];\n pairs[i][1] = nums1[i];\n }\n\n Arrays.sort(pairs, (a, b) -> b[0] - a[0]);\n\n PriorityQueue minHeap = new PriorityQueue<>();\n long maxScore = 0, sum = 0;\n\n for (int i = 0; i < n; i++) {\n int currNum1 = pairs[i][1];\n int currNum2 = pairs[i][0];\n\n sum += currNum1;\n minHeap.add(currNum1);\n\n if (minHeap.size() > k) {\n sum -= minHeap.poll();\n }\n\n if (minHeap.size() == k) {\n maxScore = Math.max(maxScore, sum * currNum2);\n }\n }\n\n return maxScore;\n }\n}", + "title": "2636. Maximum Subsequence Score", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums . A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k . Return the number of unique XOR triplet values from all possible triplets (i, j, k) . Example 1: Input: nums = [1,3] Output: 2 Explanation: The possible XOR triplet values are: The unique XOR values are {1, 3} . Thus, the output is 2. Example 2: Input: nums = [6,7,8,9] Output: 4 Explanation: The possible XOR triplet values are {6, 7, 8, 9} . Thus, the output is 4.", + "description_images": [], + "constraints": [ + "(0, 0, 0) → 1 XOR 1 XOR 1 = 1", + "(0, 0, 1) → 1 XOR 1 XOR 3 = 3", + "(0, 1, 1) → 1 XOR 3 XOR 3 = 1", + "(1, 1, 1) → 3 XOR 3 XOR 3 = 3" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int uniqueXorTriplets(int[] nums) {\n Set pairs = new HashSet<>(List.of(0));\n for (int i = 0, n = nums.length; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n pairs.add(nums[i] ^ nums[j]);\n }\n }\n\n BitSet triplets = new BitSet();\n for (int xy : pairs) {\n for (int z : nums) {\n triplets.set(xy ^ z);\n }\n }\n\n return triplets.cardinality();\n }\n}", + "title": "3820. Number of Unique XOR Triplets II", + "topic": "Array" + }, + { + "difficulty": "Medium", + "language": "java", + "description": "You are given an integer array nums of length n , where nums is a permutation of the numbers in the range [1, n] . A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k . Return the number of unique XOR triplet values from all possible triplets (i, j, k) . Example 1: Input: nums = [1,2] Output: 2 Explanation: The possible XOR triplet values are: The unique XOR values are {1, 2} , so the output is 2. Example 2: Input: nums = [3,1,2] Output: 4 Explanation: The possible XOR triplet values include: The unique XOR values are {0, 1, 2, 3} , so the output is 4.", + "description_images": [], + "constraints": [ + "(0, 0, 0) → 1 XOR 1 XOR 1 = 1", + "(0, 0, 1) → 1 XOR 1 XOR 2 = 2", + "(0, 1, 1) → 1 XOR 2 XOR 2 = 1", + "(1, 1, 1) → 2 XOR 2 XOR 2 = 2" + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int uniqueXorTriplets(int[] nums) {\n int n = nums.length;\n\n if (n < 3)\n return n;\n\n // Find the Most Significant Bit\n int count = 0;\n int temp = n;\n while (temp > 0) {\n temp >>= 1;\n count++;\n }\n\n return (int) Math.pow(2, count);\n }\n}", + "title": "3824. Number of Unique XOR Triplets I", + "topic": "Array" + }, + { + "difficulty": "Easy", + "language": "java", + "description": "You are given an integer array nums and an integer k . You can perform the following operation any number of times: Return the minimum number of operations required to make the sum of the array divisible by k . Example 1: Input: nums = [3,9,7], k = 5 Output: 4 Explanation: Example 2: Input: nums = [4,1,3], k = 4 Output: 0 Explanation: Example 3: Input: nums = [3,2], k = 6 Output: 5 Explanation:", + "description_images": [], + "constraints": [ + "Select an index i and replace nums[i] with nums[i] - 1 ." + ], + "examples": [], + "follow_up": null, + "solution": "class Solution {\n public int minOperations(int[] nums, int k) {\n int sum = 0;\n\n for (int num : nums) {\n sum += num;\n }\n\n int remainder = sum % k;\n\n if (remainder == 0)\n return 0;\n\n return remainder;\n }\n}", + "title": "3846. Minimum Operations to Make Array Sum Divisible by K", + "topic": "Array" + } +] \ No newline at end of file diff --git a/question-service/prisma/seed/seed.js b/question-service/prisma/seed/seed.js new file mode 100644 index 000000000..ee537b72e --- /dev/null +++ b/question-service/prisma/seed/seed.js @@ -0,0 +1,53 @@ +import {PrismaClient} from '../../generated/prisma/index.js'; +import fs from 'fs'; +import path from 'path'; +import {fileURLToPath} from 'url'; + +// To use __dirname in ES modules +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const dataPath = path.join(__dirname, 'questions-list-cleaned.json'); + +// Initialize Prisma Client +const prisma = new PrismaClient(); +async function main() { + //read from JSON file + const data = JSON.parse(fs.readFileSync(dataPath, 'utf-8')); + + for (const q of data) { + + // Skip if any compulsory field missing + if (!q.title || !q.description || !q.solution || !q.difficulty || !q.topic) continue; + + // Skip if difficulty not one of EASY, MEDIUM, HARD + const difficulty = q.difficulty.toUpperCase(); + if (!["EASY","MEDIUM","HARD"].includes(difficulty)) continue; + + //create question + await prisma.question.create({ + data: { + title: q.title, // question title + description: q.description, // question description + descriptionImages: q.description_images || [], // question images if any + constraints: q.constraints || [], // question constraints if any + examples: q.examples || null, // question output examples if any + solution: q.solution, // solution to question + difficulty: q.difficulty.toUpperCase(), // question difficulty (enum: EASY/MEDIUM/HARD) + language: q.language || null, // question language + topic: q.topic, // question topic + followUp: q.follow_up || null, // question follow up if any + }, + }); + } + console.log('question insert completed.'); +} + +// Execute the main function and handle errors +main() + .catch((e) => { + console.error(e); + process.exit(1); + }) + .finally(async () => { + await prisma.$disconnect(); + }); \ No newline at end of file